Skip to main content

using "if" in addVars()

Answered

Comments

4 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

    You can use the \(\texttt{if}\)-statement in other \(\texttt{for}\)-loops as well

    import gurobipy as gp
    from gurobipy import GRB

    SetI=[i for i in range(3)]
    SetJ=[i for i in range(2)]
    m=gp.Model('example')
    x=m.addVars([(i,j) for i in SetI for j in SetJ if i!=j], vtype=GRB.BINARY, name='x')
    m.setObjective(sum(x[i,j] for i in SetI for j in SetJ if i!=j) , GRB.MINIMIZE)
    m.addConstrs((sum(x[i,j] for j in SetJ if i!=j)<=1 for i in SetI), name='constr1')
    m.optimize()

    Alternatively, you could generate an index list for your variables. However, this will not make the construction of your constraints easier due to the need of individually accessing the first or second index.

    import gurobipy as gp
    from gurobipy import GRB

    SetI=[i for i in range(3)]
    SetJ=[i for i in range(2)]
    varset = [(i,j) for i in SetI for j in SetJ if i!=j]
    m=gp.Model('example')
    x=m.addVars(varset, vtype=GRB.BINARY, name='x')
    m.setObjective(sum(x[i,j] for (i,j) in varset) , GRB.MINIMIZE)
    m.addConstrs((sum(x[i,j] for j in SetJ if i!=j)<=1 for i in SetI), name='constr1')
    m.optimize()

    Best regards, 
    Jaromił

    0
  • Marina Csanady
    • Gurobi-versary
    • First Comment
    • First Question

    Thanks for your suggestions.

    I also tried to work with var.index, but also got the same error message. Why is that?

     

    import gurobipy as gp
    from gurobipy import GRB

    SetI=[i for i in range(3)]
    SetJ=[i for i in range(2)]
    m=gp.Model('example')
    x=m.addVars([(i,j) for i in SetI for j in SetJ if i!=j], vtype=GRB.BINARY, name='x')
    m.setObjective(sum(x[i,j] for i in SetI for j in SetJ if x[i,j].index!=-1 ) , GRB.MINIMIZE)
    m.addConstrs((sum(x[i,j] for j in SetJ if x[i,j].index!=-1)<=1 for i in SetI), name='constr1')
    m.optimize()
    0
  • Jaromił Najman
    • Gurobi Staff

    Working with var.index does not save you from trying to access key \(\texttt{(0,0)}\). You are still accessing the not  available variable \(\texttt{x[0,0]}\) to check its \(\texttt{.index}\) field.

    Best regards, 
    Jaromił

    0

Post is closed for comments.