Reputation: 1
I have a complex MIP model in Python, solve with Gurobi, and long program to run. Usually, I run it and then write the output (values of variables, solution parameters, etc.) to a file. For large instances, the model does not find any solution within the time limit, and then logically gives me an error when I try to retrieve values for variables, which stops the whole code. In this case, I would like it to skip the output section. I tried to achieve this by only writing the output if model.Params.SolutionCount != 0. However, it still gives me the same error of trying to retrieve the variables within the if-statement. Is there any other way to tell Python to skip code if there is no solution without interrupting the program completely? Thank you!
Upvotes: 0
Views: 506
Reputation: 6726
You should always check the solution status before trying to query solution values. This can be like this:
...
model.optimize()
if model.status == GRB.INF_OR_UNBD:
# Turn presolve off to determine whether the model is infeasible
# or unbounded
model.setParam(GRB.Param.Presolve, 0)
model.optimize()
if model.status == GRB.OPTIMAL:
print('Optimal objective: %g' % model.objVal)
model.write('model.sol')
sys.exit(0)
elif model.status != GRB.INFEASIBLE:
print('Optimization was stopped with status %d' % model.status)
sys.exit(0)
This is taken from the Gurobi documentation.
Upvotes: 0