routing: Remove format() in python samples

This commit is contained in:
Corentin Le Molgat
2023-04-13 11:49:14 +02:00
parent 19baa38270
commit a26be5b7bc
22 changed files with 251 additions and 237 deletions

View File

@@ -23,7 +23,6 @@
Distances are in meters.
"""
from functools import partial
from ortools.constraint_solver import pywrapcp
@@ -74,8 +73,8 @@ def create_data_model():
#######################
def manhattan_distance(position_1, position_2):
"""Computes the Manhattan distance between two points"""
return (
abs(position_1[0] - position_2[0]) + abs(position_1[1] - position_2[1]))
return (abs(position_1[0] - position_2[0]) +
abs(position_1[1] - position_2[1]))
def create_distance_evaluator(data):
@@ -126,33 +125,31 @@ def add_capacity_constraints(routing, data, demand_evaluator_index):
###########
def print_solution(data, routing, manager, assignment): # pylint:disable=too-many-locals
"""Prints assignment on console"""
print('Objective: {}'.format(assignment.ObjectiveValue()))
print(f'Objective: {assignment.ObjectiveValue()}')
total_distance = 0
total_load = 0
capacity_dimension = routing.GetDimensionOrDie('Capacity')
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
distance = 0
while not routing.IsEnd(index):
load_var = capacity_dimension.CumulVar(index)
plan_output += ' {} Load({}) -> '.format(
manager.IndexToNode(index), assignment.Value(load_var))
plan_output += (f' {manager.IndexToNode(index)} '
f'Load({assignment.Value(load_var)}) -> ')
previous_index = index
index = assignment.Value(routing.NextVar(index))
distance += routing.GetArcCostForVehicle(previous_index, index,
vehicle_id)
load_var = capacity_dimension.CumulVar(index)
plan_output += ' {0} Load({1})\n'.format(
manager.IndexToNode(index), assignment.Value(load_var))
plan_output += 'Distance of the route: {}m\n'.format(distance)
plan_output += 'Load of the route: {}\n'.format(
assignment.Value(load_var))
plan_output += f' {manager.IndexToNode(index)} Load({assignment.Value(load_var)})\n'
plan_output += f'Distance of the route: {distance}m\n'
plan_output += f'Load of the route: {assignment.Value(load_var)}\n'
print(plan_output)
total_distance += distance
total_load += assignment.Value(load_var)
print('Total Distance of all routes: {}m'.format(total_distance))
print('Total Load of all routes: {}'.format(total_load))
print(f'Total Distance of all routes: {total_distance}m')
print(f'Total Load of all routes: {total_load}')
########

View File

@@ -42,7 +42,6 @@
into account in `create_distance_evaluator()`.
"""
from functools import partial
from ortools.constraint_solver import pywrapcp
@@ -163,6 +162,7 @@ def create_distance_evaluator(data):
def add_distance_dimension(routing, manager, data, distance_evaluator_index):
"""Add Global Span constraint"""
del manager
distance = 'Distance'
routing.AddDimension(
distance_evaluator_index,
@@ -227,7 +227,8 @@ def create_time_evaluator(data):
travel_time = 0
else:
travel_time = manhattan_distance(
data['locations'][from_node], data['locations'][to_node]) / data['vehicle_speed']
data['locations'][from_node],
data['locations'][to_node]) / data['vehicle_speed']
return travel_time
_total_time = {}
@@ -239,8 +240,8 @@ def create_time_evaluator(data):
_total_time[from_node][to_node] = 0
else:
_total_time[from_node][to_node] = int(
service_time(data, from_node) + travel_time(
data, from_node, to_node))
service_time(data, from_node) +
travel_time(data, from_node, to_node))
def time_evaluator(manager, from_node, to_node):
"""Returns the total time between the two nodes"""
@@ -310,20 +311,21 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
while not routing.IsEnd(index):
load_var = capacity_dimension.CumulVar(index)
time_var = time_dimension.CumulVar(index)
plan_output += ' {0} Load({1}) Time({2},{3}) ->'.format(
manager.IndexToNode(index),
assignment.Value(load_var),
assignment.Min(time_var), assignment.Max(time_var))
plan_output += (
f' {manager.IndexToNode(index)} '
f'Load({assignment.Value(load_var)}) '
f'Time({assignment.Min(time_var)},{assignment.Max(time_var)}) ->'
)
previous_index = index
index = assignment.Value(routing.NextVar(index))
distance += routing.GetArcCostForVehicle(previous_index, index,
vehicle_id)
load_var = capacity_dimension.CumulVar(index)
time_var = time_dimension.CumulVar(index)
plan_output += ' {0} Load({1}) Time({2},{3})\n'.format(
manager.IndexToNode(index),
assignment.Value(load_var),
assignment.Min(time_var), assignment.Max(time_var))
plan_output += (
f' {manager.IndexToNode(index)} '
f'Load({assignment.Value(load_var)}) '
f'Time({assignment.Min(time_var)},{assignment.Max(time_var)})\n')
plan_output += f'Distance of the route: {distance}m\n'
plan_output += f'Load of the route: {assignment.Value(load_var)}\n'
plan_output += f'Time of the route: {assignment.Value(time_var)}min\n'
@@ -331,9 +333,9 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
total_distance += distance
total_load += assignment.Value(load_var)
total_time += assignment.Value(time_var)
print('Total Distance of all routes: {}m'.format(total_distance))
print('Total Load of all routes: {}'.format(total_load))
print('Total Time of all routes: {}min'.format(total_time))
print(f'Total Distance of all routes: {total_distance}m')
print(f'Total Load of all routes: {total_load}')
print(f'Total Time of all routes: {total_time}min')
########

