How to use multi-level indexing in pyomo with a set and a rangeset?
<p>I have multiple levels of indices in my model in <code>pyomo</code>, and I need to be able to index variables like this:</p>

<pre><code>model.b['a',1]
</code></pre>

<p>But this doesn't seem possible for some reason.  I can use multilevel indexing like this:</p>

<pre><code>model = ConcreteModel()
model.W = RangeSet(0,1)
model.I = RangeSet(0,4)
model.J = RangeSet(0,4)
model.K = RangeSet(0,3)

model.B = Var(model.W, model.I, model.J, model.K)
model.B[1,2,3,0]  # access the variable using the indices - THIS WORKS!!
</code></pre>

<p>But this does not work, however:</p>

<pre><code>model = ConcreteModel()
model.W = Set(['a','b'])
model.I = RangeSet(0,4)

model.b = Var(model.W, model.I)  # I can't even create this - throws exception
</code></pre>

<p>...it throws the exception:</p>

<pre><code>TypeError: Cannot index a component with an indexed set
</code></pre>

<p>Why does the first one work and not the second one?</p>

<p>The problem is that when you write</p>

<pre><code>model.W = Set(['a','b'])
</code></pre>

<p>you are actually creating an indexed Set object rather than a Set with the values in the provided list. This is because all Pyomo component constructors treat positional arguments as indexing sets.</p>

<p>You can fix this by adding the "initialize" keyword before your list of values</p>

<pre><code>model.W = Set(initialize=['a','b'])
</code></pre>

<p>The same would be true if you provided a list of integers rather than strings</p>

<pre><code>model.I = Set(initialize=[0,1,2,3,4])
</code></pre>

python python-2.7 pyomo