Search code examples
pythonpyomo

How to define chained calculations in Pyomo model?


I am not sure that I am modelling the constraints correctly. I have the chain-type calculations in my model, meaning that the balance_equation should use the values of previously calculated power_rule and weight_rule. Please see a simplified example below.

def power_rule(model, r, t):
    return model.v[r,t] == 25*model.x[r,t].value
model.power_flow = Constraint(model.R, model.T, rule=power_rule)

def weight_rule(model, r, t):
    return model.z[r,t] == 5*model.x[r,t].value
model.weight_flow = Constraint(model.R, model.T, rule=weight_rule)

def balance_equation(model, r, t):
    if t == 0:
        return Constraint.Skip
    return model.w[r,t] == model.w[r,t-1].value + model.v[r,t] - model.z[r,t].value
model.flow = Constraint(model.R, model.T, rule=balance_equation)

Previously, I initialized w, v and z with 0 for all t and r index values. This does not seem logical for me. I would expect to only initialize w[r,0] and then the calculation of the rest of values should be chained.

However, it looks like the chain calculation is not executed and the variables v and z are not updated, remaining the same all the time. What is wrong in my aproach? Should I use model.power_flow and model.weight_flow instead of model.v and model.z? If so, any example would be helpful. Thanks.


Solution

  • You should never use .value in a constraint expression. This causes the current value of a variable to be used in the expression instead of the variable itself, i.e. when the value of the variable changes the expression will not be updated. Even after removing .value, the constraints will only be satisfied after sending the model to a solver. This means you have to initialize each variable independently, there is no automated infrastructure for "chaining" the initialization calculations.