使用docplex python API添加新变量的有效方法是什么?

时间:2019-11-13 07:12:00

标签: cplex docplex

我对docplex库有一个基本问题。 有谁知道从现有模型中添加/删除变量的最佳方法是什么? 我正在使用以下代码创建决策变量

self.model.continuous_var_dict(self.N, lb=0)

我可以仅增加self.N的大小来再次运行此行吗?

我还想知道是否存在一种更新现有约束的有效方法,现在,我正在删除所有约束,并使用以下代码添加新约束

self.model.remove_constraints(self.constrains)
self.constrains = self.model.add_constraints(
        self.model.sum(self.cons_coef[(i, k, p)] * self.x_mp[(k, p)] for k, p in self.N) == 1 for i in range(N))

如果我只想在列生成中添加新列怎么办?

2 个答案:

答案 0 :(得分:0)

您可以进行增量更改:

 from docplex.mp.model import Model

# original model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

mdl.export("c:\\buses.lp")

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

#now 350 kids instead of 300

print()
print("now 350 kids instead of 300")    

mdl.get_constraint_by_name("kids").rhs=350;
mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

# no more than 4 buses 40 seats

print()
print("no more than 4 buses 40 seats")


mdl.get_var_by_name("nbBus40").ub=4
mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

#change the objective so that cost for 40 seats is 450
#and remove the limit on the number of buses 40 seats

print()
print("change the objective so that cost for 40 seats is 450")
print("and remove the limit on the number of buses 40 seats  ")  

mdl.get_var_by_name("nbBus40").ub=1000
mdl.set_objective("min",nbbus40*450 + nbbus30*400);
mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value) 

给出

nbBus40  =  6.0
nbBus30  =  2.0

now 350 kids instead of 300
nbBus40  =  8.0
nbBus30  =  1.0

no more than 4 buses 40 seats
nbBus40  =  2.0
nbBus30  =  9.0

change the objective so that cost for 40 seats is 450
and remove the limit on the number of buses 40 seats  
nbBus40  =  8.0
nbBus30  =  1.0

答案 1 :(得分:0)

添加变量(通过continuous_var_dict)的方式很好。是的,您可以重复调用continuous_var_dict以添加几批变量。在性能方面,docplex应该以最快的方式将它们添加到CPLEX中。如果您对效果不佳感到惊讶,请分享具体信息。

要删除变量,请从模型的目标和约束中删除它们。例如,使用LinearExpr.remove_term

要修改约束,您可以执行以下操作(请参见LinearConstraint.lhs):

for c in contraints:
   c.lhs += model.sum_vars(newvars)

docplex“增量建模”示例对此进行了演示(请参见here)。