Skip to main content

Fastest way to add constraints

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Jaromił Najman
    • 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

Post is closed for comments.