View File

@@ -86,8 +86,8 @@ def create_data_model():
#######################
def manhattan_distance(position_1, position_2):
"""Computes the Manhattan distance between two points"""
return (
abs(position_1[0] - position_2[0]) + abs(position_1[1] - position_2[1]))
return (abs(position_1[0] - position_2[0]) +
abs(position_1[1] - position_2[1]))
def create_distance_evaluator(data):
@@ -145,8 +145,9 @@ def create_time_evaluator(data):
if from_node == to_node:
travel_time = 0
else:
travel_time = manhattan_distance(data['locations'][from_node], data[
'locations'][to_node]) / data['vehicle_speed']
travel_time = manhattan_distance(
data['locations'][from_node],
data['locations'][to_node]) / data['vehicle_speed']
return travel_time
_total_time = {}
@@ -158,8 +159,8 @@ def create_time_evaluator(data):
_total_time[from_node][to_node] = 0
else:
_total_time[from_node][to_node] = int(
service_time(data, from_node) + travel_time(
data, from_node, to_node))
service_time(data, from_node) +
travel_time(data, from_node, to_node))
def time_evaluator(manager, from_node, to_node):
"""Returns the total time between the two nodes"""
@@ -210,18 +211,18 @@ def print_solution(manager, routing, assignment): # pylint:disable=too-many-loc
total_time = 0
for vehicle_id in range(manager.GetNumberOfVehicles()):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
distance = 0
while not routing.IsEnd(index):
load_var = capacity_dimension.CumulVar(index)
time_var = time_dimension.CumulVar(index)
slack_var = time_dimension.SlackVar(index)
plan_output += ' {0} Load({1}) Time({2},{3}) Slack({4},{5}) ->'.format(
manager.IndexToNode(index),
assignment.Value(load_var),
assignment.Min(time_var),
assignment.Max(time_var),
assignment.Min(slack_var), assignment.Max(slack_var))
plan_output += (
f' {manager.IndexToNode(index)} '
f'Load({assignment.Value(load_var)}) '
f'Time({assignment.Min(time_var)},{assignment.Max(time_var)}) '
f'Slack({assignment.Min(slack_var)},{assignment.Max(slack_var)}) ->'
)
previous_index = index
index = assignment.Value(routing.NextVar(index))
distance += routing.GetArcCostForVehicle(previous_index, index,
@@ -229,22 +230,20 @@ def print_solution(manager, routing, assignment): # pylint:disable=too-many-loc
load_var = capacity_dimension.CumulVar(index)
time_var = time_dimension.CumulVar(index)
slack_var = time_dimension.SlackVar(index)
plan_output += ' {0} Load({1}) Time({2},{3})\n'.format(
manager.IndexToNode(index),
assignment.Value(load_var),
assignment.Min(time_var), assignment.Max(time_var))
plan_output += 'Distance of the route: {0}m\n'.format(distance)
plan_output += 'Load of the route: {}\n'.format(
assignment.Value(load_var))
plan_output += 'Time of the route: {}\n'.format(
assignment.Value(time_var))
plan_output += (
f' {manager.IndexToNode(index)} '
f'Load({assignment.Value(load_var)}) '
f'Time({assignment.Min(time_var)},{assignment.Max(time_var)})\n')
plan_output += f'Distance of the route: {distance}m\n'
plan_output += f'Load of the route: {assignment.Value(load_var)}\n'
plan_output += f'Time of the route: {assignment.Value(time_var)}\n'
print(plan_output)
total_distance += distance
total_load += assignment.Value(load_var)
total_time += assignment.Value(time_var)
print('Total Distance of all routes: {0}m'.format(total_distance))
print('Total Load of all routes: {}'.format(total_load))
print('Total Time of all routes: {0}min'.format(total_time))
print(f'Total Distance of all routes: {total_distance}m')
print(f'Total Load of all routes: {total_load}')
print(f'Total Time of all routes: {total_time}min')
# [END solution_printer]

View File

@@ -109,10 +109,8 @@ def main():
# Create the routing index manager.
# [START index_manager]
manager = pywrapcp.RoutingIndexManager(
len(data['time_matrix']),
data['num_vehicles'],
data['depot'])
manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']),
data['num_vehicles'], data['depot'])
# [END index_manager]
# Create Routing Model.
@@ -165,13 +163,15 @@ def main():
# Add a break lasting 5 minutes, start between 25 and 45 minutes after route start
for v in range(manager.GetNumberOfVehicles()):
start_var = time_dimension.CumulVar(routing.Start(v))
break_start = routing.solver().Sum([routing.solver().IntVar(25, 45), start_var])
break_start = routing.solver().Sum(
[routing.solver().IntVar(25, 45), start_var])
break_intervals = [
routing.solver().FixedDurationIntervalVar(
break_start, 5, 'Break for vehicle {}'.format(v))
routing.solver().FixedDurationIntervalVar(break_start, 5,
f'Break for vehicle {v}')
]
time_dimension.SetBreakIntervalsOfVehicle(break_intervals, v, node_visit_transit)
time_dimension.SetBreakIntervalsOfVehicle(break_intervals, v,
node_visit_transit)
# [END break_constraint]
# Setting first solution heuristic.

