Search code examples
pyomo

How to retrieve value of constraint from Pyomo


Say I have a constraint that is defined in the following way in my abstractmodel:

def flow_constraint(model, t, b):
flows = sum(
            sum( (model.Factor[area_from, t, b] - model.Factor[area_to, t, b]) 
                * model.flow[area_from, area_to, t] for (area_to) in get_border(area_from))
                    for area_from in model.Areas)
return flows <= model.RAM[t, b] 

model.flow_constraint = Constraint(model.BranchesIndex, rule = flow_constraint)

Is there a way to retrieve the value of this constraint directly from the model?


Solution

  • Constraint values only make sense in the context of a concrete instance. For abstract models, the constraints have been declared but not defined. That is, the containers (like Constraint) have been declared to exist, but they are empty. Once you have a concrete instance (either after calling create_instance() on the Abstract model or by directly creating a ConcreteModel), there are a couple options.

    Your constraint is really a set of constraints (indexed by model.BranchesIndex). You can display the values of all the constraints in the indexed constraint with:

    # (assuming m is a concrete instance from create_instance(), or a ConcreteModel)
    m.flow_constraint.display()
    

    You can get the numerical values of a single constraint through the lower, body, and upper attributes. For example:

    print("%s <= %s <= %s" % ( 
        value(m.flow_constraint[t,b].lower),
        value(m.flow_constraint[t,b].body),
        value(m.flow_constraint[t,b].upper) ))