Zying
Zying

Reputation: 13

Obtain all value while Gurobi has only one feasible solutions in Python

How do I get all the value of the variable while Gurobi has only one feasible solution? for example: Optimal objective is 5 and there are four values that can reach the feasible solution,as shown below. [1, 2, 1, 1], [2, 1, 1, 1], [2, 1, 2, 0], [3, 0, 2, 0] But the Gurobi only show one value,as show below:

x[0]:3.0
x[1]:0.0
x[2]:2.0
x[3]:0.0

please tell me how do I get all the value.Thank you very much!

Upvotes: 1

Views: 688

Answers (1)

joni
joni

Reputation: 7157

Assuming you want to enumerate all optimal solutions for a MIP, you can do it with the help of the PoolGap, PoolSolutions and PoolSearchMode parameters.

  • The PoolSolutions parameter determines how many feasible solutions are stored while solving the MIP.
  • The PoolGap parameter determines the allowed gap for all stored solutions. Set it to 0.0 to only allow optimal solutions inside the solution pool.
  • The PoolSearchMode parameter sets the search mode for the MIP tree search. Set it to 2 to search for the n best solutions, where n is just the value set for PoolSolutions.

Here's a minimal example:

import gurobipy as gp

coins = [1, 2, 5, 10, 20, 50, 100, 200]

m = gp.Model()
x = m.addVars(8, vtype='I', name="x")
m.addConstr(sum(coins[i]*x[i] for i in range(8)) == 200)

# Parameters
m.Params.PoolSearchMode = 2
m.Params.PoolSolutions = 10**8
m.Params.PoolGap = 0.0

# Optimize
m.optimize()

# Iterate over all found solutions
for k in range(m.SolCount):
    m.Params.SolutionNumber = k
    print([var.Xn for var in m.getVars()])

Upvotes: 2

Related Questions