View File

@@ -113,26 +113,25 @@ def print_solution(data, manager, routing, solution):
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
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)
plan_output += f' {node_index} Load({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)
plan_output += f' {manager.IndexToNode(index)} Load({route_load})\n'
plan_output += f'Distance of the route: {route_distance}m\n'
plan_output += f'Load of the route: {route_load}\n'
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))
print(f'Total distance of all routes: {total_distance}m')
print(f'Total load of all routes: {total_load}')
# [END solution_printer]

View File

@@ -115,33 +115,32 @@ def print_solution(data, manager, routing, assignment):
if routing.IsStart(node) or routing.IsEnd(node):
continue
if assignment.Value(routing.NextVar(node)) == node:
dropped_nodes += ' {}'.format(manager.IndexToNode(node))
dropped_nodes += f' {manager.IndexToNode(node)}'
print(dropped_nodes)
# Display routes
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
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)
plan_output += f' {node_index} Load({route_load}) -> '
previous_index = index
index = assignment.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)
plan_output += f' {manager.IndexToNode(index)} Load({route_load})\n'
plan_output += f'Distance of the route: {route_distance}m\n'
plan_output += f'Load of the route: {route_load}\n'
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))
print(f'Total Distance of all routes: {total_distance}m')
print(f'Total Load of all routes: {total_load}')
# [END solution_printer]

View File

@@ -116,19 +116,19 @@ def print_solution(data, manager, routing, solution):
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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 += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
print(f'Maximum of the route distances: {max_route_distance}m')
# [END solution_printer]

View File

@@ -116,19 +116,19 @@ def print_solution(data, manager, routing, solution):
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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 += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
print(f'Maximum of the route distances: {max_route_distance}m')
# [END solution_printer]

View File

