我是Pyomo的新手,并且想知道如何更改具有一个或多个索引的现有模型参数的值。
我看过一些标量参数的示例,即没有索引。例如:
model5 = ConcreteModel()
model5.data2 = Param(initialize=10.0, mutable=True)
print("print data2 before")
model5.data2.pprint()
model5.data2 = 999
print("print data2 after")
model5.data2.pprint()
这将产生输出:
print data2 before
data2 : Size=1, Index=None, Domain=Any, Default=None, Mutable=True
Key : Value
None : 10.0
print data2 after
data2 : Size=1, Index=None, Domain=Any, Default=None, Mutable=True
Key : Value
None : 999
但是,如果我尝试使用具有索引的参数来执行此操作,则会收到错误消息。以下代码失败,但可能不足为奇,因为我试图将Python对象分配给Pyomo对象。用索引(或多个索引)更新参数的正确方法是什么?
model5 = ConcreteModel()
# Make a small set
myList = ['i1', 'i2', 'i3', 'i4']
model5.i = Set(dimen=1, initialize=myList)
# Make a dict for each element in the set and give it the value 10
dataDict = {}
for element in myList:
dataDict[element] = 10
print("print dataDict")
print(dataDict)
# Make the data into a model Param
model5.data = Param(model5.i, initialize=dataDict, mutable=True)
print("print data parameter")
model5.data.pprint()
# Change a values for each element to 999
for element in myList:
dataDict[element] = 999
# Try and update the Param
model5.data = dataDict # THIS FAILS <-- how do I do this?
答案 0 :(得分:1)
tl,dr :使用要更新(可变!)参数的reconstruct
方法。
首先,我的建议是将将模型初始化的过程放入函数中,以便您可以在不同位置调用它并重用它。
from pyomo import environ as pe
def create_model(d):
"""Create Pyomo Concrete Model.
Parameters
----------
d : dict
Dictionary with keys corresponding to components names.
"""
model = pe.ConcreteModel()
model.I = pe.Set(initialize=d['I'])
model.data = pe.Param(model.I, mutable=True, initialize=d['data'])
return model
然后,您可以使用所需的任何数据初始化模型:
d = {}
d['I'] = ['i1', 'i2', 'i3', 'i4']
d['data'] = {i : 10 for i in d['I']}
model = create_model(d)
model.data.pprint()
data : Size=4, Index=I, Domain=Any, Default=None, Mutable=True
Key : Value
i1 : 10
i2 : 10
i3 : 10
i4 : 10
现在使用reconstruct
更新值:
new_values = {i: 5 for i in d['I']} # 5 here is arbitrary, you
model.data.reconstruct(new_values)
model.data.pprint()
data : Size=4, Index=I, Domain=Any, Default=None, Mutable=True
Key : Value
i1 : 5
i2 : 5
i3 : 5
i4 : 5
请注意,data
是一个确实令人困惑的参数名称,您应该找到更具体的名称。