【问题标题】:How to check if something exists in a Pyomo model如何检查 Pyomo 模型中是否存在某些东西
【发布时间】:2019-05-08 19:18:29
【问题描述】:

我正在寻找一个 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

这是最好的方法吗?

【问题讨论】:

  • 为什么这不是最好的方法?至于列表元素,如果您查看文档,它会调用 list_components()
  • 您能指出您指的是哪些文档吗?我找不到 list_components(),但函数 component_objects() 将为 AbstractModel 中的所有组件返回一个迭代器

标签: python optimization pyomo


【解决方案1】:

因为字符串和非空对象在 python 中通常是真的,而 None 是假的:

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”会被打印,但“there”不会。

【讨论】:

    猜你喜欢
    • 2014-05-12
    • 2012-06-04
    • 2012-03-12
    • 1970-01-01
    • 2017-02-12
    • 2012-04-29
    • 2012-05-11
    相关资源
    最近更新 更多