-
Notifications
You must be signed in to change notification settings - Fork 1
/
data.py
1647 lines (1349 loc) · 73.7 KB
/
data.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 ArgumentParser
import copy
import os
import math
import random
from collections import Counter, defaultdict
from itertools import islice, zip_longest
from time import time
import platform
import json
import gc
import h5py
from copy import deepcopy
from itertools import combinations
import torch
from torch import nn
import pandas as pd
import numpy as np
from einops import repeat, rearrange
from scipy import sparse, spatial
from tqdm import tqdm, trange
import networkx as nx
from sklearn.utils import shuffle
from sklearn.neighbors import NearestNeighbors, BallTree
from utils import create_if_noexists, remove_if_exists, intersection, geo_distance, idDocker, DotDict, TransferFunction, next_batch
from utils import k_shortest_paths, latlon2quadkey
pd.options.mode.chained_assignment = None
CLASS_COL = 'driver'
SET_NAMES = [(0, 'train'), (1, 'val'), (2, 'test')]
MIN_TRIP_LEN = 6
MAX_TRIP_LEN = 120
TRIP_COLS = ['tod', 'road', 'road_prop', 'lng', 'lat', 'weekday', 'seq_i', 'seconds']
DATASET_PATH = os.environ['DATASET_PATH']
META_PATH = os.environ['META_PATH']
class Data:
def __init__(self, name, road_type='road_network'):
self.name = name
self.base_path = META_PATH
self.dataset_path = DATASET_PATH
self.df_path = f'{self.dataset_path}/{self.name}.h5'
self.meta_dir = f'{self.base_path}/meta/{self.name}'
self.stat_path = f'{self.meta_dir}/stat_grid.h5' if road_type == 'grid' else f'{self.meta_dir}/stat.h5'
self.get_meta_path = lambda meta_type, select_set: os.path.join(
self.meta_dir, f'{meta_type}_' + \
('grid_' if road_type == 'grid' else '') + \
f'{select_set}.npz'
)
assert road_type in ['road_network', 'grid'], "road type must be road_network or grid"
self.road_type = road_type
""" Load functions for loading dataframes and meta. """
def read_hdf(self):
# Load the raw data from HDF files.
# One set of raw dataset is composed of one HDF file with four keys.
# The trips contains the sequences of trajectories, with three columns: trip, time, road
self.trips = pd.read_hdf(self.df_path, key='trips')
# The trip_info contains meta information about trips. For now, this is mainly used for class labels.
self.trip_info = pd.read_hdf(self.df_path, key='trip_info')
# The road_info contains meta information about roads.
self.road_info = pd.read_hdf(self.df_path, key='road_info')
# self.trips = pd.merge(self.trips, self.road_info[['road', 'lng', 'lat']], on='road', how='left')
self.network_info = None
self.network = None
# Convert time column to datetime if it's float
if pd.api.types.is_float_dtype(self.trips['time']):
self.trips['time'] = pd.to_datetime(self.trips['time'])
if self.road_type == 'grid':
self.project_to_grid()
# Add some columns to the trip
self.trips['seconds'] = self.trips['time'].apply(lambda x: x.timestamp())
self.trips['tod'] = self.trips['seconds'] % (24 * 60 * 60) / (24 * 60 * 60)
self.trips['weekday'] = self.trips['time'].dt.weekday
self.stat = self.trips.describe()
num_road = int(self.road_info['road'].max() + 1)
num_class = int(self.trip_info[CLASS_COL].max() + 1)
if self.road_type == 'grid':
self.data_info = pd.Series([num_road, num_class, self.num_w, self.num_h],
index=['num_road', 'num_class', 'num_w', 'num_h'])
else:
self.data_info = pd.Series([num_road, num_class], index=['num_road', 'num_class'])
print('Loaded DataFrame from', self.df_path)
self.num_road = num_road
num_trips = self.trip_info.shape[0]
self.train_val_test_trips = (self.trip_info['trip'].iloc[:int(num_trips * 0.8)],
self.trip_info['trip'].iloc[int(num_trips * 0.8):int(num_trips * 0.9)],
self.trip_info['trip'].iloc[int(num_trips * 0.9):])
create_if_noexists(self.meta_dir)
self.stat.to_hdf(self.stat_path, key='stat')
self.data_info.to_hdf(self.stat_path, key='info')
print(self.stat)
print(self.data_info)
print('Dumped dataset info into', self.stat_path)
self.valid_trips = [self.get_valid_trip_id(i) for i in range(3)]
def project_to_grid(self):
print("Project trips to grids, ", end='')
delta_degree = 0.0015
min_lng, max_lng = self.trips['lng'].min(), self.trips['lng'].max()
min_lat, max_lat = self.trips['lat'].min(), self.trips['lat'].max()
num_h = math.ceil((max_lat - min_lat) / delta_degree)
num_w = math.ceil((max_lng - min_lng) / delta_degree)
self.num_h = num_h
self.num_w = num_w
self.num_road = num_w * num_h
def _project_lng_to_w(lng):
return np.clip(np.ceil((lng - min_lng) / (max_lng - min_lng) * num_w) - 1, 0,
num_w - 1)
def _project_lat_to_h(lat):
return np.clip(np.ceil((lat - min_lat) / (max_lat - min_lat) * num_h) - 1, 0,
num_h - 1)
ws = self.trips['lng'].apply(_project_lng_to_w)
hs = self.trips['lat'].apply(_project_lat_to_h)
self.trips['road'] = [h * num_w + w for h, w in zip(hs, ws)]
road_lngs = np.arange(num_w) * delta_degree + delta_degree / 2 + min_lng
road_lats = np.arange(num_h) * delta_degree + delta_degree / 2 + min_lat
road_lngs = repeat(road_lngs, 'W -> (H W)', H=num_h)
road_lats = repeat(road_lats, 'H -> (H W)', W=num_w)
self.road_info = pd.DataFrame({
"road": list(range(num_w * num_h)),
"lng": road_lngs,
"lat": road_lats
})
def load_stat(self):
# Load statistical information for features.
self.stat = pd.read_hdf(self.stat_path, key='stat')
self.data_info = pd.read_hdf(self.stat_path, key='info')
def load_meta(self, meta_type, select_set):
meta_path = self.get_meta_path(meta_type, select_set)
loaded = np.load(meta_path, allow_pickle=True)
print('Loaded meta from', meta_path)
return list(loaded.values())
def build_network(self):
if self.network is None:
network = nx.Graph()
nodes = list(set(self.road_info['o'].unique()) | set(self.road_info['d'].unique()))
network.add_nodes_from(nodes)
# network.add_edges_from(self.network_info[['o', 'd']].to_numpy().astype(int),
# distance=self.network_info['length'].to_numpy().astype(float))
network.add_weighted_edges_from(self.road_info[['o', 'd', 'length']].to_numpy(), weight='length')
self.network = network
def get_valid_trip_id(self, select_set):
select_trip_id = self.train_val_test_trips[select_set]
trips = self.trips[self.trips['trip'].isin(select_trip_id)]
valid_trip_id = []
for _, group in tqdm(trips.groupby('trip'), desc='Filtering trips', total=select_trip_id.shape[0], leave=False):
if (not group.isna().any().any()) and group.shape[0] >= MIN_TRIP_LEN and group.shape[0] <= MAX_TRIP_LEN:
valid_trip_id.append(group.iloc[0]['trip'])
return valid_trip_id
def dump_meta(self, meta_type, select_set):
"""
Dump meta data into numpy binary files for fast loading later.
:param meta_type: type name of meta data to dump.
:param select_set: index of set to dump. 0 - training set, 1 - validation set, and 2 - testing set.
"""
# Prepare some common objects that will probably be useful for various types of meta data.
select_trip_id = self.valid_trips[select_set]
known_trips = self.trips[self.trips['trip'].isin(self.valid_trips[0] + self.valid_trips[1])]
trips = self.trips[self.trips['trip'].isin(select_trip_id)]
trip_info = self.trip_info[self.trip_info['trip'].isin(select_trip_id)]
max_trip_len = max(Counter(trips['trip']).values())
trip_normalizer = Normalizer(self.stat, feat_cols=[0, 2, 3, 4], norm_type='minmax')
if meta_type == 'trip':
"""
The "trip" meta data obeys the original form of trajectories.
One complete trajectory sequence is regarded as one trip.
"""
arrs, valid_lens = [], []
for _, group in tqdm(trips.groupby('trip'), desc='Gathering trips', total=len(select_trip_id)):
arr = group[TRIP_COLS].to_numpy()
valid_len = arr.shape[0]
offset = group['time'].apply(lambda x: x.timestamp()).to_numpy()
offset = (offset - offset[0]) / (offset[-1] - offset[0]) * 2 - 1
arr = np.append(arr, offset.reshape(-1, 1), 1)
# Pad all trips to the maximum length by repeating the last item.
arr = np.concatenate([arr, np.repeat(arr[-1:], max_trip_len - valid_len, axis=0)], 0)
arrs.append(arr)
valid_lens.append(valid_len)
# Features of arrs: TRIP_COLS + [offset]
arrs, valid_lens = np.stack(arrs, 0), np.array(valid_lens)
arrs = trip_normalizer(arrs)
meta = [arrs, valid_lens]
elif 'timemat' in meta_type:
"""
Construct time matrix of meta types
"""
params = meta_type.split('-')
params.remove('timemat')
sup_meta_type = '-'.join(params)
try:
trip_arrs, valid_lens = self.load_meta(sup_meta_type, select_set)[:2]
except FileNotFoundError:
raise FileNotFoundError("Dump meta type {} first.".format(sup_meta_type))
time_arrs = trip_arrs[:, :, 7] # seconds
meta = [gen_time_mat(time_arrs), ]
elif 'traj2vectime' in meta_type:
params = meta_type.split('-')
params.remove('traj2vectime')
sup_meta_type = '-'.join(params)
try:
trip_arrs, valid_lens = self.load_meta(sup_meta_type, select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta type {} first.".format(sup_meta_type))
road_list = trip_arrs[:, :, 1].astype(int)
time_arrs = trip_arrs[:, :, 7] # seconds
time_diff = time_arrs[:, 1:] - time_arrs[:, :-1]
time_diff = np.concatenate([np.zeros([len(time_arrs), 1]), time_diff], axis=1)
meta = [road_list, valid_lens, time_diff]
elif meta_type == 'class' or meta_type == 'classbatch':
"""
The "class" meta data provides classification label.
Typically, the label calculates from user or driver ID.
"""
classes = trip_info[CLASS_COL].to_numpy()
meta = [classes]
elif meta_type == 'tte':
"""
The "tte" meta data provides travel time estimation label.
The ground truth travel time is the time span of trajectories in minutes.
"""
travel_times = []
for _, row in tqdm(trip_info.iterrows(), desc='Gathering TTEs', total=trip_info.shape[0]):
travel_times.append((row['end'] - row['start']).total_seconds() / 60)
travel_times = np.array(travel_times)
meta = [travel_times]
elif 'resample' in meta_type:
"""
The "resample" meta data records the resampled version of "trip" meta data.
The trajectories is resampled along time axis given a certain sampling rate.
The last point of trajectories is always appended.
"""
# Parameters are given in the meta_type. Use format "resample-{sample_rate}"
params = meta_type.split('-')
# Sample rate (in minutes) of the sparse trajectories.
sample_rate = float(params[1])
# Resample trips, also gather road segment candidates based on spatial distance.
arrs, lengths = [], []
for _, group in tqdm(trips.groupby('trip'), desc='Resampling trips', total=len(select_trip_id)):
reindex_trip = group.reset_index().set_index('time')
resampled_trip = reindex_trip[~reindex_trip.index.duplicated()].resample(
rule=pd.Timedelta(sample_rate, 'seconds'), origin='start').asfreq()
resampled_trip = resampled_trip[resampled_trip['seq_i'].notnull()] # resample would result in Nan
resampled_arr = resampled_trip[TRIP_COLS].to_numpy()
# Append the last point of this trajectory if it is absent in the resampled trajectory.
if resampled_trip['seq_i'].iloc[-1] != group['seq_i'].iloc[-1]:
resampled_arr = np.append(resampled_arr, group.iloc[-1:][TRIP_COLS].to_numpy(), 0)
arrs.append(resampled_arr)
lengths.append(resampled_arr.shape[0])
lengths = np.array(lengths)
# Pad all resampled trips to the maximum length.
max_resampled_length = lengths.max()
# Features of resampled trips: TRIP_COL
arrs = np.stack([
np.concatenate([trip, np.repeat(trip[-1:], max_resampled_length - trip.shape[0], 0)], 0)
for trip in arrs], 0)
arrs = trip_normalizer(arrs)
meta = [arrs, lengths]
elif 'distcand' in meta_type:
"""
The "distcand" meta data records the distance candidates given a certain distance threshold in meters.
The road segments within the distance threshold of GPS points are recorded.
"""
# Parameters are given in the meta_type. Use format "distcand-{dist_thres}".
dist_thres = float(meta_type.split('-')[1])
# Prepare the coordinates of roads.
road_coors = self.road_info[['road', 'road_lng', 'road_lat']].to_numpy()
cand_seq = []
max_num_cand = 0
for _, group in tqdm(trips.groupby('trip'), desc='Finding distance candidates', total=len(select_trip_id)):
cand_row = []
for _, row in group.iterrows():
# Calculate the geographical distance between this GPS point and all road segments.
dist = geo_distance(row['lng'], row['lat'], road_coors[:, 1], road_coors[:, 2])
cand = road_coors[:, 0][dist <= dist_thres].astype(int).tolist()
max_num_cand = max(len(cand), max_num_cand)
cand_row.append(cand)
cand_seq.append(cand_row)
pad_seq = []
for cand_row in cand_seq:
cand_row = [cand + [-1] * (max_num_cand - len(cand)) for cand in cand_row]
pad_seq.append(cand_row + [cand_row[-1]] * (max_trip_len - len(cand_row)))
pad_seq = np.array(pad_seq).astype(int)
meta = [pad_seq]
elif 'knncand' in meta_type:
"""
The "knncand" meta data records the k-nearest neighbor candidates given a certain k value.
The road segments that are within the set of kNN of GPS points are recorded.
"""
# Parameters are given in the meta_type. Use format "knncand-{k}".
k = int(meta_type.split('-')[1])
# Prepare the coordinates of roads and the knn model.
road_coors = self.road_info[['road', 'road_lng', 'road_lat']].to_numpy()
knn = NearestNeighbors(n_neighbors=k)
knn.fit(road_coors[:, [1, 2]])
cand_seq = []
for _, group in tqdm(trips.groupby('trip'), desc='Finding knn candidates', total=len(select_trip_id)):
_, neighbors = knn.kneighbors(group[['lng', 'lat']].to_numpy())
cand_seq.append(neighbors)
pad_seq = []
for cand_row in cand_seq:
pad_seq.append(np.concatenate([cand_row, np.repeat(
cand_row[-1:], max_trip_len - cand_row.shape[0], 0)], 0))
pad_seq = np.stack(pad_seq, 0).astype(int)
meta = [pad_seq]
elif 'fromto' in meta_type:
"""
The "fromto" meta data records the next and previous road segments of trajectories.
"""
from_to_roads, valid_lengths = [], []
for _, group in tqdm(trips.groupby('trip'), desc='Gathering from-to sequences', total=len(select_trip_id)):
from_to_road = group[['road', 'seq_i']].to_numpy().astype(int)
from_to_road = np.stack([from_to_road[1:, 0], from_to_road[1:, 1],
from_to_road[:-1, 0], from_to_road[:-1, 1]], 1)
valid_length = from_to_road.shape[0]
from_to_road = np.append(
from_to_road, np.repeat(from_to_road[-1:], max_trip_len - 1 - valid_length, 0), 0)
from_to_roads.append(from_to_road)
valid_lengths.append(valid_length)
# Features of from_to_roads: [to_road_segments, to_seg_i, from_road_segments, from_seg_i]
from_to_roads = np.stack(from_to_roads, 0)
valid_lengths = np.array(valid_lengths)
meta = [from_to_roads, valid_lengths]
elif 'seqcand' in meta_type:
"""
The "seqcand" meta data record the sequential candidate mask given a certain maximum number of neighbors.
The road segments within the possible transfer candidates of the current point are recorded.
"""
# Parameters are given in the meta_type. Use format "seqcand-{nei_thres}".
nei_thres = int(meta_type.split('-')[1])
# Gather all possible transfer between road segments.
known_trip_trans = known_trips.shift(1).join(known_trips, lsuffix='_from', rsuffix='_to')
known_trip_trans = known_trip_trans[known_trip_trans['trip_from'] == known_trip_trans['trip_to']]
known_trip_trans = known_trip_trans[known_trip_trans['road_from'] != known_trip_trans['road_to']]
transfer_counter = Counter((int(row['road_from']), int(row['road_to']))
for index, row in known_trip_trans.iterrows())
transfer_pairs = pd.DataFrame([[l, r, v] for (l, r), v in transfer_counter.items()], columns=[
'road_from', 'road_to', 'freq'])
# Form the dicts of sequential candidates.
transfer_tos = {index: group.sort_values('freq', ascending=False)['road_to'].tolist()
for index, group in transfer_pairs.groupby('road_from')}
transfer_froms = {index: group.sort_values('freq', ascending=False)['road_from'].tolist()
for index, group in transfer_pairs.groupby('road_to')}
trip_trans = trips.shift(1).join(trips, lsuffix='_from', rsuffix='_to')
trip_trans = trip_trans[trip_trans['trip_from'] == trip_trans['trip_to']]
to_cand_seq, from_cand_seq = [], []
for _, group in tqdm(trip_trans.groupby('trip_from'), desc='Finding sequential candidates',
total=len(select_trip_id)):
to_cand_row, from_cand_row = [], []
for _, row in group.iterrows():
# Fetch sequential candidates and calculate corresponding masks.
to_cand = transfer_tos.get(row['road_from'], [row['road_from']])[:nei_thres]
from_cand = transfer_froms.get(row['road_to'], [row['road_to']])[:nei_thres]
to_cand_row.append(to_cand + [-1] * (nei_thres - len(to_cand)))
from_cand_row.append(from_cand + [-1] * (nei_thres - len(from_cand)))
to_cand_seq.append([[-1] * nei_thres] + to_cand_row)
from_cand_seq.append(from_cand_row + [[-1] * nei_thres])
pad_to_cand, pad_from_cand = [], []
for to_cand_row, from_cand_row in zip(to_cand_seq, from_cand_seq):
pad_to_cand.append(to_cand_row + [to_cand_row[-1]] * (max_trip_len - len(to_cand_row)))
pad_from_cand.append(from_cand_row + [from_cand_row[-1]] * (max_trip_len - len(from_cand_row)))
pad_to_cand = np.array(pad_to_cand).astype(int)
pad_from_cand = np.array(pad_from_cand).astype(int)
meta = [pad_to_cand, pad_from_cand]
elif 'mlm' in meta_type:
"""
Meta type corresponds to Masked Language Model-style pre-training.
"""
# Parameters are given in the meta_type. Use format "mlm-{sample_rate}".
params = meta_type.split('-')
sample_rate = float(params[1])
arrs, valid_lens = [], []
special_token_start = self.data_info['num_road']
for _, group in tqdm(trips.groupby('trip'), desc='Gathering MLM trips', total=len(select_trip_id)):
reindex_trip = group.reset_index().set_index('time')
resampled_trip = reindex_trip[~reindex_trip.index.duplicated()].resample(
rule=pd.Timedelta(sample_rate, 'seconds'), origin='start').asfreq()
resampled_trip = resampled_trip[resampled_trip['seq_i'].notnull()]
if resampled_trip['seq_i'].iloc[-1] != group['seq_i'].iloc[-1]:
resampled_trip = pd.concat([resampled_trip, group.iloc[[-1]]], axis=0)
group = group.set_index('seq_i')
group['token'] = group['road']
group.loc[resampled_trip['seq_i'], 'token'] = special_token_start
group = group.reset_index()
valid_len = group.shape[0]
# Features of MLM trips: TRIP_COL + 'token'
arr = group[TRIP_COLS + ['token']].to_numpy()
arr = np.concatenate([arr, np.repeat(arr[-1:], max_trip_len - valid_len, axis=0)], 0)
arrs.append(arr)
valid_lens.append(valid_len)
arrs, valid_lens = np.stack(arrs, 0), np.array(valid_lens)
meta = [arrs, valid_lens]
elif 'trim' in meta_type or 'shift' in meta_type:
"""
Trajectory Trimming Augmentation
"""
# Parameters are given in the meta_type. Use format "trim-{edit_ratio}".
params = meta_type.split('-')
augment_type = params[0]
edit_ratio = float(params[1])
if augment_type == 'trim':
data_augment_func = trim_traj
elif augment_type == 'shift':
data_augment_func = temporal_shift
else:
raise NotImplementedError("No augmentation strategy ", augment_type)
try:
trip_arr, valid_lens = self.load_meta('trip', select_set)
except:
raise ValueError("File {} does not exist, "
"please dump meta data 'trip' first.".format(self.get_meta_path('trip', select_set)))
trip_arr, valid_lens = data_augment_func(trip_arr, valid_lens, edit_ratio, time_index=7, padding=True)
meta = [trip_arr, valid_lens]
elif 'transprob' in meta_type:
"""
Loc transfer probability without adjacency.
"""
# Gather all possible transfer between road segments.
known_trip_trans = known_trips.shift(1).join(known_trips, lsuffix='_from', rsuffix='_to')
known_trip_trans = known_trip_trans[known_trip_trans['trip_from'] == known_trip_trans['trip_to']]
known_trip_trans = known_trip_trans[known_trip_trans['road_from'] != known_trip_trans['road_to']]
transfer_counter = Counter((int(row['road_from']), int(row['road_to']))
for index, row in known_trip_trans.iterrows())
transfer_pairs = pd.DataFrame([[l, r, v] for (l, r), v in transfer_counter.items()], columns=[
'road_from', 'road_to', 'freq'])
froms = []
tos = []
freqs = []
for index, group in transfer_pairs.groupby('road_from'):
for _, sample in group.iterrows():
froms.append(int(sample['road_from']))
tos.append(int(sample['road_to']))
freqs.append(float(sample['freq']) / max(1, sample['freq'].sum()))
edge_index = np.array([froms, tos])
trans_prob = np.array(freqs)[:, None]
meta = [edge_index, trans_prob]
elif 'trajsim' in meta_type:
Data_generator = Trajsim_data_generator(self.trips, meta_type, self.meta_dir)
Data_generator.create_vocal()
if not os.path.exists(Data_generator.VDpath):
Data_generator.create_dist()
src_arr, tgt_arr, mta_arr = Data_generator.create_data(trips, select_trip_id)
meta = [src_arr, tgt_arr, mta_arr]
elif 'detourtgt' in meta_type:
"""
Detour-based similar trajectory search using in START.
"""
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
self.build_network()
target_is, tgt_detoured_trips, tgt_detour_lens = [], [], []
for target_i, (_, group) in tqdm(enumerate(trips.groupby('trip')),
desc="Gathering detour positive meta",
total=len(select_trip_id)):
# Avoid multi traj points in one segment
group = group.loc[~group['road'].duplicated(), TRIP_COLS + ['time']]
group['seq_i'] = list(range(len(group)))
a, detour_len, detour = traj_detour(group, max_detour_amount=0.2, road_network=self.network,
road_info=self.road_info)
if a is None:
continue
else:
arr = a[TRIP_COLS].to_numpy()
offset = a['time'].apply(lambda x: x.timestamp()).to_numpy()
offset = (offset - offset[0]) / (offset[-1] - offset[0]) * 2 - 1
arr = np.append(arr, offset.reshape(-1, 1), 1)
tgt_detoured_trips.append(arr)
tgt_detour_lens.append(len(a))
target_is.append(target_i)
if len(tgt_detoured_trips) == num_target:
break
target_is = np.array(target_is)
tgt_detour_lens = np.array(tgt_detour_lens)
max_tgt_detour_len = tgt_detour_lens.max()
padded_detour_trips = []
for group in tgt_detoured_trips:
padded_detour_trips.append(np.concatenate(
[group, np.repeat(group[-1:], max_tgt_detour_len - group.shape[0], axis=0)], 0))
tgt_detoured_trips = np.stack(padded_detour_trips, 0)
tgt_detoured_trips = trip_normalizer(tgt_detoured_trips)
meta = [tgt_detoured_trips, tgt_detour_lens, target_is]
elif 'detourqry' in meta_type:
"""
Detour-based similar trajectory search using in START.
"""
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
try:
trip_arrs, valid_lens = self.load_meta('trip', select_set)
_, _, target_is = self.load_meta('detourtgt-{}-{}'.format(num_target, num_negative), select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta type trip and detourgtgt-{}-{} first."
.format(num_target, num_negative))
query_trips = trip_arrs[target_is, ...]
query_valid_lens = valid_lens[target_is, ...]
meta = [query_trips, query_valid_lens]
elif 'detourneg' in meta_type:
"""
Detour-based similar trajectory search using in START.
"""
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
self.build_network()
try:
_, _, target_is = self.load_meta(f'detourtgt-{num_target}-{num_negative}', select_set)
except FileNotFoundError:
raise FileNotFoundError(f"Dump meta detourtgt-{num_target}-{num_negative} first.")
neg_detoured_trips, neg_detour_lens = [], []
for target_i, (_, group) in tqdm(enumerate(trips.groupby('trip')),
desc="Gathering detour positive meta",
total=len(select_trip_id)):
if target_i <= target_is[-1]:
continue
# Avoid multi traj points in one segment
group = group.loc[~group['road'].duplicated(), TRIP_COLS + ['time']]
group['seq_i'] = list(range(len(group)))
a, detour_len, detour = traj_detour(group, max_detour_amount=0.2,
road_network=self.network, road_info=self.road_info)
if a is None:
continue
else:
arr = a[TRIP_COLS].to_numpy()
offset = a['time'].apply(lambda x: x.timestamp()).to_numpy()
offset = (offset - offset[0]) / (offset[-1] - offset[0]) * 2 - 1
arr = np.append(arr, offset.reshape(-1, 1), 1)
neg_detoured_trips.append(arr)
neg_detour_lens.append(len(a))
if len(neg_detoured_trips) == num_negative:
break
neg_detour_lens = np.array(neg_detour_lens)
max_neg_detour_len = neg_detour_lens.max()
padded_neg_detour_trips = []
for group in neg_detoured_trips:
padded_neg_detour_trips.append(np.concatenate(
[group, np.repeat(group[-1:], max_neg_detour_len - group.shape[0], axis=0)], 0))
neg_detoured_trips = np.stack(padded_neg_detour_trips, 0)
neg_detoured_trips = trip_normalizer(neg_detoured_trips)
meta = [neg_detoured_trips, neg_detour_lens]
elif 'hoptgt' in meta_type:
"""
Target set for hop-based similar trajectory search,
target: odd indices
"""
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
try:
trips, valid_lens = self.load_meta('trip', select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta type {} first.".format('trip'))
# target_valid_lens = np.ceil(valid_lens / 2).astype(int)
# target_trips = trips[:num_target, ::2, :]
target_trips, target_valid_lens, target_is = [], [], []
for i, (trip, valid_len) in tqdm(enumerate(zip(trips, valid_lens)),
desc="Gathering hop-based target samples",
total=len(valid_lens)):
if valid_len < 2:
continue
target_trip = trip[1::2]
target_trips.append(target_trip)
target_valid_lens.append(math.floor(valid_len / 2))
target_is.append(i)
if len(target_trips) == num_target:
break
target_trips = np.stack(target_trips, 0)
target_valid_lens = np.array(target_valid_lens)
target_is = np.array(target_is).astype(int)
meta = [target_trips, target_valid_lens, target_is]
elif 'hopqry' in meta_type:
"""
Query set for hop-based similar trajectory search,
query: even indices
"""
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
try:
_, _, target_is = self.load_meta('hoptgt-{}-{}'.format(num_target, num_negative), select_set)
trips, valid_lens = self.load_meta('trip', select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta type {} first.".format('trip'))
query_valid_lens = np.ceil(valid_lens / 2).astype(int)
query_trips = trips[target_is, ::2, :]
meta = [query_trips, query_valid_lens]
elif 'hopneg' in meta_type:
params = meta_type.split('-')
num_target = int(params[1])
num_negative = int(params[2])
try:
_, _, target_is = self.load_meta('hoptgt-{}-{}'.format(num_target, num_negative), select_set)
trips, valid_lens = self.load_meta('trip', select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta type trip and hoptgt-{}-{} first.".format(num_target, num_negative))
max_index = target_is[-1]
neg_trips = trips[max_index: max_index + num_negative]
neg_valid_lens = valid_lens[max_index: max_index + num_negative]
meta = [neg_trips, neg_valid_lens]
elif 'slice' in meta_type:
"""
Slice data augmentation,
Wang H, Feng J, Sun L, et al.
Abnormal trajectory detection based on geospatial consistent modeling. IEEE Access, 2020
"""
from utils import SDMSampleGenerator
params = meta_type.split('-')
window_size = int(params[1])
arrs = []
for _, group in tqdm(trips.groupby('trip'), desc="Gathering trip slices", total=len(select_trip_id)):
arr = group['road'].to_numpy().astype(int)
mask = [i for i in range(1, len(arr)) if arr[i] == arr[i - 1]]
unmask = [True if e not in mask else False for e in np.arange(len(arr))]
arr = arr[unmask]
valid_len = arr.shape[0]
end_index = valid_len - window_size + 1
index = 0
while index < end_index:
arrs.append(arr[index: index + window_size])
index += 1
arrs = np.stack(arrs, 0)
generator = SDMSampleGenerator(arrs, min_count=5)
sources = []
destinations = []
midways = []
negs = []
for arr in arrs:
source = arr[0]
destination = arr[-1]
midway = arr[1:-1]
for m in midway:
sources.append(source)
destinations.append(destination)
midways.append(m)
negs.append(generator.getNegatives(m, 5))
sources, destinations, midways, negs = [np.array(e) for e in (sources, destinations, midways, negs)]
meta = [sources, destinations, midways, negs]
elif 'trajimage' in meta_type:
params = meta_type.split('-')
threshold = int(params[1])
dest_pre_length = int(params[2]) if len(params) == 3 else None
images = []
for _, group in tqdm(trips.groupby('trip'), desc="Gathering traj images", total=len(select_trip_id)):
if dest_pre_length is not None:
group = group.loc[:len(group) - dest_pre_length, :]
image = np.zeros([self.num_h, self.num_w])
magntitudes = Counter(group['road'])
for road, count in magntitudes.items():
if count < threshold:
continue
h = road // self.num_w
w = road % self.num_w
image[h, w] = 1
images.append(image)
images = np.stack(images, axis=0)[:, None, ...] # (N, C, H, W)
meta = [images, ]
elif 'coccur' in meta_type:
"""
Co-occurrence in time window
"""
# Parameters are given in the meta_type. Use format "coccur-{window_size}".
params = meta_type.split('-')
window_size = int(params[1])
pos_samples = []
neg_samples = []
for _, group in tqdm(trips.groupby('trip'), desc='Gathering co-occurence pairs', total=len(select_trip_id)):
# Avoid multi traj points in one segment
group = group.loc[~group['road'].duplicated(), TRIP_COLS + ['time']]
group['seq_i'] = list(range(len(group)))
for t, row in group.iterrows():
window = group.loc[((group['time'] - row['time']).apply(lambda x: x.total_seconds()) <= window_size) &
((group['time'] - row['time']).apply(lambda x: x.total_seconds()) >= 0), 'road'].to_list()
if len(window) < 2:
continue
pos_pairs = np.array(list(combinations(window, 2)))
pos_samples.append(pos_pairs)
neg_pairs = deepcopy(pos_pairs)
neg_pairs[range(len(neg_pairs)), np.random.randint(2, size=len(neg_pairs))] = \
np.random.choice(list(set(self.road_info['road'].to_list()).difference(set(window))),
len(neg_pairs))
neg_samples.append(neg_pairs)
pos_samples = np.concatenate(pos_samples, axis=0)
neg_samples = np.concatenate(neg_samples, axis=0)
pos_df = pd.DataFrame(pos_samples, columns=['r1', 'r2'])
pos_df['coccur'] = 1
pos_df = pd.merge(pos_df, self.road_info[['road', 'level']], left_on='r1', right_on='road', how='left')
pos_df = pd.merge(pos_df, self.road_info[['road', 'level']], left_on='r2', right_on='road', how='left', suffixes=('_1', '_2'))
same_type = [1 if t1 == t2 else 0 for t1, t2 in zip(pos_df['level_1'], pos_df['level_2'])]
pos_df['type'] = same_type
neg_df = pd.DataFrame(neg_samples, columns=['r1', 'r2'])
neg_df['coccur'] = 0
neg_df = pd.merge(neg_df, self.road_info[['road', 'level']], left_on='r1', right_on='road', how='left')
neg_df = pd.merge(neg_df, self.road_info[['road', 'level']], left_on='r2', right_on='road', how='left',
suffixes=('_1', '_2'))
same_type = [1 if t1 == t2 else 0 for t1, t2 in zip(neg_df['level_1'], neg_df['level_2'])]
neg_df['type'] = same_type
meta = [pos_df.loc[:, ['r1', 'r2', 'coccur', 'type']].values,
neg_df.loc[:, ['r1', 'r2', 'coccur', 'type']].values]
elif 'road2vec' in meta_type:
"""
Road2Vec module, return the road segment embeddings.
"""
params = meta_type.split('-')
window_size = int(params[1])
embed_dim = int(params[2])
try:
pos_samples, neg_samples = self.load_meta('coccur-{}'.format(window_size), select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump coccur-{} first.".format(window_size))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
alpha_ = 0.9
road2vec = Road2Vec(self.num_road, embed_dim).to(device)
samples = np.concatenate([pos_samples, neg_samples], axis=0).astype(float)
coccur_criterion = torch.nn.BCELoss()
type_criterion = torch.nn.BCELoss()
optimizer = torch.optim.Adam(road2vec.parameters(), lr=1e-3)
mean_loss = float('inf')
loss_log = []
description = 'Road2Vec training, loss: %.4f'
with trange(100, desc=description % mean_loss, total=100) as pbar:
for epoch in pbar:
loss_log_epoch = []
np.random.shuffle(samples)
for batch in next_batch(samples, 512):
batch = torch.from_numpy(batch).long().to(device)
x = batch[:, :2]
logits = road2vec(x)
coccur_label = batch[:, 2].float()
type_label = batch[:, 3].float()
coccur_loss = coccur_criterion(logits, coccur_label)
type_loss = type_criterion(logits, type_label)
loss = alpha_ * coccur_loss + (1 - alpha_) * type_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_log_epoch.append(loss.item())
mean_loss = float(np.mean(loss_log_epoch))
pbar.set_description(description % mean_loss)
loss_log.append(mean_loss)
meta = [road2vec.embedding.weight.cpu().detach().numpy()]
elif 't2vec' in meta_type:
Data_generator = t2vec_data_generator(self.trips, meta_type, self.meta_dir)
num_out_region = Data_generator.make_vocab()
# Data_generator.create_dist()
if not os.path.exists(Data_generator.VDpath):
Data_generator.saveKNearestVocabs()
# Create dataset (Note: Padding operation is not performed here)
src_arr, tgt_arr, mta_arr = Data_generator.processe_data(trips, select_trip_id)
meta = [src_arr, tgt_arr, mta_arr]
elif 'timefea' in meta_type:
"""
Time features including week, day, hour, minute and seconds.
"""
try:
trip_arrs, valid_lens = self.load_meta('trip', select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta trip first.")
second_seq = trip_arrs[..., 7]
N, L = second_seq.shape
timestamps = [pd.to_datetime(e, unit='s') for e in second_seq.reshape(-1)]
week_seq = np.array([e.weekofyear for e in timestamps])
day_seq = np.array([e.dayofyear for e in timestamps])
hour_seq = np.array([e.hour for e in timestamps])
minute_seq = np.array([e.minute for e in timestamps])
second_seq = np.array([e.second for e in timestamps])
out_seq = np.stack([week_seq, day_seq, hour_seq, minute_seq, second_seq], -1).reshape([N, L, 5])
meta = [out_seq]
elif 'quadkey' in meta_type:
"""
Quadkey of road from hierarchical map gridding method.
"""
params = meta_type.split('-')
level = int(params[1])
try:
trip_arrs, valid_lens = self.load_meta('trip', select_set)
except FileNotFoundError:
raise FileNotFoundError("Dump meta trip first.")
N, L, E = trip_arrs.shape
min_lat, max_lat = trip_arrs[:, :, 4].min(), trip_arrs[:, :, 4].max()
min_lon, max_lon = trip_arrs[:, :, 3].min(), trip_arrs[:, :, 3].max()
quadkeys = [latlon2quadkey(lat, lon, level, min_lat, max_lat, min_lon, max_lon)
for lat, lon in zip(trip_arrs[..., 4].reshape(-1), trip_arrs[..., 3].reshape(-1))]
quadkeys = np.array([list(quadkey) for quadkey in quadkeys]).astype(int).reshape([N, L, -1])
meta = [quadkeys, valid_lens]
elif 'robustDAA' in meta_type:
params = meta_type.split('-')
width, height = int(params[1]), int(params[2]) # the width and height of the whole grid region
if len(params) > 3:
noise = float(params[3]) # the variance of gaussian noise added to trajectory
else:
noise = None
def trip2grid(trip: pd.DataFrame):
# records number of times that the moving object stays in the grid area.
grid_map = np.zeros((height,width),dtype=np.int32)
min_lng, min_lat = trip["lng"].min(), trip["lat"].min()
lng_span = trip["lng"].max()-trip["lng"].min()
lat_span = trip["lat"].max()-trip["lat"].min()
for i in trip.index:
xoffset = math.floor(width * (trip.loc[i]["lng"]-min_lng)/lng_span)
yoffset = math.floor(height * (trip.loc[i]["lat"]-min_lat)/lat_span)
# Ensure not out of bounds
xoffset = min(xoffset,width-1)
yoffset = min(yoffset,height-1)
grid_map[yoffset, xoffset] += 1 # Increment count for corresponding grid area
return grid_map
src_arrs, tgt_arrs = [], []
for _, group in tqdm(trips.groupby('trip'), desc='Gathering trips', total=len(select_trip_id)):
arr = group[['lng', 'lat']]
# Convert longitude and latitude to meters
arr[['lng', 'lat']] = arr.apply(lambda row: pd.Series(TransferFunction.lonlat2meters(row['lng'],row['lat'])), axis = 1)
# Add Gaussian noise to trajectory
if noise is not None:
noise_arr = arr.applymap(lambda x: x + random.gauss(mu=0,sigma=noise))
else:
noise_arr = arr.deepcopy()
grid_features = np.diagonal(trip2grid(arr))
noise_grid_features = np.diagonal(trip2grid(noise_arr))
# grid_features is of equal length, no padding needed
src_arrs.append(noise_grid_features)
tgt_arrs.append(grid_features)
src_arrs, tgt_arrs = np.stack(src_arrs,0),np.stack(tgt_arrs,0)
meta = [src_arrs, tgt_arrs]
elif 'speedacc' in meta_type:
"""