Search code examples
dictionaryparameterspyomo

Define parameter in pyomo from dictionary key


I am fairly new to Python/Pyomo, and I am trying to define a parameter cost(n) from the key ('score') in this dictionary that I have created:

operations[1] = {"score" : 100, "start_node": 2, "end_node": 3}
operations[2] = {"score" : 120, "start_node": 4, "end_node": 3}
...
operations[n] = {"score" : 155, "start_node": 5, "end_node": 2}

I have tried to do that with this approach, but it doesn't seem to work:

n_operations=len(operations) 
model = ConcreteModel()
model.O = RangeSet(1,n_operations)

def c_init(model, operations):

   for i in range(1,n_operations):
       print(i)
       cost=operations[i]['score']
       return cost

model.cost = Param(model.O, initialize=c_init)

Do you have an idea of how to tackle this issue?

Thanks!


Solution

  • Like all rules in Pyomo, when you pass a function to Param's initialize= keyword, that function is called once for each index. So you should modify your rule to be:

    def c_init(model, operation):
        return operations[operation]['score']