Pyomo模型约束报'int object is not callable'错误的排查求助
解决Pyomo约束构建中的'int object is not callable'错误
问题场景
构建Pyomo优化模型的约束时触发int object is not callable错误,相关代码如下:
import pyomo.environ as pyo from pyomo.environ import * from pyomo.opt import SolverFactory startday_index=[0,1,2,3,4,5,6] transport_index=[0,1,2] routes_index=[0,1,2,3] model = ConcreteModel() model.routes=pyo.Set(initialize=range(4)) model.transport=pyo.Set(initialize=range(3)) model.startday=pyo.Set(initialize=range(7)) model.x=pyo.Var(routes_index,transport_index,startday_index,bounds=(0,1),within=Integers) def rule1(model,i): return sum(model.x[i,j,k] for j in transport_index for k in startday_index)==1 #Constraint implemented model.C1=Constraint(routes_index, rule=rule1)
错误信息:
Constructing component 'C1_index_1' from data=None failed: TypeError: 'int' object is not callable
错误原因
- 变量索引使用外部列表而非模型内Set:Pyomo的变量和约束需要关联模型内部定义的
Set对象,而非外部Python列表,否则会导致索引解析异常。 - 约束索引使用外部列表:创建
Constraint时传入外部列表routes_index作为索引集,Pyomo无法正确解析为模型的索引组件,触发类型错误。 - 混合导入易引发命名冲突:同时使用
import pyomo.environ as pyo和from pyomo.environ import *,虽不是直接诱因,但易导致命名混淆,增加排查难度。
修复方案
1. 统一使用模型内的Set作为索引
修改变量和约束的索引为模型中定义的Set对象,同时在约束规则中遍历模型内的集合:
import pyomo.environ as pyo startday_index=[0,1,2,3,4,5,6] transport_index=[0,1,2] routes_index=[0,1,2,3] model = pyo.ConcreteModel() model.routes = pyo.Set(initialize=routes_index) model.transport = pyo.Set(initialize=transport_index) model.startday = pyo.Set(initialize=startday_index) # 变量使用模型内的Set作为索引 model.x = pyo.Var(model.routes, model.transport, model.startday, bounds=(0,1), within=pyo.Integers) def rule1(model, i): # 约束规则中遍历模型内的Set return sum(model.x[i, j, k] for j in model.transport for k in model.startday) == 1 # 约束使用模型内的Set作为索引集 model.C1 = pyo.Constraint(model.routes, rule=rule1)
2. 规范导入方式
统一使用pyo.前缀调用Pyomo组件,避免from pyomo.environ import *带来的命名冲突风险,代码更清晰可控。
验证说明
修改后,模型的变量和约束均关联模型内部的Set对象,Pyomo能正确解析索引和构建约束组件,可消除int object is not callable错误。
内容的提问来源于stack exchange,提问作者Sauhaard Batra
相关产品推荐
相关产品推荐

