pythonoptimizationgurobipyomo

Multidimensional Variable with Different index length in Pyomo or Gurobi


I want to solve an optimization problem in Python. I am trying to define a variable x_{g,h} where the index g belongs to the set G and the index h belongs to the set H(g), i.e., the set of indices h varies for different indices g. Is there any way to define variable x with these indices in Pyomo or Gurobi-Python?

In Pyomo, I tried to define it in a loop, like

for g in p.keys():
    for h in range(0,p.rop[g].npairs,1):
        model.x_gen_h = Var(g,h,within=NonNegativeReals)

I got this error:

TypeError: 'int' object is not iterable.

I appreciate any help or comment!


Solution

  • The trick is in defining the indexing set used to index the variable. Pyomo does not support looping over individual indices and adding them to a Var one at a time. You should use some clever Python code to build up the whole indexing set. For example, you can use something like this to filter out the indices you want:

    m = ConcreteModel()
    
    m.g = Set(initialize=[1,2,3])
    
    h = {1:['a','b'], 2:['b','c'], 3:['c','d']}
    m.h_all = Set(initialize=set(sum(h.values(),[]))) # Extract unique h values
    
    # Initialize set to be entire cross product of g and h and then filter desired values
    m.hg = Set(initialize=m.g*m.h_all, filter=lambda m,g,hi:hi in h[g])
    m.x = Var(m.hg, within=NonNegativeReals)
    

    An even better alternative would be:

    h = {1:['a','b'], 2:['b','c'], 3:['c','d']}
    m.hg = Set(initialize=list((i,j) for i in h.keys() for j in h[i])