I have the constraint z_1 + z_2 = 1 in a concrete model. I want to add another variable z_n at the nth step of solving. E.g. the constraint would become z_1 + z_2 + z_3 = 1 in the first step of solving and z_1 + z_2 + z_3 + z_4 = 1 in the next step, and so on.
I really appreciate it if anyone has a suggestion
Thanks a lot!
I am using ConstraintList() method and one way that came to my mind was deleting the constraint in each step and rewriting that. But I am not sure how to do it and if it is efficient or not.
Thanks,
There are a lot of ways to do what you want. The simplest is to update the constraint in question with a new relational expression:
>>> import pyomo.environ as pyo
>>> m = pyo.ConcreteModel()
>>> m.z = pyo.Var(range(5))
>>> m.c = pyo.Constraint(expr=m.z[0] + m.z[1] == 1)
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : z[0] + z[1] : 1.0 : True
>>> m.c.set_value(m.c.body + m.z[2] == m.c.upper)
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : z[0] + z[1] + z[2] : 1.0 : True
>>> m.c.set_value(m.c.body + m.z[3] == m.c.upper)
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : z[0] + z[1] + z[2] + z[3] : 1.0 : True
Alternatively, an approach that requires less manipulation of the model is to use an Expression
(named expression) component to hold the constraint body and just update that expression:
>>> m = pyo.ConcreteModel()
>>> m.z = pyo.Var(range(5))
>>> m.e = pyo.Expression(expr=m.z[0] + m.z[1])
>>> m.c = pyo.Constraint(expr=m.e == 1)
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : e : 1.0 : True
>>> m.e.pprint()
e : Size=1, Index=None
Key : Expression
None : z[0] + z[1]
>>> m.e.expr += m.z[2]
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : e : 1.0 : True
>>> m.e.pprint()
e : Size=1, Index=None
Key : Expression
None : z[0] + z[1] + z[2]
>>> m.e.expr += m.z[3]
>>> m.c.pprint()
c : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : 1.0 : e : 1.0 : True
>>> m.e.pprint()
e : Size=1, Index=None
Key : Expression
None : z[0] + z[1] + z[2] + z[3]