Get an instance to inherit another instance's constraints in pyomo

99 views Asked by At

I'm trying to create an instance that inherits another instance's constraints, whilst adding some new ones.

Is there a way to "copy" the previous instance's constraints into the new one?

Here's a snippet from the code

...
model.bnb_bound_constraints = ConstraintList()
...

non_solved_instances = []
bnb_end = False
incumbent_value = 0
solve_counter = 0
integer_variables_list = []

bnb_instance = model.create_instance(data)
variables_list = [bnb_instance.x]
non_solved_instances.append(bnb_instance) 

while bnb_end != True:

    solve_counter += 1
    print len(non_solved_instances), "Non solved instance(s)"
    bnb_solve = optsolver.solve(non_solved_instances[0], tee = False)
    print "Objective value for instance", solve_counter,":",value(non_solved_instances[0].obj)

    if value(non_solved_instances[0].obj.sense)*value(non_solved_instances[0].obj) <= value(non_solved_instances[0].obj.sense)*incumbent_value:

        incumbent_value = 2000

        for new_instance in range(2):

            bnb_instance = model.create_instance(data)
            variables_list = [bnb_instance.x]

            for con in non_solved_instances[0].bnb_bound_constraints:
                bnb_instance.bnb_bound_constraints.add(non_solved_instances[0].bnb_bound_constraints[con].expr)
                #This is what ive been trying to do to copy the constraints, doesnt work though.

            if new_instance == 0:
                bnb_instance.bnb_bound_constraints.add(expr = bnb_instance.x[solve_counter] <= floor(value(non_solved_instances[0].x[solve_counter])))
                #adds a new constraint to bnb_instance

            elif new_instance == 1:
                bnb_instance.bnb_bound_constraints.add(expr = bnb_instance.x[solve_counter] >= ceil(value(non_solved_instances[0].x[solve_counter]))) 
                #adds a new constraint to bnb_instance

            non_solved_instances.append(bnb_instance)

    del non_solved_instances[0]

    if len(non_solved_instances) == 0 or solve_counter >= 20:
        bnb_end = True

non_solved_instances[0] contains the "original" instance, whose constraints i wish to inherit to bnb_instance

Cheers!

1

There are 1 answers

0
Bethany Nicholson On BEST ANSWER

One way would be to clone the entire model and then add additional constraints to the clone

m = ConcreteModel()
# Add stuff to m

m2 = m.clone()
m2.c2 = Constraint(expr=m2.x**2<=10)