python - ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a

admin2025-04-28  2

My code is as follows:

import pyomo.environ as pyo

model = pyo.ConcreteModel()
model.x = pyo.Var(range(2), domain=pyo.Reals)
model.Constraint2 = pyo.Constraint(expr=sum([x for x in model.x]) >= 0)

I am getting the error:

ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object

But the error disappear if I try:

model.Constraint2 = pyo.Constraint(expr=model.x[0] + model.x[1] >= 0)

Looks like it is impossible to iterate a variable like a list in pyomo. Is it correct? I am not able to find it in documentation.

My code is as follows:

import pyomo.environ as pyo

model = pyo.ConcreteModel()
model.x = pyo.Var(range(2), domain=pyo.Reals)
model.Constraint2 = pyo.Constraint(expr=sum([x for x in model.x]) >= 0)

I am getting the error:

ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object

But the error disappear if I try:

model.Constraint2 = pyo.Constraint(expr=model.x[0] + model.x[1] >= 0)

Looks like it is impossible to iterate a variable like a list in pyomo. Is it correct? I am not able to find it in documentation.

Share Improve this question asked Jan 9 at 18:51 AndreyAndrey 6,4073 gold badges23 silver badges47 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

There are 2 ways how to solve it:

1st. Create explicitly a set for the model and iterate over the variable:

import pyomo.environ as pyo

model = pyo.ConcreteModel()
model.i = pyo.RangeSet(2)
model.x = pyo.Var(model.i, domain=pyo.Reals)
model.Constraint2 = pyo.Constraint(expr=sum(model.x[i] for i in model.i) >= 0)

2nd. Extract values of the variable and iterate over them:

import pyomo.environ as pyo

model = pyo.ConcreteModel()
model.x = pyo.Var(range(2), domain=pyo.Reals)
model.Constraint2 = pyo.Constraint(expr=sum(x for x in model.x.extract_values().values()) >= 0)

Both are valid, I would personally go for the 1st option.

I hope it helps!

转载请注明原文地址:http://www.anycun.com/QandA/1745779396a91179.html