-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdataset.py
executable file
·2298 lines (1902 loc) · 91.7 KB
/
dataset.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
import pandas as pd
import pickle as pkl
import os
import numpy as np
import networkx as nx
import scipy
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
import utils
from sqlalchemy import TIMESTAMP
import math
import copy
from geopy.distance import vincenty
def apply_small_num(row, *args):
"""
Apply Function: Replace small number in the cell of Dataframe with np.nan
:param row: row in a pd.Dataframe
:param args: Variable length argument list.
:return: the modified row
"""
for i, link_i in enumerate(args[0]):
if row[link_i] < args[1]:
row[link_i] = np.nan
return row
def cvt_df_nan_2_list(df, cols, nb_bins):
"""
Convert any nan cell in a pd.Dataframe into zero array with length of nb_bins
:param df: pd.Dataframe, the target Dataframe
:param cols: list, list of column names
:param nb_bins: int, number of buckets for the histogram
:return: pd.Dataframe, the converted Dataframe.
"""
for col in cols:
df.loc[df[col].isnull(), col] = \
df.loc[df[col].isnull(), col].apply(
lambda x: np.zeros(nb_bins - 1))
return df
def apply_list(array_like):
"""
Convert the array like content into list
:param array_like (numpy.array or related):
:return: list: List format of the argument.
"""
return list(array_like.values)
def vel_list(array_like, edge_len):
"""
Convert the array like content into list
:param array_like (numpy.array or related):
:return: list: List format of the argument.
"""
if len(array_like) > 0:
vel_array = array_like.values[array_like.values > 0]
if len(vel_array) <= 0:
vel_array = []
else:
vel_array = edge_len / array_like.values
else:
vel_array = []
return list(vel_array)
def my_rolling_apply_list(frame, func, hist_range, window=1):
"""
Construct histogram in all cells
:param frame (pd.Dataframe): The source dataframe
:param func: The function need to be applied
:param link_len (double): the length of the current link
:param hist_range (np.array): the histogram buckets
:param window (int): The size of the window
:return: pd.Series
"""
index = frame.index[window - 1:]
values = [func(frame.iloc[i:i + window], hist_range)
for i in range(len(frame) - window + 1)]
return pd.Series(data=values, index=index).reindex(frame.index)
def my_rolling_apply_avg(frame, func, window=1):
"""
Construct average value in all cells
:param frame (pd.Dataframe): The source dataframe
:param window (int): The size of the window
:param func: The function need to be applied
:param link_len (double): the length of the current link
:return: pd.Series
"""
index = frame.index[window - 1:]
values = [func(frame.iloc[i:i + window])
for i in range(len(frame) - window + 1)]
return pd.Series(data=values, index=index).reindex(frame.index)
class DataSet(object):
def __init__(self, data_dir, base_dir, server_name, conf_dir, random_node,
cat_head, con_head, start_date, test_start_date, test_end_date,
data_rm_ratio=0.5,
source_ratio=0.5, sample_rate=5, windows_size=1, predict_size=4,
small_threshold=0.0, big_threshold=50.0, min_nb=5, unit=1609.34,
combo_random=True, num_combos=3):
self.data_dir = data_dir
self.base_dir = base_dir
self.random_node = random_node
self.min_nb = min_nb
self.unit = unit
self.num_combos = num_combos
self.combo_random = combo_random
self.engine = utils.connect_sql_server(server_name, conf_dir)
# Get a road graph with the max number of nodes
self.edges_adj, self.graph_edges = self.construct_road_graph()
self.data_rm_ratio = data_rm_ratio
self.source_ratio = source_ratio
self.data_rm = [int(len(self.graph_edges) * data_rm_ratio)]
self.data_needed = [len(self.graph_edges) - self.data_rm[0]]
self.nb_source = [int(len(self.graph_edges) * source_ratio)]
self.cat_head = cat_head
self.con_head = con_head
self.start_date = start_date
self.test_start_date = test_start_date
self.test_end_date = test_end_date
self.sample_rate = sample_rate
self.window_size = windows_size
self.predict_size = predict_size
self.small_threshold = small_threshold
self.big_threshold = big_threshold
self.scaler = MinMaxScaler().fit([[self.small_threshold],
[self.big_threshold]])
def construct_road_graph(self):
"""
Construct a edge-noded graph
:return: csr matrix, list of nodes
"""
edge_adj_file, edges_file = self._get_graph_file()
if os.path.exists(edge_adj_file) and os.path.exists(edges_file):
print("Reading road graph from existing file...")
print('{}\n{}'.format(edge_adj_file, edges_file))
with open(edge_adj_file, 'rb') as f:
edges_adj = pkl.load(f)
with open(edges_file, 'rb') as f:
edges = pkl.load(f)
else:
edge_dict_file = os.path.join(self.base_dir, 'edge_dict.pickle')
if os.path.exists(edge_dict_file):
with open(edge_dict_file, 'rb') as f:
edge_dict = pkl.load(f)
else:
print("Constructing road graph...")
edge_dict = self._get_edge_connection()
with open(edge_dict_file, 'wb') as f:
pkl.dump(edge_dict, f)
print("Construction Done! ")
selected_nodes = list(edge_dict.keys())
print("The number of nodes is ", len(selected_nodes))
edges_adj, edges = self._convert_edge_graph(
edge_dict, self.random_node)
final_selected_nodes = set(selected_nodes).intersection(edges)
print("Number of selected edge in "
"final edges is {0}/{1}".format(
len(final_selected_nodes), len(edges)))
with open(edge_adj_file, 'wb') as f:
pkl.dump(edges_adj, f)
with open(edges_file, 'wb') as f:
pkl.dump(edges, f)
return edges_adj, edges
def construct_node_graph(self):
"""
convert a graph from edge connections to node connection
:param random_node: bool, whether to random shuffle the data
:param engine: sqlalchemy sql server engine
:return:
dict_edge_node, a dictionary contains the mapping of edge node to real node
link_ids, list of link ids used in this road network
W, Adjacency matrix of the resulted graph
L, Laplacian matrix of the resulted graph
D, Degree matrix of the resulted graph
"""
path_directed_dict = os.path.join(
self.data_dir, 'dict_edge_node.pickle')
if not os.path.exists(path_directed_dict):
dict_edge_node = self.construct_dict_edge_node()
else:
with open(path_directed_dict, 'rb') as f_di_dict:
dict_edge_node = pkl.load(f_di_dict)
self.row_ind, self.col_ind = self.obtain_col_row(dict_edge_node)
# get a directed graph and convert it into undirected
di_graph = self.construct_DiGraph(dict_edge_node)
nodes = di_graph.nodes()
A = nx.adjacency_matrix(di_graph, nodes)
# convert adjacency to proximity matrix
A = A.todense()
# W = self.get_hop_proximity_matrix(di_graph, hop=2)
W = self.get_proximity_matrix(A)
W_row_sum = W.sum(axis=1)
D = np.diag(W_row_sum)
# W_row_sum = [sum(W.sum(axis=1).tolist(), [])]
# D = scipy.sparse.diags(W_row_sum, [0])
L = D - W
return dict_edge_node, self.graph_edges, W, L, D
def construct_dict_edge_node(self):
return self._construct_dict_edge_node()
def construct_DiGraph(self, dict_edg_node):
return self._construct_DiGraph(dict_edg_node)
def get_proximity_matrix(self, A):
"""
Get a proximity matrix from adjacency matrix
:param A: 2d dimension of array
:return: 2d numpy array
"""
assert A.ndim == 2
W = np.zeros(A.shape, dtype=np.float32)
m = np.sum(A)
for i in range(A.shape[0]):
for j in range(A.shape[1]):
W[i, j] = np.sum(A[i, :]) * np.sum(A[:, j]) / (2 * m)
return W
def get_df_vel(self):
print("Entering into constructing avg...")
if 'avg' in self.data_dir:
df_vel_path = os.path.join(self.data_dir, '..', '..', '..', '..')
else:
df_vel_path = os.path.join(self.data_dir, '..', '..', '..', '..', '..')
df_vel_file = os.path.join(df_vel_path, 'df_vel.pickle')
# Data of origin to all destinations.
if not os.path.exists(df_vel_file):
df_vel = self._construct_link_vel_list()
df_vel = df_vel.drop_duplicates('time')
with open(df_vel_file, 'wb') as f:
pkl.dump(df_vel, f)
else:
print("Reading generated df_vel.pickle file...")
with open(df_vel_file, 'rb') as f:
df_vel = pkl.load(f)
df_vel = df_vel.set_index('time')
return df_vel
def construct_speed_table(self):
"""
Construct an average travel speed of nodes within certain time range.
:param nodes: list, seg_ids that we are required.
:param sample_freq: str, sample rate.
:param write_db: bool, write the constructed results into database or not/
:return: Dataframe, table contains the avg travel speed of all nodes.
"""
df_link_vel = self._construct_link_vel_list()
# df_link_vel = self._convert_tt_vel(df_link_tt)
# Get the time_index and day of week
df_link_vel['time_index'] = (df_link_vel['time'].dt.hour * 60 / self.sample_rate +
df_link_vel['time'].dt.minute / self.sample_rate).astype(int)
df_link_vel['dayofweek'] = df_link_vel['time'].dt.dayofweek
return df_link_vel
def construct_estimation_df(self, method, window, hist_range=None):
df_vel_list = self.get_df_vel()
if method == 'avg':
df_vel_result = df_vel_list.apply(
my_rolling_apply_avg, axis=0,
args=(self.get_vel_avg_rolling,
window))
elif method == 'hist':
assert hist_range is not None
df_vel_result = df_vel_list.apply(
my_rolling_apply_list, axis=0,
args=(self.get_vel_hist_rolling,
hist_range, window))
else:
raise Exception("[!] Unkown method type: {}".format(method))
df_vel_result = df_vel_result.reset_index()
# Get the time_index and day of week
df_vel_result['time_index'] = (df_vel_result['time'].dt.hour * 60 / self.sample_rate +
df_vel_result['time'].dt.minute / self.sample_rate).astype(int)
df_vel_result['dayofweek'] = df_vel_result['time'].dt.dayofweek
return df_vel_result
def construct_count_df(self, method, window):
df_vel_list = self.get_df_vel()
df_count = df_vel_list.apply(
my_rolling_apply_avg, axis=0, args=(
self.get_vel_count_rolling, window))
df_count = df_count.reset_index()
return df_count
def construct_origin_df(self, method, window):
df_vel_list = self.get_df_vel()
df_count = df_vel_list.apply(
my_rolling_apply_avg, axis=0, args=(
self.get_vel_value_rolling, window))
df_count = df_count.reset_index()
return df_count
def get_vel_hist_rolling(self, pdSeries_like, hist_bin):
data_lists = pdSeries_like.values.flatten()
data_list = []
for i, item in enumerate(data_lists):
if type(item) == list or type(item) == np.ndarray:
for j, item_j in enumerate(item):
data_list.append(item_j)
else:
continue
# data_list = [item for sublist in data_lists for item in sublist]
# tt_array = pdSeries_like.values.flatten()
data_array = np.array(data_list)
data_keep = (data_array < self.big_threshold) & (
data_array >= self.small_threshold)
data_array = data_array[data_keep]
if len(data_array) < self.min_nb:
# print("length smaller than {}...".format(self.min_nb))
return np.nan
hist, bin_edges = np.histogram(data_array, hist_bin, density=True)
if np.isnan(hist).any():
print('nan hist returned!')
print('data', data_array)
print(hist)
return np.nan
hist *= hist_bin[1] - hist_bin[0]
return hist
def get_vel_avg_rolling(self, pdSeries_like):
data_lists = pdSeries_like.values.flatten()
data_list = []
for i, item in enumerate(data_lists):
if type(item) == list or type(item) == np.ndarray:
for j, item_j in enumerate(item):
data_list.append(item_j)
else:
continue
data_array = np.array(data_list)
data_keep = (data_array < self.big_threshold) & (
data_array >= self.small_threshold)
data_array = data_array[data_keep]
if len(data_array) < self.min_nb:
# print("length smaller than {}...".format(self.min_nb))
return np.nan
mean = np.nanmean(data_array)
f_mean = self.scaler.transform([[mean]])[0]
return f_mean
def get_vel_count_rolling(self, pdSeries_like):
data_lists = pdSeries_like.values.flatten()
data_list = []
for i, item in enumerate(data_lists):
if type(item) == list or type(item) == np.ndarray:
for j, item_j in enumerate(item):
data_list.append(item_j)
else:
continue
data_array = np.array(data_list)
data_keep = (data_array < self.big_threshold) & (
data_array >= self.small_threshold)
data_array = data_array[data_keep]
return len(data_array)
def get_vel_value_rolling(self, pdSeries_like):
data_lists = pdSeries_like.values.flatten()
data_list = []
for i, item in enumerate(data_lists):
if type(item) == list or type(item) == np.ndarray:
for j, item_j in enumerate(item):
data_list.append(item_j)
else:
continue
data_array = np.array(data_list)
data_keep = (data_array < self.big_threshold) & (
data_array >= self.small_threshold)
data_array = data_array[data_keep]
return list(data_array)
def convert_multi_channel_array(self, df_all_array, nb_bins):
multi_channel_array = []
all_shape = df_all_array.shape
for i in range(all_shape[0]):
channel_i = np.zeros((all_shape[1], nb_bins))
for j in range(all_shape[1]):
if pd.isnull([df_all_array[i, j]]).any():
continue
else:
for k in range(nb_bins):
channel_i[j, k] = df_all_array[i, j][k]
multi_channel_array.append(channel_i)
multi_channel_array = np.array(multi_channel_array)
return multi_channel_array
def categorical_trans_file(self, data, cat_head):
# make the training data categorical
les = {}
for i in range(data.shape[1]):
le = LabelEncoder()
data[:, i] = le.fit_transform(data[:, i])
les[cat_head[i]] = le
with open('les.pickle', 'wb') as f:
pkl.dump(les, f, -1)
return les, data
def prepare_est_pred_with_date(self, method, window, mode='prediction',
hist_range=None,
least=True, least_threshold=0.5):
if method == 'hist':
assert hist_range is not None
nb_bins = len(hist_range) - 1
elif method == 'avg':
nb_bins = 1
else:
raise Exception("[!] Unkown method: {}".format(method))
assert mode == 'prediction' or mode == 'estimation'
dict_normal_file = os.path.join(self.data_dir, 'dict_normal.pickle')
train_data_dict_file = os.path.join(
self.data_dir, 'train_data_dict.pickle')
validate_data_dict_file = os.path.join(
self.data_dir, 'validate_data_dict.pickle')
if os.path.exists(dict_normal_file) and os.path.exists(train_data_dict_file) \
and os.path.exists(validate_data_dict_file):
print("Reading feature from existing file...")
print('{}\n{}\n{}'.format(dict_normal_file,
train_data_dict_file,
validate_data_dict_file))
with open(dict_normal_file, 'rb') as f:
dict_normal = pkl.load(f)
with open(train_data_dict_file, 'rb') as f:
train_data_dict = pkl.load(f)
with open(validate_data_dict_file, 'rb') as f:
validate_data_dict = pkl.load(f)
else:
df_all = self.construct_estimation_df(
method, window=window, hist_range=hist_range)
# get the number of records
df_count = self.construct_count_df(method, window)
df_vel_list = self.construct_origin_df(method, window)
row_notnull = pd.notnull(df_all[self.graph_edges].values)
if least:
num_needed = int(len(self.graph_edges) * (1 - least_threshold))
else:
num_needed = len(self.graph_edges) - self.data_rm[0]
row_keep = row_notnull.sum(axis=1) >= num_needed
df_x_all = df_all[row_keep]
if mode == 'estimation':
df_y_all = df_x_all.copy()
df_count = df_count[row_keep]
df_vel_list = df_vel_list[row_keep]
else:
df_y_index = df_x_all.index + window
df_y_all = df_all.loc[df_y_index]
df_count = df_count.loc[df_y_index]
df_vel_list = df_vel_list.loc[df_y_index]
print("The dimension of the dataframe is {}".format(df_all.shape))
x_all_array = df_x_all[self.graph_edges].values
y_all_array = df_y_all[self.graph_edges].values
y_all_count = df_count[self.graph_edges].values
vel_list = df_vel_list[self.graph_edges].values
con_array = df_x_all[self.con_head].values
cat_array = df_x_all[self.cat_head].values.astype(np.int)
# position indicator of meaningful data
row_notnull = row_notnull[row_keep, :]
validate_row = (df_x_all['time'] > self.test_start_date) & \
(df_x_all['time'] < self.test_end_date)
training_row = validate_row == False
dict_normal = {}
# 2. max_min normalization for continuous data (wind speed,
# temperature)
for i, con_head_i in enumerate(self.con_head):
scaler_i = MinMaxScaler()
con_array[:, i] = scaler_i.fit_transform(con_array[:, i])
dict_normal[con_head_i] = scaler_i
# 3. categorical type data
les, cat_array = self.categorical_trans_file(
cat_array, self.cat_head)
dict_normal.update(les)
con_validate = con_array[validate_row, :]
cat_validate = cat_array[validate_row, :]
cat_train = cat_array[training_row, :]
con_train = con_array[training_row, :]
df_all_x_array = self.convert_multi_channel_array(
x_all_array, nb_bins)
df_all_y_array = self.convert_multi_channel_array(
y_all_array, nb_bins)
array_y_weight = np.zeros(row_notnull.shape, dtype=np.int8)
y_pos = np.sum(df_all_y_array, axis=2) > 0
array_y_weight[y_pos] = 1
df_all_x_array = self.construct_x_array(df_all_x_array, row_notnull)
x_train = df_all_x_array[training_row, :, :]
x_validate = df_all_x_array[validate_row, :, :]
y_validate = df_all_y_array[validate_row, :, :]
if mode == 'estimation':
y_train = x_train.copy()
train_y_pos = np.sum(y_train, axis=2) > 0
train_y_weight = np.zeros(train_y_pos.shape, dtype=np.int8)
train_y_weight[train_y_pos] = 1
val_y_pos = np.sum(x_validate, axis=2) > 0
val_y_weight = array_y_weight[validate_row, :]
val_y_weight[val_y_pos] = 0
y_validate[val_y_pos] = np.zeros(nb_bins)
else:
y_train = df_all_y_array[training_row, :, :]
train_y_weight = array_y_weight[training_row, :]
val_y_weight = array_y_weight[validate_row, :]
# get the count of records to construct histograms
y_train_count = y_all_count[training_row, :]
y_val_count = y_all_count[validate_row, :]
# get the original records
train_vel_list = vel_list[training_row, :]
val_vel_list = vel_list[validate_row, :]
train_data_dict = {'velocity_x': x_train,
'velocity_y': y_train,
'weight_y': train_y_weight,
'count_y': y_train_count,
'vel_list': train_vel_list,
'cat': cat_train,
'con': con_train}
validate_data_dict = {'velocity_x': x_validate,
'velocity_y': y_validate,
'weight_y': val_y_weight,
'count_y': y_val_count,
'vel_list': val_vel_list,
'cat': cat_validate,
'con': con_validate}
# write these three dict into files
dict_list = ['dict_normal',
'train_data_dict', 'validate_data_dict']
dicts = [dict_normal, train_data_dict, validate_data_dict]
for i, dict_i in enumerate(dict_list):
path_dict_i = os.path.join(self.data_dir, dict_i + '.pickle')
with open(path_dict_i, 'wb') as f:
pkl.dump(dicts[i], f)
if mode == 'estimation':
self.verify_data_correctness(train_data_dict, validate_data_dict)
else:
self.verify_pred_data_correctness(train_data_dict, validate_data_dict)
return dict_normal, train_data_dict, validate_data_dict
def construct_x_array(self, df_all_x_array, row_notnull):
"""random select num needed nodes with data"""
for i in range(row_notnull.shape[0]):
not_selected_bool = np.array([True] * len(self.graph_edges))
notnull_idx_i = np.where(row_notnull[i, :])[0]
num_needed = len(self.graph_edges) - self.data_rm[0]
if len(notnull_idx_i) < num_needed:
continue
rand_choice_idx = np.random.choice(
notnull_idx_i, num_needed, replace=False)
not_selected_bool[rand_choice_idx] = False
df_all_x_array[i, not_selected_bool] = 0
return df_all_x_array
def verify_data_correctness(self, train_data_dict, validate_data_dict):
"""verify the correctness of the estimation data"""
num_needed = len(self.graph_edges) - self.data_rm[0]
x_train = train_data_dict['velocity_x']
y_train = train_data_dict['velocity_y']
train_y_weight = train_data_dict['weight_y']
x_val = validate_data_dict['velocity_x']
y_val = validate_data_dict['velocity_y']
val_y_weight = validate_data_dict['weight_y']
x_train_sum2 = np.sum(x_train, axis=2)
assert np.sum(np.sum(x_train_sum2 > 0, axis=1) != num_needed) == 0
assert np.array_equal(x_train, y_train)
assert np.array_equal(x_train_sum2 > 0, train_y_weight == 1)
x_val_sum2 = np.sum(x_val, axis=2)
y_val_sum2 = np.sum(y_val, axis=2)
assert np.sum(np.sum(x_val_sum2>0, axis=1) != num_needed) == 0
assert np.array_equal(y_val_sum2>0, val_y_weight == 1)
def verify_pred_data_correctness(self, train_data_dict, validate_data_dict):
"""verify the correctness of the prediction data"""
num_needed = len(self.graph_edges) - self.data_rm[0]
x_train = train_data_dict['velocity_x']
y_train = train_data_dict['velocity_y']
train_y_weight = train_data_dict['weight_y']
x_val = validate_data_dict['velocity_x']
y_val = validate_data_dict['velocity_y']
val_y_weight = validate_data_dict['weight_y']
x_train_sum3 = np.sum(x_train, axis=2)
y_train_sum3 = np.sum(y_train, axis=2)
assert np.sum(np.sum(x_train_sum3 > 0, axis=1) != num_needed) == 0
assert np.array_equal(y_train_sum3 > 0, train_y_weight == 1)
x_val_sum3 = np.sum(x_val, axis=2)
y_val_sum3 = np.sum(y_val, axis=2)
assert np.sum(np.sum(x_val_sum3 > 0, axis=1) != num_needed) == 0
assert np.array_equal(y_val_sum3>0, val_y_weight==1)
def _get_graph_file(self):
return NotImplementedError
def _get_edge_connection(self):
return NotImplementedError
def _convert_edge_graph(self, edge_dict, random_node=False):
return NotImplementedError
def _construct_dict_edge_node(self):
return NotImplementedError
def _construct_DiGraph(self, dict_edg_node):
return NotImplementedError
def _construct_link_vel_list(self):
return NotImplementedError
def _construct_seq_data(self, df_vel, list_inters, nb_bins, combo_random=False):
"""
Construct sequence data with specified intervals
:param df_vel: Dataframe, source data
:param list_inters: list, specified intervals
:param combo_random: bool, default is False, prefer combinations
:return: np.arrays
"""
list_x_array = []
list_y_array = []
list_y_weight = []
list_con = []
list_cat = []
for inter_i in list_inters:
cur_inters = list(range(inter_i, inter_i + self.window_size))
cur_inters.append(int(inter_i + self.window_size + self.predict_size - 1))
# print("Now it's in {0}/{1}".format(test, len(list_inters)))
dt_series = pd.Series([pd.Timedelta(minutes=i * self.sample_rate)
for i in cur_inters])
dt_series += self.start_date
row_selected = df_vel.loc[dt_series, self.graph_edges].values
row_selected = self.convert_multi_channel_array(row_selected, nb_bins)
tmp_con = df_vel.loc[dt_series[0], self.con_head]
tmp_cat = df_vel.loc[dt_series[0], self.cat_head]
if combo_random:
list_x_array, list_y_array, list_y_weight = \
self._arange_data_random(row_selected, list_x_array,
list_y_array, list_y_weight)
list_con.append(tmp_con)
list_cat.append(tmp_cat)
else:
list_x_array, list_y_array, list_y_weight, com_num = \
self._arange_data_combos(row_selected, list_x_array,
list_y_array, list_y_weight)
list_con += [tmp_con] * com_num
list_cat += [tmp_cat] * com_num
x_array = np.array(list_x_array)
y_array = np.array(list_y_array)
y_weight = np.array(list_y_weight)
con_array = np.array(list_con)
cat_array = np.array(list_cat)
train_data_dict = {'velocity_x': x_array,
'velocity_y': y_array,
'weight_y': y_weight,
'cat': cat_array,
'con': con_array}
return train_data_dict
def _arange_data_random(self, row_selected, list_x_array,
list_y_array, list_y_weight):
"""
Process the data in a random order
:param row_selected:
:param list_x_array:
:param list_y_array:
:param list_y_weight:
:return:
"""
x_data = self.tailor_data_needed_single_random(row_selected[:self.window_size, :])
# print("The shape of the x_data after is ", x_data.shape)
y_weight, y_data = self.tailor_predicted_val_weights(
row_selected[self.window_size:, :])
list_x_array.append(x_data)
list_y_array.append(y_data)
list_y_weight.append(y_weight)
return list_x_array, list_y_array, list_y_weight
def _arange_data_combos(self, row_selected, list_x_array, list_y_array, list_y_weight):
"""
Process the data in a random order
:param row_selected:
:param list_x_array:
:param list_y_array:
:param list_y_weight:
:return:
"""
list_x_data = self.tailor_data_needed_combination(row_selected[:self.window_size, :])
# print("The shape of the x_data after is ", x_data.shape)
y_weight, y_data = self.tailor_predicted_val_weights(
row_selected[self.window_size:, :])
list_y_data = [y_data] * len(list_x_data)
list_y_weight_i = [y_weight] * len(list_x_data)
list_x_array += list_x_data
list_y_array += list_y_data
list_y_weight += list_y_weight_i
return list_x_array, list_y_array, list_y_weight, len(list_x_data)
def tailor_data_needed_combination(self, row_array):
row_notnull = pd.notnull(row_array)
combinations_list = [row_array]
for row_i in range(row_notnull.shape[0]):
notnull_idx_i = np.where(row_notnull[row_i, :])[0]
assert len(notnull_idx_i) >= self.data_needed[0]
if (len(notnull_idx_i) - self.data_needed[0] + 1) >= self.num_combos:
row_i_combos_num = self.num_combos
else:
row_i_combos_num = len(notnull_idx_i) - self.data_needed[0] + 1
prev_num_combinations = len(combinations_list)
combinations_list = combinations_list * row_i_combos_num
for i in range(row_i_combos_num):
combo_i = notnull_idx_i[i:self.data_needed[0] + i]
for prev_i in range(prev_num_combinations):
row_array_i = copy.copy(combinations_list[i*prev_num_combinations + prev_i])
not_selected_bool = np.array([True] * row_array.shape[1])
not_selected_bool[combo_i] = False
row_array_i[row_i, not_selected_bool] = 0
combinations_list[i*prev_num_combinations + prev_i] = row_array_i
return combinations_list
def tailor_data_needed_single_random(self, row_array):
row_notnull = pd.notnull(row_array)
for row_i in range(row_notnull.shape[0]):
not_selected_bool = np.array([True] * row_array.shape[1])
notnull_idx_i = np.where(row_notnull[row_i, :])[0]
rand_choice_idx = np.random.choice(
notnull_idx_i, self.data_needed[0], replace=False)
not_selected_bool[rand_choice_idx] = False
row_array[row_i, not_selected_bool] = 0
return row_array
def tailor_predicted_val_weights(self, row_array):
row_notnull = pd.notnull(row_array)
y_weight = np.zeros(row_notnull.shape, dtype=np.int)
y_weight[row_notnull] = 1
row_array[row_notnull == False] = 0.0
return y_weight, row_array
def get_effective_inters(self, df_all, least=True, least_threshold=0.5):
"""
Convert the dataframe of single origin to sequence data format.
:param df_all: pd.dataframe, average speed from single origin to all destinations.
:param least: bool, whether to keep all the data or not.
:param least_threshold: float, the threshold of the minimum percentage needed.
:return: list, "inter"s that meet the requirement of least threshold
"""
nb_rows = df_all.shape[0]
# select the destinations that meet the requirement
columns_selected = self.graph_edges.copy()
columns_selected.append('time')
df_all = df_all.loc[:, columns_selected]
df_all.loc[:, df_all.columns != 'time'] = \
df_all.loc[:, df_all.columns != 'time'].replace([np.inf, -np.inf], np.nan)
data_array = df_all.loc[:, df_all.columns != 'time'].values
print("The shape of data array is ", data_array.shape)
row_notnull = pd.notnull(data_array)
row_keep = np.array([True] * nb_rows)
tmp_row_notnull = row_notnull.copy()
df_all['inter'] = ((df_all['time'].dt.date -
self.start_date.date()).dt.days * (60 / self.sample_rate) * 24 +
df_all['time'].dt.hour * (60 / self.sample_rate) +
df_all['time'].dt.minute / self.sample_rate).astype(int)
# if least if true, a maximum least threshold should be met.
if least:
num_needed = len(self.graph_edges) - \
int(len(self.graph_edges) * least_threshold)
else:
num_needed = len(self.graph_edges) - self.data_rm[0]
# Since df_all contains one column of 'time', we need num_needed "+ 1" here.
curr_row_keep = tmp_row_notnull.sum(axis=1) >= num_needed
print("The maximum number of records is ", np.max(tmp_row_notnull.sum(axis=1)))
row_keep = np.logical_and(row_keep, curr_row_keep)
df_all = df_all[row_keep]
df_all = df_all.sort_values('inter', ascending=True)
start_inters = []
for i in range(df_all.shape[0] - self.window_size - self.predict_size):
start_ind = int(i)
end_ind = int(i+self.window_size)
train_pred_inters = list(range(start_ind, end_ind))
train_pred_inters.append(int(i+self.window_size+self.predict_size - 1))
inters = df_all.iloc[train_pred_inters]['inter'].tolist()
train_start_inter = inters[0]
train_end_inter = inters[-2]
predict_inter = train_end_inter + self.predict_size
if train_end_inter - train_start_inter + 1 == self.window_size \
and predict_inter == inters[-1]:
start_inters.append(train_start_inter)
return start_inters
def obtain_col_row(self, dict_edge_node):
row_indicator = []
col_indicator = []
# construct the indicator Ys for training and validating
for ind, link_i in enumerate(self.graph_edges):
if self.name == 'kdd':
node_y = dict_edge_node['{}_i'.format(link_i)]
node_x = dict_edge_node['{}_o'.format(link_i)]
row_indicator.append(node_y)
col_indicator.append(node_x)
else:
node_y = dict_edge_node[link_i.split('-')[0]]
node_x = dict_edge_node[link_i.split('-')[1]]
row_indicator.append(node_y)
col_indicator.append(node_x)
return row_indicator, col_indicator
def prepare_lsm_data(self, data_value, v_list=False):
assert data_value.ndim == 2 or data_value.ndim == 1
if data_value.ndim == 1:
data_value = np.expand_dims(data_value, -1)
nb_nodes = max(max(self.row_ind), max(self.col_ind)) + 1
ndim_data_value = data_value.shape[-1]
list_sp_matrix = []
validate_sum = 0
for dim_i in range(ndim_data_value):
if v_list:
dict_list = {}
for node_i in range(nb_nodes):
dict_list[node_i] = [[]] * nb_nodes
pd_list = pd.DataFrame(data=dict_list)
for ind, link_i in enumerate(self.graph_edges):
row_i = self.row_ind[ind]
col_i = self.col_ind[ind]
pd_list.at[row_i, col_i] = data_value[ind, dim_i]
list_sp_matrix.append(pd_list.values)
else:
values = []
for ind, link_i in enumerate(self.graph_edges):
values.append(data_value[ind, dim_i])
mean_matrix = scipy.sparse.csr_matrix(
(values, (self.row_ind, self.col_ind)),
shape=(nb_nodes, nb_nodes), dtype=np.float32)
validate_sum += np.sum(values)
list_sp_matrix.append(mean_matrix)
# print("data value is ", data_value)
# print("Sum of Data is ", np.sum(data_value))
# print("Validate sum is ", validate_sum)
if not v_list:
assert np.isclose(np.sum(data_value), validate_sum)
return list_sp_matrix
def prepare_lsm_learning_data(self, data, test_label, test_weight,
test_count, mean_y, test_vel_list):
"""
This function is specifically for preparing avg data transform
:param data: np.array (BZ, N, B)
:param test_label: np.array (BZ, N, B)
:param test_weight: np.array (BZ, N)
:param test_count: np.array (BZ, N)
:param dict_edge_node: dictionary = {node: ind}
:return:
"""
nb_rows = data.shape[0]
list_G_ts = []
list_trainY_ts = []
list_weight_ts = []
list_count_ts = []
list_val_weight_ts = []
list_vel_list_ts = []
for row_i in range(nb_rows):
data_i = data[row_i, ...]
test_label_i = test_label[row_i, ...]
test_weight_i = test_weight[row_i]
count_i = test_count[row_i]
vel_list_i = test_vel_list[row_i]
no_data_pos = np.sum(data_i, axis=-1) == 0.
in_data_ones = np.ones(test_weight_i.shape, dtype=np.int8)