Fastest way to add constraints
AnsweredWe are currently using Python to use Gurobi. We first make all the constraints without using Gurobi. We store a list of variables cons.lhsVars = [1, 3, 5] and and list of coefficients cons.lhsCoeff = [1, 1, 1] and the rhs cons.rhs = [3]. In the end we want to make the constraint x1 + x3 + x5 <= 3.
First we make all Gurobi variables with the following code. (It's simplified, there are a few ifstatements inside the forloop whether there is a lower/upperbound or not. Otherwise I'd have used dict comprehension.
gurVars = {}
for ix, var in enumerate(variables):
gurVars[ix] = m.addVar(vtype=var.typeVar, lb=var.lowBound, ub=var.upBound, name=f"v{ix}")
Afterwards we make the constraints:
for cons in constraints:
consVars = [gurVars[i] for i in cons.lhsVars]
symbol = cons.symbol
expr = LinExpr()
expr.addTerms(cons.lhsCoeff, consVars)
if symbol == "<=":
m.addConstr(expr <= cons.rhs, name = cons.naam)
elif symbol == "==":
m.addConstr(expr == cons.rhs, name = cons.naam)
elif symbol == ">=":
m.addConstr(expr >= cons.rhs, name = cons.naam)
Is there a way to make this code faster? I think most advantages can be made in the second part of the code. Thanks for your help.

Since you have all information at hand your approach is probably already the fastest. You can avoid the ifclause during constraint construction and additionally use the addLConstr() method if you are working with linear constraints only.
for cons in constraints:
consVars = [gurVars[i] for i in cons.lhsVars]
symbol = cons.symbol[0] # get the sense '<', '=', '>'
expr = LinExpr(cons.lhsCoeff, consVars)
m.addLConstr(expr, sense = symbol, rhs = cons.rhs, name = cons.naam)Alternatively, you could manipulate your data a bit and use the Python Matrix API which can be faster than the "traditional" approach. The addMConstr method would construct all linear constraints at once. In your case, you would have to use a list for your variables and numpy arrays for your lhs, rhs, and symbol lists. The matrix1.py example is a good point to get started with the Python Matrix API.
The Knowledge Base article How do I improve the time to build my model? might hold additional information.
Best regards,
Jaromił1
Please sign in to leave a comment.
Comments
1 comment