Search code examples
pythonpython-3.xpyomogams-math

How do set up something similar to GAMS' circular indexing for Pyomo


I'm working on a pyomo constraint that has a rule in the first loop to do some calculation based on the last loop. So for T = 24, each loop is:

def const1(model,t):
    return model.x[t] == model.x[t - 1] + ef_H * model.d[t] - model.g[t]
model.x_const = Constraint(T, rule=const1)

In the first loop however, I want it to use the value from the last loop and do the calculation, like so:

def const1(model,t):
    if t == 0:
          return model.x[t] == model.x[24] + ef_H * model.d[t] - model.g[t]
    return model.x[t] == model.x[t - 1] + ef_H * model.d[t] - model.g[t]
model.x_const = Constraint(T, rule=const1)

I know in GAMS, there's the -- command, that you can set something like:

model.x[t] == model.x[t -- 1] + ef_H * model.d[t] - model.g[t]

and it will use the last value (t = 24) to calculate your initial model.x[t]. Is there a simple way in pyomo that can achieve this?

Thanks very much in advance for your help!


Solution

  • I assume T is a list of elements for a set known as 'T' in the model. You will need to define this set as ordered to make this work. Then you can use the pyomo Set.prevw method, which gives you the previous member of a set, wrapping if needed. I would also recommend defining that set as part of the model, rather than a free-floating object.

    So you can write fairly simple code like this:

    model.T = Set(initialize=T, ordered=True)
    
    def const1(model, t):
        return model.x[t] == model.x[model.T.prevw(t)] + ef_H * model.d[t] - model.g[t]
    model.x_const = Constraint(model.T, rule=const1)