forked from scipopt/PySCIPOpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_heur.py
67 lines (48 loc) · 1.63 KB
/
test_heur.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import gc
import weakref
import pytest
from pyscipopt import Model, Heur, SCIP_RESULT, SCIP_PARAMSETTING, SCIP_HEURTIMING
from pyscipopt.scip import is_memory_freed
from util import is_optimized_mode
class MyHeur(Heur):
def heurexec(self, heurtiming, nodeinfeasible):
sol = self.model.createSol(self)
vars = self.model.getVars()
self.model.setSolVal(sol, vars[0], 5.0)
self.model.setSolVal(sol, vars[1], 0.0)
accepted = self.model.trySol(sol)
if accepted:
return {"result": SCIP_RESULT.FOUNDSOL}
else:
return {"result": SCIP_RESULT.DIDNOTFIND}
def test_heur():
# create solver instance
s = Model()
heuristic = MyHeur()
s.includeHeur(heuristic, "PyHeur", "custom heuristic implemented in python", "Y", timingmask=SCIP_HEURTIMING.BEFORENODE)
s.setPresolve(SCIP_PARAMSETTING.OFF)
# add some variables
x = s.addVar("x", obj=1.0)
y = s.addVar("y", obj=2.0)
# add some constraint
s.addCons(x + 2*y >= 5)
# solve problem
s.optimize()
# print solution
assert round(s.getVal(x)) == 5.0
assert round(s.getVal(y)) == 0.0
def test_heur_memory():
if is_optimized_mode():
pytest.skip()
def inner():
s = Model()
heuristic = MyHeur()
s.includeHeur(heuristic, "PyHeur", "custom heuristic implemented in python", "Y", timingmask=SCIP_HEURTIMING.BEFORENODE)
return weakref.proxy(heuristic)
heur_prox = inner()
gc.collect() # necessary?
with pytest.raises(ReferenceError):
heur_prox.name
assert is_memory_freed()
if __name__ == "__main__":
test_heur()