Find the first occurence of a 1 during optimisation
AnsweredHi,
I'm quite new at using Gurobi.
In my model, I only have binary variables. They are stored in a list (let assume [x0, x1, x2, x3, x4])
How can I find the first occurence of a 1 and add a constraint on it ?
For example:
Suppose the optimal solution found is [0,0,1,1,0] (but I can't access it directly as the optimization is still in progress).
I want to create another list that would be equal to [0,0,1,0,0] (all variables equal to 0 except the one at the same position as the first occurrence of 1 in the previous list) and add a constraint to it.
Does anyone have an idea ?
Thanks a lot ! (I hope I formulated my question clearly)
-
Hi Daphnée,
you can indeed access all feasible solutions found in the course of the optimization process - this can be achieved by callbacks (here's an example).
If I understood you correctly, you would be interested in querying the values of the variables in the incumbent solution and then adding some kind of constraint to the original model.
Querying can be done as follows:
def mycallback(model, where):
if where == GRB.Callback.MIPSOL: # we are interested in situations in which the solver has found an integer feasible solution
current_solution = model.cbGetSolution(model._vars)
# now, current solution holds the list of variable values in the current solution.
# from here on you can add your special constraint
m = gp.Model()
# ... defining your model here
m._vars = m.getVars()
m.optimize(mycallback)To be able to help you with the constraint, it would be useful to see the mathematical formulation of the model you are trying to solve, as well as the constraint you are trying to implement. We will then gladly help you further.
Best regards
Jonasz0 -
Hi Daphnée,
Are you perhaps just wanting another set of variables, y, that maintain the relationship you have described to the x variables? It is not quite clear, but if so then you can define \(y_0, y_1, \ldots, y_4\) and constraints:
\[\sum_{i=0}^4 y_i \leq 1\]
\[y_i \leq x_i, \forall i = 0, \ldots, 4\]
\[\sum_{i=0}^j y_i \geq x_j, \forall j = 0, \ldots, 4\]to achieve this. You can then define indicator constraints (either explicitly or in Big M form) on a particular y variable to constrain the corresponding x variable in the case that the particular y variable is 1.
- Riley
0 -
Hi Riley,
Thank you very much for your quick response. This is exactly what I was looking for !
0
Please sign in to leave a comment.
Comments
3 comments