Implement iteration_cb for LearningSolver; reactivate TSP

This commit is contained in:
2020-09-23 17:46:18 -05:00
parent 5390a5b656
commit e527e75481
8 changed files with 91 additions and 60 deletions

View File

@@ -21,3 +21,6 @@ class Component(ABC):
@abstractmethod
def fit(self, training_instances):
pass
def after_iteration(self, solver, instance, model):
return False

View File

@@ -38,6 +38,18 @@ class DynamicLazyConstraintsComponent(Component):
cut = instance.build_lazy_constraint(model, v)
solver.internal_solver.add_constraint(cut)
def after_iteration(self, solver, instance, model):
logger.debug("Finding violated (dynamic) lazy constraints...")
violations = instance.find_violated_lazy_constraints(model)
if len(violations) == 0:
return False
instance.found_violated_lazy_constraints += violations
logger.debug(" %d violations found" % len(violations))
for v in violations:
cut = instance.build_lazy_constraint(model, v)
solver.internal_solver.add_constraint(cut)
return True
def after_solve(self, solver, instance, model, results):
pass

View File

@@ -35,13 +35,20 @@ class StaticLazyConstraintsComponent(Component):
def after_solve(self, solver, instance, model, results):
pass
def on_callback(self, solver, instance, model):
print(self.pool)
def after_iteration(self, solver, instance, model):
logger.debug("Finding violated (static) lazy constraints...")
n_added = 0
for c in self.pool:
if not solver.internal_solver.is_constraint_satisfied(c.obj):
self.pool.remove(c)
solver.internal_solver.add_constraint(c.obj)
instance.found_violated_lazy_constraints += [c.cid]
n_added += 1
if n_added > 0:
logger.debug(" %d violations found" % n_added)
return True
else:
return False
def fit(self, training_instances):
logger.debug("Extracting x and y...")

View File

@@ -95,8 +95,9 @@ def test_usage_with_solver():
])
internal.add_constraint.reset_mock()
# LearningSolver calls callback (first time)
component.on_callback(solver, instance, None)
# LearningSolver calls after_iteration (first time)
should_repeat = component.after_iteration(solver, instance, None)
assert should_repeat
# Should ask internal solver to verify if constraints in the pool are
# satisfied and add the ones that are not
@@ -105,8 +106,9 @@ def test_usage_with_solver():
internal.add_constraint.assert_called_once_with("<c2>")
internal.add_constraint.reset_mock()
# LearningSolver calls callback (second time)
component.on_callback(solver, instance, None)
# LearningSolver calls after_iteration (second time)
should_repeat = component.after_iteration(solver, instance, None)
assert not should_repeat
# The lazy constraint pool should be empty by now, so no calls should be made
internal.is_constraint_satisfied.assert_not_called()