From 616ae91968722d5fc11093298706213828c45df0 Mon Sep 17 00:00:00 2001 From: Joao-Dionisio Date: Wed, 11 Nov 2026 15:25:53 +0000 Subject: [PATCH 1/2] Add LPExact wrapping SCIP 11's exact LP interface --- scripts/generate_stubs.py | 2 +- src/pyscipopt/__init__.py | 1 + src/pyscipopt/lpexact.pxi | 625 ++++++++++++++++++++++++++++++++++++++ src/pyscipopt/scip.pxd | 45 +++ src/pyscipopt/scip.pxi | 1 + src/pyscipopt/scip.pyi | 72 +++++ tests/test_lpexact.py | 140 +++++++++ 7 files changed, 885 insertions(+), 1 deletion(-) create mode 100644 src/pyscipopt/lpexact.pxi create mode 100644 tests/test_lpexact.py diff --git a/scripts/generate_stubs.py b/scripts/generate_stubs.py index 1cdaa3163..7b79b2f32 100755 --- a/scripts/generate_stubs.py +++ b/scripts/generate_stubs.py @@ -107,7 +107,7 @@ class StubGenerator: 'BaseModel', 'Benders', 'Benderscut', 'BoundChange', 'Branchrule', 'Column', 'ColumnExact', 'Conshdlr', 'Constant', 'Constraint', 'Cutsel', 'DomainChanges', 'Event', 'Eventhdlr', 'Expr', 'ExprCons', 'GenExpr', 'Heur', 'IIS', 'IISfinder', - 'LP', 'NLRow', 'Node', 'Nodesel', 'PowExpr', 'Presol', 'Pricer', + 'LP', 'LPExact', 'NLRow', 'Node', 'Nodesel', 'PowExpr', 'Presol', 'Pricer', 'ProdExpr', 'Prop', 'Reader', 'Relax', 'Row', 'RowExact', 'Sepa', 'Solution', 'SumExpr', 'Term', 'UnaryExpr', 'Variable', '_VarArray', } diff --git a/src/pyscipopt/__init__.py b/src/pyscipopt/__init__.py index 4aaabd7ac..fe7b5cac2 100644 --- a/src/pyscipopt/__init__.py +++ b/src/pyscipopt/__init__.py @@ -31,6 +31,7 @@ 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 LPExact as LPExact from pyscipopt.scip import IISfinder as IISfinder from pyscipopt.scip import PY_SCIP_LPPARAM as SCIP_LPPARAM from pyscipopt.scip import PY_SCIP_BASESTAT as SCIP_BASESTAT diff --git a/src/pyscipopt/lpexact.pxi b/src/pyscipopt/lpexact.pxi new file mode 100644 index 000000000..fb1b6410b --- /dev/null +++ b/src/pyscipopt/lpexact.pxi @@ -0,0 +1,625 @@ +##@file lpexact.pxi +#@brief LP solving in exact rational arithmetic through SCIP's exact LP interface + +_INF = float("inf") + + +cdef int _setRational(SCIP_RATIONAL* rational, value) except -1: + if isinstance(value, float) and abs(value) == _INF: + SCIPrationalSetString(rational, b"inf" if value > 0 else b"-inf") + else: + SCIPrationalSetString(rational, str(Fraction(value)).encode()) + return 0 + + +cdef SCIP_RATIONAL** _createRationals(int n) except NULL: + cdef SCIP_RATIONAL** array = NULL + + PY_SCIP_CALL(SCIPrationalCreateArray(&array, n)) + if array == NULL: + raise MemoryError() + return array + + +cdef SCIP_RATIONAL** _createRationalArray(values) except NULL: + cdef int n = len(values) + cdef SCIP_RATIONAL** array = _createRationals(n) + cdef int i + + try: + for i in range(n): + _setRational(array[i], values[i]) + except BaseException: + SCIPrationalFreeArray(&array, n) + raise + return array + + +cdef void _freeRationals(SCIP_RATIONAL*** array, int n) noexcept: + if array[0] != NULL: + SCIPrationalFreeArray(array, n) + + +cdef list _fromRationals(SCIP_RATIONAL** array, int n): + return [_fromRational(array[i]) for i in range(n)] + + +cdef int* _createInts(values) except NULL: + cdef int n = len(values) + cdef int* array = malloc(max(n, 1) * sizeof(int)) + cdef int i + + if array == NULL: + raise MemoryError() + try: + for i in range(n): + array[i] = values[i] + except BaseException: + free(array) + raise + return array + + +cdef list _getSolPart(SCIP_LPIEXACT* lpi, int n, int part): + cdef SCIP_RATIONAL** vector = NULL + + if n == 0: + return [] + try: + vector = _createRationals(n) + if part == 0: + PY_SCIP_CALL(SCIPlpiExactGetSol(lpi, NULL, vector, NULL, NULL, NULL)) + elif part == 1: + PY_SCIP_CALL(SCIPlpiExactGetSol(lpi, NULL, NULL, vector, NULL, NULL)) + elif part == 2: + PY_SCIP_CALL(SCIPlpiExactGetSol(lpi, NULL, NULL, NULL, vector, NULL)) + else: + PY_SCIP_CALL(SCIPlpiExactGetSol(lpi, NULL, NULL, NULL, NULL, vector)) + return _fromRationals(vector, n) + finally: + _freeRationals(&vector, n) + + +cdef class LPExact: + """LP solved in exact rational arithmetic by SCIP's exact LP interface. + + Values are given as Fraction, int, float or str and returned as Fraction; + infinite bounds and sides are float("inf") and -float("inf"). + """ + cdef SCIP_LPIEXACT* lpi + cdef readonly str name + + def __init__(self, name="LP", sense="minimize"): + """ + Parameters + ---------- + name : str, optional + name of the problem (Default value = "LP") + sense : str, optional + "minimize" or "maximize" (Default value = "minimize") + + """ + if SCIPlpiExactGetSolverName() == b"NONE": + raise ValueError("SCIP was built without an exact LP solver, LPExact needs a SCIP build with exact SoPlex") + self.name = name + n = str_conversion(name) + if sense == "minimize": + PY_SCIP_CALL(SCIPlpiExactCreate(&self.lpi, NULL, n, SCIP_OBJSEN_MINIMIZE)) + elif sense == "maximize": + PY_SCIP_CALL(SCIPlpiExactCreate(&self.lpi, NULL, n, SCIP_OBJSEN_MAXIMIZE)) + else: + raise Warning("unrecognized objective sense") + + def __dealloc__(self): + if self.lpi != NULL: + PY_SCIP_CALL(SCIPlpiExactFree(&self.lpi)) + + def __repr__(self): + return self.name + + def writeLP(self, filename): + """Write the LP to a file.""" + PY_SCIP_CALL(SCIPlpiExactWriteLP(self.lpi, str_conversion(filename))) + + def readLP(self, filename): + """Read the LP from a file.""" + PY_SCIP_CALL(SCIPlpiExactReadLP(self.lpi, str_conversion(filename))) + + def infinity(self): + """Return the value representing infinity: float("inf").""" + return _INF + + def isInfinity(self, val): + """Return whether val is positive infinity.""" + return val == _INF + + def addCol(self, entries, obj=0, lb=0, ub=None): + """Add a single column. + + Parameters + ---------- + entries : list of tuple + (row index, coefficient) pairs of the nonzero entries of the column + obj : Fraction or int or float or str, optional + objective coefficient (Default value = 0) + lb : Fraction or int or float or str or None, optional + lower bound, None for -infinity (Default value = 0) + ub : Fraction or int or float or str or None, optional + upper bound, None for infinity (Default value = None) + + """ + self.addCols([entries], [obj], [lb], [ub]) + + def addCols(self, entrieslist, objs=None, lbs=None, ubs=None): + """Add multiple columns. + + Parameters + ---------- + entrieslist : list of list of tuple + (row index, coefficient) pairs of the nonzero entries of each column + objs : list, optional + objective coefficients (Default value = all 0) + lbs : list, optional + lower bounds, None for -infinity (Default value = all 0) + ubs : list, optional + upper bounds, None for infinity (Default value = all infinity) + + """ + cdef int ncols = len(entrieslist) + cdef int nnonz + cdef SCIP_RATIONAL** c_objs = NULL + cdef SCIP_RATIONAL** c_lbs = NULL + cdef SCIP_RATIONAL** c_ubs = NULL + cdef SCIP_RATIONAL** c_vals = NULL + cdef int* c_beg = NULL + cdef int* c_inds = NULL + + if ncols == 0: + return + objs = [0] * ncols if objs is None else list(objs) + lbs = [0] * ncols if lbs is None else [-_INF if lb is None else lb for lb in lbs] + ubs = [_INF] * ncols if ubs is None else [_INF if ub is None else ub for ub in ubs] + if not len(objs) == len(lbs) == len(ubs) == ncols: + raise ValueError("objs, lbs and ubs must have one entry per column") + begs, inds, vals = [], [], [] + for entries in entrieslist: + begs.append(len(inds)) + for ind, val in entries: + inds.append(ind) + vals.append(val) + nnonz = len(vals) + + try: + c_objs = _createRationalArray(objs) + c_lbs = _createRationalArray(lbs) + c_ubs = _createRationalArray(ubs) + if nnonz > 0: + c_vals = _createRationalArray(vals) + c_beg = _createInts(begs) + c_inds = _createInts(inds) + PY_SCIP_CALL(SCIPlpiExactAddCols(self.lpi, ncols, c_objs, c_lbs, c_ubs, NULL, nnonz, c_beg, c_inds, c_vals)) + finally: + free(c_inds) + free(c_beg) + _freeRationals(&c_vals, nnonz) + _freeRationals(&c_ubs, ncols) + _freeRationals(&c_lbs, ncols) + _freeRationals(&c_objs, ncols) + + def delCols(self, firstcol, lastcol): + """Delete the columns firstcol..lastcol.""" + PY_SCIP_CALL(SCIPlpiExactDelCols(self.lpi, firstcol, lastcol)) + + def addRow(self, entries, lhs=0, rhs=None): + """Add a single row. + + Parameters + ---------- + entries : list of tuple + (column index, coefficient) pairs of the nonzero entries of the row + lhs : Fraction or int or float or str or None, optional + left-hand side, None for -infinity (Default value = 0) + rhs : Fraction or int or float or str or None, optional + right-hand side, None for infinity (Default value = None) + + """ + self.addRows([entries], [lhs], [rhs]) + + def addRows(self, entrieslist, lhss=None, rhss=None): + """Add multiple rows. + + Parameters + ---------- + entrieslist : list of list of tuple + (column index, coefficient) pairs of the nonzero entries of each row + lhss : list, optional + left-hand sides, None for -infinity (Default value = all 0) + rhss : list, optional + right-hand sides, None for infinity (Default value = all infinity) + + """ + cdef int nrows = len(entrieslist) + cdef int nnonz + cdef SCIP_RATIONAL** c_lhss = NULL + cdef SCIP_RATIONAL** c_rhss = NULL + cdef SCIP_RATIONAL** c_vals = NULL + cdef int* c_beg = NULL + cdef int* c_inds = NULL + + if nrows == 0: + return + lhss = [0] * nrows if lhss is None else [-_INF if lhs is None else lhs for lhs in lhss] + rhss = [_INF] * nrows if rhss is None else [_INF if rhs is None else rhs for rhs in rhss] + if not len(lhss) == len(rhss) == nrows: + raise ValueError("lhss and rhss must have one entry per row") + begs, inds, vals = [], [], [] + for entries in entrieslist: + begs.append(len(inds)) + for ind, val in entries: + inds.append(ind) + vals.append(val) + nnonz = len(vals) + + try: + c_lhss = _createRationalArray(lhss) + c_rhss = _createRationalArray(rhss) + if nnonz > 0: + c_vals = _createRationalArray(vals) + c_beg = _createInts(begs) + c_inds = _createInts(inds) + PY_SCIP_CALL(SCIPlpiExactAddRows(self.lpi, nrows, c_lhss, c_rhss, NULL, nnonz, c_beg, c_inds, c_vals)) + finally: + free(c_inds) + free(c_beg) + _freeRationals(&c_vals, nnonz) + _freeRationals(&c_rhss, nrows) + _freeRationals(&c_lhss, nrows) + + def delRows(self, firstrow, lastrow): + """Delete the rows firstrow..lastrow.""" + PY_SCIP_CALL(SCIPlpiExactDelRows(self.lpi, firstrow, lastrow)) + + def getBounds(self, firstcol=0, lastcol=None): + """Return the lower and upper bounds of the columns firstcol..lastcol, or None if the range is empty. + + Returns + ------- + tuple of (list of Fraction, list of Fraction) or None + + """ + cdef SCIP_RATIONAL** c_lbs = NULL + cdef SCIP_RATIONAL** c_ubs = NULL + cdef int n + + if lastcol is None: + lastcol = self.ncols() - 1 + if firstcol > lastcol: + return None + n = lastcol - firstcol + 1 + try: + c_lbs = _createRationals(n) + c_ubs = _createRationals(n) + PY_SCIP_CALL(SCIPlpiExactGetBounds(self.lpi, firstcol, lastcol, c_lbs, c_ubs)) + return _fromRationals(c_lbs, n), _fromRationals(c_ubs, n) + finally: + _freeRationals(&c_ubs, n) + _freeRationals(&c_lbs, n) + + def getSides(self, firstrow=0, lastrow=None): + """Return the left- and right-hand sides of the rows firstrow..lastrow, or None if the range is empty. + + Returns + ------- + tuple of (list of Fraction, list of Fraction) or None + + """ + cdef SCIP_RATIONAL** c_lhss = NULL + cdef SCIP_RATIONAL** c_rhss = NULL + cdef int n + + if lastrow is None: + lastrow = self.nrows() - 1 + if firstrow > lastrow: + return None + n = lastrow - firstrow + 1 + try: + c_lhss = _createRationals(n) + c_rhss = _createRationals(n) + PY_SCIP_CALL(SCIPlpiExactGetRows(self.lpi, firstrow, lastrow, c_lhss, c_rhss, NULL, NULL, NULL, NULL)) + return _fromRationals(c_lhss, n), _fromRationals(c_rhss, n) + finally: + _freeRationals(&c_rhss, n) + _freeRationals(&c_lhss, n) + + def chgObj(self, col, obj): + """Change the objective coefficient of a column.""" + cdef int c_col = col + cdef SCIP_RATIONAL** c_obj = NULL + + try: + c_obj = _createRationalArray([obj]) + PY_SCIP_CALL(SCIPlpiExactChgObj(self.lpi, 1, &c_col, c_obj)) + finally: + _freeRationals(&c_obj, 1) + + def chgCoef(self, row, col, newval): + """Change a single coefficient of the constraint matrix.""" + cdef SCIP_RATIONAL* c_val = _createRational(newval) + + try: + PY_SCIP_CALL(SCIPlpiExactChgCoef(self.lpi, row, col, c_val)) + finally: + SCIPrationalFree(&c_val) + + def chgBound(self, col, lb, ub): + """Change the lower and upper bound of a column; None means infinite.""" + cdef int c_col = col + cdef SCIP_RATIONAL** c_lb = NULL + cdef SCIP_RATIONAL** c_ub = NULL + + try: + c_lb = _createRationalArray([-_INF if lb is None else lb]) + c_ub = _createRationalArray([_INF if ub is None else ub]) + PY_SCIP_CALL(SCIPlpiExactChgBounds(self.lpi, 1, &c_col, c_lb, c_ub)) + finally: + _freeRationals(&c_ub, 1) + _freeRationals(&c_lb, 1) + + def chgSide(self, row, lhs, rhs): + """Change the left- and right-hand side of a row; None means infinite.""" + cdef int c_row = row + cdef SCIP_RATIONAL** c_lhs = NULL + cdef SCIP_RATIONAL** c_rhs = NULL + + try: + c_lhs = _createRationalArray([-_INF if lhs is None else lhs]) + c_rhs = _createRationalArray([_INF if rhs is None else rhs]) + PY_SCIP_CALL(SCIPlpiExactChgSides(self.lpi, 1, &c_row, c_lhs, c_rhs)) + finally: + _freeRationals(&c_rhs, 1) + _freeRationals(&c_lhs, 1) + + def clear(self): + """Remove all columns and rows.""" + PY_SCIP_CALL(SCIPlpiExactClear(self.lpi)) + + def nrows(self): + """Return the number of rows.""" + cdef int nrows + + PY_SCIP_CALL(SCIPlpiExactGetNRows(self.lpi, &nrows)) + return nrows + + def ncols(self): + """Return the number of columns.""" + cdef int ncols + + PY_SCIP_CALL(SCIPlpiExactGetNCols(self.lpi, &ncols)) + return ncols + + def solve(self, dual=True): + """Solve the LP and return the optimal objective value, or None if the LP was not solved to optimality. + + Parameters + ---------- + dual : bool, optional + use the dual instead of the primal simplex (Default value = True) + + Returns + ------- + Fraction or None + + """ + cdef SCIP_RATIONAL* objval = NULL + + if dual: + PY_SCIP_CALL(SCIPlpiExactSolveDual(self.lpi)) + else: + PY_SCIP_CALL(SCIPlpiExactSolvePrimal(self.lpi)) + if not SCIPlpiExactIsOptimal(self.lpi): + return None + PY_SCIP_CALL(SCIPrationalCreate(&objval)) + try: + PY_SCIP_CALL(SCIPlpiExactGetObjval(self.lpi, objval)) + return _fromRational(objval) + finally: + SCIPrationalFree(&objval) + + def isOptimal(self): + """Return whether the last solve reached optimality.""" + return SCIPlpiExactIsOptimal(self.lpi) + + def isPrimalFeasible(self): + """Return whether the LP is proven primal feasible.""" + return SCIPlpiExactIsPrimalFeasible(self.lpi) + + def isDualFeasible(self): + """Return whether the LP is proven dual feasible.""" + return SCIPlpiExactIsDualFeasible(self.lpi) + + def getObjVal(self): + """Return the objective value of the last solve.""" + cdef SCIP_RATIONAL* objval = NULL + + PY_SCIP_CALL(SCIPrationalCreate(&objval)) + try: + PY_SCIP_CALL(SCIPlpiExactGetSol(self.lpi, objval, NULL, NULL, NULL, NULL)) + return _fromRational(objval) + finally: + SCIPrationalFree(&objval) + + def getPrimal(self): + """Return the primal solution of the last solve as a list of Fraction.""" + return _getSolPart(self.lpi, self.ncols(), 0) + + def getDual(self): + """Return the dual solution of the last solve as a list of Fraction.""" + return _getSolPart(self.lpi, self.nrows(), 1) + + def getActivity(self): + """Return the row activities of the last solve as a list of Fraction.""" + return _getSolPart(self.lpi, self.nrows(), 2) + + def getRedcost(self): + """Return the reduced costs of the last solve as a list of Fraction.""" + return _getSolPart(self.lpi, self.ncols(), 3) + + def getPrimalRay(self): + """Return a primal ray as a list of Fraction if the LP is proven unbounded, None otherwise.""" + cdef int ncols + cdef SCIP_RATIONAL** c_ray = NULL + + if not SCIPlpiExactHasPrimalRay(self.lpi): + return None + ncols = self.ncols() + try: + c_ray = _createRationals(ncols) + PY_SCIP_CALL(SCIPlpiExactGetPrimalRay(self.lpi, c_ray)) + return _fromRationals(c_ray, ncols) + finally: + _freeRationals(&c_ray, ncols) + + def getDualRay(self): + """Return a dual Farkas ray as a list of Fraction if the LP is proven infeasible, None otherwise.""" + cdef int nrows + cdef SCIP_RATIONAL** c_ray = NULL + + if not SCIPlpiExactHasDualRay(self.lpi): + return None + nrows = self.nrows() + try: + c_ray = _createRationals(nrows) + PY_SCIP_CALL(SCIPlpiExactGetDualfarkas(self.lpi, c_ray)) + return _fromRationals(c_ray, nrows) + finally: + _freeRationals(&c_ray, nrows) + + def getNIterations(self): + """Return the number of simplex iterations of the last solve.""" + cdef int niters + + PY_SCIP_CALL(SCIPlpiExactGetIterations(self.lpi, &niters)) + return niters + + def getBasisInds(self): + """Return the indices of the basic columns and rows; index i >= 0 is column i, index i < 0 is row -i-1.""" + cdef int nrows = self.nrows() + cdef int* c_binds = malloc(max(nrows, 1) * sizeof(int)) + cdef int i + + if c_binds == NULL: + raise MemoryError() + try: + PY_SCIP_CALL(SCIPlpiExactGetBasisInd(self.lpi, c_binds)) + return [c_binds[i] for i in range(nrows)] + finally: + free(c_binds) + + def getBase(self): + """Return the basis status of the columns and of the rows as SCIP_BASESTAT values. + + Returns + ------- + tuple of (list of int, list of int) + + """ + cdef int ncols = self.ncols() + cdef int nrows = self.nrows() + cdef int* c_cstat = NULL + cdef int* c_rstat = NULL + cdef int i + + try: + c_cstat = malloc(max(ncols, 1) * sizeof(int)) + c_rstat = malloc(max(nrows, 1) * sizeof(int)) + if c_cstat == NULL or c_rstat == NULL: + raise MemoryError() + PY_SCIP_CALL(SCIPlpiExactGetBase(self.lpi, c_cstat, c_rstat)) + return [c_cstat[i] for i in range(ncols)], [c_rstat[i] for i in range(nrows)] + finally: + free(c_rstat) + free(c_cstat) + + def setBase(self, cstat, rstat): + """Set the basis status of the columns and of the rows from SCIP_BASESTAT values. + + Parameters + ---------- + cstat : list of int + one status per column + rstat : list of int + one status per row + + """ + cdef int ncols = self.ncols() + cdef int nrows = self.nrows() + cdef int* c_cstat = NULL + cdef int* c_rstat = NULL + + if len(cstat) != ncols: + raise ValueError(f"cstat has length {len(cstat)}, expected {ncols}") + if len(rstat) != nrows: + raise ValueError(f"rstat has length {len(rstat)}, expected {nrows}") + try: + c_cstat = _createInts(cstat) + c_rstat = _createInts(rstat) + PY_SCIP_CALL(SCIPlpiExactSetBase(self.lpi, c_cstat, c_rstat)) + finally: + free(c_rstat) + free(c_cstat) + + def setIntParam(self, param, value): + """Set an int parameter; raises KeyError if the exact LP solver does not support it. + + Parameters + ---------- + param : SCIP_LPPARAM + value : int + + """ + PY_SCIP_CALL(SCIPlpiExactSetIntpar(self.lpi, param, value)) + + def setRealParam(self, param, value): + """Set a real parameter; raises KeyError if the exact LP solver does not support it. + + Parameters + ---------- + param : SCIP_LPPARAM + value : float + + """ + PY_SCIP_CALL(SCIPlpiExactSetRealpar(self.lpi, param, value)) + + def getIntParam(self, param): + """Return an int parameter; raises KeyError if the exact LP solver does not support it. + + Parameters + ---------- + param : SCIP_LPPARAM + + Returns + ------- + int + + """ + cdef int value + + PY_SCIP_CALL(SCIPlpiExactGetIntpar(self.lpi, param, &value)) + return value + + def getRealParam(self, param): + """Return a real parameter; raises KeyError if the exact LP solver does not support it. + + Parameters + ---------- + param : SCIP_LPPARAM + + Returns + ------- + float + + """ + cdef SCIP_Real value + + PY_SCIP_CALL(SCIPlpiExactGetRealpar(self.lpi, param, &value)) + return value diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index e5ecb691d..1051d9a64 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -1702,10 +1702,55 @@ cdef extern from "scip/bendersdefcuts.h": cdef extern from "scip/rational.h": SCIP_RETCODE SCIPrationalCreate(SCIP_RATIONAL** rational) void SCIPrationalFree(SCIP_RATIONAL** rational) + SCIP_RETCODE SCIPrationalCreateArray(SCIP_RATIONAL*** rational, int size) + void SCIPrationalFreeArray(SCIP_RATIONAL*** ratarray, int size) 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 "lpiexact/type_lpiexact.h": + ctypedef struct SCIP_LPIEXACT: + pass + +cdef extern from "lpiexact/lpiexact.h": + const char* SCIPlpiExactGetSolverName() + SCIP_RETCODE SCIPlpiExactCreate(SCIP_LPIEXACT** lpi, SCIP_MESSAGEHDLR* messagehdlr, const char* name, SCIP_OBJSEN objsen) + SCIP_RETCODE SCIPlpiExactFree(SCIP_LPIEXACT** lpi) + SCIP_RETCODE SCIPlpiExactWriteLP(SCIP_LPIEXACT* lpi, const char* fname) + SCIP_RETCODE SCIPlpiExactReadLP(SCIP_LPIEXACT* lpi, const char* fname) + SCIP_RETCODE SCIPlpiExactAddCols(SCIP_LPIEXACT* lpi, int ncols, SCIP_RATIONAL** obj, SCIP_RATIONAL** lb, SCIP_RATIONAL** ub, char** colnames, int nnonz, int* beg, int* ind, SCIP_RATIONAL** val) + SCIP_RETCODE SCIPlpiExactDelCols(SCIP_LPIEXACT* lpi, int firstcol, int lastcol) + SCIP_RETCODE SCIPlpiExactAddRows(SCIP_LPIEXACT* lpi, int nrows, SCIP_RATIONAL** lhs, SCIP_RATIONAL** rhs, char** rownames, int nnonz, int* beg, int* ind, SCIP_RATIONAL** val) + SCIP_RETCODE SCIPlpiExactDelRows(SCIP_LPIEXACT* lpi, int firstrow, int lastrow) + SCIP_RETCODE SCIPlpiExactGetBounds(SCIP_LPIEXACT* lpi, int firstcol, int lastcol, SCIP_RATIONAL** lbs, SCIP_RATIONAL** ubs) + SCIP_RETCODE SCIPlpiExactGetRows(SCIP_LPIEXACT* lpi, int firstrow, int lastrow, SCIP_RATIONAL** lhs, SCIP_RATIONAL** rhs, int* nnonz, int* beg, int* ind, SCIP_RATIONAL** val) + SCIP_RETCODE SCIPlpiExactChgObj(SCIP_LPIEXACT* lpi, int ncols, int* ind, SCIP_RATIONAL** obj) + SCIP_RETCODE SCIPlpiExactChgCoef(SCIP_LPIEXACT* lpi, int row, int col, SCIP_RATIONAL* newval) + SCIP_RETCODE SCIPlpiExactChgBounds(SCIP_LPIEXACT* lpi, int ncols, int* ind, SCIP_RATIONAL** lb, SCIP_RATIONAL** ub) + SCIP_RETCODE SCIPlpiExactChgSides(SCIP_LPIEXACT* lpi, int nrows, int* ind, SCIP_RATIONAL** lhs, SCIP_RATIONAL** rhs) + SCIP_RETCODE SCIPlpiExactClear(SCIP_LPIEXACT* lpi) + SCIP_RETCODE SCIPlpiExactGetNRows(SCIP_LPIEXACT* lpi, int* nrows) + SCIP_RETCODE SCIPlpiExactGetNCols(SCIP_LPIEXACT* lpi, int* ncols) + SCIP_RETCODE SCIPlpiExactSolvePrimal(SCIP_LPIEXACT* lpi) + SCIP_RETCODE SCIPlpiExactSolveDual(SCIP_LPIEXACT* lpi) + SCIP_Bool SCIPlpiExactIsOptimal(SCIP_LPIEXACT* lpi) + SCIP_Bool SCIPlpiExactIsPrimalFeasible(SCIP_LPIEXACT* lpi) + SCIP_Bool SCIPlpiExactIsDualFeasible(SCIP_LPIEXACT* lpi) + SCIP_Bool SCIPlpiExactHasPrimalRay(SCIP_LPIEXACT* lpi) + SCIP_Bool SCIPlpiExactHasDualRay(SCIP_LPIEXACT* lpi) + SCIP_RETCODE SCIPlpiExactGetObjval(SCIP_LPIEXACT* lpi, SCIP_RATIONAL* objval) + SCIP_RETCODE SCIPlpiExactGetSol(SCIP_LPIEXACT* lpi, SCIP_RATIONAL* objval, SCIP_RATIONAL** primsol, SCIP_RATIONAL** dualsol, SCIP_RATIONAL** activity, SCIP_RATIONAL** redcost) + SCIP_RETCODE SCIPlpiExactGetPrimalRay(SCIP_LPIEXACT* lpi, SCIP_RATIONAL** ray) + SCIP_RETCODE SCIPlpiExactGetDualfarkas(SCIP_LPIEXACT* lpi, SCIP_RATIONAL** dualfarkas) + SCIP_RETCODE SCIPlpiExactGetIterations(SCIP_LPIEXACT* lpi, int* iterations) + SCIP_RETCODE SCIPlpiExactGetBasisInd(SCIP_LPIEXACT* lpi, int* bind) + SCIP_RETCODE SCIPlpiExactGetBase(SCIP_LPIEXACT* lpi, int* cstat, int* rstat) + SCIP_RETCODE SCIPlpiExactSetBase(SCIP_LPIEXACT* lpi, int* cstat, int* rstat) + SCIP_RETCODE SCIPlpiExactGetIntpar(SCIP_LPIEXACT* lpi, SCIP_LPPARAM type, int* ival) + SCIP_RETCODE SCIPlpiExactGetRealpar(SCIP_LPIEXACT* lpi, SCIP_LPPARAM type, SCIP_Real* dval) + SCIP_RETCODE SCIPlpiExactSetIntpar(SCIP_LPIEXACT* lpi, SCIP_LPPARAM type, int ival) + SCIP_RETCODE SCIPlpiExactSetRealpar(SCIP_LPIEXACT* lpi, SCIP_LPPARAM type, SCIP_Real dval) + cdef extern from "scip/cons_exactlinear.h": SCIP_RETCODE SCIPcreateConsExactLinear(SCIP* scip, SCIP_CONS** cons, diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 2833fcdf8..daca1b4f2 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -7172,3 +7172,4 @@ def print_memory_in_use(): include "model.pxi" include "exact.pxi" +include "lpexact.pxi" diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index ddc3a608c..ea96e76b9 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -751,6 +751,78 @@ class LP: def solve(self, dual: bool = True) -> float: ... def writeLP(self, filename: bytes | bytearray) -> None: ... +@disjoint_base +class LPExact: + @property + def name(self) -> str: ... + def __init__( + self, name: str = "LP", sense: Literal["minimize", "maximize"] = "minimize" + ) -> None: ... + def addCol( + self, + entries: Sequence[tuple[int, _Rational | str]], + obj: _Rational | str = 0, + lb: _Rational | str | None = 0, + ub: _Rational | str | None = None, + ) -> None: ... + def addCols( + self, + entrieslist: Sequence[Sequence[tuple[int, _Rational | str]]], + objs: Sequence[_Rational | str] | None = None, + lbs: Sequence[_Rational | str | None] | None = None, + ubs: Sequence[_Rational | str | None] | None = None, + ) -> None: ... + def addRow( + self, + entries: Sequence[tuple[int, _Rational | str]], + lhs: _Rational | str | None = 0, + rhs: _Rational | str | None = None, + ) -> None: ... + def addRows( + self, + entrieslist: Sequence[Sequence[tuple[int, _Rational | str]]], + lhss: Sequence[_Rational | str | None] | None = None, + rhss: Sequence[_Rational | str | None] | None = None, + ) -> None: ... + def chgBound(self, col: int, lb: _Rational | str | None, ub: _Rational | str | None) -> None: ... + def chgCoef(self, row: int, col: int, newval: _Rational | str) -> None: ... + def chgObj(self, col: int, obj: _Rational | str) -> None: ... + def chgSide(self, row: int, lhs: _Rational | str | None, rhs: _Rational | str | None) -> None: ... + def clear(self) -> None: ... + def delCols(self, firstcol: int, lastcol: int) -> None: ... + def delRows(self, firstrow: int, lastrow: int) -> None: ... + def getActivity(self) -> list[Fraction]: ... + def getBase(self) -> tuple[list[int], list[int]]: ... + def getBasisInds(self) -> list[int]: ... + def getBounds( + self, firstcol: int = 0, lastcol: int | None = None + ) -> tuple[list[Fraction | float], list[Fraction | float]] | None: ... + def getDual(self) -> list[Fraction]: ... + def getDualRay(self) -> list[Fraction] | None: ... + def getIntParam(self, param: Incomplete) -> int: ... + def getNIterations(self) -> int: ... + def getObjVal(self) -> Fraction: ... + def getPrimal(self) -> list[Fraction]: ... + def getPrimalRay(self) -> list[Fraction] | None: ... + def getRealParam(self, param: Incomplete) -> float: ... + def getRedcost(self) -> list[Fraction]: ... + def getSides( + self, firstrow: int = 0, lastrow: int | None = None + ) -> tuple[list[Fraction | float], list[Fraction | float]] | None: ... + def infinity(self) -> float: ... + def isDualFeasible(self) -> bool: ... + def isInfinity(self, val: _Rational | str) -> bool: ... + def isOptimal(self) -> bool: ... + def isPrimalFeasible(self) -> bool: ... + def ncols(self) -> int: ... + def nrows(self) -> int: ... + def readLP(self, filename: str) -> None: ... + def setBase(self, cstat: Sequence[int], rstat: Sequence[int]) -> None: ... + def setIntParam(self, param: Incomplete, value: int) -> None: ... + def setRealParam(self, param: Incomplete, value: float) -> None: ... + def solve(self, dual: bool = True) -> Fraction | None: ... + def writeLP(self, filename: str) -> None: ... + class MatrixConstraint(np.ndarray): def getConshdlrName(self) -> Incomplete: ... def isActive(self) -> Incomplete: ... diff --git a/tests/test_lpexact.py b/tests/test_lpexact.py new file mode 100644 index 000000000..b8e2e4865 --- /dev/null +++ b/tests/test_lpexact.py @@ -0,0 +1,140 @@ +from fractions import Fraction + +import pytest + +from pyscipopt import LPExact, SCIP_BASESTAT, SCIP_LPPARAM + +F = Fraction +INF = float("inf") + + +def _exact_lp_supported(): + try: + LPExact() + except ValueError: + return False + return True + + +pytestmark = pytest.mark.skipif(not _exact_lp_supported(), reason="SCIP was built without an exact LP solver") + + +def all_fractions(values): + return all(type(v) is Fraction for v in values) + + +def test_lpexact_build_solve_and_modify(): + lp = LPExact("exact") + assert repr(lp) == "exact" + assert lp.ncols() == 0 and lp.nrows() == 0 + assert lp.infinity() == INF + assert lp.isInfinity(lp.infinity()) and not lp.isInfinity(F(10) ** 30) + + lp.addCols([[], []], objs=[F(1, 3), F(1, 7)]) + lp.addRow([(0, F(2, 3)), (1, F(5, 7))], lhs=F(1, 11)) + assert lp.ncols() == 2 and lp.nrows() == 1 + assert lp.getBounds() == ([0, 0], [INF, INF]) + assert lp.getSides() == ([F(1, 11)], [INF]) + assert lp.getBounds(1, 0) is None + + objval = lp.solve() + assert lp.isOptimal() and lp.isPrimalFeasible() and lp.isDualFeasible() + assert objval == F(1, 55) and type(objval) is Fraction + assert lp.getObjVal() == F(1, 55) + assert lp.getPrimal() == [0, F(7, 55)] + assert lp.getDual() == [F(1, 5)] + assert lp.getRedcost() == [F(1, 5), 0] + assert lp.getActivity() == [F(1, 11)] + assert all_fractions(lp.getPrimal() + lp.getDual() + lp.getRedcost() + lp.getActivity()) + assert lp.getNIterations() >= 0 + assert lp.getPrimalRay() is None and lp.getDualRay() is None + + assert len(lp.getBasisInds()) == lp.nrows() + cstat, rstat = lp.getBase() + assert len(cstat) == 2 and len(rstat) == 1 + assert set(cstat) <= {SCIP_BASESTAT.LOWER, SCIP_BASESTAT.BASIC, SCIP_BASESTAT.UPPER, SCIP_BASESTAT.ZERO} + lp.setBase(cstat, rstat) + assert lp.solve(dual=False) == F(1, 55) + assert lp.getBase() == (cstat, rstat) + with pytest.raises(ValueError): + lp.setBase([SCIP_BASESTAT.BASIC], rstat) + + lp.chgObj(0, F(1, 10)) + assert lp.solve() == F(3, 220) + lp.chgBound(0, 0, F(1, 22)) + assert lp.solve() == F(1, 60) + assert lp.getBounds(0, 0) == ([0], [F(1, 22)]) + lp.chgSide(0, F(1, 11), F(1, 11)) + assert lp.solve() == F(1, 60) + assert lp.getSides() == ([F(1, 11)], [F(1, 11)]) + lp.chgCoef(0, 1, F(10, 7)) + assert lp.solve() == F(1, 110) + assert lp.getPrimal() == [0, F(7, 110)] + + lp.addCol([(0, 1)], obj=F(1, 2), lb=0, ub=1) + assert lp.ncols() == 3 + assert lp.solve() == F(1, 110) and lp.getPrimal()[2] == 0 + lp.delCols(2, 2) + lp.addRows([[(0, 1), (1, 1)]], lhss=[-INF], rhss=[F(1, 2)]) + assert lp.nrows() == 2 + assert lp.getSides(1, 1) == ([-INF], [F(1, 2)]) + assert lp.solve() == F(1, 110) + lp.delRows(1, 1) + assert lp.nrows() == 1 + + lp.addCol([], obj="1/9") + assert lp.solve() == F(1, 110) + + with pytest.raises(ValueError): + lp.addCol([], obj=float("nan")) + with pytest.raises(TypeError): + lp.addRow([(0, None)]) + assert lp.ncols() == 3 and lp.nrows() == 1 + + lp.clear() + assert lp.ncols() == 0 and lp.nrows() == 0 + + with pytest.raises(Warning): + LPExact(sense="sideways") + + +def test_lpexact_unbounded_and_infeasible(): + lp = LPExact(sense="maximize") + lp.addCol([], obj=1) + lp.solve() + assert not lp.isOptimal() + ray = lp.getPrimalRay() + assert len(ray) == 1 and ray[0] > 0 and all_fractions(ray) + + lp = LPExact() + lp.addCol([], lb=0, ub=1) + lp.addRow([(0, 1)], lhs=2) + lp.solve() + assert not lp.isOptimal() and not lp.isPrimalFeasible() + farkas = lp.getDualRay() + assert len(farkas) == 1 and farkas[0] != 0 and all_fractions(farkas) + + +def test_lpexact_params_and_files(tmp_path): + lp = LPExact() + for param, value in [(SCIP_LPPARAM.FROMSCRATCH, 1), (SCIP_LPPARAM.LPITLIM, 7), (SCIP_LPPARAM.SCALING, 0)]: + lp.setIntParam(param, value) + assert lp.getIntParam(param) == value + for param, value in [(SCIP_LPPARAM.LPTILIM, 12.5), (SCIP_LPPARAM.OBJLIM, 3.0)]: + lp.setRealParam(param, value) + assert lp.getRealParam(param) == value + with pytest.raises(KeyError): + lp.getRealParam(SCIP_LPPARAM.BARRIERCONVTOL) + with pytest.raises(KeyError): + lp.setIntParam(SCIP_LPPARAM.THREADS, 2) + + lp.addCols([[], []], objs=[1, 4]) + lp.addRow([(0, 1), (1, 2)], lhs=5) + path = tmp_path / "exact.lp" + lp.writeLP(str(path)) + assert path.exists() + + other = LPExact() + other.readLP(str(path)) + assert other.ncols() == 2 and other.nrows() == 1 + assert other.solve() == 5 From b09e15b2230775b220c1bde79f4028a882926986 Mon Sep 17 00:00:00 2001 From: Joao-Dionisio Date: Thu, 12 Nov 2026 10:11:43 +0000 Subject: [PATCH 2/2] Add LPExact changelog entry --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bb240e58..6a90ae6b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Added more type annotations and deprecation markers to the stubs. - Added tests for `getObjVal()` and `getVal()` - Added `addConsLinear()` to add linear constraints from variables and coefficients without building an expression +- Added `LPExact` to build and solve LPs in exact rational arithmetic through SCIP 11's exact LP interface ### Fixed - Fixed `lotsizing_lazy` example: lock the handler's variables in `conslock` so presolve cannot aggregate them away (#1252) - Dual and Farkas getters for linear, knapsack, and logicor constraints now return zero when presolving has removed them.