Skip to main content

Fastest way to add constraints

Answered

Comments

1 comment

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Since you have all information at hand your approach is probably already the fastest. You can avoid the if-clause 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.