1#!/usr/bin/env python3 2# Copyright 2010-2021 Google LLC 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# [START program] 15"""Capacited Vehicles Routing Problem (CVRP).""" 16 17# [START import] 18from ortools.constraint_solver import routing_enums_pb2 19from ortools.constraint_solver import pywrapcp 20# [END import] 21 22 23# [START data_model] 24def create_data_model(): 25 """Stores the data for the problem.""" 26 data = {} 27 data['distance_matrix'] = [ 28 [ 29 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 30 468, 776, 662 31 ], 32 [ 33 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 34 1016, 868, 1210 35 ], 36 [ 37 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 38 1130, 788, 1552, 754 39 ], 40 [ 41 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 42 1164, 560, 1358 43 ], 44 [ 45 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 46 1050, 674, 1244 47 ], 48 [ 49 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 50 514, 1050, 708 51 ], 52 [ 53 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 54 514, 1278, 480 55 ], 56 [ 57 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 58 662, 742, 856 59 ], 60 [ 61 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 62 320, 1084, 514 63 ], 64 [ 65 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 66 274, 810, 468 67 ], 68 [ 69 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 70 730, 388, 1152, 354 71 ], 72 [ 73 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 74 308, 650, 274, 844 75 ], 76 [ 77 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 78 536, 388, 730 79 ], 80 [ 81 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 82 342, 422, 536 83 ], 84 [ 85 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 86 342, 0, 764, 194 87 ], 88 [ 89 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 90 388, 422, 764, 0, 798 91 ], 92 [ 93 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 94 536, 194, 798, 0 95 ], 96 ] 97 # [START demands_capacities] 98 data['demands'] = [0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8] 99 data['vehicle_capacities'] = [15, 15, 15, 15] 100 # [END demands_capacities] 101 data['num_vehicles'] = 4 102 data['depot'] = 0 103 return data 104 # [END data_model] 105 106 107# [START solution_printer] 108def print_solution(data, manager, routing, solution): 109 """Prints solution on console.""" 110 print(f'Objective: {solution.ObjectiveValue()}') 111 total_distance = 0 112 total_load = 0 113 for vehicle_id in range(data['num_vehicles']): 114 index = routing.Start(vehicle_id) 115 plan_output = 'Route for vehicle {}:\n'.format(vehicle_id) 116 route_distance = 0 117 route_load = 0 118 while not routing.IsEnd(index): 119 node_index = manager.IndexToNode(index) 120 route_load += data['demands'][node_index] 121 plan_output += ' {0} Load({1}) -> '.format(node_index, route_load) 122 previous_index = index 123 index = solution.Value(routing.NextVar(index)) 124 route_distance += routing.GetArcCostForVehicle( 125 previous_index, index, vehicle_id) 126 plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index), 127 route_load) 128 plan_output += 'Distance of the route: {}m\n'.format(route_distance) 129 plan_output += 'Load of the route: {}\n'.format(route_load) 130 print(plan_output) 131 total_distance += route_distance 132 total_load += route_load 133 print('Total distance of all routes: {}m'.format(total_distance)) 134 print('Total load of all routes: {}'.format(total_load)) 135 # [END solution_printer] 136 137 138def main(): 139 """Solve the CVRP problem.""" 140 # Instantiate the data problem. 141 # [START data] 142 data = create_data_model() 143 # [END data] 144 145 # Create the routing index manager. 146 # [START index_manager] 147 manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), 148 data['num_vehicles'], data['depot']) 149 # [END index_manager] 150 151 # Create Routing Model. 152 # [START routing_model] 153 routing = pywrapcp.RoutingModel(manager) 154 155 # [END routing_model] 156 157 # Create and register a transit callback. 158 # [START transit_callback] 159 def distance_callback(from_index, to_index): 160 """Returns the distance between the two nodes.""" 161 # Convert from routing variable Index to distance matrix NodeIndex. 162 from_node = manager.IndexToNode(from_index) 163 to_node = manager.IndexToNode(to_index) 164 return data['distance_matrix'][from_node][to_node] 165 166 transit_callback_index = routing.RegisterTransitCallback(distance_callback) 167 # [END transit_callback] 168 169 # Define cost of each arc. 170 # [START arc_cost] 171 routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) 172 173 # [END arc_cost] 174 175 # Add Capacity constraint. 176 # [START capacity_constraint] 177 def demand_callback(from_index): 178 """Returns the demand of the node.""" 179 # Convert from routing variable Index to demands NodeIndex. 180 from_node = manager.IndexToNode(from_index) 181 return data['demands'][from_node] 182 183 demand_callback_index = routing.RegisterUnaryTransitCallback( 184 demand_callback) 185 routing.AddDimensionWithVehicleCapacity( 186 demand_callback_index, 187 0, # null capacity slack 188 data['vehicle_capacities'], # vehicle maximum capacities 189 True, # start cumul to zero 190 'Capacity') 191 # [END capacity_constraint] 192 193 # Setting first solution heuristic. 194 # [START parameters] 195 search_parameters = pywrapcp.DefaultRoutingSearchParameters() 196 search_parameters.first_solution_strategy = ( 197 routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) 198 search_parameters.local_search_metaheuristic = ( 199 routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) 200 search_parameters.time_limit.FromSeconds(1) 201 # [END parameters] 202 203 # Solve the problem. 204 # [START solve] 205 solution = routing.SolveWithParameters(search_parameters) 206 # [END solve] 207 208 # Print solution on console. 209 # [START print_solution] 210 if solution: 211 print_solution(data, manager, routing, solution) 212 # [END print_solution] 213 214 215if __name__ == '__main__': 216 main() 217# [END program] 218