-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvrp.py
120 lines (93 loc) · 3.82 KB
/
vrp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""Vehicles Routing Problem (VRP)."""
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
import pdb
import os
import sys
#sys.path.append("../LP_projects")
import city_ops
import csv
def create_data_model(city_names):
data = {}
data['distance_matrix'] = city_ops.modify_data_for_google_or(city_names)
data['num_vehicles'] = 3
data['depot'] = 0
return data
def print_solution(data, manager, routing, solution, city_names):
"""Prints solution on console."""
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
path_list = []
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
city_names_dict = create_city_names_dict(city_names)
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(city_names_dict[manager.IndexToNode(index)])
path_list.append(city_names_dict[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(city_names_dict[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)
path_list.append(city_names_dict[manager.IndexToNode(index)])
print('Maximum of the route distances: {}m'.format(max_route_distance))
def create_city_names_dict(city_names):
di = {}
i = 0
for c in city_names:
di[i] = c
i += 1
return di
def read_cities_from_file(a_file):
cities_list = []
with open(a_file, 'r') as f:
for line in f:
curr_line = line.split(",")
cities_list.extend(curr_line)
return cities_list
def main():
"""Solve the CVRP problem."""
# Instantiate the data problem.
city_names = read_cities_from_file(sys.argv[1])
data = create_data_model(city_names)
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Create and register a transit callback.
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)
# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
30000, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if solution:
print_solution(data, manager, routing, solution, city_names)
if __name__ == '__main__':
main()