Skip to main content

Adding and referencing constraints

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff 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 Gurobi Staff

    You can use Model.addConstrs() to add multiple constraints at once. The returned value is a tupledict that maps the generator expression indices to the corresponding Constr objects.

    Below is an example you can modify to fit your needs. It also takes advantage of Model.addVars() and tupledict.sum().

    xBar = m.addVars(N, T, vtype=GRB.BINARY, name='xBar')
    # c is a tupledict mapping indices 0..N-1 to Constr objects
    c = m.addConstrs((xBar.sum(i, '*') == 1 for i in range(N)), name='sum_to_one')

    m.optimize()

    for i in range(N):
        print(c[i].ConstrName, c[i].Pi)

    Note that you can use Model.getAttr() to obtain a tupledict mapping the constraint indices to their corresponding Pi values:

    # pi is a tupledict mapping 0..N-1 to the corresponding constraint's dual value
    pi = m.getAttr('Pi', c)
    0

Post is closed for comments.