using "if" in addVars()
AnsweredI'm working on a problem with a lot of variables. In fact to much variables to run in reasonable time. My first approach was to create all possible varibles and delete the unnecessary ones (via model.remove()), but the runtime was still to long.
Therefore I want to eliminate the number of varibles before even creating them by using an "if" condition in addVars().
But now I have the problem of adressing the variables correctly. As error message i get
KeyError: (0,0)
Below you see a minimal example which represents my current approach:
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 ) , GRB.MINIMIZE)
m.addConstrs((sum(x[i,j] for j in SetJ )<=1 for i in SetI ), name='constr1')
m.optimize()
-
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 -
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 -
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
Please sign in to leave a comment.
Comments
3 comments