tools: update notebooks

This commit is contained in:
Corentin Le Molgat
2023-11-13 10:51:25 +01:00
parent c5267146fa
commit 43e400c4f2
10 changed files with 23 additions and 891 deletions

View File

@@ -1,268 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2023 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# cvrp"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/cvrp.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/cvrp.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"%pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"Capacitated Vehicle Routing Problem (CVRP).\n",
"\n",
" This is a sample using the routing library python wrapper to solve a CVRP\n",
" problem.\n",
" A description of the problem can be found here:\n",
" http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
"\n",
" Distances are in meters.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"from functools import partial\n",
"\n",
"from ortools.constraint_solver import pywrapcp\n",
"from ortools.constraint_solver import routing_enums_pb2\n",
"\n",
"\n",
"###########################\n",
"# Problem Data Definition #\n",
"###########################\n",
"def create_data_model():\n",
" \"\"\"Stores the data for the problem\"\"\"\n",
" data = {}\n",
" # Locations in block unit\n",
" _locations = \\\n",
" [(4, 4), # depot\n",
" (2, 0), (8, 0), # locations to visit\n",
" (0, 1), (1, 1),\n",
" (5, 2), (7, 2),\n",
" (3, 3), (6, 3),\n",
" (5, 5), (8, 5),\n",
" (1, 6), (2, 6),\n",
" (3, 7), (6, 7),\n",
" (0, 8), (7, 8)]\n",
" # Compute locations in meters using the block dimension defined as follow\n",
" # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
" # here we use: 114m x 80m city block\n",
" # src: https://nyti.ms/2GDoRIe 'NY Times: Know Your distance'\n",
" data['locations'] = [(l[0] * 114, l[1] * 80) for l in _locations]\n",
" data['num_locations'] = len(data['locations'])\n",
" data['demands'] = \\\n",
" [0, # depot\n",
" 1, 1, # 1, 2\n",
" 2, 4, # 3, 4\n",
" 2, 4, # 5, 6\n",
" 8, 8, # 7, 8\n",
" 1, 2, # 9,10\n",
" 1, 2, # 11,12\n",
" 4, 4, # 13, 14\n",
" 8, 8] # 15, 16\n",
" data['num_vehicles'] = 4\n",
" data['vehicle_capacity'] = 15\n",
" data['depot'] = 0\n",
" return data\n",
"\n",
"\n",
"#######################\n",
"# Problem Constraints #\n",
"#######################\n",
"def manhattan_distance(position_1, position_2):\n",
" \"\"\"Computes the Manhattan distance between two points\"\"\"\n",
" return (abs(position_1[0] - position_2[0]) +\n",
" abs(position_1[1] - position_2[1]))\n",
"\n",
"\n",
"def create_distance_evaluator(data):\n",
" \"\"\"Creates callback to return distance between points.\"\"\"\n",
" _distances = {}\n",
" # precompute distance between location to have distance callback in O(1)\n",
" for from_node in range(data['num_locations']):\n",
" _distances[from_node] = {}\n",
" for to_node in range(data['num_locations']):\n",
" if from_node == to_node:\n",
" _distances[from_node][to_node] = 0\n",
" else:\n",
" _distances[from_node][to_node] = (manhattan_distance(\n",
" data['locations'][from_node], data['locations'][to_node]))\n",
"\n",
" def distance_evaluator(manager, from_node, to_node):\n",
" \"\"\"Returns the manhattan distance between the two nodes\"\"\"\n",
" return _distances[manager.IndexToNode(from_node)][manager.IndexToNode(\n",
" to_node)]\n",
"\n",
" return distance_evaluator\n",
"\n",
"\n",
"def create_demand_evaluator(data):\n",
" \"\"\"Creates callback to get demands at each location.\"\"\"\n",
" _demands = data['demands']\n",
"\n",
" def demand_evaluator(manager, node):\n",
" \"\"\"Returns the demand of the current node\"\"\"\n",
" return _demands[manager.IndexToNode(node)]\n",
"\n",
" return demand_evaluator\n",
"\n",
"\n",
"def add_capacity_constraints(routing, data, demand_evaluator_index):\n",
" \"\"\"Adds capacity constraint\"\"\"\n",
" capacity = 'Capacity'\n",
" routing.AddDimension(\n",
" demand_evaluator_index,\n",
" 0, # null capacity slack\n",
" data['vehicle_capacity'],\n",
" True, # start cumul to zero\n",
" capacity)\n",
"\n",
"\n",
"###########\n",
"# Printer #\n",
"###########\n",
"def print_solution(data, routing, manager, assignment): # pylint:disable=too-many-locals\n",
" \"\"\"Prints assignment on console\"\"\"\n",
" print(f'Objective: {assignment.ObjectiveValue()}')\n",
" total_distance = 0\n",
" total_load = 0\n",
" capacity_dimension = routing.GetDimensionOrDie('Capacity')\n",
" for vehicle_id in range(data['num_vehicles']):\n",
" index = routing.Start(vehicle_id)\n",
" plan_output = f'Route for vehicle {vehicle_id}:\\n'\n",
" distance = 0\n",
" while not routing.IsEnd(index):\n",
" load_var = capacity_dimension.CumulVar(index)\n",
" plan_output += (f' {manager.IndexToNode(index)} '\n",
" f'Load({assignment.Value(load_var)}) -> ')\n",
" previous_index = index\n",
" index = assignment.Value(routing.NextVar(index))\n",
" distance += routing.GetArcCostForVehicle(previous_index, index,\n",
" vehicle_id)\n",
" load_var = capacity_dimension.CumulVar(index)\n",
" plan_output += f' {manager.IndexToNode(index)} Load({assignment.Value(load_var)})\\n'\n",
" plan_output += f'Distance of the route: {distance}m\\n'\n",
" plan_output += f'Load of the route: {assignment.Value(load_var)}\\n'\n",
" print(plan_output)\n",
" total_distance += distance\n",
" total_load += assignment.Value(load_var)\n",
" print(f'Total Distance of all routes: {total_distance}m')\n",
" print(f'Total Load of all routes: {total_load}')\n",
"\n",
"\n",
"########\n",
"# Main #\n",
"########\n",
"def main():\n",
" \"\"\"Entry point of the program\"\"\"\n",
" # Instantiate the data problem.\n",
" data = create_data_model()\n",
"\n",
" # Create the routing index manager\n",
" manager = pywrapcp.RoutingIndexManager(data['num_locations'],\n",
" data['num_vehicles'], data['depot'])\n",
"\n",
" # Create Routing Model\n",
" routing = pywrapcp.RoutingModel(manager)\n",
"\n",
" # Define weight of each edge\n",
" distance_evaluator = routing.RegisterTransitCallback(\n",
" partial(create_distance_evaluator(data), manager))\n",
" routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator)\n",
"\n",
" # Add Capacity constraint\n",
" demand_evaluator_index = routing.RegisterUnaryTransitCallback(\n",
" partial(create_demand_evaluator(data), manager))\n",
" add_capacity_constraints(routing, data, demand_evaluator_index)\n",
"\n",
" # Setting first solution heuristic (cheapest addition).\n",
" search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
" search_parameters.first_solution_strategy = (\n",
" routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # pylint: disable=no-member\n",
" search_parameters.local_search_metaheuristic = (\n",
" routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)\n",
" search_parameters.time_limit.FromSeconds(1)\n",
"\n",
" # Solve the problem.\n",
" assignment = routing.SolveWithParameters(search_parameters)\n",
" print_solution(data, routing, manager, assignment)\n",
"\n",
"\n",
"main()\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -1,366 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2023 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# cvrptw"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/cvrptw.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/cvrptw.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"%pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"Capacitated Vehicle Routing Problem with Time Windows (CVRPTW).\n",
"\n",
" This is a sample using the routing library python wrapper to solve a CVRPTW\n",
" problem.\n",
" A description of the problem can be found here:\n",
" http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
"\n",
" Distances are in meters and time in minutes.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"from functools import partial\n",
"from ortools.constraint_solver import routing_enums_pb2\n",
"from ortools.constraint_solver import pywrapcp\n",
"\n",
"\n",
"def create_data_model():\n",
" \"\"\"Stores the data for the problem.\"\"\"\n",
" data = {}\n",
" # Locations in block unit\n",
" _locations = \\\n",
" [(4, 4), # depot\n",
" (2, 0), (8, 0), # locations to visit\n",
" (0, 1), (1, 1),\n",
" (5, 2), (7, 2),\n",
" (3, 3), (6, 3),\n",
" (5, 5), (8, 5),\n",
" (1, 6), (2, 6),\n",
" (3, 7), (6, 7),\n",
" (0, 8), (7, 8)]\n",
" # Compute locations in meters using the block dimension defined as follow\n",
" # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
" # here we use: 114m x 80m city block\n",
" # src: https://nyti.ms/2GDoRIe \"NY Times: Know Your distance\"\n",
" data['locations'] = [(l[0] * 114, l[1] * 80) for l in _locations]\n",
" data['num_locations'] = len(data['locations'])\n",
" data['time_windows'] = \\\n",
" [(0, 0),\n",
" (75, 85), (75, 85), # 1, 2\n",
" (60, 70), (45, 55), # 3, 4\n",
" (0, 8), (50, 60), # 5, 6\n",
" (0, 10), (10, 20), # 7, 8\n",
" (0, 10), (75, 85), # 9, 10\n",
" (85, 95), (5, 15), # 11, 12\n",
" (15, 25), (10, 20), # 13, 14\n",
" (45, 55), (30, 40)] # 15, 16\n",
" data['demands'] = \\\n",
" [0, # depot\n",
" 1, 1, # 1, 2\n",
" 2, 4, # 3, 4\n",
" 2, 4, # 5, 6\n",
" 8, 8, # 7, 8\n",
" 1, 2, # 9,10\n",
" 1, 2, # 11,12\n",
" 4, 4, # 13, 14\n",
" 8, 8] # 15, 16\n",
" data['time_per_demand_unit'] = 5 # 5 minutes/unit\n",
" data['num_vehicles'] = 4\n",
" data['vehicle_capacity'] = 15\n",
" data['vehicle_speed'] = 83 # Travel speed: 5km/h converted in m/min\n",
" data['depot'] = 0\n",
" return data\n",
"\n",
"\n",
"#######################\n",
"# Problem Constraints #\n",
"#######################\n",
"def manhattan_distance(position_1, position_2):\n",
" \"\"\"Computes the Manhattan distance between two points\"\"\"\n",
" return (abs(position_1[0] - position_2[0]) +\n",
" abs(position_1[1] - position_2[1]))\n",
"\n",
"\n",
"def create_distance_evaluator(data):\n",
" \"\"\"Creates callback to return distance between points.\"\"\"\n",
" _distances = {}\n",
" # precompute distance between location to have distance callback in O(1)\n",
" for from_node in range(data['num_locations']):\n",
" _distances[from_node] = {}\n",
" for to_node in range(data['num_locations']):\n",
" if from_node == to_node:\n",
" _distances[from_node][to_node] = 0\n",
" else:\n",
" _distances[from_node][to_node] = (manhattan_distance(\n",
" data['locations'][from_node], data['locations'][to_node]))\n",
"\n",
" def distance_evaluator(manager, from_node, to_node):\n",
" \"\"\"Returns the manhattan distance between the two nodes\"\"\"\n",
" return _distances[manager.IndexToNode(from_node)][manager.IndexToNode(\n",
" to_node)]\n",
"\n",
" return distance_evaluator\n",
"\n",
"\n",
"def create_demand_evaluator(data):\n",
" \"\"\"Creates callback to get demands at each location.\"\"\"\n",
" _demands = data['demands']\n",
"\n",
" def demand_evaluator(manager, node):\n",
" \"\"\"Returns the demand of the current node\"\"\"\n",
" return _demands[manager.IndexToNode(node)]\n",
"\n",
" return demand_evaluator\n",
"\n",
"\n",
"def add_capacity_constraints(routing, data, demand_evaluator_index):\n",
" \"\"\"Adds capacity constraint\"\"\"\n",
" capacity = 'Capacity'\n",
" routing.AddDimension(\n",
" demand_evaluator_index,\n",
" 0, # null capacity slack\n",
" data['vehicle_capacity'],\n",
" True, # start cumul to zero\n",
" capacity)\n",
"\n",
"\n",
"def create_time_evaluator(data):\n",
" \"\"\"Creates callback to get total times between locations.\"\"\"\n",
"\n",
" def service_time(data, node):\n",
" \"\"\"Gets the service time for the specified location.\"\"\"\n",
" return data['demands'][node] * data['time_per_demand_unit']\n",
"\n",
" def travel_time(data, from_node, to_node):\n",
" \"\"\"Gets the travel times between two locations.\"\"\"\n",
" if from_node == to_node:\n",
" travel_time = 0\n",
" else:\n",
" travel_time = manhattan_distance(\n",
" data['locations'][from_node],\n",
" data['locations'][to_node]) / data['vehicle_speed']\n",
" return travel_time\n",
"\n",
" _total_time = {}\n",
" # precompute total time to have time callback in O(1)\n",
" for from_node in range(data['num_locations']):\n",
" _total_time[from_node] = {}\n",
" for to_node in range(data['num_locations']):\n",
" if from_node == to_node:\n",
" _total_time[from_node][to_node] = 0\n",
" else:\n",
" _total_time[from_node][to_node] = int(\n",
" service_time(data, from_node) +\n",
" travel_time(data, from_node, to_node))\n",
"\n",
" def time_evaluator(manager, from_node, to_node):\n",
" \"\"\"Returns the total time between the two nodes\"\"\"\n",
" return _total_time[manager.IndexToNode(from_node)][manager.IndexToNode(\n",
" to_node)]\n",
"\n",
" return time_evaluator\n",
"\n",
"\n",
"def add_time_window_constraints(routing, manager, data, time_evaluator_index):\n",
" \"\"\"Add Global Span constraint\"\"\"\n",
" time = 'Time'\n",
" horizon = 120\n",
" routing.AddDimension(\n",
" time_evaluator_index,\n",
" horizon, # allow waiting time\n",
" horizon, # maximum time per vehicle\n",
" False, # don't force start cumul to zero since we are giving TW to start nodes\n",
" time)\n",
" time_dimension = routing.GetDimensionOrDie(time)\n",
" # Add time window constraints for each location except depot\n",
" # and 'copy' the slack var in the solution object (aka Assignment) to print it\n",
" for location_idx, time_window in enumerate(data['time_windows']):\n",
" if location_idx == 0:\n",
" continue\n",
" index = manager.NodeToIndex(location_idx)\n",
" time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])\n",
" routing.AddToAssignment(time_dimension.SlackVar(index))\n",
" # Add time window constraints for each vehicle start node\n",
" # and 'copy' the slack var in the solution object (aka Assignment) to print it\n",
" for vehicle_id in range(data['num_vehicles']):\n",
" index = routing.Start(vehicle_id)\n",
" time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],\n",
" data['time_windows'][0][1])\n",
" routing.AddToAssignment(time_dimension.SlackVar(index))\n",
" # Warning: Slack var is not defined for vehicle's end node\n",
" #routing.AddToAssignment(time_dimension.SlackVar(self.routing.End(vehicle_id)))\n",
"\n",
"\n",
"def print_solution(manager, routing, assignment): # pylint:disable=too-many-locals\n",
" \"\"\"Prints assignment on console\"\"\"\n",
" print(f'Objective: {assignment.ObjectiveValue()}')\n",
" time_dimension = routing.GetDimensionOrDie('Time')\n",
" capacity_dimension = routing.GetDimensionOrDie('Capacity')\n",
" total_distance = 0\n",
" total_load = 0\n",
" total_time = 0\n",
" for vehicle_id in range(manager.GetNumberOfVehicles()):\n",
" index = routing.Start(vehicle_id)\n",
" plan_output = f'Route for vehicle {vehicle_id}:\\n'\n",
" distance = 0\n",
" while not routing.IsEnd(index):\n",
" load_var = capacity_dimension.CumulVar(index)\n",
" time_var = time_dimension.CumulVar(index)\n",
" slack_var = time_dimension.SlackVar(index)\n",
" plan_output += (\n",
" f' {manager.IndexToNode(index)} '\n",
" f'Load({assignment.Value(load_var)}) '\n",
" f'Time({assignment.Min(time_var)},{assignment.Max(time_var)}) '\n",
" f'Slack({assignment.Min(slack_var)},{assignment.Max(slack_var)}) ->'\n",
" )\n",
" previous_index = index\n",
" index = assignment.Value(routing.NextVar(index))\n",
" distance += routing.GetArcCostForVehicle(previous_index, index,\n",
" vehicle_id)\n",
" load_var = capacity_dimension.CumulVar(index)\n",
" time_var = time_dimension.CumulVar(index)\n",
" slack_var = time_dimension.SlackVar(index)\n",
" plan_output += (\n",
" f' {manager.IndexToNode(index)} '\n",
" f'Load({assignment.Value(load_var)}) '\n",
" f'Time({assignment.Min(time_var)},{assignment.Max(time_var)})\\n')\n",
" plan_output += f'Distance of the route: {distance}m\\n'\n",
" plan_output += f'Load of the route: {assignment.Value(load_var)}\\n'\n",
" plan_output += f'Time of the route: {assignment.Value(time_var)}\\n'\n",
" print(plan_output)\n",
" total_distance += distance\n",
" total_load += assignment.Value(load_var)\n",
" total_time += assignment.Value(time_var)\n",
" print(f'Total Distance of all routes: {total_distance}m')\n",
" print(f'Total Load of all routes: {total_load}')\n",
" print(f'Total Time of all routes: {total_time}min')\n",
"\n",
"\n",
"def main():\n",
" \"\"\"Solve the Capacitated VRP with time windows.\"\"\"\n",
" # Instantiate the data problem.\n",
" data = create_data_model()\n",
"\n",
" # Create the routing index manager.\n",
" manager = pywrapcp.RoutingIndexManager(data['num_locations'],\n",
" data['num_vehicles'], data['depot'])\n",
"\n",
" # Create Routing Model.\n",
" routing = pywrapcp.RoutingModel(manager)\n",
"\n",
" # Define weight of each edge.\n",
" distance_evaluator_index = routing.RegisterTransitCallback(\n",
" partial(create_distance_evaluator(data), manager))\n",
"\n",
" # Define cost of each arc.\n",
" routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\n",
"\n",
" # Add Capacity constraint.\n",
" demand_evaluator_index = routing.RegisterUnaryTransitCallback(\n",
" partial(create_demand_evaluator(data), manager))\n",
" add_capacity_constraints(routing, data, demand_evaluator_index)\n",
"\n",
" # Add Time Window constraint.\n",
" time_evaluator_index = routing.RegisterTransitCallback(\n",
" partial(create_time_evaluator(data), manager))\n",
" add_time_window_constraints(routing, manager, data, time_evaluator_index)\n",
"\n",
" # Setting first solution heuristic (cheapest addition).\n",
" search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
" search_parameters.first_solution_strategy = (\n",
" routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
" search_parameters.local_search_metaheuristic = (\n",
" routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)\n",
" search_parameters.time_limit.FromSeconds(2)\n",
" search_parameters.log_search = True\n",
"\n",
" # Solve the problem.\n",
" solution = routing.SolveWithParameters(search_parameters)\n",
"\n",
" # Print solution on console.\n",
" if solution:\n",
" print_solution(manager, routing, solution)\n",
" else:\n",
" print('No solution found!')\n",
"\n",
"\n",
"main()\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -146,6 +146,7 @@
" print(f\"Maximum of the route distances: {max_route_distance}m\")\n",
"\n",
"\n",
"\n",
"def main():\n",
" \"\"\"Solve the CVRP problem.\"\"\"\n",
" # Instantiate the data problem.\n",

