![](/img/trans.png)
[英]CPLEX Python API how to multiply a decision variable with a dummy in the objective function?
[英]How to include a function in CPLEX objective function?
我正在嘗試使用 python API 使用 IBM CPLEX 框架來制定和解決優化問題。
我的目標 function 如下:
在哪里 和
是我的 integer 變量。 我在我的代碼中定義變量如下:
function f如下:
def f(p,n):
if p==4 and n ==4:
return 0.8
elif p==4 and n ==8:
return 0.9
elif p==6. and n==4:
return 0.88
.
.
.
我的問題:
我遇到的問題是關於調用 function f 並在該 function 中使用變量 n。具體而言,我無法將此變量與 4 或 8 等數字進行比較,或者我無法將此變量用作字典的索引。 我得到的錯誤是:
我嘗試如下實現 function f:
def f (p,n):
my_dictionary = {4:{4:0.8,8:0.9},6:{4:0.88,8:0.92}
return my_dictionary[p][n]
我收到“keyerror exception”的錯誤,這意味着我的字典中沒有作為 n 的鍵。
如何將變量的值傳遞給 function 並在那里使用該值?
您可以使用邏輯約束:
from docplex.mp.model import Model
mdl = Model(name='test')
n = mdl.integer_var(name='n')
p = mdl.integer_var(name='p')
restimes100=mdl.integer_var(name='restimes100')
res=mdl.continuous_var(name='res')
def f(p,n):
if p==4 and n ==4:
return 0.8
elif p==4 and n ==8:
return 0.9
elif p==6. and n==4:
return 0.88
mdl.add( mdl.logical_and(p==4,n ==4)==(restimes100==80))
mdl.add( mdl.logical_and(p==4,n ==8)==(restimes100==90))
mdl.add( mdl.logical_and(p==6,n ==4)==(restimes100==88))
mdl.add(p==6)
mdl.add(n==4)
mdl.add(res==restimes100*0.01)
mdl.solve()
print("res in cplex = ",res.solution_value)
print("res with f = ",f(6,4))
給
res in cplex = 0.88
res with f = 0.88
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.