Skip to content

Commit

Permalink
Merge pull request #497 from scipopt/493-allow-NULL-solution
Browse files Browse the repository at this point in the history
proper fix for #493
  • Loading branch information
mattmilten authored Apr 25, 2021
2 parents e280010 + 53264f5 commit 87e8117
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased
### Added
### Fixed
- allow NULL solutions to query LP solutions in the correct solving stage
### Changed
### Removed

Expand Down
12 changes: 10 additions & 2 deletions src/pyscipopt/scip.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,6 @@ cdef class Solution:
cdef create(SCIP* scip, SCIP_SOL* scip_sol):
if scip == NULL:
raise Warning("cannot create Solution with SCIP* == NULL")
if scip_sol == NULL:
return None
sol = Solution()
sol.sol = scip_sol
sol.scip = scip
Expand All @@ -543,11 +541,13 @@ cdef class Solution:
def __getitem__(self, Expr expr):
# fast track for Variable
if isinstance(expr, Variable):
self._checkStage("SCIPgetSolVal")
var = <Variable> expr
return SCIPgetSolVal(self.scip, self.sol, var.scip_var)
return sum(self._evaluate(term)*coeff for term, coeff in expr.terms.items() if coeff != 0)

def _evaluate(self, term):
self._checkStage("SCIPgetSolVal")
result = 1
for var in term.vartuple:
result *= SCIPgetSolVal(self.scip, self.sol, (<Variable> var).scip_var)
Expand All @@ -560,6 +560,7 @@ cdef class Solution:
cdef SCIP_VAR* scip_var

vals = {}
self._checkStage("SCIPgetSolVal")
for i in range(SCIPgetNVars(self.scip)):
scip_var = SCIPgetVars(self.scip)[i]

Expand All @@ -569,6 +570,12 @@ cdef class Solution:

vals[name] = SCIPgetSolVal(self.scip, self.sol, scip_var)
return str(vals)

def _checkStage(self, method):
if method in ["SCIPgetSolVal", "getSolObjVal"]:
if self.sol == NULL and not SCIPgetStage(self.scip) == SCIP_STAGE_SOLVING:
raise Warning(f"{method} cannot only be called in stage SOLVING without a valid solution (current stage: {SCIPgetStage(self.scip)})")


cdef class BoundChange:
"""Bound change."""
Expand Down Expand Up @@ -4151,6 +4158,7 @@ cdef class Model:
"""
if sol == None:
sol = Solution.create(self._scip, NULL)
sol._checkStage("getSolObjVal")
if original:
objval = SCIPgetSolOrigObj(self._scip, sol.sol)
else:
Expand Down

0 comments on commit 87e8117

Please sign in to comment.