之前我们解介绍了TSP、VRP问题,使大家对车辆路径规划问题有了初步的了解,今天我们对VRP问题进一步扩展,我们来探讨带容量限制的车辆路径规划问题:CVRP( capacitated vehicle routing problem)。CVRP是VRP的另一种应用,具体应用场景是这样的: 车辆具有承载能力,每辆车在有限的承载能力的情况下需要在不同地点取货或送货。货物具有数量,重量或体积,并且车辆具有它们可以承载的最大容量上限。我们要做的是以最低的成本提货或送货,同时不能超过车辆的容量上限。下面我们来讲一个具体例子,在讲这个例子之前我们先假设,所有地点的都有货物需要被提取,这里为了将问题简单化,我们只考虑提货不考虑送货(后续我们会考虑既提货也送货的情形),也就是让每辆车到不同的地点去提货,但每次都不能超过车辆自身的容量限制。
CVRP例子
下面我们要举一个具有容量限制的 CVRP 示例。该例在之前的 VRP 例子的基础上进行了扩展:
在每个地点都有一个货物需要提取,并且每个地点的货物都有自己的容量(体积或重量等)。此外,每辆车的最大容量为 15。(这里为了计算简单化,我们不指定容量的单位。)
下面的网格中蓝色圈表示需要访问的地点,中间的黑色圈显示物流公司所在的地点。每个地点需要被提取的货物的容量显示在圆圈的右下方。
我们的要求是为每辆车分配这些地点的访问路线,并且让所有车辆行程的总路程最短,并且每辆车提取的货物不能超过自身的容量限制,所有货物必须被提取。
使用 OR-Tools 解决 CVRP 问题
创建数据模型
首先,根据以上数据示例创建数据模型,数据模型中包含了:
- 距离矩阵(distance_matrix)
- 车辆数量(num_vehicles)
- 出发点索引(depot)
- 每个地点的货物容量需求(demands)
- 每辆车的容量上限(vehicle_capacities)
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
def create_data_model():
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = [
[
0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,
468, 776, 662
],
[
548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674,
1016, 868, 1210
],
[
776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,
1130, 788, 1552, 754
],
[
696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822,
1164, 560, 1358
],
[
582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708,
1050, 674, 1244
],
[
274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,
514, 1050, 708
],
[
502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856,
514, 1278, 480
],
[
194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,
662, 742, 856
],
[
308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,
320, 1084, 514
],
[
194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,
274, 810, 468
],
[
536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,
730, 388, 1152, 354
],
[
502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,
308, 650, 274, 844
],
[
388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194,
536, 388, 730
],
[
354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0,
342, 422, 536
],
[
468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,
342, 0, 764, 194
],
[
776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,
388, 422, 764, 0, 798
],
[
662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,
536, 194, 798, 0
],
]
data['num_vehicles'] = 4 #车辆数量
data['depot'] = 0 #出发点索引
data['demands'] = [0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8] #每个地点的需求量
data['vehicle_capacities'] = [15, 15, 15, 15]#每辆车的容量
return data
data = create_data_model()
这里我们假设有4辆车,每辆车的容量都是15,总共17个地点需要访问(包含出发点), 每个地点都有不同容量的货物需要提取。
创建路由模型
以下代码在程序的主要部分创建了索引管理器(manager)和路由模型(routing)。 manager主要根据distance_matrix来管理各个地点的索引,而routing用来计算和存储访问路径。
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),data['num_vehicles'], data['depot'])
routing = pywrapcp.RoutingModel(manager)
创建距离回调函数
这里我们定义了一个距离回调函数用来从返回distance_matrix中返回给定的两个地点之间的距离,接下来我们还要设置旅行成本(routing.SetArcCostEvaluatorOfAllVehicles)它将告诉求解器如何计算任意两个地点的访问成本, 这里我们的成本指的是任意两个地点之间的距离。
def distance_callback(from_index, to_index):
"""Returns the distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
添加容量需求回调和容量约束
除了距离回调之外,求解器还需要一个容量需求回调,它返回每个位置的需求,以及容量约束的维度。
def demand_callback(from_index):
from_node = manager.IndexToNode(from_index)
return data['demands'][from_node]
demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)
routing.AddDimensionWithVehicleCapacity(
demand_callback_index, # callback_index
0, # slack_max
data['vehicle_capacities'], # capacity
True, # fix_start_cumulative_to_zero
'Capacity' #维度名称)
AddDimension方法的参数说明:
- callback_index:返回两个地点之间距离的回调的索引。索引是求解器对回调的内部引用,由 RegisterTransitCallback 或 RegisterUnitaryTransitCallback 等方法创建。
- slack_max:slack 的最大值,一个变量,用于表示位置的等待时间。如果问题不涉及等待时间,通常可以将 slack_max 设置为 0。
- capacity:容量,沿每条路线累积的总数量的最大值。使用容量来创建类似于 CVRP 中的约束。如果我们的问题没有这样的约束,可以将capacity设置为一个足够大的值,以便对路由没有限制—例如,用于定义回调的矩阵或数组的所有条目的总和。
- fix_start_cumulative_to_zero:布尔值。如果为 true,则数量的累计值从 0 开始。在大多数情况下,应将其设置为 True。但是,对于VRPTW或资源限制问题,由于时间窗口限制,某些车辆可能必须在时间0之后启动,因此您应该针对这些问题将fix_start_cumulative_to_zero设置为False。
- 维度名称:维度名称的字符串,例如“距离”,您可以使用它来访问程序中其他地方的变量。
设置搜索策略
类似于之前TSP应用中的设置,这里我们也需要设置 first_solution_strategy:PATH_CHEAPEST_ARC
, 这里第一解决方案策略设置为PATH_CHEAPEST_ARC
,它通过重复添加不会导致先前访问过的节点(出发点除外)的权重最小的边为求解器创建初始路径,该策略可以快速得到一个可行解。
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
#search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
#search_parameters.time_limit.FromSeconds(30)
后面我们尝试使用更高级的搜索策略(代码中暂时被注释掉的部分):LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH,改策略被称为:引导局部搜索,它能使求解器能够避开局部最小值后继续搜索,但最终的结果不一定是全局最优解。
注意: 使用 GUIDED_LOCAL_SEARCH 或其他元启发式算法时,需要为求解器设置搜索时间限制——否则求解器不会终止。 可以将时间限制设置为 30 秒。
添加打印访问路径函数
该函数可以打印每辆车的路线,以及其累积负载:车辆在其路线上停靠时的总容量。
def print_solution(data, manager, routing, solution):
"""Prints solution on console."""
print(f'Objective: {solution.ObjectiveValue()}')
total_distance = 0
total_load = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
route_load = 0
while not routing.IsEnd(index):
node_index = manager.IndexToNode(index)
route_load += data['demands'][node_index]
plan_output += ' {0} Load({1}) -> '.format(node_index, route_load)
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index),
route_load)
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += 'Load of the route: {}\n'.format(route_load)
print(plan_output)
total_distance += route_distance
total_load += route_load
print('Total distance of all routes: {}m'.format(total_distance))
print('Total load of all routes: {}'.format(total_load))
问题求解
solution = routing.SolveWithParameters(search_parameters)
if solution:
print_solution(data, manager, routing, solution)
这个方案看上去不太理想,因为 vehicle 0和 vehicle 1都绕了两个大圈子,并且它们的行驶路线都超过了2000。
下面是我们把搜索策略切换到GUIDED_LOCAL_SEARCH后的输出结果:
通过切换搜索策略,最短路径由原来的6872减少到6208,并且每辆车的访问路线更加合理,没有出现绕大圈子的情况,而且每辆车的行驶路径的长度都在2000以前,同为1552。
小结
1.在CVRP的应用场景中,数据模型需要增加每个地点的货物容量需求:demands 和 每辆车的容量上限:vehicle_capacities。
2.需要添加容量需求回调函数和容量约束。
3.通过切换搜索策略,可以得到一个较为满意的解。