Skip to main content

Adding indexed name to a complex constraint

Answered

Comments

6 comments

  • Silke Horn
    Gurobi Staff Gurobi Staff

    Your code already does everything except for the constraint naming. The addConstrs method takes a name argument to define the name pattern. If you add name="my_constr", your constraint names will be my_constr[s1,s2]. Would that work for you?

    0
  • Nitin Singh
    Gurobi-versary
    Conversationalist
    First Question

    Thanks,
    That did work in my case and I could access constraint names using the indexes.
    I have a follow up question: How can I now access the Left hand side of a certain constraint i.e. the expression using only the constraint names?

    0
  • Silke Horn
    Gurobi Staff Gurobi Staff

    If you have a constraint object, you need to use the getRow method on the model to get the left-hand-side expression. This will then be a LinExpr object.

    One question: Did you need the names to access the constraints (via getConstrByName)? The addConstrs method returns a dictionary that you could use to access them more efficiently. For example:

    my_constrs = model.addConstrs(
    # your code
    )

    constr = my_constrs[(s1,s2)]
    row = model.getRow(constr)
    1
  • Nitin Singh
    Gurobi-versary
    Conversationalist
    First Question

    Thanks. Is there anyway I can simple use the constraint names defined earlier to access the expression rather than having an object defined for them?

    0
  • Silke Horn
    Gurobi Staff Gurobi Staff

    I am not sure I understand your question.

    You could use getConstrByName to access the constraint by its name. However, we usually discourage using this function since it is not very efficient. Storing the constraints in a dictionary is usually the more efficient way to do this. However, for small models, it should not make a noticeable difference.

    In order to get the expression on the left-hand side, there is no way around getRow. You could chain it into one line though:

    lin_expr = model.getRow(model.getConstrByName("<your_name>"))

    Does that help?

    1
  • Nitin Singh
    Gurobi-versary
    Conversationalist
    First Question

    yes, this helps. 
    Thanks for the answers. 

    0

Please sign in to leave a comment.