diff --git a/CHANGELOG.md b/CHANGELOG.md index 4daaf48c2..8bb240e58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ - `Expr` and `GenExpr` support `__pos__` magic method like `+Expr` or `+GenExpr` - Added type annotations to most methods on the `Model` class - Added tests for `getRowLinear()` and extended existing testing for `isActive()` +- Added `ExactModel` and `ExactVariable` for exact (rational) solving with SCIP 11; their ordinary methods take and return `Fraction`s, and `RowExact`/`ColumnExact` gained getters ### Fixed - Fixed Cython 3.3 compatibility (#1248) - Made `test_markDoNotAggrVar_and_getStatus` robust to SCIP presolve changes by discovering the aggregated/multi-aggregated variables instead of hardcoding them @@ -42,6 +43,7 @@ - Extended `structured_optimization_trace` recipe to support context-managed JSONL tracing with final `run_end` records, alongside the existing attach-style in-memory tracing. - Integration tests now run in the merge queue before merging instead of after pushing to `master` (#1249) ### Removed +- Removed `Model.enableExactSolving()`, `Model.isExact()`, `Model.allowNegSlackExact()`, `Model.branchLPExact()` and `Model.addRowExact()`; use `ExactModel`, which exposes the last three as `allowNegSlack()`, `branchLP()` and `addRow()` - `SumExpr`.coefs has been removed; its values were always 1.0 (#1258) - Deprecated `getOp` method in `GenExpr` (#1259) - Deprecated inner enumerate class `Operator` (#1259) diff --git a/scripts/generate_stubs.py b/scripts/generate_stubs.py index a7c2acf25..1cdaa3163 100755 --- a/scripts/generate_stubs.py +++ b/scripts/generate_stubs.py @@ -104,10 +104,10 @@ class StubGenerator: # Classes that should have @disjoint_base decorator # These are user-facing classes that should not be structurally compatible DISJOINT_BASE_CLASSES = { - 'Benders', 'Benderscut', 'BoundChange', 'Branchrule', 'Column', 'ColumnExact', + 'BaseModel', 'Benders', 'Benderscut', 'BoundChange', 'Branchrule', 'Column', 'ColumnExact', 'Conshdlr', 'Constant', 'Constraint', 'Cutsel', 'DomainChanges', 'Event', 'Eventhdlr', 'Expr', 'ExprCons', 'GenExpr', 'Heur', 'IIS', 'IISfinder', - 'LP', 'Model', 'NLRow', 'Node', 'Nodesel', 'PowExpr', 'Presol', 'Pricer', + 'LP', 'NLRow', 'Node', 'Nodesel', 'PowExpr', 'Presol', 'Pricer', 'ProdExpr', 'Prop', 'Reader', 'Relax', 'Row', 'RowExact', 'Sepa', 'Solution', 'SumExpr', 'Term', 'UnaryExpr', 'Variable', '_VarArray', } diff --git a/src/pyscipopt/__init__.py b/src/pyscipopt/__init__.py index 170d86e42..4aaabd7ac 100644 --- a/src/pyscipopt/__init__.py +++ b/src/pyscipopt/__init__.py @@ -8,7 +8,10 @@ # export user-relevant objects: from pyscipopt.Multidict import multidict as multidict +from pyscipopt.scip import BaseModel as BaseModel from pyscipopt.scip import Model as Model +from pyscipopt.scip import ExactModel as ExactModel +from pyscipopt.scip import ExactVariable as ExactVariable from pyscipopt.scip import Variable as Variable from pyscipopt.scip import MatrixVariable as MatrixVariable from pyscipopt.scip import Constraint as Constraint @@ -25,6 +28,8 @@ from pyscipopt.scip import Prop as Prop from pyscipopt.scip import Reader as Reader from pyscipopt.scip import Sepa as Sepa +from pyscipopt.scip import Symhdlr as Symhdlr +from pyscipopt.scip import SymComp as SymComp from pyscipopt.scip import LP as LP from pyscipopt.scip import IISfinder as IISfinder from pyscipopt.scip import PY_SCIP_LPPARAM as SCIP_LPPARAM diff --git a/src/pyscipopt/benders.pxi b/src/pyscipopt/benders.pxi index 913f12584..9f439fdec 100644 --- a/src/pyscipopt/benders.pxi +++ b/src/pyscipopt/benders.pxi @@ -1,7 +1,7 @@ ##@file benders.pxi #@brief Base class of the Benders decomposition Plugin cdef class Benders: - cdef public Model model + cdef public BaseModel model cdef public str name cdef SCIP_BENDERS* _benders diff --git a/src/pyscipopt/benderscut.pxi b/src/pyscipopt/benderscut.pxi index 475dec16e..4de1b116a 100644 --- a/src/pyscipopt/benderscut.pxi +++ b/src/pyscipopt/benderscut.pxi @@ -1,7 +1,7 @@ ##@file benderscut.pxi #@brief Base class of the Benderscut Plugin cdef class Benderscut: - cdef public Model model + cdef public BaseModel model cdef public Benders benders cdef public str name diff --git a/src/pyscipopt/branchrule.pxi b/src/pyscipopt/branchrule.pxi index 99ebab1d3..e68ae236e 100644 --- a/src/pyscipopt/branchrule.pxi +++ b/src/pyscipopt/branchrule.pxi @@ -1,7 +1,7 @@ ##@file branchrule.pxi #@brief Base class of the Branchrule Plugin cdef class Branchrule: - cdef public Model model + cdef public BaseModel model def branchfree(self): '''frees memory of branching rule''' diff --git a/src/pyscipopt/conshdlr.pxi b/src/pyscipopt/conshdlr.pxi index 79ae972b0..fb2186d12 100644 --- a/src/pyscipopt/conshdlr.pxi +++ b/src/pyscipopt/conshdlr.pxi @@ -2,7 +2,7 @@ #@brief base class of the Constraint Handler plugin cdef class Conshdlr: - cdef public Model model + cdef public BaseModel model cdef public str name def consfree(self): diff --git a/src/pyscipopt/cutsel.pxi b/src/pyscipopt/cutsel.pxi index 28ea94708..2aade7a84 100644 --- a/src/pyscipopt/cutsel.pxi +++ b/src/pyscipopt/cutsel.pxi @@ -1,7 +1,7 @@ ##@file cutsel.pxi #@brief Base class of the Cutsel Plugin cdef class Cutsel: - cdef public Model model + cdef public BaseModel model def cutselfree(self): '''frees memory of cut selector''' diff --git a/src/pyscipopt/event.pxi b/src/pyscipopt/event.pxi index 0ce0cb451..99f117721 100644 --- a/src/pyscipopt/event.pxi +++ b/src/pyscipopt/event.pxi @@ -1,7 +1,7 @@ ##@file event.pxi #@brief Base class of the Event Handler Plugin cdef class Eventhdlr: - cdef public Model model + cdef public BaseModel model cdef public str name # eventtypes caught via `Model.catchEvent`, auto-dropped on `eventexit`. cdef list _caught_events diff --git a/src/pyscipopt/exact.pxi b/src/pyscipopt/exact.pxi new file mode 100644 index 000000000..1823d98a1 --- /dev/null +++ b/src/pyscipopt/exact.pxi @@ -0,0 +1,1696 @@ +cdef SCIP_RATIONAL* _createRational(value) except NULL: + """Create a SCIP_RATIONAL holding the finite rational value; the caller must free it with SCIPrationalFree.""" + cdef SCIP_RATIONAL* rational = NULL + + desc = str(Fraction(value)).encode() + PY_SCIP_CALL(SCIPrationalCreate(&rational)) + SCIPrationalSetString(rational, desc) + return rational + +cdef SCIP_RATIONAL* _createBound(value) except NULL: + """Create a SCIP_RATIONAL for a bound or side, where +/- float("inf") is allowed; the caller must free it.""" + cdef SCIP_RATIONAL* rational = NULL + + if not (isinstance(value, float) and abs(value) == float("inf")): + return _createRational(value) + PY_SCIP_CALL(SCIPrationalCreate(&rational)) + SCIPrationalSetString(rational, b"inf" if value > 0 else b"-inf") + return rational + +cdef object _fromRational(SCIP_RATIONAL* rational): + """Convert a SCIP_RATIONAL to a Fraction, or to a float for +/- infinity.""" + cdef int length = SCIPrationalStrLen(rational) + cdef char* buf = malloc(length + 1) + + if buf == NULL: + raise MemoryError() + SCIPrationalToString(rational, buf, length + 1) + desc = buf[:length].decode("ascii") + free(buf) + + if desc == "+infinity": + return float("inf") + if desc == "-infinity": + return -float("inf") + return Fraction(desc) + +cdef _checkExactSol(Solution sol): + if sol.sol != NULL and not SCIPsolIsExact(sol.sol): + raise ValueError("solution has no exact values") + +_VARSTATUS_NAMES = { + SCIP_VARSTATUS_ORIGINAL: "ORIGINAL", + SCIP_VARSTATUS_LOOSE: "LOOSE", + SCIP_VARSTATUS_COLUMN: "COLUMN", + SCIP_VARSTATUS_FIXED: "FIXED", + SCIP_VARSTATUS_AGGREGATED: "AGGREGATED", + SCIP_VARSTATUS_MULTAGGR: "MULTAGGR", + SCIP_VARSTATUS_NEGATED: "NEGATED", +} + +cdef class ColumnExact: + """Base class holding a pointer to corresponding SCIP_COLEXACT.""" + + @staticmethod + cdef create(SCIP_COLEXACT* scipcolexact): + """ + Main method for creating a ColumnExact class. Is used instead of __init__. + + Parameters + ---------- + scipcolexact : SCIP_COLEXACT* + A pointer to the SCIP_COLEXACT + + Returns + ------- + col : ColumnExact + The Python representative of the SCIP_COLEXACT + + """ + if scipcolexact == NULL: + raise Warning("cannot create ColumnExact with SCIP_COLEXACT* == NULL") + col = ColumnExact() + col.scip_col_exact = scipcolexact + return col + + def getVar(self): + """ + Retrieve the variable this column represents. + + Returns + ------- + ExactVariable + + """ + return Variable.create(SCIPcolExactGetVar(self.scip_col_exact)) + +cdef class RowExact: + """Base class holding a pointer to corresponding SCIP_ROW.""" + + @staticmethod + cdef create(SCIP_ROWEXACT* sciprowexact): + """ + Main method for creating a RowExact class. Is used instead of __init__. + + Parameters + ---------- + sciprow : SCIP_ROWEXACT* + A pointer to the SCIP_ROWEXACT + + Returns + ------- + row : Row + The Python representative of the SCIP_ROWEXACT + + """ + if sciprowexact == NULL: + raise Warning("cannot create Row with SCIP_ROWEXACT* == NULL") + row_exact = RowExact() + row_exact.scip_row_exact = sciprowexact + return row_exact + + + def getLhs(self): + """ + Retrieve the exact left-hand side of the row. + + Returns + ------- + Fraction or float + a Fraction, or -inf if the row has no left-hand side + + """ + return _fromRational(SCIProwExactGetLhs(self.scip_row_exact)) + + def getRhs(self): + """ + Retrieve the exact right-hand side of the row. + + Returns + ------- + Fraction or float + a Fraction, or inf if the row has no right-hand side + + """ + return _fromRational(SCIProwExactGetRhs(self.scip_row_exact)) + + def getConstant(self): + """ + Retrieve the exact constant shift of the row. + + Returns + ------- + Fraction + + """ + return _fromRational(SCIProwExactGetConstant(self.scip_row_exact)) + + def getNNonz(self): + """ + Retrieve the number of nonzero entries in the row. + + Returns + ------- + int + + """ + return SCIProwExactGetNNonz(self.scip_row_exact) + + def getCols(self): + """ + Retrieve the columns of the row. + + Returns + ------- + list of ColumnExact + + """ + cdef SCIP_COLEXACT** cols = SCIProwExactGetCols(self.scip_row_exact) + cdef int i + + return [ColumnExact.create(cols[i]) for i in range(SCIProwExactGetNNonz(self.scip_row_exact))] + + def getVals(self): + """ + Retrieve the exact coefficients of the row. + + Returns + ------- + list of Fraction + + """ + cdef SCIP_RATIONAL** vals = SCIProwExactGetVals(self.scip_row_exact) + cdef int i + + return [_fromRational(vals[i]) for i in range(SCIProwExactGetNNonz(self.scip_row_exact))] + + def isInLP(self): + """ + Retrieve whether the row is a member of the current exact LP. + + Returns + ------- + bool + + """ + return SCIProwExactIsInLP(self.scip_row_exact) + +cdef class ExactVariable(Variable): + """Variable of an ExactModel: bounds, objective and LP value are rationals.""" + + def getObj(self): + """ + Retrieve the exact objective coefficient of the variable. + + Returns + ------- + Fraction + + """ + return _fromRational(SCIPvarGetObjExact(self.scip_var)) + + def getLbOriginal(self): + """ + Retrieve the exact original lower bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or -inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetLbOriginalExact(self.scip_var)) + + def getUbOriginal(self): + """ + Retrieve the exact original upper bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetUbOriginalExact(self.scip_var)) + + def getLbGlobal(self): + """ + Retrieve the exact global lower bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or -inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetLbGlobalExact(self.scip_var)) + + def getUbGlobal(self): + """ + Retrieve the exact global upper bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetUbGlobalExact(self.scip_var)) + + def getLbLocal(self): + """ + Retrieve the exact local lower bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or -inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetLbLocalExact(self.scip_var)) + + def getUbLocal(self): + """ + Retrieve the exact local upper bound of the variable. + + Returns + ------- + Fraction or float + a Fraction, or inf if the variable is unbounded + + """ + return _fromRational(SCIPvarGetUbLocalExact(self.scip_var)) + + def getLPSol(self): + """ + Returns the current LP solution value of the variable as a Fraction. + + Returns + ------- + Fraction + + """ + cdef SCIP_RATIONAL* rational = NULL + + PY_SCIP_CALL(SCIPrationalCreate(&rational)) + SCIPvarGetLPSolExact(self.scip_var, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getCol(self): + """ + Returns the exact LP column of the variable. + + Returns + ------- + ColumnExact + + """ + return ColumnExact.create(SCIPvarGetColExact(self.scip_var)) + + + def getStatus(self): + """ + Retrieve the status of the exact variable data (ORIGINAL, LOOSE, COLUMN, FIXED, AGGREGATED, MULTAGGR, NEGATED). + + Returns + ------- + str + + """ + return _VARSTATUS_NAMES.get(SCIPvarGetStatusExact(self.scip_var)) + +cdef class ExactModel(BaseModel): + """ + Model that solves exactly over the rationals. + + Variables, constraints and solutions carry exact data. Methods take Fractions + (or ints) and return Fractions; infinite bounds and sides are +/- float("inf"). + """ + + def __init__(self, problemName='model', defaultPlugins=True, createscip=True, threadsafe=False): + """ + Parameters + ---------- + problemName : str, optional + name of the problem (default 'model') + defaultPlugins : bool, optional + use default plugins (default True) + createscip : bool, optional + initialize the Model object and creates a SCIP instance + threadsafe : bool, optional + False if data can be safely shared between the source and target problem + + """ + if not PYSCIPOPT_WITH_EXACTSOLVE: + raise ValueError("SCIP was built without exact solving support, ExactModel needs a SCIP build with exact solving enabled") + super().__init__(problemName, defaultPlugins, createscip=createscip, threadsafe=threadsafe) + + cdef _configureScip(self): + PY_SCIP_CALL(SCIPenableExactSolving(self._scip, True)) + + def setObjective(self, expr, sense='minimize', clear='true'): + """ + Not available in exact solving mode: expressions hold floating-point coefficients. + Set objective coefficients with addVar(obj=...) or chgVarObj() instead. + """ + raise TypeError("ExactModel.setObjective is not available because expressions hold floating-point coefficients; set objective coefficients with addVar(obj=...) or chgVarObj()") + + def addVar(self, name='', vtype='C', lb=0, ub=None, obj=0, pricedVar=False, pricedVarScore=1.0, deletable=False): + """ + Create a new variable with exact (rational) bounds and objective coefficient. + + Parameters + ---------- + name : str, optional + name of the variable, generic if empty (Default value = '') + vtype : str, optional + type of the variable: 'C' continuous, 'I' integer, or 'B' binary + (Default value = 'C') + lb : Fraction, int or None, optional + lower bound of the variable, use None for -infinity (Default value = 0) + ub : Fraction, int or None, optional + upper bound of the variable, use None for +infinity, or 1 for binary variables + (Default value = None) + obj : Fraction or int, optional + objective coefficient of the variable (Default value = 0) + + Returns + ------- + Variable + + Notes + ----- + Floats are taken at their exact binary value, e.g. 0.1 is not 1/10. + + """ + cdef SCIP_VAR* scip_var = NULL + cdef SCIP_RATIONAL* lbexact = NULL + cdef SCIP_RATIONAL* ubexact = NULL + cdef SCIP_RATIONAL* objexact = NULL + cdef SCIP_VARTYPE vartype + cdef SCIP_RETCODE rc + + if pricedVar or deletable: + raise ValueError("priced and deletable variables are not supported in exact solving mode") + if name == '': + name = 'x'+str(SCIPgetNVars(self._scip)+1) + cname = str_conversion(name) + + vtype = vtype.upper() + if vtype in ['C', 'CONTINUOUS']: + vartype = SCIP_VARTYPE_CONTINUOUS + elif vtype in ['B', 'BINARY']: + vartype = SCIP_VARTYPE_BINARY + if ub is None: + ub = 1 + elif vtype in ['I', 'INTEGER']: + vartype = SCIP_VARTYPE_INTEGER + else: + raise Warning("unrecognized variable type") + + lb = -float("inf") if lb is None else lb + ub = float("inf") if ub is None else ub + obj = Fraction(obj) + if lb > ub: + raise ValueError("lower bound %s exceeds upper bound %s" % (lb, ub)) + + PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, + max(float(lb), -SCIPinfinity(self._scip)), + min(float(ub), SCIPinfinity(self._scip)), + float(obj), vartype)) + lbexact = _createBound(lb) + ubexact = _createBound(ub) + objexact = _createRational(obj) + rc = SCIPaddVarExactData(self._scip, scip_var, lbexact, ubexact, objexact) + SCIPrationalFree(&lbexact) + SCIPrationalFree(&ubexact) + SCIPrationalFree(&objexact) + if rc != SCIP_OKAY: + SCIPreleaseVar(self._scip, &scip_var) + PY_SCIP_CALL(rc) + PY_SCIP_CALL(SCIPaddVar(self._scip, scip_var)) + + pyVar = self._getOrCreateVar(scip_var) + SCIPvarSetData(scip_var, pyVar) + PY_SCIP_CALL(SCIPreleaseVar(self._scip, &scip_var)) + return pyVar + + def chgVarObj(self, Variable var, newobj): + """ + Change the exact objective coefficient of a variable. + + Parameters + ---------- + var : Variable + variable to change the objective coefficient of + newobj : Fraction or int + new objective coefficient + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + rational = _createRational(newobj) + rc = SCIPchgVarObjExact(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgVarLb(self, Variable var, lb): + """ + Change the exact lower bound of a variable. + + Parameters + ---------- + var : Variable + variable to change the bound of + lb : Fraction, int or None + new lower bound, use None for -infinity + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + rational = _createBound(-float("inf") if lb is None else lb) + rc = SCIPchgVarLbExact(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgVarUb(self, Variable var, ub): + """ + Change the exact upper bound of a variable. + + Parameters + ---------- + var : Variable + variable to change the bound of + ub : Fraction, int or None + new upper bound, use None for +infinity + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + rational = _createBound(float("inf") if ub is None else ub) + rc = SCIPchgVarUbExact(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgVarLbGlobal(self, Variable var, lb): + """ + Changes the lower bound of the variable exactly. + + Parameters + ---------- + var : Variable + lb : Rational + new bound (None for -infinity) + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + rational = _createBound(-float("inf") if lb is None else lb) + rc = SCIPchgVarLbGlobalExact(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgVarUbGlobal(self, Variable var, ub): + """ + Changes the upper bound of the variable exactly. + + Parameters + ---------- + var : Variable + ub : Rational + new bound (None for +infinity) + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + rational = _createBound(float("inf") if ub is None else ub) + rc = SCIPchgVarUbGlobalExact(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def fixVar(self, Variable var, val): + """ + Fixes the variable to a rational value in the current node. + + Parameters + ---------- + var : Variable + val : Rational + + Returns + ------- + infeasible : bool + fixed : bool + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + cdef SCIP_Bool infeasible + cdef SCIP_Bool fixed + + rational = _createRational(val) + rc = SCIPfixVarExact(self._scip, var.scip_var, rational, &infeasible, &fixed) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + return infeasible, fixed + + def tightenVarLb(self, Variable var, lb, force=False): + """ + Tightens the lower bound of the variable exactly in the current node. + + Parameters + ---------- + var : Variable + lb : Rational + force : bool, optional + ignored; the exact SCIP function has no force parameter + + Returns + ------- + infeasible : bool + tightened : bool + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + + rational = _createRational(lb) + rc = SCIPtightenVarLbExact(self._scip, var.scip_var, rational, &infeasible, &tightened) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + return infeasible, tightened + + def tightenVarUb(self, Variable var, ub, force=False): + """ + Tightens the upper bound of the variable exactly in the current node. + + Parameters + ---------- + var : Variable + ub : Rational + force : bool, optional + ignored; the exact SCIP function has no force parameter + + Returns + ------- + infeasible : bool + tightened : bool + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + + rational = _createRational(ub) + rc = SCIPtightenVarUbExact(self._scip, var.scip_var, rational, &infeasible, &tightened) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + return infeasible, tightened + + def aggregateVars(self, Variable varx, Variable vary, coefx=1, coefy=-1, rhs=0): + """ + Aggregates two variables exactly: coefx * varx + coefy * vary == rhs. + + Returns + ------- + infeasible : bool + redundant : bool + aggregated : bool + + """ + cdef SCIP_RATIONAL* scalarx + cdef SCIP_RATIONAL* scalary + cdef SCIP_RATIONAL* rhsexact + cdef SCIP_RETCODE rc + cdef SCIP_Bool infeasible + cdef SCIP_Bool redundant + cdef SCIP_Bool aggregated + + scalarx = _createRational(coefx) + scalary = _createRational(coefy) + rhsexact = _createRational(rhs) + rc = SCIPaggregateVarsExact(self._scip, varx.scip_var, vary.scip_var, scalarx, scalary, rhsexact, &infeasible, &redundant, &aggregated) + SCIPrationalFree(&scalarx) + SCIPrationalFree(&scalary) + SCIPrationalFree(&rhsexact) + PY_SCIP_CALL(rc) + return infeasible, redundant, aggregated + + def startDive(self): + """Initiates exact LP diving.""" + PY_SCIP_CALL(SCIPstartExactDive(self._scip)) + + def endDive(self): + """Quits exact LP diving.""" + PY_SCIP_CALL(SCIPendExactDive(self._scip)) + + def solveDiveLP(self, itlim=-1): + """ + Solves the exact diving LP. + + Returns + ------- + lperror : bool + cutoff : bool + + """ + cdef SCIP_Bool lperror + cdef SCIP_Bool cutoff + + PY_SCIP_CALL(SCIPsolveExactDiveLP(self._scip, itlim, &lperror, &cutoff)) + return lperror, cutoff + + def chgVarLbDive(self, Variable var, newbound): + """Changes the lower bound of the variable in the exact dive.""" + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + rational = _createBound(-float("inf") if newbound is None else newbound) + rc = SCIPchgVarLbExactDive(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgVarUbDive(self, Variable var, newbound): + """Changes the upper bound of the variable in the exact dive.""" + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + rational = _createBound(float("inf") if newbound is None else newbound) + rc = SCIPchgVarUbExactDive(self._scip, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def tightenVarLbGlobal(self, var, lb, force=False): + """Not available in exact solving mode.""" + raise ValueError("tightenVarLbGlobal is not available in exact solving mode") + + def tightenVarUbGlobal(self, var, ub, force=False): + """Not available in exact solving mode.""" + raise ValueError("tightenVarUbGlobal is not available in exact solving mode") + + def chgVarLbNode(self, node, var, lb): + """Not available in exact solving mode.""" + raise ValueError("chgVarLbNode is not available in exact solving mode") + + def chgVarUbNode(self, node, var, ub): + """Not available in exact solving mode.""" + raise ValueError("chgVarUbNode is not available in exact solving mode") + + def chgVarObjDive(self, var, newobj): + """Not available in exact solving mode.""" + raise ValueError("chgVarObjDive is not available in exact solving mode") + + def chgVarLbProbing(self, var, lb): + """Not available in exact solving mode.""" + raise ValueError("chgVarLbProbing is not available in exact solving mode") + + def chgVarUbProbing(self, var, ub): + """Not available in exact solving mode.""" + raise ValueError("chgVarUbProbing is not available in exact solving mode") + + def chgVarObjProbing(self, var, newobj): + """Not available in exact solving mode.""" + raise ValueError("chgVarObjProbing is not available in exact solving mode") + + def fixVarProbing(self, var, fixedval): + """Not available in exact solving mode.""" + raise ValueError("fixVarProbing is not available in exact solving mode") + + def setObjlimit(self, objlimit): + """Not available in exact solving mode: SCIP has no exact objective limit.""" + raise ValueError("setObjlimit is not available in exact solving mode") + + def infinity(self): + """Retrieve the value representing infinity in exact solving mode: inf.""" + return float("inf") + + def epsilon(self): + """Retrieve the comparison tolerance in exact solving mode: 0.""" + return Fraction(0) + + def feastol(self): + """Retrieve the feasibility tolerance in exact solving mode: 0.""" + return Fraction(0) + + def frac(self, value): + """Return the exact fractional part of value.""" + value = Fraction(value) + return value - value // 1 + + def feasFrac(self, value): + """Return the exact fractional part of value.""" + return self.frac(value) + + def feasFloor(self, value): + """Round value down to the nearest integer, exactly.""" + return Fraction(value) // 1 + + def feasCeil(self, value): + """Round value up to the nearest integer, exactly.""" + return -(-Fraction(value) // 1) + + def feasRound(self, value): + """Round value to the nearest integer, exactly; halves round up.""" + return (Fraction(value) + Fraction(1, 2)) // 1 + + def isZero(self, value): + """Return whether value is exactly zero.""" + return value == 0 + + def isFeasZero(self, value): + """Return whether value is exactly zero.""" + return self.isZero(value) + + def isInfinity(self, value): + """Return whether value is positive infinity.""" + return value == float("inf") + + def isPositive(self, val): + """Return whether val is exactly positive.""" + return val > 0 + + def isFeasPositive(self, value): + """Return whether value is exactly positive.""" + return self.isPositive(value) + + def isNegative(self, val): + """Return whether val is exactly negative.""" + return val < 0 + + def isFeasNegative(self, value): + """Return whether value is exactly negative.""" + return self.isNegative(value) + + def isIntegral(self, value): + """Return whether value is exactly integral.""" + return Fraction(value).denominator == 1 + + def isFeasIntegral(self, value): + """Return whether value is exactly integral.""" + return self.isIntegral(value) + + def isEQ(self, val1, val2): + """Return whether val1 and val2 are exactly equal.""" + return val1 == val2 + + def isFeasEQ(self, val1, val2): + """Return whether val1 and val2 are exactly equal.""" + return self.isEQ(val1, val2) + + def isLT(self, val1, val2): + """Return whether val1 is exactly less than val2.""" + return val1 < val2 + + def isFeasLT(self, val1, val2): + """Return whether val1 is exactly less than val2.""" + return self.isLT(val1, val2) + + def isLE(self, val1, val2): + """Return whether val1 is exactly less than or equal to val2.""" + return val1 <= val2 + + def isFeasLE(self, val1, val2): + """Return whether val1 is exactly less than or equal to val2.""" + return self.isLE(val1, val2) + + def isGT(self, val1, val2): + """Return whether val1 is exactly greater than val2.""" + return val1 > val2 + + def isFeasGT(self, val1, val2): + """Return whether val1 is exactly greater than val2.""" + return self.isGT(val1, val2) + + def isGE(self, val1, val2): + """Return whether val1 is exactly greater than or equal to val2.""" + return val1 >= val2 + + def isFeasGE(self, val1, val2): + """Return whether val1 is exactly greater than or equal to val2.""" + return self.isGE(val1, val2) + + def isHugeValue(self, val): + """Not available in exact solving mode: there is no huge-value threshold.""" + raise ValueError("isHugeValue is not available in exact solving mode") + + def getLPSolstat(self): + """ + Retrieve the solution status of the current exact LP. + + Returns + ------- + SCIP_LPSOLSTAT + + """ + if SCIPgetStage(self._scip) != SCIP_STAGE_SOLVING: + raise Warning("getLPSolstat cannot be called in stage %i." % SCIPgetStage(self._scip)) + return SCIPgetLPExactSolstat(self._scip) + + def printRow(self, RowExact row not None): + """ + Print a row to stdout; a RowExact is printed with its exact coefficients and sides. + + Parameters + ---------- + row : Row or RowExact + + """ + PY_SCIP_CALL(SCIPprintRowExact(self._scip, row.scip_row_exact, NULL)) + + def addConsLinear(self, vars, vals, lhs, rhs, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add an exact linear constraint lhs <= sum(vals[i] * vars[i]) <= rhs. + + Parameters + ---------- + vars : list of Variable + variables of the constraint + vals : list of Fraction or int + coefficients of the variables + lhs : Fraction, int or None + left-hand side, use None for -infinity + rhs : Fraction, int or None + right-hand side, use None for +infinity + name : str, optional + name of the constraint, generic if empty (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + + """ + cdef _VarArray wrapper = _VarArray(vars) + cdef int nvars = wrapper.size + cdef SCIP_RATIONAL** valsexact = NULL + cdef SCIP_RATIONAL* lhsexact = NULL + cdef SCIP_RATIONAL* rhsexact = NULL + cdef SCIP_CONS* scip_cons = NULL + cdef SCIP_RETCODE rc + cdef int i + + if len(vals) != nvars: + raise ValueError("number of variables (%i) and coefficients (%i) must be the same" % (nvars, len(vals))) + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + vals = [Fraction(val) for val in vals] + lhs = -float("inf") if lhs is None else lhs + rhs = float("inf") if rhs is None else rhs + + valsexact = malloc(max(nvars, 1) * sizeof(SCIP_RATIONAL*)) + if valsexact == NULL: + raise MemoryError() + for i in range(nvars): + valsexact[i] = _createRational(vals[i]) + lhsexact = _createBound(lhs) + rhsexact = _createBound(rhs) + + rc = SCIPcreateConsExactLinear( + self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, valsexact, + lhsexact, rhsexact, initial, separate, enforce, check, propagate, local, modifiable, + dynamic, removable, stickingatnode) + for i in range(nvars): + SCIPrationalFree(&valsexact[i]) + free(valsexact) + SCIPrationalFree(&lhsexact) + SCIPrationalFree(&rhsexact) + PY_SCIP_CALL(rc) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + return pyCons + + def _checkExactLinear(self, Constraint cons): + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype != 'exactlinear': + raise ValueError("expected a constraint of type exactlinear, got %s" % constype) + + def addCoefLinear(self, Constraint cons, Variable var, value): + """ + Add a variable with an exact coefficient to an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + var : Variable + variable to add + value : Fraction or int + coefficient of the variable + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + self._checkExactLinear(cons) + rational = _createRational(value) + rc = SCIPaddCoefExactLinear(self._scip, cons.scip_cons, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgCoefLinear(self, Constraint cons, Variable var, value): + """ + Change the exact coefficient of a variable in an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + var : Variable + variable whose coefficient is changed + value : Fraction or int + new coefficient of the variable + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + self._checkExactLinear(cons) + rational = _createRational(value) + rc = SCIPchgCoefExactLinear(self._scip, cons.scip_cons, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgLhs(self, Constraint cons, lhs): + """ + Change the exact left-hand side of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + lhs : Fraction, int or None + new left-hand side, use None for -infinity + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + self._checkExactLinear(cons) + rational = _createBound(-float("inf") if lhs is None else lhs) + rc = SCIPchgLhsExactLinear(self._scip, cons.scip_cons, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def chgRhs(self, Constraint cons, rhs): + """ + Change the exact right-hand side of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + rhs : Fraction, int or None + new right-hand side, use None for +infinity + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + self._checkExactLinear(cons) + rational = _createBound(float("inf") if rhs is None else rhs) + rc = SCIPchgRhsExactLinear(self._scip, cons.scip_cons, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def getLhs(self, Constraint cons): + """ + Retrieve the exact left-hand side of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + + Returns + ------- + Fraction or float + a Fraction, or -inf if the constraint has no left-hand side + + """ + self._checkExactLinear(cons) + return _fromRational(SCIPgetLhsExactLinear(self._scip, cons.scip_cons)) + + def getRhs(self, Constraint cons): + """ + Retrieve the exact right-hand side of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + + Returns + ------- + Fraction or float + a Fraction, or inf if the constraint has no right-hand side + + """ + self._checkExactLinear(cons) + return _fromRational(SCIPgetRhsExactLinear(self._scip, cons.scip_cons)) + + def getValsLinear(self, Constraint cons): + """ + Retrieve the exact coefficients of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + exact linear constraint + + Returns + ------- + dict of str to Fraction + + """ + cdef SCIP_VAR** vars + cdef SCIP_RATIONAL** vals + cdef int i + + self._checkExactLinear(cons) + vars = SCIPgetVarsExactLinear(self._scip, cons.scip_cons) + vals = SCIPgetValsExactLinear(self._scip, cons.scip_cons) + + valsdict = {} + for i in range(SCIPgetNVarsExactLinear(self._scip, cons.scip_cons)): + valsdict[bytes(SCIPvarGetName(vars[i])).decode('utf-8')] = _fromRational(vals[i]) + + return valsdict + + def getActivity(self, Constraint cons, Solution sol = None): + """ + Retrieve the exact activity of an exact linear constraint in a given solution. + + Parameters + ---------- + cons : Constraint + exact linear constraint + sol : Solution or None, optional + solution to compute the activity in, or None for the current LP/pseudo solution + (Default value = None) + + Returns + ------- + Fraction + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + cdef SCIP_SOL* scip_sol = NULL + + self._checkExactLinear(cons) + if not self.getStage() >= SCIP_STAGE_SOLVING: + raise Warning("method cannot be called before problem is solved") + if sol is not None: + _checkExactSol(sol) + scip_sol = sol.sol + + rational = _createRational(0) + rc = SCIPgetActivityExactLinear(self._scip, cons.scip_cons, scip_sol, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + return result + + def addObjoffset(self, offset, solutions=False): + """ + Add an exact constant to the objective function of the original problem. + + Parameters + ---------- + offset : Fraction or int + offset to add + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + if solutions: + raise ValueError("addObjoffset(solutions=True) is not available in exact solving mode") + if SCIPgetStage(self._scip) != SCIP_STAGE_PROBLEM: + raise Warning("addObjoffset can only be called in stage PROBLEM in exact solving mode") + rational = _createRational(offset) + rc = SCIPaddOrigObjoffsetExact(self._scip, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def getObjoffset(self, original=True): + """ + Retrieve the exact objective offset of the original problem. + + Returns + ------- + Fraction + + """ + if not original: + raise ValueError("only the original objective offset is available in exact solving mode") + if not SCIP_STAGE_PROBLEM <= SCIPgetStage(self._scip) <= SCIP_STAGE_SOLVED: + raise Warning("getObjoffset cannot be called in stage %i." % SCIPgetStage(self._scip)) + return _fromRational(SCIPgetOrigObjoffsetExact(self._scip)) + + def addCons(self, cons, name='', **kwargs): + """ + Not available in exact solving mode: expressions hold floating-point coefficients. + Use addConsLinear(vars, vals, lhs, rhs) instead. + """ + raise TypeError("ExactModel.addCons is not available because expressions hold floating-point coefficients; use addConsLinear(vars, vals, lhs, rhs)") + + def delCoefLinear(self, Constraint cons, Variable var): + """ + Deletes a variable from an exact linear constraint. + + Parameters + ---------- + cons : Constraint + var : Variable + + """ + self._checkExactLinear(cons) + PY_SCIP_CALL(SCIPdelCoefExactLinear(self._scip, cons.scip_cons, var.scip_var)) + + def getSlack(self, Constraint cons, Solution sol = None, side = None): + """ + Retrieve the slack of an exact linear constraint in the given solution. + + Parameters + ---------- + cons : Constraint + sol : Solution or None, optional + solution to use, None to use the current node's solution (Default value = None) + side : str or None, optional + whether to use 'lhs' or 'rhs' for ranged constraints, None to return minimum (Default value = None) + + Returns + ------- + Fraction or float + + """ + if not self.getStage() >= SCIP_STAGE_SOLVING: + raise Warning("method cannot be called before problem is solved") + lhs = self.getLhs(cons) + rhs = self.getRhs(cons) + activity = self.getActivity(cons, sol) + lhsslack = activity - lhs + rhsslack = rhs - activity + if side == 'lhs': + return lhsslack + elif side == 'rhs': + return rhsslack + else: + return min(lhsslack, rhsslack) + + def getRowLinear(self, Constraint cons): + """ + Retrieve the floating-point LP row of an exact linear constraint. + + Parameters + ---------- + cons : Constraint + + Returns + ------- + Row + + """ + self._checkExactLinear(cons) + return RowExact.create(SCIPgetRowExactExactLinear(self._scip, cons.scip_cons)) + + def getDualsolLinear(self, Constraint cons): + """ + Retrieve the dual solution of an exact linear constraint as a Fraction. + + Parameters + ---------- + cons : Constraint + + Returns + ------- + Fraction + + """ + cdef SCIP_RATIONAL* rational = NULL + + self._checkExactLinear(cons) + transcons = self.getTransformedCons(cons) if cons.isOriginal() else cons + PY_SCIP_CALL(SCIPrationalCreate(&rational)) + SCIPgetFpDualsolExactLinear(self._scip, transcons.scip_cons, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getDualfarkasLinear(self, Constraint cons): + """ + Retrieve the dual Farkas value of an exact linear constraint as a Fraction. + + Parameters + ---------- + cons : Constraint + + Returns + ------- + Fraction + + """ + cdef SCIP_RATIONAL* rational = NULL + + self._checkExactLinear(cons) + transcons = self.getTransformedCons(cons) if cons.isOriginal() else cons + PY_SCIP_CALL(SCIPrationalCreate(&rational)) + SCIPgetFpDualfarkasExactLinear(self._scip, transcons.scip_cons, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getConsVars(self, Constraint constraint): + """ + Gets variables in constraint; exact linear constraints are handled exactly. + + Parameters + ---------- + constraint : Constraint + + Returns + ------- + list of Variable + + """ + cdef SCIP_VAR** vars + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(constraint.scip_cons))).decode('UTF-8') + if constype != 'exactlinear': + return super().getConsVars(constraint) + vars = SCIPgetVarsExactLinear(self._scip, constraint.scip_cons) + return [self._getOrCreateVar(vars[i]) for i in range(SCIPgetNVarsExactLinear(self._scip, constraint.scip_cons))] + + def getConsVals(self, Constraint constraint): + """ + Gets coefficients in constraint; exact linear constraints return Fractions. + + Parameters + ---------- + constraint : Constraint + + Returns + ------- + list of Fraction + + """ + cdef SCIP_RATIONAL** vals + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(constraint.scip_cons))).decode('UTF-8') + if constype != 'exactlinear': + raise ValueError("getConsVals is only available for exact linear constraints in exact solving mode") + vals = SCIPgetValsExactLinear(self._scip, constraint.scip_cons) + return [_fromRational(vals[i]) for i in range(SCIPgetNVarsExactLinear(self._scip, constraint.scip_cons))] + + def _checkBoundStage(self, method): + if not SCIP_STAGE_TRANSFORMED <= SCIPgetStage(self._scip) <= SCIP_STAGE_EXITSOLVE: + raise Warning("%s cannot be called in stage %i." % (method, SCIPgetStage(self._scip))) + + def createSol(self, Heur heur = None, initlp=False): + """ + Create a new exact primal solution in the transformed space. + + Parameters + ---------- + heur : Heur or None, optional + heuristic that found the solution (Default value = None) + initlp : bool, optional + Should the created solution be initialised to the current LP solution instead of all zeros + + Returns + ------- + Solution + + """ + cdef SCIP_HEUR* _heur + cdef SCIP_SOL* _sol + + if isinstance(heur, Heur): + n = str_conversion(heur.name) + _heur = SCIPfindHeur(self._scip, n) + else: + _heur = NULL + if not initlp: + PY_SCIP_CALL(SCIPcreateSolExact(self._scip, &_sol, _heur)) + else: + PY_SCIP_CALL(SCIPcreateLPSolExact(self._scip, &_sol, _heur)) + return Solution.create(self._scip, _sol) + + def createOrigSol(self, Heur heur = None): + """Not available in exact solving mode.""" + raise ValueError("createOrigSol is not available in exact solving mode") + + def createPartialSol(self, Heur heur = None): + """Not available in exact solving mode.""" + raise ValueError("createPartialSol is not available in exact solving mode") + + def setSolVal(self, Solution solution, Variable var, val): + """ + Set a variable in a solution to a rational value. + + Parameters + ---------- + solution : Solution + var : Variable + val : Rational + + """ + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + + assert solution.sol != NULL, "Cannot set value to a freed solution." + rational = _createRational(val) + rc = SCIPsetSolValExact(self._scip, solution.sol, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) + + def getSolVal(self, Solution sol, expr): + """ + Retrieve the exact value of a variable in the given solution. + + Parameters + ---------- + sol : Solution or None + solution, None for the current LP/pseudo solution + expr : Variable or MatrixVariable + + Returns + ------- + Fraction or np.ndarray + + """ + cdef SCIP_RATIONAL* rational + + if sol is None: + sol = Solution.create(self._scip, NULL) + sol._checkStage("SCIPgetSolVal") + _checkExactSol(sol) + if isinstance(expr, MatrixVariable): + values = np.empty(expr.shape, dtype=object) + for idx in np.ndindex(expr.shape): + values[idx] = self.getSolVal(sol, expr[idx]) + return values + if not isinstance(expr, Variable): + raise TypeError("exact solution values are only available for variables; evaluate expressions from the variable values") + rational = _createRational(0) + SCIPgetSolValExact(self._scip, sol.sol, (expr).scip_var, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getVal(self, expr): + """ + Retrieve the exact value of a variable in the best known solution. + + Parameters + ---------- + expr : Variable or MatrixVariable + + Returns + ------- + Fraction or np.ndarray + + """ + cdef SCIP_SOL* current_best_sol + + if SCIPgetStage(self._scip) in {SCIP_STAGE_INIT, SCIP_STAGE_FREE}: + raise Warning("Method cannot be called in stage ", self.getStage()) + current_best_sol = SCIPgetBestSol(self._scip) + if self._bestSol is None or self._bestSol.sol != current_best_sol: + self._bestSol = Solution.create(self._scip, current_best_sol) + if self._bestSol.sol == NULL and SCIPgetStage(self._scip) != SCIP_STAGE_SOLVING: + raise Warning("No solution available") + return self.getSolVal(self._bestSol, expr) + + def getSolObjVal(self, Solution sol, original=True): + """ + Retrieve the exact objective value of the solution. + + Parameters + ---------- + sol : Solution or None + original : bool, optional + objective value in original space; only True is supported, SCIP exports no exact + transformed objective value (Default value = True) + + Returns + ------- + Fraction + + """ + cdef SCIP_RATIONAL* rational + + if not original: + raise ValueError("the transformed objective value is not available in exact solving mode") + if sol is None: + sol = Solution.create(self._scip, NULL) + sol._checkStage("getSolObjVal") + _checkExactSol(sol) + rational = _createRational(0) + SCIPgetSolOrigObjExact(self._scip, sol.sol, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def trySol(self, Solution solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, free=True): + """ + Check given exact primal solution for feasibility and try to add it to the storage. + + Returns + ------- + stored : bool + + """ + cdef SCIP_Bool stored + + if SCIPgetStage(self._scip) < SCIP_STAGE_TRANSFORMED: + raise Warning("trySol cannot be called before the problem is transformed") + if free: + PY_SCIP_CALL(SCIPtrySolFree(self._scip, &solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) + else: + PY_SCIP_CALL(SCIPtrySol(self._scip, solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) + return stored + + def printSol(self, Solution solution=None, write_zeros=False): + """ + Print the given exact primal solution. + + Parameters + ---------- + solution : Solution or None, optional + solution to print, None for the current LP/pseudo solution + write_zeros : bool, optional + include variables that are set to zero + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + if solution is None: + PY_SCIP_CALL(SCIPprintSolExact(self._scip, NULL, NULL, write_zeros)) + else: + PY_SCIP_CALL(SCIPprintSolExact(self._scip, solution.sol, NULL, write_zeros)) + locale.setlocale(locale.LC_NUMERIC, user_locale) + + def printBestSol(self, write_zeros=False): + """Print the best exact primal solution.""" + cdef SCIP_SOL* best = SCIPgetBestSol(self._scip) + + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + if best == NULL: + PY_SCIP_CALL(SCIPprintBestSol(self._scip, NULL, write_zeros)) + else: + PY_SCIP_CALL(SCIPprintSolExact(self._scip, best, NULL, write_zeros)) + locale.setlocale(locale.LC_NUMERIC, user_locale) + + def writeSol(self, Solution solution, filename="origprob.sol", write_zeros=False): + """Write the given exact primal solution to a file.""" + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + PY_SCIP_CALL(SCIPprintSolExact(self._scip, solution.sol, cfile, write_zeros)) + locale.setlocale(locale.LC_NUMERIC, user_locale) + + def writeBestSol(self, filename="origprob.sol", write_zeros=False): + """Write the best exact primal solution to a file.""" + cdef SCIP_SOL* best = SCIPgetBestSol(self._scip) + + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + if best == NULL: + PY_SCIP_CALL(SCIPprintBestSol(self._scip, cfile, write_zeros)) + else: + PY_SCIP_CALL(SCIPprintSolExact(self._scip, best, cfile, write_zeros)) + locale.setlocale(locale.LC_NUMERIC, user_locale) + + def getPrimalbound(self): + """ + Retrieve the exact best primal bound (objective value of the best solution). + + Returns + ------- + Fraction or float + + """ + cdef SCIP_RATIONAL* rational + + self._checkBoundStage("getPrimalbound") + rational = _createRational(0) + SCIPgetPrimalboundExact(self._scip, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getDualbound(self): + """ + Retrieve the exact best dual bound. + + Returns + ------- + Fraction or float + + """ + cdef SCIP_RATIONAL* rational + + self._checkBoundStage("getDualbound") + rational = _createRational(0) + SCIPgetDualboundExact(self._scip, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getUpperbound(self): + """ + Retrieve the exact global upper (primal) bound in transformed space. + + Returns + ------- + Fraction or float + + """ + cdef SCIP_RATIONAL* rational + + self._checkBoundStage("getUpperbound") + rational = _createRational(0) + SCIPgetUpperboundExact(self._scip, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getLowerbound(self): + """ + Retrieve the exact global lower (dual) bound in transformed space. + + Returns + ------- + Fraction or float + + """ + cdef SCIP_RATIONAL* rational + + self._checkBoundStage("getLowerbound") + rational = _createRational(0) + SCIPgetLowerboundExact(self._scip, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getLPObjVal(self): + """ + Retrieve the objective value of the current exact LP. + + Returns + ------- + Fraction or float + + """ + cdef SCIP_RATIONAL* rational + + self._checkBoundStage("getLPObjVal") + rational = _createRational(0) + SCIPgetLPExactObjval(self._scip, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result + + def getCutoffbound(self): + """ + Retrieve the exact global cutoff bound. + + Returns + ------- + Fraction or float + + """ + self._checkBoundStage("getCutoffbound") + return _fromRational(SCIPgetCutoffboundExact(self._scip)) + + def allowNegSlack(self): + """ + Returns whether negative slack is allowed in exact solving mode. + + Returns + ------- + bool + """ + + return SCIPallowNegSlack(self._scip) + + def branchLP(self): + """ + Performs exact LP branching. + + Returns + ------- + SCIP_RESULT + """ + cdef SCIP_RESULT result + PY_SCIP_CALL(SCIPbranchLPExact(self._scip, &result)) + return result + + def addRow(self, RowExact rowexact): + """ + Adds an exact row to the LP. + + Parameters + ---------- + rowexact : RowExact + The exact row to add. + """ + PY_SCIP_CALL(SCIPaddRowExact(self._scip, rowexact.scip_row_exact)) diff --git a/src/pyscipopt/heuristic.pxi b/src/pyscipopt/heuristic.pxi index da5efeccc..5dc833cc8 100644 --- a/src/pyscipopt/heuristic.pxi +++ b/src/pyscipopt/heuristic.pxi @@ -1,7 +1,7 @@ ##@file heuristic.pxi #@brief Base class of the Heuristics Plugin cdef class Heur: - cdef public Model model + cdef public BaseModel model cdef public str name def heurfree(self): diff --git a/src/pyscipopt/iisfinder.pxi b/src/pyscipopt/iisfinder.pxi index 774d49749..96f33be22 100644 --- a/src/pyscipopt/iisfinder.pxi +++ b/src/pyscipopt/iisfinder.pxi @@ -1,7 +1,7 @@ ##@file iisfinder.pxi #@brief Base class of the IIS finder Plugin cdef class IISfinder: - cdef public Model model + cdef public BaseModel model cdef public IIS iis cdef SCIP_IIS* scip_iis cdef SCIP_IISFINDER* scip_iisfinder diff --git a/src/pyscipopt/model.pxi b/src/pyscipopt/model.pxi new file mode 100644 index 000000000..409705f69 --- /dev/null +++ b/src/pyscipopt/model.pxi @@ -0,0 +1,6356 @@ +cdef class Column: + """Base class holding a pointer to corresponding SCIP_COL.""" + + @staticmethod + cdef create(SCIP_COL* scipcol): + """ + Main method for creating a Column class. Is used instead of __init__. + + Parameters + ---------- + scipcol : SCIP_COL* + A pointer to the SCIP_COL + + Returns + ------- + col : Column + The Python representative of the SCIP_COL + + """ + if scipcol == NULL: + raise Warning("cannot create Column with SCIP_COL* == NULL") + col = Column() + col.scip_col = scipcol + return col + + def getLPPos(self): + """ + Gets position of column in current LP, or -1 if it is not in LP. + + Returns + ------- + int + + """ + return SCIPcolGetLPPos(self.scip_col) + + def getBasisStatus(self): + """ + Gets the basis status of a column in the LP solution + + Returns + ------- + str + Possible values are "lower", "basic", "upper", and "zero" + + Raises + ------ + Exception + If SCIP returns an unknown basis status + + Notes + ----- + Returns basis status "zero" for columns not in the current SCIP LP. + + """ + cdef SCIP_BASESTAT stat = SCIPcolGetBasisStatus(self.scip_col) + if stat == SCIP_BASESTAT_LOWER: + return "lower" + elif stat == SCIP_BASESTAT_BASIC: + return "basic" + elif stat == SCIP_BASESTAT_UPPER: + return "upper" + elif stat == SCIP_BASESTAT_ZERO: + return "zero" + else: + raise Exception('SCIP returned unknown base status!') + + def isIntegral(self): + """ + Returns whether the associated variable is of integral type (binary, integer, implicit integer). + + Returns + ------- + bool + + """ + return SCIPcolIsIntegral(self.scip_col) + + def getVar(self): + """ + Gets variable this column represents. + + Returns + ------- + Variable + + """ + cdef SCIP_VAR* var = SCIPcolGetVar(self.scip_col) + return Variable.create(var) + + def getPrimsol(self): + """ + Gets the primal LP solution of a column. + + Returns + ------- + float + + """ + return SCIPcolGetPrimsol(self.scip_col) + + def getLb(self): + """ + Gets lower bound of column. + + Returns + ------- + float + + """ + return SCIPcolGetLb(self.scip_col) + + def getUb(self): + """ + Gets upper bound of column. + + Returns + ------- + float + + """ + return SCIPcolGetUb(self.scip_col) + + def getObjCoeff(self): + """ + Gets objective value coefficient of a column. + + Returns + ------- + float + + """ + return SCIPcolGetObj(self.scip_col) + + def getAge(self): + """ + Gets the age of the column, i.e., the total number of successive times a column was in the LP + and was 0.0 in the solution. + + Returns + ------- + int + + """ + return SCIPcolGetAge(self.scip_col) + + def __hash__(self): + return hash(self.scip_col) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self.scip_col == (other).scip_col) + +cdef class Row: + """Base class holding a pointer to corresponding SCIP_ROW.""" + + @staticmethod + cdef create(SCIP_ROW* sciprow): + """ + Main method for creating a Row class. Is used instead of __init__. + + Parameters + ---------- + sciprow : SCIP_ROW* + A pointer to the SCIP_ROW + + Returns + ------- + row : Row + The Python representative of the SCIP_ROW + + """ + if sciprow == NULL: + raise Warning("cannot create Row with SCIP_ROW* == NULL") + row = Row() + row.scip_row = sciprow + return row + + @property + def name(self): + return bytes(SCIProwGetName(self.scip_row)).decode("utf-8") + + def getLhs(self): + """ + Returns the left hand side of row. + + Returns + ------- + float + + """ + return SCIProwGetLhs(self.scip_row) + + def getRhs(self): + """ + Returns the right hand side of row. + + Returns + ------- + float + + """ + return SCIProwGetRhs(self.scip_row) + + def getConstant(self): + """ + Gets constant shift of row. + + Returns + ------- + float + + """ + return SCIProwGetConstant(self.scip_row) + + def getDualsol(self): + """ + Returns the dual solution of row. + + Returns + ------- + float + + """ + return SCIProwGetDualsol(self.scip_row) + + def getDualfarkas(self): + """ + Returns the dual Farkas solution of row. + + Returns + ------- + float + + """ + return SCIProwGetDualfarkas(self.scip_row) + + def getLPPos(self): + """ + Gets position of row in current LP, or -1 if it is not in LP. + + Returns + ------- + int + + """ + return SCIProwGetLPPos(self.scip_row) + + def getBasisStatus(self): + """ + Gets the basis status of a row in the LP solution. + + Returns + ------- + str + Possible values are "lower", "basic", and "upper" + + Raises + ------ + Exception + If SCIP returns an unknown or "zero" basis status + + Notes + ----- + Returns basis status "basic" for rows not in the current SCIP LP. + + """ + cdef SCIP_BASESTAT stat = SCIProwGetBasisStatus(self.scip_row) + if stat == SCIP_BASESTAT_LOWER: + return "lower" + elif stat == SCIP_BASESTAT_BASIC: + return "basic" + elif stat == SCIP_BASESTAT_UPPER: + return "upper" + elif stat == SCIP_BASESTAT_ZERO: + # this shouldn't happen! + raise Exception('SCIP returned base status zero for a row!') + else: + raise Exception('SCIP returned unknown base status!') + + def isIntegral(self): + """ + Returns TRUE iff the activity of the row (without the row's constant) + is always integral in a feasible solution. + + Returns + ------- + bool + + """ + return SCIProwIsIntegral(self.scip_row) + + def isLocal(self): + """ + Returns TRUE iff the row is only valid locally. + + Returns + ------- + bool + + """ + return SCIProwIsLocal(self.scip_row) + + def isModifiable(self): + """ + Returns TRUE iff row is modifiable during node processing (subject to column generation). + + Returns + ------- + bool + + """ + return SCIProwIsModifiable(self.scip_row) + + def isRemovable(self): + """ + Returns TRUE iff row is removable from the LP (due to aging or cleanup). + + Returns + ------- + bool + + """ + return SCIProwIsRemovable(self.scip_row) + + def isInGlobalCutpool(self): + """ + Return TRUE iff row is a member of the global cut pool. + + Returns + ------- + bool + + """ + return SCIProwIsInGlobalCutpool(self.scip_row) + + def getOrigintype(self): + """ + Returns type of origin that created the row. + + Returns + ------- + PY_SCIP_ROWORIGINTYPE + + """ + return SCIProwGetOrigintype(self.scip_row) + + def getConsOriginConshdlrtype(self): + """ + Returns type of constraint handler that created the row. + + Returns + ------- + str + + """ + cdef SCIP_CONS* scip_con = SCIProwGetOriginCons(self.scip_row) + return bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(scip_con))).decode('UTF-8') + + def getNNonz(self): + """ + Get number of nonzero entries in row vector. + + Returns + ------- + int + + """ + return SCIProwGetNNonz(self.scip_row) + + def getNLPNonz(self): + """ + Get number of nonzero entries in row vector that correspond to columns currently in the SCIP LP. + + Returns + ------- + int + + """ + return SCIProwGetNLPNonz(self.scip_row) + + def getCols(self): + """ + Gets list with columns of nonzero entries + + Returns + ------- + list of Column + + """ + cdef SCIP_COL** cols = SCIProwGetCols(self.scip_row) + cdef int i + return [Column.create(cols[i]) for i in range(self.getNNonz())] + + def getVals(self): + """ + Gets list with coefficients of nonzero entries. + + Returns + ------- + list of int + + """ + cdef SCIP_Real* vals = SCIProwGetVals(self.scip_row) + cdef int i + return [vals[i] for i in range(self.getNNonz())] + + def getAge(self): + """ + Gets the age of the row. (The consecutive times the row has been non-active in the LP). + + Returns + ------- + int + + """ + return SCIProwGetAge(self.scip_row) + + def getNorm(self): + """ + Gets Euclidean norm of row vector. + + Returns + ------- + float + + """ + return SCIProwGetNorm(self.scip_row) + + def __hash__(self): + return hash(self.scip_row) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self.scip_row == (other).scip_row) + +cdef class NLRow: + """Base class holding a pointer to corresponding SCIP_NLROW.""" + + @staticmethod + cdef create(SCIP_NLROW* scipnlrow): + """ + Main method for creating a NLRow class. Is used instead of __init__. + + Parameters + ---------- + scipnlrow : SCIP_NLROW* + A pointer to the SCIP_NLROW + + Returns + ------- + nlrow : NLRow + The Python representative of the SCIP_NLROW + + """ + if scipnlrow == NULL: + raise Warning("cannot create NLRow with SCIP_NLROW* == NULL") + nlrow = NLRow() + nlrow.scip_nlrow = scipnlrow + return nlrow + + @property + def name(self): + return bytes(SCIPnlrowGetName(self.scip_nlrow)).decode("utf-8") + + def getConstant(self): + """ + Returns the constant of a nonlinear row. + + Returns + ------- + float + + """ + return SCIPnlrowGetConstant(self.scip_nlrow) + + def getLinearTerms(self): + """ + Returns a list of tuples (var, coef) representing the linear part of a nonlinear row. + + Returns + ------- + list of tuple + + """ + cdef SCIP_VAR** linvars = SCIPnlrowGetLinearVars(self.scip_nlrow) + cdef SCIP_Real* lincoefs = SCIPnlrowGetLinearCoefs(self.scip_nlrow) + cdef int nlinvars = SCIPnlrowGetNLinearVars(self.scip_nlrow) + cdef int i + return [(Variable.create(linvars[i]), lincoefs[i]) for i in range(nlinvars)] + + def getLhs(self): + """ + Returns the left hand side of a nonlinear row. + + Returns + ------- + float + + """ + return SCIPnlrowGetLhs(self.scip_nlrow) + + def getRhs(self): + """ + Returns the right hand side of a nonlinear row. + + Returns + ------- + float + + """ + return SCIPnlrowGetRhs(self.scip_nlrow) + + def getDualsol(self): + """ + Gets the dual NLP solution of a nonlinear row. + + Returns + ------- + float + + """ + return SCIPnlrowGetDualsol(self.scip_nlrow) + + def __hash__(self): + return hash(self.scip_nlrow) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self.scip_nlrow == (other).scip_nlrow) + + +cdef class Model(BaseModel): + """Model solving with floating-point arithmetic.""" + + def getFirstPrimalBound(self): + """ + Gets the primal bound of the very first solution in the original space. + + Returns + ------- + float + + """ + return SCIPgetFirstPrimalBound(self._scip) + + def getAvgLowerbound(self): + """ + Gets average lower (dual) bound of all unprocessed nodes in transformed problem. + + Returns + ------- + float + + """ + return SCIPgetAvgLowerbound(self._scip) + + def getAvgDualbound(self): + """ + Gets average dual bound of all unprocessed nodes for original problem. + + Returns + ------- + float + + """ + return SCIPgetAvgDualbound(self._scip) + + def getLowerbound(self): + """ + Gets global lower (dual) bound of the transformed problem. + + Returns + ------- + float + + """ + return SCIPgetLowerbound(self._scip) + + def getCutoffbound(self): + """ + Gets the cutoff bound of the transformed problem. + + Returns + ------- + float + + """ + return SCIPgetCutoffbound(self._scip) + + def getUpperbound(self): + """ + Gets global upper (primal) bound in transformed problem (objective value of best solution or user objective limit). + + Returns + ------- + float + """ + return SCIPgetUpperbound(self._scip) + + def infinity(self): + """ + Retrieve SCIP's infinity value. + + Returns + ------- + int + + """ + return SCIPinfinity(self._scip) + + def epsilon(self): + """ + Retrieve epsilon for e.g. equality checks. + + Returns + ------- + float + + """ + return SCIPepsilon(self._scip) + + def feastol(self): + """ + Retrieve feasibility tolerance. + + Returns + ------- + float + + """ + return SCIPfeastol(self._scip) + + def feasFrac(self, value): + """ + Returns fractional part of value, i.e. x - floor(x) in feasible tolerance: x - floor(x+feastol). + + Parameters + ---------- + value : float + + Returns + ------- + float + + """ + return SCIPfeasFrac(self._scip, value) + + def frac(self, value): + """ + Returns fractional part of value, i.e. x - floor(x) in epsilon tolerance: x - floor(x+eps). + + Parameters + ---------- + value : float + + Returns + ------- + float + + """ + return SCIPfrac(self._scip, value) + + def feasFloor(self, value): + """ + Rounds value + feasibility tolerance down to the next integer. + + Parameters + ---------- + value : float + + Returns + ------- + float + + """ + return SCIPfeasFloor(self._scip, value) + + def feasCeil(self, value): + """ + Rounds value - feasibility tolerance up to the next integer. + + Parameters + ---------- + value : float + + Returns + ------- + float + + """ + return SCIPfeasCeil(self._scip, value) + + def feasRound(self, value): + """ + Rounds value to the nearest integer in feasibility tolerance. + + Parameters + ---------- + value : float + + Returns + ------- + float + + """ + return SCIPfeasRound(self._scip, value) + + def isZero(self, value): + """ + Returns whether abs(value) < eps. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisZero(self._scip, value) + + def isFeasZero(self, value): + """ + Returns whether abs(value) < feastol. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisFeasZero(self._scip, value) + + def isInfinity(self, value): + """ + Returns whether value is SCIP's infinity. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisInfinity(self._scip, value) + + def isFeasNegative(self, value): + """ + Returns whether value < -feastol. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisFeasNegative(self._scip, value) + + def isFeasPositive(self, value): + """ + Returns whether value > feastol. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisFeasPositive(self._scip, value) + + def isFeasIntegral(self, value): + """ + Returns whether value is integral within the LP feasibility bounds. + + Parameters + ---------- + value : float + + Returns + ------- + bool + + """ + return SCIPisFeasIntegral(self._scip, value) + + def isIntegral(self, value): + """ + Returns whether value is integral within epsilon tolerance. + + Parameters + ---------- + value : float + value to check + + Returns + ------- + bool + + """ + return SCIPisIntegral(self._scip, value) + + def adjustedVarLb(self, Variable var, lb): + """ + Returns the adjusted (i.e. rounded, if the given variable is of integral type) lower bound value; + does not change the bounds of the variable. + + Parameters + ---------- + var : Variable + variable for which the bound is adjusted + lb : float + lower bound value to adjust + + Returns + ------- + float + adjusted lower bound + + """ + return SCIPadjustedVarLb(self._scip, var.scip_var, lb) + + def adjustedVarUb(self, Variable var, ub): + """ + Returns the adjusted (i.e. rounded, if the given variable is of integral type) upper bound value; + does not change the bounds of the variable. + + Parameters + ---------- + var : Variable + variable for which the bound is adjusted + ub : float + upper bound value to adjust + + Returns + ------- + float + adjusted upper bound + + """ + return SCIPadjustedVarUb(self._scip, var.scip_var, ub) + + def isEQ(self, val1, val2): + """ + Checks, if values are in range of epsilon. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisEQ(self._scip, val1, val2) + + def isFeasEQ(self, val1, val2): + """ + Returns if relative difference between val1 and val2 is in range of feasibility tolerance. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisFeasEQ(self._scip, val1, val2) + + def isFeasLT(self, val1, val2): + """ + Returns whether relative difference between val1 and val2 is lower than minus feasibility tolerance. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisFeasLT(self._scip, val1, val2) + + def isFeasLE(self, val1, val2): + """ + Returns whether relative difference between val1 and val2 is not greater than feasibility tolerance. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisFeasLE(self._scip, val1, val2) + + def isFeasGT(self, val1, val2): + """ + Returns whether relative difference between val1 and val2 is greater than feasibility tolerance. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisFeasGT(self._scip, val1, val2) + + def isFeasGE(self, val1, val2): + """ + Returns whether relative difference of val1 and val2 is not lower than minus feasibility tolerance. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisFeasGE(self._scip, val1, val2) + + def isLE(self, val1, val2): + """ + Returns whether val1 <= val2 + eps. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisLE(self._scip, val1, val2) + + def isLT(self, val1, val2): + """ + Returns whether val1 < val2 - eps. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisLT(self._scip, val1, val2) + + def isGE(self, val1, val2): + """ + Returns whether val1 >= val2 - eps. + + Parameters + ---------- + val1 : float + val2 : float + + Returns + ------- + bool + + """ + return SCIPisGE(self._scip, val1, val2) + + def isGT(self, val1, val2): + """ + Returns whether val1 > val2 + eps. + + Parameters + ---------- + val1 : float + val2 : foat + + Returns + ------- + bool + + """ + return SCIPisGT(self._scip, val1, val2) + + def isHugeValue(self, val): + """ + Checks if value is huge and should be + handled separately (e.g., in activity computation). + + Parameters + ---------- + val : float + + Returns + ------- + bool + + """ + return SCIPisHugeValue(self._scip, val) + + def isPositive(self, val): + """ + Returns whether val > eps. + + Parameters + ---------- + val : float + + Returns + ------- + bool + + """ + return SCIPisPositive(self._scip, val) + + def isNegative(self, val): + """ + Returns whether val < -eps. + + Parameters + ---------- + val : float + + Returns + ------- + bool + + """ + return SCIPisNegative(self._scip, val) + + def setObjlimit(self, objlimit): + """ + Set a limit on the objective function. + Only solutions with objective value better than this limit are accepted. + + Parameters + ---------- + objlimit : float + limit on the objective function + + """ + PY_SCIP_CALL(SCIPsetObjlimit(self._scip, objlimit)) + + def getObjlimit(self): + """ + Returns current limit on objective function. + + Returns + ------- + float + + """ + return SCIPgetObjlimit(self._scip) + + def setObjective(self, expr, sense = 'minimize', clear = 'true'): + """ + Establish the objective function as a linear expression. + + Parameters + ---------- + expr : Expr or float + the objective function SCIP Expr, or constant value + sense : str, optional + the objective sense ("minimize" or "maximize") (Default value = 'minimize') + clear : bool, optional + set all other variables objective coefficient to zero (Default value = 'true') + + """ + cdef SCIP_VAR** vars + cdef int nvars + cdef SCIP_Real coef + cdef int i + cdef _VarArray wrapper + + if not isinstance(expr, Expr) and not _is_number(expr): + raise TypeError( + f"requires Expr or number but got type {type(expr).__name__!s}" + ) + + # turn the constant value into an Expr instance for further processing + expr = Expr() + expr + if expr.degree() > 1: + raise ValueError("SCIP does not support nonlinear objective functions. Consider using set_nonlinear_objective in the pyscipopt.recipe.nonlinear") + + + if clear: + # clear existing objective function + self.addObjoffset(-self.getObjoffset()) + vars = SCIPgetOrigVars(self._scip) + nvars = SCIPgetNOrigVars(self._scip) + for i in range(nvars): + PY_SCIP_CALL(SCIPchgVarObj(self._scip, vars[i], 0.0)) + + if expr[CONST] != 0.0: + self.addObjoffset(expr[CONST]) + + for term, coef in expr.terms.items(): + # avoid CONST term of Expr + if term != CONST: + assert len(term) == 1 + wrapper = _VarArray(term[0]) + PY_SCIP_CALL(SCIPchgVarObj(self._scip, wrapper.ptr[0], coef)) + + if sense == "minimize": + self.setMinimize() + elif sense == "maximize": + self.setMaximize() + else: + raise Warning("unrecognized optimization sense: %s" % sense) + + def getObjective(self): + """ + Retrieve objective function as Expr. + + Returns + ------- + Expr + + """ + variables = self.getVars() + objective = Expr() + for var in variables: + coeff = var.getObj() + if coeff != 0: + objective += coeff * var + objective.normalize() + return objective + + def addObjoffset(self, offset, solutions = False): + """ + Add constant offset to objective. + + Parameters + ---------- + offset : float + offset to add + solutions : bool, optional + add offset also to existing solutions (Default value = False) + + """ + if solutions: + PY_SCIP_CALL(SCIPaddObjoffset(self._scip, offset)) + else: + PY_SCIP_CALL(SCIPaddOrigObjoffset(self._scip, offset)) + + def getObjoffset(self, original = True): + """ + Retrieve constant objective offset + + Parameters + ---------- + original : bool, optional + offset of original or transformed problem (Default value = True) + + Returns + ------- + float + + """ + if original: + return SCIPgetOrigObjoffset(self._scip) + else: + return SCIPgetTransObjoffset(self._scip) + + def getLocalEstimate(self, original = False): + """ + Gets estimate of best primal solution w.r.t. original or transformed problem contained in current subtree. + + Parameters + ---------- + original : bool, optional + get estimate of original or transformed problem (Default value = False) + + Returns + ------- + float + + """ + if original: + return SCIPgetLocalOrigEstimate(self._scip) + else: + return SCIPgetLocalTransEstimate(self._scip) + + # Variable Functions + def addVar(self, name='', vtype='C', lb=0.0, ub=None, obj=0.0, pricedVar=False, pricedVarScore=1.0, deletable=False): + """ + Create a new variable. Default variable is non-negative and continuous. + + Parameters + ---------- + name : str, optional + name of the variable, generic if empty (Default value = '') + vtype : str, optional + type of the variable: 'C' continuous, 'I' integer, 'B' binary, and 'M' implicit integer + (Default value = 'C') + lb : float or None, optional + lower bound of the variable, use None for -infinity (Default value = 0.0) + ub : float or None, optional + upper bound of the variable, use None for +infinity (Default value = None) + obj : float, optional + objective value of variable (Default value = 0.0) + pricedVar : bool, optional + is the variable a pricing candidate? (Default value = False) + pricedVarScore : float, optional + score of variable in case it is priced, the higher the better (Default value = 1.0) + + Returns + ------- + Variable + + """ + cdef SCIP_VAR* scip_var + + # replace empty name with generic one + if name == '': + name = 'x'+str(SCIPgetNVars(self._scip)+1) + cname = str_conversion(name) + + # replace None with corresponding infinity + if lb is None: + lb = -SCIPinfinity(self._scip) + if ub is None: + ub = SCIPinfinity(self._scip) + + vtype = vtype.upper() + if vtype in ['C', 'CONTINUOUS']: + PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_CONTINUOUS)) + elif vtype in ['B', 'BINARY']: + if ub > 1.0: + ub = 1.0 + if lb < 0.0: + lb = 0.0 + PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_BINARY)) + elif vtype in ['I', 'INTEGER']: + PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_INTEGER)) + elif vtype in ['M', 'IMPLINT']: + PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_DEPRECATED_VARTYPE_IMPLINT)) + else: + raise Warning("unrecognized variable type") + + if deletable: + SCIPvarMarkDeletable(scip_var) + + if pricedVar: + PY_SCIP_CALL(SCIPaddPricedVar(self._scip, scip_var, pricedVarScore)) + else: + PY_SCIP_CALL(SCIPaddVar(self._scip, scip_var)) + + pyVar = self._getOrCreateVar(scip_var) + + #setting the variable data + SCIPvarSetData(scip_var, pyVar) + PY_SCIP_CALL(SCIPreleaseVar(self._scip, &scip_var)) + return pyVar + + def fixVar(self, Variable var, val): + """ + Fixes the variable var to the value val if possible. + + Parameters + ---------- + var : Variable + variable to fix + val : float + the fix value + + Returns + ------- + infeasible : bool + Is the fixing infeasible? + fixed : bool + Was the fixing performed? + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool fixed + PY_SCIP_CALL(SCIPfixVar(self._scip, var.scip_var, val, &infeasible, &fixed)) + return infeasible, fixed + + def aggregateVars(self, Variable varx, Variable vary, coefx=1.0, coefy=-1.0, rhs=0.0): + """ + Aggregate two variables by adding an aggregation constraint. + + The aggregation is defined by the linear equation: + + coefx * varx + coefy * vary = rhs + + After aggregation, varx becomes a redundant variable and vary remains active. + The aggregation effectively substitutes varx with: (rhs - coefy * vary) / coefx + + This method can only be called during presolving. + + Parameters + ---------- + varx : Variable + variable to be aggregated (will become redundant) + vary : Variable + variable to aggregate with (will remain active) + coefx : float, optional + coefficient for varx in the aggregation equation (default: 1.0) + coefy : float, optional + coefficient for vary in the aggregation equation (default: -1.0) + rhs : float, optional + right-hand side of the aggregation equation (default: 0.0) + + Returns + ------- + infeasible : bool + whether the aggregation is infeasible (e.g., bounds are incompatible) + redundant : bool + whether the aggregation makes varx redundant + aggregated : bool + whether the aggregation was actually performed + + Examples + -------- + To express x = y (i.e., 1*x + (-1)*y = 0): + + infeas, redun, aggr = model.aggregateVars(x, y, 1.0, -1.0, 0.0) + + To express x = 5 - y (i.e., 1*x + 1*y = 5): + + infeas, redun, aggr = model.aggregateVars(x, y, 1.0, 1.0, 5.0) + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool redundant + cdef SCIP_Bool aggregated + PY_SCIP_CALL(SCIPaggregateVars(self._scip, + varx.scip_var, + vary.scip_var, + coefx, + coefy, + rhs, + &infeasible, + &redundant, + &aggregated)) + return infeasible, redundant, aggregated + + def tightenVarLb(self, Variable var, lb, force=False): + """ + Tighten the lower bound in preprocessing or current node, if the bound is tighter. + + Parameters + ---------- + var : Variable + SCIP variable + lb : float + possible new lower bound + force : bool, optional + force tightening even if below bound strengthening tolerance (default = False) + + Returns + ------- + infeasible : bool + Whether new domain is empty + tightened : bool + Whether the bound was tightened + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPtightenVarLb(self._scip, var.scip_var, lb, force, &infeasible, &tightened)) + return infeasible, tightened + + def tightenVarUb(self, Variable var, ub, force=False): + """ + Tighten the upper bound in preprocessing or current node, if the bound is tighter. + + Parameters + ---------- + var : Variable + SCIP variable + ub : float + possible new upper bound + force : bool, optional + force tightening even if below bound strengthening tolerance + + Returns + ------- + infeasible : bool + Whether new domain is empty + tightened : bool + Whether the bound was tightened + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPtightenVarUb(self._scip, var.scip_var, ub, force, &infeasible, &tightened)) + return infeasible, tightened + + def tightenVarUbGlobal(self, Variable var, ub, force=False): + """ + Tighten the global upper bound, if the bound is tighter. + + Parameters + ---------- + var : Variable + SCIP variable + ub : float + possible new upper bound + force : bool, optional + force tightening even if below bound strengthening tolerance + + Returns + ------- + infeasible : bool + Whether new domain is empty + tightened : bool + Whether the bound was tightened + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPtightenVarUbGlobal(self._scip, var.scip_var, ub, force, &infeasible, &tightened)) + return infeasible, tightened + + def tightenVarLbGlobal(self, Variable var, lb, force=False): + """Tighten the global lower bound, if the bound is tighter. + + Parameters + ---------- + var : Variable + SCIP variable + lb : float + possible new lower bound + force : bool, optional + force tightening even if below bound strengthening tolerance + + Returns + ------- + infeasible : bool + Whether new domain is empty + tightened : bool + Whether the bound was tightened + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPtightenVarLbGlobal(self._scip, var.scip_var, lb, force, &infeasible, &tightened)) + return infeasible, tightened + + def chgVarLb(self, Variable var, lb): + """ + Changes the lower bound of the specified variable. + + Parameters + ---------- + var : Variable + variable to change bound of + lb : float or None + new lower bound (set to None for -infinity) + + """ + if lb is None: + lb = -SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarLb(self._scip, var.scip_var, lb)) + + def chgVarUb(self, Variable var, ub): + """Changes the upper bound of the specified variable. + + Parameters + ---------- + var : Variable + variable to change bound of + lb : float or None + new upper bound (set to None for +infinity) + + """ + if ub is None: + ub = SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarUb(self._scip, var.scip_var, ub)) + + def chgVarLbGlobal(self, Variable var, lb): + """Changes the global lower bound of the specified variable. + + Parameters + ---------- + var : Variable + variable to change bound of + lb : float or None + new lower bound (set to None for -infinity) + + """ + if lb is None: + lb = -SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarLbGlobal(self._scip, var.scip_var, lb)) + + def chgVarUbGlobal(self, Variable var, ub): + """Changes the global upper bound of the specified variable. + + Parameters + ---------- + var : Variable + variable to change bound of + lb : float or None + new upper bound (set to None for +infinity) + + """ + if ub is None: + ub = SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarUbGlobal(self._scip, var.scip_var, ub)) + + def chgVarLbNode(self, Node node, Variable var, lb): + """Changes the lower bound of the specified variable at the given node. + + Parameters + ---------- + node : Node + Node at which the variable bound will be changed + var : Variable + variable to change bound of + lb : float or None + new lower bound (set to None for -infinity) + + """ + + if lb is None: + lb = -SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarLbNode(self._scip, node.scip_node, var.scip_var, lb)) + + def chgVarUbNode(self, Node node, Variable var, ub): + """Changes the upper bound of the specified variable at the given node. + + Parameters + ---------- + node : Node + Node at which the variable bound will be changed + var : Variable + variable to change bound of + lb : float or None + new upper bound (set to None for +infinity) + + """ + if ub is None: + ub = SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarUbNode(self._scip, node.scip_node, var.scip_var, ub)) + + def getVarDict(self, transformed=False): + """ + Gets dictionary with variables names as keys and current variable values as items. + + Parameters + ---------- + transformed : bool, optional + Get transformed variables instead of original (Default value = False) + + Returns + ------- + dict of str to float + + """ + var_dict = {} + for var in self.getVars(transformed=transformed): + var_dict[var.name] = self.getVal(var) + return var_dict + + def updateNodeLowerbound(self, Node node, lb): + """ + If given value is larger than the node's lower bound (in transformed problem), + sets the node's lower bound to the new value. + + Parameters + ---------- + node : Node + the node to update + lb : float + new bound (if greater) for the node + + """ + PY_SCIP_CALL(SCIPupdateNodeLowerbound(self._scip, node.scip_node, lb)) + + # LP Methods + def getLPSolstat(self): + """ + Gets solution status of current LP. + + Returns + ------- + SCIP_LPSOLSTAT + + """ + return SCIPgetLPSolstat(self._scip) + + def getLPObjVal(self): + """ + Gets objective value of current LP (which is the sum of column and loose objective value). + + Returns + ------- + float + + """ + + return SCIPgetLPObjval(self._scip) + + def getLPColsData(self): + """ + Retrieve current LP columns. + + Returns + ------- + list of Column + + """ + cdef SCIP_COL** cols + cdef int ncols + cdef int i + + PY_SCIP_CALL(SCIPgetLPColsData(self._scip, &cols, &ncols)) + + return [Column.create(cols[i]) for i in range(ncols)] + + def getLPRowsData(self): + """ + Retrieve current LP rows. + + Returns + ------- + list of Row + + """ + cdef SCIP_ROW** rows + cdef int nrows + cdef int i + + PY_SCIP_CALL(SCIPgetLPRowsData(self._scip, &rows, &nrows)) + + return [Row.create(rows[i]) for i in range(nrows)] + + def getLPBInvRow(self, row): + """ + Gets a row from the inverse basis matrix B^-1 + + Parameters + ---------- + row : int + The row index of the inverse basis matrix + + Returns + ------- + list of float + + """ + # TODO: sparsity information + cdef int nrows = SCIPgetNLPRows(self._scip) + cdef SCIP_Real* coefs = malloc(nrows * sizeof(SCIP_Real)) + cdef int i + + PY_SCIP_CALL(SCIPgetLPBInvRow(self._scip, row, coefs, NULL, NULL)) + result = [coefs[i] for i in range(nrows)] + free(coefs) + + return result + + def getLPBInvARow(self, row): + """ + Gets a row from B^-1 * A. + + Parameters + ---------- + row : int + The row index of the inverse basis matrix multiplied by the coefficient matrix + + Returns + ------- + list of float + + """ + # TODO: sparsity information + cdef int ncols = SCIPgetNLPCols(self._scip) + cdef SCIP_Real* coefs = malloc(ncols * sizeof(SCIP_Real)) + cdef int i + + PY_SCIP_CALL(SCIPgetLPBInvARow(self._scip, row, NULL, coefs, NULL, NULL)) + result = [coefs[i] for i in range(ncols)] + free(coefs) + + return result + + # LP Col Methods + def getColRedCost(self, Column col): + """ + Gets the reduced cost of the column in the current LP. + + Parameters + ---------- + col : Column + + Returns + ------- + float + + """ + return SCIPgetColRedcost(self._scip, col.scip_col) + + #TODO: documentation!! + # LP Row Methods + def createEmptyRowSepa(self, Sepa sepa, name="row", lhs = 0.0, rhs = None, local = True, modifiable = False, removable = True): + """ + Creates and captures an LP row without any coefficients from a separator. + + Parameters + ---------- + sepa : Sepa + separator that creates the row + name : str, optional + name of row (Default value = "row") + lhs : float or None, optional + left hand side of row (Default value = 0) + rhs : float or None, optional + right hand side of row (Default value = None) + local : bool, optional + is row only valid locally? (Default value = True) + modifiable : bool, optional + is row modifiable during node processing (subject to column generation)? (Default value = False) + removable : bool, optional + should the row be removed from the LP due to aging or cleanup? (Default value = True) + + Returns + ------- + Row + + """ + cdef SCIP_ROW* row + lhs = -SCIPinfinity(self._scip) if lhs is None else lhs + rhs = SCIPinfinity(self._scip) if rhs is None else rhs + scip_sepa = SCIPfindSepa(self._scip, str_conversion(sepa.name)) + PY_SCIP_CALL(SCIPcreateEmptyRowSepa(self._scip, &row, scip_sepa, str_conversion(name), lhs, rhs, local, modifiable, removable)) + PyRow = Row.create(row) + return PyRow + + def createEmptyRowUnspec(self, name="row", lhs = 0.0, rhs = None, local = True, modifiable = False, removable = True): + """ + Creates and captures an LP row without any coefficients from an unspecified source. + + Parameters + ---------- + name : str, optional + name of row (Default value = "row") + lhs : float or None, optional + left hand side of row (Default value = 0) + rhs : float or None, optional + right hand side of row (Default value = None) + local : bool, optional + is row only valid locally? (Default value = True) + modifiable : bool, optional + is row modifiable during node processing (subject to column generation)? (Default value = False) + removable : bool, optional + should the row be removed from the LP due to aging or cleanup? (Default value = True) + + Returns + ------- + Row + + """ + cdef SCIP_ROW* row + lhs = -SCIPinfinity(self._scip) if lhs is None else lhs + rhs = SCIPinfinity(self._scip) if rhs is None else rhs + PY_SCIP_CALL(SCIPcreateEmptyRowUnspec(self._scip, &row, str_conversion(name), lhs, rhs, local, modifiable, removable)) + PyRow = Row.create(row) + return PyRow + + def getRowActivity(self, Row row): + """ + Returns the activity of a row in the last LP or pseudo solution. + + Parameters + ---------- + row : Row + + Returns + ------- + float + + """ + return SCIPgetRowActivity(self._scip, row.scip_row) + + def getRowLPActivity(self, Row row): + """ + Returns the activity of a row in the last LP solution. + + Parameters + ---------- + row : Row + + Returns + ------- + float + + """ + return SCIPgetRowLPActivity(self._scip, row.scip_row) + + # TODO: do we need this? (also do we need release var??) + def releaseRow(self, Row row not None): + """ + Decreases usage counter of LP row, and frees memory if necessary. + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPreleaseRow(self._scip, &row.scip_row)) + + def cacheRowExtensions(self, Row row not None): + """ + Informs row that all subsequent additions of variables to the row + should be cached and not directly applied; + after all additions were applied, flushRowExtensions() must be called; + while the caching of row extensions is activated, information methods of the + row give invalid results; caching should be used, if a row is build with addVarToRow() + calls variable by variable to increase the performance. + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPcacheRowExtensions(self._scip, row.scip_row)) + + def flushRowExtensions(self, Row row not None): + """ + Flushes all cached row extensions after a call of cacheRowExtensions() + and merges coefficients with equal columns into a single coefficient + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPflushRowExtensions(self._scip, row.scip_row)) + + def addVarToRow(self, Row row not None, Variable var not None, value): + """ + Resolves variable to columns and adds them with the coefficient to the row. + + Parameters + ---------- + row : Row + Row in which the variable will be added + var : Variable + Variable which will be added to the row + value : float + Coefficient on the variable when placed in the row + + """ + PY_SCIP_CALL(SCIPaddVarToRow(self._scip, row.scip_row, var.scip_var, value)) + + def printRow(self, Row row not None): + """ + Prints row. + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPprintRow(self._scip, row.scip_row, NULL)) + + def getRowNumIntCols(self, Row row): + """ + Returns number of intergal columns in the row. + + Parameters + ---------- + row : Row + + Returns + ------- + int + + """ + return SCIPgetRowNumIntCols(self._scip, row.scip_row) + + def getRowObjParallelism(self, Row row): + """ + Returns 1 if the row is parallel, and 0 if orthogonal. + + Parameters + ---------- + row : Row + + Returns + ------- + float + + """ + return SCIPgetRowObjParallelism(self._scip, row.scip_row) + + def getRowParallelism(self, Row row1, Row row2, orthofunc=101): + """ + Returns the degree of parallelism between hyplerplanes. 1 if perfectly parallel, 0 if orthogonal. + For two row vectors v, w the parallelism is calculated as: abs(v*w)/(abs(v)*abs(w)). + 101 in this case is an 'e' (euclidean) in ASCII. The other acceptable input is 100 (d for discrete). + + Parameters + ---------- + row1 : Row + row2 : Row + orthofunc : int, optional + 101 (default) is an 'e' (euclidean) in ASCII. Alternate value is 100 (d for discrete) + + Returns + ------- + float + + """ + return SCIProwGetParallelism(row1.scip_row, row2.scip_row, orthofunc) + + def getRowDualSol(self, Row row): + """ + Gets the dual LP solution of a row. + + Parameters + ---------- + row : Row + + Returns + ------- + float + + """ + return SCIProwGetDualsol(row.scip_row) + + # Cutting Plane Methods + def addPoolCut(self, Row row not None): + """ + If not already existing, adds row to global cut pool. + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPaddPoolCut(self._scip, row.scip_row)) + + def getCutEfficacy(self, Row cut not None, Solution sol = None): + """ + Returns efficacy of the cut with respect to the given primal solution or the + current LP solution: e = -feasibility/norm + + Parameters + ---------- + cut : Row + sol : Solution or None, optional + + Returns + ------- + float + + """ + return SCIPgetCutEfficacy(self._scip, NULL if sol is None else sol.sol, cut.scip_row) + + def isCutEfficacious(self, Row cut not None, Solution sol = None): + """ + Returns whether the cut's efficacy with respect to the given primal solution or the + current LP solution is greater than the minimal cut efficacy. + + Parameters + ---------- + cut : Row + sol : Solution or None, optional + + Returns + ------- + float + + """ + return SCIPisCutEfficacious(self._scip, NULL if sol is None else sol.sol, cut.scip_row) + + def getCutLPSolCutoffDistance(self, Row cut not None, Solution sol not None): + """ + Returns row's cutoff distance in the direction of the given primal solution. + + Parameters + ---------- + cut : Row + sol : Solution + + Returns + ------- + float + + """ + return SCIPgetCutLPSolCutoffDistance(self._scip, sol.sol, cut.scip_row) + + def addCut(self, Row cut not None, forcecut = False): + """ + Adds cut to separation storage and returns whether cut has been detected to be infeasible for local bounds. + + Parameters + ---------- + cut : Row + The cut that will be added + forcecut : bool, optional + Whether the cut should be forced or not, i.e., selected no matter what + + Returns + ------- + infeasible : bool + Whether the cut has been detected to be infeasible from local bounds + + """ + cdef SCIP_Bool infeasible + PY_SCIP_CALL(SCIPaddRow(self._scip, cut.scip_row, forcecut, &infeasible)) + return infeasible + + def _createConsLinear(self, ExprCons lincons, **kwargs): + """ + The function for creating a linear constraint, but not adding it to the Model. + Please do not use this function directly, but rather use createConsFromExpr + + Parameters + ---------- + lincons : ExprCons + kwargs : dict, optional + + Returns + ------- + Constraint + + """ + assert isinstance(lincons, ExprCons), "given constraint is not ExprCons but %s" % lincons.__class__.__name__ + + assert lincons.expr.degree() <= 1, "given constraint is not linear, degree == %d" % lincons.expr.degree() + terms = lincons.expr.terms + + cdef int nvars = len(terms.items()) + cdef SCIP_VAR** vars_array = malloc(nvars * sizeof(SCIP_VAR*)) + cdef SCIP_Real* coeffs_array = malloc(nvars * sizeof(SCIP_Real)) + cdef SCIP_CONS* scip_cons + cdef SCIP_Real coeff + cdef int i + cdef _VarArray wrapper + + for i, (key, coeff) in enumerate(terms.items()): + wrapper = _VarArray(key[0]) + vars_array[i] = wrapper.ptr[0] + coeffs_array[i] = coeff + + PY_SCIP_CALL(SCIPcreateConsLinear( + self._scip, &scip_cons, str_conversion(kwargs['name']), nvars, vars_array, coeffs_array, + kwargs['lhs'], kwargs['rhs'], kwargs['initial'], + kwargs['separate'], kwargs['enforce'], kwargs['check'], + kwargs['propagate'], kwargs['local'], kwargs['modifiable'], + kwargs['dynamic'], kwargs['removable'], kwargs['stickingatnode'])) + + PyCons = Constraint.create(scip_cons) + + free(vars_array) + free(coeffs_array) + + return PyCons + + def _createConsQuadratic(self, ExprCons quadcons, **kwargs): + """ + The function for creating a quadratic constraint, but not adding it to the Model. + Please do not use this function directly, but rather use createConsFromExpr + + Parameters + ---------- + quadcons : ExprCons + kwargs : dict, optional + + Returns + ------- + Constraint + + """ + terms = quadcons.expr.terms + assert quadcons.expr.degree() <= 2, "given constraint is not quadratic, degree == %d" % quadcons.expr.degree() + + cdef SCIP_CONS* scip_cons + cdef SCIP_EXPR* prodexpr + cdef _VarArray wrapper + PY_SCIP_CALL(SCIPcreateConsQuadraticNonlinear( + self._scip, &scip_cons, str_conversion(kwargs['name']), + 0, NULL, NULL, # linear + 0, NULL, NULL, NULL, # quadratc + kwargs['lhs'], kwargs['rhs'], + kwargs['initial'], kwargs['separate'], kwargs['enforce'], + kwargs['check'], kwargs['propagate'], kwargs['local'], + kwargs['modifiable'], kwargs['dynamic'], kwargs['removable'])) + + for v, c in terms.items(): + if len(v) == 1: # linear + wrapper = _VarArray(v[0]) + PY_SCIP_CALL(SCIPaddLinearVarNonlinear(self._scip, scip_cons, wrapper.ptr[0], c)) + else: # nonlinear + assert len(v) == 2, 'term length must be 1 or 2 but it is %s' % len(v) + + varexprs = malloc(2 * sizeof(SCIP_EXPR*)) + wrapper = _VarArray(v[0]) + PY_SCIP_CALL( SCIPcreateExprVar(self._scip, &varexprs[0], wrapper.ptr[0], NULL, NULL) ) + wrapper = _VarArray(v[1]) + PY_SCIP_CALL( SCIPcreateExprVar(self._scip, &varexprs[1], wrapper.ptr[0], NULL, NULL) ) + PY_SCIP_CALL( SCIPcreateExprProduct(self._scip, &prodexpr, 2, varexprs, 1.0, NULL, NULL) ) + + PY_SCIP_CALL( SCIPaddExprNonlinear(self._scip, scip_cons, prodexpr, c) ) + + PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &prodexpr) ) + PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &varexprs[1]) ) + PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &varexprs[0]) ) + free(varexprs) + + PyCons = Constraint.create(scip_cons) + + return PyCons + + def _createConsNonlinear(self, cons, **kwargs): + """ + The function for creating a non-linear constraint, but not adding it to the Model. + Please do not use this function directly, but rather use createConsFromExpr + + Parameters + ---------- + cons : ExprCons + kwargs : dict, optional + + Returns + ------- + Constraint + + """ + cdef SCIP_EXPR* expr + cdef SCIP_EXPR** varexprs + cdef SCIP_EXPR** monomials + cdef SCIP_CONS* scip_cons + cdef _VarArray wrapper + cdef int* idxs + cdef int i + cdef int j + + terms = cons.expr.terms + + # collect variables + variables = {i: [var for var in term] for i, term in enumerate(terms)} + + # create monomials for terms + monomials = malloc(len(terms) * sizeof(SCIP_EXPR*)) + termcoefs = malloc(len(terms) * sizeof(SCIP_Real)) + for i, (term, coef) in enumerate(terms.items()): + wrapper = _VarArray(variables[i]) + + PY_SCIP_CALL( SCIPcreateExprMonomial(self._scip, &monomials[i], wrapper.size, wrapper.ptr, NULL, NULL, NULL) ) + termcoefs[i] = coef + + # create polynomial from monomials + PY_SCIP_CALL( SCIPcreateExprSum(self._scip, &expr, len(terms), monomials, termcoefs, 0.0, NULL, NULL)) + + # create nonlinear constraint for expr + PY_SCIP_CALL( SCIPcreateConsNonlinear( + self._scip, + &scip_cons, + str_conversion(kwargs['name']), + expr, + kwargs['lhs'], + kwargs['rhs'], + kwargs['initial'], + kwargs['separate'], + kwargs['enforce'], + kwargs['check'], + kwargs['propagate'], + kwargs['local'], + kwargs['modifiable'], + kwargs['dynamic'], + kwargs['removable']) ) + + PyCons = Constraint.create(scip_cons) + + PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &expr) ) + for i in range(len(terms)): + PY_SCIP_CALL(SCIPreleaseExpr(self._scip, &monomials[i])) + free(monomials) + free(termcoefs) + + return PyCons + + def _createConsGenNonlinear(self, cons, **kwargs): + """ + The function for creating a general non-linear constraint, but not adding it to the Model. + Please do not use this function directly, but rather use createConsFromExpr + + Parameters + ---------- + cons : ExprCons + kwargs : dict, optional + + Returns + ------- + Constraint + + """ + cdef SCIP_EXPR* scip_expr + cdef SCIP_CONS* scip_cons + cdef GenExpr expr = cons.expr + + # recursively create the SCIP expression tree from python's expression tree + scip_expr = expr.to_scip_expr(self._scip) + + # create nonlinear constraint for the expression root + PY_SCIP_CALL(SCIPcreateConsNonlinear( + self._scip, + &scip_cons, + str_conversion(kwargs["name"]), + scip_expr, + kwargs["lhs"], + kwargs["rhs"], + kwargs["initial"], + kwargs["separate"], + kwargs["enforce"], + kwargs["check"], + kwargs["propagate"], + kwargs["local"], + kwargs["modifiable"], + kwargs["dynamic"], + kwargs["removable"])) + + PY_SCIP_CALL(SCIPreleaseExpr(self._scip, &scip_expr)) + + return Constraint.create(scip_cons) + + def createConsFromExpr(self, cons, name='', initial=True, separate=True, + enforce=True, check=True, propagate=True, local=False, + modifiable=False, dynamic=False, removable=False, + stickingatnode=False): + """ + Create a linear or nonlinear constraint without adding it to the SCIP problem. + This is useful for creating disjunction constraints without also enforcing the individual constituents. + Currently, this can only be used as an argument to `.addConsElemDisjunction`. To add + an individual linear/nonlinear constraint, prefer `.addCons()`. + + Parameters + ---------- + cons : ExprCons + The expression constraint that is not yet an actual constraint + name : str, optional + the name of the constraint, generic name if empty (Default value = '') + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The created Constraint object. + + """ + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + kwargs = dict(name=name, initial=initial, separate=separate, + enforce=enforce, check=check, + propagate=propagate, local=local, + modifiable=modifiable, dynamic=dynamic, + removable=removable, + stickingatnode=stickingatnode + ) + + kwargs['lhs'] = -SCIPinfinity(self._scip) if cons._lhs is None else cons._lhs + kwargs['rhs'] = SCIPinfinity(self._scip) if cons._rhs is None else cons._rhs + + deg = cons.expr.degree() + if deg <= 1: + return self._createConsLinear(cons, **kwargs) + elif deg <= 2: + return self._createConsQuadratic(cons, **kwargs) + elif deg == INFINITY: # general nonlinear + return self._createConsGenNonlinear(cons, **kwargs) + else: + return self._createConsNonlinear(cons, **kwargs) + + # Constraint functions + def addCons(self, cons, name='', initial=True, separate=True, + enforce=True, check=True, propagate=True, local=False, + modifiable=False, dynamic=False, removable=False, + stickingatnode=False): + """ + Add a linear or nonlinear constraint. + + Parameters + ---------- + cons : ExprCons + the constraint expression to add to the model (e.g., x + y <= 5) + name : str, optional + the name of the constraint, generic name if empty (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraints always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The created and added Constraint object. + + """ + assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ + + cdef SCIP_CONS* scip_cons + + kwargs = dict(name=name, initial=initial, separate=separate, + enforce=enforce, check=check, + propagate=propagate, local=local, + modifiable=modifiable, dynamic=dynamic, + removable=removable, + stickingatnode=stickingatnode + ) + # we have to pass this back to a SCIP_CONS* + # object to create a new python constraint & handle constraint release + # correctly. Otherwise, segfaults when trying to query information + # about the created constraint later. + pycons_initial = self.createConsFromExpr(cons, **kwargs) + scip_cons = (pycons_initial).scip_cons + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pycons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pycons + + def addConsDisjunction(self, conss, name = '', initial = True, + relaxcons = None, enforce=True, check =True, + local=False, modifiable = False, dynamic = False): + """ + Add a disjunction constraint. + + Parameters + ---------- + conss : iterable of ExprCons + An iterable of constraint objects to be included initially in the disjunction. + Currently, these must be expressions. + name : str, optional + the name of the disjunction constraint. + initial : bool, optional + should the LP relaxation of disjunction constraint be in the initial LP? (Default value = True) + relaxcons : None, optional + a conjunction constraint containing the linear relaxation of the disjunction constraint, or None. + NOT YET SUPPORTED. (Default value = None) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + + Returns + ------- + Constraint + The created disjunction constraint + + """ + cdef SCIP_EXPR* scip_expr + cdef SCIP_CONS* scip_cons + cdef SCIP_CONS* disj_cons + cdef int n_conss + cdef int i + + def ensure_iterable(elem, length): + if isinstance(elem, Iterable): + return elem + else: + return list(repeat(elem, length)) + assert isinstance(conss, Iterable), "Given constraint list is not iterable" + + conss = list(conss) + n_conss = len(conss) + + PY_SCIP_CALL(SCIPcreateConsDisjunction( + self._scip, &disj_cons, str_conversion(name), 0, &scip_cons, NULL, + initial, enforce, check, local, modifiable, dynamic + )) + + + # TODO add constraints to disjunction + for i, cons in enumerate(conss): + pycons = self.createConsFromExpr(cons, name=name, initial = initial, + enforce=enforce, check=check, + local=local, modifiable=modifiable, dynamic=dynamic + ) + PY_SCIP_CALL(SCIPaddConsElemDisjunction(self._scip,disj_cons, (pycons).scip_cons)) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &(pycons).scip_cons)) + PY_SCIP_CALL(SCIPaddCons(self._scip, disj_cons)) + PyCons = self._getOrCreateCons(disj_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &disj_cons)) + + return PyCons + + def addConsElemDisjunction(self, Constraint disj_cons, Constraint cons): + """ + Appends a constraint to a disjunction. + + Parameters + ---------- + disj_cons : Constraint + the disjunction constraint to append to. + cons : Constraint + the constraint to append + + Returns + ------- + disj_cons : Constraint + The disjunction constraint with `cons` appended. + + """ + PY_SCIP_CALL(SCIPaddConsElemDisjunction(self._scip, (disj_cons).scip_cons, (cons).scip_cons)) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &(cons).scip_cons)) + return disj_cons + + def addMatrixConsDisjunction(self, conss: Iterable, + name: Union[str, np.ndarray] = '', initial: Union[bool, np.ndarray] = True, + relaxcons=None, enforce: Union[bool, np.ndarray] = True, + check: Union[bool, np.ndarray] = True, local: Union[bool, np.ndarray] = False, + modifiable: Union[bool, np.ndarray] = False, + dynamic: Union[bool, np.ndarray] = False): + """ + Add an elementwise disjunction of matrix constraint expressions. + + Given an iterable of ``MatrixExprCons`` with a common shape, creates one + disjunction per index: for each position ``idx``, the resulting + disjunction enforces that at least one of ``conss[k][idx]`` holds. + ``ExprCons`` entries are broadcast to every position. If every entry in + ``conss`` is a plain ``ExprCons``, the call is forwarded to + :meth:`addConsDisjunction` and returns a single ``Constraint``. + + Note: this method accepts constraint *expressions* (e.g., ``A @ x <= b``), + not ``MatrixConstraint``/``Constraint`` objects returned by + :meth:`addMatrixCons`/:meth:`addCons`. + + Parameters + ---------- + conss : iterable of MatrixExprCons or ExprCons + Constraint expressions to combine elementwise into disjunctions. All + ``MatrixExprCons`` entries must share the same shape. + name : str or np.ndarray, optional + Name of the disjunction constraints. (Default value = "") + initial : bool or np.ndarray, optional + Should the LP relaxation be in the initial LP? (Default value = True) + relaxcons : None, optional + NOT YET SUPPORTED. (Default value = None) + enforce : bool or np.ndarray, optional + Should the constraint be enforced during node processing? (Default value = True) + check : bool or np.ndarray, optional + Should the constraint be checked for feasibility? (Default value = True) + local : bool or np.ndarray, optional + Is the constraint only valid locally? (Default value = False) + modifiable : bool or np.ndarray, optional + Is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool or np.ndarray, optional + Is the constraint subject to aging? (Default value = False) + + Returns + ------- + MatrixConstraint or Constraint + A ``MatrixConstraint`` of the common shape when any entry of + ``conss`` is a ``MatrixExprCons``; otherwise a single + ``Constraint`` from the scalar fallback. + """ + if not isinstance(conss, Iterable): + raise TypeError(f"given constraint list is not iterable, but got {type(conss).__name__}") + conss = list(conss) + + for cons in conss: + if not isinstance(cons, (ExprCons, MatrixExprCons)): + raise TypeError( + "element of conss is not MatrixExprCons nor ExprCons but %s" + % cons.__class__.__name__ + ) + + if all(isinstance(cons, ExprCons) for cons in conss): + return self.addConsDisjunction( + conss, name=name, initial=initial, relaxcons=relaxcons, + enforce=enforce, check=check, local=local, + modifiable=modifiable, dynamic=dynamic, + ) + + shape = None + for cons in conss: + if isinstance(cons, MatrixExprCons): + if shape is None: + shape = cons.shape + elif cons.shape != shape: + raise ValueError( + "All MatrixExprCons in conss must have the same shape, " + "got %s and %s" % (shape, cons.shape) + ) + + for arr in (name, initial, enforce, check, local, modifiable, dynamic): + if isinstance(arr, np.ndarray): + assert arr.shape == shape + + if isinstance(name, str): + matrix_names = np.full(shape, name, dtype=object) + if name != "": + for idx in np.ndindex(shape): + matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" + else: + matrix_names = name + + matrix_initial = initial if isinstance(initial, np.ndarray) else np.full(shape, initial, dtype=bool) + matrix_enforce = enforce if isinstance(enforce, np.ndarray) else np.full(shape, enforce, dtype=bool) + matrix_check = check if isinstance(check, np.ndarray) else np.full(shape, check, dtype=bool) + matrix_local = local if isinstance(local, np.ndarray) else np.full(shape, local, dtype=bool) + matrix_modifiable = modifiable if isinstance(modifiable, np.ndarray) else np.full(shape, modifiable, dtype=bool) + matrix_dynamic = dynamic if isinstance(dynamic, np.ndarray) else np.full(shape, dynamic, dtype=bool) + + matrix_cons = np.empty(shape, dtype=object) + for idx in np.ndindex(shape): + elem_conss = [ + cons[idx] if isinstance(cons, MatrixExprCons) else cons + for cons in conss + ] + matrix_cons[idx] = self.addConsDisjunction( + elem_conss, + name=matrix_names[idx], + initial=matrix_initial[idx], + relaxcons=relaxcons, + enforce=matrix_enforce[idx], + check=matrix_check[idx], + local=matrix_local[idx], + modifiable=matrix_modifiable[idx], + dynamic=matrix_dynamic[idx], + ) + + return matrix_cons.view(MatrixConstraint) + + def getConsVals(self, Constraint constraint): + """ + Returns the value array of an arbitrary SCIP constraint that can be represented as a single linear constraint. + + Parameters + ---------- + constraint : Constraint + Constraint to get the values from. + + Returns + ------- + list of float + + """ + cdef SCIP_Real* _vals + cdef int nvars + cdef SCIP_Bool success + cdef int i + + nvars = self.getConsNVars(constraint) + _vals = malloc(nvars * sizeof(SCIP_Real)) + PY_SCIP_CALL(SCIPgetConsVals(self._scip, constraint.scip_cons, _vals, nvars, &success)) + + if not success: + free(_vals) + return None + + vals = [_vals[i] for i in range(nvars)] + free(_vals) + return vals + + def getNVarsAnd(self, Constraint and_cons): + """ + Gets number of variables in and constraint. + + Parameters + ---------- + and_cons : Constraint + AND constraint to get the number of variables from. + + Returns + ------- + int + + """ + + return SCIPgetNVarsAnd(self._scip, and_cons.scip_cons) + + def getVarsAnd(self, Constraint and_cons): + """ + Gets variables in AND constraint. + + Parameters + ---------- + and_cons : Constraint + AND Constraint to get the variables from. + + Returns + ------- + list of Variable + + """ + + cdef SCIP_VAR** _vars + cdef int nvars + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(and_cons.scip_cons))).decode('UTF-8') + assert constype == 'and', "The constraint handler %s does not have this functionality." % constype + + nvars = SCIPgetNVarsAnd(self._scip, and_cons.scip_cons) + _vars = SCIPgetVarsAnd(self._scip, and_cons.scip_cons) + + vars = [] + for i in range(nvars): + vars.append(self._getOrCreateVar(_vars[i])) + + return vars + + def getResultantAnd(self, Constraint and_cons): + """ + Gets the resultant variable in And constraint. + + Parameters + ---------- + and_cons : Constraint + Constraint to get the resultant variable from. + + Returns + ------- + Variable + + """ + cdef SCIP_VAR* _resultant + + _resultant = SCIPgetResultantAnd(self._scip, and_cons.scip_cons) + return self._getOrCreateVar(_resultant) + + def isAndConsSorted(self, Constraint and_cons): + """ + Returns if the variables of the AND-constraint are sorted with respect to their indices. + + Parameters + ---------- + and_cons : Constraint + Constraint to check. + + Returns + ------- + bool + + """ + + return SCIPisAndConsSorted(self._scip, and_cons.scip_cons) + + def sortAndCons(self, Constraint and_cons): + """ + Sorts the variables of the AND-constraint with respect to their indices. + + Parameters + ---------- + and_cons : Constraint + Constraint to sort. + + """ + + PY_SCIP_CALL(SCIPsortAndCons(self._scip, and_cons.scip_cons)) + + def getNVarsLogicor(self, Constraint logicor_cons): + """ + Gets number of variables in logicor constraint. + + Parameters + ---------- + logicor_cons : Constraint + logicor constraint to get the number of variables from. + + Returns + ------- + int + + """ + + return SCIPgetNVarsLogicor(self._scip, logicor_cons.scip_cons) + + def getVarsLogicor(self, Constraint logicor_cons): + """ + Gets variables in logicor constraint. + + Parameters + ---------- + logicor_cons : Constraint + logicor constraint to get the variables from. + + Returns + ------- + list of Variable + + """ + + cdef SCIP_VAR** _vars + cdef int nvars + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(logicor_cons.scip_cons))).decode('UTF-8') + assert constype == 'logicor', "The constraint handler %s does not have this functionality." % constype + + nvars = SCIPgetNVarsLogicor(self._scip, logicor_cons.scip_cons) + _vars = SCIPgetVarsLogicor(self._scip, logicor_cons.scip_cons) + + vars = [] + for i in range(nvars): + vars.append(self._getOrCreateVar(_vars[i])) + + return vars + + def addCoefLogicor(self, Constraint logicor_cons, Variable var): + """ + Adds a variable to a logicor constraint. + + Parameters + ---------- + logicor_cons : Constraint + logicor constraint to add the variable to. + var : Variable + BINARY variable to add. + + """ + + PY_SCIP_CALL(SCIPaddCoefLogicor(self._scip, logicor_cons.scip_cons, var.scip_var)) + + def getDualsolLogicor(self, Constraint logicor_cons): + """ + Gets the dual solution of a logicor constraint in the current LP. + + Parameters + ---------- + logicor_cons : Constraint + logicor constraint to get the dual solution from. + + Returns + ------- + float + Zero if presolve removed the transformed constraint. + + """ + cdef SCIP_CONS* transcons = self._getTransformedCons(logicor_cons, "logicor") + if transcons == NULL: + return 0.0 + + return SCIPgetDualsolLogicor(self._scip, transcons) + + def getDualfarkasLogicor(self, Constraint logicor_cons): + """ + Gets the dual Farkas value of a logicor constraint in the current infeasible LP. + + Parameters + ---------- + logicor_cons : Constraint + logicor constraint to get the dual Farkas value from. + + Returns + ------- + float + Zero if presolve removed the transformed constraint. + + """ + cdef SCIP_CONS* transcons = self._getTransformedCons(logicor_cons, "logicor") + if transcons == NULL: + return 0.0 + + return SCIPgetDualfarkasLogicor(self._scip, transcons) + + def addExprNonlinear(self, Constraint cons, expr, coef): + """ + Add coef*expr to nonlinear constraint. + + Parameters + ---------- + cons : Constraint + expr : Expr or GenExpr + coef : float + + """ + assert self.getStage() == 1, "addExprNonlinear cannot be called in stage %i." % self.getStage() + assert cons.isNonlinear(), "addExprNonlinear can only be called with nonlinear constraints." + + cdef Constraint temp_cons + cdef SCIP_EXPR* scip_expr + + temp_cons = self.addCons(expr <= 0) + scip_expr = SCIPgetExprNonlinear(temp_cons.scip_cons) + + PY_SCIP_CALL(SCIPaddExprNonlinear(self._scip, cons.scip_cons, scip_expr, coef)) + self.delCons(temp_cons) + + def addConsCoeff(self, Constraint cons, Variable var, coeff): + """ + Add coefficient to the constraint (if non-zero). + + Parameters + ---------- + cons : Constraint + Constraint to be changed + var : Variable + variable to be added + coeff : float + coefficient of new variable + + """ + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype == 'linear': + PY_SCIP_CALL(SCIPaddCoefLinear(self._scip, cons.scip_cons, var.scip_var, coeff)) + elif constype == 'knapsack': + PY_SCIP_CALL(SCIPaddCoefKnapsack(self._scip, cons.scip_cons, var.scip_var, coeff)) + else: + raise NotImplementedError("Adding coefficients to %s constraints is not implemented." % constype) + + def addConsNode(self, Node node, ExprCons cons, Node validnode=None, name='', + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=True, dynamic=False, removable=True, + stickingatnode=True): + """ + Add a constraint to the given node. + + Parameters + ---------- + node : Node + node at which the constraint will be added + cons : ExprCons + the constraint expression to add to the node (e.g., x + y <= 5) + validnode : Node or None, optional + more global node where cons is also valid. (Default=None) + name : str, optional + name of the constraint (Default value = '') + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = True) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = True) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added? (Default value = True) + + Returns + ------- + Constraint + The added Constraint object. + + """ + assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ + + cdef SCIP_CONS* scip_cons + + kwargs = dict(name=name, initial=initial, separate=separate, + enforce=enforce, check=check, propagate=propagate, + local=local, modifiable=False, dynamic=dynamic, + removable=removable, stickingatnode=stickingatnode) + pycons_initial = self.createConsFromExpr(cons, **kwargs) + scip_cons = (pycons_initial).scip_cons + + if isinstance(validnode, Node): + PY_SCIP_CALL(SCIPaddConsNode(self._scip, node.scip_node, scip_cons, validnode.scip_node)) + else: + PY_SCIP_CALL(SCIPaddConsNode(self._scip, node.scip_node, scip_cons, NULL)) + + pycons = Constraint.create(scip_cons) + pycons.data = (pycons_initial).data + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pycons + + def addConsLocal(self, ExprCons cons, Node validnode=None, name='', + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=True, dynamic=False, removable=True, + stickingatnode=True): + """ + Add a constraint to the current node. + + Parameters + ---------- + cons : ExprCons + the constraint expression to add to the current node (e.g., x + y <= 5) + validnode : Node or None, optional + more global node where cons is also valid. (Default=None) + name : str, optional + name of the constraint (Default value = '') + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = True) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = True) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added? (Default value = True) + + Returns + ------- + Constraint + The added Constraint object. + + """ + assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ + + cdef SCIP_CONS* scip_cons + + kwargs = dict(name=name, initial=initial, separate=separate, + enforce=enforce, check=check, propagate=propagate, + local=local, modifiable=False, dynamic=dynamic, + removable=removable, stickingatnode=stickingatnode) + pycons_initial = self.createConsFromExpr(cons, **kwargs) + scip_cons = (pycons_initial).scip_cons + + if isinstance(validnode, Node): + PY_SCIP_CALL(SCIPaddConsLocal(self._scip, scip_cons, validnode.scip_node)) + else: + PY_SCIP_CALL(SCIPaddConsLocal(self._scip, scip_cons, NULL)) + + pycons = Constraint.create(scip_cons) + pycons.data = (pycons_initial).data + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pycons + + def addConsLinear(self, vars, vals, lhs=None, rhs=None, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add a linear constraint lhs <= sum(vals[i] * vars[i]) <= rhs directly from + variables and coefficients, without building an expression. Faster than addCons + for building large models. + + Parameters + ---------- + vars : list of Variable + variables in the constraint + vals : list of float + coefficients of the variables + lhs : float or None, optional + left-hand side, -infinity if None (Default value = None) + rhs : float or None, optional + right-hand side, infinity if None (Default value = None) + name : str, optional + name of the constraint, generic name if empty (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created linear constraint + + """ + cdef int nvars = len(vars) + cdef int i + cdef SCIP_Real* vals_array + cdef SCIP_CONS* scip_cons + cdef _VarArray wrapper + + if nvars != len(vals): + raise ValueError("Number of variables and values must be the same.") + + if lhs is None: + lhs = -SCIPinfinity(self._scip) + if rhs is None: + rhs = SCIPinfinity(self._scip) + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + wrapper = _VarArray(vars) + vals_array = malloc(nvars * sizeof(SCIP_Real)) + for i in range(nvars): + vals_array[i] = vals[i] + + PY_SCIP_CALL(SCIPcreateConsLinear( + self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, vals_array, + lhs, rhs, initial, separate, enforce, check, propagate, local, modifiable, + dynamic, removable, stickingatnode)) + + free(vals_array) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsKnapsack(self, vars, weights, capacity, name="", + initial=True, separate=True, enforce=True, check=True, + modifiable=False, propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Parameters + ---------- + vars : list of Variable + list of variables to be included + weights : list of int + list of weights + capacity: int + capacity of the knapsack + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created knapsack constraint + """ + + cdef int nvars = len(vars) + cdef int i + cdef SCIP_Longint* weights_array = malloc(nvars * sizeof(SCIP_Real)) + cdef SCIP_CONS* scip_cons + cdef _VarArray wrapper + + assert nvars == len(weights), "Number of variables and weights must be the same." + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + wrapper = _VarArray(vars) + for i in range(nvars): + weights_array[i] = weights[i] + + PY_SCIP_CALL(SCIPcreateConsKnapsack( + self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, weights_array, + capacity, initial, separate, enforce, check, propagate, local, modifiable, + dynamic, removable, stickingatnode)) + + free(weights_array) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsCumulative(self, vars, durations, demands, capacity, name="", + initial=True, separate=True, enforce=True, check=True, + modifiable=False, propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add a cumulative constraint. + + A cumulative constraint models resource-constrained scheduling: given jobs + with start times, durations, and demands on a shared resource of fixed + capacity, it ensures that at every time point t the total demand of all + jobs active at t does not exceed the capacity. Job j is active at t if + start[j] <= t < start[j] + duration[j]. + + The start times are given as integer variables in `vars`. The `durations`, + `demands`, and `capacity` arguments must be fixed integers. End times are + implicit (start + duration); post separate constraints if explicit end + variables are needed. + + If you simply want the jobs to not overlap, set all durations to '1'. + + Parameters + ---------- + vars : list of Variable + list of integer variables corresponding to job start times + durations : list of int + list of durations, one for each job + demands : list of int + list of demands, one for each job + capacity : int + available cumulative capacity at any time point + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created cumulative constraint + """ + + cdef int nvars = len(vars) + cdef int i + cdef int* durations_array = malloc(nvars * sizeof(int)) + cdef int* demands_array = malloc(nvars * sizeof(int)) + cdef SCIP_CONS* scip_cons + cdef _VarArray wrapper + + assert nvars == len(durations) == len(demands), "Number of variables, durations, and demands must be the same." + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + wrapper = _VarArray(vars) + for i in range(nvars): + durations_array[i] = durations[i] + demands_array[i] = demands[i] + + PY_SCIP_CALL(SCIPcreateConsCumulative( + self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, durations_array, + demands_array, capacity, initial, separate, enforce, check, propagate, local, modifiable, + dynamic, removable, stickingatnode)) + + free(durations_array) + free(demands_array) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsSOS1(self, vars, weights=None, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add an SOS1 constraint. + + Parameters + ---------- + vars : list of Variable + list of variables to be included + weights : list of float or None, optional + list of weights (Default value = None) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created SOS1 constraint + + """ + cdef SCIP_CONS* scip_cons + cdef int nvars + cdef int i + cdef _VarArray wrapper + + PY_SCIP_CALL(SCIPcreateConsSOS1(self._scip, &scip_cons, str_conversion(name), 0, NULL, NULL, + initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + nvars = len(vars) + wrapper = _VarArray(vars) + if weights is None: + for i in range(nvars): + PY_SCIP_CALL(SCIPappendVarSOS1(self._scip, scip_cons, wrapper.ptr[i])) + else: + for i in range(nvars): + PY_SCIP_CALL(SCIPaddVarSOS1(self._scip, scip_cons, wrapper.ptr[i], weights[i])) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsSOS2(self, vars, weights=None, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add an SOS2 constraint. + + Parameters + ---------- + vars : list of Variable + list of variables to be included + weights : list of float or None, optional + list of weights (Default value = None) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created SOS2 constraint + + """ + cdef SCIP_CONS* scip_cons + cdef int nvars + cdef int i + cdef _VarArray wrapper + + PY_SCIP_CALL(SCIPcreateConsSOS2(self._scip, &scip_cons, str_conversion(name), 0, NULL, NULL, + initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + nvars = len(vars) + wrapper = _VarArray(vars) + if weights is None: + for i in range(nvars): + PY_SCIP_CALL(SCIPappendVarSOS2(self._scip, scip_cons, wrapper.ptr[i])) + else: + for i in range(nvars): + PY_SCIP_CALL(SCIPaddVarSOS2(self._scip, scip_cons, wrapper.ptr[i], weights[i])) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsAnd(self, vars, resvar, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add an AND-constraint. + + Parameters + ---------- + vars : list of Variable + list of BINARY variables to be included (operators) + resvar : Variable + BINARY variable (resultant) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created AND constraint + + """ + cdef int nvars = len(vars) + cdef SCIP_VAR** _vars + cdef SCIP_VAR* _resvar + cdef _VarArray resvar_wrapper = _VarArray(resvar) + cdef _VarArray vars_wrapper = _VarArray(vars) + cdef SCIP_CONS* scip_cons + cdef int i + + _resvar = resvar_wrapper.ptr[0] + _vars = vars_wrapper.ptr + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + PY_SCIP_CALL(SCIPcreateConsAnd(self._scip, &scip_cons, str_conversion(name), _resvar, nvars, _vars, + initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsOr(self, vars, resvar, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add an OR-constraint. + + Parameters + ---------- + vars : list of Variable + list of BINARY variables to be included (operators) + resvar : Variable + BINARY variable (resultant) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created OR constraint + + """ + cdef int nvars = len(vars) + cdef SCIP_VAR** _vars + cdef SCIP_VAR* _resvar + cdef _VarArray resvar_wrapper = _VarArray(resvar) + cdef _VarArray vars_wrapper = _VarArray(vars) + cdef SCIP_CONS* scip_cons + cdef int i + + _resvar = resvar_wrapper.ptr[0] + _vars = vars_wrapper.ptr + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + PY_SCIP_CALL(SCIPcreateConsOr(self._scip, &scip_cons, str_conversion(name), _resvar, nvars, _vars, + initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsXor(self, vars, rhsvar, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add a XOR-constraint. + + Parameters + ---------- + vars : list of Variable + list of binary variables to be included (operators) + rhsvar : bool + BOOLEAN value, explicit True, False or bool(obj) is needed (right-hand side) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created XOR constraint + + """ + assert type(rhsvar) is type(bool()), "Provide BOOLEAN value as rhsvar, you gave %s." % type(rhsvar) + + cdef int nvars = len(vars) + cdef SCIP_VAR** _vars + cdef SCIP_CONS* scip_cons + cdef int i + cdef _VarArray wrapper = _VarArray(vars) + + _vars = wrapper.ptr + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + PY_SCIP_CALL(SCIPcreateConsXor(self._scip, &scip_cons, str_conversion(name), rhsvar, nvars, _vars, + initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsLogicor(self, vars, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, modifiable=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add a logicor constraint: at least one of the given binary variables must be one. + + Parameters + ---------- + vars : list of Variable + list of BINARY variables, at least one of which must take value one + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created logicor constraint + + """ + cdef int nvars = len(vars) + cdef SCIP_VAR** _vars + cdef _VarArray vars_wrapper = _VarArray(vars) + cdef SCIP_CONS* scip_cons + + _vars = vars_wrapper.ptr + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + PY_SCIP_CALL(SCIPcreateConsLogicor(self._scip, &scip_cons, str_conversion(name), nvars, _vars, + initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsCardinality(self, consvars, cardval, indvars=None, weights=None, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """ + Add a cardinality constraint that allows at most 'cardval' many nonzero variables. + + Parameters + ---------- + consvars : list of Variable + list of variables to be included + cardval : int + nonnegative integer + indvars : list of Variable or None, optional + indicator variables indicating which variables may be treated as nonzero in + cardinality constraint, or None if new indicator variables should be + introduced automatically (Default value = None) + weights : list of float or None, optional + weights determining the variable order, or None if variables should be ordered + in the same way they were added to the constraint (Default value = None) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created Cardinality constraint + + """ + cdef SCIP_VAR* indvar + cdef SCIP_CONS* scip_cons + cdef int i + cdef _VarArray v_wrapper + cdef _VarArray indvar_wrapper + cdef SCIP_VAR* scip_var + + PY_SCIP_CALL(SCIPcreateConsCardinality(self._scip, &scip_cons, str_conversion(name), 0, NULL, cardval, NULL, NULL, + initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) + + # circumvent an annoying bug in SCIP 4.0.0 that does not allow uninitialized weights + if weights is None: + weights = list(range(1, len(consvars) + 1)) + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + v_wrapper = _VarArray(consvars) + for i, v in enumerate(consvars): + scip_var = v_wrapper.ptr[i] + if indvars: + indvar_wrapper = _VarArray(indvars[i]) + indvar = indvar_wrapper.ptr[0] + else: + indvar = NULL + + if weights is None: + PY_SCIP_CALL(SCIPappendVarCardinality(self._scip, scip_cons, scip_var, indvar)) + else: + PY_SCIP_CALL(SCIPaddVarCardinality(self._scip, scip_cons, scip_var, indvar, weights[i])) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addConsIndicator(self, cons, binvar=None, activeone=True, name="", + initial=True, separate=True, enforce=True, check=True, + propagate=True, local=False, dynamic=False, + removable=False, stickingatnode=False): + """Add an indicator constraint for the linear inequality `cons`. + + The `binvar` argument models the redundancy of the linear constraint. A solution for which + `binvar` is 1 must satisfy the constraint. + + Parameters + ---------- + cons : ExprCons + a linear inequality + binvar : Variable, optional + binary indicator variable, or None if it should be created (Default value = None) + activeone : bool, optional + constraint should active if binvar is 1 (0 if activeone = False) + name : str, optional + name of the constraint (Default value = "") + initial : bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool, optional + is the constraint only valid locally? (Default value = False) + dynamic : bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool, optional + should the constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + Constraint + The newly created Indicator constraint + + """ + cdef SCIP_VAR* _binVar + cdef SCIP_CONS* scip_cons + cdef SCIP_Real coeff + cdef _VarArray wrapper + + assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ + + if cons._lhs is not None and cons._rhs is not None: + raise ValueError("expected inequality that has either only a left or right hand side") + + if name == '': + name = 'c'+str(SCIPgetNConss(self._scip)+1) + + if cons.expr.degree() > 1: + raise ValueError("expected linear inequality, expression has degree %d" % cons.expr.degree()) + + if cons._rhs is not None: + rhs = cons._rhs + negate = False + else: + rhs = -cons._lhs + negate = True + + if binvar is not None: + wrapper = _VarArray(binvar) + _binVar = wrapper.ptr[0] + if not activeone: + PY_SCIP_CALL(SCIPgetNegatedVar(self._scip, _binVar, &_binVar)) + else: + _binVar = NULL + + PY_SCIP_CALL(SCIPcreateConsIndicator(self._scip, &scip_cons, str_conversion(name), _binVar, 0, NULL, NULL, rhs, + initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) + terms = cons.expr.terms + + for key, coeff in terms.items(): + if negate: + coeff = -coeff + wrapper = _VarArray(key[0]) + PY_SCIP_CALL(SCIPaddVarIndicator(self._scip, scip_cons, wrapper.ptr[0], coeff)) + + PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) + pyCons = self._getOrCreateCons(scip_cons) + + PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) + + return pyCons + + def addMatrixConsIndicator(self, cons: Union[ExprCons, MatrixExprCons], binvar: Union[Variable, MatrixVariable] = None, + activeone: Union[bool, np.ndarray] = True, name: Union[str, np.ndarray] = "", + initial: Union[bool, np.ndarray] = True, separate: Union[bool, np.ndarray] = True, + enforce: Union[bool, np.ndarray] = True, check: Union[bool, np.ndarray] = True, + propagate: Union[bool, np.ndarray] = True, local: Union[bool, np.ndarray] = False, + dynamic: Union[bool, np.ndarray] = False, removable: Union[bool, np.ndarray] = False, + stickingatnode: Union[bool, np.ndarray] = False) -> MatrixConstraint: + """Add an indicator matrix constraint for the linear inequality `cons`. + + The `binvar` argument models the redundancy of the linear constraint. A solution + for which `binvar` is 1 must satisfy the constraint. + + Parameters + ---------- + cons : ExprCons or MatrixExprCons + a linear inequality + binvar : Variable or MatrixVariable, optional + binary indicator variable / matrix variable, or None if it should be created. (Default value = None) + activeone : bool or np.ndarray, optional + the matrix constraint should be active if binvar is 1 (0 if activeone = False). + name : str or np.ndarray, optional + name of the matrix constraint. (Default value = "") + initial : bool or np.ndarray, optional + should the LP relaxation of matrix constraint be in the initial LP? (Default value = True) + separate : bool or np.ndarray, optional + should the matrix constraint be separated during LP processing? (Default value = True) + enforce : bool or np.ndarray, optional + should the matrix constraint be enforced during node processing? (Default value = True) + check : bool or np.ndarray, optional + should the matrix constraint be checked for feasibility? (Default value = True) + propagate : bool or np.ndarray, optional + should the matrix constraint be propagated during node processing? (Default value = True) + local : bool or np.ndarray, optional + is the matrix constraint only valid locally? (Default value = False) + dynamic : bool or np.ndarray, optional + is the matrix constraint subject to aging? (Default value = False) + removable : bool or np.ndarray, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool or np.ndarray, optional + should the matrix constraint always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) + + Returns + ------- + MatrixConstraint + The newly created Indicator MatrixConstraint object. + """ + + if not isinstance(cons, (ExprCons, MatrixExprCons)): + raise TypeError("given constraint is not MatrixExprCons nor ExprCons but %s" % cons.__class__.__name__) + + if isinstance(cons, ExprCons): + return self.addConsIndicator(cons, binvar=binvar, activeone=activeone, name=name, + initial=initial, separate=separate, enforce=enforce, check=check, + propagate=propagate, local=local, dynamic=dynamic, removable=removable, + stickingatnode=stickingatnode) + + shape = cons.shape + + if isinstance(binvar, MatrixVariable): + assert binvar.shape == shape + if isinstance(activeone, np.ndarray): + assert activeone.shape == shape + if isinstance(name, np.ndarray): + assert name.shape == shape + if isinstance(initial, np.ndarray): + assert initial.shape == shape + if isinstance(separate, np.ndarray): + assert separate.shape == shape + if isinstance(enforce, np.ndarray): + assert enforce.shape == shape + if isinstance(check, np.ndarray): + assert check.shape == shape + if isinstance(propagate, np.ndarray): + assert propagate.shape == shape + if isinstance(local, np.ndarray): + assert local.shape == shape + if isinstance(dynamic, np.ndarray): + assert dynamic.shape == shape + if isinstance(removable, np.ndarray): + assert removable.shape == shape + if isinstance(stickingatnode, np.ndarray): + assert stickingatnode.shape == shape + + if not isinstance(binvar, MatrixVariable): + matrix_binvar = np.full(shape, binvar, dtype=Variable) + else: + matrix_binvar = binvar + + if not isinstance(activeone, np.ndarray): + matrix_activeone = np.full(shape, activeone, dtype=bool) + else: + matrix_activeone = activeone + + if isinstance(name, str): + matrix_names = np.full(shape, name, dtype=object) + if name != "": + for idx in np.ndindex(shape): + matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" + else: + matrix_names = name + + if not isinstance(initial, np.ndarray): + matrix_initial = np.full(shape, initial, dtype=bool) + else: + matrix_initial = initial + + if not isinstance(enforce, np.ndarray): + matrix_enforce = np.full(shape, enforce, dtype=bool) + else: + matrix_enforce = enforce + + if not isinstance(separate, np.ndarray): + matrix_separate = np.full(shape, separate, dtype=bool) + else: + matrix_separate = separate + + if not isinstance(check, np.ndarray): + matrix_check = np.full(shape, check, dtype=bool) + else: + matrix_check = check + + if not isinstance(propagate, np.ndarray): + matrix_propagate = np.full(shape, propagate, dtype=bool) + else: + matrix_propagate = propagate + + if not isinstance(local, np.ndarray): + matrix_local = np.full(shape, local, dtype=bool) + else: + matrix_local = local + + if not isinstance(dynamic, np.ndarray): + matrix_dynamic = np.full(shape, dynamic, dtype=bool) + else: + matrix_dynamic = dynamic + + if not isinstance(removable, np.ndarray): + matrix_removable = np.full(shape, removable, dtype=bool) + else: + matrix_removable = removable + + if not isinstance(stickingatnode, np.ndarray): + matrix_stickingatnode = np.full(shape, stickingatnode, dtype=bool) + else: + matrix_stickingatnode = stickingatnode + + matrix_cons = np.empty(shape, dtype=object) + for idx in np.ndindex(shape): + matrix_cons[idx] = self.addConsIndicator( + cons[idx], + binvar=matrix_binvar[idx], + activeone=matrix_activeone[idx], + name=matrix_names[idx], + initial=matrix_initial[idx], + separate=matrix_separate[idx], + enforce=matrix_enforce[idx], + check=matrix_check[idx], + propagate=matrix_propagate[idx], + local=matrix_local[idx], + dynamic=matrix_dynamic[idx], + removable=matrix_removable[idx], + stickingatnode=matrix_stickingatnode[idx], + ) + + return matrix_cons.view(MatrixConstraint) + + def getLinearConsIndicator(self, Constraint cons): + """ + Get the linear constraint corresponding to the indicator constraint. + + Parameters + ---------- + cons : Constraint + The indicator constraint + + Returns + ------- + Constraint or None + """ + + cdef SCIP_CONS* lincons = SCIPgetLinearConsIndicator(cons.scip_cons) + if lincons == NULL: + return None + return self._getOrCreateCons(lincons) + + def getSlackVarIndicator(self, Constraint cons): + """ + Get slack variable of an indicator constraint. + + + Parameters + ---------- + cons : Constraint + The indicator constraint + + Returns + ------- + Variable + + """ + cdef SCIP_VAR* var = SCIPgetSlackVarIndicator(cons.scip_cons) + return self._getOrCreateVar(var) + + def addPyCons(self, Constraint cons): + """ + Adds a customly created cons. + + Parameters + ---------- + cons : Constraint + constraint to add + + """ + PY_SCIP_CALL(SCIPaddCons(self._scip, cons.scip_cons)) + Py_INCREF(cons) + + def addVarSOS1(self, Constraint cons, Variable var, weight): + """ + Add variable to SOS1 constraint. + + Parameters + ---------- + cons : Constraint + SOS1 constraint + var : Variable + new variable + weight : weight + weight of new variable + + """ + PY_SCIP_CALL(SCIPaddVarSOS1(self._scip, cons.scip_cons, var.scip_var, weight)) + + def appendVarSOS1(self, Constraint cons, Variable var): + """ + Append variable to SOS1 constraint. + + Parameters + ---------- + cons : Constraint + SOS1 constraint + var : Variable + variable to append + + """ + PY_SCIP_CALL(SCIPappendVarSOS1(self._scip, cons.scip_cons, var.scip_var)) + + def addVarSOS2(self, Constraint cons, Variable var, weight): + """ + Add variable to SOS2 constraint. + + Parameters + ---------- + cons : Constraint + SOS2 constraint + var : Variable + new variable + weight : weight + weight of new variable + + """ + PY_SCIP_CALL(SCIPaddVarSOS2(self._scip, cons.scip_cons, var.scip_var, weight)) + + def appendVarSOS2(self, Constraint cons, Variable var): + """ + Append variable to SOS2 constraint. + + Parameters + ---------- + cons : Constraint + SOS2 constraint + var : Variable + variable to append + + """ + PY_SCIP_CALL(SCIPappendVarSOS2(self._scip, cons.scip_cons, var.scip_var)) + + def chgRhs(self, Constraint cons, rhs): + """ + Change right-hand side value of a constraint. + + Parameters + ---------- + cons : Constraint + constraint to change the right-hand side from + rhs : float or None + new right-hand side (set to None for +infinity) + + """ + + if rhs is None: + rhs = SCIPinfinity(self._scip) + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype == 'linear': + PY_SCIP_CALL(SCIPchgRhsLinear(self._scip, cons.scip_cons, rhs)) + elif constype == 'nonlinear': + PY_SCIP_CALL(SCIPchgRhsNonlinear(self._scip, cons.scip_cons, rhs)) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + def chgCapacityKnapsack(self, Constraint cons, capacity): + """ + Change capacity of a knapsack constraint. + + Parameters + ---------- + cons : Constraint + knapsack constraint to change the capacity from + capacity : float or None + new capacity (set to None for +infinity) + + """ + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + assert constype == 'knapsack', "method cannot be called for constraints of type " + constype + + if capacity is None: + capacity = SCIPinfinity(self._scip) + + PY_SCIP_CALL(SCIPchgCapacityKnapsack(self._scip, cons.scip_cons, capacity)) + + def chgLhs(self, Constraint cons, lhs): + """ + Change left-hand side value of a constraint. + + Parameters + ---------- + cons : Constraint + constraint to change the left-hand side from + lhs : float or None + new left-hand side (set to None for -infinity) + + """ + + if lhs is None: + lhs = -SCIPinfinity(self._scip) + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype == 'linear': + PY_SCIP_CALL(SCIPchgLhsLinear(self._scip, cons.scip_cons, lhs)) + elif constype == 'nonlinear': + PY_SCIP_CALL(SCIPchgLhsNonlinear(self._scip, cons.scip_cons, lhs)) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + def getRhs(self, Constraint cons): + """ + Retrieve right-hand side value of a constraint. + + Parameters + ---------- + cons : Constraint + constraint to get the right-hand side from + + Returns + ------- + float + + """ + cdef SCIP_Bool success + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + + if cons.isLinearType(): + rhs = SCIPconsGetRhs(self._scip, cons.scip_cons, &success) + assert(success) + return rhs + elif constype == 'nonlinear': + return SCIPgetRhsNonlinear(cons.scip_cons) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + def getCapacityKnapsack(self, Constraint cons): + """ + Retrieve capacity of a knapsack constraint. + + Parameters + ---------- + cons : Constraint + knapsack constraint to get the capacity from + + Returns + ------- + float + + """ + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + assert constype == 'knapsack', "method cannot be called for constraints of type " + constype + + return SCIPgetCapacityKnapsack(self._scip, cons.scip_cons) + + def getLhs(self, Constraint cons): + """ + Retrieve left-hand side value of a constraint. + + Parameters + ---------- + cons : Constraint + linear or nonlinear constraint + + Returns + ------- + float + + """ + cdef SCIP_Bool success + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + + if cons.isLinearType(): + lhs = SCIPconsGetLhs(self._scip, cons.scip_cons, &success) + assert(success) + return lhs + elif constype == 'nonlinear': + return SCIPgetLhsNonlinear(cons.scip_cons) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + def chgCoefLinear(self, Constraint cons, Variable var, value): + """ + Changes coefficient of variable in linear constraint; + deletes the variable if coefficient is zero; adds variable if not yet contained in the constraint + This method may only be called during problem creation stage for an original constraint and variable. + This method requires linear time to search for occurences of the variable in the constraint data. + + Parameters + ---------- + cons : Constraint + linear constraint + var : Variable + variable of constraint entry + value : float + new coefficient of constraint entry + + """ + PY_SCIP_CALL( SCIPchgCoefLinear(self._scip, cons.scip_cons, var.scip_var, value) ) + + def delCoefLinear(self, Constraint cons, Variable var): + """ + Deletes variable from linear constraint + This method may only be called during problem creation stage for an original constraint and variable. + This method requires linear time to search for occurrences of the variable in the constraint data. + + Parameters + ---------- + cons : Constraint + linear constraint + var : Variable + variable of constraint entry + + """ + + PY_SCIP_CALL( SCIPdelCoefLinear(self._scip, cons.scip_cons, var.scip_var) ) + + def addCoefLinear(self, Constraint cons, Variable var, value): + """ + Adds coefficient to linear constraint (if it is not zero) + + Parameters + ---------- + cons : Constraint + linear constraint + var : Variable + variable of constraint entry + value : float + coefficient of constraint entry + + """ + + PY_SCIP_CALL( SCIPaddCoefLinear(self._scip, cons.scip_cons, var.scip_var, value) ) + + def addCoefKnapsack(self, Constraint cons, Variable var, weight): + """ + Adds coefficient to knapsack constraint (if it is not zero) + + Parameters + ---------- + cons : Constraint + knapsack constraint + var : Variable + variable of constraint entry + weight : float + coefficient of constraint entry + + """ + + PY_SCIP_CALL( SCIPaddCoefKnapsack(self._scip, cons.scip_cons, var.scip_var, weight) ) + + def getActivity(self, Constraint cons, Solution sol = None): + """ + Retrieve activity of given constraint. + Can only be called after solving is completed. + + Parameters + ---------- + cons : Constraint + linear constraint + sol : Solution or None, optional + solution to compute activity of, None to use current node's solution (Default value = None) + + Returns + ------- + float + + """ + cdef SCIP_Real activity + cdef SCIP_SOL* scip_sol + + if not self.getStage() >= SCIP_STAGE_SOLVING: + raise Warning("method cannot be called before problem is solved") + + if isinstance(sol, Solution): + scip_sol = sol.sol + else: + scip_sol = NULL + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype == 'linear': + activity = SCIPgetActivityLinear(self._scip, cons.scip_cons, scip_sol) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + return activity + + def getSlack(self, Constraint cons, Solution sol = None, side = None): + """ + Retrieve slack of given constraint. + Can only be called after solving is completed. + + Parameters + ---------- + cons : Constraint + linear constraint + sol : Solution or None, optional + solution to compute slack of, None to use current node's solution (Default value = None) + side : str or None, optional + whether to use 'lhs' or 'rhs' for ranged constraints, None to return minimum (Default value = None) + + Returns + ------- + float + + """ + cdef SCIP_Real activity + cdef SCIP_SOL* scip_sol + + + if not self.getStage() >= SCIP_STAGE_SOLVING: + raise Warning("method cannot be called before problem is solved") + + if isinstance(sol, Solution): + scip_sol = sol.sol + else: + scip_sol = NULL + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if constype == 'linear': + lhs = SCIPgetLhsLinear(self._scip, cons.scip_cons) + rhs = SCIPgetRhsLinear(self._scip, cons.scip_cons) + activity = SCIPgetActivityLinear(self._scip, cons.scip_cons, scip_sol) + else: + raise Warning("method cannot be called for constraints of type " + constype) + + lhsslack = activity - lhs + rhsslack = rhs - activity + + if side == 'lhs': + return lhsslack + elif side == 'rhs': + return rhsslack + else: + return min(lhsslack, rhsslack) + + def isNLPConstructed(self): + """ + Returns whether SCIP's internal NLP has been constructed. + + Returns + ------- + bool + + """ + return SCIPisNLPConstructed(self._scip) + + def getNNlRows(self): + """ + Gets current number of nonlinear rows in SCIP's internal NLP. + + Returns + ------- + int + + """ + return SCIPgetNNLPNlRows(self._scip) + + def getNlRows(self): + """ + Returns a list with the nonlinear rows in SCIP's internal NLP. + + Returns + ------- + list of NLRow + + """ + cdef SCIP_NLROW** nlrows = SCIPgetNLPNlRows(self._scip) + cdef int i + + return [NLRow.create(nlrows[i]) for i in range(self.getNNlRows())] + + def getNlRowSolActivity(self, NLRow nlrow, Solution sol = None): + """ + Gives the activity of a nonlinear row for a given primal solution. + + Parameters + ---------- + nlrow : NLRow + sol : Solution or None, optional + a primal solution, if None, then the current LP solution is used + + Returns + ------- + float + + """ + cdef SCIP_Real activity + cdef SCIP_SOL* solptr + + solptr = sol.sol if not sol is None else NULL + PY_SCIP_CALL( SCIPgetNlRowSolActivity(self._scip, nlrow.scip_nlrow, solptr, &activity) ) + return activity + + def getNlRowSolFeasibility(self, NLRow nlrow, Solution sol = None): + """ + Gives the feasibility of a nonlinear row for a given primal solution + + Parameters + ---------- + nlrow : NLRow + sol : Solution or None, optional + a primal solution, if None, then the current LP solution is used + + Returns + ------- + bool + + """ + cdef SCIP_Real feasibility + cdef SCIP_SOL* solptr + + solptr = sol.sol if not sol is None else NULL + PY_SCIP_CALL( SCIPgetNlRowSolFeasibility(self._scip, nlrow.scip_nlrow, solptr, &feasibility) ) + return feasibility + + def getNlRowActivityBounds(self, NLRow nlrow): + """ + Gives the minimal and maximal activity of a nonlinear row w.r.t. the variable's bounds. + + Parameters + ---------- + nlrow : NLRow + + Returns + ------- + tuple of float + + """ + cdef SCIP_Real minactivity + cdef SCIP_Real maxactivity + + PY_SCIP_CALL( SCIPgetNlRowActivityBounds(self._scip, nlrow.scip_nlrow, &minactivity, &maxactivity) ) + return (minactivity, maxactivity) + + def printNlRow(self, NLRow nlrow): + """ + Prints nonlinear row. + + Parameters + ---------- + nlrow : NLRow + + """ + PY_SCIP_CALL( SCIPprintNlRow(self._scip, nlrow.scip_nlrow, NULL) ) + + def checkQuadraticNonlinear(self, Constraint cons): + """ + Returns if the given constraint is quadratic. + + Parameters + ---------- + cons : Constraint + + Returns + ------- + bool + + """ + cdef SCIP_Bool isquadratic + PY_SCIP_CALL( SCIPcheckQuadraticNonlinear(self._scip, cons.scip_cons, &isquadratic) ) + return isquadratic + + def getTermsQuadratic(self, Constraint cons): + """ + Retrieve bilinear, quadratic, and linear terms of a quadratic constraint. + + Parameters + ---------- + cons : Constraint + + Returns + ------- + bilinterms : list of tuple + Triples ``(var1, var2, coef)`` for terms of the form + ``coef * var1 * var2`` with ``var1 != var2``. + quadterms : list of tuple + Triples ``(var, sqrcoef, lincoef)`` for variables that appear in + quadratic or bilinear terms. ``sqrcoef`` is the coefficient of + ``var**2``, and ``lincoef`` is the linear coefficient of ``var`` + if it also appears linearly. + linterms : list of tuple + Pairs ``(var, coef)`` for purely linear variables, i.e., + variables that do not participate in any quadratic or bilinear term. + + """ + cdef SCIP_EXPR* expr + cdef int termidx + + # linear terms + cdef SCIP_EXPR** linexprs + cdef SCIP_Real* lincoefs + cdef SCIP_Real lincoef + cdef int nlinvars + + # bilinear terms + cdef SCIP_EXPR* bilinterm1 + cdef SCIP_EXPR* bilinterm2 + cdef SCIP_Real bilincoef + cdef int nbilinterms + + # quadratic terms + cdef SCIP_EXPR* quadexpr + cdef SCIP_EXPR* sqrexpr + cdef SCIP_Real sqrcoef + cdef int nquadterms + + # variables + cdef SCIP_VAR* scipvar1 + cdef SCIP_VAR* scipvar2 + + assert cons.isNonlinear(), "constraint is not nonlinear" + assert self.checkQuadraticNonlinear(cons), "constraint is not quadratic" + + expr = SCIPgetExprNonlinear(cons.scip_cons) + SCIPexprGetQuadraticData(expr, NULL, &nlinvars, &linexprs, &lincoefs, + &nquadterms, &nbilinterms, NULL, NULL) + + linterms = [] + bilinterms = [] + + # Purely linear terms (variables not in any quadratic/bilinear term) + for termidx in range(nlinvars): + var = self._getOrCreateVar(SCIPgetVarExprVar(linexprs[termidx])) + linterms.append((var, lincoefs[termidx])) + + # Collect quadratic terms in a dict so we can merge entries for the same variable. + quaddict = {} # var.ptr() -> [var, sqrcoef, lincoef] + + for termidx in range(nbilinterms): + SCIPexprGetQuadraticBilinTerm(expr, termidx, &bilinterm1, &bilinterm2, &bilincoef, NULL, NULL) + scipvar1 = SCIPgetVarExprVar(bilinterm1) + scipvar2 = SCIPgetVarExprVar(bilinterm2) + var1 = self._getOrCreateVar(scipvar1) + var2 = self._getOrCreateVar(scipvar2) + if scipvar1 != scipvar2: + bilinterms.append((var1, var2, bilincoef)) + else: + # Squared term reported as bilinear var*var + key = var1.ptr() + if key in quaddict: + quaddict[key][1] += bilincoef + else: # TODO: SCIP handles expr like x**2 appropriately, but PySCIPOpt requires this. Need to investigate why. + quaddict[key] = [var1, bilincoef, 0.0] + + # Also collect linear coefficients from the quadratic terms + for termidx in range(nquadterms): + SCIPexprGetQuadraticQuadTerm(expr, termidx, &quadexpr, &lincoef, &sqrcoef, NULL, NULL, &sqrexpr) + scipvar1 = SCIPgetVarExprVar(quadexpr) + var = self._getOrCreateVar(scipvar1) + key = var.ptr() + if key in quaddict: + quaddict[key][1] += sqrcoef + quaddict[key][2] += lincoef + else: + quaddict[key] = [var, sqrcoef, lincoef] + + quadterms = [tuple(entry) for entry in quaddict.values()] + + return (bilinterms, quadterms, linterms) + + def setRelaxSolVal(self, Variable var, val): + """ + Sets the value of the given variable in the global relaxation solution. + + Parameters + ---------- + var : Variable + val : float + + """ + PY_SCIP_CALL(SCIPsetRelaxSolVal(self._scip, NULL, var.scip_var, val)) + + def getValsLinear(self, Constraint cons): + """ + Retrieve the coefficients of a linear constraint + + Parameters + ---------- + cons : Constraint + linear constraint to get the coefficients of + + Returns + ------- + dict of str to float + + """ + cdef SCIP_VAR** vars + cdef SCIP_Real* vals + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if not constype == 'linear': + raise Warning("coefficients not available for constraints of type ", constype) + + vals = SCIPgetValsLinear(self._scip, cons.scip_cons) + vars = SCIPgetVarsLinear(self._scip, cons.scip_cons) + + valsdict = {} + for i in range(SCIPgetNVarsLinear(self._scip, cons.scip_cons)): + valsdict[bytes(SCIPvarGetName(vars[i])).decode('utf-8')] = vals[i] + + return valsdict + + def getWeightsKnapsack(self, Constraint cons): + """ + Retrieve the coefficients of a knapsack constraint + + Parameters + ---------- + cons : Constraint + knapsack constraint to get the coefficients of + + Returns + ------- + dict of str to float + + """ + cdef SCIP_VAR** vars + cdef SCIP_Longint* vals + cdef int nvars + cdef int i + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if not constype == 'knapsack': + raise Warning("weights not available for constraints of type ", constype) + + nvars = SCIPgetNVarsKnapsack(self._scip, cons.scip_cons) + vals = SCIPgetWeightsKnapsack(self._scip, cons.scip_cons) + vars = SCIPgetVarsKnapsack(self._scip, cons.scip_cons) + + valsdict = {} + for i in range(nvars): + var_name = bytes(SCIPvarGetName(vars[i])).decode('utf-8') + valsdict[var_name] = vals[i] + + return valsdict + + def getRowLinear(self, Constraint cons): + """ + Retrieve the linear relaxation of the given linear constraint as a row. + May return NULL if no LP row was yet created; the user must not modify the row! + + Parameters + ---------- + cons : Constraint + linear constraint to get the coefficients of + + Returns + ------- + Row + + """ + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if not constype == 'linear': + raise Warning("coefficients not available for constraints of type ", constype) + + cdef SCIP_ROW* row = SCIPgetRowLinear(self._scip, cons.scip_cons) + return Row.create(row) + + def getDualsolLinear(self, Constraint cons): + """ + Retrieve the dual solution to a linear constraint. + + Parameters + ---------- + cons : Constraint + linear constraint + + Returns + ------- + float + Zero if presolve removed the transformed constraint. + + """ + cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "linear") + if transcons == NULL: + return 0.0 + + return SCIPgetDualsolLinear(self._scip, transcons) + + def getDualsolKnapsack(self, Constraint cons): + """ + Retrieve the dual solution to a knapsack constraint. + + Parameters + ---------- + cons : Constraint + knapsack constraint + + Returns + ------- + float + + """ + cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "knapsack") + if transcons == NULL: + return 0.0 + + return SCIPgetDualsolKnapsack(self._scip, transcons) + + def getDualMultiplier(self, Constraint cons): + """ + DEPRECATED: Retrieve the dual solution to a linear constraint. + + Parameters + ---------- + cons : Constraint + linear constraint + + Returns + ------- + float + + """ + raise Warning("model.getDualMultiplier(cons) is deprecated: please use model.getDualsolLinear(cons)") + + def getDualfarkasLinear(self, Constraint cons): + """ + Retrieve the dual farkas value to a linear constraint. + + Parameters + ---------- + cons : Constraint + linear constraint + + Returns + ------- + float + Zero if presolve removed the transformed constraint. + + """ + # TODO this should ideally be handled on the SCIP side + cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "linear") + if transcons == NULL: + return 0.0 + + return SCIPgetDualfarkasLinear(self._scip, transcons) + + def getDualfarkasKnapsack(self, Constraint cons): + """ + Retrieve the dual farkas value to a knapsack constraint. + + Parameters + ---------- + cons : Constraint + knapsack constraint + + Returns + ------- + float + + """ + # TODO this should ideally be handled on the SCIP side + cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "knapsack") + if transcons == NULL: + return 0.0 + + return SCIPgetDualfarkasKnapsack(self._scip, transcons) + + def getVarRedcost(self, Variable var): + """ + Retrieve the reduced cost of a variable. + + Parameters + ---------- + var : Variable + variable to get the reduced cost of + + Returns + ------- + float + + """ + redcost = None + try: + redcost = SCIPgetVarRedcost(self._scip, var.scip_var) + if self.getObjectiveSense() == "maximize": + redcost = -redcost + except: + raise Warning("no reduced cost available for variable " + var.name) + return redcost + + def getDualSolVal(self, Constraint cons, boundconstraint=False): + """ + Returns dual solution value of a constraint. + + Parameters + ---------- + cons : Constraint + constraint to get the dual solution value of + boundconstraint : bool, optional + Decides whether to store a bool if the constraint is a bound constraint + (default = False) + + Returns + ------- + float + + """ + cdef SCIP_Real _dualsol + cdef SCIP_Bool _bounded + + if boundconstraint: + SCIPgetDualSolVal(self._scip, cons.scip_cons, &_dualsol, &_bounded) + else: + SCIPgetDualSolVal(self._scip, cons.scip_cons, &_dualsol, NULL) + + return _dualsol + + def createCons(self, Conshdlr conshdlr, name, initial=True, separate=True, enforce=True, check=True, propagate=True, + local=False, modifiable=False, dynamic=False, removable=False, stickingatnode=False): + """ + Create a constraint of a custom constraint handler. + + Parameters + ---------- + conshdlr : Conshdlr + constraint handler + name : str + name of constraint handler + initial : bool, optional + (Default value = True) + separate : bool, optional + (Default value = True) + enforce : bool, optional + (Default value = True) + check : bool, optional + (Default value = True) + propagate : bool, optional + (Default value = True) + local : bool, optional + (Default value = False) + modifiable : bool, optional + (Default value = False) + dynamic : bool, optional + (Default value = False) + removable : bool, optional + (Default value = False) + stickingatnode : bool, optional + (Default value = False) + + Returns + ------- + Constraint + + """ + + n = str_conversion(name) + cdef SCIP_CONSHDLR* scip_conshdlr + scip_conshdlr = SCIPfindConshdlr(self._scip, str_conversion(conshdlr.name)) + constraint = Constraint() + PY_SCIP_CALL(SCIPcreateCons(self._scip, &(constraint.scip_cons), n, scip_conshdlr, constraint, + initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) + return constraint + + def getLPBranchCands(self): + """ + Gets branching candidates for LP solution branching (fractional variables) along with solution values, + fractionalities, and number of branching candidates; The number of branching candidates does NOT account + for fractional implicit integer variables which should not be used for branching decisions. Fractional + implicit integer variables are stored at the positions nlpcands to nlpcands + nfracimplvars - 1 + branching rules should always select the branching candidate among the first npriolpcands of the candidate list + + Returns + ------- + list of Variable + list of variables of LP branching candidates + list of float + list of LP candidate solution values + list of float + list of LP candidate fractionalities + int + number of LP branching candidates + int + number of candidates with maximal priority + int + number of fractional implicit integer variables + + """ + cdef SCIP_VAR** lpcands + cdef SCIP_Real* lpcandssol + cdef SCIP_Real* lpcandsfrac + cdef int ncands + cdef int nlpcands + cdef int npriolpcands + cdef int nfracimplvars + cdef int i + + PY_SCIP_CALL(SCIPgetLPBranchCands(self._scip, &lpcands, &lpcandssol, &lpcandsfrac, + &nlpcands, &npriolpcands, &nfracimplvars)) + + return ([self._getOrCreateVar(lpcands[i]) for i in range(nlpcands)], [lpcandssol[i] for i in range(nlpcands)], + [lpcandsfrac[i] for i in range(nlpcands)], nlpcands, npriolpcands, nfracimplvars) + + def branchVarVal(self, Variable variable, value): + """ + Branches on variable using a value which separates the domain of the variable. + + Parameters + ---------- + variable : Variable + Variable to branch on + value : float + value to branch on + + Returns + ------- + Node + Node created for the down (left) branch + Node or None + Node created for the equal child (middle child). Only exists if the branch variable is integer + Node + Node created for the up (right) branch + + """ + cdef SCIP_NODE* downchild + cdef SCIP_NODE* eqchild + cdef SCIP_NODE* upchild + cdef _VarArray wrapper = _VarArray(variable) + + PY_SCIP_CALL(SCIPbranchVarVal(self._scip, wrapper.ptr[0], value, &downchild, &eqchild, &upchild)) + + return Node.create(downchild), Node.create(eqchild), Node.create(upchild) + + def calcNodeselPriority(self, Variable variable, branchdir, targetvalue): + """ + Calculates the node selection priority for moving the given variable's LP value + to the given target value; + this node selection priority can be given to the SCIPcreateChild() call. + + Parameters + ---------- + variable : Variable + variable on which the branching is applied + branchdir : PY_SCIP_BRANCHDIR + type of branching that was performed + targetvalue : float + new value of the variable in the child node + + Returns + ------- + float + node selection priority for moving the given variable's LP value to the given target value + + """ + return SCIPcalcNodeselPriority(self._scip, variable.scip_var, branchdir, targetvalue) + + def calcChildEstimate(self, Variable variable, targetvalue): + """ + Calculates an estimate for the objective of the best feasible solution + contained in the subtree after applying the given branching; + this estimate can be given to the SCIPcreateChild() call. + + Parameters + ---------- + variable : Variable + Variable to compute the estimate for + targetvalue : float + new value of the variable in the child node + + Returns + ------- + float + objective estimate of the best solution in the subtree after applying the given branching + + """ + return SCIPcalcChildEstimate(self._scip, variable.scip_var, targetvalue) + + # Diving methods (Diving is LP related) + def startDive(self): + """Initiates LP diving. + It allows the user to change the LP in several ways, solve, change again, etc, + without affecting the actual LP. When endDive() is called, + SCIP will undo all changes done and recover the LP it had before startDive.""" + PY_SCIP_CALL(SCIPstartDive(self._scip)) + + def endDive(self): + """Quits probing and resets bounds and constraints to the focus node's environment.""" + PY_SCIP_CALL(SCIPendDive(self._scip)) + + def chgVarObjDive(self, Variable var, newobj): + """ + Changes (column) variable's objective value in current dive. + + Parameters + ---------- + var : Variable + newobj : float + + """ + PY_SCIP_CALL(SCIPchgVarObjDive(self._scip, var.scip_var, newobj)) + + def chgVarLbDive(self, Variable var, newbound): + """ + Changes variable's current lb in current dive. + + Parameters + ---------- + var : Variable + newbound : float + + """ + PY_SCIP_CALL(SCIPchgVarLbDive(self._scip, var.scip_var, newbound)) + + def chgVarUbDive(self, Variable var, newbound): + """ + Changes variable's current ub in current dive. + + Parameters + ---------- + var : Variable + newbound : float + + """ + PY_SCIP_CALL(SCIPchgVarUbDive(self._scip, var.scip_var, newbound)) + + def getVarLbDive(self, Variable var): + """ + Returns variable's current lb in current dive. + + Parameters + ---------- + var : Variable + + Returns + ------- + float + + """ + return SCIPgetVarLbDive(self._scip, var.scip_var) + + def getVarUbDive(self, Variable var): + """ + Returns variable's current ub in current dive. + + Parameters + ---------- + var : Variable + + Returns + ------- + float + + """ + return SCIPgetVarUbDive(self._scip, var.scip_var) + + def chgRowLhsDive(self, Row row, newlhs): + """ + Changes row lhs in current dive, change will be undone after diving + ends, for permanent changes use SCIPchgRowLhs(). + + Parameters + ---------- + row : Row + newlhs : float + + """ + PY_SCIP_CALL(SCIPchgRowLhsDive(self._scip, row.scip_row, newlhs)) + + def chgRowRhsDive(self, Row row, newrhs): + """ + Changes row rhs in current dive, change will be undone after diving + ends. For permanent changes use SCIPchgRowRhs(). + + Parameters + ---------- + row : Row + newrhs : float + + """ + PY_SCIP_CALL(SCIPchgRowRhsDive(self._scip, row.scip_row, newrhs)) + + def addRowDive(self, Row row): + """ + Adds a row to the LP in current dive. + + Parameters + ---------- + row : Row + + """ + PY_SCIP_CALL(SCIPaddRowDive(self._scip, row.scip_row)) + + def solveDiveLP(self, itlim = -1): + """ + Solves the LP of the current dive. No separation or pricing is applied. + + Parameters + ---------- + itlim : int, optional + maximal number of LP iterations to perform (Default value = -1, that is, no limit) + + Returns + ------- + lperror : bool + whether an unresolved lp error occured + cutoff : bool + whether the LP was infeasible or the objective limit was reached + + """ + cdef SCIP_Bool lperror + cdef SCIP_Bool cutoff + + PY_SCIP_CALL(SCIPsolveDiveLP(self._scip, itlim, &lperror, &cutoff)) + return lperror, cutoff + + def chgVarObjProbing(self, Variable var, newobj): + """Changes (column) variable's objective value during probing mode.""" + PY_SCIP_CALL( SCIPchgVarObjProbing(self._scip, var.scip_var, newobj) ) + + def chgVarLbProbing(self, Variable var, lb): + """ + Changes the variable lower bound during probing mode. + + Parameters + ---------- + var : Variable + variable to change bound of + lb : float or None + new lower bound (set to None for -infinity) + + """ + if lb is None: + lb = -SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarLbProbing(self._scip, var.scip_var, lb)) + + def chgVarUbProbing(self, Variable var, ub): + """ + Changes the variable upper bound during probing mode. + + Parameters + ---------- + var : Variable + variable to change bound of + ub : float or None + new upper bound (set to None for +infinity) + + """ + if ub is None: + ub = SCIPinfinity(self._scip) + PY_SCIP_CALL(SCIPchgVarUbProbing(self._scip, var.scip_var, ub)) + + def fixVarProbing(self, Variable var, fixedval): + """ + Fixes a variable at the current probing node. + + Parameters + ---------- + var : Variable + fixedval : float + + """ + PY_SCIP_CALL( SCIPfixVarProbing(self._scip, var.scip_var, fixedval) ) + + def writeLP(self, filename="LP.lp"): + """ + Writes current LP to a file. + + Parameters + ---------- + filename : str, optional + file name (Default value = "LP.lp") + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + absfile = str_conversion(abspath(filename)) + PY_SCIP_CALL( SCIPwriteLP(self._scip, absfile) ) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def writeMIP(self, filename, genericnames=False, origobj=False, lazyconss=False): + """ + Writes MIP relaxation of the current branch-and-bound node to a file + + Parameters + ---------- + filename : str + name of the output file + genericnames : bool, optional + should generic names like x_i and row_j be used in order to avoid troubles with reserved symbols? (Default value = False) + origobj : bool, optional + should the original objective function be used (Default value = False) + lazyconss : bool, optional + output removable rows as lazy constraints? (Default value = False) + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + absfile = str_conversion(abspath(filename)) + PY_SCIP_CALL(SCIPwriteMIP(self._scip, absfile, genericnames, origobj, lazyconss)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def createSol(self, Heur heur = None, initlp=False): + """ + Create a new primal solution in the transformed space. + + Parameters + ---------- + heur : Heur or None, optional + heuristic that found the solution (Default value = None) + initlp : bool, optional + Should the created solution be initialised to the current LP solution instead of all zeros + + Returns + ------- + Solution + + """ + cdef SCIP_SOL* _sol + cdef SCIP_HEUR* _heur = self._getHeur(heur) + + if not initlp: + PY_SCIP_CALL(SCIPcreateSol(self._scip, &_sol, _heur)) + else: + PY_SCIP_CALL(SCIPcreateLPSol(self._scip, &_sol, _heur)) + solution = Solution.create(self._scip, _sol) + return solution + + def createPartialSol(self, Heur heur = None): + """ + Create a partial primal solution, initialized to unknown values. + + Parameters + ---------- + heur : Heur or None, optional + heuristic that found the solution (Default value = None) + + Returns + ------- + Solution + + """ + cdef SCIP_SOL* _sol + cdef SCIP_HEUR* _heur = self._getHeur(heur) + + PY_SCIP_CALL(SCIPcreatePartialSol(self._scip, &_sol, _heur)) + partialsolution = Solution.create(self._scip, _sol) + return partialsolution + + def createOrigSol(self, Heur heur = None): + """ + Create a new primal solution in the original space. + + Parameters + ---------- + heur : Heur or None, optional + heuristic that found the solution (Default value = None) + + Returns + ------- + Solution + + """ + cdef SCIP_HEUR* _heur + cdef SCIP_SOL* _sol + + _heur = self._getHeur(heur) + + PY_SCIP_CALL(SCIPcreateOrigSol(self._scip, &_sol, _heur)) + solution = Solution.create(self._scip, _sol) + return solution + + def printBestSol(self, write_zeros=False): + """ + Prints the best feasible primal solution. + + Parameters + ---------- + write_zeros : bool, optional + include variables that are set to zero (Default = False) + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + PY_SCIP_CALL(SCIPprintBestSol(self._scip, NULL, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def printSol(self, Solution solution=None, write_zeros=False): + """ + Print the given primal solution. + + Parameters + ---------- + solution : Solution or None, optional + solution to print (default = None) + write_zeros : bool, optional + include variables that are set to zero (Default=False) + + """ + + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + if solution is None: + PY_SCIP_CALL(SCIPprintSol(self._scip, NULL, NULL, write_zeros)) + else: + PY_SCIP_CALL(SCIPprintSol(self._scip, solution.sol, NULL, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def writeBestSol(self, filename="origprob.sol", write_zeros=False): + """ + Write the best feasible primal solution to a file. + + Parameters + ---------- + filename : str, optional + name of the output file (Default="origprob.sol") + write_zeros : bool, optional + include variables that are set to zero (Default=False) + + """ + + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + # use this doubled opening pattern to ensure that IOErrors are + # triggered early and in Python not in C,Cython or SCIP. + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + PY_SCIP_CALL(SCIPprintBestSol(self._scip, cfile, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def writeBestTransSol(self, filename="transprob.sol", write_zeros=False): + """ + Write the best feasible primal solution for the transformed problem to a file. + + Parameters + ---------- + filename : str, optional + name of the output file (Default="transprob.sol") + write_zeros : bool, optional + include variables that are set to zero (Default=False) + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + # use this double opening pattern to ensure that IOErrors are + # triggered early and in python not in C, Cython or SCIP. + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + PY_SCIP_CALL(SCIPprintBestTransSol(self._scip, cfile, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def writeSol(self, Solution solution, filename="origprob.sol", write_zeros=False): + """ + Write the given primal solution to a file. + + Parameters + ---------- + solution : Solution + solution to write + filename : str, optional + name of the output file (Default="origprob.sol") + write_zeros : bool, optional + include variables that are set to zero (Default=False) + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + # use this doubled opening pattern to ensure that IOErrors are + # triggered early and in Python not in C,Cython or SCIP. + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + PY_SCIP_CALL(SCIPprintSol(self._scip, solution.sol, cfile, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def writeTransSol(self, Solution solution, filename="transprob.sol", write_zeros=False): + """ + Write the given transformed primal solution to a file. + + Parameters + ---------- + solution : Solution + transformed solution to write + filename : str, optional + name of the output file (Default="transprob.sol") + write_zeros : bool, optional + include variables that are set to zero (Default=False) + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + # use this doubled opening pattern to ensure that IOErrors are + # triggered early and in Python not in C,Cython or SCIP. + with open(filename, "w") as f: + cfile = fdopen(f.fileno(), "w") + PY_SCIP_CALL(SCIPprintTransSol(self._scip, solution.sol, cfile, write_zeros)) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + # perhaps this should not be included as it implements duplicated functionality + # (as does it's namesake in SCIP) + def readSol(self, filename): + """ + Reads a given solution file, problem has to be transformed in advance. + + Parameters + ---------- + filename : str + name of the input file + + """ + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + absfile = str_conversion(abspath(filename)) + PY_SCIP_CALL(SCIPreadSol(self._scip, absfile)) + + locale.setlocale(locale.LC_NUMERIC, user_locale) + + def readSolFile(self, filename): + """ + Reads a given solution file. + + Solution is created but not added to storage/the model. + Use 'addSol' OR 'trySol' to add it. + + Parameters + ---------- + filename : str + name of the input file + + Returns + ------- + Solution + + """ + cdef SCIP_Bool partial + cdef SCIP_Bool error + cdef SCIP_Bool stored + cdef Solution solution + + str_absfile = abspath(filename) + absfile = str_conversion(str_absfile) + solution = self.createSol() + + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + PY_SCIP_CALL(SCIPreadSolFile(self._scip, absfile, solution.sol, False, &partial, &error)) + + locale.setlocale(locale.LC_NUMERIC, user_locale) + + if error: + raise Exception("SCIP: reading solution from file " + str_absfile + " failed!") + + return solution + + def setSolVal(self, Solution solution, Variable var, val): + """ + Set a variable in a solution. + + Parameters + ---------- + solution : Solution + solution to be modified + var : Variable + variable in the solution + val : float + value of the specified variable + + """ + cdef SCIP_SOL* _sol + _sol = solution.sol + + assert _sol != NULL, "Cannot set value to a freed solution." + PY_SCIP_CALL(SCIPsetSolVal(self._scip, _sol, var.scip_var, val)) + + def trySol(self, Solution solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, free=True): + """ + Check given primal solution for feasibility and try to add it to the storage. + + Parameters + ---------- + solution : Solution + 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 + + """ + cdef SCIP_Bool stored + if free: + PY_SCIP_CALL(SCIPtrySolFree(self._scip, &solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) + else: + PY_SCIP_CALL(SCIPtrySol(self._scip, solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) + return stored + + def getSolObjVal(self, Solution sol, original=True): + """ + Retrieve the objective value of the solution. + + Parameters + ---------- + sol : Solution + original : bool, optional + objective value in original space (Default value = True) + + Returns + ------- + float + + """ + if sol == None: + sol = Solution.create(self._scip, NULL) + + sol._checkStage("getSolObjVal") + + if original: + objval = SCIPgetSolOrigObj(self._scip, sol.sol) + else: + objval = SCIPgetSolTransObj(self._scip, sol.sol) + + return objval + + def getSolVal( + self, + Solution sol, + expr: Union[Expr, GenExpr, MatrixExpr], + ) -> Union[float, np.ndarray]: + """ + Retrieve value of given variable or expression in the given solution. + + Parameters + ---------- + sol : Solution + Solution to query the value from. If None, the current LP/pseudo solution is + used. + + expr : Expr, GenExpr, MatrixExpr + Expression to query the value of. + + Returns + ------- + float or np.ndarray + + Notes + ----- + A variable is also an expression. + + """ + # no need to create a NULL solution wrapper in case we have a variable + return (sol or Solution.create(self._scip, NULL))[expr] + + def getVal(self, expr: Union[Expr, GenExpr, MatrixExpr]) -> Union[float, np.ndarray]: + """ + Retrieve the value of the given variable or expression in the best known solution. + Can only be called after solving is completed. + + Parameters + ---------- + expr : Expr, GenExpr or MatrixExpr + Expression to query the value of. + + Returns + ------- + float or np.ndarray + + Notes + ----- + A variable is also an expression. + + """ + if SCIPgetStage(self._scip) in {SCIP_STAGE_INIT, SCIP_STAGE_FREE}: + raise Warning("Method cannot be called in stage ", self.getStage()) + + self._ensureFreshBestSol() + + if self._bestSol.sol == NULL and SCIPgetStage(self._scip) != SCIP_STAGE_SOLVING: + raise Warning("No solution available") + + return self._bestSol[expr] + + def getPrimalRayVal(self, Variable var): + """ + Gets value of given variable in primal ray causing unboundedness of the LP relaxation. + + Parameters + ---------- + var : Variable + + Returns + ------- + float + + """ + assert SCIPhasPrimalRay(self._scip), "The problem does not have a primal ray." + + return SCIPgetPrimalRayVal(self._scip, var.scip_var) + + def getPrimalRay(self): + """ + Gets primal ray causing unboundedness of the LP relaxation. + + Returns + ------- + list of float + + """ + assert SCIPhasPrimalRay(self._scip), "The problem does not have a primal ray." + cdef SCIP_VAR** vars = SCIPgetVars(self._scip) + cdef int nvars = SCIPgetNVars(self._scip) + cdef int i + + ray = [] + for i in range(nvars): + ray.append(float(SCIPgetPrimalRayVal(self._scip, vars[i]))) + + return ray + + def getPrimalbound(self): + """ + Retrieve the best primal bound. + + Returns + ------- + float + + """ + return SCIPgetPrimalbound(self._scip) + + def getDualbound(self): + """ + Retrieve the best dual bound. + + Returns + ------- + float + + """ + return SCIPgetDualbound(self._scip) + + def getDualboundRoot(self): + """ + Retrieve the best root dual bound. + + Returns + ------- + float + + """ + return SCIPgetDualboundRoot(self._scip) + + def getLowerboundRoot(self): + """ + Gets lower (dual) bound in transformed problem of the root node. + + Returns + ------- + float + + """ + return SCIPgetLowerboundRoot(self._scip) + + def chgReoptObjective(self, coeffs, sense = 'minimize'): + """ + Change the objective function for reoptimization. + + Parameters + ---------- + coeffs : Expr + the coefficients as a linear expression + sense : str + the objective sense (Default value = 'minimize') + + """ + cdef SCIP_VAR** vars + cdef int nvars + cdef SCIP_Real* _coeffs + cdef SCIP_OBJSENSE objsense + cdef int i + cdef _VarArray wrapper + + if sense == "minimize": + objsense = SCIP_OBJSENSE_MINIMIZE + elif sense == "maximize": + objsense = SCIP_OBJSENSE_MAXIMIZE + else: + raise Warning("unrecognized optimization sense: %s" % sense) + + assert isinstance(coeffs, Expr), "given coefficients are not Expr but %s" % coeffs.__class__.__name__ + + if coeffs.degree() > 1: + raise ValueError("Nonlinear objective functions are not supported!") + if coeffs[CONST] != 0.0: + raise ValueError("Constant offsets in objective are not supported!") + + nvars = len(coeffs.terms) - (CONST in coeffs.terms) + + if nvars == 0: + PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, NULL, NULL, 0)) + return + + _coeffs = malloc(nvars * sizeof(SCIP_Real)) + vars = malloc(nvars * sizeof(SCIP_VAR*)) + + i = 0 + for term, coef in coeffs.terms.items(): + # avoid CONST term of Expr + if term != CONST: + wrapper = _VarArray(term[0]) + vars[i] = wrapper.ptr[0] + _coeffs[i] = coef + i += 1 + + PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, vars, _coeffs, nvars)) + + free(vars) + free(_coeffs) + + def getVarStrongbranchLast(self, Variable var): + """ + Get the results of the last strong branching call on this variable (potentially was called + at another node). + + Parameters + ---------- + var : Variable + variable to get the previous strong branching information from + + Returns + ------- + down : float + The dual bound of the LP after branching down on the variable + up : float + The dual bound of the LP after branchign up on the variable + downvalid : bool + stores whether the returned down value is a valid dual bound, or NULL + upvalid : bool + stores whether the returned up value is a valid dual bound, or NULL + solval : float + The solution value of the variable at the last strong branching call + lpobjval : float + The LP objective value at the time of the last strong branching call + + """ + + cdef SCIP_Real down + cdef SCIP_Real up + cdef SCIP_Real solval + cdef SCIP_Real lpobjval + cdef SCIP_Bool downvalid + cdef SCIP_Bool upvalid + + PY_SCIP_CALL(SCIPgetVarStrongbranchLast(self._scip, var.scip_var, &down, &up, &downvalid, &upvalid, &solval, &lpobjval)) + + return down, up, downvalid, upvalid, solval, lpobjval + + def getVarStrongbranch(self, Variable var, itlim, idempotent=False, integral=False): + """ + Strong branches and gets information on column variable. + + Parameters + ---------- + var : Variable + Variable to get strong branching information on + itlim : int + LP iteration limit for total strong branching calls + idempotent : bool, optional + Should SCIP's state remain the same after the call? + integral : bool, optional + Boolean on whether the variable is currently integer. + + Returns + ------- + down : float + The dual bound of the LP after branching down on the variable + up : float + The dual bound of the LP after branchign up on the variable + downvalid : bool + stores whether the returned down value is a valid dual bound, or NULL + upvalid : bool + stores whether the returned up value is a valid dual bound, or NULL + downinf : bool + store whether the downwards branch is infeasible + upinf : bool + store whether the upwards branch is infeasible + downconflict : bool + store whether a conflict constraint was created for an infeasible downwards branch + upconflict : bool + store whether a conflict constraint was created for an infeasible upwards branch + lperror : bool + whether an unresolved LP error occurred in the solving process + + """ + + cdef SCIP_Real down + cdef SCIP_Real up + cdef SCIP_Bool downvalid + cdef SCIP_Bool upvalid + cdef SCIP_Bool downinf + cdef SCIP_Bool upinf + cdef SCIP_Bool downconflict + cdef SCIP_Bool upconflict + cdef SCIP_Bool lperror + + if integral: + PY_SCIP_CALL(SCIPgetVarStrongbranchInt(self._scip, var.scip_var, itlim, idempotent, &down, &up, &downvalid, + &upvalid, &downinf, &upinf, &downconflict, &upconflict, &lperror)) + else: + PY_SCIP_CALL(SCIPgetVarStrongbranchFrac(self._scip, var.scip_var, itlim, idempotent, &down, &up, &downvalid, + &upvalid, &downinf, &upinf, &downconflict, &upconflict, &lperror)) + + return down, up, downvalid, upvalid, downinf, upinf, downconflict, upconflict, lperror + + def getBipartiteGraphRepresentation(self, prev_col_features=None, prev_edge_features=None, prev_row_features=None, + static_only=False, suppress_warnings=False): + """ + This function generates the bipartite graph representation of an LP, which was first used in + the following paper: + @inproceedings{conf/nips/GasseCFCL19, + title={Exact Combinatorial Optimization with Graph Convolutional Neural Networks}, + author={Gasse, Maxime and Chételat, Didier and Ferroni, Nicola and Charlin, Laurent and Lodi, Andrea}, + booktitle={Advances in Neural Information Processing Systems 32}, + year={2019} + } + The exact features have been modified compared to the original implementation. + This function is used mainly in the machine learning community for MIP. + A user can only call it during the solving process, when there is an LP object. This means calling it + from some user defined plugin on the Python side. + An example plugin is a branching rule or an event handler, which is exclusively created to call this function. + The user must then make certain to return the appropriate SCIP_RESULT (e.g. DIDNOTRUN) + + Parameters + ---------- + prev_col_features : list of list or None, optional + The list of column features previously returned by this function + prev_edge_features : list of list or None, optional + The list of edge features previously returned by this function + prev_row_features : list of list or None, optional + The list of row features previously returned by this function + static_only : bool, optional + Whether exclusively static features should be generated + suppress_warnings : bool, optional + Whether warnings should be suppressed + + Returns + ------- + col_features : list of list + edge_features : list of list + row_features : list of list + dict + The feature mappings for the columns, edges, and rows + + """ + cdef SCIP* scip = self._scip + cdef SCIP_VARTYPE vtype + cdef SCIP_Real sim, prod + cdef int col_i + cdef int i + cdef int j + cdef int k + + # Check if SCIP is in the correct stage + if SCIPgetStage(scip) != SCIP_STAGE_SOLVING: + raise Warning("This functionality can only been called in SCIP_STAGE SOLVING. The row and column" + "information is then accessible") + + # Generate column features + cdef SCIP_COL** cols = SCIPgetLPCols(scip) + cdef int ncols = SCIPgetNLPCols(scip) + + if static_only: + n_col_features = 5 + col_feature_map = {"continuous": 0, "binary": 1, "integer": 2, "implicit_integer": 3, "obj_coef": 4} + else: + n_col_features = 19 + col_feature_map = {"continuous": 0, "binary": 1, "integer": 2, "implicit_integer": 3, "obj_coef": 4, + "has_lb": 5, "has_ub": 6, "sol_at_lb": 7, "sol_at_ub": 8, "sol_val": 9, "sol_frac": 10, + "red_cost": 11, "basis_lower": 12, "basis_basic": 13, "basis_upper": 14, + "basis_zero": 15, "best_incumbent_val": 16, "avg_incumbent_val": 17, "age": 18} + + if prev_col_features is None: + col_features = [[0 for i in range(n_col_features)] for j in range(ncols)] + else: + assert len(prev_col_features) > 0, "Previous column features is empty" + col_features = prev_col_features + if len(prev_col_features) != ncols: + if not suppress_warnings: + raise Warning(f"The number of columns has changed. Previous column data being ignored") + else: + col_features = [[0 for i in range(n_col_features)] for j in range(ncols)] + prev_col_features = None + if len(prev_col_features[0]) != n_col_features: + raise Warning(f"Dimension mismatch in provided previous features and new features:" + f"{len(prev_col_features[0])} != {n_col_features}") + + cdef SCIP_SOL* sol = SCIPgetBestSol(scip) + cdef SCIP_VAR* var + cdef SCIP_Real lb + cdef SCIP_Real ub + cdef SCIP_Real solval + cdef SCIP_BASESTAT basis_status + + for i in range(ncols): + col_i = SCIPcolGetLPPos(cols[i]) + var = SCIPcolGetVar(cols[i]) + + lb = SCIPcolGetLb(cols[i]) + ub = SCIPcolGetUb(cols[i]) + solval = SCIPcolGetPrimsol(cols[i]) + + # Collect the static features first (don't need to changed if previous features are passed) + if prev_col_features is None: + # Variable types + vtype = SCIPvarGetType(var) + if vtype == SCIP_VARTYPE_BINARY: + col_features[col_i][col_feature_map["binary"]] = 1 + elif vtype == SCIP_VARTYPE_INTEGER: + col_features[col_i][col_feature_map["integer"]] = 1 + elif vtype == SCIP_VARTYPE_CONTINUOUS: + col_features[col_i][col_feature_map["continuous"]] = 1 + elif vtype == SCIP_DEPRECATED_VARTYPE_IMPLINT: + col_features[col_i][col_feature_map["implicit_integer"]] = 1 + # Objective coefficient + col_features[col_i][col_feature_map["obj_coef"]] = SCIPcolGetObj(cols[i]) + + # Collect the dynamic features + if not static_only: + # Lower bound + if not SCIPisInfinity(scip, abs(lb)): + col_features[col_i][col_feature_map["has_lb"]] = 1 + + # Upper bound + if not SCIPisInfinity(scip, abs(ub)): + col_features[col_i][col_feature_map["has_ub"]] = 1 + + # Basis status + basis_status = SCIPcolGetBasisStatus(cols[i]) + if basis_status == SCIP_BASESTAT_LOWER: + col_features[col_i][col_feature_map["basis_lower"]] = 1 + elif basis_status == SCIP_BASESTAT_BASIC: + col_features[col_i][col_feature_map["basis_basic"]] = 1 + elif basis_status == SCIP_BASESTAT_UPPER: + col_features[col_i][col_feature_map["basis_upper"]] = 1 + elif basis_status == SCIP_BASESTAT_ZERO: + col_features[col_i][col_feature_map["basis_zero"]] = 1 + + # Reduced cost + col_features[col_i][col_feature_map["red_cost"]] = SCIPgetColRedcost(scip, cols[i]) + + # Age + col_features[col_i][col_feature_map["age"]] = SCIPcolGetAge(cols[i]) + + # LP solution value + col_features[col_i][col_feature_map["sol_val"]] = solval + col_features[col_i][col_feature_map["sol_frac"]] = SCIPfeasFrac(scip, solval) + col_features[col_i][col_feature_map["sol_at_lb"]] = int(SCIPisEQ(scip, solval, lb)) + col_features[col_i][col_feature_map["sol_at_ub"]] = int(SCIPisEQ(scip, solval, ub)) + + # Incumbent solution value + if sol is NULL: + col_features[col_i][col_feature_map["best_incumbent_val"]] = None + col_features[col_i][col_feature_map["avg_incumbent_val"]] = None + else: + col_features[col_i][col_feature_map["best_incumbent_val"]] = SCIPgetSolVal(scip, sol, var) + col_features[col_i][col_feature_map["avg_incumbent_val"]] = SCIPvarGetAvgSol(var) + + # Generate row features + cdef SCIP_ROW** rows = SCIPgetLPRows(scip) + cdef int nrows = SCIPgetNLPRows(scip) + + if static_only: + n_row_features = 6 + row_feature_map = {"has_lhs": 0, "has_rhs": 1, "n_non_zeros": 2, "obj_cosine": 3, "bias": 4, "norm": 5} + else: + n_row_features = 14 + row_feature_map = {"has_lhs": 0, "has_rhs": 1, "n_non_zeros": 2, "obj_cosine": 3, "bias": 4, "norm": 5, + "sol_at_lhs": 6, "sol_at_rhs": 7, "dual_sol": 8, "age": 9, + "basis_lower": 10, "basis_basic": 11, "basis_upper": 12, "basis_zero": 13} + + if prev_row_features is None: + row_features = [[0 for i in range(n_row_features)] for j in range(nrows)] + else: + assert len(prev_row_features) > 0, "Previous row features is empty" + row_features = prev_row_features + if len(prev_row_features) != nrows: + if not suppress_warnings: + raise Warning(f"The number of rows has changed. Previous row data being ignored") + else: + row_features = [[0 for i in range(n_row_features)] for j in range(nrows)] + prev_row_features = None + if len(prev_row_features[0]) != n_row_features: + raise Warning(f"Dimension mismatch in provided previous features and new features:" + f"{len(prev_row_features[0])} != {n_row_features}") + + cdef SCIP_Real lhs + cdef SCIP_Real rhs + cdef SCIP_Real cst + cdef int nnzrs = 0 + + for i in range(nrows): + + # lhs <= activity + cst <= rhs + lhs = SCIProwGetLhs(rows[i]) + rhs = SCIProwGetRhs(rows[i]) + cst = SCIProwGetConstant(rows[i]) + activity = SCIPgetRowLPActivity(scip, rows[i]) + + if prev_row_features is None: + # number of coefficients + row_features[i][row_feature_map["n_non_zeros"]] = SCIProwGetNLPNonz(rows[i]) + nnzrs += row_features[i][row_feature_map["n_non_zeros"]] + + # left-hand-side + if not SCIPisInfinity(scip, abs(lhs)): + row_features[i][row_feature_map["has_lhs"]] = 1 + + # right-hand-side + if not SCIPisInfinity(scip, abs(rhs)): + row_features[i][row_feature_map["has_rhs"]] = 1 + + # bias + row_features[i][row_feature_map["bias"]] = cst + + # Objective cosine similarity + row_features[i][row_feature_map["obj_cosine"]] = SCIPgetRowObjParallelism(scip, rows[i]) + + # L2 norm + row_features[i][row_feature_map["norm"]] = SCIProwGetNorm(rows[i]) + + if not static_only: + + # Dual solution + row_features[i][row_feature_map["dual_sol"]] = SCIProwGetDualsol(rows[i]) + + # Basis status + basis_status = SCIProwGetBasisStatus(rows[i]) + if basis_status == SCIP_BASESTAT_LOWER: + row_features[i][row_feature_map["basis_lower"]] = 1 + elif basis_status == SCIP_BASESTAT_BASIC: + row_features[i][row_feature_map["basis_basic"]] = 1 + elif basis_status == SCIP_BASESTAT_UPPER: + row_features[i][row_feature_map["basis_upper"]] = 1 + elif basis_status == SCIP_BASESTAT_ZERO: + row_features[i][row_feature_map["basis_zero"]] = 1 + + # Age + row_features[i][row_feature_map["age"]] = SCIProwGetAge(rows[i]) + + # Is tight + row_features[i][row_feature_map["sol_at_lhs"]] = int(SCIPisEQ(scip, activity, lhs)) + row_features[i][row_feature_map["sol_at_rhs"]] = int(SCIPisEQ(scip, activity, rhs)) + + # Generate edge (coefficient) features + cdef SCIP_COL** row_cols + cdef SCIP_Real * row_vals + + n_edge_features = 3 + edge_feature_map = {"col_idx": 0, "row_idx": 1, "coef": 2} + if prev_edge_features is None: + edge_features = [[0 for i in range(n_edge_features)] for j in range(nnzrs)] + j = 0 + for i in range(nrows): + # coefficient indexes and values + row_cols = SCIProwGetCols(rows[i]) + row_vals = SCIProwGetVals(rows[i]) + for k in range(row_features[i][row_feature_map["n_non_zeros"]]): + edge_features[j][edge_feature_map["col_idx"]] = SCIPcolGetLPPos(row_cols[k]) + edge_features[j][edge_feature_map["row_idx"]] = i + edge_features[j][edge_feature_map["coef"]] = row_vals[k] + j += 1 + else: + assert len(prev_edge_features) > 0, "Previous edge features is empty" + edge_features = prev_edge_features + if len(prev_edge_features) != nnzrs: + if not suppress_warnings: + raise Warning(f"The number of coefficients in the LP has changed. Previous edge data being ignored") + else: + edge_features = [[0 for i in range(3)] for j in range(nnzrs)] + prev_edge_features = None + if len(prev_edge_features[0]) != 3: + raise Warning(f"Dimension mismatch in provided previous features and new features:" + f"{len(prev_edge_features[0])} != 3") + + return (col_features, edge_features, row_features, + {"col": col_feature_map, "edge": edge_feature_map, "row": row_feature_map}) + + def copyLargeNeighborhoodSearch(self, to_fix, fix_vals) -> Model: + """ + Creates a configured copy of the transformed problem and applies provided fixings intended for LNS heuristics. + + Parameters + ---------- + to_fix : List[Variable] + A list of variables to fix in the copy + fix_vals : List[Real] + A list of the values to which to fix the variables in the copy (care their order) + + Returns + ------- + model : Model + A model containing the created copy + """ + cdef SCIP* subscip + cdef SCIP_HASHMAP* varmap + cdef SCIP_VAR** orig_vars = SCIPgetVars(self._scip) + cdef SCIP_VAR** vars = malloc(len(to_fix) * sizeof(SCIP_VAR*)) + cdef SCIP_Real* vals = malloc(len(fix_vals) * sizeof(SCIP_Real)) + cdef SCIP_Real val + cdef SCIP_Bool valid + cdef SCIP_Bool success + cdef int i + cdef int j = 0 + + name_to_val = {var.name: val for var, val in zip(to_fix, fix_vals)} + for i, var in enumerate(self.getVars()): + if var.name in name_to_val: + vars[j] = orig_vars[i] + vals[j] = name_to_val[var.name] + j+= 1 + + PY_SCIP_CALL(SCIPcreate(&subscip)) + PY_SCIP_CALL( SCIPhashmapCreate(&varmap, SCIPblkmem(subscip), self.getNVars()) ) + PY_SCIP_CALL( SCIPcopyLargeNeighborhoodSearch(self._scip, subscip, varmap, "LNhS_subscip", vars, vals, + len(to_fix), False, False, &success, &valid) ) + sub_model = BaseModel.create(subscip) + sub_model._freescip = True + free(vars) + free(vals) + SCIPhashmapFree(&varmap) + + return sub_model + + def addMatrixVar(self, + shape: Union[int, Tuple], + name: Union[str, np.ndarray] = '', + vtype: Union[str, np.ndarray] = 'C', + lb: Union[int, float, np.ndarray, None] = 0.0, + ub: Union[int, float, np.ndarray, None] = None, + obj: Union[int, float, np.ndarray] = 0.0, + pricedVar: Union[bool, np.ndarray] = False, + pricedVarScore: Union[int, float, np.ndarray] = 1.0 + ) -> MatrixVariable: + """ + Create a new matrix of variable. Default matrix variables are non-negative and continuous. + + Parameters + ---------- + shape : int or tuple + the shape of the resultant MatrixVariable + name : str or np.ndarray, optional + name of the matrix variable, generic if empty (Default value = '') + vtype : str or np.ndarray, optional + type of the matrix variable: 'C' continuous, 'I' integer, 'B' binary, and 'M' implicit integer + (Default value = 'C') + lb : float or np.ndarray or None, optional + lower bound of the matrix variable, use None for -infinity (Default value = 0.0) + ub : float or np.ndarray or None, optional + upper bound of the matrix variable, use None for +infinity (Default value = None) + obj : float or np.ndarray, optional + objective value of matrix variable (Default value = 0.0) + pricedVar : bool or np.ndarray, optional + is the matrix variable a pricing candidate? (Default value = False) + pricedVarScore : float or np.ndarray, optional + score of matrix variable in case it is priced, the higher the better (Default value = 1.0) + + Returns + ------- + MatrixVariable + + """ + # assert has_numpy, "Numpy is not installed. Please install numpy to use matrix variables." + + if isinstance(name, np.ndarray): + assert name.shape == shape + if isinstance(vtype, np.ndarray): + assert vtype.shape == shape + if isinstance(lb, np.ndarray): + assert lb.shape == shape + if isinstance(ub, np.ndarray): + assert ub.shape == shape + if isinstance(obj, np.ndarray): + assert obj.shape == shape + if isinstance(pricedVar, np.ndarray): + assert pricedVar.shape == shape + if isinstance(pricedVarScore, np.ndarray): + assert pricedVarScore.shape == shape + + if isinstance(shape, int): + ndim = 1 + else: + ndim = len(shape) + + matrix_variable = np.empty(shape, dtype=object) + + if isinstance(name, str): + matrix_names = np.full(shape, name, dtype=object) + if name != "": + for idx in np.ndindex(matrix_variable.shape): + matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" + else: + matrix_names = name + + if not isinstance(vtype, np.ndarray): + matrix_vtypes = np.full(shape, vtype, dtype=str) + else: + matrix_vtypes = vtype + + if not isinstance(lb, np.ndarray): + matrix_lbs = np.full(shape, lb, dtype=object) + else: + matrix_lbs = lb + + if not isinstance(ub, np.ndarray): + matrix_ubs = np.full(shape, ub, dtype=object) + else: + matrix_ubs = ub + + if not isinstance(obj, np.ndarray): + matrix_objs = np.full(shape, obj, dtype=float) + else: + matrix_objs = obj + + if not isinstance(pricedVar, np.ndarray): + matrix_priced_vars = np.full(shape, pricedVar, dtype=bool) + else: + matrix_priced_vars = pricedVar + + if not isinstance(pricedVarScore, np.ndarray): + matrix_priced_var_scores = np.full(shape, pricedVarScore, dtype=float) + else: + matrix_priced_var_scores = pricedVarScore + + for idx in np.ndindex(matrix_variable.shape): + matrix_variable[idx] = self.addVar(name=matrix_names[idx], vtype=matrix_vtypes[idx], lb=matrix_lbs[idx], + ub=matrix_ubs[idx], obj=matrix_objs[idx], pricedVar=matrix_priced_vars[idx], + pricedVarScore=matrix_priced_var_scores[idx]) + + return matrix_variable.view(MatrixVariable) + + def inferVarLbSym(self, Variable var, lb, SymComp symcomp, inferinfo, force=False): + """ + Tighten the lower bound of a variable, storing the symmetry component as reason for conflict analysis. + + Parameters + ---------- + var : Variable + lb : float + new lower bound + symcomp : SymComp + symmetry component that deduced the bound change + inferinfo : int + user information passed to symresprop() + force : bool, optional + force tightening even if below bound strengthening tolerance (Default value = False) + + Returns + ------- + infeasible : bool + tightened : bool + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPinferVarLbSym(self._scip, var.scip_var, lb, symcomp.scip_symcomp, inferinfo, force, + &infeasible, &tightened)) + return infeasible, tightened + + def inferVarUbSym(self, Variable var, ub, SymComp symcomp, inferinfo, force=False): + """ + Tighten the upper bound of a variable, storing the symmetry component as reason for conflict analysis. + + Parameters + ---------- + var : Variable + ub : float + new upper bound + symcomp : SymComp + symmetry component that deduced the bound change + inferinfo : int + user information passed to symresprop() + force : bool, optional + force tightening even if below bound strengthening tolerance (Default value = False) + + Returns + ------- + infeasible : bool + tightened : bool + + """ + cdef SCIP_Bool infeasible + cdef SCIP_Bool tightened + PY_SCIP_CALL(SCIPinferVarUbSym(self._scip, var.scip_var, ub, symcomp.scip_symcomp, inferinfo, force, + &infeasible, &tightened)) + return infeasible, tightened diff --git a/src/pyscipopt/nodesel.pxi b/src/pyscipopt/nodesel.pxi index 144549fe4..82bf760fd 100644 --- a/src/pyscipopt/nodesel.pxi +++ b/src/pyscipopt/nodesel.pxi @@ -1,7 +1,7 @@ ##@file nodesel.pxi #@brief Base class of the Nodesel Plugin cdef class Nodesel: - cdef public Model model + cdef public BaseModel model def nodefree(self): '''frees memory of node selector''' diff --git a/src/pyscipopt/presol.pxi b/src/pyscipopt/presol.pxi index 7f4096d98..2d1738063 100644 --- a/src/pyscipopt/presol.pxi +++ b/src/pyscipopt/presol.pxi @@ -1,7 +1,7 @@ ##@file presol.pxi #@brief Base class of the Presolver Plugin cdef class Presol: - cdef public Model model + cdef public BaseModel model def presolfree(self): '''frees memory of presolver''' diff --git a/src/pyscipopt/pricer.pxi b/src/pyscipopt/pricer.pxi index dbe19ff35..bca1f44d7 100644 --- a/src/pyscipopt/pricer.pxi +++ b/src/pyscipopt/pricer.pxi @@ -1,7 +1,7 @@ ##@file pricer.pxi #@brief Base class of the Pricers Plugin cdef class Pricer: - cdef public Model model + cdef public BaseModel model cdef SCIP_PRICER* scip_pricer def pricerfree(self): diff --git a/src/pyscipopt/propagator.pxi b/src/pyscipopt/propagator.pxi index 4601b6634..05d3bfe77 100644 --- a/src/pyscipopt/propagator.pxi +++ b/src/pyscipopt/propagator.pxi @@ -1,7 +1,7 @@ ##@file propagator.pxi #@brief Base class of the Propagators Plugin cdef class Prop: - cdef public Model model + cdef public BaseModel model def propfree(self): '''calls destructor and frees memory of propagator''' diff --git a/src/pyscipopt/reader.pxi b/src/pyscipopt/reader.pxi index 017c43eb9..8c0912272 100644 --- a/src/pyscipopt/reader.pxi +++ b/src/pyscipopt/reader.pxi @@ -1,7 +1,7 @@ ##@file reader.pxi #@brief Base class of the Reader Plugin cdef class Reader: - cdef public Model model + cdef public BaseModel model cdef public str name def readerfree(self): diff --git a/src/pyscipopt/relax.pxi b/src/pyscipopt/relax.pxi index a409f6230..15f1189bd 100644 --- a/src/pyscipopt/relax.pxi +++ b/src/pyscipopt/relax.pxi @@ -1,7 +1,7 @@ ##@file relax.pxi #@brief Base class of the Relaxator Plugin cdef class Relax: - cdef public Model model + cdef public BaseModel model cdef public str name def relaxfree(self): diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 277789ce9..e5ecb691d 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -417,6 +417,22 @@ cdef extern from "scip/scip.h": ctypedef struct SYM_GRAPH: pass + ctypedef enum SYM_SYMTYPE: + SYM_SYMTYPE_PERM + SYM_SYMTYPE_SIGNPERM + + ctypedef struct SCIP_SYMHDLR: + pass + + ctypedef struct SCIP_SYMHDLRDATA: + pass + + ctypedef struct SCIP_SYMCOMP: + pass + + ctypedef struct SCIP_SYMCOMPDATA: + pass + ctypedef struct SCIP_READER: pass @@ -590,6 +606,7 @@ cdef extern from "scip/scip.h": const char* suffix, SCIP_Bool globalcopy, SCIP_Bool enablepricing, + SCIP_Bool copysymhdlrs, SCIP_Bool threadsafe, SCIP_Bool passmessagehdlr, SCIP_Bool* valid) @@ -599,6 +616,7 @@ cdef extern from "scip/scip.h": SCIP_HASHMAP* consmap, const char* suffix, SCIP_Bool enablepricing, + SCIP_Bool copysymhdlrs, SCIP_Bool threadsafe, SCIP_Bool passmessagehdlr, SCIP_Bool* valid) @@ -759,6 +777,7 @@ cdef extern from "scip/scip.h": SCIP_Longint SCIPnodeGetNumber(SCIP_NODE* node) int SCIPnodeGetDepth(SCIP_NODE* node) SCIP_Real SCIPnodeGetLowerbound(SCIP_NODE* node) + SCIP_RATIONAL* SCIPnodeGetLowerboundExact(SCIP_NODE* node) SCIP_RETCODE SCIPupdateNodeLowerbound(SCIP* scip, SCIP_NODE* node, SCIP_Real newbound) SCIP_Real SCIPnodeGetEstimate(SCIP_NODE* node) SCIP_NODETYPE SCIPnodeGetType(SCIP_NODE* node) @@ -779,7 +798,7 @@ cdef extern from "scip/scip.h": void SCIPnodeGetAddedConss(SCIP_NODE* node, SCIP_CONS** addedconss, int* naddedconss, int addedconsssize) void SCIPnodeGetNDomchg(SCIP_NODE* node, int* nbranchings, int* nconsprop, - int* nprop) + int* nprop, int* nsymprop) SCIP_DOMCHG* SCIPnodeGetDomchg(SCIP_NODE* node) # Domain change methods @@ -1204,6 +1223,61 @@ cdef extern from "scip/scip.h": SCIP_PROPDATA* SCIPpropGetData (SCIP_PROP* prop) + # Symmetry handler plugin + SCIP_RETCODE SCIPincludeSymhdlr(SCIP* scip, + const char* name, + const char* desc, + int priority, + int proppriority, + int sepapriority, + int presolpriority, + int propfreq, + int sepafreq, + SCIP_Bool delayprop, + SCIP_Bool delaysepa, + SCIP_Real maxbounddist, + int maxprerounds, + SCIP_PROPTIMING proptiming, + SCIP_PRESOLTIMING presoltiming, + SCIP_RETCODE (*symhdlrtryadd) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SYM_SYMTYPE symtype, int** perms, int nperms, + SCIP_VAR** permvars, int npermvars, SCIP_Real* permvardomcenter, SCIP_HASHMAP* permvarmap, + SYM_GRAPH* symgraph, int id, SCIP_SYMCOMPDATA** symcompdata, int* naddedconss, + SCIP_Bool allowbdchgs, int* nchgbds, SCIP_Bool* success), + SCIP_RETCODE (*symcopy) (SCIP* scip, SCIP_SYMHDLR* symhdlr), + SCIP_RETCODE (*symfree) (SCIP* scip, SCIP_SYMHDLR* symhdlr), + SCIP_RETCODE (*syminit) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps), + SCIP_RETCODE (*symexit) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps), + SCIP_RETCODE (*syminitsol) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps), + SCIP_RETCODE (*symexitsol) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, SCIP_Bool restart), + SCIP_RETCODE (*symsepalp) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_RESULT* result, SCIP_Bool allowlocal, int depth), + SCIP_RETCODE (*symsepasol) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SOL* sol, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_RESULT* result, SCIP_Bool allowlocal, int depth), + SCIP_RETCODE (*symprop) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_PROPTIMING proptiming, SCIP_RESULT* result), + SCIP_RETCODE (*symresprop) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP* symcomp, SCIP_VAR* infervar, int inferinfo, + SCIP_BOUNDTYPE boundtype, SCIP_BDCHGIDX* bdchgidx, SCIP_Real relaxedbd, SCIP_RESULT* result), + SCIP_RETCODE (*sympresol) (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, int nrounds, + SCIP_PRESOLTIMING presoltiming, int nnewfixedvars, int nnewaggrvars, int nnewchgvartypes, + int nnewchgbds, int nnewholes, int nnewdelconss, int nnewaddconss, int nnewupgdconss, + int nnewchgcoefs, int nnewchgsides, int* nfixedvars, int* naggrvars, int* nchgvartypes, + int* nchgbds, int* naddholes, int* ndelconss, int* naddconss, int* nupgdconss, + int* nchgcoefs, int* nchgsides, SCIP_RESULT* result), + SCIP_SYMHDLRDATA* symhdlrdata) + + SCIP_SYMHDLRDATA* SCIPsymhdlrGetData(SCIP_SYMHDLR* symhdlr) + const char* SCIPsymhdlrGetName(SCIP_SYMHDLR* symhdlr) + SCIP_SYMHDLR* SCIPfindSymhdlr(SCIP* scip, const char* name) + SCIP_SYMHDLR** SCIPgetSymhdlrs(SCIP* scip) + int SCIPgetNSymhdlrs(SCIP* scip) + SCIP_SYMCOMPDATA* SCIPsymcompGetData(SCIP_SYMCOMP* symcomp) + SCIP_SYMHDLR* SCIPsymcompGetHdlr(SCIP_SYMCOMP* symcomp) + const char* SCIPsymcompGetName(SCIP_SYMCOMP* symcomp) + SCIP_RETCODE SCIPinferVarLbSym(SCIP* scip, SCIP_VAR* var, SCIP_Real newbound, SCIP_SYMCOMP* infersymcomp, int inferinfo, + SCIP_Bool force, SCIP_Bool* infeasible, SCIP_Bool* tightened) + SCIP_RETCODE SCIPinferVarUbSym(SCIP* scip, SCIP_VAR* var, SCIP_Real newbound, SCIP_SYMCOMP* infersymcomp, int inferinfo, + SCIP_Bool force, SCIP_Bool* infeasible, SCIP_Bool* tightened) + # Heuristics plugin SCIP_RETCODE SCIPincludeHeur(SCIP* scip, const char* name, @@ -1233,6 +1307,7 @@ cdef extern from "scip/scip.h": const char* name, const char* desc, int priority, + SCIP_Bool enable, SCIP_RETCODE (*iisfindercopy) (SCIP* scip, SCIP_IISFINDER* iisfinder), SCIP_RETCODE (*iisfinderfree) (SCIP* scip, SCIP_IISFINDER* iisfinder), SCIP_RETCODE (*iisfinderexec) (SCIP_IIS* iis, SCIP_IISFINDER* iisfinder, SCIP_RESULT* result), @@ -1458,6 +1533,50 @@ cdef extern from "scip/scip.h": SCIP_Bool SCIPallowNegSlack(SCIP* scip); SCIP_RETCODE SCIPbranchLPExact(SCIP* scip, SCIP_RESULT* result); SCIP_RETCODE SCIPaddRowExact(SCIP* scip, SCIP_ROWEXACT* rowexact); + SCIP_RETCODE SCIPaddVarExactData(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* lb, SCIP_RATIONAL* ub, SCIP_RATIONAL* obj) + SCIP_RETCODE SCIPchgVarObjExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newobj) + SCIP_RETCODE SCIPchgVarLbExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_RETCODE SCIPchgVarUbExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_Bool SCIPvarIsExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetObjExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetLbOriginalExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetUbOriginalExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetLbGlobalExact(SCIP_VAR* var) + SCIP_VARSTATUS SCIPvarGetStatusExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetUbGlobalExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetLbLocalExact(SCIP_VAR* var) + SCIP_RATIONAL* SCIPvarGetUbLocalExact(SCIP_VAR* var) + void SCIPvarGetLPSolExact(SCIP_VAR* var, SCIP_RATIONAL* res) + SCIP_COLEXACT* SCIPvarGetColExact(SCIP_VAR* var) + SCIP_RETCODE SCIPchgVarLbGlobalExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_RETCODE SCIPchgVarUbGlobalExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_RETCODE SCIPchgVarLbExactDive(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_RETCODE SCIPchgVarUbExactDive(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound) + SCIP_RETCODE SCIPstartExactDive(SCIP* scip) + SCIP_LPSOLSTAT SCIPgetLPExactSolstat(SCIP* scip) + SCIP_RETCODE SCIPprintRowExact(SCIP* scip, SCIP_ROWEXACT* row, FILE* file) + SCIP_RETCODE SCIPendExactDive(SCIP* scip) + SCIP_RETCODE SCIPsolveExactDiveLP(SCIP* scip, int itlim, SCIP_Bool* lperror, SCIP_Bool* cutoff) + SCIP_RETCODE SCIPfixVarExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* fixedval, SCIP_Bool* infeasible, SCIP_Bool* fixed) + SCIP_RETCODE SCIPtightenVarLbExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound, SCIP_Bool* infeasible, SCIP_Bool* tightened) + SCIP_RETCODE SCIPtightenVarUbExact(SCIP* scip, SCIP_VAR* var, SCIP_RATIONAL* newbound, SCIP_Bool* infeasible, SCIP_Bool* tightened) + SCIP_RETCODE SCIPaggregateVarsExact(SCIP* scip, SCIP_VAR* varx, SCIP_VAR* vary, SCIP_RATIONAL* scalarx, SCIP_RATIONAL* scalary, SCIP_RATIONAL* rhs, SCIP_Bool* infeasible, SCIP_Bool* redundant, SCIP_Bool* aggregated) + void SCIPgetSolValExact(SCIP* scip, SCIP_SOL* sol, SCIP_VAR* var, SCIP_RATIONAL* res) + void SCIPgetSolOrigObjExact(SCIP* scip, SCIP_SOL* sol, SCIP_RATIONAL* res) + SCIP_RETCODE SCIPcreateSolExact(SCIP* scip, SCIP_SOL** sol, SCIP_HEUR* heur) + SCIP_RETCODE SCIPcreateLPSolExact(SCIP* scip, SCIP_SOL** sol, SCIP_HEUR* heur) + SCIP_RETCODE SCIPsetSolValExact(SCIP* scip, SCIP_SOL* sol, SCIP_VAR* var, SCIP_RATIONAL* val) + SCIP_RETCODE SCIPprintSolExact(SCIP* scip, SCIP_SOL* sol, FILE* file, SCIP_Bool printzeros) + SCIP_RETCODE SCIPretransformSolExact(SCIP* scip, SCIP_SOL* sol) + SCIP_Bool SCIPsolIsExact(SCIP_SOL* sol) + void SCIPgetPrimalboundExact(SCIP* scip, SCIP_RATIONAL* result) + void SCIPgetDualboundExact(SCIP* scip, SCIP_RATIONAL* result) + void SCIPgetUpperboundExact(SCIP* scip, SCIP_RATIONAL* result) + void SCIPgetLowerboundExact(SCIP* scip, SCIP_RATIONAL* result) + SCIP_RATIONAL* SCIPgetCutoffboundExact(SCIP* scip) + void SCIPgetLPExactObjval(SCIP* scip, SCIP_RATIONAL* result) + SCIP_RETCODE SCIPaddOrigObjoffsetExact(SCIP* scip, SCIP_RATIONAL* addval) + SCIP_RATIONAL* SCIPgetOrigObjoffsetExact(SCIP* scip) # Exact LP SCIP methods SCIP_VAR* SCIPcolExactGetVar(SCIP_COLEXACT* col); @@ -1580,6 +1699,48 @@ cdef extern from "scip/scipdefplugins.h": cdef extern from "scip/bendersdefcuts.h": SCIP_RETCODE SCIPincludeBendersDefaultCuts(SCIP* scip, SCIP_BENDERS* benders) +cdef extern from "scip/rational.h": + SCIP_RETCODE SCIPrationalCreate(SCIP_RATIONAL** rational) + void SCIPrationalFree(SCIP_RATIONAL** rational) + void SCIPrationalSetString(SCIP_RATIONAL* res, const char* desc) + int SCIPrationalToString(SCIP_RATIONAL* rational, char* str, int strlen) + int SCIPrationalStrLen(SCIP_RATIONAL* rational) + +cdef extern from "scip/cons_exactlinear.h": + SCIP_RETCODE SCIPcreateConsExactLinear(SCIP* scip, + SCIP_CONS** cons, + const char* name, + int nvars, + SCIP_VAR** vars, + SCIP_RATIONAL** vals, + SCIP_RATIONAL* lhs, + SCIP_RATIONAL* rhs, + SCIP_Bool initial, + SCIP_Bool separate, + SCIP_Bool enforce, + SCIP_Bool check, + SCIP_Bool propagate, + SCIP_Bool local, + SCIP_Bool modifiable, + SCIP_Bool dynamic, + SCIP_Bool removable, + SCIP_Bool stickingatnode) + SCIP_RETCODE SCIPaddCoefExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_VAR* var, SCIP_RATIONAL* val) + SCIP_RETCODE SCIPchgCoefExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_VAR* var, SCIP_RATIONAL* val) + SCIP_RETCODE SCIPchgLhsExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_RATIONAL* lhs) + SCIP_RETCODE SCIPchgRhsExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_RATIONAL* rhs) + SCIP_RATIONAL* SCIPgetLhsExactLinear(SCIP* scip, SCIP_CONS* cons) + SCIP_RATIONAL* SCIPgetRhsExactLinear(SCIP* scip, SCIP_CONS* cons) + SCIP_RATIONAL** SCIPgetValsExactLinear(SCIP* scip, SCIP_CONS* cons) + SCIP_VAR** SCIPgetVarsExactLinear(SCIP* scip, SCIP_CONS* cons) + int SCIPgetNVarsExactLinear(SCIP* scip, SCIP_CONS* cons) + SCIP_RETCODE SCIPdelCoefExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_VAR* var) + SCIP_ROW* SCIPgetRowExactLinear(SCIP* scip, SCIP_CONS* cons) + SCIP_ROWEXACT* SCIPgetRowExactExactLinear(SCIP* scip, SCIP_CONS* cons) + void SCIPgetFpDualsolExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_RATIONAL* ret) + void SCIPgetFpDualfarkasExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_RATIONAL* ret) + SCIP_RETCODE SCIPgetActivityExactLinear(SCIP* scip, SCIP_CONS* cons, SCIP_SOL* sol, SCIP_RATIONAL* ret) + cdef extern from "scip/cons_linear.h": SCIP_RETCODE SCIPcreateConsLinear(SCIP* scip, SCIP_CONS** cons, @@ -2284,6 +2445,9 @@ cdef class Variable(Expr): @staticmethod cdef create(SCIP_VAR* scipvar) +cdef class ExactVariable(Variable): + pass + cdef class Constraint: cdef SCIP_CONS* scip_cons # can be used to store problem data @@ -2298,7 +2462,13 @@ cdef class IIS: @staticmethod cdef create(SCIP_IIS* iis) -cdef class Model: +cdef class SymComp: + cdef SCIP_SYMCOMP* scip_symcomp + + @staticmethod + cdef create(SCIP_SYMCOMP* scip_symcomp) + +cdef class BaseModel: cdef SCIP* _scip cdef SCIP_Bool* _valid # store best solution to get the solution values easier @@ -2329,6 +2499,7 @@ cdef class Model: # helper methods for later var and cons cleanup cdef _getOrCreateCons(self, SCIP_CONS* scip_cons) cdef _getOrCreateVar(self, SCIP_VAR* scip_var) + cdef _configureScip(self) cdef _free_scip_instance(self) cdef _ensureFreshBestSol(self) @@ -2339,3 +2510,9 @@ cdef class Model: @staticmethod cdef create(SCIP* scip) + +cdef class Model(BaseModel): + pass + +cdef class ExactModel(BaseModel): + pass diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index a849a30b3..2833fcdf8 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -18,6 +18,7 @@ from posix.stdio cimport fileno from collections.abc import Iterable from itertools import repeat from dataclasses import dataclass +from fractions import Fraction from typing import Union import numpy as np @@ -36,6 +37,7 @@ include "presol.pxi" include "pricer.pxi" include "propagator.pxi" include "sepa.pxi" +include "symhdlr.pxi" include "reader.pxi" include "relax.pxi" include "nodesel.pxi" @@ -64,8 +66,14 @@ cdef extern from "scip/config.h": #else #define PYSCIPOPT_WITH_DEBUG_SOLUTION 0 #endif + #ifdef SCIP_WITH_EXACTSOLVE + #define PYSCIPOPT_WITH_EXACTSOLVE 1 + #else + #define PYSCIPOPT_WITH_EXACTSOLVE 0 + #endif """ bint PYSCIPOPT_WITH_DEBUG_SOLUTION + bint PYSCIPOPT_WITH_EXACTSOLVE # Mapping the SCIP_RESULT enum to a python class # This is required to return SCIP_RESULT in the python code @@ -487,8552 +495,3774 @@ cdef class Event: return (self.__class__ == other.__class__ and self.event == (other).event) -cdef class Column: - """Base class holding a pointer to corresponding SCIP_COL.""" + +cdef class Solution: + """Base class holding a pointer to corresponding SCIP_SOL.""" + + # We are raising an error here to avoid creating a solution without an associated model. See Issue #625 + def __init__(self, raise_error = True): + if raise_error: + raise ValueError("To create a solution you should use the createSol method of the Model class.") @staticmethod - cdef create(SCIP_COL* scipcol): + cdef create(SCIP* scip, SCIP_SOL* scip_sol): """ - Main method for creating a Column class. Is used instead of __init__. + Main method for creating a Solution class. Please use createSol method of the Model class + when wanting to create a Solution as a user. Parameters ---------- - scipcol : SCIP_COL* - A pointer to the SCIP_COL + scip : SCIP* + A pointer to the SCIP object + scip_sol : SCIP_SOL* + A pointer to the SCIP_SOL Returns ------- - col : Column - The Python representative of the SCIP_COL + sol : Solution + The Python representative of the SCIP_SOL """ - if scipcol == NULL: - raise Warning("cannot create Column with SCIP_COL* == NULL") - col = Column() - col.scip_col = scipcol - return col + if scip == NULL: + raise Warning("cannot create Solution with SCIP* == NULL") + sol = Solution(raise_error=False) + sol.sol = scip_sol + sol.scip = scip + return sol + + def __getitem__( + self, + expr: Union[Expr, GenExpr, MatrixExpr], + ) -> Union[float, np.ndarray]: + if not isinstance(expr, (Expr, GenExpr, MatrixExpr)): + raise TypeError( + "Argument 'expr' has incorrect type, expected 'Expr', 'GenExpr', or " + f"'MatrixExpr', got {type(expr).__name__!r}" + ) + + self._checkStage("SCIPgetSolVal") + return expr._evaluate(self) + + def __setitem__(self, Variable var, value): + PY_SCIP_CALL(SCIPsetSolVal(self.scip, self.sol, var.scip_var, value)) + + def __repr__(self): + cdef SCIP_VAR* scip_var + cdef int i + vals = {} + self._checkStage("SCIPgetSolVal") + for i in range(SCIPgetNOrigVars(self.scip)): + scip_var = SCIPgetOrigVars(self.scip)[i] + # extract name + cname = bytes(SCIPvarGetName(scip_var)) + name = cname.decode('utf-8') + vals[name] = SCIPgetSolVal(self.scip, self.sol, scip_var) + return str(vals) + + def _checkStage(self, method): + if method in ["SCIPgetSolVal", "getSolObjVal"]: + stage_check = SCIPgetStage(self.scip) not in [SCIP_STAGE_INIT, SCIP_STAGE_FREE] + if not stage_check or self.sol == NULL and SCIPgetStage(self.scip) != SCIP_STAGE_SOLVING: + raise Warning(f"{method} can only be called with a valid solution or in stage SOLVING (current stage: {SCIPgetStage(self.scip)})") - def getLPPos(self): + def getOrigin(self): """ - Gets position of column in current LP, or -1 if it is not in LP. + Returns origin of solution: where to retrieve uncached elements. Returns ------- - int - + PY_SCIP_SOLORIGIN """ - return SCIPcolGetLPPos(self.scip_col) + return SCIPsolGetOrigin(self.sol) - def getBasisStatus(self): + def isExact(self): """ - Gets the basis status of a column in the LP solution + Returns whether the solution has exact (rational) values. Returns ------- - str - Possible values are "lower", "basic", "upper", and "zero" - - Raises - ------ - Exception - If SCIP returns an unknown basis status + bool + """ + return self.sol != NULL and SCIPsolIsExact(self.sol) - Notes - ----- - Returns basis status "zero" for columns not in the current SCIP LP. - - """ - cdef SCIP_BASESTAT stat = SCIPcolGetBasisStatus(self.scip_col) - if stat == SCIP_BASESTAT_LOWER: - return "lower" - elif stat == SCIP_BASESTAT_BASIC: - return "basic" - elif stat == SCIP_BASESTAT_UPPER: - return "upper" - elif stat == SCIP_BASESTAT_ZERO: - return "zero" + def retransform(self): + """ retransforms solution to original problem space """ + if SCIPsolIsExact(self.sol): + PY_SCIP_CALL(SCIPretransformSolExact(self.scip, self.sol)) else: - raise Exception('SCIP returned unknown base status!') + PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) - def isIntegral(self): + def translate(self, BaseModel target): """ - Returns whether the associated variable is of integral type (binary, integer, implicit integer). + translate solution to a target model solution + + Parameters + ---------- + target : Model Returns ------- - bool - + targetSol: Solution """ - return SCIPcolIsIntegral(self.scip_col) + if self.getOrigin() != SCIP_SOLORIGIN_ORIGINAL: + PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) + cdef Solution targetSol = Solution.create(target._scip, NULL) + cdef SCIP_VAR** source_vars = SCIPgetOrigVars(self.scip) + PY_SCIP_CALL(SCIPtranslateSubSol(target._scip, self.scip, self.sol, NULL, source_vars, &(targetSol.sol))) + return targetSol - def getVar(self): +cdef class BoundChange: + """Bound change.""" + + @staticmethod + cdef create(SCIP_BOUNDCHG* scip_boundchg): """ - Gets variable this column represents. + Main method for creating a BoundChange class. Is used instead of __init__. + + Parameters + ---------- + scip_boundchg : SCIP_BOUNDCHG* + A pointer to the SCIP_BOUNDCHG Returns ------- - Variable + boundchg : BoundChange + The Python representative of the SCIP_BOUNDCHG """ - cdef SCIP_VAR* var = SCIPcolGetVar(self.scip_col) - return Variable.create(var) + if scip_boundchg == NULL: + raise Warning("cannot create BoundChange with SCIP_BOUNDCHG* == NULL") + boundchg = BoundChange() + boundchg.scip_boundchg = scip_boundchg + return boundchg - def getPrimsol(self): + def getNewBound(self): """ - Gets the primal LP solution of a column. + Returns the new value of the bound in the bound change. Returns ------- float """ - return SCIPcolGetPrimsol(self.scip_col) + return SCIPboundchgGetNewbound(self.scip_boundchg) - def getLb(self): + def getVar(self): """ - Gets lower bound of column. + Returns the variable of the bound change. Returns ------- - float + Variable """ - return SCIPcolGetLb(self.scip_col) + return Variable.create(SCIPboundchgGetVar(self.scip_boundchg)) - def getUb(self): + def getBoundchgtype(self): """ - Gets upper bound of column. + Returns the bound change type of the bound change. Returns ------- - float + int + (0 = branching, 1 = consinfer, 2 = propinfer) """ - return SCIPcolGetUb(self.scip_col) + return SCIPboundchgGetBoundchgtype(self.scip_boundchg) - def getObjCoeff(self): + def getBoundtype(self): """ - Gets objective value coefficient of a column. + Returns the bound type of the bound change. Returns ------- - float + int + (0 = lower, 1 = upper) """ - return SCIPcolGetObj(self.scip_col) + return SCIPboundchgGetBoundtype(self.scip_boundchg) - def getAge(self): + def isRedundant(self): """ - Gets the age of the column, i.e., the total number of successive times a column was in the LP - and was 0.0 in the solution. + Returns whether the bound change is redundant due to a more global bound that is at least as strong. Returns ------- - int + bool """ - return SCIPcolGetAge(self.scip_col) - - def __hash__(self): - return hash(self.scip_col) + return SCIPboundchgIsRedundant(self.scip_boundchg) - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self.scip_col == (other).scip_col) + def __repr__(self): + return f"{self.getVar()} {_SCIP_BOUNDTYPE_TO_STRING[self.getBoundtype()]} {self.getNewBound()}" -cdef class ColumnExact: - """Base class holding a pointer to corresponding SCIP_COLEXACT.""" +cdef class DomainChanges: + """Set of domain changes.""" @staticmethod - cdef create(SCIP_COLEXACT* scipcolexact): + cdef create(SCIP_DOMCHG* scip_domchg): """ - Main method for creating a ColumnExact class. Is used instead of __init__. + Main method for creating a DomainChanges class. Is used instead of __init__. Parameters ---------- - scipcolexact : SCIP_COLEXACT* - A pointer to the SCIP_COLEXACT + scip_domchg : SCIP_DOMCHG* + A pointer to the SCIP_DOMCHG + + Returns + ------- + domchg : DomainChanges + The Python representative of the SCIP_DOMCHG + + """ + if scip_domchg == NULL: + raise Warning("cannot create DomainChanges with SCIP_DOMCHG* == NULL") + domchg = DomainChanges() + domchg.scip_domchg = scip_domchg + return domchg + + def getBoundchgs(self): + """ + Returns the bound changes in the domain change. Returns ------- - col : ColumnExact - The Python representative of the SCIP_COLEXACT + list of BoundChange """ - if scipcolexact == NULL: - raise Warning("cannot create ColumnExact with SCIP_COLEXACT* == NULL") - col = ColumnExact() - col.scip_col_exact = scipcolexact - return col + cdef int nboundchgs = SCIPdomchgGetNBoundchgs(self.scip_domchg) + cdef int i + return [BoundChange.create(SCIPdomchgGetBoundchg(self.scip_domchg, i)) + for i in range(nboundchgs)] -cdef class Row: - """Base class holding a pointer to corresponding SCIP_ROW.""" +cdef class Node: + """Base class holding a pointer to corresponding SCIP_NODE""" @staticmethod - cdef create(SCIP_ROW* sciprow): + cdef create(SCIP_NODE* scipnode): """ - Main method for creating a Row class. Is used instead of __init__. + Main method for creating a Node class. Is used instead of __init__. Parameters ---------- - sciprow : SCIP_ROW* - A pointer to the SCIP_ROW + scipnode : SCIP_NODE* + A pointer to the SCIP_NODE Returns ------- - row : Row - The Python representative of the SCIP_ROW + node : Node + The Python representative of the SCIP_NODE """ - if sciprow == NULL: - raise Warning("cannot create Row with SCIP_ROW* == NULL") - row = Row() - row.scip_row = sciprow - return row - - @property - def name(self): - return bytes(SCIProwGetName(self.scip_row)).decode("utf-8") + if scipnode == NULL: + return None + node = Node() + node.scip_node = scipnode + return node - def getLhs(self): + def getParent(self): """ - Returns the left hand side of row. + Retrieve parent node (or None if the node has no parent node). Returns ------- - float + Node """ - return SCIProwGetLhs(self.scip_row) + return Node.create(SCIPnodeGetParent(self.scip_node)) - def getRhs(self): + def getNumber(self): """ - Returns the right hand side of row. + Retrieve number of node. Returns ------- - float + int """ - return SCIProwGetRhs(self.scip_row) + return SCIPnodeGetNumber(self.scip_node) - def getConstant(self): + def getDepth(self): """ - Gets constant shift of row. + Retrieve depth of node. Returns ------- - float + int """ - return SCIProwGetConstant(self.scip_row) + return SCIPnodeGetDepth(self.scip_node) - def getDualsol(self): + def getType(self): """ - Returns the dual solution of row. + Retrieve type of node. Returns ------- - float + PY_SCIP_NODETYPE """ - return SCIProwGetDualsol(self.scip_row) + return SCIPnodeGetType(self.scip_node) - def getDualfarkas(self): + def getLowerbound(self): """ - Returns the dual Farkas solution of row. + Retrieve lower bound of node. Returns ------- - float + float or Fraction + a Fraction (or -inf) when the node belongs to an exact model """ - return SCIProwGetDualfarkas(self.scip_row) + cdef SCIP_RATIONAL* exact = SCIPnodeGetLowerboundExact(self.scip_node) - def getLPPos(self): + if exact != NULL: + return _fromRational(exact) + return SCIPnodeGetLowerbound(self.scip_node) + + def getEstimate(self): """ - Gets position of row in current LP, or -1 if it is not in LP. + Retrieve the estimated value of the best feasible solution in subtree of the node. Returns ------- - int + float """ - return SCIProwGetLPPos(self.scip_row) + return SCIPnodeGetEstimate(self.scip_node) - def getBasisStatus(self): + def getAddedConss(self): """ - Gets the basis status of a row in the LP solution. + Retrieve all constraints added at this node. Returns ------- - str - Possible values are "lower", "basic", and "upper" - - Raises - ------ - Exception - If SCIP returns an unknown or "zero" basis status + list of Constraint - Notes - ----- - Returns basis status "basic" for rows not in the current SCIP LP. - - """ - cdef SCIP_BASESTAT stat = SCIProwGetBasisStatus(self.scip_row) - if stat == SCIP_BASESTAT_LOWER: - return "lower" - elif stat == SCIP_BASESTAT_BASIC: - return "basic" - elif stat == SCIP_BASESTAT_UPPER: - return "upper" - elif stat == SCIP_BASESTAT_ZERO: - # this shouldn't happen! - raise Exception('SCIP returned base status zero for a row!') - else: - raise Exception('SCIP returned unknown base status!') + """ + cdef int addedconsssize = SCIPnodeGetNAddedConss(self.scip_node) + if addedconsssize == 0: + return [] + cdef SCIP_CONS** addedconss = malloc(addedconsssize * sizeof(SCIP_CONS*)) + cdef int nconss + cdef int i + SCIPnodeGetAddedConss(self.scip_node, addedconss, &nconss, addedconsssize) + assert nconss == addedconsssize + constraints = [Constraint.create(addedconss[i]) for i in range(nconss)] + free(addedconss) + return constraints - def isIntegral(self): + def getNAddedConss(self): """ - Returns TRUE iff the activity of the row (without the row's constant) - is always integral in a feasible solution. + Retrieve number of added constraints at this node. Returns ------- - bool + int """ - return SCIProwIsIntegral(self.scip_row) + return SCIPnodeGetNAddedConss(self.scip_node) - def isLocal(self): + def isActive(self): """ - Returns TRUE iff the row is only valid locally. + Is the node in the path to the current node? Returns ------- bool """ - return SCIProwIsLocal(self.scip_row) + return SCIPnodeIsActive(self.scip_node) - def isModifiable(self): + def isPropagatedAgain(self): """ - Returns TRUE iff row is modifiable during node processing (subject to column generation). + Is the node marked to be propagated again? Returns ------- bool """ - return SCIProwIsModifiable(self.scip_row) + return SCIPnodeIsPropagatedAgain(self.scip_node) - def isRemovable(self): + def getNParentBranchings(self): """ - Returns TRUE iff row is removable from the LP (due to aging or cleanup). + Retrieve the number of variable branchings that were performed in the parent node to create this node. Returns ------- - bool + int """ - return SCIProwIsRemovable(self.scip_row) + cdef SCIP_VAR* dummy_branchvars + cdef SCIP_Real dummy_branchbounds + cdef SCIP_BOUNDTYPE dummy_boundtypes + cdef int nbranchvars + # This is a hack: the SCIP interface has no function to directly get the + # number of parent branchings, i.e., SCIPnodeGetNParentBranchings() does + # not exist. + SCIPnodeGetParentBranchings(self.scip_node, &dummy_branchvars, + &dummy_branchbounds, &dummy_boundtypes, + &nbranchvars, 0) + return nbranchvars - def isInGlobalCutpool(self): + def getParentBranchings(self): """ - Return TRUE iff row is a member of the global cut pool. + Retrieve the set of variable branchings that were performed in the parent node to create this node. Returns ------- - bool + list of Variable + list of float + list of int """ - return SCIProwIsInGlobalCutpool(self.scip_row) + cdef int nbranchvars = self.getNParentBranchings() + if nbranchvars == 0: + return None + cdef SCIP_VAR** branchvars = malloc(nbranchvars * sizeof(SCIP_VAR*)) + cdef SCIP_Real* branchbounds = malloc(nbranchvars * sizeof(SCIP_Real)) + cdef SCIP_BOUNDTYPE* boundtypes = malloc(nbranchvars * sizeof(SCIP_BOUNDTYPE)) + cdef int i + SCIPnodeGetParentBranchings(self.scip_node, branchvars, branchbounds, + boundtypes, &nbranchvars, nbranchvars) + + py_variables = [Variable.create(branchvars[i]) for i in range(nbranchvars)] + py_branchbounds = [branchbounds[i] for i in range(nbranchvars)] + py_boundtypes = [boundtypes[i] for i in range(nbranchvars)] + free(boundtypes) + free(branchbounds) + free(branchvars) + return py_variables, py_branchbounds, py_boundtypes - def getOrigintype(self): + def getNDomchg(self): """ - Returns type of origin that created the row. + Retrieve the number of bound changes due to branching, constraint propagation, and propagation. Returns ------- - PY_SCIP_ROWORIGINTYPE + nbranchings : int + nconsprop : int + nprop : int """ - return SCIProwGetOrigintype(self.scip_row) + cdef int nbranchings + cdef int nconsprop + cdef int nprop + SCIPnodeGetNDomchg(self.scip_node, &nbranchings, &nconsprop, &nprop, NULL) + return nbranchings, nconsprop, nprop - def getConsOriginConshdlrtype(self): + def getDomchg(self): """ - Returns type of constraint handler that created the row. + Retrieve domain changes for this node. Returns ------- - str + DomainChanges """ - cdef SCIP_CONS* scip_con = SCIProwGetOriginCons(self.scip_row) - return bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(scip_con))).decode('UTF-8') + cdef SCIP_DOMCHG* domchg = SCIPnodeGetDomchg(self.scip_node) + if domchg == NULL: + return None + return DomainChanges.create(domchg) + + def __hash__(self): + return hash(self.scip_node) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self.scip_node == (other).scip_node) + +cdef class Variable(Expr): + """Is a linear expression and has SCIP_VAR*""" - def getNNonz(self): + @staticmethod + cdef create(SCIP_VAR* scipvar): """ - Get number of nonzero entries in row vector. + Main method for creating a Variable class. Is used instead of __init__. + + Parameters + ---------- + scipvar : SCIP_VAR* + A pointer to the SCIP_VAR Returns ------- - int + var : Variable + The Python representative of the SCIP_VAR """ - return SCIProwGetNNonz(self.scip_row) + if scipvar == NULL: + raise Warning("cannot create Variable with SCIP_VAR* == NULL") + var = ExactVariable() if SCIPvarIsExact(scipvar) else Variable() + var.scip_var = scipvar + Expr.__init__(var, {Term(var) : 1.0}) + return var + + @property + def name(self): + if self.scip_var == NULL: + return "" + return bytes(SCIPvarGetName(self.scip_var)).decode("utf-8") + + cdef Variable copy(self, bint copy=True): + return self + + def ptr(self): + return (self.scip_var) + + def __repr__(self): + return self.name - def getNLPNonz(self): + def vtype(self): """ - Get number of nonzero entries in row vector that correspond to columns currently in the SCIP LP. + Retrieve the variables type (BINARY, INTEGER, CONTINUOUS, or IMPLINT) Returns ------- - int + str + "BINARY", "INTEGER", "CONTINUOUS", or "IMPLINT" """ - return SCIProwGetNLPNonz(self.scip_row) - - def getCols(self): + vartype = SCIPvarGetType(self.scip_var) + if vartype == SCIP_VARTYPE_BINARY: + return "BINARY" + elif vartype == SCIP_VARTYPE_INTEGER: + return "INTEGER" + elif vartype == SCIP_VARTYPE_CONTINUOUS: + return "CONTINUOUS" + elif vartype == SCIP_DEPRECATED_VARTYPE_IMPLINT: + return "IMPLINT" + + def isBinary(self): """ - Gets list with columns of nonzero entries + Returns whether variable is of BINARY type. Returns ------- - list of Column - + bool """ - cdef SCIP_COL** cols = SCIProwGetCols(self.scip_row) - cdef int i - return [Column.create(cols[i]) for i in range(self.getNNonz())] + return SCIPvarIsBinary(self.scip_var) + + def isIntegral(self): + """ + Returns whether variable is of INTEGER type. - def getVals(self): + Returns + ------- + bool + """ + return SCIPvarIsIntegral(self.scip_var) + + def isImpliedIntegral(self): """ - Gets list with coefficients of nonzero entries. + Returns whether variable is implied integral (weakly or strongly). Returns ------- - list of int + bool + """ + return SCIPvarIsImpliedIntegral(self.scip_var) + + def isNonImpliedIntegral(self): + """ + Returns TRUE if the variable is integral, but not implied integral.. + Returns + ------- + bool """ - cdef SCIP_Real* vals = SCIProwGetVals(self.scip_row) - cdef int i - return [vals[i] for i in range(self.getNNonz())] + return SCIPvarIsNonimpliedIntegral(self.scip_var) - def getAge(self): + def getImplType(self): """ - Gets the age of the row. (The consecutive times the row has been non-active in the LP). + Returns the implied integral type of the variable Returns ------- - int - + PY_SCIP_IMPLINTTYPE """ - return SCIProwGetAge(self.scip_row) + return SCIPvarGetImplType(self.scip_var) - def getNorm(self): + def getStatus(self): """ - Gets Euclidean norm of row vector. + Retrieve the variable status (ORIGINAL, LOOSE, COLUMN, FIXED, AGGREGATED, MULTAGGR, NEGATED) Returns ------- - float + str + "ORIGINAL", "LOOSE", "COLUMN", "FIXED", "AGGREGATED", "MULTAGGR", "NEGATED" """ - return SCIProwGetNorm(self.scip_row) - - def __hash__(self): - return hash(self.scip_row) + varstatus = SCIPvarGetStatus(self.scip_var) + if varstatus == SCIP_VARSTATUS_ORIGINAL: + return "ORIGINAL" + elif varstatus == SCIP_VARSTATUS_LOOSE: + return "LOOSE" + elif varstatus == SCIP_VARSTATUS_COLUMN: + return "COLUMN" + elif varstatus == SCIP_VARSTATUS_FIXED: + return "FIXED" + elif varstatus == SCIP_VARSTATUS_AGGREGATED: + return "AGGREGATED" + elif varstatus == SCIP_VARSTATUS_MULTAGGR: + return "MULTAGGR" + elif varstatus == SCIP_VARSTATUS_NEGATED: + return "NEGATED" - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self.scip_row == (other).scip_row) + def isOriginal(self): + """ + Retrieve whether the variable belongs to the original problem -cdef class RowExact: - """Base class holding a pointer to corresponding SCIP_ROW.""" + Returns + ------- + bool - @staticmethod - cdef create(SCIP_ROWEXACT* sciprowexact): """ - Main method for creating a RowExact class. Is used instead of __init__. + return SCIPvarIsOriginal(self.scip_var) - Parameters - ---------- - sciprow : SCIP_ROWEXACT* - A pointer to the SCIP_ROWEXACT + def isActive(self): + """ + Retrieve whether the variable is active Returns ------- - row : Row - The Python representative of the SCIP_ROWEXACT + bool """ - if sciprowexact == NULL: - raise Warning("cannot create Row with SCIP_ROWEXACT* == NULL") - row_exact = RowExact() - row_exact.scip_row_exact = sciprowexact - return row_exact - -cdef class NLRow: - """Base class holding a pointer to corresponding SCIP_NLROW.""" + return SCIPvarIsActive(self.scip_var) - @staticmethod - cdef create(SCIP_NLROW* scipnlrow): + def isInLP(self): """ - Main method for creating a NLRow class. Is used instead of __init__. - - Parameters - ---------- - scipnlrow : SCIP_NLROW* - A pointer to the SCIP_NLROW + Retrieve whether the variable is a COLUMN variable that is member of the current LP. Returns ------- - nlrow : NLRow - The Python representative of the SCIP_NLROW + bool """ - if scipnlrow == NULL: - raise Warning("cannot create NLRow with SCIP_NLROW* == NULL") - nlrow = NLRow() - nlrow.scip_nlrow = scipnlrow - return nlrow - - @property - def name(self): - return bytes(SCIPnlrowGetName(self.scip_nlrow)).decode("utf-8") + return SCIPvarIsInLP(self.scip_var) - def getConstant(self): + def getIndex(self): """ - Returns the constant of a nonlinear row. + Retrieve the unique index of the variable. Returns ------- - float + int """ - return SCIPnlrowGetConstant(self.scip_nlrow) + return SCIPvarGetIndex(self.scip_var) - def getLinearTerms(self): + def getCol(self): """ - Returns a list of tuples (var, coef) representing the linear part of a nonlinear row. + Retrieve column of COLUMN variable. Returns ------- - list of tuple + Column """ - cdef SCIP_VAR** linvars = SCIPnlrowGetLinearVars(self.scip_nlrow) - cdef SCIP_Real* lincoefs = SCIPnlrowGetLinearCoefs(self.scip_nlrow) - cdef int nlinvars = SCIPnlrowGetNLinearVars(self.scip_nlrow) - cdef int i - return [(Variable.create(linvars[i]), lincoefs[i]) for i in range(nlinvars)] + cdef SCIP_COL* scip_col + scip_col = SCIPvarGetCol(self.scip_var) + return Column.create(scip_col) - def getLhs(self): + def getLbOriginal(self): """ - Returns the left hand side of a nonlinear row. + Retrieve original lower bound of variable. Returns ------- float """ - return SCIPnlrowGetLhs(self.scip_nlrow) + return SCIPvarGetLbOriginal(self.scip_var) - def getRhs(self): + def getUbOriginal(self): """ - Returns the right hand side of a nonlinear row. + Retrieve original upper bound of variable. Returns ------- float """ - return SCIPnlrowGetRhs(self.scip_nlrow) + return SCIPvarGetUbOriginal(self.scip_var) - def getDualsol(self): + def getLbGlobal(self): """ - Gets the dual NLP solution of a nonlinear row. + Retrieve global lower bound of variable. Returns ------- float """ - return SCIPnlrowGetDualsol(self.scip_nlrow) - - def __hash__(self): - return hash(self.scip_nlrow) - - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self.scip_nlrow == (other).scip_nlrow) + return SCIPvarGetLbGlobal(self.scip_var) -cdef class Solution: - """Base class holding a pointer to corresponding SCIP_SOL.""" + def getUbGlobal(self): + """ + Retrieve global upper bound of variable. - # We are raising an error here to avoid creating a solution without an associated model. See Issue #625 - def __init__(self, raise_error = True): - if raise_error: - raise ValueError("To create a solution you should use the createSol method of the Model class.") + Returns + ------- + float - @staticmethod - cdef create(SCIP* scip, SCIP_SOL* scip_sol): """ - Main method for creating a Solution class. Please use createSol method of the Model class - when wanting to create a Solution as a user. + return SCIPvarGetUbGlobal(self.scip_var) - Parameters - ---------- - scip : SCIP* - A pointer to the SCIP object - scip_sol : SCIP_SOL* - A pointer to the SCIP_SOL + def getLbLocal(self): + """ + Retrieve current lower bound of variable. Returns ------- - sol : Solution - The Python representative of the SCIP_SOL + float """ - if scip == NULL: - raise Warning("cannot create Solution with SCIP* == NULL") - sol = Solution(raise_error=False) - sol.sol = scip_sol - sol.scip = scip - return sol - - def __getitem__( - self, - expr: Union[Expr, GenExpr, MatrixExpr], - ) -> Union[float, np.ndarray]: - if not isinstance(expr, (Expr, GenExpr, MatrixExpr)): - raise TypeError( - "Argument 'expr' has incorrect type, expected 'Expr', 'GenExpr', or " - f"'MatrixExpr', got {type(expr).__name__!r}" - ) - - self._checkStage("SCIPgetSolVal") - return expr._evaluate(self) - - def __setitem__(self, Variable var, value): - PY_SCIP_CALL(SCIPsetSolVal(self.scip, self.sol, var.scip_var, value)) - - def __repr__(self): - cdef SCIP_VAR* scip_var - cdef int i - vals = {} - self._checkStage("SCIPgetSolVal") - for i in range(SCIPgetNOrigVars(self.scip)): - scip_var = SCIPgetOrigVars(self.scip)[i] - # extract name - cname = bytes(SCIPvarGetName(scip_var)) - name = cname.decode('utf-8') - vals[name] = SCIPgetSolVal(self.scip, self.sol, scip_var) - return str(vals) - - def _checkStage(self, method): - if method in ["SCIPgetSolVal", "getSolObjVal"]: - stage_check = SCIPgetStage(self.scip) not in [SCIP_STAGE_INIT, SCIP_STAGE_FREE] - if not stage_check or self.sol == NULL and SCIPgetStage(self.scip) != SCIP_STAGE_SOLVING: - raise Warning(f"{method} can only be called with a valid solution or in stage SOLVING (current stage: {SCIPgetStage(self.scip)})") + return SCIPvarGetLbLocal(self.scip_var) - def getOrigin(self): + def getUbLocal(self): """ - Returns origin of solution: where to retrieve uncached elements. + Retrieve current upper bound of variable. Returns ------- - PY_SCIP_SOLORIGIN - """ - return SCIPsolGetOrigin(self.sol) - - def retransform(self): - """ retransforms solution to original problem space """ - PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) + float - def translate(self, Model target): """ - translate solution to a target model solution + return SCIPvarGetUbLocal(self.scip_var) - Parameters - ---------- - target : Model + def getObj(self): + """ + Retrieve current objective value of variable. Returns ------- - targetSol: Solution - """ - if self.getOrigin() != SCIP_SOLORIGIN_ORIGINAL: - PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) - cdef Solution targetSol = Solution.create(target._scip, NULL) - cdef SCIP_VAR** source_vars = SCIPgetOrigVars(self.scip) - PY_SCIP_CALL(SCIPtranslateSubSol(target._scip, self.scip, self.sol, NULL, source_vars, &(targetSol.sol))) - return targetSol - -cdef class BoundChange: - """Bound change.""" + float - @staticmethod - cdef create(SCIP_BOUNDCHG* scip_boundchg): """ - Main method for creating a BoundChange class. Is used instead of __init__. + return SCIPvarGetObj(self.scip_var) - Parameters - ---------- - scip_boundchg : SCIP_BOUNDCHG* - A pointer to the SCIP_BOUNDCHG + def getLPSol(self): + """ + Retrieve the current LP solution value of variable. Returns ------- - boundchg : BoundChange - The Python representative of the SCIP_BOUNDCHG + float """ - if scip_boundchg == NULL: - raise Warning("cannot create BoundChange with SCIP_BOUNDCHG* == NULL") - boundchg = BoundChange() - boundchg.scip_boundchg = scip_boundchg - return boundchg + return SCIPvarGetLPSol(self.scip_var) - def getNewBound(self): + def getAvgSol(self): """ - Returns the new value of the bound in the bound change. + Get the weighted average solution of variable in all feasible primal solutions found. Returns ------- float """ - return SCIPboundchgGetNewbound(self.scip_boundchg) + return SCIPvarGetAvgSol(self.scip_var) - def getVar(self): + def markRelaxationOnly(self): """ - Returns the variable of the bound change. + marks that this variable has only been introduced to define a relaxation + + The variable must not have a coefficient in the objective and must be deletable. + If it is not marked deletable, it will be marked as deletable, which is only possible before + the variable is added to a problem. Returns ------- - Variable + None """ - return Variable.create(SCIPboundchgGetVar(self.scip_boundchg)) - - def getBoundchgtype(self): + SCIPvarMarkRelaxationOnly(self.scip_var) + + def isRelaxationOnly(self): """ - Returns the bound change type of the bound change. + returns whether a variable has been introduced to define a relaxation + + These variables are only valid for the current SCIP solve round, they are not contained in any (checked) + constraints, but may be used in cutting planes, for example. Relaxation-only variables are not copied + by SCIPcopyVars and cuts that contain these variables are not added as linear constraints when + restarting or transferring information from a copied SCIP to a SCIP. Also conflicts with relaxation-only + variables are not generated at the moment. Relaxation-only variables do not appear in the objective. Returns ------- - int - (0 = branching, 1 = consinfer, 2 = propinfer) + bool """ - return SCIPboundchgGetBoundchgtype(self.scip_boundchg) - - def getBoundtype(self): + return SCIPvarIsRelaxationOnly(self.scip_var) + + def isDeletable(self): """ - Returns the bound type of the bound change. + Returns whether variable is allowed to be deleted completely from the problem. Returns ------- - int - (0 = lower, 1 = upper) + bool """ - return SCIPboundchgGetBoundtype(self.scip_boundchg) + return SCIPvarIsDeletable(self.scip_var) - def isRedundant(self): + def isActive(self): """ - Returns whether the bound change is redundant due to a more global bound that is at least as strong. + Returns whether variable is an active (neither fixed nor aggregated) variable. Returns ------- - bool - + boolean """ - return SCIPboundchgIsRedundant(self.scip_boundchg) - - def __repr__(self): - return f"{self.getVar()} {_SCIP_BOUNDTYPE_TO_STRING[self.getBoundtype()]} {self.getNewBound()}" - -cdef class DomainChanges: - """Set of domain changes.""" + return SCIPvarIsActive(self.scip_var) - @staticmethod - cdef create(SCIP_DOMCHG* scip_domchg): + def getNLocksDown(self): """ - Main method for creating a DomainChanges class. Is used instead of __init__. - - Parameters - ---------- - scip_domchg : SCIP_DOMCHG* - A pointer to the SCIP_DOMCHG + Returns the number of locks for rounding down. Returns ------- - domchg : DomainChanges - The Python representative of the SCIP_DOMCHG + int """ - if scip_domchg == NULL: - raise Warning("cannot create DomainChanges with SCIP_DOMCHG* == NULL") - domchg = DomainChanges() - domchg.scip_domchg = scip_domchg - return domchg - - def getBoundchgs(self): + return SCIPvarGetNLocksDown(self.scip_var) + + def getNLocksUp(self): """ - Returns the bound changes in the domain change. + Returns the number of locks for rounding up. Returns ------- - list of BoundChange + int """ - cdef int nboundchgs = SCIPdomchgGetNBoundchgs(self.scip_domchg) - cdef int i - return [BoundChange.create(SCIPdomchgGetBoundchg(self.scip_domchg, i)) - for i in range(nboundchgs)] - -cdef class Node: - """Base class holding a pointer to corresponding SCIP_NODE""" + return SCIPvarGetNLocksUp(self.scip_var) - @staticmethod - cdef create(SCIP_NODE* scipnode): + def getNLocksDownType(self, locktype): """ - Main method for creating a Node class. Is used instead of __init__. + Returns the number of locks for rounding down of a certain type. Parameters ---------- - scipnode : SCIP_NODE* - A pointer to the SCIP_NODE + locktype : SCIP_LOCKTYPE + type of variable locks Returns ------- - node : Node - The Python representative of the SCIP_NODE + int """ - if scipnode == NULL: - return None - node = Node() - node.scip_node = scipnode - return node + return SCIPvarGetNLocksDownType(self.scip_var, locktype) - def getParent(self): + def getNLocksUpType(self, locktype): """ - Retrieve parent node (or None if the node has no parent node). + Returns the number of locks for rounding up of a certain type. + + Parameters + ---------- + locktype : SCIP_LOCKTYPE + type of variable locks Returns ------- - Node + int """ - return Node.create(SCIPnodeGetParent(self.scip_node)) + return SCIPvarGetNLocksUpType(self.scip_var, locktype) - def getNumber(self): + def varMayRound(self, direction="down"): """ - Retrieve number of node. + Checks whether it is possible to round variable up / down and stay feasible for the relaxation. + + Parameters + ---------- + direction : str + "up" or "down" Returns ------- - int + bool """ - return SCIPnodeGetNumber(self.scip_node) + if direction not in ("down", "up"): + raise Warning(f"Unrecognized direction for rounding: {direction}") + cdef SCIP_Bool mayround + if direction == "down": + mayround = SCIPvarMayRoundDown(self.scip_var) + else: + mayround = SCIPvarMayRoundUp(self.scip_var) + return mayround - def getDepth(self): + def getNBranchings(self, branchdir): """ - Retrieve depth of node. + returns the number of times a bound of the variable was changed in given direction due to branching + + Parameters + ---------- + branchdir : PY_SCIP_BRANCHDIR + branching direction (downwards, or upwards) Returns ------- int - """ - return SCIPnodeGetDepth(self.scip_node) + return SCIPvarGetNBranchings(self.scip_var, branchdir) - def getType(self): + def getNBranchingsCurrentRun(self, branchdir): """ - Retrieve type of node. - + returns the number of times a bound of the variable was changed in given direction due to branching in the + current run + + Parameters + ---------- + branchdir : PY_SCIP_BRANCHDIR + branching direction (downwards, or upwards) + Returns ------- - PY_SCIP_NODETYPE - + int """ - return SCIPnodeGetType(self.scip_node) + return SCIPvarGetNBranchingsCurrentRun(self.scip_var, branchdir) - def getLowerbound(self): +class MatrixVariable(MatrixExpr): + + def vtype(self): """ - Retrieve lower bound of node. + Retrieve the matrix variables type (BINARY, INTEGER, IMPLINT or CONTINUOUS) Returns ------- - float + np.ndarray + A matrix containing "BINARY", "INTEGER", "CONTINUOUS", or "IMPLINT" """ - return SCIPnodeGetLowerbound(self.scip_node) + vtypes = np.empty(self.shape, dtype=object) + for idx in np.ndindex(self.shape): + vtypes[idx] = self[idx].vtype() + return vtypes - def getEstimate(self): + def isInLP(self): """ - Retrieve the estimated value of the best feasible solution in subtree of the node. + Retrieve whether the matrix variable is a COLUMN variable that is member of the current LP. Returns ------- - float + np.ndarray + An array of bools """ - return SCIPnodeGetEstimate(self.scip_node) + in_lp = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self.shape): + in_lp[idx] = self[idx].isInLP() + return in_lp - def getAddedConss(self): + + def getIndex(self): """ - Retrieve all constraints added at this node. + Retrieve the unique index of the matrix variable. Returns ------- - list of Constraint - + np.ndarray + An array of integers. No two should be the same """ - cdef int addedconsssize = SCIPnodeGetNAddedConss(self.scip_node) - if addedconsssize == 0: - return [] - cdef SCIP_CONS** addedconss = malloc(addedconsssize * sizeof(SCIP_CONS*)) - cdef int nconss - cdef int i - SCIPnodeGetAddedConss(self.scip_node, addedconss, &nconss, addedconsssize) - assert nconss == addedconsssize - constraints = [Constraint.create(addedconss[i]) for i in range(nconss)] - free(addedconss) - return constraints + indices = np.empty(self.shape, dtype=int) + for idx in np.ndindex(self.shape): + indices[idx] = self[idx].getIndex() + return indices - def getNAddedConss(self): + def getCol(self): """ - Retrieve number of added constraints at this node. + Retrieve matrix of columns of COLUMN variables. Returns ------- - int - + np.ndarray + An array of Column objects """ - return SCIPnodeGetNAddedConss(self.scip_node) - def isActive(self): + columns = np.empty(self.shape, dtype=object) + for idx in np.ndindex(self.shape): + columns[idx] = self[idx].getCol() + return columns + + def getLbOriginal(self): """ - Is the node in the path to the current node? + Retrieve original lower bound of matrix variable. Returns ------- - bool + np.ndarray """ - return SCIPnodeIsActive(self.scip_node) + lbs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + lbs[idx] = self[idx].getLbOriginal() + return lbs - def isPropagatedAgain(self): + def getUbOriginal(self): """ - Is the node marked to be propagated again? + Retrieve original upper bound of matrixvariable. Returns ------- - bool + np.ndarray """ - return SCIPnodeIsPropagatedAgain(self.scip_node) + ubs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + ubs[idx] = self[idx].getUbOriginal() + return ubs - def getNParentBranchings(self): + def getLbGlobal(self): """ - Retrieve the number of variable branchings that were performed in the parent node to create this node. + Retrieve global lower bound of matrix variable. Returns ------- - int + np.ndarray """ - cdef SCIP_VAR* dummy_branchvars - cdef SCIP_Real dummy_branchbounds - cdef SCIP_BOUNDTYPE dummy_boundtypes - cdef int nbranchvars - # This is a hack: the SCIP interface has no function to directly get the - # number of parent branchings, i.e., SCIPnodeGetNParentBranchings() does - # not exist. - SCIPnodeGetParentBranchings(self.scip_node, &dummy_branchvars, - &dummy_branchbounds, &dummy_boundtypes, - &nbranchvars, 0) - return nbranchvars + lbs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + lbs[idx] = self[idx].getLbGlobal() + return lbs - def getParentBranchings(self): + def getUbGlobal(self): """ - Retrieve the set of variable branchings that were performed in the parent node to create this node. + Retrieve global upper bound of matrix variable. Returns ------- - list of Variable - list of float - list of int + np.ndarray """ - cdef int nbranchvars = self.getNParentBranchings() - if nbranchvars == 0: - return None - cdef SCIP_VAR** branchvars = malloc(nbranchvars * sizeof(SCIP_VAR*)) - cdef SCIP_Real* branchbounds = malloc(nbranchvars * sizeof(SCIP_Real)) - cdef SCIP_BOUNDTYPE* boundtypes = malloc(nbranchvars * sizeof(SCIP_BOUNDTYPE)) - cdef int i - SCIPnodeGetParentBranchings(self.scip_node, branchvars, branchbounds, - boundtypes, &nbranchvars, nbranchvars) - - py_variables = [Variable.create(branchvars[i]) for i in range(nbranchvars)] - py_branchbounds = [branchbounds[i] for i in range(nbranchvars)] - py_boundtypes = [boundtypes[i] for i in range(nbranchvars)] - free(boundtypes) - free(branchbounds) - free(branchvars) - return py_variables, py_branchbounds, py_boundtypes + ubs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + ubs[idx] = self[idx].getUbGlobal() + return ubs - def getNDomchg(self): + def getLbLocal(self): """ - Retrieve the number of bound changes due to branching, constraint propagation, and propagation. + Retrieve current lower bound of matrix variable. Returns ------- - nbranchings : int - nconsprop : int - nprop : int + np.ndarray """ - cdef int nbranchings - cdef int nconsprop - cdef int nprop - SCIPnodeGetNDomchg(self.scip_node, &nbranchings, &nconsprop, &nprop) - return nbranchings, nconsprop, nprop + lbs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + lbs[idx] = self[idx].getLbLocal() + return lbs - def getDomchg(self): + def getUbLocal(self): """ - Retrieve domain changes for this node. + Retrieve current upper bound of matrix variable. Returns ------- - DomainChanges + np.ndarray """ - cdef SCIP_DOMCHG* domchg = SCIPnodeGetDomchg(self.scip_node) - if domchg == NULL: - return None - return DomainChanges.create(domchg) - - def __hash__(self): - return hash(self.scip_node) + ubs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + ubs[idx] = self[idx].getUbLocal() + return ubs - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self.scip_node == (other).scip_node) + def getObj(self): + """ + Retrieve current objective value of matrix variable. -cdef class Variable(Expr): - """Is a linear expression and has SCIP_VAR*""" + Returns + ------- + np.ndarray - @staticmethod - cdef create(SCIP_VAR* scipvar): """ - Main method for creating a Variable class. Is used instead of __init__. + objs = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + objs[idx] = self[idx].getObj() + return objs - Parameters - ---------- - scipvar : SCIP_VAR* - A pointer to the SCIP_VAR + def getLPSol(self): + """ + Retrieve the current LP solution value of matrix variable. Returns ------- - var : Variable - The Python representative of the SCIP_VAR + np.ndarray """ - if scipvar == NULL: - raise Warning("cannot create Variable with SCIP_VAR* == NULL") - var = Variable() - var.scip_var = scipvar - Expr.__init__(var, {Term(var) : 1.0}) - return var - - @property - def name(self): - if self.scip_var == NULL: - return "" - return bytes(SCIPvarGetName(self.scip_var)).decode("utf-8") + lpsols = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + lpsols[idx] = self[idx].getLPSol() + return lpsols - cdef Variable copy(self, bint copy=True): - return self + def getAvgSol(self): + """ + Get the weighted average solution of matrix variable in all feasible primal solutions found. - def ptr(self): - return (self.scip_var) + Returns + ------- + np.ndarray - def __repr__(self): - return self.name + """ + avgsols = np.empty(self.shape, dtype=float) + for idx in np.ndindex(self.shape): + avgsols[idx] = self[idx].getAvgSol() + return avgsols - def vtype(self): + def varMayRound(self, direction="down"): """ - Retrieve the variables type (BINARY, INTEGER, CONTINUOUS, or IMPLINT) + Checks whether it is possible to round variable up / down and stay feasible for the relaxation. + + Parameters + ---------- + direction : str + "up" or "down" Returns ------- - str - "BINARY", "INTEGER", "CONTINUOUS", or "IMPLINT" + np.ndarray + An array of bools """ - vartype = SCIPvarGetType(self.scip_var) - if vartype == SCIP_VARTYPE_BINARY: - return "BINARY" - elif vartype == SCIP_VARTYPE_INTEGER: - return "INTEGER" - elif vartype == SCIP_VARTYPE_CONTINUOUS: - return "CONTINUOUS" - elif vartype == SCIP_DEPRECATED_VARTYPE_IMPLINT: - return "IMPLINT" - - def isBinary(self): + mayround = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self.shape): + mayround[idx] = self[idx].varMayRound() + return mayround + +cdef class Constraint: + """Base class holding a pointer to corresponding SCIP_CONS""" + + @staticmethod + cdef create(SCIP_CONS* scipcons): """ - Returns whether variable is of BINARY type. + Main method for creating a Constraint class. Is used instead of __init__. + + Parameters + ---------- + scipcons : SCIP_CONS* + A pointer to the SCIP_CONS Returns ------- - bool + cons : Constraint + The Python representative of the SCIP_CONS + """ - return SCIPvarIsBinary(self.scip_var) - - def isIntegral(self): + if scipcons == NULL: + raise Warning("cannot create Constraint with SCIP_CONS* == NULL") + cons = Constraint() + cons.scip_cons = scipcons + return cons + + @property + def name(self): + if self.scip_cons == NULL: + return "" + return bytes(SCIPconsGetName(self.scip_cons)).decode("utf-8") + + def ptr(self): + return (self.scip_cons) + + def __repr__(self): + return self.name + + def isOriginal(self): """ - Returns whether variable is of INTEGER type. + Retrieve whether the constraint belongs to the original problem. Returns ------- bool + """ - return SCIPvarIsIntegral(self.scip_var) - - def isImpliedIntegral(self): + return SCIPconsIsOriginal(self.scip_cons) + + def isInitial(self): """ - Returns whether variable is implied integral (weakly or strongly). + Returns True if the relaxation of the constraint should be in the initial LP. Returns ------- bool + """ - return SCIPvarIsImpliedIntegral(self.scip_var) - - def isNonImpliedIntegral(self): + return SCIPconsIsInitial(self.scip_cons) + + def isSeparated(self): """ - Returns TRUE if the variable is integral, but not implied integral.. + Returns True if constraint should be separated during LP processing. Returns ------- bool + """ - return SCIPvarIsNonimpliedIntegral(self.scip_var) + return SCIPconsIsSeparated(self.scip_cons) - def getImplType(self): + def isEnforced(self): """ - Returns the implied integral type of the variable + Returns True if constraint should be enforced during node processing. Returns ------- - PY_SCIP_IMPLINTTYPE + bool + """ - return SCIPvarGetImplType(self.scip_var) + return SCIPconsIsEnforced(self.scip_cons) - def getStatus(self): + def isChecked(self): """ - Retrieve the variable status (ORIGINAL, LOOSE, COLUMN, FIXED, AGGREGATED, MULTAGGR, NEGATED) + Returns True if constraint should be checked for feasibility. Returns ------- - str - "ORIGINAL", "LOOSE", "COLUMN", "FIXED", "AGGREGATED", "MULTAGGR", "NEGATED" + bool """ - varstatus = SCIPvarGetStatus(self.scip_var) - if varstatus == SCIP_VARSTATUS_ORIGINAL: - return "ORIGINAL" - elif varstatus == SCIP_VARSTATUS_LOOSE: - return "LOOSE" - elif varstatus == SCIP_VARSTATUS_COLUMN: - return "COLUMN" - elif varstatus == SCIP_VARSTATUS_FIXED: - return "FIXED" - elif varstatus == SCIP_VARSTATUS_AGGREGATED: - return "AGGREGATED" - elif varstatus == SCIP_VARSTATUS_MULTAGGR: - return "MULTAGGR" - elif varstatus == SCIP_VARSTATUS_NEGATED: - return "NEGATED" + return SCIPconsIsChecked(self.scip_cons) - def isOriginal(self): + def isPropagated(self): """ - Retrieve whether the variable belongs to the original problem + Returns True if constraint should be propagated during node processing. Returns ------- bool """ - return SCIPvarIsOriginal(self.scip_var) + return SCIPconsIsPropagated(self.scip_cons) - def isActive(self): + def isLocal(self): """ - Retrieve whether the variable is active + Returns True if constraint is only locally valid or not added to any (sub)problem. Returns ------- bool """ - return SCIPvarIsActive(self.scip_var) + return SCIPconsIsLocal(self.scip_cons) - def isInLP(self): + def isModifiable(self): """ - Retrieve whether the variable is a COLUMN variable that is member of the current LP. + Returns True if constraint is modifiable (subject to column generation). Returns ------- bool """ - return SCIPvarIsInLP(self.scip_var) + return SCIPconsIsModifiable(self.scip_cons) - def getIndex(self): + def isDynamic(self): """ - Retrieve the unique index of the variable. + Returns True if constraint is subject to aging. Returns ------- - int + bool """ - return SCIPvarGetIndex(self.scip_var) + return SCIPconsIsDynamic(self.scip_cons) - def getCol(self): + def isRemovable(self): """ - Retrieve column of COLUMN variable. + Returns True if constraint's relaxation should be removed from the LP due to aging or cleanup. Returns ------- - Column + bool """ - cdef SCIP_COL* scip_col - scip_col = SCIPvarGetCol(self.scip_var) - return Column.create(scip_col) + return SCIPconsIsRemovable(self.scip_cons) - def getLbOriginal(self): + def isStickingAtNode(self): """ - Retrieve original lower bound of variable. + Returns True if constraint is only locally valid or not added to any (sub)problem. Returns ------- - float + bool """ - return SCIPvarGetLbOriginal(self.scip_var) + return SCIPconsIsStickingAtNode(self.scip_cons) - def getUbOriginal(self): + def isActive(self): """ - Retrieve original upper bound of variable. + Returns True iff constraint is active in the current node. Returns ------- - float + bool """ - return SCIPvarGetUbOriginal(self.scip_var) + return SCIPconsIsActive(self.scip_cons) - def getLbGlobal(self): + def isLinear(self): """ - Retrieve global lower bound of variable. + Returns True if constraint is linear Returns ------- - float + bool """ - return SCIPvarGetLbGlobal(self.scip_var) - - def getUbGlobal(self): + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype == 'linear' + + def isKnapsack(self): """ - Retrieve global upper bound of variable. + Returns True if constraint is a knapsack constraint. + This is a special case of a linear constraint. Returns ------- - float + bool """ - return SCIPvarGetUbGlobal(self.scip_var) + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype == 'knapsack' - def getLbLocal(self): + def isCumulative(self): """ - Retrieve current lower bound of variable. + Returns True if constraint is a cumulative constraint. + Cumulative is typically used in scheduling applications. Returns ------- - float + bool """ - return SCIPvarGetLbLocal(self.scip_var) + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype == 'cumulative' - def getUbLocal(self): + def isLinearType(self): """ - Retrieve current upper bound of variable. + Returns True if constraint can be represented as a linear constraint. Returns ------- - float + bool """ - return SCIPvarGetUbLocal(self.scip_var) + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype in ('linear', 'knapsack', 'setppc', 'logicor', 'varbound') - def getObj(self): + def isNonlinear(self): """ - Retrieve current objective value of variable. + Returns True if constraint is nonlinear. Returns ------- - float + bool """ - return SCIPvarGetObj(self.scip_var) + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype == 'nonlinear' - def getLPSol(self): + def getConshdlrName(self): """ - Retrieve the current LP solution value of variable. + Return the constraint handler's name. Returns ------- - float + str """ - return SCIPvarGetLPSol(self.scip_var) + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') + return constype - def getAvgSol(self): + def __hash__(self): + return hash(self.scip_cons) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self.scip_cons == (other).scip_cons) + +class MatrixConstraint(np.ndarray): + + def isInitial(self): """ - Get the weighted average solution of variable in all feasible primal solutions found. + Returns True if the relaxation of the constraint should be in the initial LP. Returns ------- - float + np.ndarray """ - return SCIPvarGetAvgSol(self.scip_var) + initial = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + initial[idx] = self[idx].isInitial() + return initial - def markRelaxationOnly(self): + def isSeparated(self): """ - marks that this variable has only been introduced to define a relaxation - - The variable must not have a coefficient in the objective and must be deletable. - If it is not marked deletable, it will be marked as deletable, which is only possible before - the variable is added to a problem. + Returns True if constraint should be separated during LP processing. Returns ------- - None + np.ndarray """ - SCIPvarMarkRelaxationOnly(self.scip_var) - - def isRelaxationOnly(self): - """ - returns whether a variable has been introduced to define a relaxation - - These variables are only valid for the current SCIP solve round, they are not contained in any (checked) - constraints, but may be used in cutting planes, for example. Relaxation-only variables are not copied - by SCIPcopyVars and cuts that contain these variables are not added as linear constraints when - restarting or transferring information from a copied SCIP to a SCIP. Also conflicts with relaxation-only - variables are not generated at the moment. Relaxation-only variables do not appear in the objective. - - Returns - ------- - bool + separated = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + separated[idx] = self[idx].isSeparated() + return separated + def isEnforced(self): """ - return SCIPvarIsRelaxationOnly(self.scip_var) - - def isDeletable(self): - """ - Returns whether variable is allowed to be deleted completely from the problem. + Returns True if constraint should be enforced during node processing. Returns ------- - bool + np.ndarray """ - return SCIPvarIsDeletable(self.scip_var) + enforced = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + enforced[idx] = self[idx].isEnforced() + return enforced - def isActive(self): + def isChecked(self): """ - Returns whether variable is an active (neither fixed nor aggregated) variable. + Returns True if constraint should be checked for feasibility. Returns ------- - boolean - """ - return SCIPvarIsActive(self.scip_var) + np.ndarray - def getNLocksDown(self): """ - Returns the number of locks for rounding down. - - Returns - ------- - int + checked = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + checked[idx] = self[idx].isCheced() + return checked + def isPropagated(self): """ - return SCIPvarGetNLocksDown(self.scip_var) - - def getNLocksUp(self): - """ - Returns the number of locks for rounding up. + Returns True if constraint should be propagated during node processing. Returns ------- - int + np.ndarray """ - return SCIPvarGetNLocksUp(self.scip_var) + propagated = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + propagated[idx] = self[idx].isPropagated() + return propagated - def getNLocksDownType(self, locktype): + def isLocal(self): """ - Returns the number of locks for rounding down of a certain type. - - Parameters - ---------- - locktype : SCIP_LOCKTYPE - type of variable locks + Returns True if constraint is only locally valid or not added to any (sub)problem. Returns ------- - int + np.ndarray """ - return SCIPvarGetNLocksDownType(self.scip_var, locktype) + local = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + local[idx] = self[idx].isLocal() + return local - def getNLocksUpType(self, locktype): + def isModifiable(self): """ - Returns the number of locks for rounding up of a certain type. - - Parameters - ---------- - locktype : SCIP_LOCKTYPE - type of variable locks + Returns True if constraint is modifiable (subject to column generation). Returns ------- - int + np.ndarray """ - return SCIPvarGetNLocksUpType(self.scip_var, locktype) + modifiable = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + modifiable[idx] = self[idx].isModifiable() + return modifiable - def varMayRound(self, direction="down"): + def isDynamic(self): """ - Checks whether it is possible to round variable up / down and stay feasible for the relaxation. - - Parameters - ---------- - direction : str - "up" or "down" + Returns True if constraint is subject to aging. Returns ------- - bool + np.ndarray """ - if direction not in ("down", "up"): - raise Warning(f"Unrecognized direction for rounding: {direction}") - cdef SCIP_Bool mayround - if direction == "down": - mayround = SCIPvarMayRoundDown(self.scip_var) - else: - mayround = SCIPvarMayRoundUp(self.scip_var) - return mayround + dynamic = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + dynamic[idx] = self[idx].isDynamic() + return dynamic - def getNBranchings(self, branchdir): + def isRemovable(self): """ - returns the number of times a bound of the variable was changed in given direction due to branching - - Parameters - ---------- - branchdir : PY_SCIP_BRANCHDIR - branching direction (downwards, or upwards) + Returns True if constraint's relaxation should be removed from the LP due to aging or cleanup. Returns ------- - int - """ - return SCIPvarGetNBranchings(self.scip_var, branchdir) - - def getNBranchingsCurrentRun(self, branchdir): - """ - returns the number of times a bound of the variable was changed in given direction due to branching in the - current run - - Parameters - ---------- - branchdir : PY_SCIP_BRANCHDIR - branching direction (downwards, or upwards) + np.ndarray - Returns - ------- - int """ - return SCIPvarGetNBranchingsCurrentRun(self.scip_var, branchdir) - -class MatrixVariable(MatrixExpr): + removable = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + removable[idx] = self[idx].isRemovable() + return removable - def vtype(self): + def isStickingAtNode(self): """ - Retrieve the matrix variables type (BINARY, INTEGER, IMPLINT or CONTINUOUS) + Returns True if constraint is only locally valid or not added to any (sub)problem. Returns ------- np.ndarray - A matrix containing "BINARY", "INTEGER", "CONTINUOUS", or "IMPLINT" """ - vtypes = np.empty(self.shape, dtype=object) - for idx in np.ndindex(self.shape): - vtypes[idx] = self[idx].vtype() - return vtypes + stickingatnode = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + stickingatnode[idx] = self[idx].isStickingAtNode() + return stickingatnode - def isInLP(self): + def isActive(self): """ - Retrieve whether the matrix variable is a COLUMN variable that is member of the current LP. + Returns True iff constraint is active in the current node. Returns ------- np.ndarray - An array of bools """ - in_lp = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self.shape): - in_lp[idx] = self[idx].isInLP() - return in_lp - + active = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + active[idx] = self[idx].isActive() + return active - def getIndex(self): + def isLinear(self): """ - Retrieve the unique index of the matrix variable. + Returns True if constraint is linear Returns ------- np.ndarray - An array of integers. No two should be the same - """ - indices = np.empty(self.shape, dtype=int) - for idx in np.ndindex(self.shape): - indices[idx] = self[idx].getIndex() - return indices - - def getCol(self): - """ - Retrieve matrix of columns of COLUMN variables. - Returns - ------- - np.ndarray - An array of Column objects """ + islinear = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + islinear[idx] = self[idx].isLinear() + return islinear - columns = np.empty(self.shape, dtype=object) - for idx in np.ndindex(self.shape): - columns[idx] = self[idx].getCol() - return columns - - def getLbOriginal(self): + def isNonlinear(self): """ - Retrieve original lower bound of matrix variable. + Returns True if constraint is nonlinear. Returns ------- np.ndarray """ - lbs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - lbs[idx] = self[idx].getLbOriginal() - return lbs + isnonlinear = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + isnonlinear[idx] = self[idx].isNonlinear() + return isnonlinear - def getUbOriginal(self): + def getConshdlrName(self): """ - Retrieve original upper bound of matrixvariable. + Return the constraint handler's name. Returns ------- np.ndarray """ - ubs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - ubs[idx] = self[idx].getUbOriginal() - return ubs + name = np.empty(self.shape, dtype=bool) + for idx in np.ndindex(self): + name[idx] = self[idx].getConshdlrName() + return name - def getLbGlobal(self): - """ - Retrieve global lower bound of matrix variable. +cdef void relayMessage(SCIP_MESSAGEHDLR *messagehdlr, FILE *file, const char *msg) noexcept: + if file is stdout: + sys.stdout.write(msg.decode('UTF-8')) + elif file is stderr: + sys.stderr.write(msg.decode('UTF-8')) + else: + if msg is not NULL: + fputs(msg, file) + fflush(file) - Returns - ------- - np.ndarray +cdef void relayErrorMessage(void *messagehdlr, FILE *file, const char *msg) noexcept: + if file is NULL: + sys.stderr.write(msg.decode('UTF-8')) + else: + if msg is not NULL: + fputs(msg, file) + fflush(file) - """ - lbs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - lbs[idx] = self[idx].getLbGlobal() - return lbs +cdef class _VarArray: + cdef SCIP_VAR** ptr + cdef int size - def getUbGlobal(self): - """ - Retrieve global upper bound of matrix variable. + def __cinit__(self, object vars): + self.ptr = NULL + self.size = 0 - Returns - ------- - np.ndarray + if isinstance(vars, Variable): + vars = [vars] + elif not isinstance(vars, (list, tuple, MatrixVariable)): + raise TypeError(f"Expected Variable or list of Variable, got {type(vars)}.") - """ - ubs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - ubs[idx] = self[idx].getUbGlobal() - return ubs + self.size = len(vars) + if self.size: + self.ptr = malloc(self.size * sizeof(SCIP_VAR*)) + for i, var in enumerate(vars): + if not isinstance(var, Variable): + if (ndim := np.ndim(vars)) != 1: + raise ValueError(f"Expected a 1D array, but got a {ndim}D array.") + raise TypeError(f"Expected Variable, got {type(var)}.") + self.ptr[i] = (var).scip_var - def getLbLocal(self): - """ - Retrieve current lower bound of matrix variable. + def __dealloc__(self): + if self.ptr != NULL: + free(self.ptr) - Returns - ------- - np.ndarray +cdef class IIS: + @staticmethod + cdef create(SCIP_IIS* scip_iis): """ - lbs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - lbs[idx] = self[idx].getLbLocal() - return lbs + Main method for creating an IIS class. - def getUbLocal(self): - """ - Retrieve current upper bound of matrix variable. + Parameters + ---------- + scip : SCIP_IIS* + A pointer to the SCIP_IIS Returns ------- - np.ndarray + sol : IIS + The Python representative of the IIS """ - ubs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - ubs[idx] = self[idx].getUbLocal() - return ubs - - def getObj(self): + iis = IIS() + iis._iis = scip_iis + return iis + + def getTime(self): """ - Retrieve current objective value of matrix variable. + Retrieve the solving time of the IIS. Returns ------- - np.ndarray - + float """ - objs = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - objs[idx] = self[idx].getObj() - return objs + return SCIPiisGetTime(self._iis) - def getLPSol(self): + def isSubscipIrreducible(self): """ - Retrieve the current LP solution value of matrix variable. + Returns whether the IIS is irreducible. Returns ------- - np.ndarray - + bool """ - lpsols = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - lpsols[idx] = self[idx].getLPSol() - return lpsols + return SCIPiisIsSubscipIrreducible(self._iis) - def getAvgSol(self): + def isSubscipInfeasible(self): """ - Get the weighted average solution of matrix variable in all feasible primal solutions found. + Returns whether the IIS is infeasible. Returns ------- - np.ndarray - + bool """ - avgsols = np.empty(self.shape, dtype=float) - for idx in np.ndindex(self.shape): - avgsols[idx] = self[idx].getAvgSol() - return avgsols - - def varMayRound(self, direction="down"): + return SCIPiisIsSubscipInfeasible(self._iis) + + def setSubscipIrreducible(self, irreducible): """ - Checks whether it is possible to round variable up / down and stay feasible for the relaxation. + Sets the flag that states whether the IIS subscip is irreducible. Parameters ---------- - direction : str - "up" or "down" - - Returns - ------- - np.ndarray - An array of bools - + irreducible : bool + the value to set the irreducible flag to """ - mayround = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self.shape): - mayround[idx] = self[idx].varMayRound() - return mayround -cdef class Constraint: - """Base class holding a pointer to corresponding SCIP_CONS""" + SCIPiisSetSubscipIrreducible(self._iis, irreducible) - @staticmethod - cdef create(SCIP_CONS* scipcons): + def setSubscipInfeasible(self, infeasible): """ - Main method for creating a Constraint class. Is used instead of __init__. + Sets the flag that states whether the IIS subscip is infeasible. Parameters ---------- - scipcons : SCIP_CONS* - A pointer to the SCIP_CONS - - Returns - ------- - cons : Constraint - The Python representative of the SCIP_CONS - - """ - if scipcons == NULL: - raise Warning("cannot create Constraint with SCIP_CONS* == NULL") - cons = Constraint() - cons.scip_cons = scipcons - return cons - - @property - def name(self): - if self.scip_cons == NULL: - return "" - return bytes(SCIPconsGetName(self.scip_cons)).decode("utf-8") - - def ptr(self): - return (self.scip_cons) - - def __repr__(self): - return self.name - - def isOriginal(self): + infeasible : bool + the value to set the infeasible flag to """ - Retrieve whether the constraint belongs to the original problem. - - Returns - ------- - bool - """ - return SCIPconsIsOriginal(self.scip_cons) + SCIPiisSetSubscipInfeasible(self._iis, infeasible) - def isInitial(self): + def getNNodes(self): """ - Returns True if the relaxation of the constraint should be in the initial LP. + Gets number of nodes in the IIS solve. Returns ------- - bool + int """ - return SCIPconsIsInitial(self.scip_cons) - - def isSeparated(self): + return SCIPiisGetNNodes(self._iis) + + def getSubscip(self): """ - Returns True if constraint should be separated during LP processing. + Get the subscip of an IIS. Returns ------- - bool - - """ - return SCIPconsIsSeparated(self.scip_cons) - - def isEnforced(self): + Model """ - Returns True if constraint should be enforced during node processing. + cdef SCIP* subscip - Returns - ------- - bool + subscip = SCIPiisGetSubscip(self._iis) + model = BaseModel.create(subscip) + return model - """ - return SCIPconsIsEnforced(self.scip_cons) + def greedyMakeIrreducible(self): + """ + Perform the greedy deletion algorithm with singleton batches to obtain an irreducible infeasible subsystem (IIS) + """ - def isChecked(self): - """ - Returns True if constraint should be checked for feasibility. + PY_SCIP_CALL(SCIPiisGreedyMakeIrreducible(self._iis)) - Returns - ------- - bool - """ - return SCIPconsIsChecked(self.scip_cons) +# - remove create(), includeDefaultPlugins(), createProbBasic() methods +# - replace free() by "destructor" +# - interface SCIPfreeProb() +## +#@anchor Model +## +cdef class BaseModel: - def isPropagated(self): + def __init__(self, problemName='model', defaultPlugins=True, BaseModel sourceModel=None, origcopy=False, globalcopy=True, enablepricing=True, createscip=True, threadsafe=False): """ - Returns True if constraint should be propagated during node processing. + Main class holding a pointer to SCIP for managing most interactions - Returns - ------- - bool + Parameters + ---------- + problemName : str, optional + name of the problem (default 'model') + defaultPlugins : bool, optional + use default plugins? (default True) + sourceModel : Model or None, optional + create a copy of the given Model instance (default None) + origcopy : bool, optional + whether to call copy or copyOrig (default False) + globalcopy : bool, optional + whether to create a global or a local copy (default True) + enablepricing : bool, optional + whether to enable pricing in copy (default True) + createscip : bool, optional + initialize the Model object and creates a SCIP instance (default True) + threadsafe : bool, optional + False if data can be safely shared between the source and target problem (default False) """ - return SCIPconsIsPropagated(self.scip_cons) + if self.getMajorVersion() < MAJOR: + raise Exception("linked SCIP is not compatible to this version of PySCIPOpt - use at least version", MAJOR) + if self.getMajorVersion() == MAJOR and self.getMinorVersion() < MINOR: + warnings.warn( + "linked SCIP {}.{} is not recommended for this version of PySCIPOpt - use version {}.{}.{}".format( + self.getMajorVersion(), self.getMinorVersion(), MAJOR, MINOR, PATCH)) - def isLocal(self): - """ - Returns True if constraint is only locally valid or not added to any (sub)problem. + self._freescip = True + self._modelvars = {} + self._modelconss = {} + self._generated_event_handlers_count = 0 + self._benders_subproblems = [] # Keep references to Benders subproblem Models + self._plugins = [] # Keep references to plugins to break cycles in __dealloc__ + self._iis = NULL - Returns - ------- - bool - """ - return SCIPconsIsLocal(self.scip_cons) + if not createscip: + # if no SCIP instance should be created, then an empty Model object is created. + self._scip = NULL + self._bestSol = None + self._freescip = False + elif sourceModel is None: + PY_SCIP_CALL(SCIPcreate(&self._scip)) + self._bestSol = None + if defaultPlugins: + self.includeDefaultPlugins() + self._configureScip() + self.createProbBasic(problemName) + else: + PY_SCIP_CALL(SCIPcreate(&self._scip)) + self._bestSol = sourceModel._bestSol + n = str_conversion(problemName) + if origcopy: + PY_SCIP_CALL(SCIPcopyOrig(sourceModel._scip, self._scip, NULL, NULL, n, enablepricing, True, threadsafe, True, self._valid)) + else: + PY_SCIP_CALL(SCIPcopy(sourceModel._scip, self._scip, NULL, NULL, n, globalcopy, enablepricing, True, threadsafe, True, self._valid)) - def isModifiable(self): + def attachEventHandlerCallback(self, + callback, + events, + name="eventhandler", + description="" + ): """ - Returns True if constraint is modifiable (subject to column generation). - - Returns - ------- - bool + Attach an event handler to the model using a callback function. + Parameters + ---------- + callback : callable + The callback function to be called when an event occurs. + The callback function should have the following signature: + callback(model, event) + events : list of SCIP_EVENTTYPE + List of event types to attach the event handler to. + name : str, optional + Name of the event handler. If not provided, a unique default name will be generated. + description : str, optional + Description of the event handler. If not provided, an empty string will be used. """ - return SCIPconsIsModifiable(self.scip_cons) - def isDynamic(self): - """ - Returns True if constraint is subject to aging. + self._generated_event_handlers_count += 1 + model = self - Returns - ------- - bool + class EventHandler(Eventhdlr): + def __init__(self, callback): + super(EventHandler, self).__init__() + self.callback = callback - """ - return SCIPconsIsDynamic(self.scip_cons) + def eventinit(self): + for event in events: + self.model.catchEvent(event, self) - def isRemovable(self): - """ - Returns True if constraint's relaxation should be removed from the LP due to aging or cleanup. + def eventexit(self): + for event in events: + self.model.dropEvent(event, self) - Returns - ------- - bool + def eventexec(self, event): + self.callback(model, event) - """ - return SCIPconsIsRemovable(self.scip_cons) + event_handler = EventHandler(callback) - def isStickingAtNode(self): - """ - Returns True if constraint is only locally valid or not added to any (sub)problem. + if name == "eventhandler": + name = f"eventhandler_{self._generated_event_handlers_count}" - Returns - ------- - bool + self.includeEventhdlr(event_handler, name, description) - """ - return SCIPconsIsStickingAtNode(self.scip_cons) + def __del__(self): + """Free SCIP when the last external reference to the Model is dropped. - def isActive(self): + Runs before the garbage collector clears the Model's attributes, so + plugin callbacks can still reach a live ``self.model``. See + ``Model.free`` for the full lifecycle policy. """ - Returns True iff constraint is active in the current node. + self._free_scip_instance() - Returns - ------- - bool + def __dealloc__(self): + """Fallback SCIP cleanup if ``__del__`` did not already free the instance.""" + if self._scip is not NULL and self._freescip: + SCIPfree(&self._scip) - """ - return SCIPconsIsActive(self.scip_cons) + cdef _configureScip(self): + pass - def isLinear(self): - """ - Returns True if constraint is linear + cdef _free_scip_instance(self): + """Free the SCIP instance. Does not touch Python object references.""" + cdef SCIP_BENDERS** benders + cdef int nbenders + cdef int nsubproblems + cdef int i, j - Returns - ------- - bool + if self._scip is not NULL and self._freescip and PY_SCIP_CALL: + # Free Benders subproblems before freeing the main SCIP instance + if self._benders_subproblems: + benders = SCIPgetBenders(self._scip) + nbenders = SCIPgetNActiveBenders(self._scip) + for i in range(nbenders): + nsubproblems = SCIPbendersGetNSubproblems(benders[i]) + for j in range(nsubproblems): + PY_SCIP_CALL(SCIPfreeBendersSubproblem(self._scip, benders[i], j)) + + if SCIPgetStage(self._scip) == SCIP_STAGE_SOLVING and SCIPinProbing(self._scip): + PY_SCIP_CALL(SCIPendProbing(self._scip)) + + # Ignore SCIPfree retcode: cleanup must not turn into a new failure. + SCIPfree(&self._scip) + self._scip = NULL + self._freescip = False + + # Invalidate all variable and constraint pointers after freeing SCIP. See issue #604. + if self._modelvars: + for var in self._modelvars.values(): + (var).scip_var = NULL + if self._modelconss: + for cons in self._modelconss.values(): + (cons).scip_cons = NULL + + def __hash__(self): + return hash(self._scip) + + def __eq__(self, other): + return (self.__class__ == other.__class__ + and self._scip == (other)._scip) + + @staticmethod + cdef create(SCIP* scip): """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype == 'linear' - - def isKnapsack(self): - """ - Returns True if constraint is a knapsack constraint. - This is a special case of a linear constraint. + Creates a model and appropriately assigns the scip and bestsol parameters. + + Parameters + ---------- + scip : SCIP* + A pointer to a SCIP object Returns ------- - bool + Model """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype == 'knapsack' + if scip == NULL: + raise Warning("cannot create Model with SCIP* == NULL") + model = ExactModel(createscip=False) if SCIPisExact(scip) else Model(createscip=False) + model._scip = scip + model._bestSol = Solution.create(scip, SCIPgetBestSol(scip)) + model._benders_subproblems = [] # Initialize Benders subproblems list + return model - def isCumulative(self): + cdef _getOrCreateCons(self, SCIP_CONS* scip_cons): + """Get existing Constraint wrapper or create and track a new one.""" + cdef size_t ptr = scip_cons + if ptr in self._modelconss: + return self._modelconss[ptr] + pyCons = Constraint.create(scip_cons) + self._modelconss[ptr] = pyCons + return pyCons + + cdef _getOrCreateVar(self, SCIP_VAR* scip_var): + """Get existing Variable wrapper or create and track a new one.""" + cdef size_t ptr = scip_var + if ptr in self._modelvars: + return self._modelvars[ptr] + pyVar = Variable.create(scip_var) + self._modelvars[ptr] = pyVar + return pyVar + + @property + def _freescip(self): """ - Returns True if constraint is a cumulative constraint. - Cumulative is typically used in scheduling applications. + Return whether the underlying Scip pointer gets deallocted when the current + object is deleted. Returns ------- bool """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype == 'cumulative' + return self._freescip - def isLinearType(self): + @_freescip.setter + def _freescip(self, val): """ - Returns True if constraint can be represented as a linear constraint. + Set whether the underlying Scip pointer gets deallocted when the current + object is deleted. - Returns - ------- - bool + Parameters + ---------- + val : bool """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype in ('linear', 'knapsack', 'setppc', 'logicor', 'varbound') + self._freescip = val - def isNonlinear(self): + @cython.always_allow_keywords(True) + @staticmethod + def from_ptr(capsule, take_ownership): """ - Returns True if constraint is nonlinear. + Create a Model from a given pointer. + + Parameters + ---------- + capsule + The PyCapsule containing the SCIP pointer under the name "scip" + take_ownership : bool + Whether the newly created Model assumes ownership of the + underlying Scip pointer (see ``_freescip``) Returns ------- - bool + Model """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype == 'nonlinear' + if not PyCapsule_IsValid(capsule, "scip"): + raise ValueError("The given capsule does not contain a valid scip pointer") + model = BaseModel.create(PyCapsule_GetPointer(capsule, "scip")) + model._freescip = take_ownership + return model - def getConshdlrName(self): + @cython.always_allow_keywords(True) + def to_ptr(self, give_ownership): """ - Return the constraint handler's name. + Return the underlying Scip pointer to the current Model. + + Parameters + ---------- + give_ownership : bool + Whether the current Model gives away ownership of the + underlying Scip pointer (see ``_freescip``) Returns ------- - str + capsule + The underlying pointer to the current Model, wrapped in a + PyCapsule under the name "scip". """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(self.scip_cons))).decode('UTF-8') - return constype - - def __hash__(self): - return hash(self.scip_cons) + capsule = PyCapsule_New(self._scip, "scip", NULL) + if give_ownership: + self._freescip = False + return capsule - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self.scip_cons == (other).scip_cons) + def includeDefaultPlugins(self): + """Includes all default plug-ins into SCIP.""" + PY_SCIP_CALL(SCIPincludeDefaultPlugins(self._scip)) -class MatrixConstraint(np.ndarray): + def createProbBasic(self, problemName='model'): + """ + Create new problem instance with given name. + + Parameters + ---------- + problemName : str, optional + name of model or problem (Default value = 'model') - def isInitial(self): """ - Returns True if the relaxation of the constraint should be in the initial LP. + n = str_conversion(problemName) + PY_SCIP_CALL(SCIPcreateProbBasic(self._scip, n)) - Returns - ------- - np.ndarray + def freeProb(self): + """Frees problem and solution process data.""" + PY_SCIP_CALL(SCIPfreeProb(self._scip)) + + def free(self): + """Explicitly free the SCIP instance and release plugin references. + + Every included plugin holds a strong reference to its Model via + ``self.model``, and the Model holds strong references to every plugin + via ``Model._plugins``. This cycle is intentional: it keeps both sides + alive during SCIP teardown so callbacks such as ``eventexit`` and + ``consfree`` can safely reach ``self.model``. + + The cycle is broken in one of two ways: + + * Implicitly, via ``Model.__del__`` when the last external reference to + the Model is dropped. ``__del__`` runs before the garbage collector + (GC) clears attributes, so callbacks still see a live ``self.model``. + Timing is at the GC's discretion. + * Explicitly, by calling this method. SCIP is freed immediately, + teardown callbacks fire before ``free`` returns, and the plugin list + is cleared. Use this when deterministic cleanup is required. After + ``free`` the Model must not be used further. + The solve itself is not affected by which path runs. ``free`` only + controls when memory and resources are released, and when teardown + callbacks execute. """ - initial = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - initial[idx] = self[idx].isInitial() - return initial + self._free_scip_instance() - def isSeparated(self): + # Break circular references with plugins + if self._plugins: + for plugin in self._plugins: + plugin.model = None + self._plugins = [] + + # Clear Python-side caches + self._modelvars = {} + self._modelconss = {} + self._benders_subproblems = [] + self._bestSol = None + + def freeTransform(self): + """Frees all solution process data including presolving and + transformed problem, only original problem is kept.""" + if self.getStage() not in [SCIP_STAGE_INIT, + SCIP_STAGE_PROBLEM, + SCIP_STAGE_TRANSFORMED, + SCIP_STAGE_PRESOLVING, + SCIP_STAGE_PRESOLVED, + SCIP_STAGE_SOLVING, + SCIP_STAGE_SOLVED]: + raise Warning("method cannot be called in stage %i." % self.getStage()) + + # Invalidate transformed variables. See issue #604. + origvars = {ptr: var for ptr, var in self._modelvars.items() if var.isOriginal()} + for ptr, var in self._modelvars.items(): + if ptr not in origvars: + (var).scip_var = NULL + self._modelvars = origvars + + # Invalidate transformed constraints. See issue #604. + origconss = {ptr: cons for ptr, cons in self._modelconss.items() if cons.isOriginal()} + for ptr, cons in self._modelconss.items(): + if ptr not in origconss: + (cons).scip_cons = NULL + self._modelconss = origconss + + PY_SCIP_CALL(SCIPfreeTransform(self._scip)) + + def version(self): """ - Returns True if constraint should be separated during LP processing. + Retrieve SCIP version. Returns ------- - np.ndarray + float """ - separated = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - separated[idx] = self[idx].isSeparated() - return separated + return SCIPversion() - def isEnforced(self): + def getMajorVersion(self): """ - Returns True if constraint should be enforced during node processing. + Retrieve SCIP major version. Returns ------- - np.ndarray + int """ - enforced = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - enforced[idx] = self[idx].isEnforced() - return enforced + return SCIPmajorVersion() - def isChecked(self): + def getMinorVersion(self): """ - Returns True if constraint should be checked for feasibility. + Retrieve SCIP minor version. Returns ------- - np.ndarray + int """ - checked = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - checked[idx] = self[idx].isCheced() - return checked + return SCIPminorVersion() - def isPropagated(self): + def getTechVersion(self): """ - Returns True if constraint should be propagated during node processing. + Retrieve SCIP technical version. Returns ------- - np.ndarray + int """ - propagated = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - propagated[idx] = self[idx].isPropagated() - return propagated + return SCIPtechVersion() - def isLocal(self): + def printVersion(self): + """Print version, copyright information and compile mode.""" + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + SCIPprintVersion(self._scip, NULL) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def printExternalCodeVersions(self): + """Print external code versions, e.g. symmetry, non-linear solver, lp solver.""" + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") + + SCIPprintExternalCodes(self._scip, NULL) + + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def getProbName(self): """ - Returns True if constraint is only locally valid or not added to any (sub)problem. + Retrieve problem name. Returns ------- - np.ndarray + str """ - local = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - local[idx] = self[idx].isLocal() - return local + return bytes(SCIPgetProbName(self._scip)).decode('UTF-8') - def isModifiable(self): + def getTotalTime(self): """ - Returns True if constraint is modifiable (subject to column generation). + Retrieve the current total SCIP time in seconds, + i.e. the total time since the SCIP instance has been created. Returns ------- - np.ndarray + float """ - modifiable = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - modifiable[idx] = self[idx].isModifiable() - return modifiable + return SCIPgetTotalTime(self._scip) - def isDynamic(self): + def getSolvingTime(self): """ - Returns True if constraint is subject to aging. + Retrieve the current solving time in seconds. Returns ------- - np.ndarray + float """ - dynamic = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - dynamic[idx] = self[idx].isDynamic() - return dynamic + return SCIPgetSolvingTime(self._scip) - def isRemovable(self): + def getReadingTime(self): """ - Returns True if constraint's relaxation should be removed from the LP due to aging or cleanup. + Retrieve the current reading time in seconds. Returns ------- - np.ndarray + float """ - removable = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - removable[idx] = self[idx].isRemovable() - return removable + return SCIPgetReadingTime(self._scip) - def isStickingAtNode(self): + def getPresolvingTime(self): """ - Returns True if constraint is only locally valid or not added to any (sub)problem. + Returns the current presolving time in seconds. Returns ------- - np.ndarray + float """ - stickingatnode = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - stickingatnode[idx] = self[idx].isStickingAtNode() - return stickingatnode + return SCIPgetPresolvingTime(self._scip) - def isActive(self): + def getDeterministicTime(self): """ - Returns True iff constraint is active in the current node. + Computes a deterministic measure of time from statistics. Returns ------- - np.ndarray + float """ - active = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - active[idx] = self[idx].isActive() - return active + return SCIPgetDeterministicTime(self._scip) - def isLinear(self): + def getNLPIterations(self): """ - Returns True if constraint is linear + Returns the total number of LP iterations so far. Returns ------- - np.ndarray + int """ - islinear = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - islinear[idx] = self[idx].isLinear() - return islinear + return SCIPgetNLPIterations(self._scip) - def isNonlinear(self): + def getNRuns(self): """ - Returns True if constraint is nonlinear. + Gets number of branch and bound runs performed, including the current run Returns ------- - np.ndarray + int """ - isnonlinear = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - isnonlinear[idx] = self[idx].isNonlinear() - return isnonlinear + return SCIPgetNRuns(self._scip) - def getConshdlrName(self): + def getNReoptRuns(self): """ - Return the constraint handler's name. + Gets number of reoptimization runs performed, including the current run Returns ------- - np.ndarray + int """ - name = np.empty(self.shape, dtype=bool) - for idx in np.ndindex(self): - name[idx] = self[idx].getConshdlrName() - return name + return SCIPgetNReoptRuns(self._scip) -cdef void relayMessage(SCIP_MESSAGEHDLR *messagehdlr, FILE *file, const char *msg) noexcept: - if file is stdout: - sys.stdout.write(msg.decode('UTF-8')) - elif file is stderr: - sys.stderr.write(msg.decode('UTF-8')) - else: - if msg is not NULL: - fputs(msg, file) - fflush(file) + def addNNodes(self, nnodes): + """ + Add given number to the number of processed nodes in current run and in all runs, including the focus node -cdef void relayErrorMessage(void *messagehdlr, FILE *file, const char *msg) noexcept: - if file is NULL: - sys.stderr.write(msg.decode('UTF-8')) - else: - if msg is not NULL: - fputs(msg, file) - fflush(file) + Parameters + ---------- + nnodes : int -cdef class _VarArray: - cdef SCIP_VAR** ptr - cdef int size + """ + SCIPaddNNodes(self._scip, nnodes) - def __cinit__(self, object vars): - self.ptr = NULL - self.size = 0 + def getNNodes(self): + """ + Gets number of processed nodes in current run, including the focus node. - if isinstance(vars, Variable): - vars = [vars] - elif not isinstance(vars, (list, tuple, MatrixVariable)): - raise TypeError(f"Expected Variable or list of Variable, got {type(vars)}.") + Returns + ------- + int - self.size = len(vars) - if self.size: - self.ptr = malloc(self.size * sizeof(SCIP_VAR*)) - for i, var in enumerate(vars): - if not isinstance(var, Variable): - if (ndim := np.ndim(vars)) != 1: - raise ValueError(f"Expected a 1D array, but got a {ndim}D array.") - raise TypeError(f"Expected Variable, got {type(var)}.") - self.ptr[i] = (var).scip_var + """ + return SCIPgetNNodes(self._scip) - def __dealloc__(self): - if self.ptr != NULL: - free(self.ptr) + def getNTotalNodes(self): + """ + Gets number of processed nodes in all runs, including the focus node. -cdef class IIS: + Returns + ------- + int - @staticmethod - cdef create(SCIP_IIS* scip_iis): """ - Main method for creating an IIS class. + return SCIPgetNTotalNodes(self._scip) - Parameters - ---------- - scip : SCIP_IIS* - A pointer to the SCIP_IIS + def getNFeasibleLeaves(self): + """ + Retrieve number of leaf nodes processed with feasible relaxation solution. Returns ------- - sol : IIS - The Python representative of the IIS + int """ - iis = IIS() - iis._iis = scip_iis - return iis - - def getTime(self): + return SCIPgetNFeasibleLeaves(self._scip) + + def getNInfeasibleLeaves(self): """ - Retrieve the solving time of the IIS. + Gets number of infeasible leaf nodes processed. Returns ------- - float + int + """ - return SCIPiisGetTime(self._iis) + return SCIPgetNInfeasibleLeaves(self._scip) - def isSubscipIrreducible(self): + def getNObjlimLeaves(self): """ - Returns whether the IIS is irreducible. + Gets number of processed leaf nodes that hit LP objective limit. Returns ------- - bool + int + """ - return SCIPiisIsSubscipIrreducible(self._iis) + return SCIPgetNObjlimLeaves(self._scip) - def isSubscipInfeasible(self): + def getNLeaves(self): """ - Returns whether the IIS is infeasible. + Gets number of leaves in the tree. Returns ------- - bool - """ - return SCIPiisIsSubscipInfeasible(self._iis) - - def setSubscipIrreducible(self, irreducible): + int + """ - Sets the flag that states whether the IIS subscip is irreducible. + return SCIPgetNLeaves(self._scip) - Parameters - ---------- - irreducible : bool - the value to set the irreducible flag to + def getNNodesLeft(self): """ + Gets number of nodes left in the tree (children + siblings + leaves) - SCIPiisSetSubscipIrreducible(self._iis, irreducible) + Returns + ------- + int - def setSubscipInfeasible(self, infeasible): """ - Sets the flag that states whether the IIS subscip is infeasible. + return SCIPgetNNodesLeft(self._scip) - Parameters - ---------- - infeasible : bool - the value to set the infeasible flag to + def getNChildren(self): """ + Gets number of children of focus node. - SCIPiisSetSubscipInfeasible(self._iis, infeasible) + Returns + ------- + int - def getNNodes(self): """ - Gets number of nodes in the IIS solve. + return SCIPgetNChildren(self._scip) + + def getNSiblings(self): + """ + Gets number of siblings of focus node. Returns ------- int """ - return SCIPiisGetNNodes(self._iis) - - def getSubscip(self): + return SCIPgetNSiblings(self._scip) + + def getFocusNode(self): """ - Get the subscip of an IIS. + Gets focus node in the tree. + If we are in probing/diving mode this method returns the node in the tree where the probing/diving mode was started. Returns ------- - Model + Node + """ - cdef SCIP* subscip + return Node.create(SCIPgetFocusNode(self._scip)) - subscip = SCIPiisGetSubscip(self._iis) - model = Model.create(subscip) - return model + def getCurrentNode(self): + """ + Retrieve current node. - def greedyMakeIrreducible(self): - """ - Perform the greedy deletion algorithm with singleton batches to obtain an irreducible infeasible subsystem (IIS) - """ + Returns + ------- + Node - PY_SCIP_CALL(SCIPiisGreedyMakeIrreducible(self._iis)) + """ + return Node.create(SCIPgetCurrentNode(self._scip)) + def getGap(self): + """ + Retrieve the gap, + i.e. abs((primalbound - dualbound)/min(abs(primalbound),abs(dualbound))) -# - remove create(), includeDefaultPlugins(), createProbBasic() methods -# - replace free() by "destructor" -# - interface SCIPfreeProb() -## -#@anchor Model -## -cdef class Model: + Returns + ------- + float - def __init__(self, problemName='model', defaultPlugins=True, Model sourceModel=None, origcopy=False, globalcopy=True, enablepricing=True, createscip=True, threadsafe=False): """ - Main class holding a pointer to SCIP for managing most interactions - - Parameters - ---------- - problemName : str, optional - name of the problem (default 'model') - defaultPlugins : bool, optional - use default plugins? (default True) - sourceModel : Model or None, optional - create a copy of the given Model instance (default None) - origcopy : bool, optional - whether to call copy or copyOrig (default False) - globalcopy : bool, optional - whether to create a global or a local copy (default True) - enablepricing : bool, optional - whether to enable pricing in copy (default True) - createscip : bool, optional - initialize the Model object and creates a SCIP instance (default True) - threadsafe : bool, optional - False if data can be safely shared between the source and target problem (default False) + return SCIPgetGap(self._scip) + def getDepth(self): """ - if self.getMajorVersion() < MAJOR: - raise Exception("linked SCIP is not compatible to this version of PySCIPOpt - use at least version", MAJOR) - if self.getMajorVersion() == MAJOR and self.getMinorVersion() < MINOR: - warnings.warn( - "linked SCIP {}.{} is not recommended for this version of PySCIPOpt - use version {}.{}.{}".format( - self.getMajorVersion(), self.getMinorVersion(), MAJOR, MINOR, PATCH)) + Retrieve the depth of the current node. - self._freescip = True - self._modelvars = {} - self._modelconss = {} - self._generated_event_handlers_count = 0 - self._benders_subproblems = [] # Keep references to Benders subproblem Models - self._plugins = [] # Keep references to plugins to break cycles in __dealloc__ - self._iis = NULL + Returns + ------- + int - if not createscip: - # if no SCIP instance should be created, then an empty Model object is created. - self._scip = NULL - self._bestSol = None - self._freescip = False - elif sourceModel is None: - PY_SCIP_CALL(SCIPcreate(&self._scip)) - self._bestSol = None - if defaultPlugins: - self.includeDefaultPlugins() - self.createProbBasic(problemName) - else: - PY_SCIP_CALL(SCIPcreate(&self._scip)) - self._bestSol = sourceModel._bestSol - n = str_conversion(problemName) - if origcopy: - PY_SCIP_CALL(SCIPcopyOrig(sourceModel._scip, self._scip, NULL, NULL, n, enablepricing, threadsafe, True, self._valid)) - else: - PY_SCIP_CALL(SCIPcopy(sourceModel._scip, self._scip, NULL, NULL, n, globalcopy, enablepricing, threadsafe, True, self._valid)) + """ + return SCIPgetDepth(self._scip) - def attachEventHandlerCallback(self, - callback, - events, - name="eventhandler", - description="" - ): + def getMaxDepth(self): """ - Attach an event handler to the model using a callback function. + Gets maximal depth of the branch-and-bound tree processed during solving (excluding probing nodes). - Parameters - ---------- - callback : callable - The callback function to be called when an event occurs. - The callback function should have the following signature: - callback(model, event) - events : list of SCIP_EVENTTYPE - List of event types to attach the event handler to. - name : str, optional - Name of the event handler. If not provided, a unique default name will be generated. - description : str, optional - Description of the event handler. If not provided, an empty string will be used. - """ - - self._generated_event_handlers_count += 1 - model = self - - class EventHandler(Eventhdlr): - def __init__(self, callback): - super(EventHandler, self).__init__() - self.callback = callback - - def eventinit(self): - for event in events: - self.model.catchEvent(event, self) - - def eventexit(self): - for event in events: - self.model.dropEvent(event, self) - - def eventexec(self, event): - self.callback(model, event) - - event_handler = EventHandler(callback) + Returns + ------- + int - if name == "eventhandler": - name = f"eventhandler_{self._generated_event_handlers_count}" + """ + return SCIPgetMaxDepth(self._scip) - self.includeEventhdlr(event_handler, name, description) + def getMaxTotalDepth(self): + """ + Gets maximal depth of all processed nodes over all branch and bound runs. - def __del__(self): - """Free SCIP when the last external reference to the Model is dropped. + Returns + ------- + int - Runs before the garbage collector clears the Model's attributes, so - plugin callbacks can still reach a live ``self.model``. See - ``Model.free`` for the full lifecycle policy. """ - self._free_scip_instance() + return SCIPgetMaxTotalDepth(self._scip) - def __dealloc__(self): - """Fallback SCIP cleanup if ``__del__`` did not already free the instance.""" - if self._scip is not NULL and self._freescip: - SCIPfree(&self._scip) + def getNBacktracks(self): + """ + Gets total number of backtracks, i.e., number of times the new node was selected from the leaves queue. - cdef _free_scip_instance(self): - """Free the SCIP instance. Does not touch Python object references.""" - cdef SCIP_BENDERS** benders - cdef int nbenders - cdef int nsubproblems - cdef int i, j + Returns + ------- + int - if self._scip is not NULL and self._freescip and PY_SCIP_CALL: - # Free Benders subproblems before freeing the main SCIP instance - if self._benders_subproblems: - benders = SCIPgetBenders(self._scip) - nbenders = SCIPgetNActiveBenders(self._scip) + """ + return SCIPgetNBacktracks(self._scip) - for i in range(nbenders): - nsubproblems = SCIPbendersGetNSubproblems(benders[i]) - for j in range(nsubproblems): - PY_SCIP_CALL(SCIPfreeBendersSubproblem(self._scip, benders[i], j)) + def getPlungeDepth(self): + """ + Gets current plunging depth (successive selections of child/sibling nodes). - if SCIPgetStage(self._scip) == SCIP_STAGE_SOLVING and SCIPinProbing(self._scip): - PY_SCIP_CALL(SCIPendProbing(self._scip)) - - # Ignore SCIPfree retcode: cleanup must not turn into a new failure. - SCIPfree(&self._scip) - self._scip = NULL - self._freescip = False + Returns + ------- + int - # Invalidate all variable and constraint pointers after freeing SCIP. See issue #604. - if self._modelvars: - for var in self._modelvars.values(): - (var).scip_var = NULL - if self._modelconss: - for cons in self._modelconss.values(): - (cons).scip_cons = NULL + """ + return SCIPgetPlungeDepth(self._scip) - def __hash__(self): - return hash(self._scip) + def getNNodeLPIterations(self): + """ + Gets number of LP iterations used for solving node relaxations so far. - def __eq__(self, other): - return (self.__class__ == other.__class__ - and self._scip == (other)._scip) + Returns + ------- + int - @staticmethod - cdef create(SCIP* scip): """ - Creates a model and appropriately assigns the scip and bestsol parameters. + return SCIPgetNNodeLPIterations(self._scip) - Parameters - ---------- - scip : SCIP* - A pointer to a SCIP object + def getNStrongbranchLPIterations(self): + """ + Gets number of LP iterations used for strong branching so far. Returns ------- - Model + int """ - if scip == NULL: - raise Warning("cannot create Model with SCIP* == NULL") - model = Model(createscip=False) - model._scip = scip - model._bestSol = Solution.create(scip, SCIPgetBestSol(scip)) - model._benders_subproblems = [] # Initialize Benders subproblems list - return model - - cdef _getOrCreateCons(self, SCIP_CONS* scip_cons): - """Get existing Constraint wrapper or create and track a new one.""" - cdef size_t ptr = scip_cons - if ptr in self._modelconss: - return self._modelconss[ptr] - pyCons = Constraint.create(scip_cons) - self._modelconss[ptr] = pyCons - return pyCons - - cdef _getOrCreateVar(self, SCIP_VAR* scip_var): - """Get existing Variable wrapper or create and track a new one.""" - cdef size_t ptr = scip_var - if ptr in self._modelvars: - return self._modelvars[ptr] - pyVar = Variable.create(scip_var) - self._modelvars[ptr] = pyVar - return pyVar + return SCIPgetNStrongbranchLPIterations(self._scip) - @property - def _freescip(self): + def getPrimalDualIntegral(self): """ - Return whether the underlying Scip pointer gets deallocted when the current - object is deleted. + Recomputes and returns the primal dual gap stored in the stats Returns - ------- - bool - + ------ + float """ - return self._freescip + return SCIPgetPrimalDualIntegral(self._scip) - @_freescip.setter - def _freescip(self, val): + def cutoffNode(self, Node node): """ - Set whether the underlying Scip pointer gets deallocted when the current - object is deleted. + marks node and whole subtree to be cut off from the branch and bound tree. Parameters ---------- - val : bool - + node : Node """ - self._freescip = val + PY_SCIP_CALL( SCIPcutoffNode(self._scip, node.scip_node) ) - @cython.always_allow_keywords(True) - @staticmethod - def from_ptr(capsule, take_ownership): + def getCondition(self, exact=False): """ - Create a Model from a given pointer. + Get the current LP's condition number. Parameters ---------- - capsule - The PyCapsule containing the SCIP pointer under the name "scip" - take_ownership : bool - Whether the newly created Model assumes ownership of the - underlying Scip pointer (see ``_freescip``) + exact : bool, optional + whether to get an estimate or the exact value (Default value = False) Returns ------- - Model + float """ - if not PyCapsule_IsValid(capsule, "scip"): - raise ValueError("The given capsule does not contain a valid scip pointer") - model = Model.create(PyCapsule_GetPointer(capsule, "scip")) - model._freescip = take_ownership - return model + cdef SCIP_LPI* lpi + PY_SCIP_CALL(SCIPgetLPI(self._scip, &lpi)) + cdef SCIP_Real quality = 0 + if exact: + PY_SCIP_CALL(SCIPlpiGetRealSolQuality(lpi, SCIP_LPSOLQUALITY_EXACTCONDITION, &quality)) + else: + PY_SCIP_CALL(SCIPlpiGetRealSolQuality(lpi, SCIP_LPSOLQUALITY_ESTIMCONDITION, &quality)) - @cython.always_allow_keywords(True) - def to_ptr(self, give_ownership): + return quality + + def enableReoptimization(self, enable=True): """ - Return the underlying Scip pointer to the current Model. + Include specific heuristics and branching rules for reoptimization. Parameters ---------- - give_ownership : bool - Whether the current Model gives away ownership of the - underlying Scip pointer (see ``_freescip``) + enable : bool, optional + True to enable and False to disable + + """ + PY_SCIP_CALL(SCIPenableReoptimization(self._scip, enable)) + + def isReoptEnabled(self): + """ + Returns whether reoptimization is enabled. Returns ------- - capsule - The underlying pointer to the current Model, wrapped in a - PyCapsule under the name "scip". + bool """ - capsule = PyCapsule_New(self._scip, "scip", NULL) - if give_ownership: - self._freescip = False - return capsule - - def includeDefaultPlugins(self): - """Includes all default plug-ins into SCIP.""" - PY_SCIP_CALL(SCIPincludeDefaultPlugins(self._scip)) + return SCIPisReoptEnabled(self._scip) - def createProbBasic(self, problemName='model'): + def lpiGetIterations(self): """ - Create new problem instance with given name. + Get the iteration count of the last solved LP. - Parameters - ---------- - problemName : str, optional - name of model or problem (Default value = 'model') + Returns + ------- + int """ - n = str_conversion(problemName) - PY_SCIP_CALL(SCIPcreateProbBasic(self._scip, n)) + cdef SCIP_LPI* lpi + cdef int iters = 0 - def freeProb(self): - """Frees problem and solution process data.""" - PY_SCIP_CALL(SCIPfreeProb(self._scip)) + PY_SCIP_CALL(SCIPgetLPI(self._scip, &lpi)) + PY_SCIP_CALL(SCIPlpiGetIterations(lpi, &iters)) - def free(self): - """Explicitly free the SCIP instance and release plugin references. + return iters - Every included plugin holds a strong reference to its Model via - ``self.model``, and the Model holds strong references to every plugin - via ``Model._plugins``. This cycle is intentional: it keeps both sides - alive during SCIP teardown so callbacks such as ``eventexit`` and - ``consfree`` can safely reach ``self.model``. + # Objective function + def setMinimize(self): + """Set the objective sense to minimization.""" + PY_SCIP_CALL(SCIPsetObjsense(self._scip, SCIP_OBJSENSE_MINIMIZE)) - The cycle is broken in one of two ways: + def setMaximize(self): + """Set the objective sense to maximization.""" + PY_SCIP_CALL(SCIPsetObjsense(self._scip, SCIP_OBJSENSE_MAXIMIZE)) - * Implicitly, via ``Model.__del__`` when the last external reference to - the Model is dropped. ``__del__`` runs before the garbage collector - (GC) clears attributes, so callbacks still see a live ``self.model``. - Timing is at the GC's discretion. - * Explicitly, by calling this method. SCIP is freed immediately, - teardown callbacks fire before ``free`` returns, and the plugin list - is cleared. Use this when deterministic cleanup is required. After - ``free`` the Model must not be used further. + def setObjIntegral(self): + """Informs SCIP that the objective value is always integral in every feasible solution. - The solve itself is not affected by which path runs. ``free`` only - controls when memory and resources are released, and when teardown - callbacks execute. + Notes + ----- + This function should be used to inform SCIP that the objective function is integral, + helping to improve the performance. This is useful when using column generation. + If no column generation (pricing) is used, SCIP automatically detects whether the objective + function is integral or can be scaled to be integral. However, in any case, the user has to + make sure that no variable is added during the solving process that destroys this property. """ - self._free_scip_instance() - - # Break circular references with plugins - if self._plugins: - for plugin in self._plugins: - plugin.model = None - self._plugins = [] - - # Clear Python-side caches - self._modelvars = {} - self._modelconss = {} - self._benders_subproblems = [] - self._bestSol = None - - def freeTransform(self): - """Frees all solution process data including presolving and - transformed problem, only original problem is kept.""" - if self.getStage() not in [SCIP_STAGE_INIT, - SCIP_STAGE_PROBLEM, - SCIP_STAGE_TRANSFORMED, - SCIP_STAGE_PRESOLVING, - SCIP_STAGE_PRESOLVED, - SCIP_STAGE_SOLVING, - SCIP_STAGE_SOLVED]: - raise Warning("method cannot be called in stage %i." % self.getStage()) - - # Invalidate transformed variables. See issue #604. - origvars = {ptr: var for ptr, var in self._modelvars.items() if var.isOriginal()} - for ptr, var in self._modelvars.items(): - if ptr not in origvars: - (var).scip_var = NULL - self._modelvars = origvars - - # Invalidate transformed constraints. See issue #604. - origconss = {ptr: cons for ptr, cons in self._modelconss.items() if cons.isOriginal()} - for ptr, cons in self._modelconss.items(): - if ptr not in origconss: - (cons).scip_cons = NULL - self._modelconss = origconss - - PY_SCIP_CALL(SCIPfreeTransform(self._scip)) + PY_SCIP_CALL(SCIPsetObjIntegral(self._scip)) - def version(self): + def isObjIntegral(self): """ - Retrieve SCIP version. + Returns whether the objective function is integral. Returns ------- - float - - """ - return SCIPversion() + bool - def getMajorVersion(self): """ - Retrieve SCIP major version. - - Returns - ------- - int + return SCIPisObjIntegral(self._scip) + # Setting parameters + def setPresolve(self, setting): """ - return SCIPmajorVersion() + Set presolving parameter settings. - def getMinorVersion(self): - """ - Retrieve SCIP minor version. - Returns - ------- - int + Parameters + ---------- + setting : SCIP_PARAMSETTING + the parameter settings, e.g. SCIP_PARAMSETTING.OFF """ - return SCIPminorVersion() + PY_SCIP_CALL(SCIPsetPresolving(self._scip, setting, True)) - def getTechVersion(self): + def setProbName(self, name): """ - Retrieve SCIP technical version. + Set problem name. - Returns - ------- - int + Parameters + ---------- + name : str """ - return SCIPtechVersion() - - def printVersion(self): - """Print version, copyright information and compile mode.""" - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - SCIPprintVersion(self._scip, NULL) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def printExternalCodeVersions(self): - """Print external code versions, e.g. symmetry, non-linear solver, lp solver.""" - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - SCIPprintExternalCodes(self._scip, NULL) - - locale.setlocale(locale.LC_NUMERIC,user_locale) + n = str_conversion(name) + PY_SCIP_CALL(SCIPsetProbName(self._scip, n)) - def getProbName(self): + def setSeparating(self, setting): """ - Retrieve problem name. + Set separating parameter settings. - Returns - ------- - str + Parameters + ---------- + setting : SCIP_PARAMSETTING + the parameter settings, e.g. SCIP_PARAMSETTING.OFF """ - return bytes(SCIPgetProbName(self._scip)).decode('UTF-8') + PY_SCIP_CALL(SCIPsetSeparating(self._scip, setting, True)) - def getTotalTime(self): + def setHeuristics(self, setting): """ - Retrieve the current total SCIP time in seconds, - i.e. the total time since the SCIP instance has been created. + Set heuristics parameter settings. - Returns - ------- - float + Parameters + ---------- + setting : SCIP_PARAMSETTING + the parameter settings, e.g. SCIP_PARAMSETTING.OFF """ - return SCIPgetTotalTime(self._scip) + PY_SCIP_CALL(SCIPsetHeuristics(self._scip, setting, True)) - def getSolvingTime(self): + def setHeurTiming(self, heurname, heurtiming): """ - Retrieve the current solving time in seconds. - - Returns - ------- - float + Set the timing of a heuristic + Parameters + ---------- + heurname : string, name of the heuristic + heurtiming : PY_SCIP_HEURTIMING + positions in the node solving loop where heuristic should be executed """ - return SCIPgetSolvingTime(self._scip) + cdef SCIP_HEUR* _heur + n = str_conversion(heurname) + _heur = SCIPfindHeur(self._scip, n) + if _heur == NULL: + raise ValueError("Could not find heuristic <%s>" % heurname) + SCIPheurSetTimingmask(_heur, heurtiming) - def getReadingTime(self): + def getHeurTiming(self, heurname): """ - Retrieve the current reading time in seconds. + Get the timing of a heuristic + + Parameters + ---------- + heurname : string, name of the heuristic Returns ------- - float - + PY_SCIP_HEURTIMING + positions in the node solving loop where heuristic should be executed """ - return SCIPgetReadingTime(self._scip) + cdef SCIP_HEUR* _heur + n = str_conversion(heurname) + _heur = SCIPfindHeur(self._scip, n) + if _heur == NULL: + raise ValueError("Could not find heuristic <%s>" % heurname) + return SCIPheurGetTimingmask(_heur) - def getPresolvingTime(self): + def disablePropagation(self, onlyroot=False): """ - Returns the current presolving time in seconds. + Disables propagation in SCIP to avoid modifying the original problem during transformation. - Returns - ------- - float + Parameters + ---------- + onlyroot : bool, optional + use propagation when root processing is finished (Default value = False) """ - return SCIPgetPresolvingTime(self._scip) + self.setIntParam("propagating/maxroundsroot", 0) + if not onlyroot: + self.setIntParam("propagating/maxrounds", 0) - def getDeterministicTime(self): + def printProblem(self, ext='.cip', trans=False, genericnames=False): """ - Computes a deterministic measure of time from statistics. - - Returns - ------- - float + Write current model/problem to standard output. + Parameters + ---------- + ext : str, optional + the extension to be used (Default value = '.cip'). + Should have an extension corresponding to one of the readable file formats, + described in https://www.scipopt.org/doc/html/group__FILEREADERS.php. + trans : bool, optional + indicates whether the transformed problem is written to file (Default value = False) + genericnames : bool, optional + indicates whether the problem should be written with generic variable + and constraint names (Default value = False) """ - return SCIPgetDeterministicTime(self._scip) + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") - def getFirstPrimalBound(self): - """ - Gets the primal bound of the very first solution in the original space. + if trans: + PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, NULL, str_conversion(ext)[1:], genericnames)) + else: + PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, NULL, str_conversion(ext)[1:], genericnames)) - Returns - ------- - float + locale.setlocale(locale.LC_NUMERIC,user_locale) + def writeProblem(self, filename='model.cip', trans=False, genericnames=False, verbose=True): """ - return SCIPgetFirstPrimalBound(self._scip) + Write current model/problem to a file. - def getNLPIterations(self): - """ - Returns the total number of LP iterations so far. - - Returns - ------- - int + Parameters + ---------- + filename : str, optional + the name of the file to be used (Default value = 'model.cip'). + Should have an extension corresponding to one of the readable file formats, + described in https://www.scipopt.org/doc/html/group__FILEREADERS.php. + trans : bool, optional + indicates whether the transformed problem is written to file (Default value = False) + genericnames : bool, optional + indicates whether the problem should be written with generic variable + and constraint names (Default value = False) + verbose : bool, optional + indicates whether a success message should be printed """ - return SCIPgetNLPIterations(self._scip) + user_locale = locale.getlocale(category=locale.LC_NUMERIC) + locale.setlocale(locale.LC_NUMERIC, "C") - def getNRuns(self): - """ - Gets number of branch and bound runs performed, including the current run + if filename: + str_absfile = abspath(filename) + absfile = str_conversion(str_absfile) + fn, ext = splitext(absfile) + if len(ext) == 0: + ext = str_conversion('.cip') + fn = fn + ext + ext = ext[1:] - Returns - ------- - int + if trans: + PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, fn, ext, genericnames)) + else: + PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, fn, ext, genericnames)) - """ - return SCIPgetNRuns(self._scip) + if verbose: + print('wrote problem to file ' + str_absfile) + else: + if trans: + PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, NULL, str_conversion('.cip')[1:], genericnames)) + else: + PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, NULL, str_conversion('.cip')[1:], genericnames)) - def getNReoptRuns(self): + locale.setlocale(locale.LC_NUMERIC,user_locale) + + def getTransformedVar(self, Variable var): """ - Gets number of reoptimization runs performed, including the current run + Retrieve the transformed variable. + + Parameters + ---------- + var : Variable + original variable to get the transformed of Returns ------- - int + Variable """ - return SCIPgetNReoptRuns(self._scip) + cdef SCIP_VAR* _tvar + PY_SCIP_CALL(SCIPgetTransformedVar(self._scip, var.scip_var, &_tvar)) + return self._getOrCreateVar(_tvar) - def addNNodes(self, nnodes): + def addVarLocks(self, Variable var, int nlocksdown, int nlocksup): """ - Add given number to the number of processed nodes in current run and in all runs, including the focus node + Adds given values to lock numbers of variable for rounding. Parameters ---------- - nnodes : int + var : Variable + variable to adjust the locks for + nlocksdown : int + new number of down locks + nlocksup : int + new number of up locks """ - SCIPaddNNodes(self._scip, nnodes) + PY_SCIP_CALL(SCIPaddVarLocks(self._scip, var.scip_var, nlocksdown, nlocksup)) - def getNNodes(self): + def addVarLocksType(self, Variable var, int locktype, int nlocksdown, int nlocksup): """ - Gets number of processed nodes in current run, including the focus node. + adds given values to lock numbers of type locktype of variable for rounding - Returns - ------- - int + Parameters + ---------- + var : Variable + variable to adjust the locks for + locktype : SCIP_LOCKTYPE + type of variable locks + nlocksdown : int + modification in number of down locks + nlocksup : int + modification in number of up locks """ - return SCIPgetNNodes(self._scip) + PY_SCIP_CALL(SCIPaddVarLocksType(self._scip, var.scip_var, locktype, nlocksdown, nlocksup)) - def getNTotalNodes(self): + def delVar(self, Variable var): """ - Gets number of processed nodes in all runs, including the focus node. + Delete a variable. + + Parameters + ---------- + var : Variable + the variable which shall be deleted Returns ------- - int + deleted : bool + Whether deleting was successfull """ - return SCIPgetNTotalNodes(self._scip) + cdef SCIP_Bool deleted + del self._modelvars[var.ptr()] + PY_SCIP_CALL(SCIPdelVar(self._scip, var.scip_var, &deleted)) + # Invalidate pointer after deletion. See issue #604. + var.scip_var = NULL + return deleted - def getNFeasibleLeaves(self): + def chgVarType(self, Variable var, vtype): """ - Retrieve number of leaf nodes processed with feasible relaxation solution. + Changes the type of a variable. - Returns - ------- - int + Parameters + ---------- + var : Variable + variable to change type of + vtype : str + new variable type. 'C' or "CONTINUOUS", 'I' or "INTEGER", + 'B' or "BINARY", and 'M' "IMPLINT". """ - return SCIPgetNFeasibleLeaves(self._scip) + cdef SCIP_Bool infeasible + if vtype in ['C', 'CONTINUOUS']: + PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_CONTINUOUS, &infeasible)) + elif vtype in ['B', 'BINARY']: + PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_BINARY, &infeasible)) + elif vtype in ['I', 'INTEGER']: + PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_INTEGER, &infeasible)) + elif vtype in ['M', 'IMPLINT']: + PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_DEPRECATED_VARTYPE_IMPLINT, &infeasible)) + else: + raise Warning("unrecognized variable type") + if infeasible: + print('could not change variable type of variable %s' % var) - def getNInfeasibleLeaves(self): + def markDoNotAggrVar(self, Variable var): """ - Gets number of infeasible leaf nodes processed. - - Returns - ------- - int + Marks a variable preventing it from being aggregated. + Parameters + ---------- + var : Variable + variable to mark """ - return SCIPgetNInfeasibleLeaves(self._scip) + PY_SCIP_CALL(SCIPmarkDoNotAggrVar(self._scip, var.scip_var)) - def getNObjlimLeaves(self): + def markDoNotMultaggrVar(self, Variable var): """ - Gets number of processed leaf nodes that hit LP objective limit. - - Returns - ------- - int + Marks a variable preventing it from being multi-aggregated. + Parameters + ---------- + var : Variable + variable to mark """ - return SCIPgetNObjlimLeaves(self._scip) + PY_SCIP_CALL(SCIPmarkDoNotMultaggrVar(self._scip, var.scip_var)) - def getNLeaves(self): + def getVars(self, transformed=False): """ - Gets number of leaves in the tree. + Retrieve all variables. + + Parameters + ---------- + transformed : bool, optional + Get transformed variables instead of original (Default value = False) Returns ------- - int + list of Variable """ - return SCIPgetNLeaves(self._scip) + cdef SCIP_VAR** _vars + cdef int nvars + cdef int i - def getNNodesLeft(self): + vars = [] + if transformed: + _vars = SCIPgetVars(self._scip) + nvars = SCIPgetNVars(self._scip) + else: + _vars = SCIPgetOrigVars(self._scip) + nvars = SCIPgetNOrigVars(self._scip) + + for i in range(nvars): + vars.append(self._getOrCreateVar(_vars[i])) + + return vars + + def getNVars(self, transformed=True): """ - Gets number of nodes left in the tree (children + siblings + leaves) + Retrieve number of variables in the problems. + + Parameters + ---------- + transformed : bool, optional + Get transformed variables instead of original (Default value = True) Returns ------- int """ - return SCIPgetNNodesLeft(self._scip) + if transformed: + return SCIPgetNVars(self._scip) + else: + return SCIPgetNOrigVars(self._scip) - def getNChildren(self): + def getNIntVars(self): """ - Gets number of children of focus node. + Gets number of integer active problem variables. Returns ------- int """ - return SCIPgetNChildren(self._scip) + return SCIPgetNIntVars(self._scip) - def getNSiblings(self): + def getNBinVars(self): """ - Gets number of siblings of focus node. + Gets number of binary active problem variables. Returns ------- int """ - return SCIPgetNSiblings(self._scip) + return SCIPgetNBinVars(self._scip) - def getFocusNode(self): + def getNImplVars(self): """ - Gets focus node in the tree. - If we are in probing/diving mode this method returns the node in the tree where the probing/diving mode was started. + Gets number of implicit integer active problem variables. Returns ------- - Node + int """ - return Node.create(SCIPgetFocusNode(self._scip)) + return SCIPgetNImplVars(self._scip) - def getCurrentNode(self): + def getNContVars(self): """ - Retrieve current node. + Gets number of continuous active problem variables. Returns ------- - Node + int """ - return Node.create(SCIPgetCurrentNode(self._scip)) + return SCIPgetNContVars(self._scip) - def getGap(self): + def getVarPseudocostScore(self, Variable var, solVal): """ - Retrieve the gap, - i.e. abs((primalbound - dualbound)/min(abs(primalbound),abs(dualbound))) + gets the variable's pseudo cost score value for the given LP solution value + + Parameters + ---------- + variable : Variable + problem variable + solVal : float + difference of variable's new LP value - old LP value Returns ------- float - """ - return SCIPgetGap(self._scip) + return SCIPgetVarPseudocostScore(self._scip, var.scip_var, solVal) - def getDepth(self): + def getVarPseudocost(self, Variable var, branchdir): """ - Retrieve the depth of the current node. + gets the variable's pseudo cost value for the given direction + + Parameters + ---------- + variable : Variable + problem variable + branchdir : PY_SCIP_BRANCHDIR + branching direction (downwards, or upwards) Returns ------- - int - + float """ - return SCIPgetDepth(self._scip) + return SCIPgetVarPseudocost(self._scip, var.scip_var, branchdir) - def getMaxDepth(self): + def relax(self): + """Relaxes the integrality restrictions of the model.""" + if self.getStage() != SCIP_STAGE_PROBLEM: + raise Warning("method can only be called in stage PROBLEM") + + for var in self.getVars(): + self.chgVarType(var, "C") + + # Node methods + def getBestChild(self): """ - Gets maximal depth of the branch-and-bound tree processed during solving (excluding probing nodes). + Gets the best child of the focus node w.r.t. the node selection strategy. Returns ------- - int + Node """ - return SCIPgetMaxDepth(self._scip) - - def getMaxTotalDepth(self): + return Node.create(SCIPgetBestChild(self._scip)) + + def getChildren(self): """ - Gets maximal depth of all processed nodes over all branch and bound runs. + Gets the children of the focus node. Returns ------- - int + list of Nodes """ - return SCIPgetMaxTotalDepth(self._scip) + cdef SCIP_NODE** _children + cdef int n_children + cdef int i - def getNBacktracks(self): + PY_SCIP_CALL(SCIPgetChildren(self._scip, &_children, &n_children)) + + return [Node.create(_children[i]) for i in range(n_children)] + + def getSiblings(self): """ - Gets total number of backtracks, i.e., number of times the new node was selected from the leaves queue. + Gets the siblings of the focus node. Returns ------- - int + list of Nodes """ - return SCIPgetNBacktracks(self._scip) + cdef SCIP_NODE** _siblings + cdef int n_siblings + cdef int i - def getPlungeDepth(self): + PY_SCIP_CALL(SCIPgetSiblings(self._scip, &_siblings, &n_siblings)) + + return [Node.create(_siblings[i]) for i in range(n_siblings)] + + def getLeaves(self): """ - Gets current plunging depth (successive selections of child/sibling nodes). + Gets the leaves of the tree along with number of leaves. Returns ------- - int + list of Nodes """ - return SCIPgetPlungeDepth(self._scip) + cdef SCIP_NODE** _leaves + cdef int n_leaves + cdef int i + + PY_SCIP_CALL(SCIPgetLeaves(self._scip, &_leaves, &n_leaves)) - def getAvgLowerbound(self): + return [Node.create(_leaves[i]) for i in range(n_leaves)] + + def getBestSibling(self): """ - Gets average lower (dual) bound of all unprocessed nodes in transformed problem. + Gets the best sibling of the focus node w.r.t. the node selection strategy. Returns ------- - float + Node """ - return SCIPgetAvgLowerbound(self._scip) + return Node.create(SCIPgetBestSibling(self._scip)) - def getAvgDualbound(self): + def getPrioChild(self): """ - Gets average dual bound of all unprocessed nodes for original problem. + Gets the best child of the focus node w.r.t. the node selection priority + assigned by the branching rule. Returns ------- - float + Node """ - return SCIPgetAvgDualbound(self._scip) + return Node.create(SCIPgetPrioChild(self._scip)) - def getLowerbound(self): - """ - Gets global lower (dual) bound of the transformed problem. + def getPrioSibling(self): + """Gets the best sibling of the focus node w.r.t. + the node selection priority assigned by the branching rule. Returns ------- - float + Node """ - return SCIPgetLowerbound(self._scip) + return Node.create(SCIPgetPrioSibling(self._scip)) - def getCutoffbound(self): - """ - Gets the cutoff bound of the transformed problem. + def getBestLeaf(self): + """Gets the best leaf from the node queue w.r.t. the node selection strategy. Returns ------- - float + Node """ - return SCIPgetCutoffbound(self._scip) + return Node.create(SCIPgetBestLeaf(self._scip)) - def getUpperbound(self): - """ - Gets global upper (primal) bound in transformed problem (objective value of best solution or user objective limit). + def getBestNode(self): + """Gets the best node from the tree (child, sibling, or leaf) w.r.t. the node selection strategy. Returns ------- - float - """ - return SCIPgetUpperbound(self._scip) + Node - def getNNodeLPIterations(self): """ - Gets number of LP iterations used for solving node relaxations so far. + return Node.create(SCIPgetBestNode(self._scip)) + + def getBestboundNode(self): + """Gets the node with smallest lower bound from the tree (child, sibling, or leaf). Returns ------- - int + Node """ - return SCIPgetNNodeLPIterations(self._scip) + return Node.create(SCIPgetBestboundNode(self._scip)) - def getNStrongbranchLPIterations(self): + def getOpenNodes(self): """ - Gets number of LP iterations used for strong branching so far. + Access to all data of open nodes (leaves, children, and siblings). Returns ------- - int + leaves : list of Node + list of all open leaf nodes + children : list of Node + list of all open children nodes + siblings : list of Node + list of all open sibling nodes """ - return SCIPgetNStrongbranchLPIterations(self._scip) + cdef SCIP_NODE** _leaves + cdef SCIP_NODE** _children + cdef SCIP_NODE** _siblings + cdef int _nleaves + cdef int _nchildren + cdef int _nsiblings + cdef int i - def getPrimalDualIntegral(self): - """ - Recomputes and returns the primal dual gap stored in the stats + PY_SCIP_CALL(SCIPgetOpenNodesData(self._scip, &_leaves, &_children, &_siblings, &_nleaves, &_nchildren, &_nsiblings)) - Returns - ------ - float - """ - return SCIPgetPrimalDualIntegral(self._scip) + leaves = [Node.create(_leaves[i]) for i in range(_nleaves)] + children = [Node.create(_children[i]) for i in range(_nchildren)] + siblings = [Node.create(_siblings[i]) for i in range(_nsiblings)] - def cutoffNode(self, Node node): - """ - marks node and whole subtree to be cut off from the branch and bound tree. + return leaves, children, siblings - Parameters - ---------- - node : Node - """ - PY_SCIP_CALL( SCIPcutoffNode(self._scip, node.scip_node) ) + def repropagateNode(self, Node node): + """Marks the given node to be propagated again the next time a node of its subtree is processed.""" + PY_SCIP_CALL(SCIPrepropagateNode(self._scip, node.scip_node)) - def infinity(self): + def constructLP(self): """ - Retrieve SCIP's infinity value. + Makes sure that the LP of the current node is loaded and + may be accessed through the LP information methods. + Returns ------- - int + cutoff : bool + Can the node be cutoff? """ - return SCIPinfinity(self._scip) + cdef SCIP_Bool cutoff + PY_SCIP_CALL(SCIPconstructLP(self._scip, &cutoff)) + return cutoff - def epsilon(self): + def getNLPRows(self): """ - Retrieve epsilon for e.g. equality checks. + Retrieve the number of rows currently in the LP. Returns ------- - float + int """ - return SCIPepsilon(self._scip) + return SCIPgetNLPRows(self._scip) - def feastol(self): + def getNLPCols(self): """ - Retrieve feasibility tolerance. + Retrieve the number of columns currently in the LP. Returns ------- - float + int """ - return SCIPfeastol(self._scip) + return SCIPgetNLPCols(self._scip) - def feasFrac(self, value): + def getLPBasisInd(self): """ - Returns fractional part of value, i.e. x - floor(x) in feasible tolerance: x - floor(x+feastol). - - Parameters - ---------- - value : float + Gets all indices of basic columns and rows: + index i >= 0 corresponds to column i, index i < 0 to row -i-1 Returns ------- - float + list of int """ - return SCIPfeasFrac(self._scip, value) + cdef int nrows = SCIPgetNLPRows(self._scip) + cdef int* inds = malloc(nrows * sizeof(int)) + cdef int i - def frac(self, value): - """ - Returns fractional part of value, i.e. x - floor(x) in epsilon tolerance: x - floor(x+eps). + PY_SCIP_CALL(SCIPgetLPBasisInd(self._scip, inds)) + result = [inds[i] for i in range(nrows)] + free(inds) - Parameters - ---------- - value : float + return result + + def isLPSolBasic(self): + """ + Returns whether the current LP solution is basic, i.e. is defined by a valid simplex basis. Returns ------- - float + bool """ - return SCIPfrac(self._scip, value) + return SCIPisLPSolBasic(self._scip) - def feasFloor(self, value): + def allColsInLP(self): """ - Rounds value + feasibility tolerance down to the next integer. - - Parameters - ---------- - value : float + Checks if all columns, i.e. every variable with non-empty column is present in the LP. + This is not True when performing pricing for instance. Returns ------- - float + bool """ - return SCIPfeasFloor(self._scip, value) - def feasCeil(self, value): - """ - Rounds value - feasibility tolerance up to the next integer. + return SCIPallColsInLP(self._scip) - Parameters - ---------- - value : float + def getNCuts(self): + """ + Retrieve total number of cuts in storage. Returns ------- - float + int """ - return SCIPfeasCeil(self._scip, value) + return SCIPgetNCuts(self._scip) - def feasRound(self, value): + def getNCutsApplied(self): """ - Rounds value to the nearest integer in feasibility tolerance. - - Parameters - ---------- - value : float + Retrieve number of currently applied cuts. Returns ------- - float + int """ - return SCIPfeasRound(self._scip, value) + return SCIPgetNCutsApplied(self._scip) - def isZero(self, value): + def getNSepaRounds(self): """ - Returns whether abs(value) < eps. - - Parameters - ---------- - value : float + Retrieve the number of separation rounds that have been performed + at the current node. Returns ------- - bool + int """ - return SCIPisZero(self._scip, value) + return SCIPgetNSepaRounds(self._scip) - def isFeasZero(self, value): + def separateSol(self, Solution sol = None, pretendroot = False, allowlocal = True, onlydelayed = False): """ - Returns whether abs(value) < feastol. + Separates the given primal solution or the current LP solution by calling + the separators and constraint handlers' separation methods; + the generated cuts are stored in the separation storage and can be accessed + with the methods SCIPgetCuts() and SCIPgetNCuts(); + after evaluating the cuts, you have to call SCIPclearCuts() in order to remove the cuts from the + separation storage; it is possible to call SCIPseparateSol() multiple times with + different solutions and evaluate the found cuts afterwards. Parameters ---------- - value : float + sol : Solution or None, optional + solution to separate, None to use current lp solution (Default value = None) + pretendroot : bool, optional + should the cut separators be called as if we are at the root node? (Default value = "False") + allowlocal : bool, optional + should the separator be asked to separate local cuts (Default value = True) + onlydelayed : bool, optional + should only separators be called that were delayed in the previous round? (Default value = False) Returns ------- - bool - - """ - return SCIPisFeasZero(self._scip, value) + delayed : bool + whether a separator was delayed + cutoff : bool + whether the node can be cut off - def isInfinity(self, value): """ - Returns whether value is SCIP's infinity. + cdef SCIP_Bool delayed + cdef SCIP_Bool cutoff - Parameters - ---------- - value : float + PY_SCIP_CALL( SCIPseparateSol(self._scip, NULL if sol is None else sol.sol, pretendroot, allowlocal, onlydelayed, &delayed, &cutoff) ) + return delayed, cutoff - Returns - ------- - bool + def addConss(self, conss, name='', initial=True, separate=True, + enforce=True, check=True, propagate=True, local=False, + modifiable=False, dynamic=False, removable=False, + stickingatnode=False): + """Adds multiple constraints. - """ - return SCIPisInfinity(self._scip, value) + Each of the constraints is added to the model using Model.addCons(). - def isFeasNegative(self, value): - """ - Returns whether value < -feastol. + For all parameters, except `conss`, this method behaves differently depending on the + type of the passed argument: + 1. If the value is iterable, it must be of the same length as `conss`. For each + constraint, Model.addCons() will be called with the value at the corresponding index. + 2. Else, the (default) value will be applied to all of the constraints. Parameters ---------- - value : float + conss : iterable of ExprCons + An iterable of constraint objects. Any iterable will be converted into a list before further processing. + name : str or iterable of str, optional + the name of the constraint, generic name if empty (Default value = '') + initial : bool or iterable of bool, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool or iterable of bool, optional + should the constraint be separated during LP processing? (Default value = True) + enforce : bool or iterable of bool, optional + should the constraint be enforced during node processing? (Default value = True) + check : bool or iterable of bool, optional + should the constraint be checked for feasibility? (Default value = True) + propagate : bool or iterable of bool, optional + should the constraint be propagated during node processing? (Default value = True) + local : bool or iterable of bool, optional + is the constraint only valid locally? (Default value = False) + modifiable : bool or iterable of bool, optional + is the constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool or iterable of bool, optional + is the constraint subject to aging? (Default value = False) + removable : bool or iterable of bool, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool or iterable of bool, optional + should the constraints always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) Returns ------- - bool + list of Constraint + The created and added Constraint objects. """ - return SCIPisFeasNegative(self._scip, value) + cdef int n_conss + cdef int i - def isFeasPositive(self, value): - """ - Returns whether value > feastol. + if isinstance(conss, MatrixExprCons): + conss = conss.flatten() - Parameters - ---------- - value : float + def ensure_iterable(elem, length): + if isinstance(elem, Iterable): + return elem + else: + return list(repeat(elem, length)) - Returns - ------- - bool + assert isinstance(conss, Iterable), "Given constraint list is not iterable." - """ - return SCIPisFeasPositive(self._scip, value) + conss = list(conss) + n_conss = len(conss) - def isFeasIntegral(self, value): - """ - Returns whether value is integral within the LP feasibility bounds. + if isinstance(name, str): + if name == "": + name = ["" for i in range(n_conss)] + else: + name = ["%s_%s" % (name, i) for i in range(n_conss)] - Parameters - ---------- - value : float + initial = ensure_iterable(initial, n_conss) + separate = ensure_iterable(separate, n_conss) + enforce = ensure_iterable(enforce, n_conss) + check = ensure_iterable(check, n_conss) + propagate = ensure_iterable(propagate, n_conss) + local = ensure_iterable(local, n_conss) + modifiable = ensure_iterable(modifiable, n_conss) + dynamic = ensure_iterable(dynamic, n_conss) + removable = ensure_iterable(removable, n_conss) + stickingatnode = ensure_iterable(stickingatnode, n_conss) - Returns - ------- - bool + constraints = [] + for i, cons in enumerate(conss): + constraints.append( + self.addCons(cons, name[i], initial[i], separate[i], enforce[i], + check[i], propagate[i], local[i], modifiable[i], + dynamic[i], removable[i], stickingatnode[i]) + ) - """ - return SCIPisFeasIntegral(self._scip, value) + return constraints - def isIntegral(self, value): + def addMatrixCons(self, + cons: Union[ExprCons, MatrixExprCons], + name: Union[str, np.ndarray] ='', + initial: Union[bool, np.ndarray] = True, + separate: Union[bool, np.ndarray] = True, + enforce: Union[bool, np.ndarray] = True, + check: Union[bool, np.ndarray] = True, + propagate: Union[bool, np.ndarray] = True, + local: Union[bool, np.ndarray] = False, + modifiable: Union[bool, np.ndarray] = False, + dynamic: Union[bool, np.ndarray] = False, + removable: Union[bool, np.ndarray] = False, + stickingatnode: Union[bool, np.ndarray] = False): """ - Returns whether value is integral within epsilon tolerance. + Add a linear or nonlinear matrix constraint. Parameters ---------- - value : float - value to check + cons : ExprCons or MatrixExprCons + The matrix expression constraint or expression constraint, that are not yet an actual constraint + name : str or np.ndarray, optional + the name of the matrix constraint, generic name if empty (Default value = "") + initial : bool or np.ndarray, optional + should the LP relaxation of constraint be in the initial LP? (Default value = True) + separate : bool or np.ndarray, optional + should the matrix constraint be separated during LP processing? (Default value = True) + enforce : bool or np.ndarray, optional + should the matrix constraint be enforced during node processing? (Default value = True) + check : bool or np.ndarray, optional + should the matrix constraint be checked for feasibility? (Default value = True) + propagate : bool or np.ndarray, optional + should the matrix constraint be propagated during node processing? (Default value = True) + local : bool or np.ndarray, optional + is the matrix constraint only valid locally? (Default value = False) + modifiable : bool or np.ndarray, optional + is the matrix constraint modifiable (subject to column generation)? (Default value = False) + dynamic : bool or np.ndarray, optional + is the matrix constraint subject to aging? (Default value = False) + removable : bool or np.ndarray, optional + should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) + stickingatnode : bool or np.ndarray, optional + should the matrix constraints always be kept at the node where it was added, + even if it may be moved to a more global node? (Default value = False) Returns ------- - bool - - """ - return SCIPisIntegral(self._scip, value) - - def adjustedVarLb(self, Variable var, lb): + Constraint or MatrixConstraint + The created and added Constraint or MatrixConstraint. """ - Returns the adjusted (i.e. rounded, if the given variable is of integral type) lower bound value; - does not change the bounds of the variable. + if not isinstance(cons, (ExprCons, MatrixExprCons)): + raise TypeError("given constraint is not MatrixExprCons nor ExprCons but %s" % cons.__class__.__name__) - Parameters - ---------- - var : Variable - variable for which the bound is adjusted - lb : float - lower bound value to adjust + if isinstance(cons, ExprCons): + return self.addCons(cons, name=name, initial=initial, separate=separate, + enforce=enforce, check=check, propagate=propagate, + local=local, modifiable=modifiable, dynamic=dynamic, + removable=removable, stickingatnode=stickingatnode) - Returns - ------- - float - adjusted lower bound + shape = cons.shape - """ - return SCIPadjustedVarLb(self._scip, var.scip_var, lb) + if isinstance(name, np.ndarray): + assert name.shape == shape + if isinstance(initial, np.ndarray): + assert initial.shape == shape + if isinstance(separate, np.ndarray): + assert separate.shape == shape + if isinstance(enforce, np.ndarray): + assert enforce.shape == shape + if isinstance(check, np.ndarray): + assert check.shape == shape + if isinstance(propagate, np.ndarray): + assert propagate.shape == shape + if isinstance(local, np.ndarray): + assert local.shape == shape + if isinstance(modifiable, np.ndarray): + assert modifiable.shape == shape + if isinstance(dynamic, np.ndarray): + assert dynamic.shape == shape + if isinstance(removable, np.ndarray): + assert removable.shape == shape + if isinstance(stickingatnode, np.ndarray): + assert stickingatnode.shape == shape - def adjustedVarUb(self, Variable var, ub): - """ - Returns the adjusted (i.e. rounded, if the given variable is of integral type) upper bound value; - does not change the bounds of the variable. + matrix_cons = np.empty(shape, dtype=object) - Parameters - ---------- - var : Variable - variable for which the bound is adjusted - ub : float - upper bound value to adjust + if isinstance(shape, int): + ndim = 1 + else: + ndim = len(shape) + # cdef np.ndarray[object, ndim=ndim] matrix_variable = np.empty(shape, dtype=object) + matrix_variable = np.empty(shape, dtype=object) - Returns - ------- - float - adjusted upper bound + if isinstance(name, str): + matrix_names = np.full(shape, name, dtype=object) + if name != "": + for idx in np.ndindex(matrix_variable.shape): + matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" + else: + matrix_names = name - """ - return SCIPadjustedVarUb(self._scip, var.scip_var, ub) + if not isinstance(initial, np.ndarray): + matrix_initial = np.full(shape, initial, dtype=bool) + else: + matrix_initial = initial - def isEQ(self, val1, val2): - """ - Checks, if values are in range of epsilon. + if not isinstance(separate, np.ndarray): + matrix_separate = np.full(shape, separate, dtype=bool) + else: + matrix_separate = separate - Parameters - ---------- - val1 : float - val2 : float + if not isinstance(enforce, np.ndarray): + matrix_enforce = np.full(shape, enforce, dtype=bool) + else: + matrix_enforce = enforce - Returns - ------- - bool + if not isinstance(check, np.ndarray): + matrix_check = np.full(shape, check, dtype=bool) + else: + matrix_check = check - """ - return SCIPisEQ(self._scip, val1, val2) + if not isinstance(propagate, np.ndarray): + matrix_propagate = np.full(shape, propagate, dtype=bool) + else: + matrix_propagate = propagate - def isFeasEQ(self, val1, val2): - """ - Returns if relative difference between val1 and val2 is in range of feasibility tolerance. + if not isinstance(local, np.ndarray): + matrix_local = np.full(shape, local, dtype=bool) + else: + matrix_local = local - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisFeasEQ(self._scip, val1, val2) - - def isFeasLT(self, val1, val2): - """ - Returns whether relative difference between val1 and val2 is lower than minus feasibility tolerance. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisFeasLT(self._scip, val1, val2) - - def isFeasLE(self, val1, val2): - """ - Returns whether relative difference between val1 and val2 is not greater than feasibility tolerance. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisFeasLE(self._scip, val1, val2) - - def isFeasGT(self, val1, val2): - """ - Returns whether relative difference between val1 and val2 is greater than feasibility tolerance. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisFeasGT(self._scip, val1, val2) - - def isFeasGE(self, val1, val2): - """ - Returns whether relative difference of val1 and val2 is not lower than minus feasibility tolerance. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisFeasGE(self._scip, val1, val2) - - def isLE(self, val1, val2): - """ - Returns whether val1 <= val2 + eps. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisLE(self._scip, val1, val2) - - def isLT(self, val1, val2): - """ - Returns whether val1 < val2 - eps. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisLT(self._scip, val1, val2) - - def isGE(self, val1, val2): - """ - Returns whether val1 >= val2 - eps. - - Parameters - ---------- - val1 : float - val2 : float - - Returns - ------- - bool - - """ - return SCIPisGE(self._scip, val1, val2) - - def isGT(self, val1, val2): - """ - Returns whether val1 > val2 + eps. - - Parameters - ---------- - val1 : float - val2 : foat - - Returns - ------- - bool - - """ - return SCIPisGT(self._scip, val1, val2) - - def isHugeValue(self, val): - """ - Checks if value is huge and should be - handled separately (e.g., in activity computation). - - Parameters - ---------- - val : float - - Returns - ------- - bool - - """ - return SCIPisHugeValue(self._scip, val) - - def isPositive(self, val): - """ - Returns whether val > eps. - - Parameters - ---------- - val : float - - Returns - ------- - bool - - """ - return SCIPisPositive(self._scip, val) - - def isNegative(self, val): - """ - Returns whether val < -eps. - - Parameters - ---------- - val : float - - Returns - ------- - bool - - """ - return SCIPisNegative(self._scip, val) - - def getCondition(self, exact=False): - """ - Get the current LP's condition number. - - Parameters - ---------- - exact : bool, optional - whether to get an estimate or the exact value (Default value = False) - - Returns - ------- - float - - """ - cdef SCIP_LPI* lpi - PY_SCIP_CALL(SCIPgetLPI(self._scip, &lpi)) - cdef SCIP_Real quality = 0 - if exact: - PY_SCIP_CALL(SCIPlpiGetRealSolQuality(lpi, SCIP_LPSOLQUALITY_EXACTCONDITION, &quality)) - else: - PY_SCIP_CALL(SCIPlpiGetRealSolQuality(lpi, SCIP_LPSOLQUALITY_ESTIMCONDITION, &quality)) - - return quality - - def enableReoptimization(self, enable=True): - """ - Include specific heuristics and branching rules for reoptimization. - - Parameters - ---------- - enable : bool, optional - True to enable and False to disable - - """ - PY_SCIP_CALL(SCIPenableReoptimization(self._scip, enable)) - - def isReoptEnabled(self): - """ - Returns whether reoptimization is enabled. - - Returns - ------- - bool - - """ - return SCIPisReoptEnabled(self._scip) - - def lpiGetIterations(self): - """ - Get the iteration count of the last solved LP. - - Returns - ------- - int - - """ - cdef SCIP_LPI* lpi - cdef int iters = 0 - - PY_SCIP_CALL(SCIPgetLPI(self._scip, &lpi)) - PY_SCIP_CALL(SCIPlpiGetIterations(lpi, &iters)) - - return iters - - # Objective function - def setMinimize(self): - """Set the objective sense to minimization.""" - PY_SCIP_CALL(SCIPsetObjsense(self._scip, SCIP_OBJSENSE_MINIMIZE)) - - def setMaximize(self): - """Set the objective sense to maximization.""" - PY_SCIP_CALL(SCIPsetObjsense(self._scip, SCIP_OBJSENSE_MAXIMIZE)) - - def setObjlimit(self, objlimit): - """ - Set a limit on the objective function. - Only solutions with objective value better than this limit are accepted. - - Parameters - ---------- - objlimit : float - limit on the objective function - - """ - PY_SCIP_CALL(SCIPsetObjlimit(self._scip, objlimit)) - - def getObjlimit(self): - """ - Returns current limit on objective function. - - Returns - ------- - float - - """ - return SCIPgetObjlimit(self._scip) - - def setObjective(self, expr, sense = 'minimize', clear = 'true'): - """ - Establish the objective function as a linear expression. - - Parameters - ---------- - expr : Expr or float - the objective function SCIP Expr, or constant value - sense : str, optional - the objective sense ("minimize" or "maximize") (Default value = 'minimize') - clear : bool, optional - set all other variables objective coefficient to zero (Default value = 'true') - - """ - cdef SCIP_VAR** vars - cdef int nvars - cdef SCIP_Real coef - cdef int i - cdef _VarArray wrapper - - if not isinstance(expr, Expr) and not _is_number(expr): - raise TypeError( - f"requires Expr or number but got type {type(expr).__name__!s}" - ) - - # turn the constant value into an Expr instance for further processing - expr = Expr() + expr - if expr.degree() > 1: - raise ValueError("SCIP does not support nonlinear objective functions. Consider using set_nonlinear_objective in the pyscipopt.recipe.nonlinear") - - if clear: - # clear existing objective function - self.addObjoffset(-self.getObjoffset()) - vars = SCIPgetOrigVars(self._scip) - nvars = SCIPgetNOrigVars(self._scip) - for i in range(nvars): - PY_SCIP_CALL(SCIPchgVarObj(self._scip, vars[i], 0.0)) - - if expr[CONST] != 0.0: - self.addObjoffset(expr[CONST]) - - for term, coef in expr.terms.items(): - # avoid CONST term of Expr - if term != CONST: - assert len(term) == 1 - wrapper = _VarArray(term[0]) - PY_SCIP_CALL(SCIPchgVarObj(self._scip, wrapper.ptr[0], coef)) - - if sense == "minimize": - self.setMinimize() - elif sense == "maximize": - self.setMaximize() - else: - raise Warning("unrecognized optimization sense: %s" % sense) - - def getObjective(self): - """ - Retrieve objective function as Expr. - - Returns - ------- - Expr - - """ - variables = self.getVars() - objective = Expr() - for var in variables: - coeff = var.getObj() - if coeff != 0: - objective += coeff * var - objective.normalize() - return objective - - def addObjoffset(self, offset, solutions = False): - """ - Add constant offset to objective. - - Parameters - ---------- - offset : float - offset to add - solutions : bool, optional - add offset also to existing solutions (Default value = False) - - """ - if solutions: - PY_SCIP_CALL(SCIPaddObjoffset(self._scip, offset)) - else: - PY_SCIP_CALL(SCIPaddOrigObjoffset(self._scip, offset)) - - def getObjoffset(self, original = True): - """ - Retrieve constant objective offset - - Parameters - ---------- - original : bool, optional - offset of original or transformed problem (Default value = True) - - Returns - ------- - float - - """ - if original: - return SCIPgetOrigObjoffset(self._scip) - else: - return SCIPgetTransObjoffset(self._scip) - - def setObjIntegral(self): - """Informs SCIP that the objective value is always integral in every feasible solution. - - Notes - ----- - This function should be used to inform SCIP that the objective function is integral, - helping to improve the performance. This is useful when using column generation. - If no column generation (pricing) is used, SCIP automatically detects whether the objective - function is integral or can be scaled to be integral. However, in any case, the user has to - make sure that no variable is added during the solving process that destroys this property. - """ - PY_SCIP_CALL(SCIPsetObjIntegral(self._scip)) - - def isObjIntegral(self): - """ - Returns whether the objective function is integral. - - Returns - ------- - bool - - """ - return SCIPisObjIntegral(self._scip) - - def getLocalEstimate(self, original = False): - """ - Gets estimate of best primal solution w.r.t. original or transformed problem contained in current subtree. - - Parameters - ---------- - original : bool, optional - get estimate of original or transformed problem (Default value = False) - - Returns - ------- - float - - """ - if original: - return SCIPgetLocalOrigEstimate(self._scip) - else: - return SCIPgetLocalTransEstimate(self._scip) - - # Setting parameters - def setPresolve(self, setting): - """ - Set presolving parameter settings. - - - Parameters - ---------- - setting : SCIP_PARAMSETTING - the parameter settings, e.g. SCIP_PARAMSETTING.OFF - - """ - PY_SCIP_CALL(SCIPsetPresolving(self._scip, setting, True)) - - def setProbName(self, name): - """ - Set problem name. - - Parameters - ---------- - name : str - - """ - n = str_conversion(name) - PY_SCIP_CALL(SCIPsetProbName(self._scip, n)) - - def setSeparating(self, setting): - """ - Set separating parameter settings. - - Parameters - ---------- - setting : SCIP_PARAMSETTING - the parameter settings, e.g. SCIP_PARAMSETTING.OFF - - """ - PY_SCIP_CALL(SCIPsetSeparating(self._scip, setting, True)) - - def setHeuristics(self, setting): - """ - Set heuristics parameter settings. - - Parameters - ---------- - setting : SCIP_PARAMSETTING - the parameter settings, e.g. SCIP_PARAMSETTING.OFF - - """ - PY_SCIP_CALL(SCIPsetHeuristics(self._scip, setting, True)) - - def setHeurTiming(self, heurname, heurtiming): - """ - Set the timing of a heuristic - - Parameters - ---------- - heurname : string, name of the heuristic - heurtiming : PY_SCIP_HEURTIMING - positions in the node solving loop where heuristic should be executed - """ - cdef SCIP_HEUR* _heur - n = str_conversion(heurname) - _heur = SCIPfindHeur(self._scip, n) - if _heur == NULL: - raise ValueError("Could not find heuristic <%s>" % heurname) - SCIPheurSetTimingmask(_heur, heurtiming) - - def getHeurTiming(self, heurname): - """ - Get the timing of a heuristic - - Parameters - ---------- - heurname : string, name of the heuristic - - Returns - ------- - PY_SCIP_HEURTIMING - positions in the node solving loop where heuristic should be executed - """ - cdef SCIP_HEUR* _heur - n = str_conversion(heurname) - _heur = SCIPfindHeur(self._scip, n) - if _heur == NULL: - raise ValueError("Could not find heuristic <%s>" % heurname) - return SCIPheurGetTimingmask(_heur) - - def disablePropagation(self, onlyroot=False): - """ - Disables propagation in SCIP to avoid modifying the original problem during transformation. - - Parameters - ---------- - onlyroot : bool, optional - use propagation when root processing is finished (Default value = False) - - """ - self.setIntParam("propagating/maxroundsroot", 0) - if not onlyroot: - self.setIntParam("propagating/maxrounds", 0) - - def printProblem(self, ext='.cip', trans=False, genericnames=False): - """ - Write current model/problem to standard output. - - Parameters - ---------- - ext : str, optional - the extension to be used (Default value = '.cip'). - Should have an extension corresponding to one of the readable file formats, - described in https://www.scipopt.org/doc/html/group__FILEREADERS.php. - trans : bool, optional - indicates whether the transformed problem is written to file (Default value = False) - genericnames : bool, optional - indicates whether the problem should be written with generic variable - and constraint names (Default value = False) - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - if trans: - PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, NULL, str_conversion(ext)[1:], genericnames)) - else: - PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, NULL, str_conversion(ext)[1:], genericnames)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeProblem(self, filename='model.cip', trans=False, genericnames=False, verbose=True): - """ - Write current model/problem to a file. - - Parameters - ---------- - filename : str, optional - the name of the file to be used (Default value = 'model.cip'). - Should have an extension corresponding to one of the readable file formats, - described in https://www.scipopt.org/doc/html/group__FILEREADERS.php. - trans : bool, optional - indicates whether the transformed problem is written to file (Default value = False) - genericnames : bool, optional - indicates whether the problem should be written with generic variable - and constraint names (Default value = False) - verbose : bool, optional - indicates whether a success message should be printed - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - if filename: - str_absfile = abspath(filename) - absfile = str_conversion(str_absfile) - fn, ext = splitext(absfile) - if len(ext) == 0: - ext = str_conversion('.cip') - fn = fn + ext - ext = ext[1:] - - if trans: - PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, fn, ext, genericnames)) - else: - PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, fn, ext, genericnames)) - - if verbose: - print('wrote problem to file ' + str_absfile) - else: - if trans: - PY_SCIP_CALL(SCIPwriteTransProblem(self._scip, NULL, str_conversion('.cip')[1:], genericnames)) - else: - PY_SCIP_CALL(SCIPwriteOrigProblem(self._scip, NULL, str_conversion('.cip')[1:], genericnames)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - # Variable Functions - def addVar(self, name='', vtype='C', lb=0.0, ub=None, obj=0.0, pricedVar=False, pricedVarScore=1.0, deletable=False): - """ - Create a new variable. Default variable is non-negative and continuous. - - Parameters - ---------- - name : str, optional - name of the variable, generic if empty (Default value = '') - vtype : str, optional - type of the variable: 'C' continuous, 'I' integer, 'B' binary, and 'M' implicit integer - (Default value = 'C') - lb : float or None, optional - lower bound of the variable, use None for -infinity (Default value = 0.0) - ub : float or None, optional - upper bound of the variable, use None for +infinity (Default value = None) - obj : float, optional - objective value of variable (Default value = 0.0) - pricedVar : bool, optional - is the variable a pricing candidate? (Default value = False) - pricedVarScore : float, optional - score of variable in case it is priced, the higher the better (Default value = 1.0) - - Returns - ------- - Variable - - """ - cdef SCIP_VAR* scip_var - - # replace empty name with generic one - if name == '': - name = 'x'+str(SCIPgetNVars(self._scip)+1) - cname = str_conversion(name) - - # replace None with corresponding infinity - if lb is None: - lb = -SCIPinfinity(self._scip) - if ub is None: - ub = SCIPinfinity(self._scip) - - vtype = vtype.upper() - if vtype in ['C', 'CONTINUOUS']: - PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_CONTINUOUS)) - elif vtype in ['B', 'BINARY']: - if ub > 1.0: - ub = 1.0 - if lb < 0.0: - lb = 0.0 - PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_BINARY)) - elif vtype in ['I', 'INTEGER']: - PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_VARTYPE_INTEGER)) - elif vtype in ['M', 'IMPLINT']: - PY_SCIP_CALL(SCIPcreateVarBasic(self._scip, &scip_var, cname, lb, ub, obj, SCIP_DEPRECATED_VARTYPE_IMPLINT)) - else: - raise Warning("unrecognized variable type") - - if deletable: - SCIPvarMarkDeletable(scip_var) - - if pricedVar: - PY_SCIP_CALL(SCIPaddPricedVar(self._scip, scip_var, pricedVarScore)) - else: - PY_SCIP_CALL(SCIPaddVar(self._scip, scip_var)) - - pyVar = self._getOrCreateVar(scip_var) - - #setting the variable data - SCIPvarSetData(scip_var, pyVar) - PY_SCIP_CALL(SCIPreleaseVar(self._scip, &scip_var)) - return pyVar - - def addMatrixVar(self, - shape: Union[int, Tuple], - name: Union[str, np.ndarray] = '', - vtype: Union[str, np.ndarray] = 'C', - lb: Union[int, float, np.ndarray, None] = 0.0, - ub: Union[int, float, np.ndarray, None] = None, - obj: Union[int, float, np.ndarray] = 0.0, - pricedVar: Union[bool, np.ndarray] = False, - pricedVarScore: Union[int, float, np.ndarray] = 1.0 - ) -> MatrixVariable: - """ - Create a new matrix of variable. Default matrix variables are non-negative and continuous. - - Parameters - ---------- - shape : int or tuple - the shape of the resultant MatrixVariable - name : str or np.ndarray, optional - name of the matrix variable, generic if empty (Default value = '') - vtype : str or np.ndarray, optional - type of the matrix variable: 'C' continuous, 'I' integer, 'B' binary, and 'M' implicit integer - (Default value = 'C') - lb : float or np.ndarray or None, optional - lower bound of the matrix variable, use None for -infinity (Default value = 0.0) - ub : float or np.ndarray or None, optional - upper bound of the matrix variable, use None for +infinity (Default value = None) - obj : float or np.ndarray, optional - objective value of matrix variable (Default value = 0.0) - pricedVar : bool or np.ndarray, optional - is the matrix variable a pricing candidate? (Default value = False) - pricedVarScore : float or np.ndarray, optional - score of matrix variable in case it is priced, the higher the better (Default value = 1.0) - - Returns - ------- - MatrixVariable - - """ - # assert has_numpy, "Numpy is not installed. Please install numpy to use matrix variables." - - if isinstance(name, np.ndarray): - assert name.shape == shape - if isinstance(vtype, np.ndarray): - assert vtype.shape == shape - if isinstance(lb, np.ndarray): - assert lb.shape == shape - if isinstance(ub, np.ndarray): - assert ub.shape == shape - if isinstance(obj, np.ndarray): - assert obj.shape == shape - if isinstance(pricedVar, np.ndarray): - assert pricedVar.shape == shape - if isinstance(pricedVarScore, np.ndarray): - assert pricedVarScore.shape == shape - - if isinstance(shape, int): - ndim = 1 - else: - ndim = len(shape) - - matrix_variable = np.empty(shape, dtype=object) - - if isinstance(name, str): - matrix_names = np.full(shape, name, dtype=object) - if name != "": - for idx in np.ndindex(matrix_variable.shape): - matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" - else: - matrix_names = name - - if not isinstance(vtype, np.ndarray): - matrix_vtypes = np.full(shape, vtype, dtype=str) - else: - matrix_vtypes = vtype - - if not isinstance(lb, np.ndarray): - matrix_lbs = np.full(shape, lb, dtype=object) - else: - matrix_lbs = lb - - if not isinstance(ub, np.ndarray): - matrix_ubs = np.full(shape, ub, dtype=object) - else: - matrix_ubs = ub - - if not isinstance(obj, np.ndarray): - matrix_objs = np.full(shape, obj, dtype=float) - else: - matrix_objs = obj - - if not isinstance(pricedVar, np.ndarray): - matrix_priced_vars = np.full(shape, pricedVar, dtype=bool) - else: - matrix_priced_vars = pricedVar - - if not isinstance(pricedVarScore, np.ndarray): - matrix_priced_var_scores = np.full(shape, pricedVarScore, dtype=float) - else: - matrix_priced_var_scores = pricedVarScore - - for idx in np.ndindex(matrix_variable.shape): - matrix_variable[idx] = self.addVar(name=matrix_names[idx], vtype=matrix_vtypes[idx], lb=matrix_lbs[idx], - ub=matrix_ubs[idx], obj=matrix_objs[idx], pricedVar=matrix_priced_vars[idx], - pricedVarScore=matrix_priced_var_scores[idx]) - - return matrix_variable.view(MatrixVariable) - - def getTransformedVar(self, Variable var): - """ - Retrieve the transformed variable. - - Parameters - ---------- - var : Variable - original variable to get the transformed of - - Returns - ------- - Variable - - """ - cdef SCIP_VAR* _tvar - PY_SCIP_CALL(SCIPgetTransformedVar(self._scip, var.scip_var, &_tvar)) - return self._getOrCreateVar(_tvar) - - def addVarLocks(self, Variable var, int nlocksdown, int nlocksup): - """ - Adds given values to lock numbers of variable for rounding. - - Parameters - ---------- - var : Variable - variable to adjust the locks for - nlocksdown : int - new number of down locks - nlocksup : int - new number of up locks - - """ - PY_SCIP_CALL(SCIPaddVarLocks(self._scip, var.scip_var, nlocksdown, nlocksup)) - - def addVarLocksType(self, Variable var, int locktype, int nlocksdown, int nlocksup): - """ - adds given values to lock numbers of type locktype of variable for rounding - - Parameters - ---------- - var : Variable - variable to adjust the locks for - locktype : SCIP_LOCKTYPE - type of variable locks - nlocksdown : int - modification in number of down locks - nlocksup : int - modification in number of up locks - - """ - PY_SCIP_CALL(SCIPaddVarLocksType(self._scip, var.scip_var, locktype, nlocksdown, nlocksup)) - - def fixVar(self, Variable var, val): - """ - Fixes the variable var to the value val if possible. - - Parameters - ---------- - var : Variable - variable to fix - val : float - the fix value - - Returns - ------- - infeasible : bool - Is the fixing infeasible? - fixed : bool - Was the fixing performed? - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool fixed - PY_SCIP_CALL(SCIPfixVar(self._scip, var.scip_var, val, &infeasible, &fixed)) - return infeasible, fixed - - def delVar(self, Variable var): - """ - Delete a variable. - - Parameters - ---------- - var : Variable - the variable which shall be deleted - - Returns - ------- - deleted : bool - Whether deleting was successfull - - """ - cdef SCIP_Bool deleted - del self._modelvars[var.ptr()] - PY_SCIP_CALL(SCIPdelVar(self._scip, var.scip_var, &deleted)) - # Invalidate pointer after deletion. See issue #604. - var.scip_var = NULL - return deleted - - def aggregateVars(self, Variable varx, Variable vary, coefx=1.0, coefy=-1.0, rhs=0.0): - """ - Aggregate two variables by adding an aggregation constraint. - - The aggregation is defined by the linear equation: - - coefx * varx + coefy * vary = rhs - - After aggregation, varx becomes a redundant variable and vary remains active. - The aggregation effectively substitutes varx with: (rhs - coefy * vary) / coefx - - This method can only be called during presolving. - - Parameters - ---------- - varx : Variable - variable to be aggregated (will become redundant) - vary : Variable - variable to aggregate with (will remain active) - coefx : float, optional - coefficient for varx in the aggregation equation (default: 1.0) - coefy : float, optional - coefficient for vary in the aggregation equation (default: -1.0) - rhs : float, optional - right-hand side of the aggregation equation (default: 0.0) - - Returns - ------- - infeasible : bool - whether the aggregation is infeasible (e.g., bounds are incompatible) - redundant : bool - whether the aggregation makes varx redundant - aggregated : bool - whether the aggregation was actually performed - - Examples - -------- - To express x = y (i.e., 1*x + (-1)*y = 0): - - infeas, redun, aggr = model.aggregateVars(x, y, 1.0, -1.0, 0.0) - - To express x = 5 - y (i.e., 1*x + 1*y = 5): - - infeas, redun, aggr = model.aggregateVars(x, y, 1.0, 1.0, 5.0) - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool redundant - cdef SCIP_Bool aggregated - PY_SCIP_CALL(SCIPaggregateVars(self._scip, - varx.scip_var, - vary.scip_var, - coefx, - coefy, - rhs, - &infeasible, - &redundant, - &aggregated)) - return infeasible, redundant, aggregated - - def tightenVarLb(self, Variable var, lb, force=False): - """ - Tighten the lower bound in preprocessing or current node, if the bound is tighter. - - Parameters - ---------- - var : Variable - SCIP variable - lb : float - possible new lower bound - force : bool, optional - force tightening even if below bound strengthening tolerance (default = False) - - Returns - ------- - infeasible : bool - Whether new domain is empty - tightened : bool - Whether the bound was tightened - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool tightened - PY_SCIP_CALL(SCIPtightenVarLb(self._scip, var.scip_var, lb, force, &infeasible, &tightened)) - return infeasible, tightened - - def tightenVarUb(self, Variable var, ub, force=False): - """ - Tighten the upper bound in preprocessing or current node, if the bound is tighter. - - Parameters - ---------- - var : Variable - SCIP variable - ub : float - possible new upper bound - force : bool, optional - force tightening even if below bound strengthening tolerance - - Returns - ------- - infeasible : bool - Whether new domain is empty - tightened : bool - Whether the bound was tightened - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool tightened - PY_SCIP_CALL(SCIPtightenVarUb(self._scip, var.scip_var, ub, force, &infeasible, &tightened)) - return infeasible, tightened - - def tightenVarUbGlobal(self, Variable var, ub, force=False): - """ - Tighten the global upper bound, if the bound is tighter. - - Parameters - ---------- - var : Variable - SCIP variable - ub : float - possible new upper bound - force : bool, optional - force tightening even if below bound strengthening tolerance - - Returns - ------- - infeasible : bool - Whether new domain is empty - tightened : bool - Whether the bound was tightened - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool tightened - PY_SCIP_CALL(SCIPtightenVarUbGlobal(self._scip, var.scip_var, ub, force, &infeasible, &tightened)) - return infeasible, tightened - - def tightenVarLbGlobal(self, Variable var, lb, force=False): - """Tighten the global lower bound, if the bound is tighter. - - Parameters - ---------- - var : Variable - SCIP variable - lb : float - possible new lower bound - force : bool, optional - force tightening even if below bound strengthening tolerance - - Returns - ------- - infeasible : bool - Whether new domain is empty - tightened : bool - Whether the bound was tightened - - """ - cdef SCIP_Bool infeasible - cdef SCIP_Bool tightened - PY_SCIP_CALL(SCIPtightenVarLbGlobal(self._scip, var.scip_var, lb, force, &infeasible, &tightened)) - return infeasible, tightened - - def chgVarLb(self, Variable var, lb): - """ - Changes the lower bound of the specified variable. - - Parameters - ---------- - var : Variable - variable to change bound of - lb : float or None - new lower bound (set to None for -infinity) - - """ - if lb is None: - lb = -SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarLb(self._scip, var.scip_var, lb)) - - def chgVarUb(self, Variable var, ub): - """Changes the upper bound of the specified variable. - - Parameters - ---------- - var : Variable - variable to change bound of - lb : float or None - new upper bound (set to None for +infinity) - - """ - if ub is None: - ub = SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarUb(self._scip, var.scip_var, ub)) - - def chgVarLbGlobal(self, Variable var, lb): - """Changes the global lower bound of the specified variable. - - Parameters - ---------- - var : Variable - variable to change bound of - lb : float or None - new lower bound (set to None for -infinity) - - """ - if lb is None: - lb = -SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarLbGlobal(self._scip, var.scip_var, lb)) - - def chgVarUbGlobal(self, Variable var, ub): - """Changes the global upper bound of the specified variable. - - Parameters - ---------- - var : Variable - variable to change bound of - lb : float or None - new upper bound (set to None for +infinity) - - """ - if ub is None: - ub = SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarUbGlobal(self._scip, var.scip_var, ub)) - - def chgVarLbNode(self, Node node, Variable var, lb): - """Changes the lower bound of the specified variable at the given node. - - Parameters - ---------- - node : Node - Node at which the variable bound will be changed - var : Variable - variable to change bound of - lb : float or None - new lower bound (set to None for -infinity) - - """ - - if lb is None: - lb = -SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarLbNode(self._scip, node.scip_node, var.scip_var, lb)) - - def chgVarUbNode(self, Node node, Variable var, ub): - """Changes the upper bound of the specified variable at the given node. - - Parameters - ---------- - node : Node - Node at which the variable bound will be changed - var : Variable - variable to change bound of - lb : float or None - new upper bound (set to None for +infinity) - - """ - if ub is None: - ub = SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarUbNode(self._scip, node.scip_node, var.scip_var, ub)) - - def chgVarType(self, Variable var, vtype): - """ - Changes the type of a variable. - - Parameters - ---------- - var : Variable - variable to change type of - vtype : str - new variable type. 'C' or "CONTINUOUS", 'I' or "INTEGER", - 'B' or "BINARY", and 'M' "IMPLINT". - - """ - cdef SCIP_Bool infeasible - if vtype in ['C', 'CONTINUOUS']: - PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_CONTINUOUS, &infeasible)) - elif vtype in ['B', 'BINARY']: - PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_BINARY, &infeasible)) - elif vtype in ['I', 'INTEGER']: - PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_VARTYPE_INTEGER, &infeasible)) - elif vtype in ['M', 'IMPLINT']: - PY_SCIP_CALL(SCIPchgVarType(self._scip, var.scip_var, SCIP_DEPRECATED_VARTYPE_IMPLINT, &infeasible)) - else: - raise Warning("unrecognized variable type") - if infeasible: - print('could not change variable type of variable %s' % var) - - def markDoNotAggrVar(self, Variable var): - """ - Marks a variable preventing it from being aggregated. - - Parameters - ---------- - var : Variable - variable to mark - """ - PY_SCIP_CALL(SCIPmarkDoNotAggrVar(self._scip, var.scip_var)) - - def markDoNotMultaggrVar(self, Variable var): - """ - Marks a variable preventing it from being multi-aggregated. - - Parameters - ---------- - var : Variable - variable to mark - """ - PY_SCIP_CALL(SCIPmarkDoNotMultaggrVar(self._scip, var.scip_var)) - - def getVars(self, transformed=False): - """ - Retrieve all variables. - - Parameters - ---------- - transformed : bool, optional - Get transformed variables instead of original (Default value = False) - - Returns - ------- - list of Variable - - """ - cdef SCIP_VAR** _vars - cdef int nvars - cdef int i - - vars = [] - if transformed: - _vars = SCIPgetVars(self._scip) - nvars = SCIPgetNVars(self._scip) - else: - _vars = SCIPgetOrigVars(self._scip) - nvars = SCIPgetNOrigVars(self._scip) - - for i in range(nvars): - vars.append(self._getOrCreateVar(_vars[i])) - - return vars - - def getNVars(self, transformed=True): - """ - Retrieve number of variables in the problems. - - Parameters - ---------- - transformed : bool, optional - Get transformed variables instead of original (Default value = True) - - Returns - ------- - int - - """ - if transformed: - return SCIPgetNVars(self._scip) - else: - return SCIPgetNOrigVars(self._scip) - - def getNIntVars(self): - """ - Gets number of integer active problem variables. - - Returns - ------- - int - - """ - return SCIPgetNIntVars(self._scip) - - def getNBinVars(self): - """ - Gets number of binary active problem variables. - - Returns - ------- - int - - """ - return SCIPgetNBinVars(self._scip) - - def getNImplVars(self): - """ - Gets number of implicit integer active problem variables. - - Returns - ------- - int - - """ - return SCIPgetNImplVars(self._scip) - - def getNContVars(self): - """ - Gets number of continuous active problem variables. - - Returns - ------- - int - - """ - return SCIPgetNContVars(self._scip) - - def getVarDict(self, transformed=False): - """ - Gets dictionary with variables names as keys and current variable values as items. - - Parameters - ---------- - transformed : bool, optional - Get transformed variables instead of original (Default value = False) - - Returns - ------- - dict of str to float - - """ - var_dict = {} - for var in self.getVars(transformed=transformed): - var_dict[var.name] = self.getVal(var) - return var_dict - - def getVarPseudocostScore(self, Variable var, solVal): - """ - gets the variable's pseudo cost score value for the given LP solution value - - Parameters - ---------- - variable : Variable - problem variable - solVal : float - difference of variable's new LP value - old LP value - - Returns - ------- - float - """ - return SCIPgetVarPseudocostScore(self._scip, var.scip_var, solVal) - - def getVarPseudocost(self, Variable var, branchdir): - """ - gets the variable's pseudo cost value for the given direction - - Parameters - ---------- - variable : Variable - problem variable - branchdir : PY_SCIP_BRANCHDIR - branching direction (downwards, or upwards) - - Returns - ------- - float - """ - return SCIPgetVarPseudocost(self._scip, var.scip_var, branchdir) - - def updateNodeLowerbound(self, Node node, lb): - """ - If given value is larger than the node's lower bound (in transformed problem), - sets the node's lower bound to the new value. - - Parameters - ---------- - node : Node - the node to update - lb : float - new bound (if greater) for the node - - """ - PY_SCIP_CALL(SCIPupdateNodeLowerbound(self._scip, node.scip_node, lb)) - - def relax(self): - """Relaxes the integrality restrictions of the model.""" - if self.getStage() != SCIP_STAGE_PROBLEM: - raise Warning("method can only be called in stage PROBLEM") - - for var in self.getVars(): - self.chgVarType(var, "C") - - # Node methods - def getBestChild(self): - """ - Gets the best child of the focus node w.r.t. the node selection strategy. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetBestChild(self._scip)) - - def getChildren(self): - """ - Gets the children of the focus node. - - Returns - ------- - list of Nodes - - """ - cdef SCIP_NODE** _children - cdef int n_children - cdef int i - - PY_SCIP_CALL(SCIPgetChildren(self._scip, &_children, &n_children)) - - return [Node.create(_children[i]) for i in range(n_children)] - - def getSiblings(self): - """ - Gets the siblings of the focus node. - - Returns - ------- - list of Nodes - - """ - cdef SCIP_NODE** _siblings - cdef int n_siblings - cdef int i - - PY_SCIP_CALL(SCIPgetSiblings(self._scip, &_siblings, &n_siblings)) - - return [Node.create(_siblings[i]) for i in range(n_siblings)] - - def getLeaves(self): - """ - Gets the leaves of the tree along with number of leaves. - - Returns - ------- - list of Nodes - - """ - cdef SCIP_NODE** _leaves - cdef int n_leaves - cdef int i - - PY_SCIP_CALL(SCIPgetLeaves(self._scip, &_leaves, &n_leaves)) - - return [Node.create(_leaves[i]) for i in range(n_leaves)] - - def getBestSibling(self): - """ - Gets the best sibling of the focus node w.r.t. the node selection strategy. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetBestSibling(self._scip)) - - def getPrioChild(self): - """ - Gets the best child of the focus node w.r.t. the node selection priority - assigned by the branching rule. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetPrioChild(self._scip)) - - def getPrioSibling(self): - """Gets the best sibling of the focus node w.r.t. - the node selection priority assigned by the branching rule. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetPrioSibling(self._scip)) - - def getBestLeaf(self): - """Gets the best leaf from the node queue w.r.t. the node selection strategy. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetBestLeaf(self._scip)) - - def getBestNode(self): - """Gets the best node from the tree (child, sibling, or leaf) w.r.t. the node selection strategy. - - Returns - ------- - Node - - """ - return Node.create(SCIPgetBestNode(self._scip)) - - def getBestboundNode(self): - """Gets the node with smallest lower bound from the tree (child, sibling, or leaf). - - Returns - ------- - Node - - """ - return Node.create(SCIPgetBestboundNode(self._scip)) - - def getOpenNodes(self): - """ - Access to all data of open nodes (leaves, children, and siblings). - - Returns - ------- - leaves : list of Node - list of all open leaf nodes - children : list of Node - list of all open children nodes - siblings : list of Node - list of all open sibling nodes - - """ - cdef SCIP_NODE** _leaves - cdef SCIP_NODE** _children - cdef SCIP_NODE** _siblings - cdef int _nleaves - cdef int _nchildren - cdef int _nsiblings - cdef int i - - PY_SCIP_CALL(SCIPgetOpenNodesData(self._scip, &_leaves, &_children, &_siblings, &_nleaves, &_nchildren, &_nsiblings)) - - leaves = [Node.create(_leaves[i]) for i in range(_nleaves)] - children = [Node.create(_children[i]) for i in range(_nchildren)] - siblings = [Node.create(_siblings[i]) for i in range(_nsiblings)] - - return leaves, children, siblings - - def repropagateNode(self, Node node): - """Marks the given node to be propagated again the next time a node of its subtree is processed.""" - PY_SCIP_CALL(SCIPrepropagateNode(self._scip, node.scip_node)) - - # LP Methods - def getLPSolstat(self): - """ - Gets solution status of current LP. - - Returns - ------- - SCIP_LPSOLSTAT - - """ - return SCIPgetLPSolstat(self._scip) - - def constructLP(self): - """ - Makes sure that the LP of the current node is loaded and - may be accessed through the LP information methods. - - - Returns - ------- - cutoff : bool - Can the node be cutoff? - - """ - cdef SCIP_Bool cutoff - PY_SCIP_CALL(SCIPconstructLP(self._scip, &cutoff)) - return cutoff - - def getLPObjVal(self): - """ - Gets objective value of current LP (which is the sum of column and loose objective value). - - Returns - ------- - float - - """ - - return SCIPgetLPObjval(self._scip) - - def getLPColsData(self): - """ - Retrieve current LP columns. - - Returns - ------- - list of Column - - """ - cdef SCIP_COL** cols - cdef int ncols - cdef int i - - PY_SCIP_CALL(SCIPgetLPColsData(self._scip, &cols, &ncols)) - - return [Column.create(cols[i]) for i in range(ncols)] - - def getLPRowsData(self): - """ - Retrieve current LP rows. - - Returns - ------- - list of Row - - """ - cdef SCIP_ROW** rows - cdef int nrows - cdef int i - - PY_SCIP_CALL(SCIPgetLPRowsData(self._scip, &rows, &nrows)) - - return [Row.create(rows[i]) for i in range(nrows)] - - def getNLPRows(self): - """ - Retrieve the number of rows currently in the LP. - - Returns - ------- - int - - """ - return SCIPgetNLPRows(self._scip) - - def getNLPCols(self): - """ - Retrieve the number of columns currently in the LP. - - Returns - ------- - int - - """ - return SCIPgetNLPCols(self._scip) - - def getLPBasisInd(self): - """ - Gets all indices of basic columns and rows: - index i >= 0 corresponds to column i, index i < 0 to row -i-1 - - Returns - ------- - list of int - - """ - cdef int nrows = SCIPgetNLPRows(self._scip) - cdef int* inds = malloc(nrows * sizeof(int)) - cdef int i - - PY_SCIP_CALL(SCIPgetLPBasisInd(self._scip, inds)) - result = [inds[i] for i in range(nrows)] - free(inds) - - return result - - def getLPBInvRow(self, row): - """ - Gets a row from the inverse basis matrix B^-1 - - Parameters - ---------- - row : int - The row index of the inverse basis matrix - - Returns - ------- - list of float - - """ - # TODO: sparsity information - cdef int nrows = SCIPgetNLPRows(self._scip) - cdef SCIP_Real* coefs = malloc(nrows * sizeof(SCIP_Real)) - cdef int i - - PY_SCIP_CALL(SCIPgetLPBInvRow(self._scip, row, coefs, NULL, NULL)) - result = [coefs[i] for i in range(nrows)] - free(coefs) - - return result - - def getLPBInvARow(self, row): - """ - Gets a row from B^-1 * A. - - Parameters - ---------- - row : int - The row index of the inverse basis matrix multiplied by the coefficient matrix - - Returns - ------- - list of float - - """ - # TODO: sparsity information - cdef int ncols = SCIPgetNLPCols(self._scip) - cdef SCIP_Real* coefs = malloc(ncols * sizeof(SCIP_Real)) - cdef int i - - PY_SCIP_CALL(SCIPgetLPBInvARow(self._scip, row, NULL, coefs, NULL, NULL)) - result = [coefs[i] for i in range(ncols)] - free(coefs) - - return result - - def isLPSolBasic(self): - """ - Returns whether the current LP solution is basic, i.e. is defined by a valid simplex basis. - - Returns - ------- - bool - - """ - return SCIPisLPSolBasic(self._scip) - - def allColsInLP(self): - """ - Checks if all columns, i.e. every variable with non-empty column is present in the LP. - This is not True when performing pricing for instance. - - Returns - ------- - bool - - """ - - return SCIPallColsInLP(self._scip) - - # LP Col Methods - def getColRedCost(self, Column col): - """ - Gets the reduced cost of the column in the current LP. - - Parameters - ---------- - col : Column - - Returns - ------- - float - - """ - return SCIPgetColRedcost(self._scip, col.scip_col) - - #TODO: documentation!! - # LP Row Methods - def createEmptyRowSepa(self, Sepa sepa, name="row", lhs = 0.0, rhs = None, local = True, modifiable = False, removable = True): - """ - Creates and captures an LP row without any coefficients from a separator. - - Parameters - ---------- - sepa : Sepa - separator that creates the row - name : str, optional - name of row (Default value = "row") - lhs : float or None, optional - left hand side of row (Default value = 0) - rhs : float or None, optional - right hand side of row (Default value = None) - local : bool, optional - is row only valid locally? (Default value = True) - modifiable : bool, optional - is row modifiable during node processing (subject to column generation)? (Default value = False) - removable : bool, optional - should the row be removed from the LP due to aging or cleanup? (Default value = True) - - Returns - ------- - Row - - """ - cdef SCIP_ROW* row - lhs = -SCIPinfinity(self._scip) if lhs is None else lhs - rhs = SCIPinfinity(self._scip) if rhs is None else rhs - scip_sepa = SCIPfindSepa(self._scip, str_conversion(sepa.name)) - PY_SCIP_CALL(SCIPcreateEmptyRowSepa(self._scip, &row, scip_sepa, str_conversion(name), lhs, rhs, local, modifiable, removable)) - PyRow = Row.create(row) - return PyRow - - def createEmptyRowUnspec(self, name="row", lhs = 0.0, rhs = None, local = True, modifiable = False, removable = True): - """ - Creates and captures an LP row without any coefficients from an unspecified source. - - Parameters - ---------- - name : str, optional - name of row (Default value = "row") - lhs : float or None, optional - left hand side of row (Default value = 0) - rhs : float or None, optional - right hand side of row (Default value = None) - local : bool, optional - is row only valid locally? (Default value = True) - modifiable : bool, optional - is row modifiable during node processing (subject to column generation)? (Default value = False) - removable : bool, optional - should the row be removed from the LP due to aging or cleanup? (Default value = True) - - Returns - ------- - Row - - """ - cdef SCIP_ROW* row - lhs = -SCIPinfinity(self._scip) if lhs is None else lhs - rhs = SCIPinfinity(self._scip) if rhs is None else rhs - PY_SCIP_CALL(SCIPcreateEmptyRowUnspec(self._scip, &row, str_conversion(name), lhs, rhs, local, modifiable, removable)) - PyRow = Row.create(row) - return PyRow - - def getRowActivity(self, Row row): - """ - Returns the activity of a row in the last LP or pseudo solution. - - Parameters - ---------- - row : Row - - Returns - ------- - float - - """ - return SCIPgetRowActivity(self._scip, row.scip_row) - - def getRowLPActivity(self, Row row): - """ - Returns the activity of a row in the last LP solution. - - Parameters - ---------- - row : Row - - Returns - ------- - float - - """ - return SCIPgetRowLPActivity(self._scip, row.scip_row) - - # TODO: do we need this? (also do we need release var??) - def releaseRow(self, Row row not None): - """ - Decreases usage counter of LP row, and frees memory if necessary. - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPreleaseRow(self._scip, &row.scip_row)) - - def cacheRowExtensions(self, Row row not None): - """ - Informs row that all subsequent additions of variables to the row - should be cached and not directly applied; - after all additions were applied, flushRowExtensions() must be called; - while the caching of row extensions is activated, information methods of the - row give invalid results; caching should be used, if a row is build with addVarToRow() - calls variable by variable to increase the performance. - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPcacheRowExtensions(self._scip, row.scip_row)) - - def flushRowExtensions(self, Row row not None): - """ - Flushes all cached row extensions after a call of cacheRowExtensions() - and merges coefficients with equal columns into a single coefficient - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPflushRowExtensions(self._scip, row.scip_row)) - - def addVarToRow(self, Row row not None, Variable var not None, value): - """ - Resolves variable to columns and adds them with the coefficient to the row. - - Parameters - ---------- - row : Row - Row in which the variable will be added - var : Variable - Variable which will be added to the row - value : float - Coefficient on the variable when placed in the row - - """ - PY_SCIP_CALL(SCIPaddVarToRow(self._scip, row.scip_row, var.scip_var, value)) - - def printRow(self, Row row not None): - """ - Prints row. - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPprintRow(self._scip, row.scip_row, NULL)) - - def getRowNumIntCols(self, Row row): - """ - Returns number of intergal columns in the row. - - Parameters - ---------- - row : Row - - Returns - ------- - int - - """ - return SCIPgetRowNumIntCols(self._scip, row.scip_row) - - def getRowObjParallelism(self, Row row): - """ - Returns 1 if the row is parallel, and 0 if orthogonal. - - Parameters - ---------- - row : Row - - Returns - ------- - float - - """ - return SCIPgetRowObjParallelism(self._scip, row.scip_row) - - def getRowParallelism(self, Row row1, Row row2, orthofunc=101): - """ - Returns the degree of parallelism between hyplerplanes. 1 if perfectly parallel, 0 if orthogonal. - For two row vectors v, w the parallelism is calculated as: abs(v*w)/(abs(v)*abs(w)). - 101 in this case is an 'e' (euclidean) in ASCII. The other acceptable input is 100 (d for discrete). - - Parameters - ---------- - row1 : Row - row2 : Row - orthofunc : int, optional - 101 (default) is an 'e' (euclidean) in ASCII. Alternate value is 100 (d for discrete) - - Returns - ------- - float - - """ - return SCIProwGetParallelism(row1.scip_row, row2.scip_row, orthofunc) - - def getRowDualSol(self, Row row): - """ - Gets the dual LP solution of a row. - - Parameters - ---------- - row : Row - - Returns - ------- - float - - """ - return SCIProwGetDualsol(row.scip_row) - - # Cutting Plane Methods - def addPoolCut(self, Row row not None): - """ - If not already existing, adds row to global cut pool. - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPaddPoolCut(self._scip, row.scip_row)) - - def getCutEfficacy(self, Row cut not None, Solution sol = None): - """ - Returns efficacy of the cut with respect to the given primal solution or the - current LP solution: e = -feasibility/norm - - Parameters - ---------- - cut : Row - sol : Solution or None, optional - - Returns - ------- - float - - """ - return SCIPgetCutEfficacy(self._scip, NULL if sol is None else sol.sol, cut.scip_row) - - def isCutEfficacious(self, Row cut not None, Solution sol = None): - """ - Returns whether the cut's efficacy with respect to the given primal solution or the - current LP solution is greater than the minimal cut efficacy. - - Parameters - ---------- - cut : Row - sol : Solution or None, optional - - Returns - ------- - float - - """ - return SCIPisCutEfficacious(self._scip, NULL if sol is None else sol.sol, cut.scip_row) - - def getCutLPSolCutoffDistance(self, Row cut not None, Solution sol not None): - """ - Returns row's cutoff distance in the direction of the given primal solution. - - Parameters - ---------- - cut : Row - sol : Solution - - Returns - ------- - float - - """ - return SCIPgetCutLPSolCutoffDistance(self._scip, sol.sol, cut.scip_row) - - def addCut(self, Row cut not None, forcecut = False): - """ - Adds cut to separation storage and returns whether cut has been detected to be infeasible for local bounds. - - Parameters - ---------- - cut : Row - The cut that will be added - forcecut : bool, optional - Whether the cut should be forced or not, i.e., selected no matter what - - Returns - ------- - infeasible : bool - Whether the cut has been detected to be infeasible from local bounds - - """ - cdef SCIP_Bool infeasible - PY_SCIP_CALL(SCIPaddRow(self._scip, cut.scip_row, forcecut, &infeasible)) - return infeasible - - def getNCuts(self): - """ - Retrieve total number of cuts in storage. - - Returns - ------- - int - - """ - return SCIPgetNCuts(self._scip) - - def getNCutsApplied(self): - """ - Retrieve number of currently applied cuts. - - Returns - ------- - int - - """ - return SCIPgetNCutsApplied(self._scip) - - def getNSepaRounds(self): - """ - Retrieve the number of separation rounds that have been performed - at the current node. - - Returns - ------- - int - - """ - return SCIPgetNSepaRounds(self._scip) - - def separateSol(self, Solution sol = None, pretendroot = False, allowlocal = True, onlydelayed = False): - """ - Separates the given primal solution or the current LP solution by calling - the separators and constraint handlers' separation methods; - the generated cuts are stored in the separation storage and can be accessed - with the methods SCIPgetCuts() and SCIPgetNCuts(); - after evaluating the cuts, you have to call SCIPclearCuts() in order to remove the cuts from the - separation storage; it is possible to call SCIPseparateSol() multiple times with - different solutions and evaluate the found cuts afterwards. - - Parameters - ---------- - sol : Solution or None, optional - solution to separate, None to use current lp solution (Default value = None) - pretendroot : bool, optional - should the cut separators be called as if we are at the root node? (Default value = "False") - allowlocal : bool, optional - should the separator be asked to separate local cuts (Default value = True) - onlydelayed : bool, optional - should only separators be called that were delayed in the previous round? (Default value = False) - - Returns - ------- - delayed : bool - whether a separator was delayed - cutoff : bool - whether the node can be cut off - - """ - cdef SCIP_Bool delayed - cdef SCIP_Bool cutoff - - PY_SCIP_CALL( SCIPseparateSol(self._scip, NULL if sol is None else sol.sol, pretendroot, allowlocal, onlydelayed, &delayed, &cutoff) ) - return delayed, cutoff - - def _createConsLinear(self, ExprCons lincons, **kwargs): - """ - The function for creating a linear constraint, but not adding it to the Model. - Please do not use this function directly, but rather use createConsFromExpr - - Parameters - ---------- - lincons : ExprCons - kwargs : dict, optional - - Returns - ------- - Constraint - - """ - assert isinstance(lincons, ExprCons), "given constraint is not ExprCons but %s" % lincons.__class__.__name__ - - assert lincons.expr.degree() <= 1, "given constraint is not linear, degree == %d" % lincons.expr.degree() - terms = lincons.expr.terms - - cdef int nvars = len(terms.items()) - cdef SCIP_VAR** vars_array = malloc(nvars * sizeof(SCIP_VAR*)) - cdef SCIP_Real* coeffs_array = malloc(nvars * sizeof(SCIP_Real)) - cdef SCIP_CONS* scip_cons - cdef SCIP_Real coeff - cdef int i - cdef _VarArray wrapper - - for i, (key, coeff) in enumerate(terms.items()): - wrapper = _VarArray(key[0]) - vars_array[i] = wrapper.ptr[0] - coeffs_array[i] = coeff - - PY_SCIP_CALL(SCIPcreateConsLinear( - self._scip, &scip_cons, str_conversion(kwargs['name']), nvars, vars_array, coeffs_array, - kwargs['lhs'], kwargs['rhs'], kwargs['initial'], - kwargs['separate'], kwargs['enforce'], kwargs['check'], - kwargs['propagate'], kwargs['local'], kwargs['modifiable'], - kwargs['dynamic'], kwargs['removable'], kwargs['stickingatnode'])) - - PyCons = Constraint.create(scip_cons) - - free(vars_array) - free(coeffs_array) - - return PyCons - - def _createConsQuadratic(self, ExprCons quadcons, **kwargs): - """ - The function for creating a quadratic constraint, but not adding it to the Model. - Please do not use this function directly, but rather use createConsFromExpr - - Parameters - ---------- - quadcons : ExprCons - kwargs : dict, optional - - Returns - ------- - Constraint - - """ - terms = quadcons.expr.terms - assert quadcons.expr.degree() <= 2, "given constraint is not quadratic, degree == %d" % quadcons.expr.degree() - - cdef SCIP_CONS* scip_cons - cdef SCIP_EXPR* prodexpr - cdef _VarArray wrapper - PY_SCIP_CALL(SCIPcreateConsQuadraticNonlinear( - self._scip, &scip_cons, str_conversion(kwargs['name']), - 0, NULL, NULL, # linear - 0, NULL, NULL, NULL, # quadratc - kwargs['lhs'], kwargs['rhs'], - kwargs['initial'], kwargs['separate'], kwargs['enforce'], - kwargs['check'], kwargs['propagate'], kwargs['local'], - kwargs['modifiable'], kwargs['dynamic'], kwargs['removable'])) - - for v, c in terms.items(): - if len(v) == 1: # linear - wrapper = _VarArray(v[0]) - PY_SCIP_CALL(SCIPaddLinearVarNonlinear(self._scip, scip_cons, wrapper.ptr[0], c)) - else: # nonlinear - assert len(v) == 2, 'term length must be 1 or 2 but it is %s' % len(v) - - varexprs = malloc(2 * sizeof(SCIP_EXPR*)) - wrapper = _VarArray(v[0]) - PY_SCIP_CALL( SCIPcreateExprVar(self._scip, &varexprs[0], wrapper.ptr[0], NULL, NULL) ) - wrapper = _VarArray(v[1]) - PY_SCIP_CALL( SCIPcreateExprVar(self._scip, &varexprs[1], wrapper.ptr[0], NULL, NULL) ) - PY_SCIP_CALL( SCIPcreateExprProduct(self._scip, &prodexpr, 2, varexprs, 1.0, NULL, NULL) ) - - PY_SCIP_CALL( SCIPaddExprNonlinear(self._scip, scip_cons, prodexpr, c) ) - - PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &prodexpr) ) - PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &varexprs[1]) ) - PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &varexprs[0]) ) - free(varexprs) - - PyCons = Constraint.create(scip_cons) - - return PyCons - - def _createConsNonlinear(self, cons, **kwargs): - """ - The function for creating a non-linear constraint, but not adding it to the Model. - Please do not use this function directly, but rather use createConsFromExpr - - Parameters - ---------- - cons : ExprCons - kwargs : dict, optional - - Returns - ------- - Constraint - - """ - cdef SCIP_EXPR* expr - cdef SCIP_EXPR** varexprs - cdef SCIP_EXPR** monomials - cdef SCIP_CONS* scip_cons - cdef _VarArray wrapper - cdef int* idxs - cdef int i - cdef int j - - terms = cons.expr.terms - - # collect variables - variables = {i: [var for var in term] for i, term in enumerate(terms)} - - # create monomials for terms - monomials = malloc(len(terms) * sizeof(SCIP_EXPR*)) - termcoefs = malloc(len(terms) * sizeof(SCIP_Real)) - for i, (term, coef) in enumerate(terms.items()): - wrapper = _VarArray(variables[i]) - - PY_SCIP_CALL( SCIPcreateExprMonomial(self._scip, &monomials[i], wrapper.size, wrapper.ptr, NULL, NULL, NULL) ) - termcoefs[i] = coef - - # create polynomial from monomials - PY_SCIP_CALL( SCIPcreateExprSum(self._scip, &expr, len(terms), monomials, termcoefs, 0.0, NULL, NULL)) - - # create nonlinear constraint for expr - PY_SCIP_CALL( SCIPcreateConsNonlinear( - self._scip, - &scip_cons, - str_conversion(kwargs['name']), - expr, - kwargs['lhs'], - kwargs['rhs'], - kwargs['initial'], - kwargs['separate'], - kwargs['enforce'], - kwargs['check'], - kwargs['propagate'], - kwargs['local'], - kwargs['modifiable'], - kwargs['dynamic'], - kwargs['removable']) ) - - PyCons = Constraint.create(scip_cons) - - PY_SCIP_CALL( SCIPreleaseExpr(self._scip, &expr) ) - for i in range(len(terms)): - PY_SCIP_CALL(SCIPreleaseExpr(self._scip, &monomials[i])) - free(monomials) - free(termcoefs) - - return PyCons - - def _createConsGenNonlinear(self, cons, **kwargs): - """ - The function for creating a general non-linear constraint, but not adding it to the Model. - Please do not use this function directly, but rather use createConsFromExpr - - Parameters - ---------- - cons : ExprCons - kwargs : dict, optional - - Returns - ------- - Constraint - - """ - cdef SCIP_EXPR* scip_expr - cdef SCIP_CONS* scip_cons - cdef GenExpr expr = cons.expr - - # recursively create the SCIP expression tree from python's expression tree - scip_expr = expr.to_scip_expr(self._scip) - - # create nonlinear constraint for the expression root - PY_SCIP_CALL(SCIPcreateConsNonlinear( - self._scip, - &scip_cons, - str_conversion(kwargs["name"]), - scip_expr, - kwargs["lhs"], - kwargs["rhs"], - kwargs["initial"], - kwargs["separate"], - kwargs["enforce"], - kwargs["check"], - kwargs["propagate"], - kwargs["local"], - kwargs["modifiable"], - kwargs["dynamic"], - kwargs["removable"])) - - PY_SCIP_CALL(SCIPreleaseExpr(self._scip, &scip_expr)) - - return Constraint.create(scip_cons) - - def createConsFromExpr(self, cons, name='', initial=True, separate=True, - enforce=True, check=True, propagate=True, local=False, - modifiable=False, dynamic=False, removable=False, - stickingatnode=False): - """ - Create a linear or nonlinear constraint without adding it to the SCIP problem. - This is useful for creating disjunction constraints without also enforcing the individual constituents. - Currently, this can only be used as an argument to `.addConsElemDisjunction`. To add - an individual linear/nonlinear constraint, prefer `.addCons()`. - - Parameters - ---------- - cons : ExprCons - The expression constraint that is not yet an actual constraint - name : str, optional - the name of the constraint, generic name if empty (Default value = '') - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The created Constraint object. - - """ - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - kwargs = dict(name=name, initial=initial, separate=separate, - enforce=enforce, check=check, - propagate=propagate, local=local, - modifiable=modifiable, dynamic=dynamic, - removable=removable, - stickingatnode=stickingatnode - ) - - kwargs['lhs'] = -SCIPinfinity(self._scip) if cons._lhs is None else cons._lhs - kwargs['rhs'] = SCIPinfinity(self._scip) if cons._rhs is None else cons._rhs - - deg = cons.expr.degree() - if deg <= 1: - return self._createConsLinear(cons, **kwargs) - elif deg <= 2: - return self._createConsQuadratic(cons, **kwargs) - elif deg == INFINITY: # general nonlinear - return self._createConsGenNonlinear(cons, **kwargs) - else: - return self._createConsNonlinear(cons, **kwargs) - - # Constraint functions - def addCons(self, cons, name='', initial=True, separate=True, - enforce=True, check=True, propagate=True, local=False, - modifiable=False, dynamic=False, removable=False, - stickingatnode=False): - """ - Add a linear or nonlinear constraint. - - Parameters - ---------- - cons : ExprCons - the constraint expression to add to the model (e.g., x + y <= 5) - name : str, optional - the name of the constraint, generic name if empty (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraints always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The created and added Constraint object. - - """ - assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ - - cdef SCIP_CONS* scip_cons - - kwargs = dict(name=name, initial=initial, separate=separate, - enforce=enforce, check=check, - propagate=propagate, local=local, - modifiable=modifiable, dynamic=dynamic, - removable=removable, - stickingatnode=stickingatnode - ) - # we have to pass this back to a SCIP_CONS* - # object to create a new python constraint & handle constraint release - # correctly. Otherwise, segfaults when trying to query information - # about the created constraint later. - pycons_initial = self.createConsFromExpr(cons, **kwargs) - scip_cons = (pycons_initial).scip_cons - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pycons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pycons - - def addConss(self, conss, name='', initial=True, separate=True, - enforce=True, check=True, propagate=True, local=False, - modifiable=False, dynamic=False, removable=False, - stickingatnode=False): - """Adds multiple constraints. - - Each of the constraints is added to the model using Model.addCons(). - - For all parameters, except `conss`, this method behaves differently depending on the - type of the passed argument: - 1. If the value is iterable, it must be of the same length as `conss`. For each - constraint, Model.addCons() will be called with the value at the corresponding index. - 2. Else, the (default) value will be applied to all of the constraints. - - Parameters - ---------- - conss : iterable of ExprCons - An iterable of constraint objects. Any iterable will be converted into a list before further processing. - name : str or iterable of str, optional - the name of the constraint, generic name if empty (Default value = '') - initial : bool or iterable of bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool or iterable of bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool or iterable of bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool or iterable of bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool or iterable of bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool or iterable of bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool or iterable of bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool or iterable of bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool or iterable of bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool or iterable of bool, optional - should the constraints always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - list of Constraint - The created and added Constraint objects. - - """ - cdef int n_conss - cdef int i - - if isinstance(conss, MatrixExprCons): - conss = conss.flatten() - - def ensure_iterable(elem, length): - if isinstance(elem, Iterable): - return elem - else: - return list(repeat(elem, length)) - - assert isinstance(conss, Iterable), "Given constraint list is not iterable." - - conss = list(conss) - n_conss = len(conss) - - if isinstance(name, str): - if name == "": - name = ["" for i in range(n_conss)] - else: - name = ["%s_%s" % (name, i) for i in range(n_conss)] - - initial = ensure_iterable(initial, n_conss) - separate = ensure_iterable(separate, n_conss) - enforce = ensure_iterable(enforce, n_conss) - check = ensure_iterable(check, n_conss) - propagate = ensure_iterable(propagate, n_conss) - local = ensure_iterable(local, n_conss) - modifiable = ensure_iterable(modifiable, n_conss) - dynamic = ensure_iterable(dynamic, n_conss) - removable = ensure_iterable(removable, n_conss) - stickingatnode = ensure_iterable(stickingatnode, n_conss) - - constraints = [] - for i, cons in enumerate(conss): - constraints.append( - self.addCons(cons, name[i], initial[i], separate[i], enforce[i], - check[i], propagate[i], local[i], modifiable[i], - dynamic[i], removable[i], stickingatnode[i]) - ) - - return constraints - - def addMatrixCons(self, - cons: Union[ExprCons, MatrixExprCons], - name: Union[str, np.ndarray] ='', - initial: Union[bool, np.ndarray] = True, - separate: Union[bool, np.ndarray] = True, - enforce: Union[bool, np.ndarray] = True, - check: Union[bool, np.ndarray] = True, - propagate: Union[bool, np.ndarray] = True, - local: Union[bool, np.ndarray] = False, - modifiable: Union[bool, np.ndarray] = False, - dynamic: Union[bool, np.ndarray] = False, - removable: Union[bool, np.ndarray] = False, - stickingatnode: Union[bool, np.ndarray] = False): - """ - Add a linear or nonlinear matrix constraint. - - Parameters - ---------- - cons : ExprCons or MatrixExprCons - The matrix expression constraint or expression constraint, that are not yet an actual constraint - name : str or np.ndarray, optional - the name of the matrix constraint, generic name if empty (Default value = "") - initial : bool or np.ndarray, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool or np.ndarray, optional - should the matrix constraint be separated during LP processing? (Default value = True) - enforce : bool or np.ndarray, optional - should the matrix constraint be enforced during node processing? (Default value = True) - check : bool or np.ndarray, optional - should the matrix constraint be checked for feasibility? (Default value = True) - propagate : bool or np.ndarray, optional - should the matrix constraint be propagated during node processing? (Default value = True) - local : bool or np.ndarray, optional - is the matrix constraint only valid locally? (Default value = False) - modifiable : bool or np.ndarray, optional - is the matrix constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool or np.ndarray, optional - is the matrix constraint subject to aging? (Default value = False) - removable : bool or np.ndarray, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool or np.ndarray, optional - should the matrix constraints always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint or MatrixConstraint - The created and added Constraint or MatrixConstraint. - """ - if not isinstance(cons, (ExprCons, MatrixExprCons)): - raise TypeError("given constraint is not MatrixExprCons nor ExprCons but %s" % cons.__class__.__name__) - - if isinstance(cons, ExprCons): - return self.addCons(cons, name=name, initial=initial, separate=separate, - enforce=enforce, check=check, propagate=propagate, - local=local, modifiable=modifiable, dynamic=dynamic, - removable=removable, stickingatnode=stickingatnode) - - shape = cons.shape - - if isinstance(name, np.ndarray): - assert name.shape == shape - if isinstance(initial, np.ndarray): - assert initial.shape == shape - if isinstance(separate, np.ndarray): - assert separate.shape == shape - if isinstance(enforce, np.ndarray): - assert enforce.shape == shape - if isinstance(check, np.ndarray): - assert check.shape == shape - if isinstance(propagate, np.ndarray): - assert propagate.shape == shape - if isinstance(local, np.ndarray): - assert local.shape == shape - if isinstance(modifiable, np.ndarray): - assert modifiable.shape == shape - if isinstance(dynamic, np.ndarray): - assert dynamic.shape == shape - if isinstance(removable, np.ndarray): - assert removable.shape == shape - if isinstance(stickingatnode, np.ndarray): - assert stickingatnode.shape == shape - - matrix_cons = np.empty(shape, dtype=object) - - if isinstance(shape, int): - ndim = 1 - else: - ndim = len(shape) - # cdef np.ndarray[object, ndim=ndim] matrix_variable = np.empty(shape, dtype=object) - matrix_variable = np.empty(shape, dtype=object) - - if isinstance(name, str): - matrix_names = np.full(shape, name, dtype=object) - if name != "": - for idx in np.ndindex(matrix_variable.shape): - matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" - else: - matrix_names = name - - if not isinstance(initial, np.ndarray): - matrix_initial = np.full(shape, initial, dtype=bool) - else: - matrix_initial = initial - - if not isinstance(separate, np.ndarray): - matrix_separate = np.full(shape, separate, dtype=bool) - else: - matrix_separate = separate - - if not isinstance(enforce, np.ndarray): - matrix_enforce = np.full(shape, enforce, dtype=bool) - else: - matrix_enforce = enforce - - if not isinstance(check, np.ndarray): - matrix_check = np.full(shape, check, dtype=bool) - else: - matrix_check = check - - if not isinstance(propagate, np.ndarray): - matrix_propagate = np.full(shape, propagate, dtype=bool) - else: - matrix_propagate = propagate - - if not isinstance(local, np.ndarray): - matrix_local = np.full(shape, local, dtype=bool) - else: - matrix_local = local - - if not isinstance(modifiable, np.ndarray): - matrix_modifiable = np.full(shape, modifiable, dtype=bool) - else: - matrix_modifiable = modifiable - - if not isinstance(dynamic, np.ndarray): - matrix_dynamic = np.full(shape, dynamic, dtype=bool) - else: - matrix_dynamic = dynamic - - if not isinstance(removable, np.ndarray): - matrix_removable = np.full(shape, removable, dtype=bool) - else: - matrix_removable = removable - - if not isinstance(stickingatnode, np.ndarray): - matrix_stickingatnode = np.full(shape, stickingatnode, dtype=bool) - else: - matrix_stickingatnode = stickingatnode - - for idx in np.ndindex(cons.shape): - matrix_cons[idx] = self.addCons(cons[idx], name=matrix_names[idx], initial=matrix_initial[idx], - separate=matrix_separate[idx], check=matrix_check[idx], - propagate=matrix_propagate[idx], local=matrix_local[idx], - modifiable=matrix_modifiable[idx], dynamic=matrix_dynamic[idx], - removable=matrix_removable[idx], stickingatnode=matrix_stickingatnode[idx]) - - return matrix_cons.view(MatrixConstraint) - - def addConsDisjunction(self, conss, name = '', initial = True, - relaxcons = None, enforce=True, check =True, - local=False, modifiable = False, dynamic = False): - """ - Add a disjunction constraint. - - Parameters - ---------- - conss : iterable of ExprCons - An iterable of constraint objects to be included initially in the disjunction. - Currently, these must be expressions. - name : str, optional - the name of the disjunction constraint. - initial : bool, optional - should the LP relaxation of disjunction constraint be in the initial LP? (Default value = True) - relaxcons : None, optional - a conjunction constraint containing the linear relaxation of the disjunction constraint, or None. - NOT YET SUPPORTED. (Default value = None) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - - Returns - ------- - Constraint - The created disjunction constraint - - """ - cdef SCIP_EXPR* scip_expr - cdef SCIP_CONS* scip_cons - cdef SCIP_CONS* disj_cons - cdef int n_conss - cdef int i - - def ensure_iterable(elem, length): - if isinstance(elem, Iterable): - return elem - else: - return list(repeat(elem, length)) - assert isinstance(conss, Iterable), "Given constraint list is not iterable" - - conss = list(conss) - n_conss = len(conss) - - PY_SCIP_CALL(SCIPcreateConsDisjunction( - self._scip, &disj_cons, str_conversion(name), 0, &scip_cons, NULL, - initial, enforce, check, local, modifiable, dynamic - )) - - - # TODO add constraints to disjunction - for i, cons in enumerate(conss): - pycons = self.createConsFromExpr(cons, name=name, initial = initial, - enforce=enforce, check=check, - local=local, modifiable=modifiable, dynamic=dynamic - ) - PY_SCIP_CALL(SCIPaddConsElemDisjunction(self._scip,disj_cons, (pycons).scip_cons)) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &(pycons).scip_cons)) - PY_SCIP_CALL(SCIPaddCons(self._scip, disj_cons)) - PyCons = self._getOrCreateCons(disj_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &disj_cons)) - - return PyCons - - def addConsElemDisjunction(self, Constraint disj_cons, Constraint cons): - """ - Appends a constraint to a disjunction. - - Parameters - ---------- - disj_cons : Constraint - the disjunction constraint to append to. - cons : Constraint - the constraint to append - - Returns - ------- - disj_cons : Constraint - The disjunction constraint with `cons` appended. - - """ - PY_SCIP_CALL(SCIPaddConsElemDisjunction(self._scip, (disj_cons).scip_cons, (cons).scip_cons)) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &(cons).scip_cons)) - return disj_cons - - def addMatrixConsDisjunction(self, conss: Iterable, - name: Union[str, np.ndarray] = '', initial: Union[bool, np.ndarray] = True, - relaxcons=None, enforce: Union[bool, np.ndarray] = True, - check: Union[bool, np.ndarray] = True, local: Union[bool, np.ndarray] = False, - modifiable: Union[bool, np.ndarray] = False, - dynamic: Union[bool, np.ndarray] = False): - """ - Add an elementwise disjunction of matrix constraint expressions. - - Given an iterable of ``MatrixExprCons`` with a common shape, creates one - disjunction per index: for each position ``idx``, the resulting - disjunction enforces that at least one of ``conss[k][idx]`` holds. - ``ExprCons`` entries are broadcast to every position. If every entry in - ``conss`` is a plain ``ExprCons``, the call is forwarded to - :meth:`addConsDisjunction` and returns a single ``Constraint``. - - Note: this method accepts constraint *expressions* (e.g., ``A @ x <= b``), - not ``MatrixConstraint``/``Constraint`` objects returned by - :meth:`addMatrixCons`/:meth:`addCons`. - - Parameters - ---------- - conss : iterable of MatrixExprCons or ExprCons - Constraint expressions to combine elementwise into disjunctions. All - ``MatrixExprCons`` entries must share the same shape. - name : str or np.ndarray, optional - Name of the disjunction constraints. (Default value = "") - initial : bool or np.ndarray, optional - Should the LP relaxation be in the initial LP? (Default value = True) - relaxcons : None, optional - NOT YET SUPPORTED. (Default value = None) - enforce : bool or np.ndarray, optional - Should the constraint be enforced during node processing? (Default value = True) - check : bool or np.ndarray, optional - Should the constraint be checked for feasibility? (Default value = True) - local : bool or np.ndarray, optional - Is the constraint only valid locally? (Default value = False) - modifiable : bool or np.ndarray, optional - Is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool or np.ndarray, optional - Is the constraint subject to aging? (Default value = False) - - Returns - ------- - MatrixConstraint or Constraint - A ``MatrixConstraint`` of the common shape when any entry of - ``conss`` is a ``MatrixExprCons``; otherwise a single - ``Constraint`` from the scalar fallback. - """ - if not isinstance(conss, Iterable): - raise TypeError(f"given constraint list is not iterable, but got {type(conss).__name__}") - conss = list(conss) - - for cons in conss: - if not isinstance(cons, (ExprCons, MatrixExprCons)): - raise TypeError( - "element of conss is not MatrixExprCons nor ExprCons but %s" - % cons.__class__.__name__ - ) - - if all(isinstance(cons, ExprCons) for cons in conss): - return self.addConsDisjunction( - conss, name=name, initial=initial, relaxcons=relaxcons, - enforce=enforce, check=check, local=local, - modifiable=modifiable, dynamic=dynamic, - ) - - shape = None - for cons in conss: - if isinstance(cons, MatrixExprCons): - if shape is None: - shape = cons.shape - elif cons.shape != shape: - raise ValueError( - "All MatrixExprCons in conss must have the same shape, " - "got %s and %s" % (shape, cons.shape) - ) - - for arr in (name, initial, enforce, check, local, modifiable, dynamic): - if isinstance(arr, np.ndarray): - assert arr.shape == shape - - if isinstance(name, str): - matrix_names = np.full(shape, name, dtype=object) - if name != "": - for idx in np.ndindex(shape): - matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" - else: - matrix_names = name - - matrix_initial = initial if isinstance(initial, np.ndarray) else np.full(shape, initial, dtype=bool) - matrix_enforce = enforce if isinstance(enforce, np.ndarray) else np.full(shape, enforce, dtype=bool) - matrix_check = check if isinstance(check, np.ndarray) else np.full(shape, check, dtype=bool) - matrix_local = local if isinstance(local, np.ndarray) else np.full(shape, local, dtype=bool) - matrix_modifiable = modifiable if isinstance(modifiable, np.ndarray) else np.full(shape, modifiable, dtype=bool) - matrix_dynamic = dynamic if isinstance(dynamic, np.ndarray) else np.full(shape, dynamic, dtype=bool) - - matrix_cons = np.empty(shape, dtype=object) - for idx in np.ndindex(shape): - elem_conss = [ - cons[idx] if isinstance(cons, MatrixExprCons) else cons - for cons in conss - ] - matrix_cons[idx] = self.addConsDisjunction( - elem_conss, - name=matrix_names[idx], - initial=matrix_initial[idx], - relaxcons=relaxcons, - enforce=matrix_enforce[idx], - check=matrix_check[idx], - local=matrix_local[idx], - modifiable=matrix_modifiable[idx], - dynamic=matrix_dynamic[idx], - ) - - return matrix_cons.view(MatrixConstraint) - - def getConsNVars(self, Constraint constraint): - """ - Gets number of variables in a constraint. - - Parameters - ---------- - constraint : Constraint - Constraint to get the number of variables from. - - Returns - ------- - int - - Raises - ------ - TypeError - If the associated constraint handler does not have this functionality - - """ - cdef int nvars - cdef SCIP_Bool success - - PY_SCIP_CALL(SCIPgetConsNVars(self._scip, constraint.scip_cons, &nvars, &success)) - - if not success: - conshdlr = SCIPconsGetHdlr(constraint.scip_cons) - conshdrlname = SCIPconshdlrGetName(conshdlr) - raise TypeError("The constraint handler %s does not have this functionality." % conshdrlname) - - return nvars - - def getConsVars(self, Constraint constraint): - """ - Gets variables in a constraint. - - Parameters - ---------- - constraint : Constraint - Constraint to get the variables from. - - Returns - ------- - list of Variable - - """ - cdef SCIP_VAR** _vars - cdef int nvars - cdef SCIP_Bool success - cdef int i - - SCIPgetConsNVars(self._scip, constraint.scip_cons, &nvars, &success) - _vars = malloc(nvars * sizeof(SCIP_VAR*)) - SCIPgetConsVars(self._scip, constraint.scip_cons, _vars, nvars, &success) - - if not success: - free(_vars) - return None - - vars = [] - for i in range(nvars): - vars.append(self._getOrCreateVar(_vars[i])) - - free(_vars) - return vars - - def getConsVals(self, Constraint constraint): - """ - Returns the value array of an arbitrary SCIP constraint that can be represented as a single linear constraint. - - Parameters - ---------- - constraint : Constraint - Constraint to get the values from. - - Returns - ------- - list of float - - """ - cdef SCIP_Real* _vals - cdef int nvars - cdef SCIP_Bool success - cdef int i - - nvars = self.getConsNVars(constraint) - _vals = malloc(nvars * sizeof(SCIP_Real)) - PY_SCIP_CALL(SCIPgetConsVals(self._scip, constraint.scip_cons, _vals, nvars, &success)) - - if not success: - free(_vals) - return None - - vals = [_vals[i] for i in range(nvars)] - free(_vals) - return vals - - def getNVarsAnd(self, Constraint and_cons): - """ - Gets number of variables in and constraint. - - Parameters - ---------- - and_cons : Constraint - AND constraint to get the number of variables from. - - Returns - ------- - int - - """ - - return SCIPgetNVarsAnd(self._scip, and_cons.scip_cons) - - def getVarsAnd(self, Constraint and_cons): - """ - Gets variables in AND constraint. - - Parameters - ---------- - and_cons : Constraint - AND Constraint to get the variables from. - - Returns - ------- - list of Variable - - """ - - cdef SCIP_VAR** _vars - cdef int nvars - cdef int i - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(and_cons.scip_cons))).decode('UTF-8') - assert constype == 'and', "The constraint handler %s does not have this functionality." % constype - - nvars = SCIPgetNVarsAnd(self._scip, and_cons.scip_cons) - _vars = SCIPgetVarsAnd(self._scip, and_cons.scip_cons) - - vars = [] - for i in range(nvars): - vars.append(self._getOrCreateVar(_vars[i])) - - return vars - - def getResultantAnd(self, Constraint and_cons): - """ - Gets the resultant variable in And constraint. - - Parameters - ---------- - and_cons : Constraint - Constraint to get the resultant variable from. - - Returns - ------- - Variable - - """ - cdef SCIP_VAR* _resultant - - _resultant = SCIPgetResultantAnd(self._scip, and_cons.scip_cons) - return self._getOrCreateVar(_resultant) - - def isAndConsSorted(self, Constraint and_cons): - """ - Returns if the variables of the AND-constraint are sorted with respect to their indices. - - Parameters - ---------- - and_cons : Constraint - Constraint to check. - - Returns - ------- - bool - - """ - - return SCIPisAndConsSorted(self._scip, and_cons.scip_cons) - - def sortAndCons(self, Constraint and_cons): - """ - Sorts the variables of the AND-constraint with respect to their indices. - - Parameters - ---------- - and_cons : Constraint - Constraint to sort. - - """ - - PY_SCIP_CALL(SCIPsortAndCons(self._scip, and_cons.scip_cons)) - - def getNVarsLogicor(self, Constraint logicor_cons): - """ - Gets number of variables in logicor constraint. - - Parameters - ---------- - logicor_cons : Constraint - logicor constraint to get the number of variables from. - - Returns - ------- - int - - """ - - return SCIPgetNVarsLogicor(self._scip, logicor_cons.scip_cons) - - def getVarsLogicor(self, Constraint logicor_cons): - """ - Gets variables in logicor constraint. - - Parameters - ---------- - logicor_cons : Constraint - logicor constraint to get the variables from. - - Returns - ------- - list of Variable - - """ - - cdef SCIP_VAR** _vars - cdef int nvars - cdef int i - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(logicor_cons.scip_cons))).decode('UTF-8') - assert constype == 'logicor', "The constraint handler %s does not have this functionality." % constype - - nvars = SCIPgetNVarsLogicor(self._scip, logicor_cons.scip_cons) - _vars = SCIPgetVarsLogicor(self._scip, logicor_cons.scip_cons) - - vars = [] - for i in range(nvars): - vars.append(self._getOrCreateVar(_vars[i])) - - return vars - - def addCoefLogicor(self, Constraint logicor_cons, Variable var): - """ - Adds a variable to a logicor constraint. - - Parameters - ---------- - logicor_cons : Constraint - logicor constraint to add the variable to. - var : Variable - BINARY variable to add. - - """ - - PY_SCIP_CALL(SCIPaddCoefLogicor(self._scip, logicor_cons.scip_cons, var.scip_var)) - - cdef SCIP_CONS* _getTransformedCons(self, Constraint cons, str expected_cons_type): - """ - Validates constraint type and retrieves its transformed representation. - - Parameters - ---------- - cons : Constraint - Constraint to get the transformed representation for. - expected_cons_type : str - Expected constraint type name (e.g. 'linear', 'logicor', 'knapsack'). - - Returns - ------- - SCIP_CONS* - Pointer to the transformed SCIP constraint, or NULL if transformed constraint does not exist. - - Raises - ------ - Warning - If the constraint handler type does not match expected_cons_type. - - """ - cdef SCIP_CONS* transcons - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if not constype == expected_cons_type: - raise Warning(f"dual solution values not available for constraints of type {constype}") - - if cons.isOriginal(): - PY_SCIP_CALL(SCIPgetTransformedCons(self._scip, cons.scip_cons, &transcons)) - return transcons - - return cons.scip_cons - - def getDualsolLogicor(self, Constraint logicor_cons): - """ - Gets the dual solution of a logicor constraint in the current LP. - - Parameters - ---------- - logicor_cons : Constraint - logicor constraint to get the dual solution from. - - Returns - ------- - float - Zero if presolve removed the transformed constraint. - - """ - cdef SCIP_CONS* transcons = self._getTransformedCons(logicor_cons, "logicor") - if transcons == NULL: - return 0.0 - - return SCIPgetDualsolLogicor(self._scip, transcons) - - def getDualfarkasLogicor(self, Constraint logicor_cons): - """ - Gets the dual Farkas value of a logicor constraint in the current infeasible LP. - - Parameters - ---------- - logicor_cons : Constraint - logicor constraint to get the dual Farkas value from. - - Returns - ------- - float - Zero if presolve removed the transformed constraint. - - """ - cdef SCIP_CONS* transcons = self._getTransformedCons(logicor_cons, "logicor") - if transcons == NULL: - return 0.0 - - return SCIPgetDualfarkasLogicor(self._scip, transcons) - - def printCons(self, Constraint constraint): - """ - Print the constraint - - Parameters - ---------- - constraint : Constraint - - """ - return PY_SCIP_CALL(SCIPprintCons(self._scip, constraint.scip_cons, NULL)) - - def addExprNonlinear(self, Constraint cons, expr, coef): - """ - Add coef*expr to nonlinear constraint. - - Parameters - ---------- - cons : Constraint - expr : Expr or GenExpr - coef : float - - """ - assert self.getStage() == 1, "addExprNonlinear cannot be called in stage %i." % self.getStage() - assert cons.isNonlinear(), "addExprNonlinear can only be called with nonlinear constraints." - - cdef Constraint temp_cons - cdef SCIP_EXPR* scip_expr - - temp_cons = self.addCons(expr <= 0) - scip_expr = SCIPgetExprNonlinear(temp_cons.scip_cons) - - PY_SCIP_CALL(SCIPaddExprNonlinear(self._scip, cons.scip_cons, scip_expr, coef)) - self.delCons(temp_cons) - - def addConsCoeff(self, Constraint cons, Variable var, coeff): - """ - Add coefficient to the constraint (if non-zero). - - Parameters - ---------- - cons : Constraint - Constraint to be changed - var : Variable - variable to be added - coeff : float - coefficient of new variable - - """ - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if constype == 'linear': - PY_SCIP_CALL(SCIPaddCoefLinear(self._scip, cons.scip_cons, var.scip_var, coeff)) - elif constype == 'knapsack': - PY_SCIP_CALL(SCIPaddCoefKnapsack(self._scip, cons.scip_cons, var.scip_var, coeff)) - else: - raise NotImplementedError("Adding coefficients to %s constraints is not implemented." % constype) - - def addConsNode(self, Node node, ExprCons cons, Node validnode=None, name='', - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=True, dynamic=False, removable=True, - stickingatnode=True): - """ - Add a constraint to the given node. - - Parameters - ---------- - node : Node - node at which the constraint will be added - cons : ExprCons - the constraint expression to add to the node (e.g., x + y <= 5) - validnode : Node or None, optional - more global node where cons is also valid. (Default=None) - name : str, optional - name of the constraint (Default value = '') - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = True) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = True) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added? (Default value = True) - - Returns - ------- - Constraint - The added Constraint object. - - """ - assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ - - cdef SCIP_CONS* scip_cons - - kwargs = dict(name=name, initial=initial, separate=separate, - enforce=enforce, check=check, propagate=propagate, - local=local, modifiable=False, dynamic=dynamic, - removable=removable, stickingatnode=stickingatnode) - pycons_initial = self.createConsFromExpr(cons, **kwargs) - scip_cons = (pycons_initial).scip_cons - - if isinstance(validnode, Node): - PY_SCIP_CALL(SCIPaddConsNode(self._scip, node.scip_node, scip_cons, validnode.scip_node)) - else: - PY_SCIP_CALL(SCIPaddConsNode(self._scip, node.scip_node, scip_cons, NULL)) - - pycons = Constraint.create(scip_cons) - pycons.data = (pycons_initial).data - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pycons - - def addConsLocal(self, ExprCons cons, Node validnode=None, name='', - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=True, dynamic=False, removable=True, - stickingatnode=True): - """ - Add a constraint to the current node. - - Parameters - ---------- - cons : ExprCons - the constraint expression to add to the current node (e.g., x + y <= 5) - validnode : Node or None, optional - more global node where cons is also valid. (Default=None) - name : str, optional - name of the constraint (Default value = '') - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = True) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = True) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added? (Default value = True) - - Returns - ------- - Constraint - The added Constraint object. - - """ - assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ - - cdef SCIP_CONS* scip_cons - - kwargs = dict(name=name, initial=initial, separate=separate, - enforce=enforce, check=check, propagate=propagate, - local=local, modifiable=False, dynamic=dynamic, - removable=removable, stickingatnode=stickingatnode) - pycons_initial = self.createConsFromExpr(cons, **kwargs) - scip_cons = (pycons_initial).scip_cons - - if isinstance(validnode, Node): - PY_SCIP_CALL(SCIPaddConsLocal(self._scip, scip_cons, validnode.scip_node)) - else: - PY_SCIP_CALL(SCIPaddConsLocal(self._scip, scip_cons, NULL)) - - pycons = Constraint.create(scip_cons) - pycons.data = (pycons_initial).data - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pycons - - def addConsLinear(self, vars, vals, lhs=None, rhs=None, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, modifiable=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add a linear constraint lhs <= sum(vals[i] * vars[i]) <= rhs directly from - variables and coefficients, without building an expression. Faster than addCons - for building large models. - - Parameters - ---------- - vars : list of Variable - variables in the constraint - vals : list of float - coefficients of the variables - lhs : float or None, optional - left-hand side, -infinity if None (Default value = None) - rhs : float or None, optional - right-hand side, infinity if None (Default value = None) - name : str, optional - name of the constraint, generic name if empty (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created linear constraint - - """ - cdef int nvars = len(vars) - cdef int i - cdef SCIP_Real* vals_array - cdef SCIP_CONS* scip_cons - cdef _VarArray wrapper - - if nvars != len(vals): - raise ValueError("Number of variables and values must be the same.") - - if lhs is None: - lhs = -SCIPinfinity(self._scip) - if rhs is None: - rhs = SCIPinfinity(self._scip) - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - wrapper = _VarArray(vars) - vals_array = malloc(nvars * sizeof(SCIP_Real)) - for i in range(nvars): - vals_array[i] = vals[i] - - PY_SCIP_CALL(SCIPcreateConsLinear( - self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, vals_array, - lhs, rhs, initial, separate, enforce, check, propagate, local, modifiable, - dynamic, removable, stickingatnode)) - - free(vals_array) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsKnapsack(self, vars, weights, capacity, name="", - initial=True, separate=True, enforce=True, check=True, - modifiable=False, propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Parameters - ---------- - vars : list of Variable - list of variables to be included - weights : list of int - list of weights - capacity: int - capacity of the knapsack - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created knapsack constraint - """ - - cdef int nvars = len(vars) - cdef int i - cdef SCIP_Longint* weights_array = malloc(nvars * sizeof(SCIP_Real)) - cdef SCIP_CONS* scip_cons - cdef _VarArray wrapper - - assert nvars == len(weights), "Number of variables and weights must be the same." - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - wrapper = _VarArray(vars) - for i in range(nvars): - weights_array[i] = weights[i] - - PY_SCIP_CALL(SCIPcreateConsKnapsack( - self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, weights_array, - capacity, initial, separate, enforce, check, propagate, local, modifiable, - dynamic, removable, stickingatnode)) - - free(weights_array) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsCumulative(self, vars, durations, demands, capacity, name="", - initial=True, separate=True, enforce=True, check=True, - modifiable=False, propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add a cumulative constraint. - - A cumulative constraint models resource-constrained scheduling: given jobs - with start times, durations, and demands on a shared resource of fixed - capacity, it ensures that at every time point t the total demand of all - jobs active at t does not exceed the capacity. Job j is active at t if - start[j] <= t < start[j] + duration[j]. - - The start times are given as integer variables in `vars`. The `durations`, - `demands`, and `capacity` arguments must be fixed integers. End times are - implicit (start + duration); post separate constraints if explicit end - variables are needed. - - If you simply want the jobs to not overlap, set all durations to '1'. - - Parameters - ---------- - vars : list of Variable - list of integer variables corresponding to job start times - durations : list of int - list of durations, one for each job - demands : list of int - list of demands, one for each job - capacity : int - available cumulative capacity at any time point - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created cumulative constraint - """ - - cdef int nvars = len(vars) - cdef int i - cdef int* durations_array = malloc(nvars * sizeof(int)) - cdef int* demands_array = malloc(nvars * sizeof(int)) - cdef SCIP_CONS* scip_cons - cdef _VarArray wrapper - - assert nvars == len(durations) == len(demands), "Number of variables, durations, and demands must be the same." - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - wrapper = _VarArray(vars) - for i in range(nvars): - durations_array[i] = durations[i] - demands_array[i] = demands[i] - - PY_SCIP_CALL(SCIPcreateConsCumulative( - self._scip, &scip_cons, str_conversion(name), nvars, wrapper.ptr, durations_array, - demands_array, capacity, initial, separate, enforce, check, propagate, local, modifiable, - dynamic, removable, stickingatnode)) - - free(durations_array) - free(demands_array) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsSOS1(self, vars, weights=None, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add an SOS1 constraint. - - Parameters - ---------- - vars : list of Variable - list of variables to be included - weights : list of float or None, optional - list of weights (Default value = None) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created SOS1 constraint - - """ - cdef SCIP_CONS* scip_cons - cdef int nvars - cdef int i - cdef _VarArray wrapper - - PY_SCIP_CALL(SCIPcreateConsSOS1(self._scip, &scip_cons, str_conversion(name), 0, NULL, NULL, - initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - nvars = len(vars) - wrapper = _VarArray(vars) - if weights is None: - for i in range(nvars): - PY_SCIP_CALL(SCIPappendVarSOS1(self._scip, scip_cons, wrapper.ptr[i])) - else: - for i in range(nvars): - PY_SCIP_CALL(SCIPaddVarSOS1(self._scip, scip_cons, wrapper.ptr[i], weights[i])) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsSOS2(self, vars, weights=None, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add an SOS2 constraint. - - Parameters - ---------- - vars : list of Variable - list of variables to be included - weights : list of float or None, optional - list of weights (Default value = None) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created SOS2 constraint - - """ - cdef SCIP_CONS* scip_cons - cdef int nvars - cdef int i - cdef _VarArray wrapper - - PY_SCIP_CALL(SCIPcreateConsSOS2(self._scip, &scip_cons, str_conversion(name), 0, NULL, NULL, - initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - nvars = len(vars) - wrapper = _VarArray(vars) - if weights is None: - for i in range(nvars): - PY_SCIP_CALL(SCIPappendVarSOS2(self._scip, scip_cons, wrapper.ptr[i])) - else: - for i in range(nvars): - PY_SCIP_CALL(SCIPaddVarSOS2(self._scip, scip_cons, wrapper.ptr[i], weights[i])) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsAnd(self, vars, resvar, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, modifiable=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add an AND-constraint. - - Parameters - ---------- - vars : list of Variable - list of BINARY variables to be included (operators) - resvar : Variable - BINARY variable (resultant) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created AND constraint - - """ - cdef int nvars = len(vars) - cdef SCIP_VAR** _vars - cdef SCIP_VAR* _resvar - cdef _VarArray resvar_wrapper = _VarArray(resvar) - cdef _VarArray vars_wrapper = _VarArray(vars) - cdef SCIP_CONS* scip_cons - cdef int i - - _resvar = resvar_wrapper.ptr[0] - _vars = vars_wrapper.ptr - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - PY_SCIP_CALL(SCIPcreateConsAnd(self._scip, &scip_cons, str_conversion(name), _resvar, nvars, _vars, - initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsOr(self, vars, resvar, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, modifiable=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add an OR-constraint. - - Parameters - ---------- - vars : list of Variable - list of BINARY variables to be included (operators) - resvar : Variable - BINARY variable (resultant) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created OR constraint - - """ - cdef int nvars = len(vars) - cdef SCIP_VAR** _vars - cdef SCIP_VAR* _resvar - cdef _VarArray resvar_wrapper = _VarArray(resvar) - cdef _VarArray vars_wrapper = _VarArray(vars) - cdef SCIP_CONS* scip_cons - cdef int i - - _resvar = resvar_wrapper.ptr[0] - _vars = vars_wrapper.ptr - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - PY_SCIP_CALL(SCIPcreateConsOr(self._scip, &scip_cons, str_conversion(name), _resvar, nvars, _vars, - initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsXor(self, vars, rhsvar, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, modifiable=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add a XOR-constraint. - - Parameters - ---------- - vars : list of Variable - list of binary variables to be included (operators) - rhsvar : bool - BOOLEAN value, explicit True, False or bool(obj) is needed (right-hand side) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created XOR constraint - - """ - assert type(rhsvar) is type(bool()), "Provide BOOLEAN value as rhsvar, you gave %s." % type(rhsvar) - - cdef int nvars = len(vars) - cdef SCIP_VAR** _vars - cdef SCIP_CONS* scip_cons - cdef int i - cdef _VarArray wrapper = _VarArray(vars) - - _vars = wrapper.ptr - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - PY_SCIP_CALL(SCIPcreateConsXor(self._scip, &scip_cons, str_conversion(name), rhsvar, nvars, _vars, - initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsLogicor(self, vars, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, modifiable=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add a logicor constraint: at least one of the given binary variables must be one. - - Parameters - ---------- - vars : list of Variable - list of BINARY variables, at least one of which must take value one - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - modifiable : bool, optional - is the constraint modifiable (subject to column generation)? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created logicor constraint - - """ - cdef int nvars = len(vars) - cdef SCIP_VAR** _vars - cdef _VarArray vars_wrapper = _VarArray(vars) - cdef SCIP_CONS* scip_cons - - _vars = vars_wrapper.ptr - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - PY_SCIP_CALL(SCIPcreateConsLogicor(self._scip, &scip_cons, str_conversion(name), nvars, _vars, - initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsCardinality(self, consvars, cardval, indvars=None, weights=None, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """ - Add a cardinality constraint that allows at most 'cardval' many nonzero variables. - - Parameters - ---------- - consvars : list of Variable - list of variables to be included - cardval : int - nonnegative integer - indvars : list of Variable or None, optional - indicator variables indicating which variables may be treated as nonzero in - cardinality constraint, or None if new indicator variables should be - introduced automatically (Default value = None) - weights : list of float or None, optional - weights determining the variable order, or None if variables should be ordered - in the same way they were added to the constraint (Default value = None) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created Cardinality constraint - - """ - cdef SCIP_VAR* indvar - cdef SCIP_CONS* scip_cons - cdef int i - cdef _VarArray v_wrapper - cdef _VarArray indvar_wrapper - cdef SCIP_VAR* scip_var - - PY_SCIP_CALL(SCIPcreateConsCardinality(self._scip, &scip_cons, str_conversion(name), 0, NULL, cardval, NULL, NULL, - initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) - - # circumvent an annoying bug in SCIP 4.0.0 that does not allow uninitialized weights - if weights is None: - weights = list(range(1, len(consvars) + 1)) - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - v_wrapper = _VarArray(consvars) - for i, v in enumerate(consvars): - scip_var = v_wrapper.ptr[i] - if indvars: - indvar_wrapper = _VarArray(indvars[i]) - indvar = indvar_wrapper.ptr[0] - else: - indvar = NULL - - if weights is None: - PY_SCIP_CALL(SCIPappendVarCardinality(self._scip, scip_cons, scip_var, indvar)) - else: - PY_SCIP_CALL(SCIPaddVarCardinality(self._scip, scip_cons, scip_var, indvar, weights[i])) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addConsIndicator(self, cons, binvar=None, activeone=True, name="", - initial=True, separate=True, enforce=True, check=True, - propagate=True, local=False, dynamic=False, - removable=False, stickingatnode=False): - """Add an indicator constraint for the linear inequality `cons`. - - The `binvar` argument models the redundancy of the linear constraint. A solution for which - `binvar` is 1 must satisfy the constraint. - - Parameters - ---------- - cons : ExprCons - a linear inequality - binvar : Variable, optional - binary indicator variable, or None if it should be created (Default value = None) - activeone : bool, optional - constraint should active if binvar is 1 (0 if activeone = False) - name : str, optional - name of the constraint (Default value = "") - initial : bool, optional - should the LP relaxation of constraint be in the initial LP? (Default value = True) - separate : bool, optional - should the constraint be separated during LP processing? (Default value = True) - enforce : bool, optional - should the constraint be enforced during node processing? (Default value = True) - check : bool, optional - should the constraint be checked for feasibility? (Default value = True) - propagate : bool, optional - should the constraint be propagated during node processing? (Default value = True) - local : bool, optional - is the constraint only valid locally? (Default value = False) - dynamic : bool, optional - is the constraint subject to aging? (Default value = False) - removable : bool, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool, optional - should the constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - Constraint - The newly created Indicator constraint - - """ - cdef SCIP_VAR* _binVar - cdef SCIP_CONS* scip_cons - cdef SCIP_Real coeff - cdef _VarArray wrapper - - assert isinstance(cons, ExprCons), "given constraint is not ExprCons but %s" % cons.__class__.__name__ - - if cons._lhs is not None and cons._rhs is not None: - raise ValueError("expected inequality that has either only a left or right hand side") - - if name == '': - name = 'c'+str(SCIPgetNConss(self._scip)+1) - - if cons.expr.degree() > 1: - raise ValueError("expected linear inequality, expression has degree %d" % cons.expr.degree()) - - if cons._rhs is not None: - rhs = cons._rhs - negate = False - else: - rhs = -cons._lhs - negate = True - - if binvar is not None: - wrapper = _VarArray(binvar) - _binVar = wrapper.ptr[0] - if not activeone: - PY_SCIP_CALL(SCIPgetNegatedVar(self._scip, _binVar, &_binVar)) - else: - _binVar = NULL - - PY_SCIP_CALL(SCIPcreateConsIndicator(self._scip, &scip_cons, str_conversion(name), _binVar, 0, NULL, NULL, rhs, - initial, separate, enforce, check, propagate, local, dynamic, removable, stickingatnode)) - terms = cons.expr.terms - - for key, coeff in terms.items(): - if negate: - coeff = -coeff - wrapper = _VarArray(key[0]) - PY_SCIP_CALL(SCIPaddVarIndicator(self._scip, scip_cons, wrapper.ptr[0], coeff)) - - PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons)) - pyCons = self._getOrCreateCons(scip_cons) - - PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons)) - - return pyCons - - def addMatrixConsIndicator(self, cons: Union[ExprCons, MatrixExprCons], binvar: Union[Variable, MatrixVariable] = None, - activeone: Union[bool, np.ndarray] = True, name: Union[str, np.ndarray] = "", - initial: Union[bool, np.ndarray] = True, separate: Union[bool, np.ndarray] = True, - enforce: Union[bool, np.ndarray] = True, check: Union[bool, np.ndarray] = True, - propagate: Union[bool, np.ndarray] = True, local: Union[bool, np.ndarray] = False, - dynamic: Union[bool, np.ndarray] = False, removable: Union[bool, np.ndarray] = False, - stickingatnode: Union[bool, np.ndarray] = False) -> MatrixConstraint: - """Add an indicator matrix constraint for the linear inequality `cons`. - - The `binvar` argument models the redundancy of the linear constraint. A solution - for which `binvar` is 1 must satisfy the constraint. - - Parameters - ---------- - cons : ExprCons or MatrixExprCons - a linear inequality - binvar : Variable or MatrixVariable, optional - binary indicator variable / matrix variable, or None if it should be created. (Default value = None) - activeone : bool or np.ndarray, optional - the matrix constraint should be active if binvar is 1 (0 if activeone = False). - name : str or np.ndarray, optional - name of the matrix constraint. (Default value = "") - initial : bool or np.ndarray, optional - should the LP relaxation of matrix constraint be in the initial LP? (Default value = True) - separate : bool or np.ndarray, optional - should the matrix constraint be separated during LP processing? (Default value = True) - enforce : bool or np.ndarray, optional - should the matrix constraint be enforced during node processing? (Default value = True) - check : bool or np.ndarray, optional - should the matrix constraint be checked for feasibility? (Default value = True) - propagate : bool or np.ndarray, optional - should the matrix constraint be propagated during node processing? (Default value = True) - local : bool or np.ndarray, optional - is the matrix constraint only valid locally? (Default value = False) - dynamic : bool or np.ndarray, optional - is the matrix constraint subject to aging? (Default value = False) - removable : bool or np.ndarray, optional - should the relaxation be removed from the LP due to aging or cleanup? (Default value = False) - stickingatnode : bool or np.ndarray, optional - should the matrix constraint always be kept at the node where it was added, - even if it may be moved to a more global node? (Default value = False) - - Returns - ------- - MatrixConstraint - The newly created Indicator MatrixConstraint object. - """ - - if not isinstance(cons, (ExprCons, MatrixExprCons)): - raise TypeError("given constraint is not MatrixExprCons nor ExprCons but %s" % cons.__class__.__name__) - - if isinstance(cons, ExprCons): - return self.addConsIndicator(cons, binvar=binvar, activeone=activeone, name=name, - initial=initial, separate=separate, enforce=enforce, check=check, - propagate=propagate, local=local, dynamic=dynamic, removable=removable, - stickingatnode=stickingatnode) - - shape = cons.shape - - if isinstance(binvar, MatrixVariable): - assert binvar.shape == shape - if isinstance(activeone, np.ndarray): - assert activeone.shape == shape - if isinstance(name, np.ndarray): - assert name.shape == shape - if isinstance(initial, np.ndarray): - assert initial.shape == shape - if isinstance(separate, np.ndarray): - assert separate.shape == shape - if isinstance(enforce, np.ndarray): - assert enforce.shape == shape - if isinstance(check, np.ndarray): - assert check.shape == shape - if isinstance(propagate, np.ndarray): - assert propagate.shape == shape - if isinstance(local, np.ndarray): - assert local.shape == shape - if isinstance(dynamic, np.ndarray): - assert dynamic.shape == shape - if isinstance(removable, np.ndarray): - assert removable.shape == shape - if isinstance(stickingatnode, np.ndarray): - assert stickingatnode.shape == shape - - if not isinstance(binvar, MatrixVariable): - matrix_binvar = np.full(shape, binvar, dtype=Variable) - else: - matrix_binvar = binvar - - if not isinstance(activeone, np.ndarray): - matrix_activeone = np.full(shape, activeone, dtype=bool) - else: - matrix_activeone = activeone - - if isinstance(name, str): - matrix_names = np.full(shape, name, dtype=object) - if name != "": - for idx in np.ndindex(shape): - matrix_names[idx] = f"{name}_{'_'.join(map(str, idx))}" - else: - matrix_names = name - - if not isinstance(initial, np.ndarray): - matrix_initial = np.full(shape, initial, dtype=bool) - else: - matrix_initial = initial - - if not isinstance(enforce, np.ndarray): - matrix_enforce = np.full(shape, enforce, dtype=bool) - else: - matrix_enforce = enforce - - if not isinstance(separate, np.ndarray): - matrix_separate = np.full(shape, separate, dtype=bool) - else: - matrix_separate = separate - - if not isinstance(check, np.ndarray): - matrix_check = np.full(shape, check, dtype=bool) - else: - matrix_check = check - - if not isinstance(propagate, np.ndarray): - matrix_propagate = np.full(shape, propagate, dtype=bool) - else: - matrix_propagate = propagate - - if not isinstance(local, np.ndarray): - matrix_local = np.full(shape, local, dtype=bool) - else: - matrix_local = local - - if not isinstance(dynamic, np.ndarray): - matrix_dynamic = np.full(shape, dynamic, dtype=bool) - else: - matrix_dynamic = dynamic - - if not isinstance(removable, np.ndarray): - matrix_removable = np.full(shape, removable, dtype=bool) - else: - matrix_removable = removable - - if not isinstance(stickingatnode, np.ndarray): - matrix_stickingatnode = np.full(shape, stickingatnode, dtype=bool) - else: - matrix_stickingatnode = stickingatnode - - matrix_cons = np.empty(shape, dtype=object) - for idx in np.ndindex(shape): - matrix_cons[idx] = self.addConsIndicator( - cons[idx], - binvar=matrix_binvar[idx], - activeone=matrix_activeone[idx], - name=matrix_names[idx], - initial=matrix_initial[idx], - separate=matrix_separate[idx], - enforce=matrix_enforce[idx], - check=matrix_check[idx], - propagate=matrix_propagate[idx], - local=matrix_local[idx], - dynamic=matrix_dynamic[idx], - removable=matrix_removable[idx], - stickingatnode=matrix_stickingatnode[idx], - ) - - return matrix_cons.view(MatrixConstraint) - - def getLinearConsIndicator(self, Constraint cons): - """ - Get the linear constraint corresponding to the indicator constraint. - - Parameters - ---------- - cons : Constraint - The indicator constraint - - Returns - ------- - Constraint or None - """ - - cdef SCIP_CONS* lincons = SCIPgetLinearConsIndicator(cons.scip_cons) - if lincons == NULL: - return None - return self._getOrCreateCons(lincons) - - def getSlackVarIndicator(self, Constraint cons): - """ - Get slack variable of an indicator constraint. - - - Parameters - ---------- - cons : Constraint - The indicator constraint - - Returns - ------- - Variable - - """ - cdef SCIP_VAR* var = SCIPgetSlackVarIndicator(cons.scip_cons) - return self._getOrCreateVar(var) - - def addPyCons(self, Constraint cons): - """ - Adds a customly created cons. - - Parameters - ---------- - cons : Constraint - constraint to add - - """ - PY_SCIP_CALL(SCIPaddCons(self._scip, cons.scip_cons)) - Py_INCREF(cons) - - def addVarSOS1(self, Constraint cons, Variable var, weight): - """ - Add variable to SOS1 constraint. - - Parameters - ---------- - cons : Constraint - SOS1 constraint - var : Variable - new variable - weight : weight - weight of new variable - - """ - PY_SCIP_CALL(SCIPaddVarSOS1(self._scip, cons.scip_cons, var.scip_var, weight)) - - def appendVarSOS1(self, Constraint cons, Variable var): - """ - Append variable to SOS1 constraint. - - Parameters - ---------- - cons : Constraint - SOS1 constraint - var : Variable - variable to append - - """ - PY_SCIP_CALL(SCIPappendVarSOS1(self._scip, cons.scip_cons, var.scip_var)) - - def addVarSOS2(self, Constraint cons, Variable var, weight): - """ - Add variable to SOS2 constraint. - - Parameters - ---------- - cons : Constraint - SOS2 constraint - var : Variable - new variable - weight : weight - weight of new variable - - """ - PY_SCIP_CALL(SCIPaddVarSOS2(self._scip, cons.scip_cons, var.scip_var, weight)) - - def appendVarSOS2(self, Constraint cons, Variable var): - """ - Append variable to SOS2 constraint. - - Parameters - ---------- - cons : Constraint - SOS2 constraint - var : Variable - variable to append - - """ - PY_SCIP_CALL(SCIPappendVarSOS2(self._scip, cons.scip_cons, var.scip_var)) - - def setInitial(self, Constraint cons, newInit): - """ - Set "initial" flag of a constraint. - - Parameters - ---------- - cons : Constraint - newInit : bool - - """ - PY_SCIP_CALL(SCIPsetConsInitial(self._scip, cons.scip_cons, newInit)) - - def setModifiable(self, Constraint cons, newMod): - """ - Set "modifiable" flag of a constraint. - - Parameters - ---------- - cons : Constraint - newMod : bool - - """ - PY_SCIP_CALL(SCIPsetConsModifiable(self._scip, cons.scip_cons, newMod)) - - def setRemovable(self, Constraint cons, newRem): - """ - Set "removable" flag of a constraint. - - Parameters - ---------- - cons : Constraint - newRem : bool - - """ - PY_SCIP_CALL(SCIPsetConsRemovable(self._scip, cons.scip_cons, newRem)) - - def setEnforced(self, Constraint cons, newEnf): - """ - Set "enforced" flag of a constraint. - - Parameters - ---------- - cons : Constraint - newEnf : bool - - """ - PY_SCIP_CALL(SCIPsetConsEnforced(self._scip, cons.scip_cons, newEnf)) - - def setCheck(self, Constraint cons, newCheck): - """ - Set "check" flag of a constraint. - - Parameters - ---------- - cons : Constraint - newCheck : bool - - """ - PY_SCIP_CALL(SCIPsetConsChecked(self._scip, cons.scip_cons, newCheck)) - - def chgRhs(self, Constraint cons, rhs): - """ - Change right-hand side value of a constraint. - - Parameters - ---------- - cons : Constraint - constraint to change the right-hand side from - rhs : float or None - new right-hand side (set to None for +infinity) - - """ - - if rhs is None: - rhs = SCIPinfinity(self._scip) - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if constype == 'linear': - PY_SCIP_CALL(SCIPchgRhsLinear(self._scip, cons.scip_cons, rhs)) - elif constype == 'nonlinear': - PY_SCIP_CALL(SCIPchgRhsNonlinear(self._scip, cons.scip_cons, rhs)) - else: - raise Warning("method cannot be called for constraints of type " + constype) - - def chgCapacityKnapsack(self, Constraint cons, capacity): - """ - Change capacity of a knapsack constraint. - - Parameters - ---------- - cons : Constraint - knapsack constraint to change the capacity from - capacity : float or None - new capacity (set to None for +infinity) - - """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - assert constype == 'knapsack', "method cannot be called for constraints of type " + constype - - if capacity is None: - capacity = SCIPinfinity(self._scip) - - PY_SCIP_CALL(SCIPchgCapacityKnapsack(self._scip, cons.scip_cons, capacity)) - - def chgLhs(self, Constraint cons, lhs): - """ - Change left-hand side value of a constraint. - - Parameters - ---------- - cons : Constraint - constraint to change the left-hand side from - lhs : float or None - new left-hand side (set to None for -infinity) - - """ - - if lhs is None: - lhs = -SCIPinfinity(self._scip) - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if constype == 'linear': - PY_SCIP_CALL(SCIPchgLhsLinear(self._scip, cons.scip_cons, lhs)) - elif constype == 'nonlinear': - PY_SCIP_CALL(SCIPchgLhsNonlinear(self._scip, cons.scip_cons, lhs)) - else: - raise Warning("method cannot be called for constraints of type " + constype) - - def getRhs(self, Constraint cons): - """ - Retrieve right-hand side value of a constraint. - - Parameters - ---------- - cons : Constraint - constraint to get the right-hand side from - - Returns - ------- - float - - """ - cdef SCIP_Bool success - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - - if cons.isLinearType(): - rhs = SCIPconsGetRhs(self._scip, cons.scip_cons, &success) - assert(success) - return rhs - elif constype == 'nonlinear': - return SCIPgetRhsNonlinear(cons.scip_cons) - else: - raise Warning("method cannot be called for constraints of type " + constype) - - def getCapacityKnapsack(self, Constraint cons): - """ - Retrieve capacity of a knapsack constraint. - - Parameters - ---------- - cons : Constraint - knapsack constraint to get the capacity from - - Returns - ------- - float - - """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - assert constype == 'knapsack', "method cannot be called for constraints of type " + constype - - return SCIPgetCapacityKnapsack(self._scip, cons.scip_cons) - - def getLhs(self, Constraint cons): - """ - Retrieve left-hand side value of a constraint. - - Parameters - ---------- - cons : Constraint - linear or nonlinear constraint - - Returns - ------- - float - - """ - cdef SCIP_Bool success - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - - if cons.isLinearType(): - lhs = SCIPconsGetLhs(self._scip, cons.scip_cons, &success) - assert(success) - return lhs - elif constype == 'nonlinear': - return SCIPgetLhsNonlinear(cons.scip_cons) - else: - raise Warning("method cannot be called for constraints of type " + constype) - - def chgCoefLinear(self, Constraint cons, Variable var, value): - """ - Changes coefficient of variable in linear constraint; - deletes the variable if coefficient is zero; adds variable if not yet contained in the constraint - This method may only be called during problem creation stage for an original constraint and variable. - This method requires linear time to search for occurences of the variable in the constraint data. - - Parameters - ---------- - cons : Constraint - linear constraint - var : Variable - variable of constraint entry - value : float - new coefficient of constraint entry - - """ - PY_SCIP_CALL( SCIPchgCoefLinear(self._scip, cons.scip_cons, var.scip_var, value) ) - - def delCoefLinear(self, Constraint cons, Variable var): - """ - Deletes variable from linear constraint - This method may only be called during problem creation stage for an original constraint and variable. - This method requires linear time to search for occurrences of the variable in the constraint data. - - Parameters - ---------- - cons : Constraint - linear constraint - var : Variable - variable of constraint entry - - """ - - PY_SCIP_CALL( SCIPdelCoefLinear(self._scip, cons.scip_cons, var.scip_var) ) - - def addCoefLinear(self, Constraint cons, Variable var, value): - """ - Adds coefficient to linear constraint (if it is not zero) - - Parameters - ---------- - cons : Constraint - linear constraint - var : Variable - variable of constraint entry - value : float - coefficient of constraint entry - - """ - - PY_SCIP_CALL( SCIPaddCoefLinear(self._scip, cons.scip_cons, var.scip_var, value) ) - - def addCoefKnapsack(self, Constraint cons, Variable var, weight): - """ - Adds coefficient to knapsack constraint (if it is not zero) - - Parameters - ---------- - cons : Constraint - knapsack constraint - var : Variable - variable of constraint entry - weight : float - coefficient of constraint entry - - """ - - PY_SCIP_CALL( SCIPaddCoefKnapsack(self._scip, cons.scip_cons, var.scip_var, weight) ) - - def getActivity(self, Constraint cons, Solution sol = None): - """ - Retrieve activity of given constraint. - Can only be called after solving is completed. - - Parameters - ---------- - cons : Constraint - linear constraint - sol : Solution or None, optional - solution to compute activity of, None to use current node's solution (Default value = None) - - Returns - ------- - float - - """ - cdef SCIP_Real activity - cdef SCIP_SOL* scip_sol - - if not self.getStage() >= SCIP_STAGE_SOLVING: - raise Warning("method cannot be called before problem is solved") - - if isinstance(sol, Solution): - scip_sol = sol.sol - else: - scip_sol = NULL - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if constype == 'linear': - activity = SCIPgetActivityLinear(self._scip, cons.scip_cons, scip_sol) + if not isinstance(modifiable, np.ndarray): + matrix_modifiable = np.full(shape, modifiable, dtype=bool) else: - raise Warning("method cannot be called for constraints of type " + constype) - - return activity - - def getSlack(self, Constraint cons, Solution sol = None, side = None): - """ - Retrieve slack of given constraint. - Can only be called after solving is completed. - - Parameters - ---------- - cons : Constraint - linear constraint - sol : Solution or None, optional - solution to compute slack of, None to use current node's solution (Default value = None) - side : str or None, optional - whether to use 'lhs' or 'rhs' for ranged constraints, None to return minimum (Default value = None) - - Returns - ------- - float - - """ - cdef SCIP_Real activity - cdef SCIP_SOL* scip_sol - - - if not self.getStage() >= SCIP_STAGE_SOLVING: - raise Warning("method cannot be called before problem is solved") + matrix_modifiable = modifiable - if isinstance(sol, Solution): - scip_sol = sol.sol + if not isinstance(dynamic, np.ndarray): + matrix_dynamic = np.full(shape, dynamic, dtype=bool) else: - scip_sol = NULL + matrix_dynamic = dynamic - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if constype == 'linear': - lhs = SCIPgetLhsLinear(self._scip, cons.scip_cons) - rhs = SCIPgetRhsLinear(self._scip, cons.scip_cons) - activity = SCIPgetActivityLinear(self._scip, cons.scip_cons, scip_sol) + if not isinstance(removable, np.ndarray): + matrix_removable = np.full(shape, removable, dtype=bool) else: - raise Warning("method cannot be called for constraints of type " + constype) - - lhsslack = activity - lhs - rhsslack = rhs - activity + matrix_removable = removable - if side == 'lhs': - return lhsslack - elif side == 'rhs': - return rhsslack + if not isinstance(stickingatnode, np.ndarray): + matrix_stickingatnode = np.full(shape, stickingatnode, dtype=bool) else: - return min(lhsslack, rhsslack) - - def getTransformedCons(self, Constraint cons): - """ - Retrieve transformed constraint. - - Parameters - ---------- - cons : Constraint - - Returns - ------- - Constraint - - """ - cdef SCIP_CONS* transcons - PY_SCIP_CALL(SCIPgetTransformedCons(self._scip, cons.scip_cons, &transcons)) - return self._getOrCreateCons(transcons) + matrix_stickingatnode = stickingatnode - def isNLPConstructed(self): - """ - Returns whether SCIP's internal NLP has been constructed. + for idx in np.ndindex(cons.shape): + matrix_cons[idx] = self.addCons(cons[idx], name=matrix_names[idx], initial=matrix_initial[idx], + separate=matrix_separate[idx], check=matrix_check[idx], + propagate=matrix_propagate[idx], local=matrix_local[idx], + modifiable=matrix_modifiable[idx], dynamic=matrix_dynamic[idx], + removable=matrix_removable[idx], stickingatnode=matrix_stickingatnode[idx]) - Returns - ------- - bool + return matrix_cons.view(MatrixConstraint) + def getConsNVars(self, Constraint constraint): """ - return SCIPisNLPConstructed(self._scip) + Gets number of variables in a constraint. - def getNNlRows(self): - """ - Gets current number of nonlinear rows in SCIP's internal NLP. + Parameters + ---------- + constraint : Constraint + Constraint to get the number of variables from. Returns ------- int - """ - return SCIPgetNNLPNlRows(self._scip) + Raises + ------ + TypeError + If the associated constraint handler does not have this functionality - def getNlRows(self): """ - Returns a list with the nonlinear rows in SCIP's internal NLP. + cdef int nvars + cdef SCIP_Bool success - Returns - ------- - list of NLRow + PY_SCIP_CALL(SCIPgetConsNVars(self._scip, constraint.scip_cons, &nvars, &success)) - """ - cdef SCIP_NLROW** nlrows = SCIPgetNLPNlRows(self._scip) - cdef int i + if not success: + conshdlr = SCIPconsGetHdlr(constraint.scip_cons) + conshdrlname = SCIPconshdlrGetName(conshdlr) + raise TypeError("The constraint handler %s does not have this functionality." % conshdrlname) - return [NLRow.create(nlrows[i]) for i in range(self.getNNlRows())] + return nvars - def getNlRowSolActivity(self, NLRow nlrow, Solution sol = None): + cdef SCIP_CONS* _getTransformedCons(self, Constraint cons, str expected_cons_type): """ - Gives the activity of a nonlinear row for a given primal solution. + Validates constraint type and retrieves its transformed representation. Parameters ---------- - nlrow : NLRow - sol : Solution or None, optional - a primal solution, if None, then the current LP solution is used + cons : Constraint + Constraint to get the transformed representation for. + expected_cons_type : str + Expected constraint type name (e.g. 'linear', 'logicor', 'knapsack'). Returns ------- - float + SCIP_CONS* + Pointer to the transformed SCIP constraint, or NULL if transformed constraint does not exist. + + Raises + ------ + Warning + If the constraint handler type does not match expected_cons_type. """ - cdef SCIP_Real activity - cdef SCIP_SOL* solptr + cdef SCIP_CONS* transcons + + constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') + if not constype == expected_cons_type: + raise Warning(f"dual solution values not available for constraints of type {constype}") + + if cons.isOriginal(): + PY_SCIP_CALL(SCIPgetTransformedCons(self._scip, cons.scip_cons, &transcons)) + return transcons - solptr = sol.sol if not sol is None else NULL - PY_SCIP_CALL( SCIPgetNlRowSolActivity(self._scip, nlrow.scip_nlrow, solptr, &activity) ) - return activity + return cons.scip_cons - def getNlRowSolFeasibility(self, NLRow nlrow, Solution sol = None): + def printCons(self, Constraint constraint): """ - Gives the feasibility of a nonlinear row for a given primal solution + Print the constraint Parameters ---------- - nlrow : NLRow - sol : Solution or None, optional - a primal solution, if None, then the current LP solution is used + constraint : Constraint - Returns - ------- - bool + """ + return PY_SCIP_CALL(SCIPprintCons(self._scip, constraint.scip_cons, NULL)) + def setInitial(self, Constraint cons, newInit): """ - cdef SCIP_Real feasibility - cdef SCIP_SOL* solptr + Set "initial" flag of a constraint. - solptr = sol.sol if not sol is None else NULL - PY_SCIP_CALL( SCIPgetNlRowSolFeasibility(self._scip, nlrow.scip_nlrow, solptr, &feasibility) ) - return feasibility + Parameters + ---------- + cons : Constraint + newInit : bool - def getNlRowActivityBounds(self, NLRow nlrow): """ - Gives the minimal and maximal activity of a nonlinear row w.r.t. the variable's bounds. + PY_SCIP_CALL(SCIPsetConsInitial(self._scip, cons.scip_cons, newInit)) + + def setModifiable(self, Constraint cons, newMod): + """ + Set "modifiable" flag of a constraint. Parameters ---------- - nlrow : NLRow - - Returns - ------- - tuple of float + cons : Constraint + newMod : bool """ - cdef SCIP_Real minactivity - cdef SCIP_Real maxactivity - - PY_SCIP_CALL( SCIPgetNlRowActivityBounds(self._scip, nlrow.scip_nlrow, &minactivity, &maxactivity) ) - return (minactivity, maxactivity) + PY_SCIP_CALL(SCIPsetConsModifiable(self._scip, cons.scip_cons, newMod)) - def printNlRow(self, NLRow nlrow): + def setRemovable(self, Constraint cons, newRem): """ - Prints nonlinear row. + Set "removable" flag of a constraint. Parameters ---------- - nlrow : NLRow + cons : Constraint + newRem : bool """ - PY_SCIP_CALL( SCIPprintNlRow(self._scip, nlrow.scip_nlrow, NULL) ) + PY_SCIP_CALL(SCIPsetConsRemovable(self._scip, cons.scip_cons, newRem)) - def checkQuadraticNonlinear(self, Constraint cons): + def setEnforced(self, Constraint cons, newEnf): """ - Returns if the given constraint is quadratic. + Set "enforced" flag of a constraint. Parameters ---------- cons : Constraint - - Returns - ------- - bool + newEnf : bool """ - cdef SCIP_Bool isquadratic - PY_SCIP_CALL( SCIPcheckQuadraticNonlinear(self._scip, cons.scip_cons, &isquadratic) ) - return isquadratic + PY_SCIP_CALL(SCIPsetConsEnforced(self._scip, cons.scip_cons, newEnf)) - def getTermsQuadratic(self, Constraint cons): + def setCheck(self, Constraint cons, newCheck): """ - Retrieve bilinear, quadratic, and linear terms of a quadratic constraint. + Set "check" flag of a constraint. Parameters ---------- cons : Constraint + newCheck : bool - Returns - ------- - bilinterms : list of tuple - Triples ``(var1, var2, coef)`` for terms of the form - ``coef * var1 * var2`` with ``var1 != var2``. - quadterms : list of tuple - Triples ``(var, sqrcoef, lincoef)`` for variables that appear in - quadratic or bilinear terms. ``sqrcoef`` is the coefficient of - ``var**2``, and ``lincoef`` is the linear coefficient of ``var`` - if it also appears linearly. - linterms : list of tuple - Pairs ``(var, coef)`` for purely linear variables, i.e., - variables that do not participate in any quadratic or bilinear term. - - """ - cdef SCIP_EXPR* expr - cdef int termidx - - # linear terms - cdef SCIP_EXPR** linexprs - cdef SCIP_Real* lincoefs - cdef SCIP_Real lincoef - cdef int nlinvars - - # bilinear terms - cdef SCIP_EXPR* bilinterm1 - cdef SCIP_EXPR* bilinterm2 - cdef SCIP_Real bilincoef - cdef int nbilinterms - - # quadratic terms - cdef SCIP_EXPR* quadexpr - cdef SCIP_EXPR* sqrexpr - cdef SCIP_Real sqrcoef - cdef int nquadterms - - # variables - cdef SCIP_VAR* scipvar1 - cdef SCIP_VAR* scipvar2 - - assert cons.isNonlinear(), "constraint is not nonlinear" - assert self.checkQuadraticNonlinear(cons), "constraint is not quadratic" - - expr = SCIPgetExprNonlinear(cons.scip_cons) - SCIPexprGetQuadraticData(expr, NULL, &nlinvars, &linexprs, &lincoefs, - &nquadterms, &nbilinterms, NULL, NULL) - - linterms = [] - bilinterms = [] - - # Purely linear terms (variables not in any quadratic/bilinear term) - for termidx in range(nlinvars): - var = self._getOrCreateVar(SCIPgetVarExprVar(linexprs[termidx])) - linterms.append((var, lincoefs[termidx])) - - # Collect quadratic terms in a dict so we can merge entries for the same variable. - quaddict = {} # var.ptr() -> [var, sqrcoef, lincoef] - - for termidx in range(nbilinterms): - SCIPexprGetQuadraticBilinTerm(expr, termidx, &bilinterm1, &bilinterm2, &bilincoef, NULL, NULL) - scipvar1 = SCIPgetVarExprVar(bilinterm1) - scipvar2 = SCIPgetVarExprVar(bilinterm2) - var1 = self._getOrCreateVar(scipvar1) - var2 = self._getOrCreateVar(scipvar2) - if scipvar1 != scipvar2: - bilinterms.append((var1, var2, bilincoef)) - else: - # Squared term reported as bilinear var*var - key = var1.ptr() - if key in quaddict: - quaddict[key][1] += bilincoef - else: # TODO: SCIP handles expr like x**2 appropriately, but PySCIPOpt requires this. Need to investigate why. - quaddict[key] = [var1, bilincoef, 0.0] - - # Also collect linear coefficients from the quadratic terms - for termidx in range(nquadterms): - SCIPexprGetQuadraticQuadTerm(expr, termidx, &quadexpr, &lincoef, &sqrcoef, NULL, NULL, &sqrexpr) - scipvar1 = SCIPgetVarExprVar(quadexpr) - var = self._getOrCreateVar(scipvar1) - key = var.ptr() - if key in quaddict: - quaddict[key][1] += sqrcoef - quaddict[key][2] += lincoef - else: - quaddict[key] = [var, sqrcoef, lincoef] - - quadterms = [tuple(entry) for entry in quaddict.values()] - - return (bilinterms, quadterms, linterms) + """ + PY_SCIP_CALL(SCIPsetConsChecked(self._scip, cons.scip_cons, newCheck)) - def setRelaxSolVal(self, Variable var, val): + def getTransformedCons(self, Constraint cons): """ - Sets the value of the given variable in the global relaxation solution. + Retrieve transformed constraint. Parameters ---------- - var : Variable - val : float + cons : Constraint + + Returns + ------- + Constraint """ - PY_SCIP_CALL(SCIPsetRelaxSolVal(self._scip, NULL, var.scip_var, val)) + cdef SCIP_CONS* transcons + PY_SCIP_CALL(SCIPgetTransformedCons(self._scip, cons.scip_cons, &transcons)) + return self._getOrCreateCons(transcons) def enableDebugSol(self): """ @@ -9123,245 +4353,8 @@ cdef class Model: constraint to be deleted """ - PY_SCIP_CALL(SCIPdelConsLocal(self._scip, cons.scip_cons)) - - def getValsLinear(self, Constraint cons): - """ - Retrieve the coefficients of a linear constraint - - Parameters - ---------- - cons : Constraint - linear constraint to get the coefficients of - - Returns - ------- - dict of str to float - - """ - cdef SCIP_VAR** vars - cdef SCIP_Real* vals - cdef int i - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if not constype == 'linear': - raise Warning("coefficients not available for constraints of type ", constype) - - vals = SCIPgetValsLinear(self._scip, cons.scip_cons) - vars = SCIPgetVarsLinear(self._scip, cons.scip_cons) - - valsdict = {} - for i in range(SCIPgetNVarsLinear(self._scip, cons.scip_cons)): - valsdict[bytes(SCIPvarGetName(vars[i])).decode('utf-8')] = vals[i] - - return valsdict - - def getWeightsKnapsack(self, Constraint cons): - """ - Retrieve the coefficients of a knapsack constraint - - Parameters - ---------- - cons : Constraint - knapsack constraint to get the coefficients of - - Returns - ------- - dict of str to float - - """ - cdef SCIP_VAR** vars - cdef SCIP_Longint* vals - cdef int nvars - cdef int i - - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if not constype == 'knapsack': - raise Warning("weights not available for constraints of type ", constype) - - nvars = SCIPgetNVarsKnapsack(self._scip, cons.scip_cons) - vals = SCIPgetWeightsKnapsack(self._scip, cons.scip_cons) - vars = SCIPgetVarsKnapsack(self._scip, cons.scip_cons) - - valsdict = {} - for i in range(nvars): - var_name = bytes(SCIPvarGetName(vars[i])).decode('utf-8') - valsdict[var_name] = vals[i] - - return valsdict - - def getRowLinear(self, Constraint cons): - """ - Retrieve the linear relaxation of the given linear constraint as a row. - May return NULL if no LP row was yet created; the user must not modify the row! - - Parameters - ---------- - cons : Constraint - linear constraint to get the coefficients of - - Returns - ------- - Row - - """ - constype = bytes(SCIPconshdlrGetName(SCIPconsGetHdlr(cons.scip_cons))).decode('UTF-8') - if not constype == 'linear': - raise Warning("coefficients not available for constraints of type ", constype) - - cdef SCIP_ROW* row = SCIPgetRowLinear(self._scip, cons.scip_cons) - return Row.create(row) - - def getDualsolLinear(self, Constraint cons): - """ - Retrieve the dual solution to a linear constraint. - - Parameters - ---------- - cons : Constraint - linear constraint - - Returns - ------- - float - Zero if presolve removed the transformed constraint. - - """ - cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "linear") - if transcons == NULL: - return 0.0 - - return SCIPgetDualsolLinear(self._scip, transcons) - - def getDualsolKnapsack(self, Constraint cons): - """ - Retrieve the dual solution to a knapsack constraint. - - Parameters - ---------- - cons : Constraint - knapsack constraint - - Returns - ------- - float - - """ - cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "knapsack") - if transcons == NULL: - return 0.0 - - return SCIPgetDualsolKnapsack(self._scip, transcons) - - def getDualMultiplier(self, Constraint cons): - """ - DEPRECATED: Retrieve the dual solution to a linear constraint. - - Parameters - ---------- - cons : Constraint - linear constraint - - Returns - ------- - float - - """ - raise Warning("model.getDualMultiplier(cons) is deprecated: please use model.getDualsolLinear(cons)") - - def getDualfarkasLinear(self, Constraint cons): - """ - Retrieve the dual farkas value to a linear constraint. - - Parameters - ---------- - cons : Constraint - linear constraint - - Returns - ------- - float - Zero if presolve removed the transformed constraint. - - """ - # TODO this should ideally be handled on the SCIP side - cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "linear") - if transcons == NULL: - return 0.0 - - return SCIPgetDualfarkasLinear(self._scip, transcons) - - def getDualfarkasKnapsack(self, Constraint cons): - """ - Retrieve the dual farkas value to a knapsack constraint. - - Parameters - ---------- - cons : Constraint - knapsack constraint - - Returns - ------- - float - - """ - # TODO this should ideally be handled on the SCIP side - cdef SCIP_CONS* transcons = self._getTransformedCons(cons, "knapsack") - if transcons == NULL: - return 0.0 - - return SCIPgetDualfarkasKnapsack(self._scip, transcons) - - def getVarRedcost(self, Variable var): - """ - Retrieve the reduced cost of a variable. - - Parameters - ---------- - var : Variable - variable to get the reduced cost of - - Returns - ------- - float - - """ - redcost = None - try: - redcost = SCIPgetVarRedcost(self._scip, var.scip_var) - if self.getObjectiveSense() == "maximize": - redcost = -redcost - except: - raise Warning("no reduced cost available for variable " + var.name) - return redcost - - def getDualSolVal(self, Constraint cons, boundconstraint=False): - """ - Returns dual solution value of a constraint. - - Parameters - ---------- - cons : Constraint - constraint to get the dual solution value of - boundconstraint : bool, optional - Decides whether to store a bool if the constraint is a bound constraint - (default = False) - - Returns - ------- - float - - """ - cdef SCIP_Real _dualsol - cdef SCIP_Bool _bounded - - if boundconstraint: - SCIPgetDualSolVal(self._scip, cons.scip_cons, &_dualsol, &_bounded) - else: - SCIPgetDualSolVal(self._scip, cons.scip_cons, &_dualsol, NULL) - - return _dualsol - + PY_SCIP_CALL(SCIPdelConsLocal(self._scip, cons.scip_cons)) + def optimize(self): """Optimize the problem.""" PY_SCIP_CALL(SCIPsolve(self._scip)) @@ -9426,9 +4419,9 @@ cdef class Model: # if subproblems is a dictionary, then the dictionary is turned into a c array if isdict: for i, subprob in enumerate(subproblems.values()): - subprobs[i] = (subprob)._scip + subprobs[i] = (subprob)._scip else: - subprobs[0] = (subproblems)._scip + subprobs[0] = (subproblems)._scip # creating the default Benders' decomposition PY_SCIP_CALL(SCIPcreateBendersDefault(self._scip, subprobs, nsubproblems)) @@ -9444,10 +4437,10 @@ cdef class Model: if isdict: self._benders_subproblems = list(subproblems.values()) for subprob in self._benders_subproblems: - (subprob)._freescip = False + (subprob)._freescip = False else: self._benders_subproblems = [subproblems] - (subproblems)._freescip = False + (subproblems)._freescip = False # activating the Benders' decomposition constraint handlers self.setBoolParam("constraints/benderslp/active", True) @@ -9561,7 +4554,7 @@ cdef class Model: the subproblem to add to the decomposition """ - PY_SCIP_CALL(SCIPaddBendersSubproblem(self._scip, benders._benders, (subproblem)._scip)) + PY_SCIP_CALL(SCIPaddBendersSubproblem(self._scip, benders._benders, (subproblem)._scip)) def setBendersSubproblemIsConvex(self, Benders benders, probnumber, isconvex = True): """ @@ -9671,7 +4664,7 @@ cdef class Model: scip_subprob = SCIPbendersSubproblem(scip_benders, probnumber) - return Model.create(scip_subprob) + return BaseModel.create(scip_subprob) def getBendersVar(self, Variable var, Benders benders = None, probnumber = -1): """ @@ -9905,53 +4898,7 @@ cdef class Model: cdef SCIP_PRICER* scip_pricer PY_SCIP_CALL(SCIPdeactivatePricer(self._scip, pricer.scip_pricer)) - def copyLargeNeighborhoodSearch(self, to_fix, fix_vals) -> Model: - """ - Creates a configured copy of the transformed problem and applies provided fixings intended for LNS heuristics. - - Parameters - ---------- - to_fix : List[Variable] - A list of variables to fix in the copy - fix_vals : List[Real] - A list of the values to which to fix the variables in the copy (care their order) - - Returns - ------- - model : Model - A model containing the created copy - """ - cdef SCIP* subscip - cdef SCIP_HASHMAP* varmap - cdef SCIP_VAR** orig_vars = SCIPgetVars(self._scip) - cdef SCIP_VAR** vars = malloc(len(to_fix) * sizeof(SCIP_VAR*)) - cdef SCIP_Real* vals = malloc(len(fix_vals) * sizeof(SCIP_Real)) - cdef SCIP_Real val - cdef SCIP_Bool valid - cdef SCIP_Bool success - cdef int i - cdef int j = 0 - - name_to_val = {var.name: val for var, val in zip(to_fix, fix_vals)} - for i, var in enumerate(self.getVars()): - if var.name in name_to_val: - vars[j] = orig_vars[i] - vals[j] = name_to_val[var.name] - j+= 1 - - PY_SCIP_CALL(SCIPcreate(&subscip)) - PY_SCIP_CALL( SCIPhashmapCreate(&varmap, SCIPblkmem(subscip), self.getNVars()) ) - PY_SCIP_CALL( SCIPcopyLargeNeighborhoodSearch(self._scip, subscip, varmap, "LNhS_subscip", vars, vals, - len(to_fix), False, False, &success, &valid) ) - sub_model = Model.create(subscip) - sub_model._freescip = True - free(vars) - free(vals) - SCIPhashmapFree(&varmap) - - return sub_model - - def translateSubSol(self, Model sub_model, Solution sol, heur) -> Solution: + def translateSubSol(self, BaseModel sub_model, Solution sol, heur) -> Solution: """ Translates a solution of a model copy into a solution of the main model @@ -9986,52 +4933,6 @@ cdef class Model: return solution - def createCons(self, Conshdlr conshdlr, name, initial=True, separate=True, enforce=True, check=True, propagate=True, - local=False, modifiable=False, dynamic=False, removable=False, stickingatnode=False): - """ - Create a constraint of a custom constraint handler. - - Parameters - ---------- - conshdlr : Conshdlr - constraint handler - name : str - name of constraint handler - initial : bool, optional - (Default value = True) - separate : bool, optional - (Default value = True) - enforce : bool, optional - (Default value = True) - check : bool, optional - (Default value = True) - propagate : bool, optional - (Default value = True) - local : bool, optional - (Default value = False) - modifiable : bool, optional - (Default value = False) - dynamic : bool, optional - (Default value = False) - removable : bool, optional - (Default value = False) - stickingatnode : bool, optional - (Default value = False) - - Returns - ------- - Constraint - - """ - - n = str_conversion(name) - cdef SCIP_CONSHDLR* scip_conshdlr - scip_conshdlr = SCIPfindConshdlr(self._scip, str_conversion(conshdlr.name)) - constraint = Constraint() - PY_SCIP_CALL(SCIPcreateCons(self._scip, &(constraint.scip_cons), n, scip_conshdlr, constraint, - initial, separate, enforce, check, propagate, local, modifiable, dynamic, removable, stickingatnode)) - return constraint - def includePresol(self, Presol presol, name, desc, priority, maxrounds, timing=SCIP_PRESOLTIMING_FAST): """ Include a presolver. @@ -10169,6 +5070,60 @@ cdef class Model: prop.model = self self._plugins.append(prop) + def includeSymhdlr(self, Symhdlr symhdlr, name, desc, priority=0, proppriority=0, sepapriority=0, + presolpriority=0, propfreq=-1, sepafreq=-1, delayprop=False, delaysepa=False, + maxbounddist=1.0, maxprerounds=-1, proptiming=SCIP_PROPTIMING_BEFORELP, + presoltiming=SCIP_PRESOLTIMING_FAST): + """ + Include a symmetry handler. + + Parameters + ---------- + symhdlr : Symhdlr + symmetry handler + name : str + name of symmetry handler + desc : str + description of symmetry handler + priority : int, optional + priority for trying to add the handler to symmetry components (Default value = 0) + proppriority : int, optional + priority for propagation (Default value = 0) + sepapriority : int, optional + priority for separation (Default value = 0) + presolpriority : int, optional + priority for presolving (Default value = 0) + propfreq : int, optional + frequency for calling propagation, -1 to disable (Default value = -1) + sepafreq : int, optional + frequency for calling separation, -1 to disable (Default value = -1) + delayprop : bool, optional + should propagation be delayed if other propagators found reductions? (Default value = False) + delaysepa : bool, optional + should separation be delayed if other separators found cuts? (Default value = False) + maxbounddist : float, optional + maximal relative distance from current node's dual bound to primal bound for applying separation (Default value = 1.0) + maxprerounds : int, optional + maximal number of presolving rounds, -1 for no limit (Default value = -1) + proptiming : PY_SCIP_PROPTIMING, optional + timing mask of propagation (Default value = SCIP_PROPTIMING_BEFORELP) + presoltiming : PY_SCIP_PRESOLTIMING, optional + timing mask of presolving (Default value = SCIP_PRESOLTIMING_FAST) + + """ + n = str_conversion(name) + d = str_conversion(desc) + symhdlr._symcompdata = [] + PY_SCIP_CALL(SCIPincludeSymhdlr(self._scip, n, d, priority, proppriority, sepapriority, presolpriority, + propfreq, sepafreq, delayprop, delaysepa, maxbounddist, maxprerounds, + proptiming, presoltiming, PySymhdlrTryAdd, NULL, PySymhdlrFree, + PySymhdlrInit, PySymhdlrExit, PySymhdlrInitsol, PySymhdlrExitsol, + PySymhdlrSepaLP, PySymhdlrSepaSol, PySymhdlrProp, PySymhdlrResProp, + PySymhdlrPresol, symhdlr)) + symhdlr.model = self + symhdlr.name = name + self._plugins.append(symhdlr) + def includeHeur(self, Heur heur, name, desc, dispchar, priority=10000, freq=1, freqofs=0, maxdepth=-1, timingmask=SCIP_HEURTIMING_BEFORENODE, usessubscip=False): """ @@ -10240,7 +5195,7 @@ cdef class Model: iisfinder.iis = IIS() - PY_SCIP_CALL(SCIPincludeIISfinder(self._scip, nam, des, priority, PyiisfinderCopy, PyiisfinderFree, + PY_SCIP_CALL(SCIPincludeIISfinder(self._scip, nam, des, priority, True, PyiisfinderCopy, PyiisfinderFree, PyiisfinderExec, iisfinder)) scip_iisfinder = SCIPfindIISfinder(self._scip, nam) @@ -10475,45 +5430,6 @@ cdef class Model: benderscut.name = name self._plugins.append(benderscut) - def getLPBranchCands(self): - """ - Gets branching candidates for LP solution branching (fractional variables) along with solution values, - fractionalities, and number of branching candidates; The number of branching candidates does NOT account - for fractional implicit integer variables which should not be used for branching decisions. Fractional - implicit integer variables are stored at the positions nlpcands to nlpcands + nfracimplvars - 1 - branching rules should always select the branching candidate among the first npriolpcands of the candidate list - - Returns - ------- - list of Variable - list of variables of LP branching candidates - list of float - list of LP candidate solution values - list of float - list of LP candidate fractionalities - int - number of LP branching candidates - int - number of candidates with maximal priority - int - number of fractional implicit integer variables - - """ - cdef SCIP_VAR** lpcands - cdef SCIP_Real* lpcandssol - cdef SCIP_Real* lpcandsfrac - cdef int ncands - cdef int nlpcands - cdef int npriolpcands - cdef int nfracimplvars - cdef int i - - PY_SCIP_CALL(SCIPgetLPBranchCands(self._scip, &lpcands, &lpcandssol, &lpcandsfrac, - &nlpcands, &npriolpcands, &nfracimplvars)) - - return ([self._getOrCreateVar(lpcands[i]) for i in range(nlpcands)], [lpcandssol[i] for i in range(nlpcands)], - [lpcandsfrac[i] for i in range(nlpcands)], nlpcands, npriolpcands, nfracimplvars) - def getNLPBranchCands(self): """ Gets number of branching candidates for LP solution branching (number of fractional variables) @@ -10577,80 +5493,6 @@ cdef class Model: PY_SCIP_CALL(SCIPbranchVar(self._scip, wrapper.ptr[0], &downchild, &eqchild, &upchild)) return Node.create(downchild), Node.create(eqchild), Node.create(upchild) - def branchVarVal(self, Variable variable, value): - """ - Branches on variable using a value which separates the domain of the variable. - - Parameters - ---------- - variable : Variable - Variable to branch on - value : float - value to branch on - - Returns - ------- - Node - Node created for the down (left) branch - Node or None - Node created for the equal child (middle child). Only exists if the branch variable is integer - Node - Node created for the up (right) branch - - """ - cdef SCIP_NODE* downchild - cdef SCIP_NODE* eqchild - cdef SCIP_NODE* upchild - cdef _VarArray wrapper = _VarArray(variable) - - PY_SCIP_CALL(SCIPbranchVarVal(self._scip, wrapper.ptr[0], value, &downchild, &eqchild, &upchild)) - - return Node.create(downchild), Node.create(eqchild), Node.create(upchild) - - def calcNodeselPriority(self, Variable variable, branchdir, targetvalue): - """ - Calculates the node selection priority for moving the given variable's LP value - to the given target value; - this node selection priority can be given to the SCIPcreateChild() call. - - Parameters - ---------- - variable : Variable - variable on which the branching is applied - branchdir : PY_SCIP_BRANCHDIR - type of branching that was performed - targetvalue : float - new value of the variable in the child node - - Returns - ------- - float - node selection priority for moving the given variable's LP value to the given target value - - """ - return SCIPcalcNodeselPriority(self._scip, variable.scip_var, branchdir, targetvalue) - - def calcChildEstimate(self, Variable variable, targetvalue): - """ - Calculates an estimate for the objective of the best feasible solution - contained in the subtree after applying the given branching; - this estimate can be given to the SCIPcreateChild() call. - - Parameters - ---------- - variable : Variable - Variable to compute the estimate for - targetvalue : float - new value of the variable in the child node - - Returns - ------- - float - objective estimate of the best solution in the subtree after applying the given branching - - """ - return SCIPcalcChildEstimate(self._scip, variable.scip_var, targetvalue) - def createChild(self, nodeselprio, estimate): """ Create a child node of the focus node. @@ -10672,144 +5514,6 @@ cdef class Model: PY_SCIP_CALL(SCIPcreateChild(self._scip, &child, nodeselprio, estimate)) return Node.create(child) - # Diving methods (Diving is LP related) - def startDive(self): - """Initiates LP diving. - It allows the user to change the LP in several ways, solve, change again, etc, - without affecting the actual LP. When endDive() is called, - SCIP will undo all changes done and recover the LP it had before startDive.""" - PY_SCIP_CALL(SCIPstartDive(self._scip)) - - def endDive(self): - """Quits probing and resets bounds and constraints to the focus node's environment.""" - PY_SCIP_CALL(SCIPendDive(self._scip)) - - def chgVarObjDive(self, Variable var, newobj): - """ - Changes (column) variable's objective value in current dive. - - Parameters - ---------- - var : Variable - newobj : float - - """ - PY_SCIP_CALL(SCIPchgVarObjDive(self._scip, var.scip_var, newobj)) - - def chgVarLbDive(self, Variable var, newbound): - """ - Changes variable's current lb in current dive. - - Parameters - ---------- - var : Variable - newbound : float - - """ - PY_SCIP_CALL(SCIPchgVarLbDive(self._scip, var.scip_var, newbound)) - - def chgVarUbDive(self, Variable var, newbound): - """ - Changes variable's current ub in current dive. - - Parameters - ---------- - var : Variable - newbound : float - - """ - PY_SCIP_CALL(SCIPchgVarUbDive(self._scip, var.scip_var, newbound)) - - def getVarLbDive(self, Variable var): - """ - Returns variable's current lb in current dive. - - Parameters - ---------- - var : Variable - - Returns - ------- - float - - """ - return SCIPgetVarLbDive(self._scip, var.scip_var) - - def getVarUbDive(self, Variable var): - """ - Returns variable's current ub in current dive. - - Parameters - ---------- - var : Variable - - Returns - ------- - float - - """ - return SCIPgetVarUbDive(self._scip, var.scip_var) - - def chgRowLhsDive(self, Row row, newlhs): - """ - Changes row lhs in current dive, change will be undone after diving - ends, for permanent changes use SCIPchgRowLhs(). - - Parameters - ---------- - row : Row - newlhs : float - - """ - PY_SCIP_CALL(SCIPchgRowLhsDive(self._scip, row.scip_row, newlhs)) - - def chgRowRhsDive(self, Row row, newrhs): - """ - Changes row rhs in current dive, change will be undone after diving - ends. For permanent changes use SCIPchgRowRhs(). - - Parameters - ---------- - row : Row - newrhs : float - - """ - PY_SCIP_CALL(SCIPchgRowRhsDive(self._scip, row.scip_row, newrhs)) - - def addRowDive(self, Row row): - """ - Adds a row to the LP in current dive. - - Parameters - ---------- - row : Row - - """ - PY_SCIP_CALL(SCIPaddRowDive(self._scip, row.scip_row)) - - def solveDiveLP(self, itlim = -1): - """ - Solves the LP of the current dive. No separation or pricing is applied. - - Parameters - ---------- - itlim : int, optional - maximal number of LP iterations to perform (Default value = -1, that is, no limit) - - Returns - ------- - lperror : bool - whether an unresolved lp error occured - cutoff : bool - whether the LP was infeasible or the objective limit was reached - - """ - cdef SCIP_Bool lperror - cdef SCIP_Bool cutoff - - PY_SCIP_CALL(SCIPsolveDiveLP(self._scip, itlim, &lperror, &cutoff)) - return lperror, cutoff - def inRepropagation(self): """ Returns if the current node is already solved and only propagated again. @@ -10822,85 +5526,37 @@ cdef class Model: return SCIPinRepropagation(self._scip) # Probing methods (Probing is tree based) - def startProbing(self): - """Initiates probing, making methods SCIPnewProbingNode(), SCIPbacktrackProbing(), SCIPchgVarLbProbing(), - SCIPchgVarUbProbing(), SCIPfixVarProbing(), SCIPpropagateProbing(), SCIPsolveProbingLP(), etc available. - """ - PY_SCIP_CALL( SCIPstartProbing(self._scip) ) - - def endProbing(self): - """Quits probing and resets bounds and constraints to the focus node's environment.""" - PY_SCIP_CALL( SCIPendProbing(self._scip) ) - - def newProbingNode(self): - """Creates a new probing sub node, whose changes can be undone by backtracking to a higher node in the - probing path with a call to backtrackProbing(). - """ - PY_SCIP_CALL( SCIPnewProbingNode(self._scip) ) - - def backtrackProbing(self, probingdepth): - """ - Undoes all changes to the problem applied in probing up to the given probing depth. - - Parameters - ---------- - probingdepth : int - probing depth of the node in the probing path that should be reactivated - - """ - PY_SCIP_CALL( SCIPbacktrackProbing(self._scip, probingdepth) ) - - def getProbingDepth(self): - """Returns the current probing depth.""" - return SCIPgetProbingDepth(self._scip) - - def chgVarObjProbing(self, Variable var, newobj): - """Changes (column) variable's objective value during probing mode.""" - PY_SCIP_CALL( SCIPchgVarObjProbing(self._scip, var.scip_var, newobj) ) - - def chgVarLbProbing(self, Variable var, lb): - """ - Changes the variable lower bound during probing mode. - - Parameters - ---------- - var : Variable - variable to change bound of - lb : float or None - new lower bound (set to None for -infinity) - - """ - if lb is None: - lb = -SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarLbProbing(self._scip, var.scip_var, lb)) - - def chgVarUbProbing(self, Variable var, ub): + def startProbing(self): + """Initiates probing, making methods SCIPnewProbingNode(), SCIPbacktrackProbing(), SCIPchgVarLbProbing(), + SCIPchgVarUbProbing(), SCIPfixVarProbing(), SCIPpropagateProbing(), SCIPsolveProbingLP(), etc available. """ - Changes the variable upper bound during probing mode. + PY_SCIP_CALL( SCIPstartProbing(self._scip) ) - Parameters - ---------- - var : Variable - variable to change bound of - ub : float or None - new upper bound (set to None for +infinity) + def endProbing(self): + """Quits probing and resets bounds and constraints to the focus node's environment.""" + PY_SCIP_CALL( SCIPendProbing(self._scip) ) + def newProbingNode(self): + """Creates a new probing sub node, whose changes can be undone by backtracking to a higher node in the + probing path with a call to backtrackProbing(). """ - if ub is None: - ub = SCIPinfinity(self._scip) - PY_SCIP_CALL(SCIPchgVarUbProbing(self._scip, var.scip_var, ub)) + PY_SCIP_CALL( SCIPnewProbingNode(self._scip) ) - def fixVarProbing(self, Variable var, fixedval): + def backtrackProbing(self, probingdepth): """ - Fixes a variable at the current probing node. + Undoes all changes to the problem applied in probing up to the given probing depth. Parameters ---------- - var : Variable - fixedval : float + probingdepth : int + probing depth of the node in the probing path that should be reactivated """ - PY_SCIP_CALL( SCIPfixVarProbing(self._scip, var.scip_var, fixedval) ) + PY_SCIP_CALL( SCIPbacktrackProbing(self._scip, probingdepth) ) + + def getProbingDepth(self): + """Returns the current probing depth.""" + return SCIPgetProbingDepth(self._scip) def isObjChangedProbing(self): """ @@ -11032,385 +5688,25 @@ cdef class Model: # Solution functions - def writeLP(self, filename="LP.lp"): - """ - Writes current LP to a file. - - Parameters - ---------- - filename : str, optional - file name (Default value = "LP.lp") - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - absfile = str_conversion(abspath(filename)) - PY_SCIP_CALL( SCIPwriteLP(self._scip, absfile) ) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeMIP(self, filename, genericnames=False, origobj=False, lazyconss=False): - """ - Writes MIP relaxation of the current branch-and-bound node to a file - - Parameters - ---------- - filename : str - name of the output file - genericnames : bool, optional - should generic names like x_i and row_j be used in order to avoid troubles with reserved symbols? (Default value = False) - origobj : bool, optional - should the original objective function be used (Default value = False) - lazyconss : bool, optional - output removable rows as lazy constraints? (Default value = False) - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - absfile = str_conversion(abspath(filename)) - PY_SCIP_CALL(SCIPwriteMIP(self._scip, absfile, genericnames, origobj, lazyconss)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - cdef SCIP_HEUR* _getHeur(self, object heur): """ - Retrieves the SCIP_HEUR pointer corresponding to a heuristic object. - - Parameters - ---------- - heur : Heur or None - The heuristic object to resolve. - - Returns - ------- - SCIP_HEUR* - Pointer to the SCIP heuristic, or NULL if heur is not a Heur instance or not found. - - """ - if isinstance(heur, Heur): - n = str_conversion(heur.name) - return SCIPfindHeur(self._scip, n) - return NULL - - def createSol(self, Heur heur = None, initlp=False): - """ - Create a new primal solution in the transformed space. - - Parameters - ---------- - heur : Heur or None, optional - heuristic that found the solution (Default value = None) - initlp : bool, optional - Should the created solution be initialised to the current LP solution instead of all zeros - - Returns - ------- - Solution - - """ - cdef SCIP_SOL* _sol - cdef SCIP_HEUR* _heur = self._getHeur(heur) - - if not initlp: - PY_SCIP_CALL(SCIPcreateSol(self._scip, &_sol, _heur)) - else: - PY_SCIP_CALL(SCIPcreateLPSol(self._scip, &_sol, _heur)) - solution = Solution.create(self._scip, _sol) - return solution - - def createPartialSol(self, Heur heur = None): - """ - Create a partial primal solution, initialized to unknown values. - - Parameters - ---------- - heur : Heur or None, optional - heuristic that found the solution (Default value = None) - - Returns - ------- - Solution - - """ - cdef SCIP_SOL* _sol - cdef SCIP_HEUR* _heur = self._getHeur(heur) - - PY_SCIP_CALL(SCIPcreatePartialSol(self._scip, &_sol, _heur)) - partialsolution = Solution.create(self._scip, _sol) - return partialsolution - - def createOrigSol(self, Heur heur = None): - """ - Create a new primal solution in the original space. - - Parameters - ---------- - heur : Heur or None, optional - heuristic that found the solution (Default value = None) - - Returns - ------- - Solution - - """ - cdef SCIP_HEUR* _heur - cdef SCIP_SOL* _sol - - _heur = self._getHeur(heur) - - PY_SCIP_CALL(SCIPcreateOrigSol(self._scip, &_sol, _heur)) - solution = Solution.create(self._scip, _sol) - return solution - - def printBestSol(self, write_zeros=False): - """ - Prints the best feasible primal solution. - - Parameters - ---------- - write_zeros : bool, optional - include variables that are set to zero (Default = False) - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - PY_SCIP_CALL(SCIPprintBestSol(self._scip, NULL, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def printSol(self, Solution solution=None, write_zeros=False): - """ - Print the given primal solution. - - Parameters - ---------- - solution : Solution or None, optional - solution to print (default = None) - write_zeros : bool, optional - include variables that are set to zero (Default=False) - - """ - - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - if solution is None: - PY_SCIP_CALL(SCIPprintSol(self._scip, NULL, NULL, write_zeros)) - else: - PY_SCIP_CALL(SCIPprintSol(self._scip, solution.sol, NULL, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeBestSol(self, filename="origprob.sol", write_zeros=False): - """ - Write the best feasible primal solution to a file. - - Parameters - ---------- - filename : str, optional - name of the output file (Default="origprob.sol") - write_zeros : bool, optional - include variables that are set to zero (Default=False) - - """ - - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - # use this doubled opening pattern to ensure that IOErrors are - # triggered early and in Python not in C,Cython or SCIP. - with open(filename, "w") as f: - cfile = fdopen(f.fileno(), "w") - PY_SCIP_CALL(SCIPprintBestSol(self._scip, cfile, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeBestTransSol(self, filename="transprob.sol", write_zeros=False): - """ - Write the best feasible primal solution for the transformed problem to a file. - - Parameters - ---------- - filename : str, optional - name of the output file (Default="transprob.sol") - write_zeros : bool, optional - include variables that are set to zero (Default=False) - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - # use this double opening pattern to ensure that IOErrors are - # triggered early and in python not in C, Cython or SCIP. - with open(filename, "w") as f: - cfile = fdopen(f.fileno(), "w") - PY_SCIP_CALL(SCIPprintBestTransSol(self._scip, cfile, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeSol(self, Solution solution, filename="origprob.sol", write_zeros=False): - """ - Write the given primal solution to a file. - - Parameters - ---------- - solution : Solution - solution to write - filename : str, optional - name of the output file (Default="origprob.sol") - write_zeros : bool, optional - include variables that are set to zero (Default=False) - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - # use this doubled opening pattern to ensure that IOErrors are - # triggered early and in Python not in C,Cython or SCIP. - with open(filename, "w") as f: - cfile = fdopen(f.fileno(), "w") - PY_SCIP_CALL(SCIPprintSol(self._scip, solution.sol, cfile, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - def writeTransSol(self, Solution solution, filename="transprob.sol", write_zeros=False): - """ - Write the given transformed primal solution to a file. - - Parameters - ---------- - solution : Solution - transformed solution to write - filename : str, optional - name of the output file (Default="transprob.sol") - write_zeros : bool, optional - include variables that are set to zero (Default=False) - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - # use this doubled opening pattern to ensure that IOErrors are - # triggered early and in Python not in C,Cython or SCIP. - with open(filename, "w") as f: - cfile = fdopen(f.fileno(), "w") - PY_SCIP_CALL(SCIPprintTransSol(self._scip, solution.sol, cfile, write_zeros)) - - locale.setlocale(locale.LC_NUMERIC,user_locale) - - # perhaps this should not be included as it implements duplicated functionality - # (as does it's namesake in SCIP) - def readSol(self, filename): - """ - Reads a given solution file, problem has to be transformed in advance. - - Parameters - ---------- - filename : str - name of the input file - - """ - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - absfile = str_conversion(abspath(filename)) - PY_SCIP_CALL(SCIPreadSol(self._scip, absfile)) - - locale.setlocale(locale.LC_NUMERIC, user_locale) - - def readSolFile(self, filename): - """ - Reads a given solution file. - - Solution is created but not added to storage/the model. - Use 'addSol' OR 'trySol' to add it. - - Parameters - ---------- - filename : str - name of the input file - - Returns - ------- - Solution - - """ - cdef SCIP_Bool partial - cdef SCIP_Bool error - cdef SCIP_Bool stored - cdef Solution solution - - str_absfile = abspath(filename) - absfile = str_conversion(str_absfile) - solution = self.createSol() - - user_locale = locale.getlocale(category=locale.LC_NUMERIC) - locale.setlocale(locale.LC_NUMERIC, "C") - - PY_SCIP_CALL(SCIPreadSolFile(self._scip, absfile, solution.sol, False, &partial, &error)) - - locale.setlocale(locale.LC_NUMERIC, user_locale) - - if error: - raise Exception("SCIP: reading solution from file " + str_absfile + " failed!") - - return solution - - def setSolVal(self, Solution solution, Variable var, val): - """ - Set a variable in a solution. - - Parameters - ---------- - solution : Solution - solution to be modified - var : Variable - variable in the solution - val : float - value of the specified variable - - """ - cdef SCIP_SOL* _sol - _sol = solution.sol - - assert _sol != NULL, "Cannot set value to a freed solution." - PY_SCIP_CALL(SCIPsetSolVal(self._scip, _sol, var.scip_var, val)) - - def trySol(self, Solution solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, free=True): - """ - Check given primal solution for feasibility and try to add it to the storage. + Retrieves the SCIP_HEUR pointer corresponding to a heuristic object. Parameters ---------- - solution : Solution - 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) + heur : Heur or None + The heuristic object to resolve. Returns ------- - stored : bool - whether given solution was feasible and good enough to keep + SCIP_HEUR* + Pointer to the SCIP heuristic, or NULL if heur is not a Heur instance or not found. """ - cdef SCIP_Bool stored - if free: - PY_SCIP_CALL(SCIPtrySolFree(self._scip, &solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) - else: - PY_SCIP_CALL(SCIPtrySol(self._scip, solution.sol, printreason, completely, checkbounds, checkintegrality, checklprows, &stored)) - return stored + if isinstance(heur, Heur): + n = str_conversion(heur.name) + return SCIPfindHeur(self._scip, n) + return NULL def checkSol(self, Solution solution, printreason=True, completely=False, checkbounds=True, checkintegrality=True, checklprows=True, original=False): """ @@ -11564,33 +5860,6 @@ cdef class Model: self._bestSol = Solution.create(self._scip, _sol) return self._bestSol - def getSolObjVal(self, Solution sol, original=True): - """ - Retrieve the objective value of the solution. - - Parameters - ---------- - sol : Solution - original : bool, optional - objective value in original space (Default value = True) - - Returns - ------- - float - - """ - if sol == None: - sol = Solution.create(self._scip, NULL) - - sol._checkStage("getSolObjVal") - - if original: - objval = SCIPgetSolOrigObj(self._scip, sol.sol) - else: - objval = SCIPgetSolTransObj(self._scip, sol.sol) - - return objval - def getSolTime(self, Solution sol): """ Get clock time when this solution was found. @@ -11649,64 +5918,6 @@ cdef class Model: return self.getSolObjVal(self._bestSol, original) - def getSolVal( - self, - Solution sol, - expr: Union[Expr, GenExpr, MatrixExpr], - ) -> Union[float, np.ndarray]: - """ - Retrieve value of given variable or expression in the given solution. - - Parameters - ---------- - sol : Solution - Solution to query the value from. If None, the current LP/pseudo solution is - used. - - expr : Expr, GenExpr, MatrixExpr - Expression to query the value of. - - Returns - ------- - float or np.ndarray - - Notes - ----- - A variable is also an expression. - - """ - # no need to create a NULL solution wrapper in case we have a variable - return (sol or Solution.create(self._scip, NULL))[expr] - - def getVal(self, expr: Union[Expr, GenExpr, MatrixExpr]) -> Union[float, np.ndarray]: - """ - Retrieve the value of the given variable or expression in the best known solution. - Can only be called after solving is completed. - - Parameters - ---------- - expr : Expr, GenExpr or MatrixExpr - Expression to query the value of. - - Returns - ------- - float or np.ndarray - - Notes - ----- - A variable is also an expression. - - """ - if SCIPgetStage(self._scip) in {SCIP_STAGE_INIT, SCIP_STAGE_FREE}: - raise Warning("Method cannot be called in stage ", self.getStage()) - - self._ensureFreshBestSol() - - if self._bestSol.sol == NULL and SCIPgetStage(self._scip) != SCIP_STAGE_SOLVING: - raise Warning("No solution available") - - return self._bestSol[expr] - def hasPrimalRay(self): """ Returns whether a primal ray is stored that proves unboundedness of the LP relaxation. @@ -11718,87 +5929,6 @@ cdef class Model: """ return SCIPhasPrimalRay(self._scip) - def getPrimalRayVal(self, Variable var): - """ - Gets value of given variable in primal ray causing unboundedness of the LP relaxation. - - Parameters - ---------- - var : Variable - - Returns - ------- - float - - """ - assert SCIPhasPrimalRay(self._scip), "The problem does not have a primal ray." - - return SCIPgetPrimalRayVal(self._scip, var.scip_var) - - def getPrimalRay(self): - """ - Gets primal ray causing unboundedness of the LP relaxation. - - Returns - ------- - list of float - - """ - assert SCIPhasPrimalRay(self._scip), "The problem does not have a primal ray." - cdef SCIP_VAR** vars = SCIPgetVars(self._scip) - cdef int nvars = SCIPgetNVars(self._scip) - cdef int i - - ray = [] - for i in range(nvars): - ray.append(float(SCIPgetPrimalRayVal(self._scip, vars[i]))) - - return ray - - def getPrimalbound(self): - """ - Retrieve the best primal bound. - - Returns - ------- - float - - """ - return SCIPgetPrimalbound(self._scip) - - def getDualbound(self): - """ - Retrieve the best dual bound. - - Returns - ------- - float - - """ - return SCIPgetDualbound(self._scip) - - def getDualboundRoot(self): - """ - Retrieve the best root dual bound. - - Returns - ------- - float - - """ - return SCIPgetDualboundRoot(self._scip) - - def getLowerboundRoot(self): - """ - Gets lower (dual) bound in transformed problem of the root node. - - Returns - ------- - float - - """ - return SCIPgetLowerboundRoot(self._scip) - def writeName(self, Variable var): """ Write the name of the variable to the std out. @@ -12615,62 +6745,6 @@ cdef class Model: raise Warning("method cannot be called in stage %i." % self.getStage()) PY_SCIP_CALL(SCIPfreeReoptSolve(self._scip)) - def chgReoptObjective(self, coeffs, sense = 'minimize'): - """ - Change the objective function for reoptimization. - - Parameters - ---------- - coeffs : Expr - the coefficients as a linear expression - sense : str - the objective sense (Default value = 'minimize') - - """ - cdef SCIP_VAR** vars - cdef int nvars - cdef SCIP_Real* _coeffs - cdef SCIP_OBJSENSE objsense - cdef int i - cdef _VarArray wrapper - - if sense == "minimize": - objsense = SCIP_OBJSENSE_MINIMIZE - elif sense == "maximize": - objsense = SCIP_OBJSENSE_MAXIMIZE - else: - raise Warning("unrecognized optimization sense: %s" % sense) - - assert isinstance(coeffs, Expr), "given coefficients are not Expr but %s" % coeffs.__class__.__name__ - - if coeffs.degree() > 1: - raise ValueError("Nonlinear objective functions are not supported!") - if coeffs[CONST] != 0.0: - raise ValueError("Constant offsets in objective are not supported!") - - nvars = len(coeffs.terms) - (CONST in coeffs.terms) - - if nvars == 0: - PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, NULL, NULL, 0)) - return - - _coeffs = malloc(nvars * sizeof(SCIP_Real)) - vars = malloc(nvars * sizeof(SCIP_VAR*)) - - i = 0 - for term, coef in coeffs.terms.items(): - # avoid CONST term of Expr - if term != CONST: - wrapper = _VarArray(term[0]) - vars[i] = wrapper.ptr[0] - _coeffs[i] = coef - i += 1 - - PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, vars, _coeffs, nvars)) - - free(vars) - free(_coeffs) - def chgVarBranchPriority(self, Variable var, priority): """ Sets the branch priority of the variable. @@ -12702,44 +6776,6 @@ cdef class Model: PY_SCIP_CALL(SCIPendStrongbranch(self._scip)) - def getVarStrongbranchLast(self, Variable var): - """ - Get the results of the last strong branching call on this variable (potentially was called - at another node). - - Parameters - ---------- - var : Variable - variable to get the previous strong branching information from - - Returns - ------- - down : float - The dual bound of the LP after branching down on the variable - up : float - The dual bound of the LP after branchign up on the variable - downvalid : bool - stores whether the returned down value is a valid dual bound, or NULL - upvalid : bool - stores whether the returned up value is a valid dual bound, or NULL - solval : float - The solution value of the variable at the last strong branching call - lpobjval : float - The LP objective value at the time of the last strong branching call - - """ - - cdef SCIP_Real down - cdef SCIP_Real up - cdef SCIP_Real solval - cdef SCIP_Real lpobjval - cdef SCIP_Bool downvalid - cdef SCIP_Bool upvalid - - PY_SCIP_CALL(SCIPgetVarStrongbranchLast(self._scip, var.scip_var, &down, &up, &downvalid, &upvalid, &solval, &lpobjval)) - - return down, up, downvalid, upvalid, solval, lpobjval - def getVarStrongbranchNode(self, Variable var): """ Get the node number from the last time strong branching was called on the variable. @@ -12760,63 +6796,6 @@ cdef class Model: return node_num - def getVarStrongbranch(self, Variable var, itlim, idempotent=False, integral=False): - """ - Strong branches and gets information on column variable. - - Parameters - ---------- - var : Variable - Variable to get strong branching information on - itlim : int - LP iteration limit for total strong branching calls - idempotent : bool, optional - Should SCIP's state remain the same after the call? - integral : bool, optional - Boolean on whether the variable is currently integer. - - Returns - ------- - down : float - The dual bound of the LP after branching down on the variable - up : float - The dual bound of the LP after branchign up on the variable - downvalid : bool - stores whether the returned down value is a valid dual bound, or NULL - upvalid : bool - stores whether the returned up value is a valid dual bound, or NULL - downinf : bool - store whether the downwards branch is infeasible - upinf : bool - store whether the upwards branch is infeasible - downconflict : bool - store whether a conflict constraint was created for an infeasible downwards branch - upconflict : bool - store whether a conflict constraint was created for an infeasible upwards branch - lperror : bool - whether an unresolved LP error occurred in the solving process - - """ - - cdef SCIP_Real down - cdef SCIP_Real up - cdef SCIP_Bool downvalid - cdef SCIP_Bool upvalid - cdef SCIP_Bool downinf - cdef SCIP_Bool upinf - cdef SCIP_Bool downconflict - cdef SCIP_Bool upconflict - cdef SCIP_Bool lperror - - if integral: - PY_SCIP_CALL(SCIPgetVarStrongbranchInt(self._scip, var.scip_var, itlim, idempotent, &down, &up, &downvalid, - &upvalid, &downinf, &upinf, &downconflict, &upconflict, &lperror)) - else: - PY_SCIP_CALL(SCIPgetVarStrongbranchFrac(self._scip, var.scip_var, itlim, idempotent, &down, &up, &downvalid, - &upvalid, &downinf, &upinf, &downconflict, &upconflict, &lperror)) - - return down, up, downvalid, upvalid, downinf, upinf, downconflict, upconflict, lperror - def updateVarPseudocost(self, Variable var, valdelta, objdelta, weight): """ Updates the pseudo costs of the given variable and the global pseudo costs after a change of valdelta @@ -12881,337 +6860,40 @@ cdef class Model: """ return SCIPgetTreesizeEstimation(self._scip) - - # Exact SCIP methods - def enableExactSolving(self, SCIP_Bool enable): - """ - Enables or disables exact solving mode in SCIP. - - Parameters - ---------- - enable : SCIP_Bool - Whether to enable exact solving mode (True) or disable it (False). - """ - - PY_SCIP_CALL(SCIPenableExactSolving(self._scip, enable)) - - def isExact(self): - """ - Returns whether exact solving mode is enabled in SCIP. - - Returns - ------- - bool - """ - - return SCIPisExact(self._scip) - - def allowNegSlackExact(self): - """ - Returns whether negative slack is allowed in exact solving mode. - - Returns - ------- - bool - """ - - return SCIPallowNegSlack(self._scip) - - def branchLPExact(self): - """ - Performs exact LP branching. - - Returns - ------- - SCIP_RESULT - """ - cdef SCIP_RESULT result - PY_SCIP_CALL(SCIPbranchLPExact(self._scip, &result)) - return result - - def addRowExact(self, RowExact rowexact): - """ - Adds an exact row to the LP. - - Parameters - ---------- - rowexact : RowExact - The exact row to add. - """ - PY_SCIP_CALL(SCIPaddRowExact(self._scip, rowexact.scip_row_exact)) - - def getBipartiteGraphRepresentation(self, prev_col_features=None, prev_edge_features=None, prev_row_features=None, - static_only=False, suppress_warnings=False): + def getConsVars(self, Constraint constraint): """ - This function generates the bipartite graph representation of an LP, which was first used in - the following paper: - @inproceedings{conf/nips/GasseCFCL19, - title={Exact Combinatorial Optimization with Graph Convolutional Neural Networks}, - author={Gasse, Maxime and Chételat, Didier and Ferroni, Nicola and Charlin, Laurent and Lodi, Andrea}, - booktitle={Advances in Neural Information Processing Systems 32}, - year={2019} - } - The exact features have been modified compared to the original implementation. - This function is used mainly in the machine learning community for MIP. - A user can only call it during the solving process, when there is an LP object. This means calling it - from some user defined plugin on the Python side. - An example plugin is a branching rule or an event handler, which is exclusively created to call this function. - The user must then make certain to return the appropriate SCIP_RESULT (e.g. DIDNOTRUN) + Gets variables in a constraint. Parameters ---------- - prev_col_features : list of list or None, optional - The list of column features previously returned by this function - prev_edge_features : list of list or None, optional - The list of edge features previously returned by this function - prev_row_features : list of list or None, optional - The list of row features previously returned by this function - static_only : bool, optional - Whether exclusively static features should be generated - suppress_warnings : bool, optional - Whether warnings should be suppressed + constraint : Constraint + Constraint to get the variables from. Returns ------- - col_features : list of list - edge_features : list of list - row_features : list of list - dict - The feature mappings for the columns, edges, and rows + list of Variable """ - cdef SCIP* scip = self._scip - cdef SCIP_VARTYPE vtype - cdef SCIP_Real sim, prod - cdef int col_i + cdef SCIP_VAR** _vars + cdef int nvars + cdef SCIP_Bool success cdef int i - cdef int j - cdef int k - - # Check if SCIP is in the correct stage - if SCIPgetStage(scip) != SCIP_STAGE_SOLVING: - raise Warning("This functionality can only been called in SCIP_STAGE SOLVING. The row and column" - "information is then accessible") - # Generate column features - cdef SCIP_COL** cols = SCIPgetLPCols(scip) - cdef int ncols = SCIPgetNLPCols(scip) - - if static_only: - n_col_features = 5 - col_feature_map = {"continuous": 0, "binary": 1, "integer": 2, "implicit_integer": 3, "obj_coef": 4} - else: - n_col_features = 19 - col_feature_map = {"continuous": 0, "binary": 1, "integer": 2, "implicit_integer": 3, "obj_coef": 4, - "has_lb": 5, "has_ub": 6, "sol_at_lb": 7, "sol_at_ub": 8, "sol_val": 9, "sol_frac": 10, - "red_cost": 11, "basis_lower": 12, "basis_basic": 13, "basis_upper": 14, - "basis_zero": 15, "best_incumbent_val": 16, "avg_incumbent_val": 17, "age": 18} - - if prev_col_features is None: - col_features = [[0 for i in range(n_col_features)] for j in range(ncols)] - else: - assert len(prev_col_features) > 0, "Previous column features is empty" - col_features = prev_col_features - if len(prev_col_features) != ncols: - if not suppress_warnings: - raise Warning(f"The number of columns has changed. Previous column data being ignored") - else: - col_features = [[0 for i in range(n_col_features)] for j in range(ncols)] - prev_col_features = None - if len(prev_col_features[0]) != n_col_features: - raise Warning(f"Dimension mismatch in provided previous features and new features:" - f"{len(prev_col_features[0])} != {n_col_features}") - - cdef SCIP_SOL* sol = SCIPgetBestSol(scip) - cdef SCIP_VAR* var - cdef SCIP_Real lb - cdef SCIP_Real ub - cdef SCIP_Real solval - cdef SCIP_BASESTAT basis_status - - for i in range(ncols): - col_i = SCIPcolGetLPPos(cols[i]) - var = SCIPcolGetVar(cols[i]) - - lb = SCIPcolGetLb(cols[i]) - ub = SCIPcolGetUb(cols[i]) - solval = SCIPcolGetPrimsol(cols[i]) - - # Collect the static features first (don't need to changed if previous features are passed) - if prev_col_features is None: - # Variable types - vtype = SCIPvarGetType(var) - if vtype == SCIP_VARTYPE_BINARY: - col_features[col_i][col_feature_map["binary"]] = 1 - elif vtype == SCIP_VARTYPE_INTEGER: - col_features[col_i][col_feature_map["integer"]] = 1 - elif vtype == SCIP_VARTYPE_CONTINUOUS: - col_features[col_i][col_feature_map["continuous"]] = 1 - elif vtype == SCIP_DEPRECATED_VARTYPE_IMPLINT: - col_features[col_i][col_feature_map["implicit_integer"]] = 1 - # Objective coefficient - col_features[col_i][col_feature_map["obj_coef"]] = SCIPcolGetObj(cols[i]) - - # Collect the dynamic features - if not static_only: - # Lower bound - if not SCIPisInfinity(scip, abs(lb)): - col_features[col_i][col_feature_map["has_lb"]] = 1 - - # Upper bound - if not SCIPisInfinity(scip, abs(ub)): - col_features[col_i][col_feature_map["has_ub"]] = 1 - - # Basis status - basis_status = SCIPcolGetBasisStatus(cols[i]) - if basis_status == SCIP_BASESTAT_LOWER: - col_features[col_i][col_feature_map["basis_lower"]] = 1 - elif basis_status == SCIP_BASESTAT_BASIC: - col_features[col_i][col_feature_map["basis_basic"]] = 1 - elif basis_status == SCIP_BASESTAT_UPPER: - col_features[col_i][col_feature_map["basis_upper"]] = 1 - elif basis_status == SCIP_BASESTAT_ZERO: - col_features[col_i][col_feature_map["basis_zero"]] = 1 - - # Reduced cost - col_features[col_i][col_feature_map["red_cost"]] = SCIPgetColRedcost(scip, cols[i]) - - # Age - col_features[col_i][col_feature_map["age"]] = SCIPcolGetAge(cols[i]) - - # LP solution value - col_features[col_i][col_feature_map["sol_val"]] = solval - col_features[col_i][col_feature_map["sol_frac"]] = SCIPfeasFrac(scip, solval) - col_features[col_i][col_feature_map["sol_at_lb"]] = int(SCIPisEQ(scip, solval, lb)) - col_features[col_i][col_feature_map["sol_at_ub"]] = int(SCIPisEQ(scip, solval, ub)) - - # Incumbent solution value - if sol is NULL: - col_features[col_i][col_feature_map["best_incumbent_val"]] = None - col_features[col_i][col_feature_map["avg_incumbent_val"]] = None - else: - col_features[col_i][col_feature_map["best_incumbent_val"]] = SCIPgetSolVal(scip, sol, var) - col_features[col_i][col_feature_map["avg_incumbent_val"]] = SCIPvarGetAvgSol(var) + SCIPgetConsNVars(self._scip, constraint.scip_cons, &nvars, &success) + _vars = malloc(nvars * sizeof(SCIP_VAR*)) + SCIPgetConsVars(self._scip, constraint.scip_cons, _vars, nvars, &success) - # Generate row features - cdef SCIP_ROW** rows = SCIPgetLPRows(scip) - cdef int nrows = SCIPgetNLPRows(scip) + if not success: + free(_vars) + return None - if static_only: - n_row_features = 6 - row_feature_map = {"has_lhs": 0, "has_rhs": 1, "n_non_zeros": 2, "obj_cosine": 3, "bias": 4, "norm": 5} - else: - n_row_features = 14 - row_feature_map = {"has_lhs": 0, "has_rhs": 1, "n_non_zeros": 2, "obj_cosine": 3, "bias": 4, "norm": 5, - "sol_at_lhs": 6, "sol_at_rhs": 7, "dual_sol": 8, "age": 9, - "basis_lower": 10, "basis_basic": 11, "basis_upper": 12, "basis_zero": 13} + vars = [] + for i in range(nvars): + vars.append(self._getOrCreateVar(_vars[i])) - if prev_row_features is None: - row_features = [[0 for i in range(n_row_features)] for j in range(nrows)] - else: - assert len(prev_row_features) > 0, "Previous row features is empty" - row_features = prev_row_features - if len(prev_row_features) != nrows: - if not suppress_warnings: - raise Warning(f"The number of rows has changed. Previous row data being ignored") - else: - row_features = [[0 for i in range(n_row_features)] for j in range(nrows)] - prev_row_features = None - if len(prev_row_features[0]) != n_row_features: - raise Warning(f"Dimension mismatch in provided previous features and new features:" - f"{len(prev_row_features[0])} != {n_row_features}") - - cdef SCIP_Real lhs - cdef SCIP_Real rhs - cdef SCIP_Real cst - cdef int nnzrs = 0 - - for i in range(nrows): - - # lhs <= activity + cst <= rhs - lhs = SCIProwGetLhs(rows[i]) - rhs = SCIProwGetRhs(rows[i]) - cst = SCIProwGetConstant(rows[i]) - activity = SCIPgetRowLPActivity(scip, rows[i]) - - if prev_row_features is None: - # number of coefficients - row_features[i][row_feature_map["n_non_zeros"]] = SCIProwGetNLPNonz(rows[i]) - nnzrs += row_features[i][row_feature_map["n_non_zeros"]] - - # left-hand-side - if not SCIPisInfinity(scip, abs(lhs)): - row_features[i][row_feature_map["has_lhs"]] = 1 - - # right-hand-side - if not SCIPisInfinity(scip, abs(rhs)): - row_features[i][row_feature_map["has_rhs"]] = 1 - - # bias - row_features[i][row_feature_map["bias"]] = cst - - # Objective cosine similarity - row_features[i][row_feature_map["obj_cosine"]] = SCIPgetRowObjParallelism(scip, rows[i]) - - # L2 norm - row_features[i][row_feature_map["norm"]] = SCIProwGetNorm(rows[i]) - - if not static_only: - - # Dual solution - row_features[i][row_feature_map["dual_sol"]] = SCIProwGetDualsol(rows[i]) - - # Basis status - basis_status = SCIProwGetBasisStatus(rows[i]) - if basis_status == SCIP_BASESTAT_LOWER: - row_features[i][row_feature_map["basis_lower"]] = 1 - elif basis_status == SCIP_BASESTAT_BASIC: - row_features[i][row_feature_map["basis_basic"]] = 1 - elif basis_status == SCIP_BASESTAT_UPPER: - row_features[i][row_feature_map["basis_upper"]] = 1 - elif basis_status == SCIP_BASESTAT_ZERO: - row_features[i][row_feature_map["basis_zero"]] = 1 - - # Age - row_features[i][row_feature_map["age"]] = SCIProwGetAge(rows[i]) - - # Is tight - row_features[i][row_feature_map["sol_at_lhs"]] = int(SCIPisEQ(scip, activity, lhs)) - row_features[i][row_feature_map["sol_at_rhs"]] = int(SCIPisEQ(scip, activity, rhs)) - - # Generate edge (coefficient) features - cdef SCIP_COL** row_cols - cdef SCIP_Real * row_vals - - n_edge_features = 3 - edge_feature_map = {"col_idx": 0, "row_idx": 1, "coef": 2} - if prev_edge_features is None: - edge_features = [[0 for i in range(n_edge_features)] for j in range(nnzrs)] - j = 0 - for i in range(nrows): - # coefficient indexes and values - row_cols = SCIProwGetCols(rows[i]) - row_vals = SCIProwGetVals(rows[i]) - for k in range(row_features[i][row_feature_map["n_non_zeros"]]): - edge_features[j][edge_feature_map["col_idx"]] = SCIPcolGetLPPos(row_cols[k]) - edge_features[j][edge_feature_map["row_idx"]] = i - edge_features[j][edge_feature_map["coef"]] = row_vals[k] - j += 1 - else: - assert len(prev_edge_features) > 0, "Previous edge features is empty" - edge_features = prev_edge_features - if len(prev_edge_features) != nnzrs: - if not suppress_warnings: - raise Warning(f"The number of coefficients in the LP has changed. Previous edge data being ignored") - else: - edge_features = [[0 for i in range(3)] for j in range(nnzrs)] - prev_edge_features = None - if len(prev_edge_features[0]) != 3: - raise Warning(f"Dimension mismatch in provided previous features and new features:" - f"{len(prev_edge_features[0])} != 3") + free(_vars) + return vars - return (col_features, edge_features, row_features, - {"col": col_feature_map, "edge": edge_feature_map, "row": row_feature_map}) @dataclass class Statistics: @@ -13487,3 +7169,6 @@ def is_memory_freed(): def print_memory_in_use(): BMScheckEmptyMemory() + +include "model.pxi" +include "exact.pxi" diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 85b000c32..ddc3a608c 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -1,12 +1,15 @@ import os from collections.abc import Iterable, Mapping, Sequence -from typing import Any, ClassVar, Literal, SupportsFloat, overload +from fractions import Fraction +from typing import Any, AnyStr, ClassVar, Literal, SupportsFloat, Union, overload import numpy as np from _typeshed import Incomplete, StrOrBytesPath from numpy.typing import NDArray from typing_extensions import CapsuleType, Self, deprecated, disjoint_base +_Rational = Union[Fraction, int, float] + CONST: Term EventNames: dict MAJOR: int @@ -147,6 +150,7 @@ class Column: class ColumnExact: data: Any def __init__(self) -> None: ... + def getVar(self) -> ExactVariable: ... @disjoint_base class Conshdlr: @@ -375,6 +379,175 @@ class ExprLike: @overload def __eq__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExprCons: ... +class ExactModel(BaseModel): + def __init__( + self, + problemName: str = "model", + defaultPlugins: bool = True, + createscip: bool = True, + threadsafe: bool = False, + ) -> None: ... + def _checkBoundStage(self, method: str) -> None: ... + def addCoefLinear(self, cons: Constraint, var: Variable, value: _Rational) -> None: ... + def addCons(self, cons: Any, name: str = "", **kwargs: Any) -> Constraint: ... # type: ignore[override] + def addConsLinear( + self, + vars: Sequence[Variable], + vals: Sequence[_Rational], + lhs: _Rational | None, + rhs: _Rational | None, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + modifiable: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addObjoffset(self, offset: _Rational, solutions: bool = False) -> None: ... + def addRow(self, rowexact: RowExact) -> None: ... + def addVar( + self, + name: str = "", + vtype: str = "C", + lb: _Rational | None = 0, + ub: _Rational | None = None, + obj: _Rational = 0, + pricedVar: bool = False, + pricedVarScore: float = 1.0, + deletable: bool = False, + ) -> ExactVariable: ... + def aggregateVars(self, varx: Variable, vary: Variable, coefx: _Rational = 1, coefy: _Rational = -1, rhs: _Rational = 0) -> tuple[bool, bool, bool]: ... + def allowNegSlack(self) -> bool: ... + def branchLP(self) -> int: ... + def chgCoefLinear(self, cons: Constraint, var: Variable, value: _Rational) -> None: ... + def chgLhs(self, cons: Constraint, lhs: _Rational | None) -> None: ... + def chgRhs(self, cons: Constraint, rhs: _Rational | None) -> None: ... + def chgVarLb(self, var: Variable, lb: _Rational | None) -> None: ... + def chgVarLbDive(self, var: Variable, newbound: _Rational | None) -> None: ... + def chgVarLbGlobal(self, var: Variable, lb: _Rational | None) -> None: ... + def chgVarLbNode(self, node: Node, var: Variable, lb: float | None) -> None: ... + def chgVarLbProbing(self, var: Variable, lb: float | None) -> None: ... + def chgVarObj(self, var: Variable, newobj: _Rational) -> None: ... + def chgVarObjDive(self, var: Variable, newobj: float) -> None: ... + def chgVarObjProbing(self, var: Variable, newobj: float) -> None: ... + def chgVarUb(self, var: Variable, ub: _Rational | None) -> None: ... + def chgVarUbDive(self, var: Variable, newbound: _Rational | None) -> None: ... + def chgVarUbGlobal(self, var: Variable, ub: _Rational | None) -> None: ... + def chgVarUbNode(self, node: Node, var: Variable, ub: float | None) -> None: ... + def chgVarUbProbing(self, var: Variable, ub: float | None) -> None: ... + def createOrigSol(self, heur: Heur | None = None) -> Solution: ... + def createPartialSol(self, heur: Heur | None = None) -> Solution: ... + def createSol(self, heur: Heur | None = None, initlp: bool = False) -> Solution: ... + def delCoefLinear(self, cons: Constraint, var: Variable) -> None: ... + def endDive(self) -> None: ... + def epsilon(self) -> Fraction: ... # type: ignore[override] + def feasCeil(self, value: _Rational) -> int: ... + def feasFloor(self, value: _Rational) -> int: ... + def feasFrac(self, value: _Rational) -> Fraction: ... # type: ignore[override] + def feasRound(self, value: _Rational) -> int: ... + def feastol(self) -> Fraction: ... # type: ignore[override] + def fixVar(self, var: Variable, val: _Rational) -> tuple[bool, bool]: ... + def fixVarProbing(self, var: Variable, fixedval: float) -> None: ... + def frac(self, value: _Rational) -> Fraction: ... # type: ignore[override] + def getActivity(self, cons: Constraint, sol: Solution | None = None) -> Fraction: ... # type: ignore[override] + def getConsVals(self, constraint: Constraint) -> list[Fraction] | None: ... # type: ignore[override] + def getConsVars(self, constraint: Constraint) -> list[ExactVariable] | None: ... # type: ignore[override] + def getCutoffbound(self) -> Fraction | float: ... # type: ignore[override] + def getDualbound(self) -> Fraction | float: ... # type: ignore[override] + def getDualfarkasLinear(self, cons: Constraint) -> Fraction: ... # type: ignore[override] + def getDualsolLinear(self, cons: Constraint) -> Fraction: ... # type: ignore[override] + def getLPObjVal(self) -> Fraction | float: ... # type: ignore[override] + def getLPSolstat(self) -> int: ... + def getLhs(self, cons: Constraint) -> Fraction | float: ... # type: ignore[override] + def getLowerbound(self) -> Fraction | float: ... # type: ignore[override] + def getObjVal(self, original: bool = True) -> Fraction: ... # type: ignore[override] + def getObjoffset(self, original: bool = True) -> Fraction: ... # type: ignore[override] + def getPrimalbound(self) -> Fraction | float: ... # type: ignore[override] + def getRhs(self, cons: Constraint) -> Fraction | float: ... # type: ignore[override] + def getRowLinear(self, cons: Constraint) -> RowExact: ... # type: ignore[override] + def getSlack(self, cons: Constraint, sol: Solution | None = None, side: str | None = None) -> Fraction | float: ... # type: ignore[override] + def getSolObjVal(self, sol: Solution | None, original: bool = True) -> Fraction: ... # type: ignore[override] + def getSolVal(self, sol: Solution | None, expr: Variable | MatrixVariable) -> Fraction | float | np.ndarray: ... # type: ignore[override] + def getUpperbound(self) -> Fraction | float: ... # type: ignore[override] + def getVal(self, expr: Variable | MatrixVariable) -> Fraction | float | np.ndarray: ... # type: ignore[override] + def getValsLinear(self, cons: Constraint) -> dict[str, Fraction]: ... # type: ignore[override] + def infinity(self) -> float: ... + def isEQ(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasEQ(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasGE(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasGT(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasIntegral(self, value: _Rational) -> bool: ... + def isFeasLE(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasLT(self, val1: _Rational, val2: _Rational) -> bool: ... + def isFeasNegative(self, value: _Rational) -> bool: ... + def isFeasPositive(self, value: _Rational) -> bool: ... + def isFeasZero(self, value: _Rational) -> bool: ... + def isGE(self, val1: _Rational, val2: _Rational) -> bool: ... + def isGT(self, val1: _Rational, val2: _Rational) -> bool: ... + def isHugeValue(self, val: float) -> bool: ... + def isInfinity(self, value: _Rational) -> bool: ... + def isIntegral(self, value: _Rational) -> bool: ... + def isLE(self, val1: _Rational, val2: _Rational) -> bool: ... + def isLT(self, val1: _Rational, val2: _Rational) -> bool: ... + def isNegative(self, val: _Rational) -> bool: ... + def isPositive(self, val: _Rational) -> bool: ... + def isZero(self, value: _Rational) -> bool: ... + def printBestSol(self, write_zeros: bool = False) -> None: ... + def printRow(self, row: RowExact) -> None: ... + def printSol(self, solution: Solution | None = None, write_zeros: bool = False) -> None: ... + def setObjective( + self, + expr: Expr | SupportsFloat, + sense: Literal["minimize", "maximize"] = "minimize", + clear: bool | Literal["true"] = "true", # TODO: typo? + ) -> None: ... + def setObjlimit(self, objlimit: float) -> None: ... + def setSolVal(self, solution: Solution, var: Variable, val: _Rational) -> None: ... + def solveDiveLP(self, itlim: int = -1) -> tuple[bool, bool]: ... + def startDive(self) -> None: ... + def tightenVarLb(self, var: Variable, lb: _Rational, force: bool = False) -> tuple[bool, bool]: ... + def tightenVarLbGlobal(self, var: Variable, lb: float, force: bool = False) -> tuple[bool, bool]: ... + def tightenVarUb(self, var: Variable, ub: _Rational, force: bool = False) -> tuple[bool, bool]: ... + def tightenVarUbGlobal(self, var: Variable, ub: float, force: bool = False) -> tuple[bool, bool]: ... + def trySol( + self, + solution: Solution, + printreason: bool = True, + completely: bool = False, + checkbounds: bool = True, + checkintegrality: bool = True, + checklprows: bool = True, + free: bool = True, + ) -> bool: ... + def writeBestSol( + self, + filename: str | bytes | os.PathLike[AnyStr] = "origprob.sol", + write_zeros: bool = False, + ) -> None: ... + def writeSol( + self, + solution: Solution, + filename: str | bytes | os.PathLike[AnyStr] = "origprob.sol", + write_zeros: bool = False, + ) -> None: ... + +class ExactVariable(Variable): + def getCol(self) -> ColumnExact: ... # type: ignore[override] + def getLPSol(self) -> Fraction | float: ... # type: ignore[override] + def getLbGlobal(self) -> Fraction | float: ... # type: ignore[override] + def getLbLocal(self) -> Fraction | float: ... # type: ignore[override] + def getLbOriginal(self) -> Fraction | float: ... # type: ignore[override] + def getObj(self) -> Fraction: ... # type: ignore[override] + def getStatus(self) -> str: ... # type: ignore[override] + def getUbGlobal(self) -> Fraction | float: ... # type: ignore[override] + def getUbLocal(self) -> Fraction | float: ... # type: ignore[override] + def getUbOriginal(self) -> Fraction | float: ... # type: ignore[override] + @disjoint_base class Expr(ExprLike): @property @@ -669,154 +842,658 @@ class MatrixVariable(MatrixExpr): def __pos__(self, /) -> MatrixExpr: ... # type: ignore[override] @disjoint_base -class Model: +class BaseModel: _freescip: bool data: Any def __init__( self, problemName: str = "model", defaultPlugins: bool = True, - sourceModel: Model | None = None, + sourceModel: BaseModel | None = None, origcopy: bool = False, globalcopy: bool = True, enablepricing: bool = True, createscip: bool = True, threadsafe: bool = False, ) -> None: ... - def _createConsGenNonlinear( - self, cons: ExprCons, **kwargs: Incomplete - ) -> Constraint: ... - def _createConsLinear( - self, lincons: ExprCons, **kwargs: Incomplete - ) -> Constraint: ... - def _createConsNonlinear( - self, cons: ExprCons, **kwargs: Incomplete - ) -> Constraint: ... - def _createConsQuadratic( - self, quadcons: ExprCons, **kwargs: Incomplete - ) -> Constraint: ... def _getStageNames(self) -> None: ... def activateBenders(self, benders: Benders, nsubproblems: int) -> None: ... def addBendersSubproblem(self, benders: Benders, subproblem: Model) -> None: ... - def addCoefKnapsack( - self, cons: Constraint, var: Variable, weight: float - ) -> None: ... - def addCoefLinear(self, cons: Constraint, var: Variable, value: float) -> None: ... - def addCoefLogicor(self, logicor_cons: Constraint, var: Variable) -> None: ... - def addCons( - self, - cons: ExprCons, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - propagate: bool = True, - local: bool = False, - modifiable: bool = False, - dynamic: bool = False, - removable: bool = False, - stickingatnode: bool = False, - ) -> Constraint: ... - def addConsAnd( - self, - vars: Sequence[Variable], - resvar: Variable, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - propagate: bool = True, - local: bool = False, - modifiable: bool = False, - dynamic: bool = False, - removable: bool = False, - stickingatnode: bool = False, - ) -> Constraint: ... - def addConsCardinality( - self, - consvars: Sequence[Variable], - cardval: int, - indvars: Sequence[Variable] | None = None, - weights: Sequence[float] | None = None, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - propagate: bool = True, - local: bool = False, - dynamic: bool = False, - removable: bool = False, - stickingatnode: bool = False, - ) -> Constraint: ... - def addConsCoeff(self, cons: Constraint, var: Variable, coeff: float) -> None: ... - def addConsCumulative( + def addConss( self, - vars: Sequence[Variable], - durations: Sequence[int], - demands: Sequence[int], - capacity: int, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - modifiable: bool = False, - propagate: bool = True, - local: bool = False, - dynamic: bool = False, - removable: bool = False, - stickingatnode: bool = False, - ) -> Constraint: ... - def addConsDisjunction( + conss: Iterable[ExprCons] | MatrixExprCons, + name: str | Iterable[str] = "", + initial: bool | Iterable[bool] = True, + separate: bool | Iterable[bool] = True, + enforce: bool | Iterable[bool] = True, + check: bool | Iterable[bool] = True, + propagate: bool | Iterable[bool] = True, + local: bool | Iterable[bool] = False, + modifiable: bool | Iterable[bool] = False, + dynamic: bool | Iterable[bool] = False, + removable: bool | Iterable[bool] = False, + stickingatnode: bool | Iterable[bool] = False, + ) -> list[Constraint]: ... + def addMatrixCons( self, - conss: Iterable[ExprCons], - name: str = "", - initial: bool = True, - relaxcons: Constraint | None = None, - enforce: bool = True, - check: bool = True, - local: bool = False, - modifiable: bool = False, - dynamic: bool = False, - ) -> Constraint: ... - def addConsElemDisjunction( - self, disj_cons: Constraint, cons: Constraint - ) -> Constraint: ... - def addConsIndicator( + cons: ExprCons | MatrixExprCons, + name: str | np.ndarray = "", + initial: bool | np.ndarray = True, + separate: bool | np.ndarray = True, + enforce: bool | np.ndarray = True, + check: bool | np.ndarray = True, + propagate: bool | np.ndarray = True, + local: bool | np.ndarray = False, + modifiable: bool | np.ndarray = False, + dynamic: bool | np.ndarray = False, + removable: bool | np.ndarray = False, + stickingatnode: bool | np.ndarray = False, + ) -> Constraint | MatrixConstraint: ... + def addSol(self, solution: Solution, free: bool = True) -> bool: ... + def addVarLocks(self, var: Variable, nlocksdown: int, nlocksup: int) -> None: ... + def addVarLocksType( + self, var: Variable, locktype: int, nlocksdown: int, nlocksup: int + ) -> None: ... + def allColsInLP(self) -> bool: ... + def applyCutsProbing(self) -> bool: ... + def attachEventHandlerCallback( self, - cons: ExprCons, - binvar: Variable | None = None, - activeone: bool = True, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - propagate: bool = True, - local: bool = False, - dynamic: bool = False, - removable: bool = False, - stickingatnode: bool = False, - ) -> Constraint: ... - def addConsLinear( + callback: Incomplete, + events: Incomplete, + name: Incomplete = ..., + description: Incomplete = ..., + ) -> Incomplete: ... + def backtrackProbing(self, probingdepth: int) -> None: ... + def branchVar(self, variable: Variable) -> tuple[Node, Node | None, Node]: ... + def catchEvent(self, eventtype: Incomplete, eventhdlr: Eventhdlr) -> None: ... + def catchRowEvent( + self, row: Row, eventtype: Incomplete, eventhdlr: Eventhdlr + ) -> None: ... + def catchVarEvent( + self, var: Variable, eventtype: Incomplete, eventhdlr: Eventhdlr + ) -> None: ... + def checkBendersSubproblemOptimality( + self, solution: Solution, probnumber: int, benders: Benders | None = None + ) -> bool: ... + def checkSol( self, - vars: Sequence[Variable], - vals: Sequence[float], - lhs: float | None = None, - rhs: float | None = None, - name: str = "", - initial: bool = True, - separate: bool = True, - enforce: bool = True, - check: bool = True, - propagate: bool = True, - local: bool = False, - modifiable: bool = False, - dynamic: bool = False, - removable: bool = False, + solution: Solution, + printreason: bool = True, + completely: bool = False, + checkbounds: bool = True, + checkintegrality: bool = True, + checklprows: bool = True, + original: bool = False, + ) -> bool: ... + def chgVarBranchPriority(self, var: Variable, priority: int) -> None: ... + def chgVarType(self, var: Variable, vtype: str) -> None: ... + def computeBestSolSubproblems(self) -> None: ... + def constructLP(self) -> bool: ... + def count(self) -> None: ... + def createChild(self, nodeselprio: float, estimate: float) -> Node: ... + def createProbBasic(self, problemName: str = "model") -> None: ... + def cutoffNode(self, node: Node) -> None: ... + def deactivatePricer(self, pricer: Pricer) -> None: ... + def delCons(self, cons: Constraint) -> None: ... + def delConsLocal(self, cons: Constraint) -> None: ... + def delVar(self, var: Variable) -> bool: ... + def disableDebugSol(self) -> None: ... + def disablePropagation(self, onlyroot: bool = False) -> None: ... + def dropEvent(self, eventtype: Incomplete, eventhdlr: Eventhdlr) -> None: ... + def dropRowEvent( + self, row: Row, eventtype: Incomplete, eventhdlr: Eventhdlr + ) -> None: ... + def dropVarEvent( + self, var: Variable, eventtype: Incomplete, eventhdlr: Eventhdlr + ) -> None: ... + def enableDebugSol(self) -> None: ... + def enableReoptimization(self, enable: bool = True) -> None: ... + def endProbing(self) -> None: ... + def endStrongbranch(self) -> None: ... + def free(self) -> None: ... + @deprecated( + "Deprecated since 5.7.0; Benders subproblems are freed automatically when the master Model is deallocated." + ) + def freeBendersSubproblems(self) -> None: ... + def freeProb(self) -> None: ... + def freeReoptSolve(self) -> None: ... + def freeSol(self, solution: Solution) -> None: ... + def freeTransform(self) -> None: ... + @staticmethod + def from_ptr(capsule: CapsuleType, take_ownership: bool) -> Model: ... + def generateIIS(self) -> IIS: ... + def getBendersAuxiliaryVar( + self, probnumber: int, benders: Benders | None = None + ) -> Variable: ... + def getBendersSubproblem( + self, probnumber: int, benders: Benders | None = None + ) -> Model: ... + def getBendersVar( + self, var: Variable, benders: Benders | None = None, probnumber: int = -1 + ) -> Variable | None: ... + def getBestChild(self) -> Node | None: ... + def getBestLeaf(self) -> Node | None: ... + def getBestNode(self) -> Node | None: ... + def getBestSibling(self) -> Node | None: ... + def getBestSol(self) -> Solution | None: ... + def getBestboundNode(self) -> Node | None: ... + def getBranchScoreMultiple(self, var: Variable, gains: list[float]) -> float: ... + def getChildren(self) -> list[Node]: ... + def getCondition(self, exact: bool = False) -> float: ... + def getConsNVars(self, constraint: Constraint) -> int: ... + def getConss(self, transformed: bool = True) -> list[Constraint]: ... + def getFocusNode(self) -> Node | None: ... + def getCountedSols(self) -> list[dict[str, int]]: ... + def getCurrentNode(self) -> Node | None: ... + def getDepth(self) -> int: ... + def getDeterministicTime(self) -> float: ... + def getGap(self) -> float: ... + def getHeurTiming(self, heurname: str) -> Incomplete: ... + def getIIS(self) -> IIS: ... + def getLPBasisInd(self) -> list[int]: ... + def getLeaves(self) -> list[Node]: ... + def getMajorVersion(self) -> int: ... + def getMaxDepth(self) -> int: ... + def getMaxTotalDepth(self) -> int: ... + def getNBacktracks(self) -> int: ... + def getMinorVersion(self) -> int: ... + def getNBestSolsFound(self) -> int: ... + def getNBinVars(self) -> int: ... + def getNChildren(self) -> int: ... + def getNConss(self, transformed: bool = True) -> int: ... + def getNContVars(self) -> int: ... + def getNCountedSols(self) -> int: ... + def getNCuts(self) -> int: ... + def getNCutsApplied(self) -> int: ... + def getNFeasibleLeaves(self) -> int: ... + def getNImplVars(self) -> int: ... + def getNInfeasibleLeaves(self) -> int: ... + def getNObjlimLeaves(self) -> int: ... + def getNIntVars(self) -> int: ... + def getNLPBranchCands(self) -> int: ... + def getNLPCols(self) -> int: ... + def getNLPIterations(self) -> int: ... + def getNLPRows(self) -> int: ... + def getNLPs(self) -> int: ... + def getMemUsed(self) -> int: ... + def getMemTotal(self) -> int: ... + def getMemExternEstim(self) -> int: ... + def getNLeaves(self) -> int: ... + def getNNodesLeft(self) -> int: ... + def getNLimSolsFound(self) -> int: ... + def getNNodeLPIterations(self) -> int: ... + def getNRuns(self) -> int: ... + def getNReoptRuns(self) -> int: ... + def addNNodes(self, nnodes: int) -> None: ... + def getNNodes(self) -> int: ... + def getNReaders(self) -> int: ... + def getNSepaRounds(self) -> int: ... + def getNSiblings(self) -> int: ... + def getNSols(self) -> int: ... + def getNSolsFound(self) -> int: ... + def getNStrongbranchLPIterations(self) -> int: ... + def getPrimalDualIntegral(self) -> float: ... + def getNTotalNodes(self) -> int: ... + def getNVars(self, transformed: bool = True) -> int: ... + def getObjVal(self, original: bool = True) -> float: ... + def getObjectiveSense(self) -> Literal["maximize", "minimize", "unknown"]: ... + def getOpenNodes(self) -> tuple[list[Node], list[Node], list[Node]]: ... + def getParam(self, name: str) -> bool | int | float | str: ... + def getParams(self) -> dict[str, bool | int | float | str]: ... + def getPlungeDepth(self) -> int: ... + def getPresolvingTime(self) -> float: ... + def getPrioChild(self) -> Node | None: ... + def getPrioSibling(self) -> Node | None: ... + def getProbName(self) -> str: ... + def getProbingDepth(self) -> int: ... + def getPseudoBranchCands(self) -> tuple[list[Variable], int, int]: ... + def getReadingTime(self) -> float: ... + def getSiblings(self) -> list[Node]: ... + def getSolTime(self, sol: Solution) -> float: ... + def getSols(self) -> list[Solution]: ... + def getSolvingTime(self) -> float: ... + def getStage(self) -> Incomplete: ... + def getStageName(self) -> str: ... + def getStatus( + self, + ) -> Literal[ + "optimal", + "timelimit", + "infeasible", + "unbounded", + "userinterrupt", + "inforunbd", + "nodelimit", + "totalnodelimit", + "stallnodelimit", + "gaplimit", + "memlimit", + "sollimit", + "bestsollimit", + "restartlimit", + "primallimit", + "duallimit", + "unknown", + ]: ... + def getTechVersion(self) -> int: ... + def getTotalTime(self) -> float: ... + def getTransformedCons(self, cons: Constraint) -> Constraint: ... + def getTransformedVar(self, var: Variable) -> Variable: ... + def getTreesizeEstimation(self) -> float: ... + def getVarPseudocost(self, var: Variable, branchdir: Incomplete) -> float: ... + def getVarPseudocostScore(self, var: Variable, solVal: float) -> float: ... + def getVarStrongbranchNode(self, var: Variable) -> int: ... + def getVars(self, transformed: bool = False) -> list[Variable]: ... + def hasPrimalRay(self) -> bool: ... + def hideOutput(self, quiet: bool = True) -> None: ... + def inProbing(self) -> bool: ... + def inRepropagation(self) -> bool: ... + def includeBenders( + self, + benders: Benders, + name: str, + desc: str, + priority: int = 1, + cutlp: bool = True, + cutpseudo: bool = True, + cutrelax: bool = True, + shareaux: bool = False, + ) -> None: ... + def includeBendersDefaultCuts(self, benders: Benders) -> None: ... + def includeBenderscut( + self, + benders: Benders, + benderscut: Benderscut, + name: str, + desc: str, + priority: int = 1, + islpcut: bool = True, + ) -> None: ... + def includeBranchrule( + self, + branchrule: Branchrule, + name: str, + desc: str, + priority: int, + maxdepth: int, + maxbounddist: float, + ) -> None: ... + def includeConshdlr( + self, + conshdlr: Conshdlr, + name: str, + desc: str, + sepapriority: int = 0, + enfopriority: int = 0, + chckpriority: int = 0, + sepafreq: int = -1, + propfreq: int = -1, + eagerfreq: int = 100, + maxprerounds: int = -1, + delaysepa: bool = False, + delayprop: bool = False, + needscons: bool = True, + proptiming: Incomplete = ..., + presoltiming: Incomplete = ..., + ) -> None: ... + def includeCutsel( + self, cutsel: Cutsel, name: str, desc: str, priority: int + ) -> None: ... + def includeDefaultPlugins(self) -> None: ... + def includeEventhdlr(self, eventhdlr: Eventhdlr, name: str, desc: str) -> None: ... + def includeHeur( + self, + heur: Heur, + name: str, + desc: str, + dispchar: str, + priority: int = 10000, + freq: int = 1, + freqofs: int = 0, + maxdepth: int = -1, + timingmask: Incomplete = ..., + usessubscip: bool = False, + ) -> None: ... + def includeIISfinder( + self, + iisfinder: IISfinder, + name: str, + desc: str, + priority: int = 10000, + freq: int = 1, + ) -> None: ... + def includeNodesel( + self, + nodesel: Nodesel, + name: str, + desc: str, + stdpriority: int, + memsavepriority: int, + ) -> None: ... + def includePresol( + self, + presol: Presol, + name: str, + desc: str, + priority: int, + maxrounds: int, + timing: Incomplete = ..., + ) -> None: ... + def includePricer( + self, + pricer: Pricer, + name: str, + desc: str, + priority: int = 1, + delay: bool = True, + ) -> None: ... + def includeProp( + self, + prop: Prop, + name: str, + desc: str, + presolpriority: int, + presolmaxrounds: int, + proptiming: Incomplete, + presoltiming: Incomplete = ..., + priority: int = 1, + freq: int = 1, + delay: bool = True, + ) -> None: ... + def includeReader(self, reader: Reader, name: str, desc: str, ext: str) -> None: ... + def includeRelax( + self, relax: Relax, name: str, desc: str, priority: int = 10000, freq: int = 1 + ) -> None: ... + def includeSepa( + self, + sepa: Sepa, + name: str, + desc: str, + priority: int = 0, + freq: int = 10, + maxbounddist: float = 1.0, + usessubscip: bool = False, + delay: bool = False, + ) -> None: ... + def includeSymhdlr( + self, + symhdlr: Symhdlr, + name: str, + desc: str, + priority: int = 0, + proppriority: int = 0, + sepapriority: int = 0, + presolpriority: int = 0, + propfreq: int = -1, + sepafreq: int = -1, + delayprop: bool = False, + delaysepa: bool = False, + maxbounddist: float = 1.0, + maxprerounds: int = -1, + proptiming: Incomplete = ..., + presoltiming: Incomplete = ..., + ) -> None: ... + def initBendersDefault(self, subproblems: Model | dict[Any, Model]) -> None: ... + def interruptSolve(self) -> None: ... + def isLPSolBasic(self) -> bool: ... + def isObjChangedProbing(self) -> bool: ... + def isObjIntegral(self) -> bool: ... + def isReoptEnabled(self) -> bool: ... + def lpiGetIterations(self) -> int: ... + def markDoNotAggrVar(self, var: Variable) -> None: ... + def markDoNotMultaggrVar(self, var: Variable) -> None: ... + def newProbingNode(self) -> None: ... + def optimize(self) -> None: ... + def optimizeNogil(self) -> None: ... + def presolve(self) -> None: ... + def printCons(self, constraint: Constraint) -> None: ... + def printExternalCodeVersions(self) -> None: ... + def printProblem( + self, ext: str = ".cip", trans: bool = False, genericnames: bool = False + ) -> None: ... + def printStatistics(self, filename: StrOrBytesPath | None = None) -> None: ... + def printStatisticsJson(self) -> None: ... + def printVersion(self) -> None: ... + def propagateProbing(self, maxproprounds: int) -> tuple[bool, int]: ... + def readParams(self, file: str | os.PathLike[str]) -> None: ... + def readProblem( + self, filename: str | os.PathLike[str], extension: str | None = None + ) -> None: ... + def redirectOutput(self) -> None: ... + def relax(self) -> None: ... + def repropagateNode(self, node: Node) -> None: ... + def resetParam(self, name: str) -> None: ... + def resetParams(self) -> None: ... + def restartSolve(self) -> None: ... + def separateSol( + self, + sol: Solution | None = None, + pretendroot: bool = False, + allowlocal: bool = True, + onlydelayed: bool = False, + ) -> tuple[bool, bool]: ... + def setBendersSubproblemIsConvex( + self, benders: Benders, probnumber: int, isconvex: bool = True + ) -> None: ... + def setBoolParam(self, name: str, value: bool) -> None: ... + def setCharParam(self, name: str, value: str) -> None: ... + def setCheck(self, cons: Constraint, newCheck: bool) -> None: ... + def setEmphasis(self, paraemphasis: Incomplete, quiet: bool = True) -> None: ... + def setEnforced(self, cons: Constraint, newEnf: bool) -> None: ... + def setHeurTiming(self, heurname: str, heurtiming: Incomplete) -> None: ... + def setHeuristics(self, setting: Incomplete) -> None: ... + def setInitial(self, cons: Constraint, newInit: bool) -> None: ... + def setIntParam(self, name: str, value: int) -> None: ... + def setLogfile(self, path: str | None) -> None: ... + def setLongintParam(self, name: str, value: int) -> None: ... + def setMaximize(self) -> None: ... + def setMinimize(self) -> None: ... + def setModifiable(self, cons: Constraint, newMod: bool) -> None: ... + def setObjIntegral(self) -> None: ... + def setParam(self, name: str, value: object) -> None: ... + def setParams(self, params: Mapping[str, bool | float | str]) -> None: ... + def setParamsCountsols(self) -> None: ... + def setPresolve(self, setting: Incomplete) -> None: ... + def setProbName(self, name: str) -> None: ... + def setRealParam(self, name: str, value: float) -> None: ... + def setRemovable(self, cons: Constraint, newRem: bool) -> None: ... + def setSeparating(self, setting: Incomplete) -> None: ... + def setStringParam(self, name: str, value: str) -> None: ... + def setupBendersSubproblem( + self, + probnumber: int, + benders: Benders | None = None, + solution: Solution | None = None, + checktype: Incomplete = ..., + ) -> None: ... + def solveBendersSubproblem( + self, + probnumber: int, + solvecip: bool, + benders: Benders | None = None, + solution: Solution | None = None, + ) -> tuple[bool, float]: ... + def solveConcurrent(self) -> None: ... + def solveProbingLP(self, itlim: int = -1) -> tuple[bool, bool]: ... + def solveProbingLPWithPricing( + self, + pretendroot: bool = False, + displayinfo: bool = False, + maxpricerounds: int = -1, + ) -> tuple[bool, bool]: ... + def startProbing(self) -> None: ... + def startStrongbranch(self) -> None: ... + def to_ptr(self, give_ownership: bool) -> CapsuleType: ... + def translateSubSol( + self, sub_model: BaseModel, sol: Solution, heur: Heur + ) -> Solution: ... + def updateBendersLowerbounds( + self, lowerbounds: dict[int, float], benders: Benders | None = None + ) -> None: ... + def updateVarPseudocost( + self, var: Variable, valdelta: float, objdelta: float, weight: float + ) -> None: ... + def version(self) -> float: ... + def writeName(self, var: Variable) -> None: ... + def writeParams( + self, + filename: str | os.PathLike[str] = "param.set", + comments: bool = True, + onlychanged: bool = True, + verbose: bool = True, + ) -> None: ... + def writeProblem( + self, + filename: str | os.PathLike[str] | None = "model.cip", + trans: bool = False, + genericnames: bool = False, + verbose: bool = True, + ) -> None: ... + def writeStatistics(self, filename: StrOrBytesPath = "origprob.stats") -> None: ... + def writeStatisticsJson( + self, filename: StrOrBytesPath = "origprob.stats.json" + ) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __gt__(self, other: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __le__(self, other: object, /) -> bool: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def getConsVars(self, constraint: Constraint) -> list[Variable] | None: ... + +class Model(BaseModel): + def _createConsGenNonlinear( + self, cons: ExprCons, **kwargs: Incomplete + ) -> Constraint: ... + def _createConsLinear( + self, lincons: ExprCons, **kwargs: Incomplete + ) -> Constraint: ... + def _createConsNonlinear( + self, cons: ExprCons, **kwargs: Incomplete + ) -> Constraint: ... + def _createConsQuadratic( + self, quadcons: ExprCons, **kwargs: Incomplete + ) -> Constraint: ... + def addCoefKnapsack( + self, cons: Constraint, var: Variable, weight: float + ) -> None: ... + def addCoefLinear(self, cons: Constraint, var: Variable, value: float) -> None: ... + def addCoefLogicor(self, logicor_cons: Constraint, var: Variable) -> None: ... + def addCons( + self, + cons: ExprCons, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + modifiable: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addConsAnd( + self, + vars: Sequence[Variable], + resvar: Variable, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + modifiable: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addConsCardinality( + self, + consvars: Sequence[Variable], + cardval: int, + indvars: Sequence[Variable] | None = None, + weights: Sequence[float] | None = None, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addConsCoeff(self, cons: Constraint, var: Variable, coeff: float) -> None: ... + def addConsCumulative( + self, + vars: Sequence[Variable], + durations: Sequence[int], + demands: Sequence[int], + capacity: int, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + modifiable: bool = False, + propagate: bool = True, + local: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addConsDisjunction( + self, + conss: Iterable[ExprCons], + name: str = "", + initial: bool = True, + relaxcons: Constraint | None = None, + enforce: bool = True, + check: bool = True, + local: bool = False, + modifiable: bool = False, + dynamic: bool = False, + ) -> Constraint: ... + def addConsElemDisjunction( + self, disj_cons: Constraint, cons: Constraint + ) -> Constraint: ... + def addConsIndicator( + self, + cons: ExprCons, + binvar: Variable | None = None, + activeone: bool = True, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + dynamic: bool = False, + removable: bool = False, + stickingatnode: bool = False, + ) -> Constraint: ... + def addConsLinear( + self, + vars: Sequence[Variable], + vals: Sequence[float], + lhs: float | None = None, + rhs: float | None = None, + name: str = "", + initial: bool = True, + separate: bool = True, + enforce: bool = True, + check: bool = True, + propagate: bool = True, + local: bool = False, + modifiable: bool = False, + dynamic: bool = False, + removable: bool = False, stickingatnode: bool = False, ) -> Constraint: ... def addConsKnapsack( @@ -944,40 +1621,10 @@ class Model: removable: bool = False, stickingatnode: bool = False, ) -> Constraint: ... - def addConss( - self, - conss: Iterable[ExprCons] | MatrixExprCons, - name: str | Iterable[str] = "", - initial: bool | Iterable[bool] = True, - separate: bool | Iterable[bool] = True, - enforce: bool | Iterable[bool] = True, - check: bool | Iterable[bool] = True, - propagate: bool | Iterable[bool] = True, - local: bool | Iterable[bool] = False, - modifiable: bool | Iterable[bool] = False, - dynamic: bool | Iterable[bool] = False, - removable: bool | Iterable[bool] = False, - stickingatnode: bool | Iterable[bool] = False, - ) -> list[Constraint]: ... def addCut(self, cut: Row, forcecut: bool = False) -> bool: ... def addExprNonlinear( self, cons: Constraint, expr: Expr | GenExpr, coef: float ) -> None: ... - def addMatrixCons( - self, - cons: ExprCons | MatrixExprCons, - name: str | np.ndarray = "", - initial: bool | np.ndarray = True, - separate: bool | np.ndarray = True, - enforce: bool | np.ndarray = True, - check: bool | np.ndarray = True, - propagate: bool | np.ndarray = True, - local: bool | np.ndarray = False, - modifiable: bool | np.ndarray = False, - dynamic: bool | np.ndarray = False, - removable: bool | np.ndarray = False, - stickingatnode: bool | np.ndarray = False, - ) -> Constraint | MatrixConstraint: ... def addMatrixConsDisjunction( self, conss: Iterable[ExprCons | MatrixExprCons], @@ -1006,23 +1653,10 @@ class Model: removable: bool | np.ndarray = False, stickingatnode: bool | np.ndarray = False, ) -> Constraint | MatrixConstraint: ... - def addMatrixVar( - self, - shape: int | tuple[int, ...], - name: str | np.ndarray = "", - vtype: str | np.ndarray = "C", - lb: float | np.ndarray | None = 0.0, - ub: float | np.ndarray | None = None, - obj: float | np.ndarray = 0.0, - pricedVar: bool | np.ndarray = False, - pricedVarScore: float | np.ndarray = 1.0, - ) -> MatrixVariable: ... def addObjoffset(self, offset: float, solutions: bool = False) -> None: ... def addPoolCut(self, row: Row) -> None: ... def addPyCons(self, cons: Constraint) -> None: ... def addRowDive(self, row: Row) -> None: ... - def addRowExact(self, rowexact: RowExact) -> None: ... - def addSol(self, solution: Solution, free: bool = True) -> bool: ... def addVar( self, name: str = "", @@ -1034,10 +1668,6 @@ class Model: pricedVarScore: float = 1.0, deletable: bool = False, ) -> Variable: ... - def addVarLocks(self, var: Variable, nlocksdown: int, nlocksup: int) -> None: ... - def addVarLocksType( - self, var: Variable, locktype: int, nlocksdown: int, nlocksup: int - ) -> None: ... def addVarSOS1(self, cons: Constraint, var: Variable, weight: float) -> None: ... def addVarSOS2(self, cons: Constraint, var: Variable, weight: float) -> None: ... def addVarToRow(self, row: Row, var: Variable, value: float) -> None: ... @@ -1051,21 +1681,8 @@ class Model: coefy: float = -1.0, rhs: float = 0.0, ) -> tuple[bool, bool, bool]: ... - def allColsInLP(self) -> bool: ... - def allowNegSlackExact(self) -> bool: ... def appendVarSOS1(self, cons: Constraint, var: Variable) -> None: ... def appendVarSOS2(self, cons: Constraint, var: Variable) -> None: ... - def applyCutsProbing(self) -> bool: ... - def attachEventHandlerCallback( - self, - callback: Incomplete, - events: Incomplete, - name: Incomplete = ..., - description: Incomplete = ..., - ) -> Incomplete: ... - def backtrackProbing(self, probingdepth: int) -> None: ... - def branchLPExact(self) -> Incomplete: ... - def branchVar(self, variable: Variable) -> tuple[Node, Node | None, Node]: ... def branchVarVal( self, variable: Variable, value: float ) -> tuple[Node, Node | None, Node]: ... @@ -1074,27 +1691,7 @@ class Model: def calcNodeselPriority( self, variable: Variable, branchdir: Incomplete, targetvalue: float ) -> float: ... - def catchEvent(self, eventtype: Incomplete, eventhdlr: Eventhdlr) -> None: ... - def catchRowEvent( - self, row: Row, eventtype: Incomplete, eventhdlr: Eventhdlr - ) -> None: ... - def catchVarEvent( - self, var: Variable, eventtype: Incomplete, eventhdlr: Eventhdlr - ) -> None: ... - def checkBendersSubproblemOptimality( - self, solution: Solution, probnumber: int, benders: Benders | None = None - ) -> bool: ... def checkQuadraticNonlinear(self, cons: Constraint) -> bool: ... - def checkSol( - self, - solution: Solution, - printreason: bool = True, - completely: bool = False, - checkbounds: bool = True, - checkintegrality: bool = True, - checklprows: bool = True, - original: bool = False, - ) -> bool: ... def chgCapacityKnapsack(self, cons: Constraint, capacity: float | None) -> None: ... def chgCoefLinear(self, cons: Constraint, var: Variable, value: float) -> None: ... def chgLhs(self, cons: Constraint, lhs: float | None) -> None: ... @@ -1104,7 +1701,6 @@ class Model: def chgRhs(self, cons: Constraint, rhs: float | None) -> None: ... def chgRowLhsDive(self, row: Row, newlhs: float) -> None: ... def chgRowRhsDive(self, row: Row, newrhs: float) -> None: ... - def chgVarBranchPriority(self, var: Variable, priority: int) -> None: ... def chgVarLb(self, var: Variable, lb: float | None) -> None: ... def chgVarLbDive(self, var: Variable, newbound: float) -> None: ... def chgVarLbGlobal(self, var: Variable, lb: float | None) -> None: ... @@ -1112,19 +1708,11 @@ class Model: def chgVarLbProbing(self, var: Variable, lb: float | None) -> None: ... def chgVarObjDive(self, var: Variable, newobj: float) -> None: ... def chgVarObjProbing(self, var: Variable, newobj: float) -> None: ... - def chgVarType(self, var: Variable, vtype: str) -> None: ... def chgVarUb(self, var: Variable, ub: float | None) -> None: ... def chgVarUbDive(self, var: Variable, newbound: float) -> None: ... def chgVarUbGlobal(self, var: Variable, ub: float | None) -> None: ... def chgVarUbNode(self, node: Node, var: Variable, ub: float | None) -> None: ... def chgVarUbProbing(self, var: Variable, ub: float | None) -> None: ... - def computeBestSolSubproblems(self) -> None: ... - def constructLP(self) -> bool: ... - def copyLargeNeighborhoodSearch( - self, to_fix: Sequence[Variable], fix_vals: Sequence[float] - ) -> Model: ... - def count(self) -> None: ... - def createChild(self, nodeselprio: float, estimate: float) -> Node: ... def createCons( self, conshdlr: Conshdlr, @@ -1176,29 +1764,9 @@ class Model: ) -> Row: ... def createOrigSol(self, heur: Heur | None = None) -> Solution: ... def createPartialSol(self, heur: Heur | None = None) -> Solution: ... - def createProbBasic(self, problemName: str = "model") -> None: ... def createSol(self, heur: Heur | None = None, initlp: bool = False) -> Solution: ... - def cutoffNode(self, node: Node) -> None: ... - def deactivatePricer(self, pricer: Pricer) -> None: ... def delCoefLinear(self, cons: Constraint, var: Variable) -> None: ... - def delCons(self, cons: Constraint) -> None: ... - def delConsLocal(self, cons: Constraint) -> None: ... - def delVar(self, var: Variable) -> bool: ... - def disableDebugSol(self) -> None: ... - def disablePropagation(self, onlyroot: bool = False) -> None: ... - def dropEvent(self, eventtype: Incomplete, eventhdlr: Eventhdlr) -> None: ... - def dropRowEvent( - self, row: Row, eventtype: Incomplete, eventhdlr: Eventhdlr - ) -> None: ... - def dropVarEvent( - self, var: Variable, eventtype: Incomplete, eventhdlr: Eventhdlr - ) -> None: ... - def enableDebugSol(self) -> None: ... - def enableExactSolving(self, enable: bool) -> None: ... - def enableReoptimization(self, enable: bool = True) -> None: ... def endDive(self) -> None: ... - def endProbing(self) -> None: ... - def endStrongbranch(self) -> None: ... def epsilon(self) -> float: ... def feasCeil(self, value: float) -> float: ... def feasFloor(self, value: float) -> float: ... @@ -1209,144 +1777,45 @@ class Model: def fixVarProbing(self, var: Variable, fixedval: float) -> None: ... def flushRowExtensions(self, row: Row) -> None: ... def frac(self, value: float) -> float: ... - def free(self) -> None: ... - @deprecated( - "Deprecated since 5.7.0; Benders subproblems are freed automatically when the master Model is deallocated." - ) - def freeBendersSubproblems(self) -> None: ... - def freeProb(self) -> None: ... - def freeReoptSolve(self) -> None: ... - def freeSol(self, solution: Solution) -> None: ... - def freeTransform(self) -> None: ... - @staticmethod - def from_ptr(capsule: CapsuleType, take_ownership: bool) -> Model: ... - def generateIIS(self) -> IIS: ... def getActivity(self, cons: Constraint, sol: Solution | None = None) -> float: ... - def getBendersAuxiliaryVar( - self, probnumber: int, benders: Benders | None = None - ) -> Variable: ... - def getBendersSubproblem( - self, probnumber: int, benders: Benders | None = None - ) -> Model: ... - def getBendersVar( - self, var: Variable, benders: Benders | None = None, probnumber: int = -1 - ) -> Variable | None: ... - def getBestChild(self) -> Node | None: ... - def getBestLeaf(self) -> Node | None: ... - def getBestNode(self) -> Node | None: ... - def getBestSibling(self) -> Node | None: ... - def getBestSol(self) -> Solution | None: ... - def getBestboundNode(self) -> Node | None: ... - def getBipartiteGraphRepresentation( - self, - prev_col_features: Sequence[Sequence[float]] | None = None, - prev_edge_features: Sequence[Sequence[float]] | None = None, - prev_row_features: Sequence[Sequence[float]] | None = None, - static_only: bool = False, - suppress_warnings: bool = False, - ) -> tuple[ - list[list[float | None]], - list[list[float]], - list[list[float]], - dict[str, dict[str, int]], - ]: ... def getAvgLowerbound(self) -> float: ... def getAvgDualbound(self) -> float: ... - def getBranchScoreMultiple(self, var: Variable, gains: list[float]) -> float: ... def getCapacityKnapsack(self, cons: Constraint) -> int: ... - def getChildren(self) -> list[Node]: ... def getColRedCost(self, col: Column) -> float: ... - def getCondition(self, exact: bool = False) -> float: ... - def getConsNVars(self, constraint: Constraint) -> int: ... def getConsVals(self, constraint: Constraint) -> list[float] | None: ... - def getConsVars(self, constraint: Constraint) -> list[Variable] | None: ... - def getConss(self, transformed: bool = True) -> list[Constraint]: ... - def getFocusNode(self) -> Node | None: ... - def getCountedSols(self) -> list[dict[str, int]]: ... - def getCurrentNode(self) -> Node | None: ... def getCutEfficacy(self, cut: Row, sol: Solution | None = None) -> float: ... def getCutLPSolCutoffDistance(self, cut: Row, sol: Solution) -> float: ... def getCutoffbound(self) -> float: ... def getUpperbound(self) -> float: ... - def getDepth(self) -> int: ... - def getDeterministicTime(self) -> float: ... def getFirstPrimalBound(self) -> float: ... @deprecated("Use Model.getDualsolLinear(cons) instead.") def getDualMultiplier(self, cons: Constraint) -> float: ... - def getDualSolVal( - self, cons: Constraint, boundconstraint: bool = False - ) -> float: ... - def getDualbound(self) -> float: ... - def getDualboundRoot(self) -> float: ... - def getLowerboundRoot(self) -> float: ... - def getDualfarkasKnapsack(self, cons: Constraint) -> float: ... - def getDualfarkasLinear(self, cons: Constraint) -> float: ... - def getDualfarkasLogicor(self, logicor_cons: Constraint) -> float: ... - def getDualsolKnapsack(self, cons: Constraint) -> float: ... - def getDualsolLinear(self, cons: Constraint) -> float: ... - def getDualsolLogicor(self, logicor_cons: Constraint) -> float: ... - def getGap(self) -> float: ... - def getHeurTiming(self, heurname: str) -> Incomplete: ... - def getIIS(self) -> IIS: ... - def getLPBInvARow(self, row: int) -> list[float]: ... - def getLPBInvRow(self, row: int) -> list[float]: ... - def getLPBasisInd(self) -> list[int]: ... - def getLPBranchCands( - self, - ) -> tuple[list[Variable], list[float], list[float], int, int, int]: ... - def getLPColsData(self) -> list[Column]: ... - def getLPObjVal(self) -> float: ... - def getLPRowsData(self) -> list[Row]: ... - def getLPSolstat(self) -> Incomplete: ... - def getLeaves(self) -> list[Node]: ... - def getLhs(self, cons: Constraint) -> float: ... - def getLinearConsIndicator(self, cons: Constraint) -> Constraint | None: ... - def getLocalEstimate(self, original: bool = False) -> float: ... - def getLowerbound(self) -> float: ... - def getMajorVersion(self) -> int: ... - def getMaxDepth(self) -> int: ... - def getMaxTotalDepth(self) -> int: ... - def getNBacktracks(self) -> int: ... - def getMinorVersion(self) -> int: ... - def getNBestSolsFound(self) -> int: ... - def getNBinVars(self) -> int: ... - def getNChildren(self) -> int: ... - def getNConss(self, transformed: bool = True) -> int: ... - def getNContVars(self) -> int: ... - def getNCountedSols(self) -> int: ... - def getNCuts(self) -> int: ... - def getNCutsApplied(self) -> int: ... - def getNFeasibleLeaves(self) -> int: ... - def getNImplVars(self) -> int: ... - def getNInfeasibleLeaves(self) -> int: ... - def getNObjlimLeaves(self) -> int: ... - def getNIntVars(self) -> int: ... - def getNLPBranchCands(self) -> int: ... - def getNLPCols(self) -> int: ... - def getNLPIterations(self) -> int: ... - def getNLPRows(self) -> int: ... - def getNLPs(self) -> int: ... - def getMemUsed(self) -> int: ... - def getMemTotal(self) -> int: ... - def getMemExternEstim(self) -> int: ... - def getNLeaves(self) -> int: ... - def getNNodesLeft(self) -> int: ... - def getNLimSolsFound(self) -> int: ... + def getDualSolVal( + self, cons: Constraint, boundconstraint: bool = False + ) -> float: ... + def getDualbound(self) -> float: ... + def getDualboundRoot(self) -> float: ... + def getLowerboundRoot(self) -> float: ... + def getDualfarkasKnapsack(self, cons: Constraint) -> float: ... + def getDualfarkasLinear(self, cons: Constraint) -> float: ... + def getDualfarkasLogicor(self, logicor_cons: Constraint) -> float: ... + def getDualsolKnapsack(self, cons: Constraint) -> float: ... + def getDualsolLinear(self, cons: Constraint) -> float: ... + def getDualsolLogicor(self, logicor_cons: Constraint) -> float: ... + def getLPBInvARow(self, row: int) -> list[float]: ... + def getLPBInvRow(self, row: int) -> list[float]: ... + def getLPBranchCands( + self, + ) -> tuple[list[Variable], list[float], list[float], int, int, int]: ... + def getLPColsData(self) -> list[Column]: ... + def getLPObjVal(self) -> float: ... + def getLPRowsData(self) -> list[Row]: ... + def getLPSolstat(self) -> Incomplete: ... + def getLhs(self, cons: Constraint) -> float: ... + def getLinearConsIndicator(self, cons: Constraint) -> Constraint | None: ... + def getLocalEstimate(self, original: bool = False) -> float: ... + def getLowerbound(self) -> float: ... def getNNlRows(self) -> int: ... - def getNNodeLPIterations(self) -> int: ... - def getNRuns(self) -> int: ... - def getNReoptRuns(self) -> int: ... - def addNNodes(self, nnodes: int) -> None: ... - def getNNodes(self) -> int: ... - def getNReaders(self) -> int: ... - def getNSepaRounds(self) -> int: ... - def getNSiblings(self) -> int: ... - def getNSols(self) -> int: ... - def getNSolsFound(self) -> int: ... - def getNStrongbranchLPIterations(self) -> int: ... - def getPrimalDualIntegral(self) -> float: ... - def getNTotalNodes(self) -> int: ... - def getNVars(self, transformed: bool = True) -> int: ... def getNVarsAnd(self, and_cons: Constraint) -> int: ... def getNVarsLogicor(self, logicor_cons: Constraint) -> int: ... def getNlRowActivityBounds(self, nlrow: NLRow) -> tuple[float, float]: ... @@ -1357,251 +1826,68 @@ class Model: self, nlrow: NLRow, sol: Solution | None = None ) -> float: ... def getNlRows(self) -> list[NLRow]: ... - def getObjVal(self, original: bool = True) -> float: ... def getObjective(self) -> Expr: ... - def getObjectiveSense(self) -> Literal["maximize", "minimize", "unknown"]: ... def getObjlimit(self) -> float: ... def getObjoffset(self, original: bool = True) -> float: ... - def getOpenNodes(self) -> tuple[list[Node], list[Node], list[Node]]: ... - def getParam(self, name: str) -> bool | int | float | str: ... - def getParams(self) -> dict[str, bool | int | float | str]: ... - def getPlungeDepth(self) -> int: ... - def getPresolvingTime(self) -> float: ... def getPrimalRay(self) -> list[float]: ... def getPrimalRayVal(self, var: Variable) -> float: ... def getPrimalbound(self) -> float: ... - def getPrioChild(self) -> Node | None: ... - def getPrioSibling(self) -> Node | None: ... - def getProbName(self) -> str: ... - def getProbingDepth(self) -> int: ... - def getPseudoBranchCands(self) -> tuple[list[Variable], int, int]: ... - def getReadingTime(self) -> float: ... def getResultantAnd(self, and_cons: Constraint) -> Variable: ... def getRhs(self, cons: Constraint) -> float: ... def getRowActivity(self, row: Row) -> float: ... def getRowDualSol(self, row: Row) -> float: ... def getRowLPActivity(self, row: Row) -> float: ... - def getRowLinear(self, cons: Constraint) -> Row: ... - def getRowNumIntCols(self, row: Row) -> int: ... - def getRowObjParallelism(self, row: Row) -> float: ... - def getRowParallelism( - self, row1: Row, row2: Row, orthofunc: Literal[100, 101] = 101 - ) -> float: ... - def getSiblings(self) -> list[Node]: ... - def getSlack( - self, - cons: Constraint, - sol: Solution | None = None, - side: Literal["lhs", "rhs"] | None = None, - ) -> float: ... - def getSlackVarIndicator(self, cons: Constraint) -> Variable: ... - def getSolObjVal(self, sol: Solution | None, original: bool = True) -> float: ... - def getSolTime(self, sol: Solution) -> float: ... - @overload - def getSolVal(self, sol: Solution | None, expr: Expr | GenExpr) -> float: ... - @overload - def getSolVal(self, sol: Solution | None, expr: MatrixExpr) -> np.ndarray: ... - def getSols(self) -> list[Solution]: ... - def getSolvingTime(self) -> float: ... - def getStage(self) -> Incomplete: ... - def getStageName(self) -> str: ... - def getStatus( - self, - ) -> Literal[ - "optimal", - "timelimit", - "infeasible", - "unbounded", - "userinterrupt", - "inforunbd", - "nodelimit", - "totalnodelimit", - "stallnodelimit", - "gaplimit", - "memlimit", - "sollimit", - "bestsollimit", - "restartlimit", - "primallimit", - "duallimit", - "unknown", - ]: ... - def getTechVersion(self) -> int: ... - def getTermsQuadratic( - self, cons: Constraint - ) -> tuple[ - list[tuple[Variable, Variable, float]], - list[tuple[Variable, float, float]], - list[tuple[Variable, float]], - ]: ... - def getTotalTime(self) -> float: ... - def getTransformedCons(self, cons: Constraint) -> Constraint: ... - def getTransformedVar(self, var: Variable) -> Variable: ... - def getTreesizeEstimation(self) -> float: ... - @overload - def getVal(self, expr: Expr | GenExpr) -> float: ... - @overload - def getVal(self, expr: MatrixExpr) -> np.ndarray: ... - def getValsLinear(self, cons: Constraint) -> dict[str, float]: ... - def getVarDict(self, transformed: bool = False) -> dict[str, float]: ... - def getVarLbDive(self, var: Variable) -> float: ... - def getVarPseudocost(self, var: Variable, branchdir: Incomplete) -> float: ... - def getVarPseudocostScore(self, var: Variable, solVal: float) -> float: ... - def getVarRedcost(self, var: Variable) -> float: ... - def getVarStrongbranch( - self, - var: Variable, - itlim: int, - idempotent: bool = False, - integral: bool = False, - ) -> tuple[float, float, bool, bool, bool, bool, bool, bool, bool]: ... - def getVarStrongbranchLast( - self, var: Variable - ) -> tuple[float, float, bool, bool, float, float]: ... - def getVarStrongbranchNode(self, var: Variable) -> int: ... - def getVarUbDive(self, var: Variable) -> float: ... - def getVars(self, transformed: bool = False) -> list[Variable]: ... - def getVarsAnd(self, and_cons: Constraint) -> list[Variable]: ... - def getVarsLogicor(self, logicor_cons: Constraint) -> list[Variable]: ... - def getWeightsKnapsack(self, cons: Constraint) -> dict[str, int]: ... - def hasPrimalRay(self) -> bool: ... - def hideOutput(self, quiet: bool = True) -> None: ... - def inProbing(self) -> bool: ... - def inRepropagation(self) -> bool: ... - def includeBenders( - self, - benders: Benders, - name: str, - desc: str, - priority: int = 1, - cutlp: bool = True, - cutpseudo: bool = True, - cutrelax: bool = True, - shareaux: bool = False, - ) -> None: ... - def includeBendersDefaultCuts(self, benders: Benders) -> None: ... - def includeBenderscut( - self, - benders: Benders, - benderscut: Benderscut, - name: str, - desc: str, - priority: int = 1, - islpcut: bool = True, - ) -> None: ... - def includeBranchrule( - self, - branchrule: Branchrule, - name: str, - desc: str, - priority: int, - maxdepth: int, - maxbounddist: float, - ) -> None: ... - def includeConshdlr( - self, - conshdlr: Conshdlr, - name: str, - desc: str, - sepapriority: int = 0, - enfopriority: int = 0, - chckpriority: int = 0, - sepafreq: int = -1, - propfreq: int = -1, - eagerfreq: int = 100, - maxprerounds: int = -1, - delaysepa: bool = False, - delayprop: bool = False, - needscons: bool = True, - proptiming: Incomplete = ..., - presoltiming: Incomplete = ..., - ) -> None: ... - def includeCutsel( - self, cutsel: Cutsel, name: str, desc: str, priority: int - ) -> None: ... - def includeDefaultPlugins(self) -> None: ... - def includeEventhdlr(self, eventhdlr: Eventhdlr, name: str, desc: str) -> None: ... - def includeHeur( - self, - heur: Heur, - name: str, - desc: str, - dispchar: str, - priority: int = 10000, - freq: int = 1, - freqofs: int = 0, - maxdepth: int = -1, - timingmask: Incomplete = ..., - usessubscip: bool = False, - ) -> None: ... - def includeIISfinder( - self, - iisfinder: IISfinder, - name: str, - desc: str, - priority: int = 10000, - freq: int = 1, - ) -> None: ... - def includeNodesel( - self, - nodesel: Nodesel, - name: str, - desc: str, - stdpriority: int, - memsavepriority: int, - ) -> None: ... - def includePresol( - self, - presol: Presol, - name: str, - desc: str, - priority: int, - maxrounds: int, - timing: Incomplete = ..., - ) -> None: ... - def includePricer( - self, - pricer: Pricer, - name: str, - desc: str, - priority: int = 1, - delay: bool = True, - ) -> None: ... - def includeProp( - self, - prop: Prop, - name: str, - desc: str, - presolpriority: int, - presolmaxrounds: int, - proptiming: Incomplete, - presoltiming: Incomplete = ..., - priority: int = 1, - freq: int = 1, - delay: bool = True, - ) -> None: ... - def includeReader(self, reader: Reader, name: str, desc: str, ext: str) -> None: ... - def includeRelax( - self, relax: Relax, name: str, desc: str, priority: int = 10000, freq: int = 1 - ) -> None: ... - def includeSepa( + def getRowLinear(self, cons: Constraint) -> Row: ... + def getRowNumIntCols(self, row: Row) -> int: ... + def getRowObjParallelism(self, row: Row) -> float: ... + def getRowParallelism( + self, row1: Row, row2: Row, orthofunc: Literal[100, 101] = 101 + ) -> float: ... + def getSlack( self, - sepa: Sepa, - name: str, - desc: str, - priority: int = 0, - freq: int = 10, - maxbounddist: float = 1.0, - usessubscip: bool = False, - delay: bool = False, - ) -> None: ... + cons: Constraint, + sol: Solution | None = None, + side: Literal["lhs", "rhs"] | None = None, + ) -> float: ... + def getSlackVarIndicator(self, cons: Constraint) -> Variable: ... + def getSolObjVal(self, sol: Solution | None, original: bool = True) -> float: ... + @overload + def getSolVal(self, sol: Solution | None, expr: Expr | GenExpr) -> float: ... + @overload + def getSolVal(self, sol: Solution | None, expr: MatrixExpr) -> np.ndarray: ... + def getTermsQuadratic( + self, cons: Constraint + ) -> tuple[ + list[tuple[Variable, Variable, float]], + list[tuple[Variable, float, float]], + list[tuple[Variable, float]], + ]: ... + @overload + def getVal(self, expr: Expr | GenExpr) -> float: ... + @overload + def getVal(self, expr: MatrixExpr) -> np.ndarray: ... + def getValsLinear(self, cons: Constraint) -> dict[str, float]: ... + def getVarDict(self, transformed: bool = False) -> dict[str, float]: ... + def getVarLbDive(self, var: Variable) -> float: ... + def getVarRedcost(self, var: Variable) -> float: ... + def getVarStrongbranch( + self, + var: Variable, + itlim: int, + idempotent: bool = False, + integral: bool = False, + ) -> tuple[float, float, bool, bool, bool, bool, bool, bool, bool]: ... + def getVarStrongbranchLast( + self, var: Variable + ) -> tuple[float, float, bool, bool, float, float]: ... + def getVarUbDive(self, var: Variable) -> float: ... + def getVarsAnd(self, and_cons: Constraint) -> list[Variable]: ... + def getVarsLogicor(self, logicor_cons: Constraint) -> list[Variable]: ... + def getWeightsKnapsack(self, cons: Constraint) -> dict[str, int]: ... def infinity(self) -> float: ... - def initBendersDefault(self, subproblems: Model | dict[Any, Model]) -> None: ... - def interruptSolve(self) -> None: ... def isAndConsSorted(self, and_cons: Constraint) -> bool: ... def isCutEfficacious(self, cut: Row, sol: Solution | None = None) -> bool: ... def isEQ(self, val1: float, val2: float) -> bool: ... - def isExact(self) -> bool: ... def isFeasEQ(self, val1: float, val2: float) -> bool: ... def isFeasGE(self, val1: float, val2: float) -> bool: ... def isFeasGT(self, val1: float, val2: float) -> bool: ... @@ -1617,75 +1903,20 @@ class Model: def isInfinity(self, value: float) -> bool: ... def isIntegral(self, value: float) -> bool: ... def isLE(self, val1: float, val2: float) -> bool: ... - def isLPSolBasic(self) -> bool: ... def isLT(self, val1: float, val2: float) -> bool: ... def isNLPConstructed(self) -> bool: ... def isNegative(self, val: float) -> bool: ... - def isObjChangedProbing(self) -> bool: ... - def isObjIntegral(self) -> bool: ... def isPositive(self, val: float) -> bool: ... - def isReoptEnabled(self) -> bool: ... def isZero(self, value: float) -> bool: ... - def lpiGetIterations(self) -> int: ... - def markDoNotAggrVar(self, var: Variable) -> None: ... - def markDoNotMultaggrVar(self, var: Variable) -> None: ... - def newProbingNode(self) -> None: ... - def optimize(self) -> None: ... - def optimizeNogil(self) -> None: ... - def presolve(self) -> None: ... def printBestSol(self, write_zeros: bool = False) -> None: ... - def printCons(self, constraint: Constraint) -> None: ... - def printExternalCodeVersions(self) -> None: ... def printNlRow(self, nlrow: NLRow) -> None: ... - def printProblem( - self, ext: str = ".cip", trans: bool = False, genericnames: bool = False - ) -> None: ... def printRow(self, row: Row) -> None: ... def printSol( self, solution: Solution | None = None, write_zeros: bool = False ) -> None: ... - def printStatistics(self, filename: StrOrBytesPath | None = None) -> None: ... - def printStatisticsJson(self) -> None: ... - def printVersion(self) -> None: ... - def propagateProbing(self, maxproprounds: int) -> tuple[bool, int]: ... - def readParams(self, file: str | os.PathLike[str]) -> None: ... - def readProblem( - self, filename: str | os.PathLike[str], extension: str | None = None - ) -> None: ... def readSol(self, filename: str | os.PathLike[str]) -> None: ... def readSolFile(self, filename: str | os.PathLike[str]) -> Solution: ... - def redirectOutput(self) -> None: ... - def relax(self) -> None: ... def releaseRow(self, row: Row) -> None: ... - def repropagateNode(self, node: Node) -> None: ... - def resetParam(self, name: str) -> None: ... - def resetParams(self) -> None: ... - def restartSolve(self) -> None: ... - def separateSol( - self, - sol: Solution | None = None, - pretendroot: bool = False, - allowlocal: bool = True, - onlydelayed: bool = False, - ) -> tuple[bool, bool]: ... - def setBendersSubproblemIsConvex( - self, benders: Benders, probnumber: int, isconvex: bool = True - ) -> None: ... - def setBoolParam(self, name: str, value: bool) -> None: ... - def setCharParam(self, name: str, value: str) -> None: ... - def setCheck(self, cons: Constraint, newCheck: bool) -> None: ... - def setEmphasis(self, paraemphasis: Incomplete, quiet: bool = True) -> None: ... - def setEnforced(self, cons: Constraint, newEnf: bool) -> None: ... - def setHeurTiming(self, heurname: str, heurtiming: Incomplete) -> None: ... - def setHeuristics(self, setting: Incomplete) -> None: ... - def setInitial(self, cons: Constraint, newInit: bool) -> None: ... - def setIntParam(self, name: str, value: int) -> None: ... - def setLogfile(self, path: str | None) -> None: ... - def setLongintParam(self, name: str, value: int) -> None: ... - def setMaximize(self) -> None: ... - def setMinimize(self) -> None: ... - def setModifiable(self, cons: Constraint, newMod: bool) -> None: ... - def setObjIntegral(self) -> None: ... def setObjective( self, expr: Expr | SupportsFloat, @@ -1693,44 +1924,11 @@ class Model: clear: bool | Literal["true"] = "true", # TODO: typo? ) -> None: ... def setObjlimit(self, objlimit: float) -> None: ... - def setParam(self, name: str, value: object) -> None: ... - def setParams(self, params: Mapping[str, bool | float | str]) -> None: ... - def setParamsCountsols(self) -> None: ... - def setPresolve(self, setting: Incomplete) -> None: ... - def setProbName(self, name: str) -> None: ... - def setRealParam(self, name: str, value: float) -> None: ... def setRelaxSolVal(self, var: Variable, val: float) -> None: ... - def setRemovable(self, cons: Constraint, newRem: bool) -> None: ... - def setSeparating(self, setting: Incomplete) -> None: ... def setSolVal(self, solution: Solution, var: Variable, val: float) -> None: ... - def setStringParam(self, name: str, value: str) -> None: ... - def setupBendersSubproblem( - self, - probnumber: int, - benders: Benders | None = None, - solution: Solution | None = None, - checktype: Incomplete = ..., - ) -> None: ... - def solveBendersSubproblem( - self, - probnumber: int, - solvecip: bool, - benders: Benders | None = None, - solution: Solution | None = None, - ) -> tuple[bool, float]: ... - def solveConcurrent(self) -> None: ... def solveDiveLP(self, itlim: int = -1) -> tuple[bool, bool]: ... - def solveProbingLP(self, itlim: int = -1) -> tuple[bool, bool]: ... - def solveProbingLPWithPricing( - self, - pretendroot: bool = False, - displayinfo: bool = False, - maxpricerounds: int = -1, - ) -> tuple[bool, bool]: ... def sortAndCons(self, and_cons: Constraint) -> None: ... def startDive(self) -> None: ... - def startProbing(self) -> None: ... - def startStrongbranch(self) -> None: ... def tightenVarLb( self, var: Variable, lb: float, force: bool = False ) -> tuple[bool, bool]: ... @@ -1743,10 +1941,6 @@ class Model: def tightenVarUbGlobal( self, var: Variable, ub: float, force: bool = False ) -> tuple[bool, bool]: ... - def to_ptr(self, give_ownership: bool) -> CapsuleType: ... - def translateSubSol( - self, sub_model: Model, sol: Solution, heur: Heur - ) -> Solution: ... def trySol( self, solution: Solution, @@ -1757,14 +1951,7 @@ class Model: checklprows: bool = True, free: bool = True, ) -> bool: ... - def updateBendersLowerbounds( - self, lowerbounds: dict[int, float], benders: Benders | None = None - ) -> None: ... def updateNodeLowerbound(self, node: Node, lb: float) -> None: ... - def updateVarPseudocost( - self, var: Variable, valdelta: float, objdelta: float, weight: float - ) -> None: ... - def version(self) -> float: ... def writeBestSol( self, filename: StrOrBytesPath = "origprob.sol", @@ -1783,44 +1970,61 @@ class Model: origobj: bool = False, lazyconss: bool = False, ) -> None: ... - def writeName(self, var: Variable) -> None: ... - def writeParams( - self, - filename: str | os.PathLike[str] = "param.set", - comments: bool = True, - onlychanged: bool = True, - verbose: bool = True, - ) -> None: ... - def writeProblem( - self, - filename: str | os.PathLike[str] | None = "model.cip", - trans: bool = False, - genericnames: bool = False, - verbose: bool = True, - ) -> None: ... def writeSol( self, solution: Solution, filename: StrOrBytesPath = "origprob.sol", write_zeros: bool = False, ) -> None: ... - def writeStatistics(self, filename: StrOrBytesPath = "origprob.stats") -> None: ... - def writeStatisticsJson( - self, filename: StrOrBytesPath = "origprob.stats.json" - ) -> None: ... def writeTransSol( self, solution: Solution, filename: StrOrBytesPath = "transprob.sol", write_zeros: bool = False, ) -> None: ... - def __eq__(self, other: object, /) -> bool: ... - def __ge__(self, other: object, /) -> bool: ... - def __gt__(self, other: object, /) -> bool: ... - def __hash__(self) -> int: ... - def __le__(self, other: object, /) -> bool: ... - def __lt__(self, other: object, /) -> bool: ... - def __ne__(self, other: object, /) -> bool: ... + def getBipartiteGraphRepresentation( + self, + prev_col_features: Sequence[Sequence[float]] | None = None, + prev_edge_features: Sequence[Sequence[float]] | None = None, + prev_row_features: Sequence[Sequence[float]] | None = None, + static_only: bool = False, + suppress_warnings: bool = False, + ) -> tuple[ + list[list[float | None]], + list[list[float]], + list[list[float]], + dict[str, dict[str, int]], + ]: ... + def copyLargeNeighborhoodSearch( + self, to_fix: Sequence[Variable], fix_vals: Sequence[float] + ) -> Model: ... + def addMatrixVar( + self, + shape: int | tuple[int, ...], + name: str | np.ndarray = "", + vtype: str | np.ndarray = "C", + lb: float | np.ndarray | None = 0.0, + ub: float | np.ndarray | None = None, + obj: float | np.ndarray = 0.0, + pricedVar: bool | np.ndarray = False, + pricedVarScore: float | np.ndarray = 1.0, + ) -> MatrixVariable: ... + def inferVarLbSym( + self, + var: Variable, + lb: float, + symcomp: SymComp, + inferinfo: int, + force: bool = False, + ) -> tuple[bool, bool]: ... + def inferVarUbSym( + self, + var: Variable, + ub: float, + symcomp: SymComp, + inferinfo: int, + force: bool = False, + ) -> tuple[bool, bool]: ... @disjoint_base class NLRow: @@ -1848,7 +2052,7 @@ class Node: def getDepth(self) -> int: ... def getDomchg(self) -> DomainChanges | None: ... def getEstimate(self) -> float: ... - def getLowerbound(self) -> float: ... + def getLowerbound(self) -> float | Fraction: ... def getNAddedConss(self) -> int: ... def getNDomchg(self) -> tuple[int, int, int]: ... def getNParentBranchings(self) -> int: ... @@ -2300,6 +2504,13 @@ class Row: class RowExact: data: Any def __init__(self) -> None: ... + def getCols(self) -> list[ColumnExact]: ... + def getConstant(self) -> Fraction: ... + def getLhs(self) -> Fraction | float: ... + def getNNonz(self) -> int: ... + def getRhs(self) -> Fraction | float: ... + def getVals(self) -> list[Fraction]: ... + def isInLP(self) -> bool: ... @disjoint_base class Sepa: @@ -2320,14 +2531,80 @@ class Solution: def __init__(self, raise_error: bool = True) -> None: ... def _checkStage(self, method: str) -> None: ... def getOrigin(self) -> Incomplete: ... + def isExact(self) -> bool: ... def retransform(self) -> None: ... - def translate(self, target: Model) -> Solution: ... + def translate(self, target: BaseModel) -> Solution: ... @overload def __getitem__(self, index: Expr | GenExpr, /) -> float: ... @overload def __getitem__(self, index: MatrixExpr, /) -> np.ndarray: ... def __setitem__(self, key: Variable, value: float, /) -> None: ... +@disjoint_base +class SymComp: + def __init__(self) -> None: ... + @property + def data(self) -> Incomplete: ... + @property + def name(self) -> str: ... + def ptr(self) -> int: ... + +@disjoint_base +class Symhdlr: + model: Incomplete + name: Incomplete + def __init__(self) -> None: ... + def symexit(self, symcomps: Incomplete) -> Incomplete: ... + def symexitsol(self, symcomps: Incomplete, restart: Incomplete) -> Incomplete: ... + def symfree(self) -> Incomplete: ... + def syminit(self, symcomps: Incomplete) -> Incomplete: ... + def syminitsol(self, symcomps: Incomplete) -> Incomplete: ... + def sympresol( + self, + symcomps: Incomplete, + nrounds: Incomplete, + presoltiming: Incomplete, + nnewfixedvars: Incomplete, + nnewaggrvars: Incomplete, + nnewchgvartypes: Incomplete, + nnewchgbds: Incomplete, + nnewholes: Incomplete, + nnewdelconss: Incomplete, + nnewaddconss: Incomplete, + nnewupgdconss: Incomplete, + nnewchgcoefs: Incomplete, + nnewchgsides: Incomplete, + result_dict: Incomplete, + ) -> Incomplete: ... + def symprop(self, symcomps: Incomplete, proptiming: Incomplete) -> Incomplete: ... + def symresprop( + self, + symcomp: Incomplete, + confvar: Incomplete, + inferinfo: Incomplete, + bdtype: Incomplete, + relaxedbd: Incomplete, + ) -> Incomplete: ... + def symsepalp( + self, symcomps: Incomplete, allowlocal: Incomplete, depth: Incomplete + ) -> Incomplete: ... + def symsepasol( + self, + solution: Incomplete, + symcomps: Incomplete, + allowlocal: Incomplete, + depth: Incomplete, + ) -> Incomplete: ... + def symtryadd( + self, + symtype: Incomplete, + perms: Incomplete, + permvars: Incomplete, + permvardomcenter: Incomplete, + id: Incomplete, + allowbdchgs: Incomplete, + ) -> Incomplete: ... + class Statistics: status: str total_time: float diff --git a/src/pyscipopt/sepa.pxi b/src/pyscipopt/sepa.pxi index 22f64baac..0c45c2c0e 100644 --- a/src/pyscipopt/sepa.pxi +++ b/src/pyscipopt/sepa.pxi @@ -1,7 +1,7 @@ ##@file sepa.pxi #@brief Base class of the Separator Plugin cdef class Sepa: - cdef public Model model + cdef public BaseModel model cdef public str name def sepafree(self): diff --git a/src/pyscipopt/symhdlr.pxi b/src/pyscipopt/symhdlr.pxi new file mode 100644 index 000000000..1e49a65de --- /dev/null +++ b/src/pyscipopt/symhdlr.pxi @@ -0,0 +1,194 @@ +##@file symhdlr.pxi +#@brief Base class of the Symmetry Handler Plugin +cdef class SymComp: + @staticmethod + cdef create(SCIP_SYMCOMP* scip_symcomp): + if scip_symcomp == NULL: + raise Warning("cannot create SymComp with SCIP_SYMCOMP* == NULL") + symcomp = SymComp() + symcomp.scip_symcomp = scip_symcomp + return symcomp + + @property + def name(self): + return bytes(SCIPsymcompGetName(self.scip_symcomp)).decode('utf-8') + + @property + def data(self): + return SCIPsymcompGetData(self.scip_symcomp) + + def ptr(self): + return self.scip_symcomp + +cdef class Symhdlr: + cdef public Model model + cdef public str name + cdef list _symcompdata + + def symfree(self): + '''calls destructor and frees memory of symmetry handler''' + pass + + def syminit(self, symcomps): + '''initializes symmetry handler''' + pass + + def symexit(self, symcomps): + '''calls exit method of symmetry handler''' + pass + + def syminitsol(self, symcomps): + '''informs symmetry handler that the branch and bound process is being started''' + pass + + def symexitsol(self, symcomps, restart): + '''informs symmetry handler that the branch and bound process data is being freed''' + pass + + def symtryadd(self, symtype, perms, permvars, permvardomcenter, id, allowbdchgs): + '''tries to add a symmetry handling method for the given symmetries''' + raise NotImplementedError("symtryadd() is a fundamental callback and should be implemented in the derived class") + + def symsepalp(self, symcomps, allowlocal, depth): + '''separates the current LP solution''' + return {"result": SCIP_DIDNOTRUN} + + def symsepasol(self, solution, symcomps, allowlocal, depth): + '''separates the given primal solution''' + return {"result": SCIP_DIDNOTRUN} + + def symprop(self, symcomps, proptiming): + '''propagates domains''' + return {"result": SCIP_DIDNOTRUN} + + def symresprop(self, symcomp, confvar, inferinfo, bdtype, relaxedbd): + '''resolves the given conflicting bound, that was reduced by the given symmetry component''' + return {"result": SCIP_DIDNOTFIND} + + def sympresol(self, symcomps, nrounds, presoltiming, + nnewfixedvars, nnewaggrvars, nnewchgvartypes, nnewchgbds, nnewholes, + nnewdelconss, nnewaddconss, nnewupgdconss, nnewchgcoefs, nnewchgsides, result_dict): + '''executes presolving method of symmetry handler''' + pass + + +cdef Symhdlr getPySymhdlr(SCIP_SYMHDLR* symhdlr): + return SCIPsymhdlrGetData(symhdlr) + +cdef list getPySymComps(SCIP_SYMCOMP** symcomps, int nsymcomps): + return [SymComp.create(symcomps[i]) for i in range(nsymcomps)] + +cdef SCIP_RETCODE PySymhdlrTryAdd (SCIP* scip, SCIP_SYMHDLR* symhdlr, SYM_SYMTYPE symtype, int** perms, int nperms, + SCIP_VAR** permvars, int npermvars, SCIP_Real* permvardomcenter, SCIP_HASHMAP* permvarmap, + SYM_GRAPH* symgraph, int id, SCIP_SYMCOMPDATA** symcompdata, int* naddedconss, + SCIP_Bool allowbdchgs, int* nchgbds, SCIP_Bool* success) noexcept with gil: + cdef int permlen = npermvars if symtype == SYM_SYMTYPE_PERM else 2 * npermvars + PySymhdlr = getPySymhdlr(symhdlr) + pyperms = [[perms[p][i] for i in range(permlen)] for p in range(nperms)] + pypermvars = [Variable.create(permvars[i]) for i in range(npermvars)] + if permvardomcenter == NULL: + pydomcenter = None + else: + pydomcenter = [permvardomcenter[i] for i in range(npermvars)] + + result_dict = PySymhdlr.symtryadd(symtype, pyperms, pypermvars, pydomcenter, id, allowbdchgs) + assert isinstance(result_dict, dict), "symtryadd() must return a dictionary." + success[0] = result_dict.get("success", False) + naddedconss[0] = result_dict.get("naddedconss", 0) + nchgbds[0] = result_dict.get("nchgbds", 0) + if success[0]: + data = result_dict.get("data") + PySymhdlr._symcompdata.append(data) + symcompdata[0] = data + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrFree (SCIP* scip, SCIP_SYMHDLR* symhdlr) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + PySymhdlr.symfree() + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrInit (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + PySymhdlr.syminit(getPySymComps(symcomps, nsymcomps)) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrExit (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + PySymhdlr.symexit(getPySymComps(symcomps, nsymcomps)) + PySymhdlr._symcompdata.clear() + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrInitsol (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + PySymhdlr.syminitsol(getPySymComps(symcomps, nsymcomps)) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrExitsol (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, SCIP_Bool restart) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + PySymhdlr.symexitsol(getPySymComps(symcomps, nsymcomps), restart) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrSepaLP (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_RESULT* result, SCIP_Bool allowlocal, int depth) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + result_dict = PySymhdlr.symsepalp(getPySymComps(symcomps, nsymcomps), allowlocal, depth) + result[0] = result_dict.get("result", result[0]) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrSepaSol (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SOL* sol, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_RESULT* result, SCIP_Bool allowlocal, int depth) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + solution = Solution.create(scip, sol) + result_dict = PySymhdlr.symsepasol(solution, getPySymComps(symcomps, nsymcomps), allowlocal, depth) + result[0] = result_dict.get("result", result[0]) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrProp (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, + SCIP_PROPTIMING proptiming, SCIP_RESULT* result) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + result_dict = PySymhdlr.symprop(getPySymComps(symcomps, nsymcomps), proptiming) + result[0] = result_dict.get("result", result[0]) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrResProp (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP* symcomp, SCIP_VAR* infervar, int inferinfo, + SCIP_BOUNDTYPE boundtype, SCIP_BDCHGIDX* bdchgidx, SCIP_Real relaxedbd, SCIP_RESULT* result) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + confvar = Variable.create(infervar) + result_dict = PySymhdlr.symresprop(SymComp.create(symcomp), confvar, inferinfo, boundtype, relaxedbd) + result[0] = result_dict.get("result", result[0]) + return SCIP_OKAY + +cdef SCIP_RETCODE PySymhdlrPresol (SCIP* scip, SCIP_SYMHDLR* symhdlr, SCIP_SYMCOMP** symcomps, int nsymcomps, int nrounds, + SCIP_PRESOLTIMING presoltiming, int nnewfixedvars, int nnewaggrvars, int nnewchgvartypes, + int nnewchgbds, int nnewholes, int nnewdelconss, int nnewaddconss, int nnewupgdconss, + int nnewchgcoefs, int nnewchgsides, int* nfixedvars, int* naggrvars, int* nchgvartypes, + int* nchgbds, int* naddholes, int* ndelconss, int* naddconss, int* nupgdconss, + int* nchgcoefs, int* nchgsides, SCIP_RESULT* result) noexcept with gil: + PySymhdlr = getPySymhdlr(symhdlr) + result_dict = {} + result_dict["nfixedvars"] = nfixedvars[0] + result_dict["naggrvars"] = naggrvars[0] + result_dict["nchgvartypes"] = nchgvartypes[0] + result_dict["nchgbds"] = nchgbds[0] + result_dict["naddholes"] = naddholes[0] + result_dict["ndelconss"] = ndelconss[0] + result_dict["naddconss"] = naddconss[0] + result_dict["nupgdconss"] = nupgdconss[0] + result_dict["nchgcoefs"] = nchgcoefs[0] + result_dict["nchgsides"] = nchgsides[0] + result_dict["result"] = result[0] + PySymhdlr.sympresol(getPySymComps(symcomps, nsymcomps), nrounds, presoltiming, + nnewfixedvars, nnewaggrvars, nnewchgvartypes, nnewchgbds, nnewholes, + nnewdelconss, nnewaddconss, nnewupgdconss, nnewchgcoefs, nnewchgsides, result_dict) + result[0] = result_dict["result"] + nfixedvars[0] = result_dict["nfixedvars"] + naggrvars[0] = result_dict["naggrvars"] + nchgvartypes[0] = result_dict["nchgvartypes"] + nchgbds[0] = result_dict["nchgbds"] + naddholes[0] = result_dict["naddholes"] + ndelconss[0] = result_dict["ndelconss"] + naddconss[0] = result_dict["naddconss"] + nupgdconss[0] = result_dict["nupgdconss"] + nchgcoefs[0] = result_dict["nchgcoefs"] + nchgsides[0] = result_dict["nchgsides"] + return SCIP_OKAY diff --git a/tests/test_base_model.py b/tests/test_base_model.py new file mode 100644 index 000000000..b3be63665 --- /dev/null +++ b/tests/test_base_model.py @@ -0,0 +1,160 @@ +import re +from pathlib import Path + +import pytest + +from pyscipopt import BaseModel, Eventhdlr, Model + +SCIP_PXI = Path(__file__).resolve().parents[1] / "src" / "pyscipopt" / "scip.pxi" +MODEL_PXI = SCIP_PXI.with_name("model.pxi") + +BASE_MODEL_METHODS = frozenset({ + "_freescip", "_getStageNames", "activateBenders", "addBendersSubproblem", "addConss", + "addMatrixCons", "addNNodes", "addSol", "addVarLocks", + "addVarLocksType", "allColsInLP", "applyCutsProbing", "attachEventHandlerCallback", "backtrackProbing", + "branchVar", "catchEvent", "catchRowEvent", "catchVarEvent", "checkBendersSubproblemOptimality", + "checkSol", "chgVarBranchPriority", "chgVarType", "computeBestSolSubproblems", "constructLP", + "count", "createChild", "createProbBasic", "cutoffNode", + "data", "deactivatePricer", "delCons", "delConsLocal", "delVar", + "disableDebugSol", "disablePropagation", "dropEvent", "dropRowEvent", "dropVarEvent", + "enableDebugSol", "enableReoptimization", "endProbing", "endStrongbranch", "free", + "freeBendersSubproblems", "freeProb", "freeReoptSolve", "freeSol", "freeTransform", + "from_ptr", "generateIIS", "getBendersAuxiliaryVar", "getBendersSubproblem", "getBendersVar", + "getBestChild", "getBestLeaf", "getBestNode", "getBestSibling", "getBestSol", + "getBestboundNode", "getBranchScoreMultiple", "getChildren", "getCondition", + "getConsNVars", "getConsVars", "getConss", "getCountedSols", "getCurrentNode", "getDepth", + "getDeterministicTime", "getFocusNode", "getGap", "getHeurTiming", "getIIS", + "getLPBasisInd", "getLeaves", "getMajorVersion", "getMaxDepth", "getMaxTotalDepth", + "getMemExternEstim", "getMemTotal", "getMemUsed", "getMinorVersion", "getNBacktracks", + "getNBestSolsFound", "getNBinVars", "getNChildren", "getNConss", "getNContVars", + "getNCountedSols", "getNCuts", "getNCutsApplied", "getNFeasibleLeaves", "getNImplVars", + "getNInfeasibleLeaves", "getNIntVars", "getNLPBranchCands", "getNLPCols", "getNLPIterations", + "getNLPRows", "getNLPs", "getNLeaves", "getNLimSolsFound", "getNNodeLPIterations", + "getNNodes", "getNNodesLeft", "getNObjlimLeaves", "getNReaders", "getNReoptRuns", + "getNRuns", "getNSepaRounds", "getNSiblings", "getNSols", "getNSolsFound", + "getNStrongbranchLPIterations", "getNTotalNodes", "getNVars", "getObjVal", "getObjectiveSense", + "getOpenNodes", "getParam", "getParams", "getPlungeDepth", "getPresolvingTime", + "getPrimalDualIntegral", "getPrioChild", "getPrioSibling", "getProbName", "getProbingDepth", + "getPseudoBranchCands", "getReadingTime", "getSiblings", "getSolTime", "getSols", + "getSolvingTime", "getStage", "getStageName", "getStatus", "getTechVersion", + "getTotalTime", "getTransformedCons", "getTransformedVar", "getTreesizeEstimation", "getVarPseudocost", + "getVarPseudocostScore", "getVarStrongbranchNode", "getVars", "hasPrimalRay", "hideOutput", + "inProbing", "inRepropagation", "includeBenders", "includeBendersDefaultCuts", "includeBenderscut", + "includeBranchrule", "includeConshdlr", "includeCutsel", "includeDefaultPlugins", "includeEventhdlr", + "includeHeur", "includeIISfinder", "includeNodesel", "includePresol", "includePricer", + "includeProp", "includeReader", "includeRelax", "includeSepa", "includeSymhdlr", "initBendersDefault", + "interruptSolve", "isLPSolBasic", "isObjChangedProbing", "isObjIntegral", "isReoptEnabled", + "lpiGetIterations", "markDoNotAggrVar", "markDoNotMultaggrVar", "newProbingNode", "optimize", + "optimizeNogil", "presolve", "printCons", "printExternalCodeVersions", "printProblem", + "printStatistics", "printStatisticsJson", "printVersion", "propagateProbing", "readParams", + "readProblem", "redirectOutput", "relax", "repropagateNode", "resetParam", + "resetParams", "restartSolve", "separateSol", "setBendersSubproblemIsConvex", "setBoolParam", + "setCharParam", "setCheck", "setEmphasis", "setEnforced", "setHeurTiming", + "setHeuristics", "setInitial", "setIntParam", "setLogfile", "setLongintParam", + "setMaximize", "setMinimize", "setModifiable", "setObjIntegral", "setParam", + "setParams", "setParamsCountsols", "setPresolve", "setProbName", "setRealParam", + "setRemovable", "setSeparating", "setStringParam", "setupBendersSubproblem", "solveBendersSubproblem", + "solveConcurrent", "solveProbingLP", "solveProbingLPWithPricing", "startProbing", "startStrongbranch", + "to_ptr", "translateSubSol", "updateBendersLowerbounds", "updateVarPseudocost", "version", + "writeName", "writeParams", "writeProblem", "writeStatistics", "writeStatisticsJson", +}) + +SUBCLASS_CONTRACT = frozenset({"addCons", "getSolObjVal"}) + +FP_MARKERS = re.compile( + r"\bSCIP_Real\b|\bfloat\(|dtype=float|\bModel\b|\bExprCons\b|\bExpr\b|\bRow\b|\bColumn\b|\bNLRow\b|SCIPinfinity\(" +) + +FP_ALLOWED = frozenset({ + "addMatrixCons", "catchRowEvent", "create", "dropRowEvent", "freeBendersSubproblems", + "getBranchScoreMultiple", "getCondition", "setParam", "solveBendersSubproblem", +}) + +MEMBER_RE = re.compile(r"^ (?:def|cdef|cpdef)\b.*?(\w+)\s*\(") + + +def class_members(path, header): + if not path.exists(): + pytest.skip(f"{path.name} is not available in this checkout") + lines = path.read_text().splitlines() + start = lines.index(header) + end = start + 1 + while end < len(lines) and (not lines[end] or lines[end][0] in " \t#"): + end += 1 + members = {} + name = None + for line in lines[start + 1:end]: + match = MEMBER_RE.match(line) + if match: + name = match.group(1) + members.setdefault(name, []) + if name: + members[name].append(line) + stripped = {} + for name, body in members.items(): + text = re.sub(r'"""[\s\S]*?"""', "", "\n".join(body)) + stripped[name] = "\n".join(line.split("#")[0] for line in text.splitlines()) + return stripped + + +def test_base_model_surface_is_pinned(): + actual = {name for name in vars(BaseModel) if not name.startswith("__")} + assert actual == BASE_MODEL_METHODS + + +def test_subclass_contract_is_implemented_by_model(): + assert SUBCLASS_CONTRACT <= set(vars(Model)) + + +def test_base_model_calls_only_shared_methods(): + base = class_members(SCIP_PXI, "cdef class BaseModel:") + model_only = set(class_members(MODEL_PXI, "cdef class Model(BaseModel):")) - set(base) + offenders = {} + for name, body in base.items(): + calls = set(re.findall(r"self\.(\w+)\(", body)) + bad = sorted((calls & model_only) - SUBCLASS_CONTRACT) + if bad: + offenders[name] = bad + assert offenders == {} + + +def test_base_model_has_no_fp_markers(): + base = class_members(SCIP_PXI, "cdef class BaseModel:") + hits = {name for name, body in base.items() if FP_MARKERS.search(body)} + assert hits - FP_ALLOWED == set() + + +def test_model_subclass_and_mro(): + assert Model.__mro__[:2] == (Model, BaseModel) + + class MyModel(Model): + def __init__(self): + super().__init__("sub") + + m = MyModel() + x = m.addVar("x", lb=1) + m.setObjective(x) + m.hideOutput() + m.optimize() + assert m.getStatus() == "optimal" + assert m.getVal(x) == 1 + + +def test_from_ptr_returns_model(): + m = Model() + assert type(Model.from_ptr(m.to_ptr(False), False)) is Model + + +def test_plugin_sees_the_same_model_object(): + seen = [] + + class Watcher(Eventhdlr): + def eventinit(self): + seen.append(self.model) + + m = Model() + m.includeEventhdlr(Watcher(), "watcher", "") + m.addVar("x") + m.hideOutput() + m.optimize() + assert seen and seen[0] is m and isinstance(seen[0], BaseModel) diff --git a/tests/test_exact.py b/tests/test_exact.py new file mode 100644 index 000000000..bc9a2ee8b --- /dev/null +++ b/tests/test_exact.py @@ -0,0 +1,275 @@ +from fractions import Fraction + +import pytest + +from pyscipopt import (SCIP_EVENTTYPE, SCIP_LPSOLSTAT, SCIP_PARAMSETTING, BaseModel, Eventhdlr, Model, + ExactModel, ExactVariable, Variable) + + +def _exact_supported(): + try: + ExactModel() + except ValueError: + return False + return True + + +pytestmark = pytest.mark.skipif(not _exact_supported(), reason="SCIP was built without exact solving support") + + +def test_exact_model(): + m = ExactModel() + assert isinstance(m, BaseModel) + assert not hasattr(Model(), "chgVarObj") + assert not hasattr(m, "addVarExact") + with pytest.raises(TypeError): + Model(exact=True) + with pytest.raises(TypeError): + ExactModel(sourceModel=m) + assert isinstance(Model.from_ptr(m.to_ptr(False), False), ExactModel) + + x = m.addVar("x", lb=Fraction(1, 3), ub=Fraction(10, 3), obj=-1) + assert isinstance(x, ExactVariable) + assert all(isinstance(v, ExactVariable) for v in m.getVars()) + assert x.getLbOriginal() == Fraction(1, 3) + assert x.getLbGlobal() == Fraction(1, 3) + assert x.getUbLocal() == Fraction(10, 3) + assert x.getUbOriginal() == Fraction(10, 3) + assert x.getObj() == -1 + y = m.addVar("y", lb=None, ub=float("inf")) + assert y.getLbOriginal() == -float("inf") + assert y.getUbOriginal() == float("inf") + b = m.addVar("b", vtype="B") + assert b.getUbOriginal() == 1 + assert b.vtype() == "BINARY" + + m.chgVarObj(x, Fraction(-1, 7)) + m.chgVarLb(x, None) + m.chgVarUb(x, Fraction(5, 2)) + assert x.getObj() == Fraction(-1, 7) + assert x.getLbOriginal() == -float("inf") + assert x.getUbOriginal() == Fraction(5, 2) + + with pytest.raises(ValueError): + m.addVar("bad", lb=2, ub=1) + with pytest.raises(Warning): + m.addVar("bad", vtype="Q") + with pytest.raises(OverflowError): + m.addVar("bad", obj=float("inf")) + with pytest.raises(ValueError): + m.addVar("bad", pricedVar=True) + with pytest.raises(TypeError): + m.setObjective(x) + with pytest.raises(TypeError): + m.setObjective(Fraction(1, 3) * x) + + n = Model() + z = n.addVar("z", lb=0.5) + assert isinstance(z.getLbOriginal(), float) + assert type(z) is Variable + assert not hasattr(z, "getLbOriginalExact") + assert not hasattr(x, "getLbOriginalExact") + + +RAISING = ["tightenVarLbGlobal", "tightenVarUbGlobal", "chgVarObjDive", "chgVarLbProbing", + "chgVarUbProbing", "chgVarObjProbing", "fixVarProbing"] + + +def test_bound_changes(): + m = ExactModel() + x = m.addVar("x", lb=0, ub=10) + m.chgVarLbGlobal(x, Fraction(1, 3)) + m.chgVarUbGlobal(x, Fraction(7, 2)) + assert x.getLbGlobal() == Fraction(1, 3) + assert x.getUbGlobal() == Fraction(7, 2) + assert m.tightenVarLb(x, Fraction(1, 2)) == (False, True) + assert x.getLbLocal() == Fraction(1, 2) + assert m.fixVar(x, Fraction(3, 2)) == (False, True) + assert x.getLbLocal() == x.getUbLocal() == Fraction(3, 2) + for name in RAISING: + with pytest.raises(ValueError): + getattr(m, name)(x, 1) + with pytest.raises(ValueError): + m.chgVarLbNode(None, x, 1) + with pytest.raises(ValueError): + m.chgVarUbNode(None, x, 1) + with pytest.raises(ValueError): + m.setObjlimit(Fraction(1, 3)) + assert not hasattr(m, "chgVarLbExact") + + +def test_linear_constraints(): + m = ExactModel() + x = m.addVar("x") + y = m.addVar("y") + c = m.addConsLinear([x, y], [Fraction(1, 3), Fraction(1, 10)], None, Fraction(2, 3), name="c") + assert c.name == "c" + assert m.getLhs(c) == -float("inf") + assert m.getRhs(c) == Fraction(2, 3) + assert m.getValsLinear(c) == {"x": Fraction(1, 3), "y": Fraction(1, 10)} + assert m.getConsVals(c) == [Fraction(1, 3), Fraction(1, 10)] + assert [v.name for v in m.getConsVars(c)] == ["x", "y"] + assert all(isinstance(v, ExactVariable) for v in m.getConsVars(c)) + + m.chgCoefLinear(c, y, Fraction(1, 7)) + m.chgLhs(c, 0) + m.chgRhs(c, None) + z = m.addVar("z") + m.addCoefLinear(c, z, 3) + assert m.getValsLinear(c) == {"x": Fraction(1, 3), "y": Fraction(1, 7), "z": 3} + m.delCoefLinear(c, z) + assert "z" not in m.getValsLinear(c) + assert m.getLhs(c) == 0 + assert m.getRhs(c) == float("inf") + + with pytest.raises(ValueError): + m.addConsLinear([x, y], [1], 0, 1) + with pytest.raises(OverflowError): + m.chgCoefLinear(c, x, float("inf")) + with pytest.raises(TypeError): + m.addCons(x + y <= 1) + with pytest.raises(TypeError): + m.addCons(Fraction(1, 3) * x <= 1) + + m.addObjoffset(Fraction(1, 3)) + assert m.getObjoffset() == Fraction(1, 3) + with pytest.raises(ValueError): + m.addObjoffset(1, solutions=True) + with pytest.raises(OverflowError): + m.addObjoffset(float("inf")) + with pytest.raises(ValueError): + m.getObjoffset(original=False) + + n = Model() + w = n.addVar("w") + lin = n.addCons(w <= 1) + assert isinstance(n.getLhs(lin), float) + assert not hasattr(m, "addConsExactLinear") + + +def _knapsack(): + m = ExactModel() + m.hideOutput() + m.setPresolve(SCIP_PARAMSETTING.OFF) + x = m.addVar("x", ub=Fraction(10, 3), obj=-1) + y = m.addVar("y", vtype="I", ub=5, obj=Fraction(-1, 7)) + c = m.addConsLinear([x, y], [Fraction(1, 3), Fraction(1, 10)], None, Fraction(2, 3)) + m.addObjoffset(Fraction(1, 2)) + return m, x, y, c + + +def test_solutions(): + m, x, y, c = _knapsack() + with pytest.raises(Warning): + m.getPrimalbound() + with pytest.raises(ValueError): + m.createOrigSol() + with pytest.raises(ValueError): + m.createPartialSol() + + sol = m.createSol() + m.setSolVal(sol, x, Fraction(1, 2)) + m.setSolVal(sol, y, 1) + assert sol.isExact() + assert m.getSolVal(sol, x) == Fraction(1, 2) + with pytest.raises(TypeError): + m.getSolVal(sol, x + y) + assert m.addSol(sol) is True + + m.presolve() + sol2 = m.createSol() + m.setSolVal(sol2, x, 2) + m.setSolVal(sol2, y, 0) + assert m.trySol(sol2) is True + + m.optimize() + assert m.getStatus() == "optimal" + best = m.getBestSol() + assert best.isExact() + assert m.getObjVal() == Fraction(-3, 2) + assert m.getSolObjVal(best) == Fraction(-3, 2) + assert m.getPrimalbound() == m.getDualbound() == Fraction(-3, 2) + assert isinstance(m.getUpperbound(), Fraction) + assert isinstance(m.getLowerbound(), Fraction) + assert isinstance(m.getCutoffbound(), (Fraction, float)) + assert m.getVal(x) == 2 + assert m.getVal(y) == 0 + assert m.getActivity(c, best) == Fraction(2, 3) + assert m.getSlack(c, best) == 0 + m.printSol(best) + m.printBestSol() + best.retransform() + with pytest.raises(Exception): + m.addObjoffset(1) + assert not hasattr(m, "getSolValExact") + + +def test_no_exact_names(): + for cls in (Model, Variable, ExactModel, ExactVariable): + leaked = [n for n in dir(cls) if "Exact" in n and not n.startswith("_")] + assert leaked == [], leaked + m = ExactModel() + assert m.allowNegSlack() in (True, False) + assert not hasattr(Model(), "allowNegSlack") + + +def test_numerics(): + m = ExactModel() + third = Fraction(1, 3) + tiny = Fraction(1, 10**30) + inf = m.infinity() + assert inf == float("inf") + assert m.epsilon() == 0 and m.feastol() == 0 + assert m.isEQ(third, Fraction(2, 6)) and m.isFeasEQ(third, Fraction(2, 6)) + assert not m.isEQ(third, third + tiny) and not m.isFeasEQ(third, third + tiny) + assert m.isLT(third, third + tiny) and m.isFeasLT(third, third + tiny) + assert m.isLE(third, third) and m.isFeasLE(third, third) + assert not m.isGT(third, third) and m.isFeasGT(third + tiny, third) + assert m.isGE(third, third) and not m.isFeasGE(third, third + tiny) + assert m.isLT(third, inf) and m.isGT(third, -inf) and m.isEQ(inf, inf) + assert m.isZero(0) and not m.isZero(tiny) and not m.isFeasZero(tiny) + assert m.isPositive(tiny) and m.isFeasPositive(tiny) + assert m.isNegative(-tiny) and m.isFeasNegative(-tiny) + assert m.isIntegral(Fraction(4, 2)) and not m.isIntegral(1 + tiny) and not m.isFeasIntegral(1 + tiny) + assert m.isInfinity(inf) and not m.isInfinity(-inf) and not m.isInfinity(10**30) + assert m.frac(Fraction(7, 3)) == third and m.feasFrac(Fraction(-7, 3)) == Fraction(2, 3) + assert m.feasFloor(Fraction(7, 3)) == 2 and m.feasCeil(Fraction(7, 3)) == 3 + assert m.feasRound(Fraction(1, 2)) == 1 and m.feasRound(Fraction(-1, 2)) == 0 + with pytest.raises(ValueError): + m.isHugeValue(1) + + +class _LPProbe(Eventhdlr): + def __init__(self): + self.seen = {} + + def eventinit(self): + self.model.catchEvent(SCIP_EVENTTYPE.FIRSTLPSOLVED, self) + + def eventexit(self): + self.model.dropEvent(SCIP_EVENTTYPE.FIRSTLPSOLVED, self) + + def eventexec(self, event): + m = self.model + row = m.getRowLinear(m.getConss()[0]) + self.seen["row"] = (type(row).__name__, row.getLhs(), row.getRhs(), row.getConstant(), row.getNNonz(), + {c.getVar().name: v for c, v in zip(row.getCols(), row.getVals())}, row.isInLP()) + self.seen["status"] = [c.getVar().getStatus() for c in row.getCols()] + self.seen["solstat"] = m.getLPSolstat() + self.seen["lowerbound"] = m.getCurrentNode().getLowerbound() + m.printRow(row) + + +def test_lp_rows(): + m, x, y, c = _knapsack() + probe = _LPProbe() + m.includeEventhdlr(probe, "probe", "") + m.optimize() + name, lhs, rhs, const, nnonz, coefs, inlp = probe.seen["row"] + assert name == "RowExact" + assert lhs == -float("inf") and rhs == Fraction(2, 3) and const == 0 and nnonz == 2 + assert coefs == {"t_x": Fraction(1, 3), "t_y": Fraction(1, 10)} and inlp + assert probe.seen["status"] == ["COLUMN", "COLUMN"] + assert probe.seen["solstat"] in (SCIP_LPSOLSTAT.NOTSOLVED, SCIP_LPSOLSTAT.OPTIMAL) + lb = probe.seen["lowerbound"] + assert lb == -float("inf") or isinstance(lb, Fraction) diff --git a/tests/test_node_methods.py b/tests/test_node_methods.py index 58125b58a..87974860b 100644 --- a/tests/test_node_methods.py +++ b/tests/test_node_methods.py @@ -108,7 +108,7 @@ def test_getCutoffbound(): disable_sepa=True, disable_heur=True, disable_presolve=True, - node_lim=10000, + node_lim=100000, small=True ) diff --git a/tests/test_nonlinear.py b/tests/test_nonlinear.py index 55fe6900c..f45650c64 100644 --- a/tests/test_nonlinear.py +++ b/tests/test_nonlinear.py @@ -346,12 +346,11 @@ def test_addExprNonLinear(): m.addExprNonlinear(c, y**2, 2) m.addExprNonlinear(c1, z**(1/3), 1) - m.setParam("numerics/epsilon", 10**(-5)) # bigger eps due to nonlinearities m.optimize() assert m.getNSols() > 0 - assert m.isEQ(m.getVal(y), 2) - assert m.isEQ(m.getVal(z), 27) + assert m.isFeasEQ(m.getVal(y), 2) + assert m.isFeasEQ(m.getVal(z), 27) def test_nonlinear_lhs_rhs(): from helpers.utils import random_nlp_1 diff --git a/tests/test_recipe_nonlinear.py b/tests/test_recipe_nonlinear.py index 5354c320d..b4c859add 100644 --- a/tests/test_recipe_nonlinear.py +++ b/tests/test_recipe_nonlinear.py @@ -44,9 +44,6 @@ def test_nonlinear_objective(): obj_expr = model.getObjective() assert obj_expr.degree() == 1 - model.setParam("numerics/epsilon", 10**(-5)) # bigger eps due to nonlinearities - model2.setParam("numerics/epsilon", 10**(-5)) - model.optimize() model2.optimize() assert model.isEQ(model.getObjVal(), model2.getObjVal()) \ No newline at end of file diff --git a/tests/test_relax.py b/tests/test_relax.py index 97692497e..df6de8129 100644 --- a/tests/test_relax.py +++ b/tests/test_relax.py @@ -51,6 +51,7 @@ class EmptyRelaxator(Relax): def test_empty_relaxator(): m = Model() m.setPresolve(SCIP_PARAMSETTING.OFF) + m.setHeuristics(SCIP_PARAMSETTING.OFF) m.hideOutput() m.includeRelax(EmptyRelaxator(), "", "") diff --git a/tests/test_symhdlr.py b/tests/test_symhdlr.py new file mode 100644 index 000000000..5786e334f --- /dev/null +++ b/tests/test_symhdlr.py @@ -0,0 +1,44 @@ +from pyscipopt import Model, Symhdlr, SCIP_RESULT + + +class RecordingSymhdlr(Symhdlr): + def __init__(self): + self.tryadd_calls = [] + self.exit_data = None + self.nprop = 0 + + def symtryadd(self, symtype, perms, permvars, permvardomcenter, id, allowbdchgs): + self.tryadd_calls.append((len(perms), len(permvars))) + assert all(len(p) == len(permvars) for p in perms) + return {"success": True, "data": {"id": id, "nperms": len(perms)}} + + def symexit(self, symcomps): + self.exit_data = [(c.name, c.data) for c in symcomps] + + def symprop(self, symcomps, proptiming): + self.nprop += 1 + return {"result": SCIP_RESULT.DIDNOTFIND} + + +def test_symhdlr(): + m = Model() + m.hideOutput() + n, k = 6, 4 + x = {(i, j): m.addVar(vtype="B", obj=1 + (j == 0)) for i in range(n) for j in range(k)} + for i in range(n): + m.addCons(sum(x[i, j] for j in range(k)) == 1) + for j in range(k): + m.addCons(sum((i % 3 + 2) * x[i, j] for i in range(n)) <= 7) + + symhdlr = RecordingSymhdlr() + m.includeSymhdlr(symhdlr, "recording", "records symmetry components", priority=10**6, propfreq=1) + m.optimize() + + assert m.getStatus() == "optimal" + assert len(symhdlr.tryadd_calls) == 1 + nperms, npermvars = symhdlr.tryadd_calls[0] + assert nperms > 0 and npermvars == n * k + assert symhdlr.nprop > 0 + + m.freeTransform() + assert symhdlr.exit_data == [("symcomp0", {"id": 0, "nperms": nperms})]