Making a list of constraints in python and then deleting them

686 views
Skip to first unread message

J. Friedman

unread,
Oct 20, 2017, 9:05:10 AM10/20/17
to Gurobi Optimization
I add the following constraints:

for (s,d,t) in Y:   
         if (d != d0) and (d != d1):
             m.addConstr( (z[s,d,t] == z_m[s,d,t]), 'day_RepairOne')

Can you tell me how to make a list of constraints and then delete them?

Tobias Achterberg

unread,
Oct 20, 2017, 3:39:14 PM10/20/17
to gur...@googlegroups.com
Sure. The m.addConstr() call returns a constraint object that you can just store in your
own list, like

cons[s,d,t] = m.addConstr((z[s,d,t] == z_m[s,d,t]), 'day_RepairOne')

Then, you can call

for (s,d,t) in Y:
m.remove(cons[s,d,t])

But since Gurobi 7.5 there is actually a much nicer way to do this:

consset = m.addConstrs((z[s,d,t] == z_m[s,d,t] for (s,d,t) in Y if d != d0 and d !=
d1), name='day_RepairOne')

adds all of your constraint with a single Python statement. It returns a dictionary of
Constr objects. This you can plug directly into the remove method:

m.remove(consset)

to get rid of all these constraints. See
http://www.gurobi.com/documentation/7.5/refman/py_model_addconstrs.html and
http://www.gurobi.com/documentation/7.5/refman/py_model_remove.html


Regards,

Tobias

J. Friedman

unread,
Oct 20, 2017, 4:54:17 PM10/20/17
to Gurobi Optimization
Thanks very much Tobias, that is super simple and elegant.
Reply all
Reply to author
Forward
0 new messages