使用指南:https://developers.google.cn/optimization/introduction/python?hl=zh-cn
实例链接:https://github.com/google/or-tools/tree/stable/ortools/linear_solver/samples
求解器
ortools中的几种常用求解器:
- SCIP:处理混合整数规划(线性约束或非线性约束),处理复杂问题,可能比较耗时
- GLOP:大规模不涉及整数变量的线性优化问题
- CP-SAT: 能够找到所有满足约束条件的解,而不仅仅是找到一个最优解(比如排班安排,有多种可行解)
TSP问题
官网示例代码:https://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/tsp.py
from ortools.constraint_solver import pywrapcp
营养问题
装箱问题
官网示例代码: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)
作业问题
官网示例代码: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