View File

@@ -149,6 +149,7 @@
" print(f\"Total Distance of all routes: {total_distance}m\")\n",
"\n",
"\n",
"\n",
"class SolutionCallback:\n",
" \"\"\"Create a solution callback.\"\"\"\n",
"\n",
@@ -174,6 +175,7 @@
" self._routing_model.solver().FinishCurrentSearch()\n",
"\n",
"\n",
"\n",
"def main():\n",
" \"\"\"Entry point of the program.\"\"\"\n",
" # Instantiate the data problem.\n",

View File

@@ -1,247 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2023 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# vrpgs"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/vrpgs.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/vrpgs.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"%pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"\n",
"Simple Vehicle Routing Problem (VRP).\n",
"\n",
"This is a sample using the routing library Python wrapper to solve a VRP\n",
"instance.\n",
"A description of the problem can be found here:\n",
"http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
"\n",
"Distances are in meters.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"import functools\n",
"from ortools.constraint_solver import routing_enums_pb2\n",
"from ortools.constraint_solver import pywrapcp\n",
"\n",
"\n",
"def create_data_model():\n",
" \"\"\"Stores the data for the problem.\"\"\"\n",
" data = {}\n",
" # Locations in block unit\n",
" locations_ = [\n",
" # fmt: off\n",
" (4, 4), # depot\n",
" (2, 0), (8, 0), # locations to visit\n",
" (0, 1), (1, 1),\n",
" (5, 2), (7, 2),\n",
" (3, 3), (6, 3),\n",
" (5, 5), (8, 5),\n",
" (1, 6), (2, 6),\n",
" (3, 7), (6, 7),\n",
" (0, 8), (7, 8),\n",
" # fmt: on\n",
" ]\n",
" # Compute locations in meters using the block dimension defined as follow\n",
" # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
" # here we use: 114m x 80m city block\n",
" # src: https://nyti.ms/2GDoRIe 'NY Times: Know Your distance'\n",
" data[\"locations\"] = [(l[0] * 114, l[1] * 80) for l in locations_]\n",
" data[\"num_locations\"] = len(data[\"locations\"])\n",
" data[\"num_vehicles\"] = 4\n",
" data[\"depot\"] = 0\n",
" return data\n",
"\n",
"\n",
"\n",
"def print_solution(data, manager, routing, assignment):\n",
" \"\"\"Prints solution on console.\"\"\"\n",
" print(f\"Objective: {assignment.ObjectiveValue()}\")\n",
" total_distance = 0\n",
" for vehicle_id in range(data[\"num_vehicles\"]):\n",
" index = routing.Start(vehicle_id)\n",
" plan_output = f\"Route for vehicle {vehicle_id}:\\n\"\n",
" route_distance = 0\n",
" while not routing.IsEnd(index):\n",
" plan_output += f\" {manager.IndexToNode(index)} ->\"\n",
" previous_index = index\n",
" index = assignment.Value(routing.NextVar(index))\n",
" route_distance += routing.GetArcCostForVehicle(\n",
" previous_index, index, vehicle_id\n",
" )\n",
" plan_output += f\" {manager.IndexToNode(index)}\\n\"\n",
" plan_output += f\"Distance of the route: {route_distance}m\\n\"\n",
" print(plan_output)\n",
" total_distance += route_distance\n",
" print(f\"Total Distance of all routes: {total_distance}m\")\n",
"\n",
"\n",
"\n",
"#######################\n",
"# Problem Constraints #\n",
"#######################\n",
"def manhattan_distance(position_1, position_2):\n",
" \"\"\"Computes the Manhattan distance between two points.\"\"\"\n",
" return abs(position_1[0] - position_2[0]) + abs(position_1[1] - position_2[1])\n",
"\n",
"\n",
"def create_distance_evaluator(data):\n",
" \"\"\"Creates callback to return distance between points.\"\"\"\n",
" distances_ = {}\n",
" # precompute distance between location to have distance callback in O(1)\n",
" for from_node in range(data[\"num_locations\"]):\n",
" distances_[from_node] = {}\n",
" for to_node in range(data[\"num_locations\"]):\n",
" if from_node == to_node:\n",
" distances_[from_node][to_node] = 0\n",
" else:\n",
" distances_[from_node][to_node] = manhattan_distance(\n",
" data[\"locations\"][from_node], data[\"locations\"][to_node]\n",
" )\n",
"\n",
" def distance_evaluator(manager, from_index, to_index):\n",
" \"\"\"Returns the manhattan distance between the two nodes.\"\"\"\n",
" # Convert from routing variable Index to distance matrix NodeIndex.\n",
" from_node = manager.IndexToNode(from_index)\n",
" to_node = manager.IndexToNode(to_index)\n",
" return distances_[from_node][to_node]\n",
"\n",
" return distance_evaluator\n",
"\n",
"\n",
"def add_distance_dimension(routing, distance_evaluator_index):\n",
" \"\"\"Add Global Span constraint.\"\"\"\n",
" distance = \"Distance\"\n",
" routing.AddDimension(\n",
" distance_evaluator_index,\n",
" 0, # null slack\n",
" 3000, # maximum distance per vehicle\n",
" True, # start cumul to zero\n",
" distance,\n",
" )\n",
" distance_dimension = routing.GetDimensionOrDie(distance)\n",
" # Try to minimize the max distance among vehicles.\n",
" # /!\\ It doesn't mean the standard deviation is minimized\n",
" distance_dimension.SetGlobalSpanCostCoefficient(100)\n",
"\n",
"\n",
"def main():\n",
" \"\"\"Entry point of the program.\"\"\"\n",
" # Instantiate the data problem.\n",
" data = create_data_model()\n",
"\n",
" # Create the routing index manager.\n",
" manager = pywrapcp.RoutingIndexManager(\n",
" data[\"num_locations\"], data[\"num_vehicles\"], data[\"depot\"]\n",
" )\n",
"\n",
" # Create Routing Model.\n",
" routing = pywrapcp.RoutingModel(manager)\n",
"\n",
" # Define weight of each edge\n",
" distance_evaluator_index = routing.RegisterTransitCallback(\n",
" functools.partial(create_distance_evaluator(data), manager)\n",
" )\n",
"\n",
" # Define cost of each arc.\n",
" routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\n",
"\n",
" # Add Distance constraint.\n",
" add_distance_dimension(routing, distance_evaluator_index)\n",
"\n",
" # Setting first solution heuristic.\n",
" search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
" search_parameters.first_solution_strategy = (\n",
" routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
" )\n",
"\n",
" # Solve the problem.\n",
" solution = routing.SolveWithParameters(search_parameters)\n",
"\n",
" # Print solution on console.\n",
" if solution:\n",
" print_solution(data, manager, routing, solution)\n",
" else:\n",
" print(\"No solution found !\")\n",
"\n",
"\n",
"main()\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -119,7 +119,7 @@
" data = pd.read_table(io.StringIO(data_str), sep=r\"\\s+\")\n",
"\n",
" # Create the model.\n",
" model = model_builder.ModelBuilder()\n",
" model = model_builder.Model()\n",
"\n",
" # Variables\n",
" # x[i, j] is an array of 0-1 variables, which will be 1\n",
@@ -139,7 +139,9 @@
" model.minimize(data.cost.dot(x))\n",
"\n",
" # Create the solver with the CP-SAT backend, and solve the model.\n",
" solver = model_builder.ModelSolver(\"sat\")\n",
" solver = model_builder.Solver(\"sat\")\n",
" if not solver.solver_is_supported():\n",
" return\n",
" status = solver.solve(model)\n",
"\n",
" # Print solution.\n",

