Adding indexed name to a complex constraint
AnsweredI have defined sets of constraints using model.addConstrs(), quicksum and generator expression. As an example, take a look at below.
model.addConstrs(
(
gp.quicksum(
x[c1, c2]
for (c1, c2) in d[(s1, s2)]["trips"]
)
<= d[(s1, s2)]["upper_bound"]
for s1, s2 in d
)
)
So, essentially I have a dictionary d, whose keys are tuples (s1, s2). For every tuple, the values are multiple lists of [c1, c2] (say 10 lists for example). I use these lists to pick certain indexes of x over which I take a sum. The sum has to be less than ["upper_bound"].
I now need to defined names for my constraints. I desire to have names like my_constr_s1_s2 for each unique key (s1,s2).
How can I achieve this in Gurobipy in my code?
-
Your code already does everything except for the constraint naming. The addConstrs method takes a name argument to define the name pattern. If you add name="my_constr", your constraint names will be my_constr[s1,s2]. Would that work for you?
0 -
Thanks,
That did work in my case and I could access constraint names using the indexes.
I have a follow up question: How can I now access the Left hand side of a certain constraint i.e. the expression using only the constraint names?0 -
If you have a constraint object, you need to use the getRow method on the model to get the left-hand-side expression. This will then be a LinExpr object.
One question: Did you need the names to access the constraints (via getConstrByName)? The addConstrs method returns a dictionary that you could use to access them more efficiently. For example:
my_constrs = model.addConstrs(
# your code
)
constr = my_constrs[(s1,s2)]
row = model.getRow(constr)1 -
Thanks. Is there anyway I can simple use the constraint names defined earlier to access the expression rather than having an object defined for them?
0 -
I am not sure I understand your question.
You could use getConstrByName to access the constraint by its name. However, we usually discourage using this function since it is not very efficient. Storing the constraints in a dictionary is usually the more efficient way to do this. However, for small models, it should not make a noticeable difference.
In order to get the expression on the left-hand side, there is no way around getRow. You could chain it into one line though:
lin_expr = model.getRow(model.getConstrByName("<your_name>"))
Does that help?
1 -
yes, this helps.
Thanks for the answers.0
Please sign in to leave a comment.
Comments
6 comments