简体   繁体   English

为什么 Pyomo 无法识别“Constraint.Skip”?

[英]How why is `Constraint.Skip` not recognized in Pyomo?

I know how to create expressions using rules in Pyomo.我知道如何使用 Pyomo 中的规则创建表达式。 However, when I try to use Constraint.Skip it doesn't seem to be recognized as an attribute.但是,当我尝试使用 Constraint.Skip 时,它似乎没有被识别为属性。 Here's my minimal example:这是我的最小示例:

import pyomo.environ as pe 

m = pe.ConcreteModel() 
m.x = pe.Var() 
from constraint import * 

def expression_rule(m, i): 
    if i: 
        # generate the constraint 
        expr = 0 <= m.x   
    else: 
        # skip this index 
        expr = Constraint.Skip 
    return expr 

n=2 
m.constraints_skip_rule = pe.Constraint(range(n), rule = expression_rule) 

When I dig into the source code, I see clearly that Constraint.Skip is used many places, and the __all__ at the top of the constraint.py file includes Constraint .当我深入研究源代码时,我清楚地看到Constraint.Skip被使用的地方很多,并且constraint.py文件顶部的__all__包含Constraint Why is it not recognized in the code above?为什么在上面的代码中无法识别? Perhaps I'm missing some basic knowledge about how libraries work.也许我缺少一些关于图书馆如何工作的基本知识。

Two ways.两种方式。 In both cases, I would remove from constraint import * .在这两种情况下,我都会from constraint import *中删除。

First way: change your skip statement to expr = pe.Constraint.Skip .第一种方法:将您的跳过语句更改为expr = pe.Constraint.Skip The point being that you have imported the pyomo environment as pe .关键是您已将 pyomo 环境导入为pe

Second way: Only import the classes from pyomo that you need/plan to use.第二种方式:仅从 pyomo 导入您需要/计划使用的类。 Avoid importing * to make it less ambiguous what calls you are making.避免导入 * 以减少您正在拨打的电话的歧义。

from pyomo.environ import (ConcreteModel, Var, Constraint)  

m = ConcreteModel() 
m.x = Var() 

def expression_rule(m, i): 
    if i: 
        # generate the constraint 
        expr = 0 <= m.x   
    else: 
        # skip this index 
        expr = Constraint.Skip 
    return expr 

n=2 
m.constraints_skip_rule = Constraint(range(n), rule = expression_rule) `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM