Pyomo中at()方法的正确使用及弃用警告问题排查
Pyomo中at()方法的正确使用方式
问题背景
我在使用Pyomo时编写了如下代码:
outputVariables_list = [model.param1, model.variable1] optimal_values_list = [[pyo.value(model_item[key]) for key in model_item] for model_item in outputVariables_list]
运行时收到弃用警告:
WARNING: DEPRECATED: Using getitem to return a set value from its
(ordered) position is deprecated. Please use at() (deprecated in 6.1,
will be removed in 7.0)
我尝试替换为以下代码却报错:
optimal_values_list = [[pyo.at(model_item[key]) for key in model_item] for model_item in outputVariables_list]
此外,尝试pyo.value(model_item.at[key])和pyo.value(model_item.at(key)均触发AttributeError: 'IndexedParam' object has no attribute 'at'。
请问如何正确使用Pyomo推荐的at()方法?为何按提示使用却报错,该如何将at()集成到代码中?
更新:我使用的Pyomo组件完整列表如下(名称表明其为参数、变量或集合):
outputVariables_list_BT2 = [model.param_helpTimeSlots_BT2, model.variable_heatGenerationCoefficient_SpaceHeating_BT2, model.variable_heatGenerationCoefficient_DHW_BT2, model.variable_help_OnlyOneStorage_BT2, model.variable_temperatureBufferStorage_BT2, model.variable_usableVolumeDHWTank_BT2, model.variable_electricalPowerTotal_BT2, model.variable_pvGeneration_BT2, model.variable_windPowerAssigned_BT2, model.param_heatDemand_In_W_BT2, model.param_DHWDemand_In_W_BT2, model.param_electricalDemand_In_W_BT2, model.param_pvGenerationNominal_BT2, model.param_outSideTemperature_In_C, model.param_windAssignedNominal_BT2, model.param_COPHeatPump_SpaceHeating_BT2, model.param_COPHeatPump_DHW_BT2, model.param_electricityPrice_In_Cents, model.set_timeslots]
解决方法
核心逻辑:区分集合与其他组件
弃用警告仅针对**集合(Set)**的按位置索引操作,参数、变量等组件无需使用at()方法,仍用pyo.value()获取值。你需要先判断每个组件类型,再分别处理:
optimal_values_list = [] for model_item in outputVariables_list_BT2: if isinstance(model_item, pyo.Set): # 集合用at()按位置访问元素 values = [model_item.at(i) for i in range(len(model_item))] else: # 参数、变量保留原有逻辑,按索引遍历取值 values = [pyo.value(model_item[key]) for key in model_item] optimal_values_list.append(values)
报错原因解析
- 方法用错对象:
at()是Pyomo集合独有的方法,IndexedParam、Var这类组件没有该属性,直接调用必然触发AttributeError。 - 误解警告含义:原警告是指不要用
集合[位置索引]的方式获取元素(比如model.set_timeslots[0]),需改为model.set_timeslots.at(0),而非给参数/变量强制套at()方法。
额外说明
- 若集合是
OrderedSet类型,at()会严格按定义顺序返回元素;普通Set则按内部存储顺序返回,顺序不保证稳定。 - 参数、变量的索引遍历逻辑(
for key in model_item)完全合规,无需修改。
内容的提问来源于stack exchange,提问作者PeterBe
相关产品推荐
相关产品推荐

