Create variables in a loop
AnsweredGood morning,
I want to create a variable whose size depends on different parameters. I tried something like (I is a list like [0,1,2,3], H is an integer and T is a list like [5,10,15, 50]:
for i in I:
for j in I:
for ni in range(int(H/T[i])):
for nj in range(int(H/T[j])):
y[i,j,ni,nj] = m.addVar(vtype=GRB.BINARY, name="y%s" %str([i,j,ni,nj]))
I get the error: NameError: name 'y' is not defined. How could I solve the problem? I followed this post.
Thanks in adavance.
-
Official comment
This post is more than two 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. -
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,
David2 -
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 -
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,
David2 -
Thanks again for your great response :)
0
Post is closed for comments.
Comments
5 comments