I know how to create expressions using rules in Pyomo. However, when I try to use Constraint.Skip it doesn’t seem to be recognized as an attribute. 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
. 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 *
.
First way:
change your skip statement to expr = pe.Constraint.Skip
. The point being that you have imported the pyomo environment as pe
.
Second way: Only import the classes from pyomo that you need/plan to use. 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) `