Docplex:在克隆模型中使用变量
Docplex: use variables in a cloned model
我不明白如何修改 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
是为模型 1 创建的,但是我如何获得 'cloned x' 来修改模型 2?
变量属于一个模型。您可以通过其名称(假设它是唯一的)或其索引检索变量。
答案一:使用变量名
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:使用变量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)
不过,上面的两个解决方案增加了一个额外的约束条件,最好编辑 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
End
我不明白如何修改 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
是为模型 1 创建的,但是我如何获得 'cloned x' 来修改模型 2?
变量属于一个模型。您可以通过其名称(假设它是唯一的)或其索引检索变量。
答案一:使用变量名
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:使用变量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)
不过,上面的两个解决方案增加了一个额外的约束条件,最好编辑 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
End