makansij
makansij

Reputation: 9885

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

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.

Upvotes: 0

Views: 1798

Answers (1)

Tom Krumpolc
Tom Krumpolc

Reputation: 56

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) `

Upvotes: 2

Related Questions