-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhrga.py
819 lines (566 loc) · 25.2 KB
/
hrga.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
import osmnx as ox
import geopandas as gpd
import itertools
import time
import random
from utils import *
def route_generation_algorithm(G, D, num_routes, minimum_nodes, maximum_nodes):
"""
Generates a set of routes for a transit network design optimization problem.
Args:
G - directed graph of road network.
D - demand matrix for all nodes.
num_routes - number of routes to be generated.
minimum_nodes - minimum number of nodes in any route.
maximum_nodes - maximum number of nodes in any route.
Returns: The best set of routes.
"""
# Initialize
current_best_solution_set = initialize_routes(G, D, num_routes, minimum_nodes, maximum_nodes)
# Calculate Score
current_score = evaluate_routes(current_best_solution_set)
# Local search
solution_set, score = local_search(current_best_solution_set)
return solution_set, score
def initialize_routes(G, D, num_routes, minimum_nodes, maximum_nodes, method='edges'):
"""
Generates a initial set of routes for the route generation algorithm.
Args:
G - directed graph of road network.
D - demand matrix for all nodes.
num_routes - number of routes to be generated.
minimum_nodes - minimum number of nodes in any route.
maximum_nodes - maximum number of nodes in any route.
Returns: A set of routes.
"""
# Initialize solution list
solution_list = []
# Compute shortest paths between all origin-destination pairs
shortest_paths = get_shortest_paths(G)
# Compute edge usage probability
G = get_edge_usage_statistics(get_edge_usage(G, D, shortest_paths))
# While number of routes hasn't been exceeded
print(f'Initializing Route Generation Algorithm...')
print('')
print(f'=======> Generating {num_routes} Routes...')
# Counter
i = 0
while i < num_routes:
# Initialize new route
new_route = []
# start generating new route by picking random edge
new_route.append(get_random_edge(G))
# pre determine number of nodes
node_number = random.randint(minimum_nodes, maximum_nodes)
# Add to count
i += 1
# Reset Counter
j = 0
# While number of nodes in line hasn't been exceeded
while j < node_number -1:
# Append or prepend edge based on graph topology and current route
new_route = extend_route(G, new_route)
# Find all shortest paths that contains at least one edge from the newly generated route
#updated_shortest_paths = update_shortest_path_list(shortest_paths, new_route)
# Calculate usage probabilities
#G = get_edge_usage_statistics(get_edge_usage(G, D, updated_shortest_paths))
# Add to count
j += 1
# Add route to solution list
solution_list.append(new_route)
# Check for completeness
complete, missing_node = check_all_nodes_covered(G, solution_list)
# If solution not complete, add route to make it complete and try again
if not complete:
print(f'Solution is not complete: missing node {missing_node}')
# Check for connectedness
connected = True
# If routes unconnected
if not connected:
print(f'Solution is not fully connected: route {"a"} does not share any node with any other route')
# Convert to Node Routes
node_routes = []
unduplicated = []
for route in solution_list:
node_routes.append(path_edges_to_nodes(route))
# Check for duplicates
# Iterate over all routes in reversed order
for route in node_routes:
# If the reversed route (C, B, A) exists in the list
# Or if route (A, B, C) exists in the list
if (list(reversed(route)) not in unduplicated) and (route not in unduplicated):
# Remove it from the list
unduplicated.append(route)
# Convert back to Edge Routes
initialization = []
for route in unduplicated:
initialization.append(path_nodes_to_edges(route))
initialization.sort()
if method == 'nodes':
unduplicated.sort()
print(f'=======> {len(unduplicated)} of {num_routes} routes generated successfully!')
print(f'=======> A total of {num_routes - len(unduplicated)} routes were duplicated and removed')
print('')
for i, route in enumerate(unduplicated):
print(f'Route {i+1}: {route}')
return unduplicated
else:
print(f'=======> {len(initialization)} of {num_routes} routes generated successfully!')
print(f'=======> A total of {num_routes - len(initialization)} routes were duplicated and removed')
print('')
for i, route in enumerate(initialization):
print(f'Route {i+1}: {route}')
return initialization
def evaluate_routes(G, solution_set, demand_matrix, alpha=1, beta=5):
"""
Calculates score of solution given
Args:
G - graph of the network.
solution_set - current solution list of routes.
demand_matrix - demand matrix.
alpha - weight of distance minimization
beta - weight of transfer minimization
Returns: score
"""
# Initialize variables
route_cost = 0
transfer_cost = 0
# Convert routes to node sequence
converted_routes = []
for route in solution_set:
converted_routes.append(path_edges_to_nodes(route))
# Generate extended graph
eG = create_extended_graph(G, converted_routes, solution_set, transfer_weight=0)
for origin in list(G.nodes()):
for destination in list(G.nodes()):
if demand_matrix[origin-1][destination-1] != 0:
st_time = time.time()
# Calculate Shortest Path
shortest_path = nx.shortest_path(eG, origin, destination, weight='length')
shortest_path_length = nx.shortest_path_length(eG, origin, destination, weight='length')
# Add to costs
route_cost += demand_matrix[origin-1][destination-1] * shortest_path_length
transfer_cost += demand_matrix[origin-1][destination-1] * calculate_transfers(shortest_path)
#print(f'Node {origin} to {destination} evaluation complete. Took {(time.time() - st_time):.4f} seconds.')
# Objective function
score = (alpha * route_cost) + (beta * transfer_cost)
return score, (route_cost, transfer_cost)
def hill_climbing(G, D, current_solution, num_routes, minimum_nodes, maximum_nodes, iterations=100000):
"""
Local search algorithm to improve routes.
Args:
G - directed graph of road network.
D - demand matrix for all nodes.
num_routes - number of routes to be generated.
minimum_nodes - minimum number of nodes in any route.
maximum_nodes - maximum number of nodes in any route.
Returns: An improved set of routes.
"""
# Initialize score
solution_set_score = np.inf
# Run 100k iterations
for i in range(iterations):
# Get current score of solutions
current_score, _ = evaluate_routes(G, current_solution, D)
# If current solution has a lower score than the best solution
if solution_set_score > current_score:
# Current solution is best solution
solution_set = current_solution
# Current solution score is best solution score
solution_set_score = current_score
# Otherwise
else:
# Best solution replaces current solution
current_solution = solution_set
# Apply modification
current_solution = modify_solution(G, solution_set)
print(f'Iteration {i+1}/{iterations}: Score: {solution_set_score} | Route Count: {len(current_solution)}')
return solution_set
def tabu_search(G, D, num_routes, minimum_nodes, maximum_nodes, current_solution, max_tabu_size):
"""
Tabu search algorithm to improve routes.
Args:
G - directed graph of road network.
D - demand matrix for all nodes.
num_routes - number of routes to be generated.
minimum_nodes - minimum number of nodes in any route.
maximum_nodes - maximum number of nodes in any route.
max_tabu_size - maximum size of tabu list
Returns: An improved set of routes.
"""
# Calculate solution score
solution_score = evaluate_routes(current_solution)
# Generate Tabu List
tabu_list = []
# Iterate 5000 times
for i in range(5000):
# Generate candidate list
candidate_list = []
# Get 20 new candidates
while len(candidate_list) < 20:
# Modify solution
new_solution_set = modify_solution(current_solution)
# If new solution is not on tabu list and is connected
if (new_solution_set not in tabu_list) and (is_connected(new_solution_set)):
# Add to tabu list
candidate_list.append(new_solution_set)
# get best candidate from candidate list
best_candidate = get_best_candidate(candidate_list)
# get score
new_score = evaluate_routes(best_candidate)
# decision criteria
if new_score < current_score:
# current solution is replaced by new solution
current_solution = best_candidate
# score is replaced
solution_score = new_score
# tabu list is modified
tabu_list = difference(current_solution, tabu_list)
# tabu list expire
tabu_list = expire(tabu_list, max_tabu_size)
return current_solution
def get_edge_usage(graph, demand_matrix, shortest_paths):
"""
Calculates usage for each edge (in absolute values) of the graph.
The algorithm considers that all users choose the shortest paths
between their origin and destination.
Args:
graph - directed graph of road network.
D - demand matrix for all nodes.
shortest_paths - shortest_path ditctionary for all O-D pairs
Returns: Edge usage for all edges.
"""
# Initialize edge usage
for edge in list(graph.edges()):
nx.set_edge_attributes(graph, {edge : { "usage" : 0 }})
for origin in list(graph.nodes()):
for destination in list(graph.nodes()):
if origin != destination:
# Get shortest path sequence
shortest_path = shortest_paths[f'{origin}-{destination}']
# Iterate
for i in range(len(shortest_path) - 1):
# Simplify names
u = shortest_path[i]
v = shortest_path[i+1]
# Variables
current_edge = (u, v)
current_usage = graph[u][v]['usage']
demand = demand_matrix[origin-1][destination-1]
# Set usage as current usage + demand from origin to destination
nx.set_edge_attributes(graph, {current_edge : { "usage" : current_usage + demand }})
return graph
def get_edge_usage_statistics(graph):
"""
Calculates edge usage statistics for each edge of the graph.
The usage statistic is calculated by taking absolute edge usage,
dividing by its weight (distance or travel time) and normalizing
values between 0 and 1.
Args:
G - directed graph of road network with 'length' and 'usage'
attributes
Returns: Edge usage statistics for all edges.
"""
# Initialize edge usage statistics
for edge in list(graph.edges):
nx.set_edge_attributes(graph, {edge : { "usage_stat" : 0 }})
# Get edges
edges = [(u, v) for u, v in graph.edges()]
# Get usage and weights
edge_usage = np.array([graph[u][v]['usage'] for u, v in graph.edges()], dtype=object)
weights = np.array([graph[u][v]['length'] for u, v in graph.edges()], dtype=object)
# Divide edge_usage by weight
edge_usage_stat = edge_usage / weights
# Normalize values
norm_edge_usage_stat = edge_usage_stat / edge_usage_stat.sum()
# Add values to graph
for i, edge in enumerate(edges):
nx.set_edge_attributes(graph, {edge : { "usage_stat" : norm_edge_usage_stat[i] }})
return graph
def get_random_edge(G):
"""
Chooses random edge based on edge usage statistics.
Args:
G - directed graph of road network with usage_stat attribute
Returns: A random edge.
"""
# List of edges and usage statistics
edges = [(u, v) for u, v in G.edges()]
usage_stat = [G[u][v]['usage_stat'] for u, v in G.edges()]
# Select random edge based on statistics
return random.choices(edges, weights=usage_stat)[0]
def extend_route(G, route):
"""
Prepends or appends edge to current route.
Args:
G - directed graph of road network with usage_stat attribute
route - list containing tuples of edges in the graph.
Returns: An extended route.
"""
# Get vars
first_node = route[0][0]
last_node = route[-1][1]
# Candidate edges
prepend_candidates = list(G.edges(first_node))
append_candidates = list(G.edges(last_node))
# Remove first and last edge from candidates
try:
prepend_candidates.remove(route[0])
except:
prepend_candidates.remove(route[0][::-1])
try:
append_candidates.remove(route[-1])
except:
append_candidates.remove(route[-1][::-1])
# Convert Route to Nodes
route_nodes = path_edges_to_nodes(route)
# Remove edges already used
for edge in prepend_candidates:
# If destination node already exists in route,
# remove from candidates to avoid cycle
if (edge in route) or (edge[1] in route_nodes):
prepend_candidates.remove(edge)
elif edge[::-1] in route:
prepend_candidates.remove(edge)
for edge in append_candidates:
# If destination node already exists in route,
# remove from candidates to avoid cycle
if (edge in route) or (edge[1] in route_nodes):
append_candidates.remove(edge)
elif edge[::-1] in route:
append_candidates.remove(edge)
# Get length of arrays
prep_count = len(prepend_candidates)
app_count = len(append_candidates)
# If no candidates, exit early
if (prep_count == 0) and (app_count == 0):
return route
# Get usage probabilities
prepend_probabilities = [G[u][v]['usage_stat'] for u, v in prepend_candidates]
append_probabilities = [G[u][v]['usage_stat'] for u, v in append_candidates]
# Decision list
candidates = prepend_candidates + append_candidates
probabilites = prepend_probabilities + append_probabilities
# Select random edge based on statistics
selected_edge = random.choices(candidates, weights=probabilites)
selected_edge = selected_edge[0]
# If selected edge in append list, append. Else, prepend
if selected_edge in append_candidates:
route.append(selected_edge)
else:
route.insert(0, selected_edge[::-1])
return route
def update_shortest_path_list(shortest_paths, new_route):
"""
Updates shortest paths list based on new route. Only
shortest paths containing one or more edges from the route
remain on the list.
Args:
shortest_paths - dictionary of shortest paths for all od pairs
new_route - route in current construction
Returns: An updated shortest path dictionary.
"""
# Invert every element from route to check both directions
rev_edges = reversed_edges(new_route)
# Create list to check disjunction
edges_in_route = new_route + rev_edges
# For every od-pair in shortest path dict
for od in shortest_paths:
# Get sequence of edges
edges_in_path = path_nodes_to_edges(shortest_paths[od])
if set(edges_in_path).isdisjoint(edges_in_route):
shortest_paths[od] = []
return shortest_paths
def insert_node(G, route):
"""
Inserts a random node in a route to modify it.
Args:
G - graph of the network
route - the route, as a sequence of edges.
Returns: A modified route, with an extra node.
"""
# Initialize list
removed_edge_index = []
ins_candidate_edges = []
ins_candidate_nodes = []
# Search viable nodes
for i, edge in enumerate(route):
# Generate list of nodes 'k' as (u, k) and (k, v)
in_nodes = [v for u, v in G.edges(edge[0])]
out_nodes = [v for u, v in G.edges(edge[1])]
# Generate intersection
candidate_nodes = list(set(in_nodes) & set(out_nodes))
# If len(candidate_nodes) > 0...
if len(candidate_nodes) > 0:
removed_edge_index.append(i)
ins_candidate_edges.append(edge)
ins_candidate_nodes.append(candidate_nodes)
# Check for a viable solution
if len(ins_candidate_edges) and len(ins_candidate_nodes) > 0:
# Select random edge from candidates
selection_index = random.randint(0, len(removed_edge_index) - 1)
selected_edge = ins_candidate_edges[selection_index]
selected_edge_index_in_route = removed_edge_index[selection_index]
# Select random node from candidates for selected edge
selected_node = random.choice(ins_candidate_nodes[selection_index])
# Generate new edges to add
edge_1 = (selected_edge[0], selected_node)
edge_2 = (selected_node, selected_edge[1])
# Remove edge from route
route.pop(selected_edge_index_in_route)
# Add new edges
route.insert(selected_edge_index_in_route, edge_1)
route.insert(selected_edge_index_in_route + 1, edge_2)
return route
def remove_node(G, route):
"""
Removes a random node from a route to modify it.
Args:
G - graph of the network
route - the route, as a sequence of edges.
Returns: A modified route, with one less node.
"""
# Initialize lists
candidate_edges_indexes = []
candidate_new_edge = []
# Iterate through all nodes
for i in range(len(route) - 1):
# Determine origin and destination
origin = route[i][0]
destination = route[i+1][1]
# If node is removable
if G.has_edge(origin, destination):
# Add edge sequence indexes
candidate_edges_indexes.append((i, i+1))
candidate_new_edge.append((origin, destination))
# Check for a viable solution
if len(candidate_edges_indexes) and len(candidate_new_edge) > 0:
# Select random node from candidates
selected_node = random.choice(candidate_edges_indexes)
selected_node_index = candidate_edges_indexes.index(selected_node)
# Remove node from sequence
route.pop(selected_node[1])
route.pop(selected_node[0])
# Add new edge
route.insert(selected_node[0], candidate_new_edge[selected_node_index])
return route
def swap_node(G, route):
"""
Swaps a random node from a route to modify it.
Args:
G - graph of the network
route - the route, as a sequence of edges.
Returns: A modified route, with the same number of
nodes but a different combination.
"""
# Initialize lists
swap_candidates_indexes = []
swap_candidates = []
# Transform path into node notation
node_route = path_edges_to_nodes(route)
# Iterate through all nodes
for i in range(len(route) - 1):
# Determine origin and destination
origin = route[i][0]
destination = route[i+1][1]
# Collection of unused nodes
unused_nodes = list(set(G.nodes()) - set(node_route))
# if exists an alternative path
for candidate_node in unused_nodes:
# if exists a node that has edges from origin and to destination
if G.has_edge(origin, candidate_node) and G.has_edge(candidate_node, destination):
# Add edge sequence indexes
swap_candidates_indexes.append((i, i+1))
swap_candidates.append(((origin, candidate_node),(candidate_node, destination)))
# Check for viable solution
if len(swap_candidates_indexes) > 0 and len(swap_candidates) > 0:
# Get length of list
selected = random.randint(0, len(swap_candidates_indexes) - 1)
# Select random edges to replace
removed_edges = swap_candidates_indexes[selected]
inserted_edges = swap_candidates[selected]
# Remove old edges
route.pop(removed_edges[1])
route.pop(removed_edges[0])
# Add new edges
route.insert(removed_edges[0], inserted_edges[0])
route.insert(removed_edges[1], inserted_edges[1])
return route
def modify_solution(G, current_solution):
"""
Tabu search algorithm to improve routes.
Args:
G - graph of the network
current_solution - current solution list of routes.
Returns: An modified set of routes.
"""
# List of operations
operations = [insert_node, remove_node, swap_node, 'remove_route']
# Select random route from list
route_index = random.randint(0, len(current_solution) - 1)
route = current_solution[route_index]
# Select random operation
operation = random.choice(operations)
# Execute operation
if operation == 'remove_route':
# Delete route from array
current_solution.pop(route_index)
else:
# Modify route
modified_route = operation(G, route)
# Remove old route from list
current_solution.pop(route_index)
# Add modified route to list
current_solution.insert(route_index, modified_route)
#print(f'Selected operation: {operation.__name__}')
return current_solution
def create_extended_graph(graph, route_set, original_set, transfer_weight=0):
extended_graph = nx.Graph()
indexes = dict([(node, 0) for node in graph.nodes()])
for i, route in enumerate(route_set):
#print('')
#print(f'Route {i+1}: {route}')
#print(f'Route {i+1}: {original_set[i]}')
for j, node in enumerate(route):
current_node = 'R' + str(i+1) + '-' + str(node)
# Set index for nodes
current_node_index = node
# Add node to graph
extended_graph.add_node(current_node, original_node=node, route=i+1)
# If its not the starting node, add the edge connecting to previous node
if j > 0:
tup = tuple(sorted((previous_node_index, current_node_index)))
#print(f'previous_node: {previous_node}')
#print(f'current_node: {current_node}')
#print(f'graph: {graph}')
#print(f'tup: {tup}')
extended_graph.add_edge(current_node, previous_node, length=nx.get_edge_attributes(graph, 'length')[tup])
# Update variables
indexes[node] += 1
previous_node = current_node
previous_node_index = current_node_index
for node in graph.nodes():
# Add base nodes
extended_graph.add_node(node)
# Add connections between original node and all routes that contain that node
for (route_node, data) in extended_graph.nodes(data=True):
if data and data['original_node'] == node:
# Add edge between original graph and route nodes
extended_graph.add_edge(node, route_node, length=transfer_weight)
return extended_graph
def calculate_transfers(path):
"""
Calculates total number of transfers in a given path
Args:
path - a path, as a sequence of nodes.
Returns: number of transfers (int)
"""
# Return only base nodes (int values)
base_nodes = [node for node in path if isinstance(node, int)]
# Remove origin and destination
transfers = len(base_nodes) - 2
return transfers