Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple MILP solutions in ORTOOLS [python]

I am trying to use or-tools in Python to solve a mixed-integer linear program that has multiple optimal solutions. However, NextSolution() always returns False, so I cannot retrieve more than one solution. I understand that this function works using a constraint solver, but I would like to use the MILP solver.

The related or-tools documentation states:

As of 2020-02-10, only Gurobi and SCIP support NextSolution(), see linear_solver_interfaces_test for an example of how to configure these solvers for multiple solutions. Other solvers return false unconditionally.

However, I cannot find any such linear_solver_interfaces_test in the source repo, documentation, or via a web search. I am using ortools version 7.8.7959 and the included SCIP 7.0.1 with Python 3.6.9.

Below is my example code which illustrates a simple example of the type I would like to solve. It should produce three unique solutions, but currently produces zero solutions.

from ortools.linear_solver import pywraplp

def main():
    solver = pywraplp.Solver("multiple_solution_test", pywraplp.Solver.SCIP_MIXED_INTEGER_PROGRAMMING)
    x = solver.IntVar(0, 2, "x")
    y = solver.IntVar(0, 2, "y")
    z = solver.IntVar(0, 2, "z")
    solver.Add(x + y <= 2)
    solver.Maximize(x + y + z)  # should be 4, which can be obtained by (2,0,2), (1,1,2), or (0,2,2)
    solver.Solve()
    print_solutions(solver, x, y, z)


def print_solutions(solver, x, y, z):
    count = 0
    
    while solver.NextSolution():  # <-- NextSolution() always returns False!
        count += 1
        print("x =", x.solution_value(), "y =", y.solution_value(), "z =", z.solution_value())
    print("\nNumber of solutions found:", count)
    
    
if __name__ == "__main__":
    main()
like image 693
David Haley Avatar asked Dec 06 '25 14:12

David Haley


1 Answers

Sorry for the misleading documentation. Currently, only Gurobi supports NextSolution. I have not exported the SCIP relevant code.

If your problem only needs Boolean or integer variable, you can use the CP-SAT (ortools/sat) solver that supports enumerating over multiple solutions.

see this documentation.

like image 179
Laurent Perron Avatar answered Dec 08 '25 06:12

Laurent Perron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!