Skip to main content

How add constraints temporarily to the model?

Ongoing

Comments

5 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 why not try our AI Gurobot?.
  • Eli Towle
    • Gurobi Staff

    You can use Model.remove() to remove constraints from your model. What code are you currently using to remove the constraints? And how many constraints are you removing? 

    0
  • Amin Ahmadi
    • Gurobi-versary
    • Curious
    • First Comment

    Eli,

    Thanks for your response. As I said, I am using the remove function to eliminate constraints. Since I have to remove more than 6000 thousand constraints, this does not work for me. This is the way I remove constraints:

    for cons in model.getConstrs():
        if 'line' in cons.ConstrName:
            model.remove(cons)

     
     
    0
  • Eli Towle
    • Gurobi Staff

    This approach isn't too efficient, because you check if every model constraint name includes the text \( \texttt{`line`} \). How do you add the \( \texttt{line} \) constraints to your model? If you use Model.addConstrs(), you can pass the tupledict returned by this method directly to Model.remove():

    c = model.addConstrs((x[i] <= 1 for i in range(n)), name='line')
    model.optimize()

    # Remove all "line" constraints
    model.remove(c)

    Some alternative approaches are:

    • When building the model, use Model.copy() to create a copy of the model before the \( \texttt{line} \) constraints are added. Then, use the model copy in subsequent iterations of your algorithm.
    • Find a minimal way to modify the constraints so they are redundant. For example, if you want to remove the constraint \( \sum_{i = 1}^n x_i \leq 1 \) where the \( x_i \) are non-negative, you can change the constraint to \( \sum_{i = 1}^n x_i \geq 0 \) by modifying the Sense and RHS attributes of the Constr object. The constraint is still in the model, but it is now redundant. Gurobi should recognize this and remove the constraint during the presolve phase.
    • Build the model from scratch without the \( \texttt{line} \) constraints.
    0
  • Amin Ahmadi
    • Gurobi-versary
    • Curious
    • First Comment

    I understood. Your suggestions work perfectly. 

    Thanks for your time. 

    0

Post is closed for comments.