我正在寻找一个pyomo函数,如果pyomo模型中存在一个元素,它将返回True。
例如,如果我创建一个简单的pyomo模型,我希望它的响应如下所示。或者,也许有一种方法可以输出Pyomo模型中所有元素的列表,然后我可以检查某个元素?
import pyomo.environ as pe
model = pe.AbstractModel()
model.t = pe.Set()
model.A = pe.Param(model.t)
# Do functions such as has_element() or list_elements() exist?
model.has_element('A') # Returns True
model.has_element('B') # Returns False
elements = model.list_elements()
print('A' in elements) # Prints True
print('B' in elements) # Prints False
到目前为止,我想到的最好的方法是使用find_component()函数,如果组件存在,则返回组件;如果组件不存在,则返回None
import pyomo.environ as pe
model = pe.AbstractModel()
model.t = pe.Set()
model.A = pe.Param(model.t)
model.find_component('A') # Returns model.A
model.find_component('B') # Returns None
这是最好的方法吗?
发布于 2019-05-09 03:32:28
因为字符串和非空对象在python中通常是真的,而没有一个是假的:
if model.find_component('A'):
# do something with model A
print('here')
if model.find_component('B'):
# do something with model B
print('there')
请注意,如果您运行上面的场景,您将得到预期的结果,因为"here“将被打印出来,而”here“则不会。
https://stackoverflow.com/questions/56047644
复制相似问题