如何在CPLEX Python中实现逻辑或约束

时间:2019-06-21 20:26:26

标签: python cplex

如何在CPLEX Python MP中实现x [0,0] == 0或x [0,0]> = 2这样的约束?

好像是半整数的工作,但在我在Watson Studio DO环境中使用的CPLEX Python版本中没有semiinteger_var_matrix()。我可以使用semiinteger_var_list()可用,但想通过逻辑或约束来教自己。我尝试了x [0,0]!= 1,但是MP无法处理NE。所以我认为我可以做到上面显示的逻辑或约束。查看了doc和docplex.mp.model的来源,但仍无法弄清楚该如何做。我正处于学习CPLEX Python的早期阶段。

3 个答案:

答案 0 :(得分:1)

让我给您一个有关巴士故事的小例子:

from docplex.mp.model import 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()

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

print()
print("with nb buses 40 less than 3 or more than 7")



mdl.add((nbbus40<=3) + (nbbus40>=7) >=1)


mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

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

给出

nbBus40  =  6.0
nbBus30  =  2.0

with nb buses 40 less than 3 or more than 7
nbBus40  =  7.0
nbBus30  =  1.0

注意:您也可以写

from docplex.mp.model import 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()

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

print()
print("with nb buses 40 less than 3 or more than 7")

option1=mdl.binary_var(name='option1')
option2=mdl.binary_var(name='option2')

mdl.add(option1==(nbbus40<=3))
mdl.add(option2==(nbbus40>=7))

mdl.add(1==mdl.logical_or(option1,option2))

mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

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

https://www.linkedin.com/pulse/making-optimization-simple-python-alex-fleischer/上的许多其他小型docplex Python示例

答案 1 :(得分:1)

是的,semiinteger_dict不存在。但是x = model.semiinteger_var_dict((i, j) for i in range(I) for j in range(J)) 确实如此。所以你可以做类似的事情

x[0,0]

,然后您可以将变量引用为module X where import Language.Haskell.TH import Language.Haskell.TH.Quote import Data.Char iQQ :: QuasiQuoter iQQ = QuasiQuoter { quoteExp = return . LitE . IntegerL . read . filter isDigit, quotePat = \_ -> fail "illegal integer QuasiQuote \ \(allowed as expression only, used as a pattern)", quoteType = \_ -> fail "illegal integer QuasiQuote \ \(allowed as expression only, used as a type)", quoteDec = \_ -> fail "illegal integer QuasiQuote \ \(allowed as expression only, used as a declaration)" } 等。

答案 2 :(得分:0)

经典公式(假设上限为u)如下:

introduce fresh binary variable b

post

x <= u * b
x >= l * b

在您的情况下,l=2

u的值取决于问题,因此,必须使其尽可能小以更好地放松,这一点很重要。 (有关该主题的介绍性blog-post