View File

@@ -128,7 +128,7 @@
" items, bins = create_data_model()\n",
"\n",
" # Create the model.\n",
" model = model_builder.ModelBuilder()\n",
" model = model_builder.Model()\n",
"\n",
" # Variables\n",
" # x[i, j] = 1 if item i is packed in bin j.\n",
@@ -157,7 +157,9 @@
" model.minimize(y.sum())\n",
"\n",
" # Create the solver with the CP-SAT backend, and solve the model.\n",
" solver = model_builder.ModelSolver(\"sat\")\n",
" solver = model_builder.Solver(\"sat\")\n",
" if not solver.solver_is_supported():\n",
" return\n",
" status = solver.solve(model)\n",
"\n",
" if status == model_builder.SolveStatus.OPTIMAL:\n",

View File

@@ -90,7 +90,7 @@
"\n",
"def main():\n",
" # Create the model.\n",
" model = model_builder.ModelBuilder()\n",
" model = model_builder.Model()\n",
"\n",
" # x and y are integer non-negative variables.\n",
" x = model.new_int_var(0.0, math.inf, \"x\")\n",
@@ -123,7 +123,9 @@
" c2_copy.add_term(z_copy, 2.0)\n",
"\n",
" # Create the solver with the SCIP backend, and solve the model.\n",
" solver = model_builder.ModelSolver(\"scip\")\n",
" solver = model_builder.Solver(\"scip\")\n",
" if not solver.solver_is_supported():\n",
" return\n",
" status = solver.solve(model_copy)\n",
"\n",
" if status == model_builder.SolveStatus.OPTIMAL:\n",

