ortools 入門指南

使用指南:https://developers.google.cn/optimization/introduction/python?hl=zh-cn
實(shí)例鏈接:https://github.com/google/or-tools/tree/stable/ortools/linear_solver/samples

求解器

ortools中的幾種常用求解器:

  • SCIP:處理混合整數(shù)規(guī)劃(線性約束或非線性約束),處理復(fù)雜問題,可能比較耗時(shí)
  • GLOP:大規(guī)模不涉及整數(shù)變量的線性優(yōu)化問題
  • CP-SAT: 能夠找到所有滿足約束條件的解,而不僅僅是找到一個(gè)最優(yōu)解(比如排班安排,有多種可行解)

TSP問題

官網(wǎng)示例代碼:https://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/tsp.py
from ortools.constraint_solver import pywrapcp

營(yíng)養(yǎng)問題

裝箱問題

官網(wǎng)示例代碼:https://github.com/google/or-tools/blob/stable/ortools/linear_solver/samples/bin_packing_mip.py
推薦寫法:solver.Add(sum(x[i, j] for j in data["bins"]) == 1)

作業(yè)問題

官網(wǎng)示例代碼:https://github.com/google/or-tools/blob/stable/examples/contrib/assignment.py
boolvar的寫法

work = {}
for worker in range(num_workers):
work[worker] = solver.BoolVar(f"work[{worker}]")

for worker in range(num_workers):
solver.Add(
work[worker] == solver.Sum([x[worker, task] for task in range(num_tasks)])
)

Ab都為真才真的寫法:
constraint_g1 = solver.Constraint(1, 1)
for i in range(len(group1)):
# ab can be transformed into 0 <= a + b - 2p <= 1 with p in [0,1]
# p is True if a AND b, False otherwise
constraint = solver.Constraint(0, 1)
constraint.SetCoefficient(work[group1[i][0]], 1)
constraint.SetCoefficient(work[group1[i][1]], 1)
p = solver.BoolVar(f"g1_p{i}")
constraint.SetCoefficient(p, -2)
constraint_g1.SetCoefficient(p, 1)

日程問題

官方示例代碼:https://github.com/google/or-tools/blob/main/examples/python/shift_scheduling_sat.py

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容