Write a constraint in Pyomo with max and min

106 views Asked by At

I have to write the Pavg and H_ad constraints in pyomo from the following picture with 4 constraints, enter image description here

# 1. Average Pressure

def Avg_pressure(model, I, J, T, S, r):
    return model.Pavg[I, J, T, S] == max(model.A1p[r] * model.Pin[I, J, T, S] + model.A2p[r] * model.Pout[I, J, T, S] + model.Bp[r] for r in model.R1_2)
model.constraint52 = Constraint(model.Pipe, model.T, model.S, model.R1_2, rule=Avg_pressure)

model.pprint()

The above constraint is giving an exception error as,

PyomoException: Cannot convert non-constant Pyomo expression (0.54886306Pin[2,3,1,1] + 0.44727615Pout[2,3,1,1] + 3.02961114e-05 < 0.62043087Pin[2,3,1,1] + 0.31263309Pout[2,3,1,1] + 0.00039507888) to bool. This error is usually caused by using a Var, unit, or mutable Param in a Boolean context such as an "if" statement, or when checking container membership or equality. For example, m.x = Var() if m.x >= 1: pass and m.y = Var() if m.y in [m.x, m.y]: pass would both cause this exception.

As I am not able to write the max and min part properly, currently I am mentioning the constraints like the following,

# 1. Average Pressure

def Avg_pressure(model, I, J, T, S, r):
    return model.Pavg[I, J, T, S] >= model.A1p[r] * model.Pin[I, J, T, S] + model.A2p[r] * model.Pout[I, J, T, S] + model.Bp[r]
model.constraint51 = Constraint(model.Pipe, model.T, model.S, model.R1_2, rule=Avg_pressure)
# 5. H_ad_and_Pressure out

def H_ad_and_Pressure(model, I, J, T, S, r):
    return model.h_ad[I, J, T, S] <= model.Ah[I, J, r] * model.Pout[I, J, T, S] + model.Bh[I, J, r]
model.constraint55 = Constraint(model.C, model.T, model.S, model.R1_2, rule=H_ad_and_Pressure)

The sets, parameters and variables are all well defined. Just struggling with the max and min. It is fine even if you consider a different constraint with different variables with same kind of max and min.

1

There are 1 answers

0
AirSquid On

There isn't enough context to give too much of an answer, but I would expect it to be something like the below.

p_avg doesn't appear to be used anywhere, so I'm just stuffing it into the objective to minimize it. There are other subscripts that aren't defined, etc, but this is the basic idea. You could then go forward and use p_avg in other expressions if needed, and if the "sense" of those expressions is to minimize them, you could remove it from the objective.

# capture average
def cap_avg(model, i, j, k, r):
    return model.p_avg[i, j, k] >= model.p_in[i, j, k] * model.A[r]
model.c1 = Constraint(model.I, model.J, model.K, model.R, rule=cap_avg)

# use objective to minimize average
model.obj = Objective(expr=sum(model.p_avg[i, j, k] for i in model.I, for j in model.J, for k in model.K))