Skip to main content

Create variables in a loop

Answered

Comments

4 comments

  • David Torres Sanchez
    • Gurobi Staff

    Hi,

    You can do this using list comprehension and model.addVars:

    y = model.addVars(
        [
            (i, j, ni, nj)
          for i in range(I)
          for j in range(I)
          for ni in range(int(H / T[i]))
          for nj in range(int(H / T[j]))
        ],
        vtype=GRB.BINARY,
        name="y",
    )

    Cheers, 
    David

    2
  • Ana Guasque Ortega
    • Gurobi-versary
    • Investigator
    • Conversationalist

    Many thanks, David! I didn't know this possibility.

    An another question related to indicator constraints (if I should write the question at any other thread, please tell me)

    I read that it is not possible to compare optimization variables. What I want is:

    if x != y then z=0 (x,y and z are binary variables) and if x==y then z can be 0 or 1. I read in this link that I need an auxiliary binary variable and then use indicator constraints. The point is that following the example, I think it doesn't work for me:

    if x!=y -> b=1

    if x==y -> b=0

    Equations:

    x!=y+eps-M(1-b)  (equation 1)

    x==y+Mb  (equation 2)

    When x=0 and y=1, equation 2 is not accomplished:

    0==1+10*b -> b cannot b 1.

    I think that the point is != and ==, because in the example they work with > and <. Could you please help me or send me another post, where this problem is solved? I have not found it. 

    Thanks again.!

    0
  • David Torres Sanchez
    • Gurobi Staff

    Hi Ana,

    Thanks for the new question, I can try and answer it here.

    • Since \(\texttt{x}\) and \(\texttt{y}\) are binary, you can model the \(\texttt{!=}\) relationship as \(\texttt{x = 1 - y}\).
    • You can add an extra variable to check for this relationship

    I think this will model what you want:

    m = gp.Model()

    # Add variables
    x = m.addVar(vtype=gp.GRB.BINARY, name="x")
    y = m.addVar(vtype=gp.GRB.BINARY, name="y")
    z = m.addVar(vtype=gp.GRB.BINARY, name="z")
    aux = m.addVar(vtype=gp.GRB.BINARY, name="aux")

    # If aux = 1 then x != y, otherwise they are equal.
    m.addConstr((aux == 1) >> (x == 1 - y))
    m.addConstr((aux == 0) >> (x == y))

    # If aux = 1, then z = 0, otherwise, z can be either 0 or 1.
    m.addConstr((aux == 1) >> (z == 0))
    m.addConstr((aux == 0) >> (z <= 1))

    Cheers, 
    David

    2
  • Ana Guasque Ortega
    • Gurobi-versary
    • Investigator
    • Conversationalist

    Thanks again for your great response :)

    0

Please sign in to leave a comment.