@@ -35,42 +35,42 @@ def create_data_model():
# [START demands_capacities]
# Need 11 X and 13 Y
data['providers_x'] = [
0, # start
-11, # end
2, # X supply 1
2, # X supply 2
4, # X supply 3
4, # X supply 4
4, # X supply 5
5, # X supply 6
1, # X/Y supply 1
2, # X/Y supply 2
2, # X/Y supply 3
0, # Y supply 1
0, # Y supply 2
0, # Y supply 3
0, # Y supply 4
0, # Y supply 5
0, # Y supply 6
0, # start
-11, # end
2, # X supply 1
2, # X supply 2
4, # X supply 3
4, # X supply 4
4, # X supply 5
5, # X supply 6
1, # X/Y supply 1
2, # X/Y supply 2
2, # X/Y supply 3
0, # Y supply 1
0, # Y supply 2
0, # Y supply 3
0, # Y supply 4
0, # Y supply 5
0, # Y supply 6
]
data['providers_y'] = [
0, # start
-13, # ends
0, # X supply 1
0, # X supply 2
0, # X supply 3
0, # X supply 4
0, # X supply 5
0, # X supply 6
3, # X/Y supply 1
2, # X/Y supply 2
1, # X/Y supply 3
3, # Y supply 1
3, # Y supply 2
3, # Y supply 3
3, # Y supply 4
3, # Y supply 5
5, # Y supply 6
0, # start
-13, # ends
0, # X supply 1
0, # X supply 2
0, # X supply 3
0, # X supply 4
0, # X supply 5
0, # X supply 6
3, # X/Y supply 1
2, # X/Y supply 2
1, # X/Y supply 3
3, # Y supply 1
3, # Y supply 2
3, # Y supply 3
3, # Y supply 4
3, # Y supply 5
5, # Y supply 6
]
data['vehicle_capacities_x'] = [15] * data['num_vehicles']
data['vehicle_capacities_y'] = [15] * data['num_vehicles']
@@ -83,28 +83,28 @@ def create_data_model():
468, 776, 662
],
[
548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480,
674, 1016, 868, 1210
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
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
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
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,
@@ -127,12 +127,12 @@ def create_data_model():
308, 650, 274, 844
],
[
388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0,
194, 536, 388, 730
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
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,
@@ -209,8 +209,8 @@ def main():
# Create the routing index manager.
# [START index_manager]
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
data['num_vehicles'],
data['starts'], data['ends'])
data['num_vehicles'], data['starts'],
data['ends'])
# [END index_manager]
# Create Routing Model.
@@ -248,6 +248,7 @@ def main():
distance_dimension = routing.GetDimensionOrDie(dimension_name)
# Minimize the longest road
distance_dimension.SetGlobalSpanCostCoefficient(100)
# [END distance_constraint]
# Add Capacity constraint.
@@ -258,7 +259,8 @@ def main():
from_node = manager.IndexToNode(from_index)
return data['providers_x'][from_node]
demand_callback_x_index = routing.RegisterUnaryTransitCallback(demand_callback_x)
demand_callback_x_index = routing.RegisterUnaryTransitCallback(
demand_callback_x)
routing.AddDimensionWithVehicleCapacity(
demand_callback_x_index,
0, # null capacity slack
@@ -272,7 +274,8 @@ def main():
from_node = manager.IndexToNode(from_index)
return data['providers_y'][from_node]
demand_callback_y_index = routing.RegisterUnaryTransitCallback(demand_callback_y)
demand_callback_y_index = routing.RegisterUnaryTransitCallback(
demand_callback_y)
routing.AddDimensionWithVehicleCapacity(
demand_callback_y_index,
0, # null capacity slack
@@ -290,8 +293,12 @@ def main():
ends.append(routing.End(v))
node_end = data['ends'][0]
solver.Add(solver.Sum([load_x_dim.CumulVar(l) for l in ends]) >= -data['providers_x'][node_end])
solver.Add(solver.Sum([load_y_dim.CumulVar(l) for l in ends]) >= -data['providers_y'][node_end])
solver.Add(
solver.Sum([load_x_dim.CumulVar(l)
for l in ends]) >= -data['providers_x'][node_end])
solver.Add(
solver.Sum([load_y_dim.CumulVar(l)
for l in ends]) >= -data['providers_y'][node_end])
#solver.Add(load_y_dim.CumulVar(end) >= -data['providers_y'][node_end])
# Allow to freely drop any nodes.

View File

@@ -136,30 +136,31 @@ def print_solution(data, manager, routing, solution):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
one_var = dim_one.CumulVar(index)
one_slack_var = dim_one.SlackVar(index)
two_var = dim_two.CumulVar(index)
two_slack_var = dim_two.SlackVar(index)
plan_output += ' N:{0} one:({1},{2}) two:({3},{4}) -> '.format(
manager.IndexToNode(index), solution.Value(one_var),
solution.Value(one_slack_var), solution.Value(two_var),
solution.Value(two_slack_var))
plan_output += (
f' N:{manager.IndexToNode(index)}'
f' one:({solution.Value(one_var)}, {solution.Value(one_slack_var)})'
f' two:({solution.Value(two_var)}, {solution.Value(two_slack_var)})'
' -> ')
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
one_var = dim_one.CumulVar(index)
two_var = dim_two.CumulVar(index)
plan_output += 'N:{0} one:{1} two:{2}\n'.format(
manager.IndexToNode(index), solution.Value(one_var),
solution.Value(two_var))
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += (f'N:{manager.IndexToNode(index)}'
f' one:{solution.Value(one_var)}'
f' two:{solution.Value(two_var)}\n')
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
print(f'Maximum of the route distances: {max_route_distance}m')
# [END solution_printer]

View File

@@ -67,9 +67,13 @@ def main():
print(v_ends)
print('\nNodes:')
print('| locations | manager.GetNumberOfNodes | manager.GetNumberOfIndices | routing.nodes | routing.Size |')
print(
'| locations | manager.GetNumberOfNodes | manager.GetNumberOfIndices | routing.nodes | routing.Size |'
)
print('|---|---|---|---|---|')
print(f'| {locations} | {manager.GetNumberOfNodes()} | {manager.GetNumberOfIndices()} | {routing.nodes()} | {routing.Size()} |')
print(
f'| {locations} | {manager.GetNumberOfNodes()} | {manager.GetNumberOfIndices()} | {routing.nodes()} | {routing.Size()} |'
)
print('\nLocations:')
print('| node | index | routing.IsStart | routing.IsEnd |')
@@ -83,16 +87,22 @@ def main():
)
print('\nStart/End:')
print('| vehicle | Start/end | node | index | routing.IsStart | routing.IsEnd |')
print(
'| vehicle | Start/end | node | index | routing.IsStart | routing.IsEnd |'
)
print('|---|---|---|---|---|---|')
for v in range(manager.GetNumberOfVehicles()):
start_index = routing.Start(v)
start_node = manager.IndexToNode(start_index)
print(f'| {v} | start | {start_node} | {start_index} | {routing.IsStart(start_index)} | {routing.IsEnd(start_index)} |')
print(
f'| {v} | start | {start_node} | {start_index} | {routing.IsStart(start_index)} | {routing.IsEnd(start_index)} |'
)
for v in range(manager.GetNumberOfVehicles()):
end_index = routing.End(v)
end_node = manager.IndexToNode(end_index)
print(f'| {v} | end | {end_node} | {end_index} | {routing.IsStart(end_index)} | {routing.IsEnd(end_index)} |')
print(
f'| {v} | end | {end_node} | {end_index} | {routing.IsStart(end_index)} | {routing.IsEnd(end_index)} |'
)
if __name__ == '__main__':

View File

@@ -120,19 +120,19 @@ def print_solution(data, manager, routing, solution):
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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 += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
total_distance += route_distance
print('Total Distance of all routes: {}m'.format(total_distance))
print(f'Total Distance of all routes: {total_distance}m')
# [END solution_printer]

View File

@@ -120,19 +120,19 @@ def print_solution(data, manager, routing, assignment):
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
total_distance += route_distance
print('Total Distance of all routes: {}m'.format(total_distance))
print(f'Total Distance of all routes: {total_distance}m')
# [END solution_printer]

View File

@@ -120,19 +120,19 @@ def print_solution(data, manager, routing, assignment):
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
total_distance += route_distance
print('Total Distance of all routes: {}m'.format(total_distance))
print(f'Total Distance of all routes: {total_distance}m')
# [END solution_printer]

View File

@@ -82,22 +82,22 @@ def print_solution(data, manager, routing, solution):
total_time = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
while not routing.IsEnd(index):
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2}) -> '.format(
manager.IndexToNode(index), solution.Min(time_var),
solution.Max(time_var))
plan_output += (
f'{manager.IndexToNode(index)}'
f' Time({solution.Min(time_var)}, {solution.Max(time_var)})'
' -> ')
index = solution.Value(routing.NextVar(index))
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index),
solution.Min(time_var),
solution.Max(time_var))
plan_output += 'Time of the route: {}min\n'.format(
solution.Min(time_var))
plan_output += (
f'{manager.IndexToNode(index)}'
f' Time({solution.Min(time_var)},{solution.Max(time_var)})\n')
plan_output += f'Time of the route: {solution.Min(time_var)}min\n'
print(plan_output)
total_time += solution.Min(time_var)
print('Total time of all routes: {}min'.format(total_time))
print(f'Total time of all routes: {total_time}min')
# [END solution_printer]

