Search code examples
mathematical-optimizationpyomooperations-research

Pyomo: How do I add all set of a model's constraints to another model?


I want to add all constraints and variables from a model to a different model in Pyomo, but I cannot figure out how. The use case is when I want to transform my model to its dual, and I need to add all dual constraints and variables to the primal problem. This is actually useful when we want to add optimality conditions of a certain model to another problem.

Maybe there are other functional transformations in Pyomo that do the same, and I am not aware of them, so in a case such functionality exists, I would be more than happy if anybody could assist.

Thanks,


Solution

  • I added the constraints of a model "model2" to another model "model1" with first deleting the item from the initial model and then adding it to the other.

    Here is a sample code to show that:

    from pyomo.environ import *
    
    model1 = ConcreteModel()
    model2 = ConcreteModel()
    
    model1.a = Var([1,2,3,4,5,6], within=NonNegativeReals)
    model2.b = Var([1,2,3,4,5,6], within=NonNegativeReals)
    
    model1.c = Constraint(expr= model1.a[1] + model1.a[3] == 3)
    model2.d = Constraint(expr= model2.b[1] + model2.b[3] == 3)
    
      
    for con in model2.component_objects(Constraint):
        model2.del_component(con)
        model1.add_component('d', con)
    
    for var in model2.component_objects(Var):
        model2.del_component(var)
        model1.add_component('b', var)
    
    model1.objective = Objective(expr = model1.a[1] + model1.b[3], sense=minimize)
    
    solver = SolverFactory('glpk')
    res = solver.solve(model1)
    
    print(model1.display())