-
Notifications
You must be signed in to change notification settings - Fork 13
/
h_tsp.py
1591 lines (1407 loc) · 58 KB
/
h_tsp.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
from argparse import ArgumentError
import multiprocessing as mp
import os
from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import Callable, List, Optional, Set, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.cuda.amp as amp
import torch.nn as nn
import wandb
from matplotlib import pyplot as plt
from numba import jit
from omegaconf import DictConfig
from scipy.spatial.distance import cdist
from torch.utils.data import DataLoader, Dataset
import rl_models as models
import rl_utils as utils
from rl4cop import train_path_solver
from tsp_opt_solver import lkh_solver
DISTANCE_SCALE = 1000
# ignore numba deprecation warning
from numba.core.errors import NumbaPendingDeprecationWarning
import warnings
warnings.simplefilter("ignore", category=NumbaPendingDeprecationWarning)
class LowLevelSolver(ABC):
@abstractmethod
def solve(self, x: np.ndarray, fragment: List[int]):
pass
class LKHSolver(LowLevelSolver):
def solve(
self, data: np.ndarray, fragment: np.ndarray, runs=2
) -> Tuple[List[List[int]], np.ndarray]:
node_pos = np.take_along_axis(data, fragment[..., None], axis=1)
assert node_pos.ndim == 3
samples = []
for fragment_pos in node_pos:
samples.append(utils.nodes_to_sample(fragment_pos))
with mp.Pool(processes=10) as pool:
results = [
pool.apply_async(lkh_solver, (sample, True, runs)) for sample in samples
]
pool.close()
pool.join()
paths, lengths = [], []
for res in results:
route, dist = res.get()
paths.append(route)
lengths.append(dist)
lengths = np.array(lengths)
out_paths = []
for i, path in enumerate(paths):
assert path[0] == 0
new_path = [fragment[i][j] for j in path[:-1]]
out_paths.append(new_path)
return out_paths, lengths
class GreedySolver(LowLevelSolver):
def solve(self, x: np.ndarray, fragment: List[int]) -> Tuple[List[int], float]:
if len(fragment) == 0:
return []
fragment_pos = x.take(fragment, axis=0)
frag_len = len(fragment) - 1
dist = cdist(fragment_pos, fragment_pos)
dist_search = dist.copy()
np.fill_diagonal(dist_search, np.inf)
dist_search[:, frag_len] = np.inf
dist_search[:, 0] = np.inf
greedy_tour = [0]
city_last = 0
length = 0.0
while len(greedy_tour) < frag_len:
city_next = dist_search[city_last].argmin()
length += dist[city_last, city_next]
greedy_tour.append(city_next)
dist_search[:, city_next] = np.inf
city_last = city_next
greedy_tour.append(frag_len)
length += dist[city_last, frag_len]
new_path = [fragment[i] for i in greedy_tour]
return new_path, length
class FarthestInsertSolver(LowLevelSolver):
def solve(self, x: np.ndarray, fragment: List[int]) -> Tuple[List[int], float]:
if len(fragment) == 0:
return []
fragment_pos = x.take(fragment, axis=0)
frag_len = len(fragment)
available_nodes = set(range(frag_len))
positions = fragment_pos
tour = np.array([0, frag_len - 1])
nodes_arr = np.ma.masked_array(list(available_nodes))
best_distances = np.ma.masked_array(
cdist(positions[nodes_arr], positions[tour], "euclidean").min(axis=1)
)
# We want the most distant node, so we get the max
index_to_remove = best_distances.argmax()
next_id = nodes_arr[index_to_remove]
# Add the most distant point, as well as the first point to close the tour, we'll be inserting from here
tour = np.insert(tour, 1, next_id)
available_nodes.remove(0)
available_nodes.remove(frag_len - 1)
available_nodes.remove(next_id)
nodes_arr[index_to_remove] = np.ma.masked
best_distances[index_to_remove] = np.ma.masked
# Takes two arrays of points and returns the array of distances
def dist_arr(x1, x2):
return np.sqrt(((x1 - x2) ** 2).sum(axis=1))
# This is our selection method we will be using, it will give us the index in the masked array of the selected node,
# the city id of the selected node, and the updated distance array.
def get_next_insertion_node(nodes, positions, prev_id, best_distances):
best_distances = np.minimum(
cdist(
positions[nodes], positions[prev_id].reshape(-1, 2), "euclidean"
).min(axis=1),
best_distances,
)
max_index = best_distances.argmax()
return max_index, nodes[max_index], best_distances
while len(available_nodes) > 0:
index_to_remove, next_id, best_distances = get_next_insertion_node(
nodes_arr, positions, next_id, best_distances
)
# Finding the insertion point
c_ik = cdist(positions[tour[:-1]], positions[next_id].reshape(-1, 2))
c_jk = cdist(positions[tour[1:]], positions[next_id].reshape(-1, 2))
c_ij = dist_arr(positions[tour[:-1]], positions[tour[1:]]).reshape(-1, 1)
i = (c_ik + c_jk - c_ij).argmin()
tour = np.insert(tour, i + 1, next_id)
available_nodes.remove(next_id)
nodes_arr[index_to_remove] = np.ma.masked
best_distances[index_to_remove] = np.ma.masked
new_path = [fragment[i] for i in tour]
return new_path, None
class RLSolver(LowLevelSolver):
def __init__(self, low_level_model: nn.Module, sample_size: int = 200) -> None:
self._solver_model = low_level_model
self._sample_size = max(sample_size, 2)
def solve(
self,
data: torch.Tensor,
fragment: torch.Tensor,
frag_buffer: utils.FragmengBuffer,
) -> Tuple[List[List[int]], torch.Tensor]:
node_pos = torch.gather(
input=data, index=fragment[..., None].expand(-1, -1, data.shape[-1]), dim=1
)
assert node_pos.ndim == 3
device = self._solver_model.device
B = node_pos.shape[0]
N = node_pos.shape[1]
x = node_pos.to(device=device)
x1_min = x[..., 0].min(dim=-1, keepdim=True)[0]
x2_min = x[..., 1].min(dim=-1, keepdim=True)[0]
x1_max = x[..., 0].max(dim=-1, keepdim=True)[0]
x2_max = x[..., 1].max(dim=-1, keepdim=True)[0]
s = 0.9 / torch.maximum(x1_max - x1_min, x2_max - x2_min)
x_new = torch.empty_like(x)
x_new[..., 0] = s * (x[..., 0] - x1_min) + 0.05
x_new[..., 1] = s * (x[..., 1] - x2_min) + 0.05
frag_buffer.update_buffer(x_new.cpu())
source_nodes = torch.tensor([[0]], device=device).expand(B, 1)
target_nodes = torch.tensor([[N - 1]], device=device).expand(B, 1)
with amp.autocast(enabled=False) as a, torch.no_grad() as b, utils.evaluating(
self._solver_model
) as solver:
lengths, paths = solver(
x_new.float(),
source_nodes=source_nodes,
target_nodes=target_nodes,
val_type="x8Aug_2Traj",
return_pi=True,
group_size=self._sample_size,
)
lengths = (lengths / s.squeeze()).detach().cpu().numpy()
# Flip and construct tour on original graph
out_paths = []
paths = paths.detach().cpu().numpy()
fragment = fragment.cpu().numpy()
if B == 1:
paths = [paths]
for i, path in enumerate(paths):
# make sure path start with `0` and end with `N-1`
zero_idx = np.nonzero(path == 0)[0][0]
path = np.roll(path, -zero_idx)
assert path[0] == 0, f"{zero_idx=}, {path=}"
if path[-1] != N - 1:
path = np.roll(path, -1)
path = np.flip(path)
assert path[-1] == N - 1, f"{path=}"
assert np.unique(path).shape[0] == path.shape[0] == N
assert path.shape[0] == fragment[i].shape[0] == N
new_path = [fragment[i][j] for j in path]
out_paths.append(new_path)
return out_paths, lengths
class LargeState:
def __init__(
self,
x: torch.Tensor,
k: int,
init_tour: List[int],
dist_matrix: torch.Tensor = None,
knn_neighbor: torch.Tensor = None,
) -> None:
# for now only support single graph
assert x.ndim == 2
assert isinstance(x, torch.Tensor)
self.x = x
self.device = x.device
self.graph_size = x.shape[0]
# k for k-Nearest-Neighbor
self.k = k
if dist_matrix is None:
self.dist_matrix = dist_matrix = torch.cdist(
x.type(torch.float64) * DISTANCE_SCALE,
x.type(torch.float64) * DISTANCE_SCALE,
).type(torch.float32)
else:
assert isinstance(dist_matrix, torch.Tensor)
self.dist_matrix = dist_matrix
if knn_neighbor is None:
self.knn_neighbor = self.dist_matrix.topk(
k=self.k + 1, largest=False
).indices[:, 1:]
else:
assert isinstance(knn_neighbor, torch.Tensor)
self.knn_neighbor = knn_neighbor
self.numpy_knn_neighbor = self.knn_neighbor.cpu().numpy()
assert len(init_tour) == 2 or len(init_tour) == 0
self.selected_mask = torch.zeros(
x.shape[0], dtype=torch.bool, device=self.device
)
self.available_mask = torch.zeros(
x.shape[0], dtype=torch.bool, device=self.device
)
self.neighbor_coord = torch.zeros(
(x.shape[0], 4), dtype=torch.float32, device=self.device
)
# start with a 2-city-tour or empty tour
self.current_tour = init_tour.copy()
self.current_num_cities = len(self.current_tour)
# to make final return equals to tour length
self.current_tour_len = (
utils.get_tour_distance(init_tour, self.dist_matrix) / DISTANCE_SCALE
)
utils.update_neighbor_coord_(self.neighbor_coord, self.current_tour, self.x)
self.mask(self.current_tour)
def move_to(self, new_path: List[int]) -> None:
"""state transition given current state (partial tour) and action (new path)"""
if self.current_num_cities == 0:
self.current_tour = new_path
else:
start_idx = self.current_tour.index(new_path[0])
end_idx = self.current_tour.index(new_path[-1])
assert start_idx != end_idx, new_path
# assuming we always choose a fragment from left to right
# replace the old part in current tour with the new path, there is a city-overlap between them
if end_idx > start_idx:
self.current_tour = (
self.current_tour[:start_idx]
+ new_path
+ self.current_tour[end_idx + 1 :]
)
else:
self.current_tour = (
self.current_tour[end_idx + 1 : start_idx] + new_path
)
# make sure no duplicate cities
assert np.unique(self.current_tour).shape[0] == len(
self.current_tour
), f"{self.current_tour}"
# update info of current tour
if len(self.current_tour) < self.graph_size:
assert (
len(self.current_tour) > self.current_num_cities
), f"{len(self.current_tour)}-{self.current_num_cities}-{len(new_path)}"
else:
assert (
len(self.current_tour) == self.graph_size
), f"{len(self.current_tour)}-{self.graph_size}"
self.current_num_cities = len(self.current_tour)
self.current_tour_len = utils.get_tour_distance(
self.current_tour, self.dist_matrix
)
utils.update_neighbor_coord_(self.neighbor_coord, self.current_tour, self.x)
# update two masks
self.mask(new_path)
def mask(self, new_path: List[int]) -> None:
"""update mask status w.r.t new path"""
self.selected_mask[new_path] = True
# update mask of available starting cities for k-NN process
self.available_mask[new_path] = True
avaliable_cities = torch.where(self.available_mask == True)
available_status = torch.logical_not(
self.selected_mask[self.knn_neighbor[avaliable_cities]].all(dim=1)
)
self.available_mask[avaliable_cities] = available_status
def get_nearest_cluster_city_idx(
self, old_cities: List[int], new_cities: List[int]
) -> int:
"""find the index of the old city nearest to given new cities"""
assert old_cities
assert new_cities
city_idx = utils.get_nearest_cluster_city_idx(
self.dist_matrix, old_cities, new_cities
)
return city_idx
def get_nearest_old_city_idx(self, predict_coord: torch.Tensor) -> int:
"""find the index of the new city nearest to given coordinates"""
assert predict_coord.shape == (2,)
city_idx = utils.get_nearest_city_idx(self.x, predict_coord, self.selected_mask)
return city_idx
def get_nearest_new_city_idx(self, predict_coord: torch.Tensor) -> int:
"""find the index of the new city nearest to given coordinates"""
assert predict_coord.shape == (2,)
city_idx = utils.get_nearest_city_idx(
self.x, predict_coord, ~self.selected_mask
)
return city_idx
def get_nearest_new_city_coord(self, predict_coord: torch.Tensor) -> int:
"""find the coordinate of the available city nearest to given coordinates"""
city_idx = self.get_nearest_new_city_idx(predict_coord)
city_coord = self.x[city_idx]
assert city_coord.shape == (2,)
return city_coord
def get_nearest_avail_city_idx(self, predict_coord: torch.Tensor) -> int:
"""find the index of the available city nearest to given coordinates"""
assert predict_coord.shape == (2,)
city_idx = utils.get_nearest_city_idx(
self.x, predict_coord, self.available_mask
)
return city_idx
def get_nearest_avail_city_coord(self, predict_coord: torch.Tensor) -> int:
"""find the coordinate of the available city nearest to given coordinates"""
city_idx = self.get_nearest_avail_city_idx(predict_coord)
city_coord = self.x[city_idx]
assert city_coord.shape == (2,)
return city_coord
def to_tensor(self) -> torch.Tensor:
"""concatenate `x`, `selected_mask` to produce an state"""
available_mask = self.available_mask
return torch.cat(
[
self.x,
self.selected_mask[:, None],
available_mask[:, None],
self.neighbor_coord,
],
dim=1,
)
def to_device_(self, device: Optional[Union[torch.device, str]] = None):
self.x = self.x.to(device)
self.device = self.x.device
self.dist_matrix = self.dist_matrix.to(device)
self.knn_neighbor = self.knn_neighbor.to(device)
self.selected_mask = self.selected_mask.to(device)
self.available_mask = self.available_mask.to(device)
self.neighbor_coord = self.neighbor_coord.to(device)
@classmethod
def from_numpy(cls, numpy_state: np.ndarray):
raise NotImplementedError
def __repr__(self) -> str:
return (
f"Large Scale TSP state, num_cities: {self.x.shape[0]},"
f"current_tour: {len(self.current_tour)} - {self.current_tour_len}"
)
class Env:
def __init__(
self,
k: int,
frag_len: int = 200,
max_new_nodes: int = 160,
max_improvement_step: int = 5,
):
self.k = k
# length of the fragment sent to low-level agent
self.frag_len = frag_len
self.max_new_nodes = max_new_nodes
self.max_improvement_step = max_improvement_step
def reset(self, x: torch.Tensor, no_depot=False) -> Tuple[LargeState, float, bool]:
self.x = x.type(torch.float32)
self.device = x.device
self.graph_size = self.N = x.shape[0]
self.node_dim = self.C = x.shape[1]
# for numerical stability
dist_matrix = torch.cdist(
x.type(torch.float64) * DISTANCE_SCALE,
x.type(torch.float64) * DISTANCE_SCALE,
).type(torch.float32)
dist_matrix.fill_diagonal_(float("inf"))
knn_neighbor = dist_matrix.topk(k=self.k, largest=False).indices
if no_depot:
init_tour = []
else:
depot = 0
init_tour = [depot, knn_neighbor[depot][0].item()]
self.state = LargeState(
x=self.x,
k=self.k,
init_tour=init_tour,
dist_matrix=dist_matrix,
knn_neighbor=knn_neighbor,
)
self._improvement_steps = 0
return self.state.to_tensor()
@staticmethod
@jit(nopython=True)
def append_selected(
neighbor: np.ndarray, selected_set: Set[int], selected_mask: np.ndarray
):
result = []
for n in neighbor:
if n not in selected_set and not selected_mask[n]:
result.append(n)
return result
def get_fragment_knn(
self, predict_coord: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
# early return if already done
if self.done:
return []
assert predict_coord.ndim == 1
assert predict_coord.min() >= 0
assert predict_coord.min() <= 1
if not self._construction_done:
# choose starting city based on the model predicted coordinate
nearest_new_city = self.state.get_nearest_new_city_idx(predict_coord)
if self.state.current_num_cities != 0:
start_city = self.state.get_nearest_old_city_idx(
self.x[nearest_new_city]
)
new_city_start = self.state.get_nearest_new_city_idx(self.x[start_city])
else:
start_city = None
new_city_start = nearest_new_city
# search for new cities with k-NN heuristic
max_cities = max(
self.max_new_nodes, self.frag_len - self.state.current_num_cities
)
new_cities = []
knn_deque = []
selected_set = set()
knn_deque.append(new_city_start)
selected_set.add(new_city_start)
selected_mask = self.state.selected_mask.cpu().numpy()
while len(knn_deque) != 0 and len(new_cities) < max_cities:
node = knn_deque.pop(0)
new_cities.append(node)
res = self.append_selected(
self.state.numpy_knn_neighbor[node], selected_set, selected_mask
)
knn_deque.extend(res)
selected_set.update(res)
else:
# refine a old fragment
assert not self._improvement_done
nearest_old_city = self.state.get_nearest_old_city_idx(predict_coord)
new_cities = []
# extend fragment to `frag_len` with some old cities
if self.state.current_num_cities != 0:
fragment = self._extend_fragment(start_city, new_cities)
else:
fragment = new_cities
for i in fragment:
if i in new_cities:
assert not self.state.selected_mask[i]
else:
assert self.state.selected_mask[i]
return (
torch.tensor(fragment, device=self.device),
torch.tensor(new_cities, device=self.device),
self.unscale_action(self.x[start_city]),
)
def step(
self,
predict_coord: np.ndarray,
solver: LowLevelSolver,
greedy_reward: bool = False,
average_reward: bool = False,
float_available_status=False,
) -> Tuple[LargeState, float, bool]:
# raise exception if already done
if self.done:
raise RuntimeError("Environment has terminated!")
# get fragment
predict_coord = self.scale_action(predict_coord)
fragment, _ = self.get_fragment_knn(predict_coord)
# solve subproblem
if isinstance(solver, (RLSolver, LKHSolver)):
new_paths, _ = solver.solve(self.x[None, ...], fragment[None, ...])
new_path = new_paths[0]
else:
new_path = solver.solve(self.x, fragment)
return self._step(
new_path, greedy_reward, average_reward, float_available_status
)
def _step(
self,
new_path: List[int],
greedy_reward: bool = False,
average_reward: bool = False,
) -> Tuple[LargeState, float, bool]:
"""step function for VecEnv"""
# raise exception if already done
if self.done:
raise RuntimeError("Environment has terminated!")
if self._construction_done and not self._improvement_done:
self._improvement_steps += 1
# record old states
old_len = self.state.current_tour_len
old_num_cities = self.state.current_num_cities
# update state
self.state.move_to(new_path)
self.state.current_tour_len = (
utils.get_tour_distance(self.state.current_tour, self.state.dist_matrix)
/ DISTANCE_SCALE
)
if greedy_reward:
len_rl = (
utils.get_tour_distance(new_path, self.state.dist_matrix)
- self.state.dist_matrix[new_path[0], new_path[-1]]
) / DISTANCE_SCALE
_, len_greedy = GreedySolver().solve(self.x, new_path)
reward = len_greedy - len_rl
else:
reward = old_len - self.state.current_tour_len
if average_reward:
added_num_cities = self.state.current_num_cities - old_num_cities
reward /= added_num_cities
return self.state.to_tensor(), reward, self.done
@property
def _construction_done(self):
return self.state.current_num_cities == self.graph_size
@property
def _improvement_done(self):
return self._improvement_steps >= self.max_improvement_step
@property
def done(self):
return self._construction_done and self._improvement_done
@staticmethod
def scale_action(a):
"""scale action from [-1, 1] to [0, 1]"""
return a * 0.5 + 0.5
@staticmethod
def unscale_action(a):
"""unscale action from [0, 1] to [-1, 1]"""
return a * 2 - 1
def random_action(self):
action = torch.randn(size=(self.node_dim,), device=self.device)
return self.unscale_action(action)
def heuristic_action(self):
non_selected_idx = torch.where(self.state.selected_mask == False)[0]
random_choice = np.random.randint(0, non_selected_idx.shape[0])
new_idx = non_selected_idx[random_choice]
action = self.x[new_idx]
return self.unscale_action(action)
def _extend_fragment(self, nearest_city: int, new_cities: List[int]):
nearest_idx = self.state.current_tour.index(nearest_city)
total_extend_len = self.frag_len - len(new_cities)
assert total_extend_len > 0, total_extend_len
offset = nearest_idx - (total_extend_len // 2)
reorder_tour = (
self.state.current_tour[offset:] + self.state.current_tour[:offset]
)
assert len(reorder_tour) == len(self.state.current_tour)
fragment = (
reorder_tour[: (total_extend_len // 2)]
+ new_cities
+ reorder_tour[(total_extend_len // 2) : total_extend_len]
)
assert len(fragment) == total_extend_len + len(
new_cities
), f"{len(fragment)}-{total_extend_len}-{len(new_cities)}"
assert len(fragment) == self.frag_len, len(fragment)
assert np.unique(fragment).shape[0] == len(fragment), np.unique(fragment).shape
return fragment
def to_device_(self, device: Optional[Union[torch.device, str]] = None):
self.x = self.x.to(device)
self.device = self.x.device
self.state.to_device_(device)
def debug_check_tour_len(self):
assert self.done, self.done
l = 0
tour = self.state.current_tour
dist_matrix = self.state.dist_matrix.cpu().squeeze().numpy()
assert len(tour) == self.graph_size, f"{len(tour)=}, {self.graph_size=}"
assert np.unique(tour).shape[0] == self.graph_size, f"{np.unique(tour).shape=}"
for i in range(self.graph_size - 1):
l += dist_matrix[tour[i], tour[i + 1]]
l += dist_matrix[tour[-1], tour[0]]
l /= DISTANCE_SCALE
assert (
abs(l - self.state.current_tour_len) < 1e-3
), f"{l=}, {self.state.current_tour_len=}"
class VecEnv:
def __init__(
self,
k: int,
frag_len: int = 200,
max_new_nodes: int = 160,
max_improvement_step: int = 5,
auto_reset=False,
no_depot=False,
):
self.k = k
self.frag_len = frag_len
self.max_new_nodes = max_new_nodes
self.max_improvement_step = max_improvement_step
self.auto_reset = auto_reset
self.no_depot = no_depot
def reset(self, x: torch.Tensor):
self.x = x
self.device = x.device
self.batch_size = self.B = x.shape[0]
self.graph_size = self.N = x.shape[1]
self.node_dim = self.C = x.shape[2]
self.envs = []
for _ in range(self.batch_size):
self.envs.append(
Env(
self.k, self.frag_len, self.max_new_nodes, self.max_improvement_step
)
)
states = [self.envs[i].reset(x[i], self.no_depot) for i in range(self.B)]
self.states = states
return torch.stack(states).type(torch.float32)
@property
def done(self):
return all(e.done for e in self.envs)
def step(
self,
predict_coords: torch.Tensor,
solver: LowLevelSolver,
greedy_reward: bool = False,
average_reward: bool = False,
float_available_status=False,
tsp_data: Callable = None,
frag_buffer: utils.FragmengBuffer = None,
log: Callable = None,
):
if self.done:
raise RuntimeError("Environment has terminated!")
assert predict_coords.ndim == 2
assert predict_coords.shape[0] == self.batch_size
actions = [Env.scale_action(coord) for coord in predict_coords]
# get active indecies
if not self.auto_reset:
active_idx = [i for i in range(self.B) if not self.envs[i].done]
active_envs = [self.envs[i] for i in active_idx]
active_acts = [actions[i] for i in active_idx]
else:
active_idx = list(range(self.B))
active_envs = self.envs
active_acts = actions
# get fragment of cities with model predicted coordinate
fragments = []
new_cities = []
start_cities = []
for env, a in zip(active_envs, active_acts):
frag, new_city, start_city = env.get_fragment_knn(
a,
)
fragments.append(frag)
new_cities.append(new_city)
start_cities.append(start_city)
# solve the fragment of cities to get a new path
if isinstance(solver, RLSolver):
new_paths, _ = solver.solve(
self.x[active_idx], torch.stack(fragments), frag_buffer
)
elif isinstance(solver, LKHSolver):
np_fragments = [frag.cpu().numpy() for frag in fragments]
new_paths, _ = solver.solve(
self.x[active_idx].cpu().numpy(), np.stack(np_fragments)
)
else:
new_paths = []
for env, frag in zip(self.envs, fragments):
res = solver.solve(env.x, frag)
new_paths.append(res)
# env update states and rewards given the new path
outputs = []
for env, p in zip(active_envs, new_paths):
res = env._step(p, greedy_reward, average_reward)
outputs.append(res)
if not self.auto_reset:
states = [None] * self.B
rewards = [0.0] * self.B
dones = [False] * self.B
count = 0
for i in range(self.B):
if i in active_idx:
states[i] = outputs[count][0]
rewards[i] = outputs[count][1]
dones[i] = outputs[count][2]
count += 1
assert count == len(active_idx), f"{count}!={len(active_idx)}"
else:
states = [output[0] for output in outputs]
rewards = [output[1] for output in outputs]
dones = [output[2] for output in outputs]
for i in range(self.B):
env = self.envs[i]
if env.done:
log(
"explore/tour_length",
env.state.current_tour_len.item(),
on_step=True,
)
data = tsp_data().squeeze().to(self.device)
state = env.reset(data, self.no_depot)
self.x[i] = data
states[i] = state
for i in active_idx:
self.states[i] = states[i]
return (
torch.stack(self.states).type(torch.float32),
torch.tensor(rewards, dtype=torch.float32, device=self.device),
torch.tensor(dones, dtype=torch.float32, device=self.device),
{
"fragments": fragments,
"new_cities": new_cities,
"start_city": torch.stack(
start_cities,
),
},
)
def random_action(self):
return Env.unscale_action(torch.randn(size=(self.batch_size, self.node_dim)))
def heuristic_action(self):
return torch.stack(
[
env.heuristic_action() if not env.done else env.random_action()
for env in self.envs
],
dim=0,
)
def to_device_(self, device: Optional[Union[torch.device, str]] = None):
for env in self.envs:
env.to_device_(device)
def readDataFile(filePath):
"""
read validation dataset from "https://github.com/Spider-scnu/TSP"
"""
res = []
with open(filePath, "r") as fp:
datas = fp.readlines()
for data in datas:
data = [float(i) for i in data.split("o")[0].split()]
loc_x = torch.FloatTensor(data[::2])
loc_y = torch.FloatTensor(data[1::2])
data = torch.stack([loc_x, loc_y], dim=1)
res.append(data)
res = torch.stack(res, dim=0)
return res
class TSPDataset(Dataset):
def __init__(
self,
size=50,
node_dim=2,
num_samples=100000,
data_distribution="uniform",
data_path=None,
):
super(TSPDataset, self).__init__()
if data_distribution == "uniform":
self.data = torch.rand(num_samples, size, node_dim)
elif data_distribution == "normal":
self.data = torch.randn(num_samples, size, node_dim)
self.size = num_samples
if not data_path is None:
self.data = readDataFile(data_path)
def __len__(self):
return self.size
def __getitem__(self, idx):
return self.data[idx]
class DummyDataset(Dataset):
"""Generate a dummy dataset.
Example:
>>> from pl_bolts.datasets import DummyDataset
>>> from torch.utils.data import DataLoader
>>> # mnist dims
>>> ds = DummyDataset((1, 28, 28), (1, ))
>>> dl = DataLoader(ds, batch_size=7)
>>> # get first batch
>>> batch = next(iter(dl))
>>> x, y = batch
>>> x.size()
torch.Size([7, 1, 28, 28])
>>> y.size()
torch.Size([7, 1])
"""
def __init__(self, *shapes, num_samples: int = 10000):
"""
Args:
*shapes: list of shapes
num_samples: how many samples to use in this dataset
"""
super().__init__()
self.shapes = shapes
self.num_samples = num_samples
def __len__(self):
return self.num_samples
def __getitem__(self, idx: int):
sample = []
for shape in self.shapes:
spl = torch.rand(*shape)
sample.append(spl)
return sample
def update_buffer(buffer, traj_list):
cur_items = list(map(list, zip(*traj_list)))
cur_items = [torch.cat(item, dim=0) for item in cur_items]
buffer[:] = cur_items
steps, r_exp = len(buffer[1]), buffer[1].mean().item()
return steps, r_exp
class HTSP_PPO(pl.LightningModule):
def __init__(self, cfg: DictConfig):
super().__init__()
self.low_level_model = train_path_solver.PathSolver.load_from_checkpoint(
cfg.low_level_load_path
)
self.low_level_solver = RLSolver(
self.low_level_model, cfg.low_level_sample_size
)
# self.low_level_solver = LKHSolver()
if cfg.encoder_type == "cnn":
self.encoder = models.IMPALAEncoder(
input_dim=cfg.input_dim,
embedding_dim=cfg.embedding_dim,
)
self.encoder_target = models.IMPALAEncoder(
input_dim=cfg.input_dim,
embedding_dim=cfg.embedding_dim,
)
else:
raise TypeError(f"Encoder type {cfg.encoder_type} not supported!")
self.actor = models.ActorPPO(
state_dim=cfg.embedding_dim,
mid_dim=cfg.acotr_mid_dim,
action_dim=cfg.nb_actions,
init_a_std_log=cfg.init_a_std_log,
)
self.critic = models.CriticPPO(
state_dim=cfg.embedding_dim,
mid_dim=cfg.hidden_dim,
_action_dim=cfg.nb_actions,
)
self.critic_target = models.CriticPPO(
state_dim=cfg.embedding_dim,
mid_dim=cfg.hidden_dim,
_action_dim=cfg.nb_actions,
)
utils.hard_update(self.critic_target, self.critic)
utils.hard_update(self.encoder_target, self.encoder)
self.mse_loss = nn.MSELoss()
# self.criterion = nn.SmoothL1Loss()
self.criterion = nn.MSELoss()
self.lambda_entropy = cfg.lambda_entropy
self.cfg = cfg
self.save_hyperparameters(cfg)
# Memory
self.memory = []
self.traj_list = [
[[] for _ in range(cfg.experience_items)] for _ in range(cfg.env_num)
]
self.frag_buffer = utils.FragmengBuffer(
cfg.low_level_buffer_size, cfg.frag_len, cfg.node_dim
)
self.val_frag_buffer = utils.FragmengBuffer(
cfg.low_level_buffer_size, cfg.frag_len, cfg.node_dim
)
# Environment
self.env_maker = lambda auto_reset=False, no_depot=False: VecEnv(
k=cfg.k,
frag_len=cfg.frag_len,