View File

@@ -90,7 +90,7 @@
"\n",
"def main():\n",
" # Create the model.\n",
" model = model_builder.ModelBuilder()\n",
" model = model_builder.Model()\n",
"\n",
" # Create the variables x and y.\n",
" x = model.new_num_var(0.0, math.inf, \"x\")\n",
@@ -110,7 +110,9 @@
" model.maximize(x + 10 * y)\n",
"\n",
" # Create the solver with the GLOP backend, and solve the model.\n",
" solver = model_builder.ModelSolver(\"glop\")\n",
" solver = model_builder.Solver(\"glop\")\n",
" if not solver.solver_is_supported():\n",
" return\n",
" status = solver.solve(model)\n",
"\n",
" if status == model_builder.SolveStatus.OPTIMAL:\n",

View File

@@ -90,7 +90,7 @@
"\n",
"def main():\n",
" # Create the model.\n",
" model = model_builder.ModelBuilder()\n",
" model = model_builder.Model()\n",
"\n",
" # x and y are integer non-negative variables.\n",
" x = model.new_int_var(0.0, math.inf, \"x\")\n",
@@ -110,7 +110,9 @@
" model.maximize(x + 10 * y)\n",
"\n",
" # Create the solver with the SCIP backend, and solve the model.\n",
" solver = model_builder.ModelSolver(\"scip\")\n",
" solver = model_builder.Solver(\"scip\")\n",
" if not solver.solver_is_supported():\n",
" return\n",
" status = solver.solve(model)\n",
"\n",
" if status == model_builder.SolveStatus.OPTIMAL:\n",