|
| 1 | +""" |
| 2 | +Tests the usage of sub solutions found in heuristics with copyLargeNeighborhoodSearch() |
| 3 | +""" |
| 4 | +import pytest |
| 5 | +from pyscipopt import Model, Heur, SCIP_HEURTIMING, SCIP_RESULT |
| 6 | + |
| 7 | + |
| 8 | +class MyHeur(Heur): |
| 9 | + def __init__(self, model: Model, fix_vars, fix_vals): |
| 10 | + super().__init__() |
| 11 | + self.original_model = model |
| 12 | + self.used = False |
| 13 | + self.fix_vars = fix_vars |
| 14 | + self.fix_vals = fix_vals |
| 15 | + |
| 16 | + def heurexec(self, heurtiming, nodeinfeasible): |
| 17 | + print("Hello World") |
| 18 | + self.used = True |
| 19 | + # fix z to 2 and optimize the remaining problem |
| 20 | + m2 = self.original_model.copyLargeNeighborhoodSearch(self.fix_vars, self.fix_vals) |
| 21 | + m2.optimize() |
| 22 | + |
| 23 | + # translate the solution to the original problem |
| 24 | + sub_sol = m2.getBestSol() |
| 25 | + sol_translation = self.original_model.translateSubSol(m2, sub_sol, self) |
| 26 | + |
| 27 | + accepted = self.original_model.trySol(sol_translation) |
| 28 | + assert accepted |
| 29 | + m2.freeProb() |
| 30 | + return {"result": SCIP_RESULT.FOUNDSOL} |
| 31 | + |
| 32 | + |
| 33 | +def test_sub_sol(): |
| 34 | + m = Model("sub_sol_test") |
| 35 | + x = m.addVar(name="x", lb=0, ub=3, obj=1) |
| 36 | + y = m.addVar(name="y", lb=0, ub=3, obj=2) |
| 37 | + z = m.addVar(name="z", lb=0, ub=3, obj=3) |
| 38 | + |
| 39 | + m.addCons(4 <= x + y + z) |
| 40 | + |
| 41 | + # include the heuristic |
| 42 | + my_heur = MyHeur(m, fix_vars= [z], fix_vals = [2]) |
| 43 | + m.includeHeur(my_heur, "name", "description", "Y", timingmask=SCIP_HEURTIMING.BEFOREPRESOL, usessubscip=True) |
| 44 | + |
| 45 | + #optimize |
| 46 | + m.optimize() |
| 47 | + # assert the heuristic did run |
| 48 | + assert my_heur.used |
| 49 | + |
| 50 | + heur_sol = [2, 0, 2] |
| 51 | + opt_sol = [3, 1, 0] |
| 52 | + |
| 53 | + found_solutions = [] |
| 54 | + for sol in m.getSols(): |
| 55 | + found_solutions.append([sol[x], sol[y], sol[z]]) |
| 56 | + |
| 57 | + # both the sub_solution and the real optimum should be in the solution pool |
| 58 | + assert heur_sol in found_solutions |
| 59 | + assert opt_sol in found_solutions |
0 commit comments