LinExpr() as a faster alternative to quicksum() for constraint building?
Awaiting user inputI 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 have plenty of such constraints in my model. I read in a post (here) that gp.LinExpr() may be a faster alternative to quicksum(). I would like to test this hypothesis in my code. I am new to Gurobipy API. Could someone suggest me a way to implement LinExpr() in here if possible.
Also, as I mentioned I have multiple such constraints i.e multiple dictionaries d_1, d_2 .... which I preprepared for my requirement for building constraints.
Could there be a faster alternative to this as well?
Best Regards,

Comment:
I attempted to use gp.LinExpr(). Is my below prototype correct?model.addConstrs( ( gp.LinExpr( (1.0, x[c1, c2]) for (c1, c2) in d[(s1, s2)]["trips"] ) <= d[(s1, s2)]["upper_bound"] for s1, s2 in d ) )
I believe it is, as I got the code running and achieved the same model stats/obj func val.
However, despite this the model generation time was not noticeably changed.0 
Yes, the code looks correct. The LinExpr constructor should be the fastest way to build these expressions. However, you will only see a noticeable difference for very large expressions (hundreds of terms).
How long is your model building time? If it is slow, have you already profiled it?
You can use cProfile to find out how much time is spent in which function. This should help you narrow down which part of your code you should focus on improving.
1
Please sign in to leave a comment.
Comments
2 comments