How add constraints temporarily to the model?
OngoingHi,
I am implementing an iterative method for solving a problem. We need to have a set of constraints in the model at one iteration but not necessary for the subsequent iterations. One way is to remove them at the beginning of the next iteration altogether. However, this is a timeconsuming solution. I need an intelligent way to add a set of constraints to the model at one iteration, and while I run the second iteration, those added constraints are no longer in the model? I will be appreciated it if you suggest me a way to do it.
Thanks.

You can use Model.remove() to remove constraints from your model. What code are you currently using to remove the constraints? And how many constraints are you removing?
0 
Eli,
Thanks for your response. As I said, I am using the remove function to eliminate constraints. Since I have to remove more than 6000 thousand constraints, this does not work for me. This is the way I remove constraints:
for cons in model.getConstrs():
if 'line' in cons.ConstrName:
model.remove(cons)0 
This approach isn't too efficient, because you check if every model constraint name includes the text \( \texttt{`line`} \). How do you add the \( \texttt{line} \) constraints to your model? If you use Model.addConstrs(), you can pass the tupledict returned by this method directly to Model.remove():
c = model.addConstrs((x[i] <= 1 for i in range(n)), name='line')
model.optimize()
# Remove all "line" constraints
model.remove(c)Some alternative approaches are:
 When building the model, use Model.copy() to create a copy of the model before the \( \texttt{line} \) constraints are added. Then, use the model copy in subsequent iterations of your algorithm.
 Find a minimal way to modify the constraints so they are redundant. For example, if you want to remove the constraint \( \sum_{i = 1}^n x_i \leq 1 \) where the \( x_i \) are nonnegative, you can change the constraint to \( \sum_{i = 1}^n x_i \geq 0 \) by modifying the Sense and RHS attributes of the Constr object. The constraint is still in the model, but it is now redundant. Gurobi should recognize this and remove the constraint during the presolve phase.
 Build the model from scratch without the \( \texttt{line} \) constraints.
0 
I understood. Your suggestions work perfectly.
Thanks for your time.
0
Please sign in to leave a comment.
Comments
4 comments