View File

@@ -111,19 +111,19 @@ def print_solution(data, manager, routing, solution):
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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 += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
print(f'Maximum of the route distances: {max_route_distance}m')
# [END solution_printer]

View File

@@ -77,22 +77,22 @@ def print_solution(data, manager, routing, solution):
total_time = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
while not routing.IsEnd(index):
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2}) -> '.format(
manager.IndexToNode(index), solution.Min(time_var),
solution.Max(time_var))
plan_output += (
f'{manager.IndexToNode(index)}'
f' Time({solution.Min(time_var)},{solution.Max(time_var)})'
' -> ')
index = solution.Value(routing.NextVar(index))
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index),
solution.Min(time_var),
solution.Max(time_var))
plan_output += 'Time of the route: {}min\n'.format(
solution.Min(time_var))
plan_output += (
f'{manager.IndexToNode(index)}'
f' Time({solution.Min(time_var)},{solution.Max(time_var)})\n')
plan_output += f'Time of the route: {solution.Min(time_var)}min\n'
print(plan_output)
total_time += solution.Min(time_var)
print('Total time of all routes: {}min'.format(total_time))
print(f'Total time of all routes: {total_time}min')
# [END solution_printer]

View File

@@ -76,12 +76,12 @@ def print_solution(manager, routing, assignment):
if assignment.Value(routing.NextVar(index)) == index:
node = manager.IndexToNode(index)
if node > 16:
original = node
while original > 16:
original = original - 16
dropped_nodes += f' {node}({original})'
original = node
while original > 16:
original = original - 16
dropped_nodes += f' {node}({original})'
else:
dropped_nodes += f' {node}'
dropped_nodes += f' {node}'
print(dropped_nodes)
# Display routes
time_dimension = routing.GetDimensionOrDie('Time')
@@ -94,12 +94,12 @@ def print_solution(manager, routing, assignment):
time_var = time_dimension.CumulVar(index)
node = manager.IndexToNode(index)
if node > 16:
original = node
while original > 16:
original = original - 16
plan_output += f'{node}({original})'
original = node
while original > 16:
original = original - 16
plan_output += f'{node}({original})'
else:
plan_output += f'{node}'
plan_output += f'{node}'
plan_output += f' Time:{assignment.Value(time_var)} -> '
if start_time == 0:
start_time = assignment.Value(time_var)
@@ -126,9 +126,9 @@ def main():
# Create the routing index manager.
# [START index_manager]
manager = pywrapcp.RoutingIndexManager(
1 + 16*4, # number of locations
data['num_vehicles'],
data['depot'])
1 + 16 * 4, # number of locations
data['num_vehicles'],
data['depot'])
# [END index_manager]
# Create Routing Model.
@@ -147,9 +147,9 @@ def main():
# since our matrix is 17x17 map duplicated node to original one to
# retrieve the travel time
while from_node > 16:
from_node = from_node - 16;
from_node = from_node - 16
while to_node > 16:
to_node = to_node - 16;
to_node = to_node - 16
# add service of 25min for each location (except depot)
service_time = 0
if from_node != data['depot']:
@@ -184,35 +184,35 @@ def main():
routing.VehicleVar(index_0).SetValues([-1, 0])
# Vehicle 1 location TW: [11am, 1pm]
index_1 = manager.NodeToIndex(location_idx+16*1)
index_1 = manager.NodeToIndex(location_idx + 16 * 1)
time_dimension.CumulVar(index_1).SetRange(660, 780)
routing.VehicleVar(index_1).SetValues([-1, 1])
# Vehicle 2 location TW: [1pm, 3pm]
index_2 = manager.NodeToIndex(location_idx+16*2)
index_2 = manager.NodeToIndex(location_idx + 16 * 2)
time_dimension.CumulVar(index_2).SetRange(780, 900)
routing.VehicleVar(index_2).SetValues([-1, 2])
# Vehicle 3 location TW: [3pm, 5pm]
index_3 = manager.NodeToIndex(location_idx+16*3)
index_3 = manager.NodeToIndex(location_idx + 16 * 3)
time_dimension.CumulVar(index_3).SetRange(900, 1020)
routing.VehicleVar(index_3).SetValues([-1, 3])
# Add Disjunction so only one node among duplicate is visited
penalty = 100_000 # Give solver strong incentive to visit one node
penalty = 100_000 # Give solver strong incentive to visit one node
routing.AddDisjunction([index_0, index_1, index_2, index_3], penalty, 1)
# Add time window constraints for each vehicle start node.
depot_idx = data['depot']
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
time_dimension.CumulVar(index).SetRange(480, 1020) # (8am, 5pm)
time_dimension.CumulVar(index).SetRange(480, 1020) # (8am, 5pm)
# Add time window constraints for each vehicle end node.
depot_idx = data['depot']
for vehicle_id in range(data['num_vehicles']):
index = routing.End(vehicle_id)
time_dimension.CumulVar(index).SetRange(480, 1020) # (8am, 5pm)
time_dimension.CumulVar(index).SetRange(480, 1020) # (8am, 5pm)
# [END time_windows_constraint]
# Instantiate route start and end times to produce feasible times.

