Reputation: 23
I am using pyomo package for implementing an optimization problem. I was trying one of the example problems provided in pyomo online documentation. But, I am getting error when I was trying to solve it.
The python code used:
from __future__ import division
from pyomo.environ import *
model = AbstractModel()
model.Nodes = Set()
model.Arcs = Set(dimen=2)
model.Flow = Var(model.Arcs, domain=NonNegativeReals)
model.FlowCost = Param(model.Arcs)
model.Demand = Param(model.Nodes)
model.Supply = Param(model.Nodes)
def Obj_rule(model):
return summation(model.FlowCost, model.Flow)
model.Obj = Objective(rule=Obj_rule, sense=minimize)
def FlowBalance_rule(model, node):
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.Nodes if (i,node) in model.Arcs) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.Nodes if (j,node) in model.Arcs) \
== 0
model.FlowBalance = Constraint(model.Nodes, rule=FlowBalance_rule)
And, the data file is:
set Nodes := CityA CityB CityC ;
set Arcs :=
CityA CityB
CityA CityC
CityC CityB
;
param : FlowCost :=
CityA CityB 1.4
CityA CityC 2.7
CityC CityB 1.6
;
param Demand :=
CityA 0
CityB 1
CityC 1
;
param Supply :=
CityA 2
CityB 0
CityC 0
;
When I try to solve this, I am getting the following error.
[ 0.00] Setting up Pyomo environment
[ 0.00] Applying Pyomo preprocessing actions
[ 0.01] Creating model
ERROR: Rule failed when generating expression for constraint FlowBalance with index CityB:
KeyError: "Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'"
ERROR: Constructing component 'FlowBalance' from data=None failed:
KeyError: "Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'"
ERROR: Unexpected exception while running model test.py:
Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'
Upvotes: 1
Views: 1157
Reputation: 81
You have the following typo in FlowBalance_rule
sum(model.Flow[node, j] for j in model.Nodes if (j,node) in model.Arcs)
where the indexing model.Flow[node,j]
and the conditional if (j,node) in model.Arcs
are causing the error.
I'm assuming that you want to flip the order of the conditional tuple, the following works
def FlowBalance_rule(model, node):
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.Nodes if (i,node) in model.Arcs) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.Nodes if (node,j) in model.Arcs) \
== 0
Upvotes: 1