or-tools求解约束规划

前言

约束优化或约束规划(Constraint programming, CP)是指从一组非常大的候选集合中找出可行的解决方案,在这些候选集合中,问题可以用任意约束来建模,许多科学和工程学科中都存在CP问题。
CP是基于可行性(寻找一个可行的解决方案)而不是最优化(寻找一个最优的解决方案),它关注的是约束和变量而不是目标函数。实际上,CP问题甚至可能没有目标函数——目标可能只是通过向问题添加约束,将各种可能的解决方案缩小到更易于管理的子集。

问题

假设有3个变量x、y、z,三个数的取值都是{0,1,2},唯一的约束的x不等于y。

求解

值得注意的是,为了提高计算速度,ortools中的CP-SAT求解器只能处理整数,即所有约束的系数都应该为整数,否则乘以一个数使之变为整数。

from ortools.sat.python import cp_model

# 模型
model = cp_model.CpModel()

# 变量
num_val = 3
x = model.NewIntVar(0, 2, 'x')
y = model.NewIntVar(0, 2, 'y')
z = model.NewIntVar(0, 2, 'z')

# 约束
model.Add(x != y)

# 求解
solver = cp_model.CpSolver()
status = solver.Solve(model)

# 结果
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
    print('x=', solver.Value(x))
    print('y=', solver.Value(y))
    print('z=', solver.Value(z))

结果

在这里插入图片描述

获取所有可行解

值得注意的是,callback类中必须定义on_slution_callback(self)函数

from ortools.sat.python import cp_model

# 模型
model = cp_model.CpModel()

# 变量
num_val = 3
x = model.NewIntVar(0, 2, 'x')
y = model.NewIntVar(0, 2, 'y')
z = model.NewIntVar(0, 2, 'z')

# 约束
model.Add(x != y)
model.Add(x != z)
model.Add(y != z)


# callback类
class AllResult(cp_model.CpSolverSolutionCallback):
    def __init__(self, variables):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.variables = variables

    # 必须要写的callback函数
    def on_solution_callback(self):
        for v in self.variables:
            print(self.Value(v), end='\t')
        print('\n')


# 求解
solver = cp_model.CpSolver()
all_result = AllResult([x, y, z])
status = solver.SearchForAllSolutions(model, all_result)

# 结果
if status == cp_model.OPTIMAL:
    print('all feasible solution found')

约束规划求解带目标函数的问题

约束规划同样支持带目标函数的问题,但是目标函数系数和约束系数都必须保持为整数。

from ortools.sat.python import cp_model

# 模型
model = cp_model.CpModel()

# 变量
var_upper_bound = max(50, 45, 37)
x = model.NewIntVar(0, var_upper_bound, 'x')
y = model.NewIntVar(0, var_upper_bound, 'y')
z = model.NewIntVar(0, var_upper_bound, 'z')

# 约束
model.Add(2 * x + 7 * y + 3 * z <= 50)
model.Add(3 * x - 5 * y + 7 * z <= 45)
model.Add(5 * x + 2 * y - 6 * z <= 37)

# 目标函数
model.Maximize(2 * x + 2 * y + 3 * z)

# 求解
solver = cp_model.CpSolver()
status = solver.Solve(model)

# 结果
if status == cp_model.OPTIMAL:
    print('x=', solver.Value(x))
    print('y=', solver.Value(y))
    print('z=', solver.Value(z))
    print('objective=', solver.ObjectiveValue())

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值