Skip to content

Instantly share code, notes, and snippets.

@ruoyu0088
Created June 12, 2017 02:12
Show Gist options
  • Save ruoyu0088/48858ddb4e8504670ae8bf4df852e277 to your computer and use it in GitHub Desktop.
Save ruoyu0088/48858ddb4e8504670ae8bf4df852e277 to your computer and use it in GitHub Desktop.
from ortools.constraint_solver import pywrapcp
def SolutionCollector__len__(self):
return self.SolutionCount()
def SolutionCollector__getitem__(self, index):
if index < len(self):
return self.Solution(index)
else:
raise IndexError("index out of range {} of {}".format(index, len(self)))
def IntContainer__getitem__(self, index):
if index < len(self):
return self.Element(index)
else:
raise IndexError("index out of range {} of {}".format(index, len(self)))
pywrapcp.SolutionCollector.__len__ = lambda self: self.SolutionCount()
pywrapcp.SolutionCollector.__getitem__ = SolutionCollector__getitem__
pywrapcp.Assignment.intvars = property(lambda self: self.IntVarContainer())
pywrapcp.IntContainer.__len__ = lambda self: self.Size()
pywrapcp.IntContainer.__getitem__ = IntContainer__getitem__
pywrapcp.IntVarElement.name = property(lambda self: self.Var().Name())
pywrapcp.IntVarElement.value = property(lambda self: self.Value())
def iter_solutions(collector):
for assignment in collector:
yield [(el.name, el.value) for el in assignment.intvars]
def solve(solver, variables, collector_name="First", monitors=None):
if monitors is None:
monitors = []
solution = solver.Assignment()
solution.Add(variables)
collector = getattr(solver, collector_name + "SolutionCollector")(solution)
phase = solver.Phase(variables, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE)
if solver.Solve(phase, [collector] + monitors):
return iter_solutions(collector)
else:
return ()
class LogMonitor(pywrapcp.SearchMonitor):
def EnterSearch(self):
print("EnterSearch")
def RestartSearch(self):
print("RestartSearch")
def ExitSearch(self):
print("ExitSearch")
def BeginNextDecision(self, b):
print("BeginNextDecision", b)
def EndNextDecision(self, b, d):
print("EndNextDecision", b, d)
def ApplyDecision(self, d):
print("ApplyDecision", d)
def RefuteDecision(self, d):
print("RefuteDecision", d)
def AfterDecision(self, d, apply):
print("AfterDecision", d, apply)
def BeginFail(self):
print("BeginFail")
def EndFail(self):
print("EndFail")
def BeginInitialPropagation(self):
print("BeginInitialPropagation")
def EndInitialPropagation(self):
print("EndInitialPropagation")
def AcceptSolution(self):
print("AcceptSolution")
return super().AcceptSolution()
def AtSolution(self):
print("AtSolution")
return super().AtSolution()
def NoMoreSolutions(self):
print("NoMoreSolutions")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment