-
Notifications
You must be signed in to change notification settings - Fork 0
/
algos.py
1368 lines (1067 loc) · 38.1 KB
/
algos.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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Graph algorithms
"""
import random
from collections import deque
from itertools import combinations, permutations, product
from typing import Callable, Deque, Optional
import numpy as np
from more_itertools import set_partitions
from graph import Graph
def num_visited_along_path(g: Graph, path: list[int]) -> list[int]:
"""
Presuming that node weights = people per location
Utility function to give total visited at each position along a path
Parameters
----------
g: Graph
Input graph
path: list[int]
The path along the graph
Assertions:
Edges in path must be present in the graph/
Returns
-------
list[int]
visited[i] = sum of nodeweights of path[0..i]
empty list => visited = []
"""
if len(path) == 0:
return []
visited: list[int] = []
visited.append(g.node_weight[path[0]])
# Iterate through all nodes in path
for i in range(1, len(path)):
# Raise error if edge does not exist
if path[i] not in g.adjacen_list[path[i - 1]]:
raise ValueError(f"Edge {path[i - 1]} --> {path[i]} does not exist")
visited.append(visited[-1] + g.node_weight[path[i]])
return visited
def length_along_path(g: Graph, path: list[int]) -> list[float]:
"""
Utility function to give total length traveled at each position along a path
Parameters
----------
g: Graph
Input graph
path: list[int]
The path along the graph
Assertions:
Edges in path must be present in the graph/
Returns
-------
list[int]
length[i] = distance traveled from from path[0] to path[i]
"""
if len(path) <= 1:
return [0.0]
length: list[float] = [0.0]
# Iterate through all nodes in path
for i in range(1, len(path)):
# Raise error if edge does not exist
if path[i] not in g.adjacen_list[path[i - 1]]:
raise ValueError(f"Edge {path[i - 1]} --> {path[i]} does not exist")
length.append(length[-1] + g.edge_weight[path[i - 1]][path[i]])
return length
def generate_path_function(g: Graph, path: list[int]) -> Callable[[float], int]:
"""
Generates a function to get the number of people visited along a given path
Parameters
----------
g: Graph
Input graph
path: list[int]
The path along the graph
Assertions:
Edges in path must be present in the graph/
Non-empty path
Returns
-------
Callable[[float], int]
path_function(x) = the number of people visited at distance x along path
Assertions:
x >= 0.0
"""
if len(path) == 0:
raise ValueError("Passed path was empty")
length: list[float] = length_along_path(g, path)
visited: list[int] = num_visited_along_path(g, path)
def path_function(x: float) -> int:
if x < 0:
raise ValueError("Input was a negative distance")
# find largest index of length such that length[i] <= x
idx: int = 0
found: bool = False
while not found:
next_idx: int = idx + 1
if next_idx < len(length) and length[next_idx] <= x:
idx = next_idx
else:
found = True
return visited[idx]
return path_function
def generate_partition_path_function(
g: Graph, part: list[list[int]]
) -> Callable[[float], int]:
"""
Generates a function to get the number of people visited over time in an assignment
Parameters
----------
g: Graph
Input graph
assignment: list[list[int]]
Agent assignment
Assertions:
Must be valid agent assignment
Returns
-------
Callable[[float], int]
partition_path_function(x) = the number of people visited at distance x
Assertions:
x >= 0.0
"""
if Graph.is_agent_partition(g, [set(p) for p in part]) is False:
raise ValueError("Passed assignment is invalid")
path_functions: list[Callable[[float], int]] = []
for path in part:
path_functions.append(generate_path_function(g, path))
def partition_path_function(x: float) -> int:
if x < 0:
raise ValueError("Input was a negative distance")
res: int = 0
for f in path_functions:
res += f(x)
# Double counting start node (0) many times
res -= g.node_weight[0] * (len(path_functions) - 1)
return res
return partition_path_function
def path_length(g: Graph, path: list[int]) -> float:
"""
Get the length of a path in a graph
Essentially just a wrapper around length_along_path
Parameters
----------
g: Graph
Input graph
path: list[int]
The path along the graph
Assertions:
Edges in path must be present in the graph/
Returns
-------
float
Path length. 0.0 if the length is less then 2 nodes
"""
return length_along_path(g, path)[-1]
def floyd_warshall(g: Graph) -> list[list[float]]:
"""
Use Floyd-Warshall algorithm to solve all pairs shortest path (APSP)
Parameters
----------
g: Graph
Input graph
Returns
-------
list[list[float]]
2D array of distances
dist[i][j] = distance from i -> j
if no path exists, value is float('inf')
"""
n: int = g.num_nodes
dist: list[list[float]] = [[float("inf") for _ in range(n)] for _ in range(n)]
# initialize dist-table
for i in range(n):
dist[i][i] = 0.0
for j in range(n):
if i != j and j in g.adjacen_list[i]:
dist[i][j] = g.edge_weight[i][j]
# if dist[i][k] + dist[k][j] < dist[i][j]: update
for (k, i, j) in product(range(n), range(n), range(n)):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
def create_metric_from_graph(g: Graph) -> Graph:
"""
Create metric graph from input graph
Using Floyd-Warshall we can solve the APSP problem.
This gives edge weights that satisfy the triangle inequality
Parameters
----------
g: Graph
Input graph
Returns
-------
Graph
Graph with edgeweights based off of Floyd-Warshall Algorithm
i.e. len(u -> v) = shortest distance from u to v
"""
n: int = g.num_nodes
metric = Graph(n)
metric.node_weight = g.node_weight
metric.adjacen_list = g.adjacen_list
metric_weights: list[list[float]] = floyd_warshall(g)
for (i, j) in product(range(n), range(n)):
if (
i != j
and g.edge_weight[i][j] != -1
and metric_weights[i][j] != float("inf")
):
metric.edge_weight[i][j] = metric_weights[i][j]
return metric
def wlp(g: Graph, path: list[int]) -> float:
"""
Calculate the weighted latency of a given path
Sums of weights of node * length along path from start to node
Parameters
----------
g: Graph
Input graph
path: list[int]
The path along the graph
Assertions:
Edges in path must be present in the graph/
Returns
-------
float
Weighted Latency over the path in g
"""
# check nodes in order are actually valid nodes
for node in path:
if node >= g.num_nodes or node < 0:
raise ValueError(f"Node {node} is not in passed graph")
if len(path) <= 1:
return 0.0
path_len: list[float] = [0.0] * len(path)
for i in range(0, len(path) - 1):
if path[i + 1] not in g.adjacen_list[path[i]]:
raise ValueError(f"Edge {path[i]} --> {path[i + 1]} does not exist")
path_len[i + 1] = path_len[i] + g.edge_weight[path[i]][path[i + 1]]
# sum over sequence [v_0, v_1, ..., v_n] of w(v_i) * L(0, v_i)
return sum(g.node_weight[path[i]] * path_len[i] for i in range(len(path)))
def brute_force_mwlp(g: Graph, start: Optional[list[int]] = None) -> list[int]:
"""
Calculate minumum weighted latency
Iterates over all possible paths and solves in brute force manner
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Path order for minimum weighted latency
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
if start is None:
start = [0]
# check validity of start:
for n in start:
if n >= g.num_nodes or n < 0:
raise ValueError(f"Passed {start = } contains nodes not in g")
# keep track of visited nodes
visited: list[bool] = [False] * g.num_nodes
for n in start:
visited[n] = True
# valid nodes to visit
nodes: list[int] = [i for i in range(g.num_nodes) if visited[i] is False]
best: list[int] = []
mwlp = float("inf")
# test every permutation
for order in permutations(nodes):
full_order: list[int] = start + list(order)
curr: float = wlp(g, full_order)
if curr < mwlp:
mwlp = curr
best = full_order
return best
def nearest_neighbor(g: Graph, start: Optional[list[int]] = None) -> list[int]:
"""
Approximates MWLP using nearest neighbor heuristic
Starts from a node and goes to the nearest unvisited neighbor
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Path order for minimum weighted latency according to nearest neighbor
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
if start is None:
start = [0]
# check validity of start:
for n in start:
if n >= g.num_nodes or n < 0:
raise ValueError(f"Passed {start = } contains nodes not in g")
# keep track of visited nodes
visited: list[bool] = [False] * g.num_nodes
for n in start:
visited[n] = True
# Use queue to remember current node
order: list[int] = start
q: Deque[int] = deque()
q.appendleft(order[-1])
while len(q) != 0:
curr: int = q.pop()
dist = float("inf")
nearest: int = -1
for n in g.adjacen_list[curr]:
if not visited[n] and g.edge_weight[curr][n] < dist:
dist = g.edge_weight[curr][n]
nearest = n
if nearest != -1:
q.appendleft(nearest)
order.append(nearest)
visited[nearest] = True
return order
def greedy(g: Graph, start: Optional[list[int]] = None) -> list[int]:
"""
Approximates MWLP using greedy heuristic
Starts from a node and goes to the heaviest unvisited neighbor
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Path order for minimum weighted latency according to greedy
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
if start is None:
start = [0]
# check validity of start:
for n in start:
if n >= g.num_nodes or n < 0:
raise ValueError(f"Passed {start = } contains nodes not in g")
# keep track of visited nodes
visited: list[bool] = [False] * g.num_nodes
for n in start:
visited[n] = True
# Use queue to remember current node
order: list[int] = start
while len(order) != g.num_nodes:
curr: int = order[-1]
best_weight = float("-inf")
heaviest: int = -1
for n in g.adjacen_list[curr]:
if not visited[n] and g.node_weight[n] > best_weight:
best_weight = g.node_weight[n]
heaviest = n
if heaviest != -1:
order.append(heaviest)
visited[heaviest] = True
return order
def alternate(g: Graph, start: Optional[list[int]] = None) -> list[int]:
"""
Approximates MWLP using by alternating between two strategies (greedy + NN)
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Path order for minimum weighted latency according to alternating strategy
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
if start is None:
start = [0]
# check validity of start:
for n in start:
if n >= g.num_nodes or n < 0:
raise ValueError(f"Passed {start = } contains nodes not in g")
# keep track of visited nodes
visited: list[bool] = [False] * g.num_nodes
for n in start:
visited[n] = True
# Use queue to remember current node
order: list[int] = start
q: Deque[int] = deque()
q.appendleft(order[-1])
# 0 = Greedy, 1 = NN
counter: int = 0
while len(q) != 0:
curr: int = q.pop()
next_node: int = -1
if counter == 0:
best_weight = float("-inf")
for n in g.adjacen_list[curr]:
if not visited[n] and g.node_weight[n] > best_weight:
best_weight = g.node_weight[n]
next_node = n
else:
dist = float("inf")
for n in g.adjacen_list[curr]:
if not visited[n] and g.edge_weight[curr][n] < dist:
dist = g.edge_weight[curr][n]
next_node = n
if next_node != -1:
q.appendleft(next_node)
order.append(next_node)
visited[next_node] = True
counter = (counter + 1) % 2
return order
def random_order(g: Graph, start: Optional[list[int]] = None) -> list[int]:
"""
Creates a random order of unvisited nodes
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Random path order
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
if start is None:
start = [0]
# check validity of start:
for n in start:
if n >= g.num_nodes or n < 0:
raise ValueError(f"Passed {start = } contains nodes not in g")
# keep track of visited nodes
visited: list[bool] = [False] * g.num_nodes
for n in start:
visited[n] = True
to_visit: list[int] = [i for i in range(g.num_nodes) if visited[i] is False]
return start + list(np.random.permutation(to_visit))
def brute_force_tsp(g: Graph, start: int = 0) -> list[int]:
"""
Bruteforce solves the Travelling Salesman Problem to generate an order
Iterates over all possible paths and solves in brute force manner
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: list[int]
Optional start of path (allows for partial solving)
Assertions:
Must contain nodes that are in the graph
Returns
-------
list[int]
Path order according to best TSP solution over g
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
# check validity of start
if start >= g.num_nodes:
raise ValueError(f"{start = } is not in passed graph")
# valid nodes to visit
nodes = list(range(g.num_nodes))
nodes.remove(start)
min_dist = float("inf")
best: list[int] = []
# test every permutation
for order in permutations(nodes):
full_order: list[int] = [start] + list(order)
dist = 0.0
for i in range(g.num_nodes - 1):
dist += g.edge_weight[full_order[i]][full_order[i + 1]]
if dist < min_dist:
min_dist = dist
best = full_order
return best
def held_karp(g: Graph, start: int = 0) -> list[int]:
"""
Solves the Travelling Salesman Problem to generate an order
Uses Held Karp algorithm
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
start: int
Optional start node of path (allows for partial solving)
Returns
-------
list[int]
Path order according to best TSP solution over g
"""
# for now assume complete
if not Graph.is_complete(g):
raise ValueError("Passed graph is not complete")
# assert validity of start
if start >= g.num_nodes or start < 0:
raise ValueError(f"{start = } is not in passed graph")
# key: tuple(set[int]: nodes, int: end)
# value: tuple(float: path length, list[int]: order of nodes)
completed = {} # type: ignore # typing this would be too verbose
# recursive solver
def solve_tour(s: set[int], e: int) -> tuple[float, list[int]]:
# base case: if no in-between nodes must take edge from start -> e
if len(s) == 0:
return (g.edge_weight[start][e], [start])
min_length = float("inf")
best_order: list[int] = []
# otherwise iterate over S all possible second-t-last nodes
for i in s:
s_i: set[int] = set(s)
s_i.remove(i)
sublength, suborder = completed[frozenset(s_i), i]
length: float = sublength + g.edge_weight[i][e]
if length < min_length:
min_length = length
best_order = list(suborder) + [i]
return min_length, best_order
# solve TSP over all subsets of nodes, smallest to largest
targets: set[int] = set(i for i in range(g.num_nodes))
targets.remove(start)
for k in range(1, len(targets) + 1):
for subset in combinations(targets, k):
for e in subset:
s: set[int] = set(subset)
s.remove(e)
completed[frozenset(s), e] = solve_tour(s, e)
# Find best TSP over all nodes (essentially solving last case again)
tsp_sol = float("inf")
best_order: list[int] = []
for i in targets:
s_i = set(targets)
s_i.remove(i)
tsp, order = completed[frozenset(s_i), i]
if tsp < tsp_sol:
tsp_sol = tsp
best_order = order + [i]
return best_order
def multi_agent_brute_force(
g: Graph,
k: int,
f: Callable[..., list[int]] = brute_force_mwlp,
max_size: int = 0,
) -> list[list[int]]:
"""
Computes the optimal assignment of targets for a given heuristic
Parameters
----------
g: Graph
Input Graph
Assertions:
Must be complete
k: int
Number of agents
Assertions:
0 < k <= g.num_nodes
f: Callable[..., list[int]]
Heuristic to optimize with
Default:
Brute force mwlp
max_size: int
Maximum number of nodes that agents can visit
Default:
0 which means any number is allowed
Assertions:
Must be >= 0
Returns
-------
list[list[int]]
Optimal assignment
"""
# for now assume complete
if Graph.is_complete(g) is False:
raise ValueError("Passed graph is not complete")
if k <= 0:
raise ValueError(f"Multi-agent case must have non-zero agents ({k})")
if k > g.num_nodes:
raise ValueError(f"Multi-agent case cannot have more agents than nodes ({k})")
if max_size < 0:
raise ValueError(f"Maximum size of path cannot be negative ({max_size})")
if max_size == 0:
max_size = g.num_nodes
# assume start is at 0
nodes = list(range(1, g.num_nodes))
best_order: list[list[int]] = []
minimum = float("inf")
# iterate through each partition
for part in set_partitions(nodes, k):
if any(len(subset) > max_size for subset in part):
continue
curr = float("-inf")
part_order: list[list[int]] = []
# iterate through each group in partition
for nodes in part:
# assume starting at 0
full_list: list[int] = [0] + nodes
sg, sto, _ = Graph.subgraph(g, full_list)
# calculuate heuristic
heuristic_order: list[int] = f(sg)
curr = max(curr, wlp(sg, heuristic_order))
# collect orders
original_order = [sto[n] for n in heuristic_order]
part_order.append(original_order)
if curr < minimum:
minimum = curr
best_order = part_order
return best_order
def greedy_assignment(g: Graph, k: int) -> list[list[int]]:
"""
Greedy algorithm from "Predicting Outage Restoration..."
Finds the agent with the current shortest path
Assigns them the heaviest unvisited node
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
k: int
Number of agents
Returns
-------
list[list[int]]
Assigned targets and order of targets for each agent.
"""
if Graph.is_complete(g) is False:
raise ValueError("Passed graph is not complete")
# The only valid nodes to visit are non-starting nodes
nodes: list[int] = list(range(1, g.num_nodes))
# Sort the nodes from heaviest to least heavy
nodes = sorted(nodes, key=lambda x: g.node_weight[x], reverse=True)
# All paths must start with the start node
paths: list[list[int]] = [[0] for _ in range(k)]
for node in nodes:
# find agent with shortest path (i.e. the agent who will finish first)
agent: int = min(range(k), key=lambda x: path_length(g, paths[x]))
# append current node (heaviest unvisited) to agent
paths[agent].append(node)
return paths
def greedy_random_assignment(g: Graph, k: int, r: float) -> list[list[int]]:
"""
Greedy + Random algorithm from "Predicting Outage Restoration..."
Group agents into two groups:
Group 1: Greedy
Group 2: Random neighbor
If the agent with the current shortest path is in Group 1, assign
the heaviest node
Otherwise find a random node in the radius r from the end of their path
If no node exists, send them to the nearest neighbor
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
k: int
Number of agents
r: float
Radius of random seach
Returns
-------
list[list[int]]
Assigned targets and order of targets for each agent.
"""
if Graph.is_complete(g) is False:
raise ValueError("Passed graph is not complete")
# The only valid nodes to visit are non-starting nodes
nodes: set[int] = set(range(1, g.num_nodes))
# Randomly divide the agents into 2 groups
# group1: Finds the heaviest unvisited node
# group2: Finds a random node in a certain radius
group1: set[int] = set(random.sample(range(k), k // 2))
# All paths must start with the start node
paths: list[list[int]] = [[0] for _ in range(k)]
while len(nodes) > 0:
idx: int = min(range(k), key=lambda x: path_length(g, paths[x]))
# Greedy agents
if idx in group1:
# Find heaviest node
highest_weight: int = max(nodes, key=lambda x: g.node_weight[x])
# append current node (heaviest unvisited) to agent
paths[idx].append(highest_weight)
nodes.remove(highest_weight)
# Random destination agents
else:
# Find nodes in the current radius
curr_loc: int = paths[idx][-1]
choices: list[int] = [i for i in nodes if g.edge_weight[curr_loc][i] <= r]
# If there are no nodes in the radius, pick nearest neighbor
if len(choices) == 0:
nearest: int = min(nodes, key=lambda x: g.edge_weight[curr_loc][x])
paths[idx].append(nearest)
nodes.remove(nearest)
else:
choice: int = random.choice(choices)
paths[idx].append(choice)
nodes.remove(choice)
return paths
def nearest_neighbor_assignment(g: Graph, k: int) -> list[list[int]]:
"""
Nearest Neighbor algorithm from "Agent Based Model to Estimate..."
Find the agent with the current shortest path.
Assign them the nerest unvisited neighbor
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
k: int
Number of agents
Returns
-------
list[list[int]]
Assigned targets and order of targets for each agent.
"""
if Graph.is_complete(g) is False:
raise ValueError("Passed graph is not complete")
# The only valid nodes to visit are non-starting nodes
nodes: set[int] = set(range(1, g.num_nodes))
# All paths must start with the start node
paths: list[list[int]] = [[0] for _ in range(k)]
while len(nodes) > 0:
# Find agent with the current shortest path
idx: int = min(range(k), key=lambda x: path_length(g, paths[x]))
# Find closest node
curr_loc: int = paths[idx][-1]
closest: int = min(nodes, key=lambda x: g.edge_weight[curr_loc][x])
# append current node to agent
paths[idx].append(closest)
nodes.remove(closest)
return paths
def transfers_and_swaps_mwlp(
g: Graph, part: list[set[int]], f: Callable[..., list[int]]
) -> list[set[int]]:
"""
Transfers and swaps nodes from one agent to another based on the passed heuristic
Parameters
----------
g: Graph
Input graph
Assertions:
g must be a complete graph
part: list[set[int]]