Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
PySCIPOpt
https://pyscipopt.readthedocs.io/en/latest
Admin
PySCIPOpt is the Python interface to SCIP (Solving Constraint Integer Programs).
Tokens:
43,828
Snippets:
464
Trust Score:
8.3
Update:
3 months ago
Context
Chat
Benchmark
63
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Setup virtual environment and install PySCIPOpt Source: https://pyscipopt.readthedocs.io/en/latest/_sources/install.rst Create a virtual environment and install PySCIPOpt to prevent system package interference. ```bash python3 -m venv venv source venv/bin/activate # On Windows use: venv\Scripts\activate pip install pyscipopt ``` -------------------------------- ### Install PySCIPOpt Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Execute the installation command from the root directory of the repository. ```bash # Set environment variable SCIPOPTDIR if not yet done python -m pip install . ``` -------------------------------- ### Initialize a PySCIPOpt Model Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/constypes.rst Basic setup required to start defining variables and constraints. ```python from pyscipopt import Model, quicksum scip = Model() ``` -------------------------------- ### Install PySCIPOpt from source Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Standard command to install the package from the current directory. ```bash python -m pip install --compile . ``` -------------------------------- ### Install test dependencies Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Install the necessary requirements to run the test suite. ```bash pip install -r requirements/test.txt ``` -------------------------------- ### Initialize Model for Cut Selector Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/cutselector.rst Basic setup required to start working with cut selectors in PySCIPOpt. ```python from pyscipopt import Model, SCIP_RESULT from pyscipopt.scip import Cutsel scip = Model() ``` -------------------------------- ### Install Python Development Files Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Install system-level development headers required for building Python extensions on Linux. ```bash sudo apt-get install python3-dev # Linux ``` -------------------------------- ### Build documentation locally Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Install documentation dependencies and generate the site using Sphinx. ```bash pip install -r docs/requirements.txt sphinx-build docs docs/_build ``` -------------------------------- ### Install Build Dependencies Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Install required Python packages for building the library. ```bash pip install setuptools pip install Cython ``` -------------------------------- ### Install PySCIPOpt via pip Source: https://pyscipopt.readthedocs.io/en/latest/_sources/install.rst Standard command to install the PySCIPOpt package from PyPI. ```bash pip install pyscipopt ``` -------------------------------- ### Initialize Model for IIS Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/iis.rst Setup the Model object required for IIS operations. ```python from pyscipopt import Model, IISfinder, SCIP_RESULT model = Model() ``` -------------------------------- ### Initialize a SCIP Model Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/heuristic.rst Basic setup required to instantiate a SCIP model and import necessary constants. ```python from pyscipopt import Model, Heur, SCIP_RESULT, SCIP_HEURTIMING, SCIP_LPSOLSTAT scip = Model() ``` -------------------------------- ### Set SCIPOPTDIR on Linux and MacOS Source: https://pyscipopt.readthedocs.io/en/latest/build.html Use this command to point the installer to the SCIP installation directory on Unix-based systems. ```bash export SCIPOPTDIR=<path_to_install_dir> ``` -------------------------------- ### Install PySCIPOpt via Conda Source: https://pyscipopt.readthedocs.io/en/latest/_sources/install.rst Install PySCIPOpt and its dependencies using the conda-forge channel. ```bash conda install --channel conda-forge pyscipopt ``` -------------------------------- ### Initialize a SCIP Model Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/nodeselector.rst Setup the base Model and import the necessary Nodesel class. ```python from pyscipopt import Model from pyscipopt.scip import Nodesel scip = Model() ``` -------------------------------- ### Initialize Model for Lazy Constraints Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/lazycons.rst Basic setup for a PySCIPOpt model with necessary imports. ```python from pyscipopt import Model, quicksum, Conshdlr, SCIP_RESULT scip = Model() ``` -------------------------------- ### SCIPOPTDIR Directory Structure Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Expected directory layout for the SCIP installation path. ```RST SCIPOPTDIR > lib > libscip.so ... > include > scip > lpi > ... ``` -------------------------------- ### Example SCIP Optimization Output Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/logfile.rst A sample log showing the presolving phase and the iterative optimization progress table. ```RST presolving: (round 1, fast) 136 del vars, 0 del conss, 2 add conss, 0 chg bounds, 0 chg sides, 0 chg coeffs, 0 upgd conss, 0 impls, 0 clqs (round 2, fast) 136 del vars, 1 del conss, 2 add conss, 0 chg bounds, 132 chg sides, 0 chg coeffs, 0 upgd conss, 0 impls, 0 clqs (round 3, exhaustive) 136 del vars, 2 del conss, 2 add conss, 0 chg bounds, 133 chg sides, 0 chg coeffs, 0 upgd conss, 0 impls, 0 clqs (round 4, exhaustive) 136 del vars, 2 del conss, 2 add conss, 0 chg bounds, 133 chg sides, 0 chg coeffs, 131 upgd conss, 0 impls, 0 clqs (0.0s) probing cycle finished: starting next cycle (0.0s) symmetry computation started: requiring (bin +, int +, cont +), (fixed: bin -, int -, cont -) (0.0s) no symmetry present (symcode time: 0.00) presolving (5 rounds: 5 fast, 3 medium, 3 exhaustive): 136 deleted vars, 2 deleted constraints, 2 added constraints, 0 tightened bounds, 0 added holes, 133 changed sides, 0 changed coefficients 231 implications, 0 cliques presolved problem has 232 variables (231 bin, 0 int, 1 impl, 0 cont) and 137 constraints 53 constraints of type <knapsack> 6 constraints of type <linear> 78 constraints of type <logicor> transformed objective value is always integral (scale: 1) Presolving Time: 0.01 time | node | left |LP iter|LP it/n|mem/heur|mdpt |vars |cons |rows |cuts |sepa|confs|strbr| dualbound | primalbound | gap | compl. 0.0s| 1 | 0 | 409 | - | 5350k | 0 | 232 | 156 | 137 | 0 | 0 | 19 | 0 | 7.649866e+03 | -- | Inf | unknown o 0.0s| 1 | 0 | 1064 | - |feaspump| 0 | 232 | 156 | 137 | 0 | 0 | 19 | 0 | 7.650000e+03 | 8.267000e+03 | 8.07%| unknown 0.0s| 1 | 0 | 1064 | - | 5368k | 0 | 232 | 156 | 137 | 0 | 0 | 19 | 0 | 7.650000e+03 | 8.267000e+03 | 8.07%| unknown 0.0s| 1 | 0 | 1064 | - | 5422k | 0 | 232 | 156 | 137 | 0 | 0 | 19 | 0 | 7.650000e+03 | 8.267000e+03 | 8.07%| unknown 0.0s| 1 | 0 | 1067 | - | 5422k | 0 | 232 | 156 | 137 | 0 | 0 | 19 | 0 | 7.650000e+03 | 8.267000e+03 | 8.07%| unknown 0.1s| 1 | 0 | 1132 | - | 9912k | 0 | 232 | 156 | 138 | 1 | 1 | 19 | 0 | 7.659730e+03 | 8.267000e+03 | 7.93%| unknown 0.1s| 1 | 0 | 1133 | - | 9924k | 0 | 232 | 157 | 138 | 1 | 1 | 20 | 0 | 7.660000e+03 | 8.267000e+03 | 7.92%| unknown 0.1s| 1 | 0 | 1134 | - | 9924k | 0 | 232 | 157 | 138 | 1 | 1 | 20 | 0 | 7.660000e+03 | 8.267000e+03 | 7.92%| unknown 0.1s| 1 | 0 | 1210 | - | 15M | 0 | 232 | 157 | 141 | 4 | 2 | 20 | 0 | 7.671939e+03 | 8.267000e+03 | 7.76%| unknown 0.1s| 1 | 0 | 1213 | - | 15M | 0 | 232 | 159 | 141 | 4 | 2 | 22 | 0 | 7.672000e+03 | 8.267000e+03 | 7.76%| unknown 0.1s| 1 | 0 | 1280 | - | 18M | 0 | 232 | 157 | 143 | 6 | 3 | 22 | 0 | 7.685974e+03 | 8.267000e+03 | 7.56%| unknown 0.1s| 1 | 0 | 1282 | - | 18M | 0 | 232 | 157 | 143 | 6 | 3 | 22 | 0 | 7.686000e+03 | 8.267000e+03 | 7.56%| unknown 0.2s| 1 | 0 | 1353 | - | 21M | 0 | 232 | 156 | 145 | 8 | 4 | 22 | 0 | 7.701524e+03 | 8.267000e+03 | 7.34%| unknown 0.2s| 1 | 0 | 1355 | - | 21M | 0 | 232 | 156 | 145 | 8 | 4 | 22 | 0 | 7.702000e+03 | 8.267000e+03 | 7.34%| unknown 0.2s| 1 | 0 | 1435 | - | 24M | 0 | 232 | 156 | 147 | 10 | 5 | 22 | 0 | 7.706318e+03 | 8.267000e+03 | 7.28%| unknown time | node | left |LP iter|LP it/n|mem/heur|mdpt |vars |cons |rows |cuts |sepa|confs|strbr| dualbound | primalbound | gap | compl. 0.2s| 1 | 0 | 1438 | - | 24M | 0 | 232 | 158 | 147 | 10 | 5 | 24 | 0 | 7.707000e+03 | 8.267000e+03 | 7.27%| unknown 0.2s| 1 | 0 | 1520 | - | 30M | 0 | 232 | 158 | 149 | 12 | 6 | 24 | 0 | 7.711108e+03 | 8.267000e+03 | 7.21%| unknown 0.2s| 1 | 0 | 1521 | - | 30M | 0 | 232 | 158 | 149 | 12 | 6 | 24 | 0 | 7.712000e+03 | 8.267000e+03 | 7.20%| unknown 0.2s| 1 | 0 | 1658 | - | 34M | 0 | 232 | 158 | 151 | 14 | 7 | 24 | 0 | 7.715238e+03 | 8.267000e+03 | 7.15%| unknown 0.2s| 1 | 0 | 1659 | - | 34M | 0 | 232 | 158 | 151 | 14 | 7 | 24 | 0 | 7.716000e+03 | 8.267000e+03 | 7.14%| unknown ``` -------------------------------- ### Define Binary Variables Source: https://pyscipopt.readthedocs.io/en/latest/tutorials/constypes.html Example of creating a list of binary variables for use in constraints. ```python x = [scip.addVar(vtype='B', name=f"x_{i}") for i in range(1000)] ``` -------------------------------- ### Display SCIP Restart Information Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/logfile.rst Example of log output indicating a solver restart due to global fixings. ```RST (run 1, node 1) restarting after 26 global fixings of integer variables (restart) converted 26 cuts from the global cut pool into linear constraints ``` -------------------------------- ### Set and get SCIP parameters Source: https://pyscipopt.readthedocs.io/en/latest/tutorials/model.html Methods for setting and retrieving individual model parameters. ```python scip.setParam("limits/time", 20) ``` ```python time_limit = scip.getParam("limits/time") ``` -------------------------------- ### Define Binary Variables Source: https://pyscipopt.readthedocs.io/en/latest/tutorials/iis.html Example of adding binary variables to a model instance. ```python x1 = model.addVar(“x1”, vtype=”B”) x2 = model.addVar(“x2”, vtype=”B”) x3 = model.addVar(“x3”, vtype=”B”) ``` -------------------------------- ### Set SCIPOPTDIR Environment Variable Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Configure the path to the SCIP installation directory for build and runtime discovery. ```bash export SCIPOPTDIR=<path_to_install_dir> ``` ```bash set SCIPOPTDIR=<path_to_install_dir> # This is done for command line interfaces (cmd, Cmder, WSL) $Env:SCIPOPTDIR = "<path_to_install_dir>" # This is done for command line interfaces (powershell) ``` -------------------------------- ### Implement Efficacy-Based Cut Selection Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/cutselector.rst Example implementation that selects the 10 most efficacious cuts using SCIP's built-in efficacy calculation. ```python class MaxEfficacyCutsel(Cutsel): def cutselselect(self, cuts, forcedcuts, root, maxnselectedcuts): """ Selects the 10 cuts with largest efficacy. """ scip = self.model scores = [0] * len(cuts) for i in range(len(scores)): scores[i] = scip.getCutEfficacy(cuts[i]) rankings = sorted(range(len(cuts)), key=lambda x: scores[x], reverse=True) sorted_cuts = [cuts[rank] for rank in rankings] assert len(sorted_cuts) == len(cuts) return {'cuts': sorted_cuts, 'nselectedcuts': min(maxnselectedcuts, len(cuts), 10), 'result': SCIP_RESULT.SUCCESS} ``` -------------------------------- ### SCIP IIS Generation Log Output Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/iis.rst Example log output generated by SCIP during the IIS search process. ```text presolving: presolving (1 rounds: 1 fast, 0 medium, 0 exhaustive): 2 deleted vars, 2 deleted constraints, 0 added constraints, 0 tightened bounds, 0 added holes, 0 changed sides, 0 changed coefficients 0 implications, 0 cliques, 0 implied integral variables (0 bin, 0 int, 0 cont) presolving detected infeasibility Presolving Time: 0.00 SCIP Status : problem is solved [infeasible] Solving Time (sec) : 0.00 Solving Nodes : 0 Primal Bound : +1.00000000000000e+20 (0 solutions) Dual Bound : +1.00000000000000e+20 Gap : 0.00 % time(s)| node | cons | vars | bounds| infeasible 0.0| 0| 1| 3| 6| no 0.0| 0| 2| 3| 6| no 0.0| 0| 4| 3| 6| no 0.0| 0| 3| 3| 6| yes 0.0| 0| 2| 3| 6| yes 0.0| 0| 2| 3| 6| yes IIS Status : irreducible infeasible subsystem (IIS) found IIS irreducible : yes Generation Time (sec) : 0.01 Generation Nodes : 0 Num. Cons. in IIS : 2 Num. Vars. in IIS : 3 Num. Bounds in IIS : 6 ``` -------------------------------- ### setupBendersSubproblem(probnumber, benders=None, solution=None, checktype=1) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Sets up the Benders' subproblem given the master problem solution. ```APIDOC ## setupBendersSubproblem(probnumber, benders=None, solution=None, checktype=1) ### Description Sets up the Benders' subproblem given the master problem solution. ### Parameters - **probnumber** (int) - Required - The index of the problem that is to be set up. - **benders** (Benders or None) - Optional - The Benders' decomposition to which the subproblem belongs to. - **solution** (Solution or None) - Optional - The master problem solution that is used for the set up, if None, then the LP solution is used. - **checktype** (PY_SCIP_BENDERSENFOTYPE) - Required - The type of solution check that prompted the solving of the Benders' subproblems. ``` -------------------------------- ### Create Virtual Environment Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Initialize a Python virtual environment to manage dependencies. ```bash python -m venv <venv_name e.g. venv> ``` -------------------------------- ### startProbing() Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Initiates probing, making methods like SCIPnewProbingNode(), SCIPbacktrackProbing(), SCIPchgVarLbProbing(), SCIPchgVarUbProbing(), SCIPfixVarProbing(), SCIPpropagateProbing(), and SCIPsolveProbingLP() available. ```APIDOC ## startProbing() ### Description Initiates probing, making methods SCIPnewProbingNode(), SCIPbacktrackProbing(), SCIPchgVarLbProbing(), SCIPchgVarUbProbing(), SCIPfixVarProbing(), SCIPpropagateProbing(), SCIPsolveProbingLP(), etc available. ``` -------------------------------- ### getVarsAnd(and_cons) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Gets variables in AND constraint. ```APIDOC ### getVarsAnd(and_cons) **Parameters:** - **and_cons** (Constraint) - Required - AND Constraint to get the variables from. **Return Type:** list of Variable ``` -------------------------------- ### Column.getVar() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the variable this column represents. ```APIDOC ### Method `Column.getVar()` ### Description Returns the variable associated with this column. ### Returns - **Variable** - The variable object. ``` -------------------------------- ### Column.getUb() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the upper bound of the column. ```APIDOC ### Method `Column.getUb()` ### Description Returns the upper bound of the column. ### Returns - **float** - The upper bound value. ``` -------------------------------- ### trySol(solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, free=True) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Check given primal solution for feasibility and try to add it to the storage. ```APIDOC ## trySol(solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, free=True) ### Description Check given primal solution for feasibility and try to add it to the storage. ### Parameters - **solution** (Solution) - Required - solution to store - **printreason** (bool) - Optional - should all reasons of violations be printed? (Default value = True) - **completely** (bool) - Optional - should all violation be checked? (Default value = False) - **checkbounds** (bool) - Optional - should the bounds of the variables be checked? (Default value = True) - **checkintegrality** (bool) - Optional - does integrality have to be checked? (Default value = True) - **checklprows** (bool) - Optional - do current LP rows (both local and global) have to be checked? (Default value = True) - **free** (bool) - Optional - should solution be freed? (Default value = True) ### Returns - **stored** (bool) - whether given solution was feasible and good enough to keep ``` -------------------------------- ### Column.getLb() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the lower bound of the column. ```APIDOC ### Method `Column.getLb()` ### Description Returns the lower bound of the column. ### Returns - **float** - The lower bound value. ``` -------------------------------- ### Column.getPrimsol() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the primal LP solution of the column. ```APIDOC ### Method `Column.getPrimsol()` ### Description Returns the primal LP solution value. ### Returns - **float** - The primal solution value. ``` -------------------------------- ### includePresol Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Include a presolver. ```APIDOC ## includePresol(presol, name, desc, priority, maxrounds, timing=4) ### Description Include a presolver. ### Parameters - **presol** (Presol) - Required - presolver - **name** (str) - Required - name of presolver - **desc** (str) - Required - description of presolver - **priority** (int) - Required - priority of the presolver - **maxrounds** (int) - Required - maximal number of presolving rounds - **timing** (PY_SCIP_PRESOLTIMING) - Optional - timing mask of presolver (Default: 4) ``` -------------------------------- ### Column.getObjCoeff() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the objective value coefficient of the column. ```APIDOC ### Method `Column.getObjCoeff()` ### Description Returns the objective coefficient. ### Returns - **float** - The objective coefficient value. ``` -------------------------------- ### Column.getLPPos() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the position of the column in the current LP. ```APIDOC ### Method `Column.getLPPos()` ### Description Returns the position of the column in the current LP, or -1 if it is not in the LP. ### Returns - **int** - The position index or -1. ``` -------------------------------- ### Row.getVals() Source: https://pyscipopt.readthedocs.io/en/latest/api/row.html Gets the list of coefficients for the nonzero entries in the row. ```APIDOC ### Method `getVals()` ### Description Gets list with coefficients of nonzero entries. ### Returns - **list of int** - The coefficients of nonzero entries. ``` -------------------------------- ### startDive() Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Initiates LP diving. ```APIDOC ## startDive() ### Description Initiates LP diving. It allows the user to change the LP in several ways, solve, change again, etc, without affecting the actual LP. ``` -------------------------------- ### Row.getBasisStatus() Source: https://pyscipopt.readthedocs.io/en/latest/api/row.html Gets the basis status of a row in the LP solution. ```APIDOC ### Method `getBasisStatus()` ### Description Gets the basis status of a row in the LP solution. ### Returns - **str** - Possible values are "lower", "basic", and "upper". ### Exceptions - **Exception** - If SCIP returns an unknown or "zero" basis status. ``` -------------------------------- ### Construct Constraints with quicksum Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/constypes.rst Use quicksum for efficient summation of variables in large models. ```python x = [scip.addVar(vtype='B', name=f"x_{i}") for i in range(1000)] ``` ```python scip.addCons(quicksum(x[i] for i in range(1000)) == 1, name="sum_cons") ``` -------------------------------- ### Column.getBasisStatus() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the basis status of a column in the LP solution. ```APIDOC ### Method `Column.getBasisStatus()` ### Description Returns the basis status of the column. ### Returns - **str** - Possible values are "lower", "basic", "upper", and "zero". ### Exceptions - **Exception** - Raised if SCIP returns an unknown basis status. ``` -------------------------------- ### Retrieve All Variables Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/vartypes.rst Get a list of all variables currently added to the model. ```python scip_vars = scip.getVars() ``` -------------------------------- ### solveProbingLPWithPricing(pretendroot=False, displayinfo=False, maxpricerounds=-1) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Solves the LP at the current probing node with pricing. ```APIDOC ## solveProbingLPWithPricing(pretendroot=False, displayinfo=False, maxpricerounds=-1) ### Description Solves the LP at the current probing node and applies pricing until the LP is solved to optimality; no separation is applied. ### Parameters - **pretendroot** (bool) - Optional - Should the pricers be called as if we are at the root node? - **displayinfo** (bool) - Optional - Should info lines be displayed after each pricing round? - **maxpricerounds** (int) - Optional - Maximal number of pricing rounds. ### Response - **lperror** (bool) - Whether an unresolved LP error occurred. - **cutoff** (bool) - Whether the probing LP was infeasible or the objective limit was reached. ``` -------------------------------- ### Row.getCols() Source: https://pyscipopt.readthedocs.io/en/latest/api/row.html Gets the list of columns associated with nonzero entries in the row. ```APIDOC ### Method `getCols()` ### Description Gets list with columns of nonzero entries. ### Returns - **list of Column** - The columns of nonzero entries. ``` -------------------------------- ### Manage Solver Parameters Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/model.rst Set and retrieve individual or multiple solver parameters, or load them from a file. ```python scip.setParam("limits/time", 20) ``` ```python time_limit = scip.getParam("limits/time") ``` ```python param_dict = {"limits/time": 20} scip.setParams(param_dict) ``` ```python param_dict = scip.getParams() ``` ```python scip.readParams(path_to_file) ``` -------------------------------- ### getVarStrongbranchLast(var) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Get the results of the last strong branching call on this variable. ```APIDOC ### getVarStrongbranchLast(var) **Parameters:** - **var** (Variable) - Required **Returns:** down (float), up (float), downvalid (bool), upvalid (bool), solval (float), lpobjval (float) ``` -------------------------------- ### Configure macOS Library Path Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Ensure the SCIP dynamic library is discoverable at runtime on macOS. ```bash export DYLD_LIBRARY_PATH="<path_to_install_dir>/lib:$DYLD_LIBRARY_PATH" ``` -------------------------------- ### Register and Use a Custom IIS Finder Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/iis.rst Include the custom finder in the model instance before calling generateIIS to utilize the implementation. ```python # Create model model = Model() # Add variables and constraints (infeasible problem) x1 = model.addVar("x1", vtype="B") x2 = model.addVar("x2", vtype="B") x3 = model.addVar("x3", vtype="B") model.addCons(x1 + x2 == 1, name="c1") model.addCons(x2 + x3 == 1, name="c2") model.addCons(x1 + x3 == 1, name="c3") model.addCons(x1 + x2 + x3 <= 0, name="c4") # Create and include the custom IIS finder simple_iis = SimpleIISFinder() model.includeIISfinder( simple_iis, name="simpleiis", desc="Simple greedy IIS finder", priority=1000000 # Higher priority means it will be used first ) # Solve to verify infeasibility model.optimize() # Generate IIS using our custom finder iis = model.generateIIS() # Examine the result print(f"\nIIS Information:") print(f" Time: {iis.getTime():.2f} seconds") print(f" Nodes: {iis.getNNodes()}") print(f" Irreducible: {iis.isSubscipIrreducible()}") print(f" Number of constraints: {iis.getSubscip().getNConss()}") ``` -------------------------------- ### Read parameters from a file Source: https://pyscipopt.readthedocs.io/en/latest/tutorials/model.html Loads parameter configurations from a .set file. ```python scip.readParams(path_to_file) ``` -------------------------------- ### Defining Exponential and Logarithmic Constraints Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/expressions.rst Demonstrates the use of exp and log functions to define non-linear constraints in a PySCIPOpt model. ```python from pyscipopt import exp, log x = scip.addVar(vtype='C', name='x') y = scip.addVar(vtype='C', name='y') z = scip.addVar(vtype='C', name='z') cons_1 = scip.addCons( (1 / (1 + exp(-x))) == y, name="exp_cons") cons_2 = scip.addCons(log(x) <= z, name="log_cons) ``` -------------------------------- ### Get Variable Solution Value Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/vartypes.rst Retrieve the value of a variable from the current best solution. ```python var_val = scip.getVal(x) ``` ```python if scip.getNSols() >= 1: scip_sol = scip.getBestSol() var_val = scip_sol[x] ``` -------------------------------- ### Configure Plugin-wide Parameters Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/model.rst Adjust the aggressiveness of SCIP plugins like heuristics, presolvers, and separators. ```python from pyscipopt import Model, SCIP_PARAMSETTING scip = Model() scip.setHeuristics(SCIP_PARAMSETTING.AGGRESSIVE) ``` -------------------------------- ### Build with debug information Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Enable debug mode for PySCIPOpt. Requires the debug library of the SCIP Optimization Suite. ```bash export PYSCIPOPT_DEBUG=True # With Windows CMD: set PYSCIPOPT_DEBUG=True python -m pip install . ``` -------------------------------- ### Define and Optimize a Model Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/model.rst Create variables, add constraints, set the objective function, and run the optimization process. ```python scip = Model() x = scip.addVar(vtype='C', lb=0, ub=None, name='x') y = scip.addVar(vtype='C', lb=0, ub=None, name='y') z = scip.addVar(vtype='C', lb=0, ub=None, name='z') cons_1 = scip.addCons(x + y <= 5, name="cons_1") cons_2 = scip.addCons(x + z >= 3, name="cons_2") cons_3 = scip.addCons(y + z == 4, name="cons_3") scip.setObjective(2 * x + 3 * y - 5 * z, sense="minimize") scip.optimize() ``` -------------------------------- ### Configure unoptimized build Source: https://pyscipopt.readthedocs.io/en/latest/_sources/build.rst Set environment variables to disable optimization for faster build times, though this is discouraged for performance-critical experiments. ```bash export CFLAGS="-O0 -ggdb" ``` -------------------------------- ### getVarStrongbranchNode(var) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Get the node number from the last time strong branching was called on the variable. ```APIDOC ### getVarStrongbranchNode(var) **Parameters:** - **var** (Variable) - Required **Return Type:** int ``` -------------------------------- ### getVarStrongbranch(var, itlim, idempotent=False, integral=False) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Strong branches and gets information on column variable. ```APIDOC ### getVarStrongbranch(var, itlim, idempotent=False, integral=False) **Parameters:** - **var** (Variable) - Required - **itlim** (int) - Required - LP iteration limit - **idempotent** (bool) - Optional - **integral** (bool) - Optional **Returns:** down (float), up (float), downvalid (bool), upvalid (bool), downinf (bool), upinf (bool), downconflict (bool), upconflict (bool), lperror (bool) ``` -------------------------------- ### Log SCIP Output to File Source: https://pyscipopt.readthedocs.io/en/latest/tutorials/logfile.html Directs the solver log to a specified file path. ```python scip.setLogfile(path_to_file) ``` -------------------------------- ### getVarPseudocost(var, branchdir) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Gets the variable’s pseudo cost value for the given direction. ```APIDOC ### getVarPseudocost(var, branchdir) **Parameters:** - **variable** (Variable) - Required - Problem variable - **branchdir** (PY_SCIP_BRANCHDIR) - Required - Branching direction (downwards, or upwards) **Return Type:** float ``` -------------------------------- ### getVarDict(transformed=False) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Gets dictionary with variables names as keys and current variable values as items. ```APIDOC ### getVarDict(transformed=False) **Parameters:** - **transformed** (bool) - Optional - Get transformed variables instead of original (Default: False). **Return Type:** dict of str to float ``` -------------------------------- ### Define conscheck and consenfolp callbacks Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/lazycons.rst Implement feasibility checking and LP solution enforcement for custom constraints. ```python # checks whether solution is feasible def conscheck(self, constraints, solution, check_integrality, check_lp_rows, print_reason, completely, **results): # check if there is a violated subtour elimination constraint for cons in constraints: if self.find_subtours(cons, solution): return {"result": SCIP_RESULT.INFEASIBLE} # no violated constriant found -> feasible return {"result": SCIP_RESULT.FEASIBLE} # enforces the LP solution: searches for subtours in the solution and adds # adds constraints forbidding all the found subtours def consenfolp(self, constraints, n_useful_conss, sol_infeasible): consadded = False for cons in constraints: subtours = self.find_subtours(cons) # if there are subtours if subtours: x = cons.data['vars'] # add subtour elimination constraint for each subtour for S in subtours: print("Constraint added!") self.model.addCons(quicksum(x[i][j] for i in S for j in S if j>i) <= len(S)-1) consadded = True if consadded: return {"result": SCIP_RESULT.CONSADDED} else: return {"result": SCIP_RESULT.FEASIBLE} ``` -------------------------------- ### Row.getAge() Source: https://pyscipopt.readthedocs.io/en/latest/api/row.html Gets the age of the row, representing the number of consecutive times the row has been non-active in the LP. ```APIDOC ### Method `getAge()` ### Description Gets the age of the row. (The consecutive times the row has been non-active in the LP). ### Returns - **int** - The age of the row. ``` -------------------------------- ### Add SOS and Indicator Constraints Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/constypes.rst Demonstrates how to add SOS1 and Indicator constraints to a SCIP model. ```python sos_cons = scip.addConsSOS1([x, y, z], name="example_sos") indicator_cons = scip.addConsIndicator(x + y <= 1, binvar=z, name="example_indicator") ``` -------------------------------- ### Initialize Matrix Variable Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/matrix.rst Creates a 2x2 matrix variable and defines constraints using matrix expressions. ```python x = scip.addMatrixVar(shape=(2, 2)) assert(isinstance(x, MatrixVariable)) assert(isinstance(x[0][0], Variable)) cons = x <= 2 assert(isinstance(cons, MatrixExprCons)) assert(isinstance(cons[0][0]), ExprCons) ``` -------------------------------- ### Generate an IIS for an Infeasible Model Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/iis.rst Create an infeasible model and trigger the IIS generation process. ```python x1 = model.addVar("x1", vtype="B") x2 = model.addVar("x2", vtype="B") x3 = model.addVar("x3", vtype="B") # These four constraints cannot be satisfied simultaneously model.addCons(x1 + x2 == 1, name="c1") model.addCons(x2 + x3 == 1, name="c2") model.addCons(x1 + x3 == 1, name="c3") model.addCons(x1 + x2 + x3 <= 0, name="c4") model.optimize() iis = model.generateIIS() ``` -------------------------------- ### getVarPseudocostScore(var, solVal) Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Gets the variable’s pseudo cost score value for the given LP solution value. ```APIDOC ### getVarPseudocostScore(var, solVal) **Parameters:** - **variable** (Variable) - Required - Problem variable - **solVal** (float) - Required - Difference of variable’s new LP value - old LP value **Return Type:** float ``` -------------------------------- ### includeDefaultPlugins Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Includes all default plug-ins into SCIP. ```APIDOC ## includeDefaultPlugins() ### Description Includes all default plug-ins into SCIP. ``` -------------------------------- ### Column.getAge() Source: https://pyscipopt.readthedocs.io/en/latest/api/column.html Gets the age of the column, representing the total number of successive times the column was in the LP and had a value of 0.0 in the solution. ```APIDOC ### Method `Column.getAge()` ### Description Returns the age of the column as an integer. ### Returns - **int** - The age of the column. ``` -------------------------------- ### Defining Sine and Cosine Constraints Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/expressions.rst Shows how to implement trigonometric constraints using the native sin and cos functions. ```python from pyscipopt import cos, sin x = scip.addVar(vtype='C', name='x') y = scip.addVar(vtype='C', name='y') cons_1 = scip.addCons(sin(x) == y, name="sin_cons") cons_2 = scip.addCons(cos(y) <= 0.5, name="cos_cons") ``` -------------------------------- ### includeIISfinder Source: https://pyscipopt.readthedocs.io/en/latest/api/model.html Include an IIS (Irreducible Infeasible Set) finder handler. ```APIDOC ## includeIISfinder(iisfinder, name, desc, priority=10000, freq=1) ### Description Include an IIS (Irreducible Infeasible Set) finder handler. ### Parameters - **iisfinder** (IISfinder) - Required - IIS finder - **name** (str) - Required - name of IIS finder - **desc** (str) - Required - description of IIS finder - **priority** (int) - Optional - priority of the IISfinder - **freq** (int) - Optional - frequency for calling IIS finder ``` -------------------------------- ### Implement a Custom IIS Finder Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/iis.rst Inherit from IISfinder and implement iisfinderexec to define custom logic for identifying an IIS. ```python from pyscipopt import IISfinder, SCIP_RESULT class SimpleIISFinder(IISfinder): """ Minimal working example: keep a known infeasible subset (by name) and mark it as the IIS. """ def iisfinderexec(self): subscip = self.iis.getSubscip() # keep only constraints {c2, c4} and delete others keep = {"c2", "c4"} for cons in list(subscip.getConss()): if cons.name not in keep: subscip.delCons(cons) # Tell SCIP that our sub-SCIP represents an (irreducible) IIS self.iis.setSubscipInfeasible(True) self.iis.setSubscipIrreducible(True) return {"result": SCIP_RESULT.SUCCESS} ``` -------------------------------- ### Read a SCIP Model from a File Source: https://pyscipopt.readthedocs.io/en/latest/_sources/tutorials/readwrite.rst Use readProblem to load an optimization problem from a file into a SCIP model instance. ```python from pyscipopt import Model scip = Model() scip.readProblem(filename="example_file.mps") ```