# Can we take the constraints from one model and plug them into the other model in pyomo?

I am implementing data-driven robust optimization methodology introduced in this article in python. Somewhere of the method, I need to use pyomo for each constraint whose parameters are uncertain to form the robust counterpart. For simplicity, suppose we have only one constraint with uncertain parameters. The method stated in the article explains how to incorporate the uncertain set to find the constraint's robust counterpart. I wanted to form the robust counterpart constraints related to this constraint separately from the other constraints (that are not uncertain) due to some technical hardnesses.

Now, I have two groups of constraints, one derived from robust counterpart for uncertain constraints, and the other group is the constraints that are not uncertain, coming from the original model.

My question is that can I merge these two groups of constraints together to form the robust counterpart model as a whole?

Generally speaking, if we have two models written in pyomo, can we merge their constraints together to form a new problem? I mean can we take the constraints from one model and plug them into the other model?

And what is the syntax?

Yes, this can be done in pyomo. Pyomo implements ConcreteModel() as a Block() object, so you could just place one over the other. Thus, merging two models is quite straightforward. You'll have to define the objective separately. Here's how to do it:

from pyomo.environ import *

model1 = ConcreteModel()
model1.constraint1 = ...
model1.constraint2 = ... # model1's constraint expr
model1.obj = ... # model1 objective

...

model2 = ConcreteModel()
model2.constraint1 = ...
model2.constraint2 = ... # model2's constraint expr
model2.obj = ... # model2 objective

...

merged_model = ConcreteModel()
merged_model.model1 = model1. # This step will copy all components of model1 in merged_model
merged_model.model2 = model2  # This step will copy all components of model2 in merged_model
merged_model.model1.obj.deactivate()
merged_model.model2.obj.deactivate()
merged_model.obj = ... # merged_model_objective_expr


Pretty clean right!? You could verify if all constraints were copied successfully by viewing the constraints in merged_model using:

for i in merged_model.component_objects(Constraint):
print(i)