Search code examples
pythonpyomo

Index is not valid for indexed component. Parameter with double indexing in pyomo


I am trying to create a parameter Wind_DA with double index in the following way:

import pandas as pd
import pyomo.environ as pe
import pyomo.opt as po

#DATA
T=3;
W=1;

time = ['t{0}'.format(t+1) for t in range(T)]
wind=['W{0}'.format(w+1) for w in range(W)]

Wind_DA={}
Wind_DA['w1', 't1']=200
Wind_DA['w1', 't2']=200
Wind_DA['w1', 't3']=200

#MODEL
seq=pe.ConcreteModel()

### SETS
seq.W = pe.Set(initialize = wind)
seq.T =pe.Set(initialize = time)

### PARAMETERS

seq.Wind_DA = pe.Param(seq.W, seq.T, initialize = Wind_DA)

I am getting the following error:

KeyError: "Index '('w1', 't1')' is not valid for indexed component 'Wind_DA'".

However, when I type on the console Wind_DA[('w1', 't1')] I am getting 200, which means that this dictionary has that index. What could be the problem? Thank you in advance!


Solution

  • It just a typing error.

    When creating the wind array with wind=['W{0}'.format(w+1) for w in range(W)] you're using a capital W, but when creating the param Wind_DA = {}... you're using a lower W

    Just change wind=['W{0}'.format(w+1) for w in range(W)] for a lowercase w and that should work properly. wind=['w{0}'.format(w+1) for w in range(W)]

    import pandas as pd
    import pyomo.environ as pe
    import pyomo.opt as po
    
    #DATA
    T=3
    W=1
    
    time = ['t{0}'.format(t+1) for t in range(T)]
    wind=['w{0}'.format(w+1) for w in range(W)]
    
    Wind_DA={}
    Wind_DA['w1', 't1']=200
    Wind_DA['w1', 't2']=200
    Wind_DA['w1', 't3']=200
    
    #MODEL
    seq=pe.ConcreteModel()
    
    ### SETS
    seq.W = pe.Set(initialize = wind)
    seq.T =pe.Set(initialize = time)
    
    ### PARAMETERS
    seq.Wind_DA = pe.Param(seq.W, seq.T, initialize = Wind_DA)