View File

@@ -79,8 +79,8 @@ def print_solution(manager, routing, solution):
plan_output += f'Distance of the route: {route_distance}m\n'
total_distance += route_distance
print(plan_output)
print('Total distance of all routes: {}m'.format(total_distance))
print('Total token of all routes: {}'.format(total_token))
print(f'Total distance of all routes: {total_distance}m')
print(f'Total token of all routes: {total_token}')
def main():

View File

@@ -28,19 +28,19 @@ def print_solution(manager, routing, solution):
max_route_distance = 0
for vehicle_id in range(manager.GetNumberOfVehicles()):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
plan_output += f' {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 += 'Distance of the route: {}m\n'.format(route_distance)
plan_output += f'{manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
print(f'Maximum of the route distances: {max_route_distance}m')
# [END solution_printer]

View File

@@ -14,14 +14,14 @@
# limitations under the License.
# [START program]
"""Simple Vehicles Routing Problem (VRP).
"""Simple Vehicle 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.
This is a sample using the routing library Python wrapper to solve a VRP
instance.
A description of the problem can be found here:
http://en.wikipedia.org/wiki/Vehicle_routing_problem.
Distances are in meters.
Distances are in meters.
"""
# [START import]
@@ -75,19 +75,19 @@ def print_solution(data, manager, routing, assignment):
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)
plan_output = f'Route for vehicle {vehicle_id}:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} ->'.format(manager.IndexToNode(index))
plan_output += f' {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)
plan_output += f' {manager.IndexToNode(index)}\n'
plan_output += f'Distance of the route: {route_distance}m\n'
print(plan_output)
total_distance += route_distance
print('Total Distance of all routes: {}m'.format(total_distance))
print(f'Total Distance of all routes: {total_distance}m')
# [END solution_printer]

View File

@@ -87,9 +87,9 @@ def print_solution(routes, cumul_data):
end_time = cumul_data[i][j][1]
route_str += ' -> ' + str(route[j]) + \
' Time(' + str(start_time) + ', ' + str(end_time) + ')'
route_str += '\n Route time: {} min\n\n'.format(start_time)
route_str += f'\n Route time: {start_time}min\n\n'
total_time += cumul_data[i][len(route) - 1][0]
route_str += 'Total time: {} min'.format(total_time)
route_str += f'Total time: {total_time}min'
print(route_str)
# [END solution_printer]