我不明白如何修改docplex中的克隆模型。
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'这个错误是有意义的,因为x是为Model 1创建的,但是我如何获得“克隆x”来修改模型2?
发布于 2021-07-20 08:44:59
变量属于一个模型。您可以通过变量的名称(假设它是唯一的)或索引来检索它。
答案1:使用变量名称
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)答案2:使用变量索引
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)然而,上述两种解决方案增加了一个额外的限制,最好是编辑lhs。这是通过通过索引检索约束的克隆来完成的:
答案3:使用约束索引,编辑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)在最后一种方法中,克隆模型只有一个约束,而不是两个约束。
产出:
\Problem name: Model 2
Maximize
obj: x
Subject To
ct_x_10: x <= 9
Bounds
x <= 10
Generals
x
Endhttps://stackoverflow.com/questions/68440939
复制相似问题