0

I do not understand how cloned models in docplex can be modified.

from docplex.mp.model import Model

mdl_1 = Model('Model 1')

x = mdl_1.integer_var(0, 10, 'x')
mdl_1.add_constraint( x <= 10)

mdl_1.maximize(x)
mdl_1.solve()

#now clone
mdl_2 = mdl_1.clone(new_name='Model 2')

mdl_2.add_constraint( x <= 9) # throws (x <= 9) is not in model 'Model 2'

The error makes sense, as x was created for Model 1, but how do I get the 'cloned x' to modify Model 2?

Finn
  • 2,333
  • 1
  • 10
  • 21

1 Answers1

0

Variable belong to one model. You can retrieve a variable either via its name (assuming it is unique) or its index.

Answer 1: use variable name

x_2 = mdl_2.get_var_by_name('x')
mdl_2.add_constraint( x_2 <= 9) # throws (x <= 9) is not in model 'Model 2'
print(mdl_2.lp_string)

Answer 2: use the variable index

x_2 = mdl_2.get_var_by_index(x.index)
mdl_2.add_constraint( x_2 <= 9) # throws (x <= 9) is not in model 'Model 2'
print(mdl_2.lp_string)

However, the two solutions above add one extra constraint, it would be better to edit the lhs. This is done by retrieveing the constraint's clone via its index:

Answer 3: use the constraint index, edit rhs

c_2 = mdl_2.get_constraint_by_index(c1.index)
c_2.rhs = 9  # modify the rhs of the cloned constraint , in place
print(mdl_2.lp_string)

In this last approach, the cloned model has only one constraint, not two.

output:

\Problem name: Model 2

Maximize
 obj: x
Subject To
 ct_x_10: x <= 9

Bounds
       x <= 10

Generals
 x
End
Philippe Couronne
  • 826
  • 1
  • 5
  • 6