When multiple termination parameters are used, Gurobi Optimizer will stop when it reaches the first one. For example, if you want to stop when you reach 10% MIP gap or when 60 seconds have elapsed, then set MIPGap=0.1 and TimeLimit=60.
If a more complex set of stopping criteria is required, one possibility is to use warm starts. For example:
- Suppose you need a 1% MIP gap, while a smaller MIP gap is preferable if it takes less than 300 seconds. To implement this rule set, start with TimeLimit=300. If the value of the MIPGap attribute is larger than 0.01 when the time limit is reached, then increase the TimeLimit parameter, set the MIPGap parameter to 0.01, and continue to solve the MIP.
- To set a time limit that is considered only if at least one feasible solution has been found, you could use:
timeLimit = 20
try:
m = read('b1c1s1.mps.gz')
oldSolutionLimit = m.Params.SolutionLimit
m.Params.SolutionLimit = 1
m.optimize()
m.Params.TimeLimit = timeLimit - m.getAttr(GRB.Attr.Runtime)
m.Params.SolutionLimit = oldSolutionLimit - m.Params.SolutionLimit
m.optimize()
except (GurobiError, AttributeError, Exception) as e:
print('Caught: ' + e.message)
For more complex termination criteria, you may want to consider using callbacks. Please see How do I use callbacks to terminate the solver? for more information.
Further information
Comments
2 comments
This code raises an exception if the first solution is obtained after the timeLimit. This is because once the first solution is found, the m.Params.TimeLimit is adjusted.
If the Runtime is already over the timeLimit, then it raises the exception:
Caught: Unable to set parameter TimeLimit to value -28.9511 (minimum is 0)
For it to work, the code needs to be adjusted to say
Note it is highly unlikely that the runtime will exceed the TimeLimit, as the said TimeLimit value has already been used as one of the termination criterion. However, indeed, in some corner cases this may happen. A simple way to address this is to add 'max' clause as suggested, but you may also want to build out some more logic here to understand what exactly happened. Thank you for pointing this out.
Article is closed for comments.