Running into a Cannot initialize multiple indices of a constraint with a single expression
error when trying to create the below constraint in Pyomo, I have read other tangential answers but unsure of how to translate the learnings here. I believe the issue is that some of the variables are indexed by two sets rather than just one. However, I am summing over those indexes in Pyomo and therefore thought that my constraint could be indexed by a singular variable.
def armington_composite_demand_constraint(self, k):
return self.MODEL.armington_composite_demand[k] == (
sum(
self.MODEL.armington_composite_intermediate_demand[(k, a)]
for a in self.__activities()
)
+ sum(
self.MODEL.armington_composite_household_demand[(k, h)]
for h in self.__household_types()
)
+ sum(
self.MODEL.armington_composite_government_demand[(k, g)]
for g in self.__government_types()
)
+ sum(
self.MODEL.armington_composite_investment_demand[(k, i)]
for i in self.__investment_types()
)
)
Trying to use this function to create constraint:
# armington_composite_price_constraint
setattr(
self.MODEL,
"armington_composite_price_constraint",
po.Constraint(
self.__commodities(), rule=self.armington_composite_price_constraint
),
)
Unsure of how to fix this, I'm not sure if I am understanding the error correctly. Could someone please provide an explanation of this error and why Pyomo might struggle within summing over another index in the constraint function?
My guess is to maybe split out the sum functions... Would appreciate some help
I think the error is being raised because of how you've defined your rule. You have armington_composite_demand_constraint
as a method on a class and so when you pass self.armington_composite_demand
to the rule
argument the class instance automatically gets passed in as the first argument to the method. Behind the scenes when Pyomo calls that rule to construct the constraint it is passing in the model as the first argument followed by individual values from any indexing sets. So your rule has one too few arguments. I think the fix is just to add the model as the middle argument in your rule method:
def armington_composite_demand_constraint(self, model, k):