diff --git a/CHANGELOG.md b/CHANGELOG.md index f4f1e742f..e535d0f1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,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 @@ -55,6 +56,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/src/pyscipopt/__init__.py b/src/pyscipopt/__init__.py index 093e38383..ecc8cafe3 100644 --- a/src/pyscipopt/__init__.py +++ b/src/pyscipopt/__init__.py @@ -31,6 +31,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/exact.pxi b/src/pyscipopt/exact.pxi index 145abe915..99ae9fe21 100644 --- a/src/pyscipopt/exact.pxi +++ b/src/pyscipopt/exact.pxi @@ -1,5 +1,55 @@ ##@file exact.pxi -#@brief Exact (rational) solving: ExactModel and the exact LP row and column wrappers +#@brief Exact (rational) solving: ExactModel, the exact wrappers and the exact LP row and column wrappers + +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.""" @@ -26,6 +76,17 @@ cdef class 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.""" @@ -52,80 +113,257 @@ cdef class RowExact: 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.""" + """Variable of an ExactModel: bounds, objective and LP value are rationals.""" def getObj(self): - raise NotImplementedError("ExactVariable.getObj() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + Retrieve the exact objective coefficient of the variable. + + Returns + ------- + Fraction + """ + return _fromRational(SCIPvarGetObjExact(self.scip_var)) def getLbOriginal(self): - raise NotImplementedError("ExactVariable.getLbOriginal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getUbOriginal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getLbGlobal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getUbGlobal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getLbLocal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getUbLocal() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getLPSol() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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): - raise NotImplementedError("ExactVariable.getCol() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + Returns the exact LP column of the variable. + + Returns + ------- + ColumnExact + + """ + return ColumnExact.create(SCIPvarGetColExact(self.scip_var)) def getStatus(self): - raise NotImplementedError("ExactVariable.getStatus() is not available yet; exact values come with PySCIPOpt 7.0.0") + """ + 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 ExactSolution(Solution): """Solution of an ExactModel.""" def __getitem__(self, expr): - raise NotImplementedError("ExactSolution values are not available yet; exact values come with PySCIPOpt 7.0.0") + cdef SCIP_RATIONAL* rational + self._checkStage("SCIPgetSolVal") + 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, self.sol, (expr).scip_var, rational) + result = _fromRational(rational) + SCIPrationalFree(&rational) + return result def __setitem__(self, Variable var, value): - raise NotImplementedError("ExactSolution values are not available yet; exact values come with PySCIPOpt 7.0.0") + cdef SCIP_RATIONAL* rational + cdef SCIP_RETCODE rc + rational = _createRational(value) + rc = SCIPsetSolValExact(self.scip, self.sol, var.scip_var, rational) + SCIPrationalFree(&rational) + PY_SCIP_CALL(rc) cdef class ExactEvent(Event): - """Event on a variable of an ExactModel.""" + """Event of an ExactModel.""" def getNewBound(self): - raise NotImplementedError("ExactEvent.getNewBound() is not available yet; exact values come with PySCIPOpt 7.0.0") - + raise NotImplementedError("ExactEvent.getNewBound() is not available: SCIP has no exact getter for the new bound of an event") def getOldBound(self): - raise NotImplementedError("ExactEvent.getOldBound() is not available yet; exact values come with PySCIPOpt 7.0.0") - + raise NotImplementedError("ExactEvent.getOldBound() is not available yet in exact mode") cdef class ExactBoundChange(BoundChange): """Bound change of a variable of an ExactModel.""" def getNewBound(self): - raise NotImplementedError("ExactBoundChange.getNewBound() is not available yet; exact values come with PySCIPOpt 7.0.0") - + raise NotImplementedError("ExactBoundChange.getNewBound() is not available: SCIP has no exact getter for the new bound of a bound change") cdef class ExactModel(BaseModel): @@ -133,12 +371,10 @@ cdef class ExactModel(BaseModel): Specialised model for exact solving over the rationals. Should be used only if a certified solution is needed. Warning: SCIP has to be compiled with exact solving capabilities. - Please see https://www.scipopt.org/doc-10.0.0/html/EXACT.php. - - As of version 6.4.0, almost no exact methods are available, only - reading models with rational data and solving them exactly is possible. - - + Please see https://www.scipopt.org/doc/html/EXACT.php. + + 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): @@ -151,6 +387,7 @@ cdef class ExactModel(BaseModel): use default plugins (default True) createscip : bool, optional initialize the Model object and creates a SCIP instance + """ if not PYSCIPOPT_WITH_EXACTSOLVE: raise ValueError("SCIP was built without exact solving support, ExactModel needs a SCIP build with exact solving enabled") @@ -173,6 +410,1243 @@ cdef class ExactModel(BaseModel): ) raise AttributeError(f"'ExactModel' object has no attribute '{name}'") + 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 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 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 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 getObjVal(self, original=True): + """ + Retrieve the objective value of the best solution. + + Parameters + ---------- + original : bool, optional + objective value in original space (Default value = True) + + Returns + ------- + Fraction + + """ + + self._ensureFreshBestSol() + + if SCIPgetNSols(self._scip) == 0: + if SCIPgetStage(self._scip) != SCIP_STAGE_SOLVING: + raise Warning("Without a solution, method can only be called in stage SOLVING.") + else: + assert self._bestSol.sol != NULL + + if SCIPsolIsOriginal(self._bestSol.sol): + min_stage_requirement = SCIP_STAGE_PROBLEM + else: + min_stage_requirement = SCIP_STAGE_TRANSFORMING + + if not SCIPgetStage(self._scip) >= min_stage_requirement: + raise Warning("method cannot be called in stage %i." % self.getStage) + + return self.getSolObjVal(self._bestSol, original) + + 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 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. diff --git a/src/pyscipopt/model.pxi b/src/pyscipopt/model.pxi index a92ebf3a6..01a581791 100644 --- a/src/pyscipopt/model.pxi +++ b/src/pyscipopt/model.pxi @@ -569,9 +569,9 @@ cdef class Model(BaseModel): 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)) + 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, threadsafe, True, self._valid)) + PY_SCIP_CALL(SCIPcopy(sourceModel._scip, self._scip, NULL, NULL, n, globalcopy, enablepricing, True, threadsafe, True, self._valid)) def getFirstPrimalBound(self): """ @@ -6086,102 +6086,6 @@ cdef class Model(BaseModel): return down, up, downvalid, upvalid, downinf, upinf, downconflict, upconflict, lperror - # 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). - - Deprecated since 6.4.0; construct an ExactModel instead. Enabling - exact solving on a Model raises a ValueError. - """ - if enable: - raise ValueError("Model cannot solve exactly; construct an ExactModel instead.") - warnings.warn( - "enableExactSolving() is deprecated and will be removed in PySCIPOpt 7.0.0; construct an ExactModel instead.", - DeprecationWarning, - stacklevel=1 - ) - - PY_SCIP_CALL(SCIPenableExactSolving(self._scip, enable)) - - def isExact(self): - """ - Returns whether exact solving mode is enabled in SCIP. - - Returns - ------- - bool - - Deprecated since 6.4.0; exact models are instances of ExactModel. - """ - warnings.warn( - "isExact() is deprecated and will be removed in PySCIPOpt 7.0.0; exact models are instances of ExactModel.", - DeprecationWarning, - stacklevel=1 - ) - - return SCIPisExact(self._scip) - - def allowNegSlackExact(self): - """ - Returns whether negative slack is allowed in exact solving mode. - - Returns - ------- - bool - - Deprecated since 6.4.0; use ExactModel.allowNegSlack() instead. - """ - warnings.warn( - "allowNegSlackExact() is deprecated and will be removed in PySCIPOpt 7.0.0; use ExactModel.allowNegSlack() instead.", - DeprecationWarning, - stacklevel=1 - ) - - return SCIPallowNegSlack(self._scip) - - def branchLPExact(self): - """ - Performs exact LP branching. - - Returns - ------- - SCIP_RESULT - - Deprecated since 6.4.0; use ExactModel.branchLP() instead. - """ - warnings.warn( - "branchLPExact() is deprecated and will be removed in PySCIPOpt 7.0.0; use ExactModel.branchLP() instead.", - DeprecationWarning, - stacklevel=1 - ) - cdef SCIP_RESULT result - PY_SCIP_CALL(SCIPbranchLPExact(self._scip, &result)) - return _ENUMS[PY_SCIP_RESULT][result] - - def addRowExact(self, RowExact rowexact): - """ - Adds an exact row to the LP. - - Parameters - ---------- - rowexact : RowExact - The exact row to add. - - Deprecated since 6.4.0; use ExactModel.addRow() instead. - """ - warnings.warn( - "addRowExact() is deprecated and will be removed in PySCIPOpt 7.0.0; use ExactModel.addRow() instead.", - DeprecationWarning, - stacklevel=1 - ) - 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): """ @@ -6608,6 +6512,62 @@ cdef class Model(BaseModel): 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 + def includeBranchrule(self, Branchrule branchrule, name, desc, priority, maxdepth, maxbounddist): """ Include a branching rule. @@ -7511,6 +7471,60 @@ cdef class Model(BaseModel): PY_SCIP_CALL( SCIPapplyCutsProbing(self._scip, &cutoff) ) return cutoff + 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 includeIISfinder(self, IISfinder iisfinder, name, desc, priority=10000, freq=1): """ Include an IIS (Irreducible Infeasible Set) finder handler. @@ -7536,7 +7550,7 @@ cdef class Model(BaseModel): 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) diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index ba28df634..a1c97d7af 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -429,6 +429,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 @@ -602,6 +618,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) @@ -611,6 +628,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) @@ -773,6 +791,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) @@ -793,7 +812,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 @@ -1220,6 +1239,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, @@ -1249,6 +1323,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), @@ -1474,6 +1549,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); @@ -1596,6 +1715,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, @@ -2306,6 +2467,9 @@ cdef class Variable(Expr): cpdef size_t ptr(self) noexcept cpdef int getIndex(self) noexcept +cdef class ExactVariable(Variable): + pass + cdef class Constraint: cdef SCIP_CONS* scip_cons # can be used to store problem data @@ -2320,6 +2484,12 @@ cdef class IIS: @staticmethod cdef create(SCIP_IIS* iis) +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 @@ -2367,9 +2537,6 @@ cdef class Model(BaseModel): cdef class ExactModel(BaseModel): pass -cdef class ExactVariable(Variable): - pass - cdef class ExactSolution(Solution): pass diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 0bd1dce76..c4881dbb0 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -20,6 +20,7 @@ from posix.stdio cimport fileno from collections.abc import Iterable from itertools import repeat from dataclasses import dataclass +from fractions import Fraction from enum import Enum, Flag, IntEnum, IntFlag from typing import Union @@ -51,6 +52,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" @@ -610,9 +612,22 @@ cdef class Solution: """ return _ENUMS[PY_SCIP_SOLORIGIN][SCIPsolGetOrigin(self.sol)] + def isExact(self): + """ + Returns whether the solution has exact (rational) values. + + Returns + ------- + bool + """ + return self.sol != NULL and SCIPsolIsExact(self.sol) + def retransform(self): """ retransforms solution to original problem space """ - PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) + if SCIPsolIsExact(self.sol): + PY_SCIP_CALL(SCIPretransformSolExact(self.scip, self.sol)) + else: + PY_SCIP_CALL(SCIPretransformSol(self.scip, self.sol)) def translate(self, BaseModel target): """ @@ -832,9 +847,14 @@ cdef class Node: Returns ------- - float + float or Fraction + a Fraction (or -inf) when the node belongs to an exact model """ + cdef SCIP_RATIONAL* exact = SCIPnodeGetLowerboundExact(self.scip_node) + + if exact != NULL: + return _fromRational(exact) return SCIPnodeGetLowerbound(self.scip_node) def getEstimate(self): @@ -966,7 +986,7 @@ cdef class Node: cdef int nbranchings cdef int nconsprop cdef int nprop - SCIPnodeGetNDomchg(self.scip_node, &nbranchings, &nconsprop, &nprop) + SCIPnodeGetNDomchg(self.scip_node, &nbranchings, &nconsprop, &nprop, NULL) return nbranchings, nconsprop, nprop def getDomchg(self): diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 5fcf2835a..78595ffcc 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -1,13 +1,16 @@ import os from collections.abc import Iterable, Mapping, Sequence from enum import IntEnum, IntFlag -from typing import Any, ClassVar, Literal, SupportsFloat, overload +from fractions import Fraction +from typing import Any, 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 @@ -154,6 +157,7 @@ class Column: class ColumnExact: data: Any def __init__(self) -> None: ... + def getVar(self) -> ExactVariable: ... @disjoint_base class Conshdlr: @@ -361,12 +365,143 @@ class ExactModel(BaseModel): defaultPlugins: bool = True, createscip: bool = True, ) -> 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) -> PY_SCIP_RESULT: ... + 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 chgVarObj(self, var: Variable, newobj: _Rational) -> 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 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 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 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 printRow(self, row: RowExact) -> None: ... + def setObjective( + self, + expr: Expr | SupportsFloat, + sense: Literal["minimize", "maximize"] = "minimize", + clear: bool | Literal["true"] = "true", # TODO: typo? + ) -> 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 tightenVarUb(self, var: Variable, ub: _Rational, 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: ... -class ExactSolution(Solution): ... -class ExactVariable(Variable): ... +class ExactSolution(Solution): + def __getitem__(self, index: Variable, /) -> Fraction | float: ... # type: ignore[override] + def __setitem__(self, key: Variable, value: _Rational, /) -> None: ... # type: ignore[override] +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 ExprLike: @@ -1336,8 +1471,6 @@ class Model(BaseModel): def addPoolCut(self, row: Row) -> None: ... def addPyCons(self, cons: Constraint) -> None: ... def addRowDive(self, row: Row) -> None: ... - @deprecated("Deprecated since 6.4.0; use ExactModel.addRow() instead.") - def addRowExact(self, rowexact: RowExact) -> None: ... def addVar( self, name: str = "", @@ -1366,8 +1499,6 @@ class Model(BaseModel): def catchRowEvent( self, row: Row, eventtype: PY_SCIP_EVENTTYPE, eventhdlr: Eventhdlr ) -> None: ... - @deprecated("Deprecated since 6.4.0; use ExactModel.allowNegSlack() instead.") - def allowNegSlackExact(self) -> bool: ... def appendVarSOS1(self, cons: Constraint, var: Variable) -> None: ... def appendVarSOS2(self, cons: Constraint, var: Variable) -> None: ... def checkBendersSubproblemOptimality( @@ -1381,8 +1512,6 @@ class Model(BaseModel): def enableReoptimization(self, enable: bool = True) -> None: ... def endStrongbranch(self) -> None: ... def freeReoptSolve(self) -> None: ... - @deprecated("Deprecated since 6.4.0; use ExactModel.branchLP() instead.") - def branchLPExact(self) -> PY_SCIP_RESULT: ... def branchVarVal( self, variable: Variable, value: float ) -> tuple[Node, Node | None, Node]: ... @@ -1487,8 +1616,6 @@ class Model(BaseModel): def getLPBasisInd(self) -> list[int]: ... def getNCountedSols(self) -> int: ... def getNReoptRuns(self) -> int: ... - @deprecated("Deprecated since 6.4.0; construct an ExactModel instead.") - def enableExactSolving(self, enable: bool) -> None: ... def endDive(self) -> None: ... def epsilon(self) -> float: ... def feasCeil(self, value: float) -> float: ... @@ -1723,6 +1850,40 @@ class Model(BaseModel): 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 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]: ... def infinity(self) -> float: ... def initBendersDefault(self, subproblems: Model | dict[Any, Model]) -> None: ... def isAndConsSorted(self, and_cons: Constraint) -> bool: ... @@ -1765,8 +1926,6 @@ class Model(BaseModel): def updateBendersLowerbounds( self, lowerbounds: dict[int, float], benders: Benders | None = None ) -> None: ... - @deprecated("Deprecated since 6.4.0; exact models are instances of ExactModel.") - 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: ... @@ -1899,7 +2058,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: ... @@ -2356,6 +2515,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: @@ -2376,6 +2542,7 @@ class Solution: def __init__(self, raise_error: bool = True) -> None: ... def _checkStage(self, method: str) -> None: ... def getOrigin(self) -> PY_SCIP_SOLORIGIN: ... + def isExact(self) -> bool: ... def retransform(self) -> None: ... def translate(self, target: BaseModel) -> Solution: ... @overload @@ -2457,6 +2624,71 @@ class SumExpr(GenExpr): def __init__(self) -> None: ... def __neg__(self, /) -> ProdExpr: ... +@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: ... + @disjoint_base class Term: @property 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 index 44df4322f..73db5711c 100644 --- a/tests/test_base_model.py +++ b/tests/test_base_model.py @@ -1,4 +1,5 @@ import re +from fractions import Fraction from pathlib import Path import pytest @@ -106,17 +107,14 @@ def eventinit(self): def test_exact_model_skeleton(tmp_path): assert ExactModel.__mro__[:2] == (ExactModel, BaseModel) assert {"addRow", "allowNegSlack", "branchLP"} <= set(vars(ExactModel)) - with pytest.warns(DeprecationWarning): - Model().isExact() - with pytest.raises(ValueError): - Model().enableExactSolving(True) + assert not {"enableExactSolving", "isExact", "allowNegSlackExact", "branchLPExact", "addRowExact"} & set(dir(Model)) try: m = ExactModel() except ValueError: pytest.skip("SCIP was built without exact solving support") assert not isinstance(m, Model) assert type(BaseModel.from_ptr(m.to_ptr(False), False)) is ExactModel - assert not hasattr(m, "getVal") + assert not hasattr(m, "addConsAnd") with pytest.raises(AttributeError, match="Model.includeConshdlr has this attribute"): m.includeConshdlr with pytest.raises(AttributeError, match="no attribute 'noSuchMethod'$"): @@ -124,7 +122,7 @@ def test_exact_model_skeleton(tmp_path): assert m.getNVars() == 0 assert type(Model().addVar()) is Variable path = tmp_path / "exact.lp" - path.write_text("Minimize\n obj: x + 3 y\nSubject To\n c1: 2 x + 3 y >= 1\nBounds\n 0 <= x <= 10\n 0 <= y <= 10\nGeneral\n x\nEnd\n") + path.write_text("Minimize\n obj: x + 2 y\nSubject To\n c1: 2 x + 3 y >= 1\nBounds\n 0 <= x <= 10\n 0 <= y <= 10\nGeneral\n x\nEnd\n") m.hideOutput() m.readProblem(str(path)) m.optimize() @@ -133,7 +131,6 @@ def test_exact_model_skeleton(tmp_path): assert type(sol) is ExactSolution x = m.getVars()[0] assert x.name == "x" and x.vtype() == "INTEGER" - with pytest.raises(NotImplementedError): - x.getLbLocal() - with pytest.raises(NotImplementedError): - sol[x] + y = m.getVars()[1] + assert x.getLbLocal() == 0 + assert sol[x] == 0 and sol[y] == Fraction(1, 3) diff --git a/tests/test_exact.py b/tests/test_exact.py new file mode 100644 index 000000000..55882ffbe --- /dev/null +++ b/tests/test_exact.py @@ -0,0 +1,264 @@ +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") + + +MODEL_ONLY = ["tightenVarLbGlobal", "tightenVarUbGlobal", "chgVarObjDive", "chgVarLbProbing", + "chgVarUbProbing", "chgVarObjProbing", "fixVarProbing", "chgVarLbNode", "chgVarUbNode", + "setObjlimit", "createOrigSol", "createPartialSol", "isHugeValue"] + + +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 MODEL_ONLY: + with pytest.raises(AttributeError, match=f"Model.{name} has this attribute"): + getattr(m, name) + 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() + + 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 + + +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 a94a5dd64..53885a59a 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})]