如何使用 Python 更新 cplex 中的约束

How to update a constraint in cplex using Python

我正在使用 CPLEX 解决转运问题。首先,我使用 add_constraints 函数为标准转运问题添加三组约束,如下所示:

现在由于有一个link从一个供应节点到一个需求节点,我需要修改两个约束。任何人都知道如何实现这一点?提前致谢。

Making optimization simple with python see get and set coef

from docplex.mp.model import Model

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

mdl.solve(log_output=False,)


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


for v in ctKids.iter_variables():
   print(v," --> ",ctKids.lhs.get_coef(v))

#And now let us allow 5 more kids per bus
print("And now let us allow 5 more kids per bus")

for v in ctKids.iter_variables():  
   ctKids.lhs.add_term(v,5)


for v in ctKids.iter_variables():
   print(v," --> ",ctKids.lhs[v])

mdl.solve(log_output=False,)


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

将这些约束命名为

    supply=opt_md.add_constraints(((sum(x[i,j] for j \

        in range(n))<=s[i]) for i in range(m)),\

        names='supply')

    demand=opt_md.add_constraints(((sum(y[j,k] for j \

        in range(n))==d[k]) for k in range(p)), \

        names='demand')

    transship=opt_md.add_constraints(((sum(x[i,j] for i \

        in range(m))==(sum(y[j,k] for k \

        in range(p)))) for j in range(n)), \

        names="transship")

假设节点2为供给节点,节点8为需求节点。假设我们从 2 到 8 添加一个直接 link,变量运费为 4。首先,添加一个决策变量 x_2_8=opt_md.continuous_var(名称='x_2_8',lb=0)

然后我们需要更新两个约束(一个用于供应节点 2,另一个用于需求节点 8):

supply[1].lhs=supply[1].lhs+x_2_8

demand[3].lhs=demand[3].lhs+x_2_8

应将新项 4*x_2_8 添加到 objective 函数中。