pythonoptimizationconstraintspyomocyclic

Defining cyclic/periodic boundary conditions in Pyomo constraints


I am trying to define a constraint on a Pyomo model that utilizes a cyclic condition. Below is how I think it should work (cyclic syntax from GAMS).

from __future__ import division
from pyomo.environ import *

model = ConcreteModel()

## define sets
model.t                 = Set(initialize = [i for i in range(8760)]) 

## define variables
model.ESS_SOC           = Var(model.t, domain = NonNegativeReals) # battery state of charge
model.ESS_c             = Var(model.t, domain = NonNegativeReals) # battery charging
model.ESS_d             = Var(model.t, domain = NonNegativeReals) # battery discharging

## skip obj for this example

## define constraints
#SOC constraint
model.SOC_const = ConstraintList()
for i in model.t: 
    model.SOC_const.add( model.ESS_SOC[i] == model.ESS_SOC[i--1] + model.ESS_c[i] - model.ESS_d[i] )

But when I run the above example, I get the following error message:

KeyError: "Index '8760' is not valid for indexed component 'ESS_SOC'"

I agree with the error given the definition of model.t, but the error has me believing that it is almost doing what I want it to do, which would be to have:

model.ESS_SOC[0] == model.ESS_SOC[8759] + model.ESS_c[0] - model.ESS_d[0]
model.ESS_SOC[1] == model.ESS_SOC[0] + model.ESS_c[1] - model.ESS_d[1]
...
model.ESS_SOC[8759] == model.ESS_SOC[8758] + model.ESS_c[8759] - model.ESS_d[8759] 

Is there a way to define the constraint so that is what I get?


Solution

  • I would recommend doing this using an indexed constraint instead of a ConstraintList:

    from __future__ import division
    from pyomo.environ import *
    
    model = ConcreteModel()
    
    ## define sets
    model.t                 = Set(initialize = [i for i in range(8760)], ordered=True) 
    
    ## define variables
    model.ESS_SOC           = Var(model.t, domain = NonNegativeReals) # battery state of charge
    model.ESS_c             = Var(model.t, domain = NonNegativeReals) # battery charging
    model.ESS_d             = Var(model.t, domain = NonNegativeReals) # battery discharging
    
    ## skip obj for this example
    
    ## define constraints
    #SOC constraint
    def _SOC_const(m, i):
        if i == m.t.first():
            return model.ESS_SOC[i] == model.ESS_SOC[m.t.last()] + model.ESS_c[i] - model.ESS_d[i]
        return model.ESS_SOC[i] == model.ESS_SOC[i-1] + model.ESS_c[i] - model.ESS_d[i]
    model.SOC_const = Constraint(model.t, rule=_SOC_const)
    

    Notice that you need to set the ordered=True option on the Set for the first() and last() methods to work.