Keeping count of variable occurence in google OR Tools

72 views Asked by At

I'm playing around with OR Tools, just wondering if there is any way to hold the number of times a certain constraint is satisfied?

In this case, I'd like to keep track of the number of times my 'diff' variable is -1, -2, 0, 2 , etc.

I've gotten the solution printer from the official documentation, so would I have to edit/tweak that in any way to return count as well?

Thanks in advance, I'm new to this.

from ortools.sat.python import cp_model
model = cp_model.CpModel()
x = model.NewIntVar(0, 10, 'x')
y = model.NewIntVar(0, 10, 'y')
diff = model.NewIntVar(-10,10,'diff')
model.Add(diff == x - y)
#occurences of each diff

#solution printer
class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
    """Print intermediate solutions."""

    def __init__(self, variables):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__variables = variables
        self.__solution_count = 0

    def on_solution_callback(self):
        self.__solution_count += 1
        for v in self.__variables:
            print(f"{v}={self.Value(v)}", end=" ")
        print()

    def solution_count(self):
        return self.__solution_count

solver = cp_model.CpSolver()
# solver.parameters.log_search_progress = True
solution_printer = VarArraySolutionPrinter([x, y, diff])
solver.parameters.enumerate_all_solutions = True
status = solver.Solve(model, solution_printer)
1

There are 1 answers

1
Laurent Perron On BEST ANSWER

Why don't you just increase a counter in the on_solution_callback() method ?