routing: cleanup samples
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2010-2021 Google LLC
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -11,11 +12,19 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# [START program]
|
||||
"""Simple Vehicles Routing Problem."""
|
||||
"""Simple Vehicles Routing Problem (VRP).
|
||||
|
||||
This is a sample using the routing library python wrapper to solve a VRP
|
||||
problem.
|
||||
A description of the problem can be found here:
|
||||
http://en.wikipedia.org/wiki/Vehicle_routing_problem.
|
||||
|
||||
Distances are in meters.
|
||||
"""
|
||||
|
||||
# [START import]
|
||||
from ortools.constraint_solver import routing_enums_pb2
|
||||
from ortools.constraint_solver import pywrapcp
|
||||
from ortools.constraint_solver import routing_enums_pb2
|
||||
# [END import]
|
||||
|
||||
|
||||
@@ -119,7 +128,7 @@ def print_solution(data, manager, routing, solution):
|
||||
print(plan_output)
|
||||
total_distance += route_distance
|
||||
print('Total Distance of all routes: {}m'.format(total_distance))
|
||||
# [END solution_printer]
|
||||
# [END solution_printer]
|
||||
|
||||
|
||||
def main():
|
||||
@@ -138,7 +147,6 @@ def main():
|
||||
# Create Routing Model.
|
||||
# [START routing_model]
|
||||
routing = pywrapcp.RoutingModel(manager)
|
||||
|
||||
# [END routing_model]
|
||||
|
||||
# Create and register a transit callback.
|
||||
@@ -174,9 +182,11 @@ def main():
|
||||
# [START print_solution]
|
||||
if solution:
|
||||
print_solution(data, manager, routing, solution)
|
||||
else:
|
||||
print("No solution found !")
|
||||
# [END print_solution]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
# [END program]
|
||||
# [END program]
|
||||
|
||||
@@ -12,11 +12,19 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# [START program]
|
||||
"""Vehicles Routing Problem (VRP)."""
|
||||
"""Simple Vehicles Routing Problem (VRP).
|
||||
|
||||
This is a sample using the routing library python wrapper to solve a VRP
|
||||
problem.
|
||||
A description of the problem can be found here:
|
||||
http://en.wikipedia.org/wiki/Vehicle_routing_problem.
|
||||
|
||||
Distances are in meters.
|
||||
"""
|
||||
|
||||
# [START import]
|
||||
from ortools.constraint_solver import routing_enums_pb2
|
||||
from ortools.constraint_solver import pywrapcp
|
||||
from ortools.constraint_solver import routing_enums_pb2
|
||||
# [END import]
|
||||
|
||||
|
||||
@@ -110,22 +118,21 @@ def print_solution(data, manager, routing, solution):
|
||||
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
|
||||
route_distance = 0
|
||||
while not routing.IsEnd(index):
|
||||
plan_output += ' {} -> '.format(manager.IndexToNode(index))
|
||||
plan_output += ' {} ->'.format(manager.IndexToNode(index))
|
||||
previous_index = index
|
||||
index = solution.Value(routing.NextVar(index))
|
||||
route_distance += routing.GetArcCostForVehicle(
|
||||
previous_index, index, vehicle_id)
|
||||
plan_output += '{}\n'.format(manager.IndexToNode(index))
|
||||
plan_output += ' {}\n'.format(manager.IndexToNode(index))
|
||||
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
|
||||
print(plan_output)
|
||||
max_route_distance = max(route_distance, max_route_distance)
|
||||
print('Maximum of the route distances: {}m'.format(max_route_distance))
|
||||
|
||||
# [END solution_printer]
|
||||
|
||||
|
||||
def main():
|
||||
"""Solve the CVRP problem."""
|
||||
"""Entry point of the program."""
|
||||
# Instantiate the data problem.
|
||||
# [START data]
|
||||
data = create_data_model()
|
||||
@@ -140,7 +147,6 @@ def main():
|
||||
# Create Routing Model.
|
||||
# [START routing_model]
|
||||
routing = pywrapcp.RoutingModel(manager)
|
||||
|
||||
# [END routing_model]
|
||||
|
||||
# Create and register a transit callback.
|
||||
@@ -189,6 +195,8 @@ def main():
|
||||
# [START print_solution]
|
||||
if solution:
|
||||
print_solution(data, manager, routing, solution)
|
||||
else:
|
||||
print("No solution found !")
|
||||
# [END print_solution]
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
# This Python file uses the following encoding: utf-8
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2010-2021 Google LLC
|
||||
# Copyright 2015 Tin Arm Engineering AB
|
||||
# Copyright 2018 Google LLC
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
@@ -13,7 +12,8 @@
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
"""Vehicle Routing Problem (VRP).
|
||||
# [START program]
|
||||
"""Simple Vehicles Routing Problem (VRP).
|
||||
|
||||
This is a sample using the routing library python wrapper to solve a VRP
|
||||
problem.
|
||||
@@ -23,18 +23,16 @@
|
||||
Distances are in meters.
|
||||
"""
|
||||
|
||||
|
||||
# [START import]
|
||||
from functools import partial
|
||||
|
||||
from ortools.constraint_solver import pywrapcp
|
||||
from ortools.constraint_solver import routing_enums_pb2
|
||||
# [END import]
|
||||
|
||||
|
||||
###########################
|
||||
# Problem Data Definition #
|
||||
###########################
|
||||
# [START data_model]
|
||||
def create_data_model():
|
||||
"""Stores the data for the problem"""
|
||||
"""Stores the data for the problem."""
|
||||
data = {}
|
||||
# Locations in block unit
|
||||
_locations = \
|
||||
@@ -56,6 +54,30 @@ def create_data_model():
|
||||
data['num_vehicles'] = 4
|
||||
data['depot'] = 0
|
||||
return data
|
||||
# [END data_model]
|
||||
|
||||
|
||||
# [START solution_printer]
|
||||
def print_solution(data, manager, routing, assignment):
|
||||
"""Prints solution on console."""
|
||||
print(f'Objective: {assignment.ObjectiveValue()}')
|
||||
total_distance = 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
|
||||
while not routing.IsEnd(index):
|
||||
plan_output += ' {} ->'.format(manager.IndexToNode(index))
|
||||
previous_index = index
|
||||
index = assignment.Value(routing.NextVar(index))
|
||||
route_distance += routing.GetArcCostForVehicle(
|
||||
previous_index, index, vehicle_id)
|
||||
plan_output += ' {}\n'.format(manager.IndexToNode(index))
|
||||
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
|
||||
print(plan_output)
|
||||
total_distance += route_distance
|
||||
print('Total Distance of all routes: {}m'.format(total_distance))
|
||||
# [END solution_printer]
|
||||
|
||||
|
||||
#######################
|
||||
@@ -80,10 +102,12 @@ def create_distance_evaluator(data):
|
||||
_distances[from_node][to_node] = (manhattan_distance(
|
||||
data['locations'][from_node], data['locations'][to_node]))
|
||||
|
||||
def distance_evaluator(manager, from_node, to_node):
|
||||
def distance_evaluator(manager, from_index, to_index):
|
||||
"""Returns the manhattan distance between the two nodes"""
|
||||
return _distances[manager.IndexToNode(from_node)][manager.IndexToNode(
|
||||
to_node)]
|
||||
# Convert from routing variable Index to distance matrix NodeIndex.
|
||||
from_node = manager.IndexToNode(from_index)
|
||||
to_node = manager.IndexToNode(to_index)
|
||||
return _distances[from_node][to_node]
|
||||
|
||||
return distance_evaluator
|
||||
|
||||
@@ -103,59 +127,61 @@ def add_distance_dimension(routing, distance_evaluator_index):
|
||||
distance_dimension.SetGlobalSpanCostCoefficient(100)
|
||||
|
||||
|
||||
###########
|
||||
# Printer #
|
||||
###########
|
||||
def print_solution(data, routing, manager, assignment): # pylint:disable=too-many-locals
|
||||
"""Prints assignment on console"""
|
||||
print(f'Objective: {assignment.ObjectiveValue()}')
|
||||
total_distance = 0
|
||||
for vehicle_id in range(data['num_vehicles']):
|
||||
index = routing.Start(vehicle_id)
|
||||
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
|
||||
distance = 0
|
||||
while not routing.IsEnd(index):
|
||||
plan_output += ' {} ->'.format(manager.IndexToNode(index))
|
||||
previous_index = index
|
||||
index = assignment.Value(routing.NextVar(index))
|
||||
distance += routing.GetArcCostForVehicle(previous_index, index,
|
||||
vehicle_id)
|
||||
plan_output += ' {}\n'.format(manager.IndexToNode(index))
|
||||
plan_output += 'Distance of the route: {}m\n'.format(distance)
|
||||
print(plan_output)
|
||||
total_distance += distance
|
||||
print('Total Distance of all routes: {}m'.format(total_distance))
|
||||
|
||||
|
||||
########
|
||||
# Main #
|
||||
########
|
||||
def main():
|
||||
"""Entry point of the program"""
|
||||
"""Entry point of the program."""
|
||||
# Instantiate the data problem.
|
||||
# [START data]
|
||||
data = create_data_model()
|
||||
# [END data]
|
||||
|
||||
# Create the routing index manager
|
||||
# Create the routing index manager.
|
||||
# [START index_manager]
|
||||
manager = pywrapcp.RoutingIndexManager(data['num_locations'],
|
||||
data['num_vehicles'], data['depot'])
|
||||
# [END index_manager]
|
||||
|
||||
# Create Routing Model
|
||||
# Create Routing Model.
|
||||
# [START routing_model]
|
||||
routing = pywrapcp.RoutingModel(manager)
|
||||
# [END routing_model]
|
||||
|
||||
# Define weight of each edge
|
||||
# [START transit_callback]
|
||||
distance_evaluator_index = routing.RegisterTransitCallback(
|
||||
partial(create_distance_evaluator(data), manager))
|
||||
routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)
|
||||
add_distance_dimension(routing, distance_evaluator_index)
|
||||
# [END transit_callback]
|
||||
|
||||
# Setting first solution heuristic (cheapest addition).
|
||||
# Define cost of each arc.
|
||||
# [START arc_cost]
|
||||
routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)
|
||||
# [END arc_cost]
|
||||
|
||||
# Add Distance constraint.
|
||||
# [START distance_constraint]
|
||||
add_distance_dimension(routing, distance_evaluator_index)
|
||||
# [END distance_constraint]
|
||||
|
||||
# Setting first solution heuristic.
|
||||
# [START parameters]
|
||||
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
|
||||
search_parameters.first_solution_strategy = (
|
||||
routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # pylint: disable=no-member
|
||||
routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
|
||||
# [END parameters]
|
||||
|
||||
# Solve the problem.
|
||||
assignment = routing.SolveWithParameters(search_parameters)
|
||||
print_solution(data, routing, manager, assignment)
|
||||
# [START solve]
|
||||
solution = routing.SolveWithParameters(search_parameters)
|
||||
# [END solve]
|
||||
|
||||
# Print solution on console.
|
||||
# [START print_solution]
|
||||
if solution:
|
||||
print_solution(data, manager, routing, solution)
|
||||
else:
|
||||
print("No solution found !")
|
||||
# [END print_solution]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
# [END program]
|
||||
|
||||
Reference in New Issue
Block a user