-
Notifications
You must be signed in to change notification settings - Fork 7
/
step1_trip_processing.py
executable file
·3697 lines (3012 loc) · 113 KB
/
step1_trip_processing.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
# -*- coding: utf-8 -*-
from __future__ import division
__author__ = 'xu'
from joblib import Parallel, delayed
import multiprocessing
import os, sys
import operator
import pickle, csv, h5py
import copy, random
import time, datetime, pytz
import numpy as np
from scipy.interpolate import interp1d
from scipy.stats import gaussian_kde
from scipy import spatial
import networkx as nx
from scipy import optimize
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import rc
mpl.rc('font', family='Times New Roman')
mpl.rc('text', usetex=True)
import pandas as pd
import seaborn as sns
# sns.set(style="ticks", palette="pastel", color_codes=True)
# import vaex
import matplotlib.pyplot as plt
# plt.style.use('classic')
from matplotlib.colors import Normalize
from collections import Counter
from rtree import index
from scipy import spatial
from sklearn.cluster import DBSCAN
from sklearn.metrics import mean_squared_error
import geojson
from shapely.geometry import shape, mapping, Point
from shapely.ops import unary_union
import fiona
import itertools
from trajectory import Trajectory
from clustering import Clustering
# global variables
DallasTZ = pytz.timezone('US/Central')
if os.path.exists('/media/xu/Elements/Study/HuMNetLab/Data/Dallas/'):
dataPath = '/media/xu/Elements/Study/HuMNetLab/Data/Dallas/'
if os.path.exists('/home/xu/Data/Dallas/'):
dataPath = '/home/xu/Data/Dallas/'
if os.path.exists('/home/xu/Documents/Data/Dallas/'):
dataPath = '/home/xu/Documents/Data/Dallas/'
if os.path.exists('/global/scratch/yanyanxu/Data/Dallas/'):
dataPath = '/global/scratch/yanyanxu/Data/Dallas/'
if os.path.exists('/Volumes/TOSHIBA EXT/Study/HuMNetLab/Data/Dallas/'):
dataPath = '/Volumes/TOSHIBA EXT/Study/HuMNetLab/Data/Dallas/'
if os.path.exists('/media/Data4T/Dallas/'):
dataPath = '/media/Data4T/Dallas/'
# cityBoundary = [-97.490, -96.440, 32.630, 33.165]
# cityBoundary_forPlot = [-97.5, -96.5, 32.6, 33.2]
# cityBoundary = [-98.065, -95.855, 31.710, 33.430]
cityBoundary = [-98.0, -96.0, 32.0, 33.4]
cityBoundary_forPlot = [-98.0, -96.0, 32.0, 33.4]
'''
gridWidth = 0.005 # ~500m
numRowGrids = 343
numColGrids = 441
'''
gridWidth = 0.002 # ~200m
numRowGrids = 699
numColGrids = 999
boundaries = [(-97.22, -96.45, 32.71, 33.14),
(-97.22, -96.45, 32.71, 33.14),
(-97.47, -96.66, 32.64, 33.06),
(-97.47, -96.66, 32.64, 33.06)]
# calculate distance between two locations
def haversine(lat1, lon1, lat2, lon2):
R = 6372.8 # Earth radius in kilometers
dLat = np.radians(lat2 - lat1)
dLon = np.radians(lon2 - lon1)
a = np.sin(dLat/2)**2 + np.cos(np.radians(lat1))*np.cos(np.radians(lat2))*np.sin(dLon/2)**2
c = 2*np.arcsin(np.sqrt(a))
return R * c
def tripFilter(trip):
'''We define the following constrains to filter the trip:
-- 1. the diversity of directions between all continuous points (vectors). The direction
of a trip should be uniformed, otherwise it might be dispersive.
-- 2. the average speed between two continuous points with large displacement. The average
speed of a trip should be large enough (e.g., > 10 km/h), otherwise the user might stayed
at some places for a while.
--- 3. the duration between two continuous points is too large.'''
overallDisplacement = haversine(trip[0][2], trip[0][1], trip[-1][2], trip[-1][1])
overallDuration = (trip[-1][0] - trip[0][0])/3600.0 # hour
overallSpeed = overallDisplacement/overallDuration
displacements = []
speeds = []
durations = []
for t in range(len(trip)-1):
dist = haversine(trip[t][2], trip[t][1], trip[t+1][2], trip[t+1][1])
duration = (trip[t+1][0] - trip[t][0])/3600.0 # hour
speed = dist/duration
displacements.append(dist)
speeds.append(speed)
durations.append(duration)
# segment the trip by large duration (>0.5h)
durationThres = 0.3
displaceThres = 10
tripSegIdx = [i+1 for i in range(len(durations)) if durations[i] > durationThres]
tripSegIdx += [i + 1 for i in range(len(displacements)) if displacements[i] > displaceThres]
tripSegIdx = list(set(tripSegIdx))
tripSegIdx.sort()
# if len(tripSegIdx) == 0:
# return [trip]
subTrips = []
tripSegIdx = [0] + tripSegIdx + [len(trip)]
for i in range(len(tripSegIdx)-1):
subTrip = trip[tripSegIdx[i]: tripSegIdx[i+1]]
if len(subTrip) > 5:
subTrips.append(subTrip)
return subTrips
# refine trips segmentation
def tripSegmentation():
# load the data
sampleData = open(dataPath + "userData/allTrips_raw.csv", 'rb')
# header: userId, tripId, statingZone, targetZone, timestamp, lat, lon
count = 0
numTrips = 0
numTrips_refine = 0
preTripId = ''
preUserUd = ''
numPoints = []
trip = []
newTripId = 0
outDate = open(dataPath + "userData/allTrips_refine.csv", 'wb')
for row in sampleData:
count += 1
row = row.rstrip().split(',')
# print(row)
userId = int(row[0])
tripId = int(row[1])
ts = int(float(row[2]))
lon = float(row[3])
lat = float(row[4])
# print(userId, tripId, ts, lon, lat)
if preTripId == '':
preTripId = tripId
preUserUd = userId
if tripId != preTripId:
numTrips += 1
# process the last trip
numPoints.append(len(trip))
trip_ref = tripFilter(trip)
for tr in trip_ref:
numTrips_refine += 1
# save refined trip
for p in tr:
dts = int(p[0])
dts = datetime.datetime.fromtimestamp(dts, tz=DallasTZ)
ts_str = dts.strftime("%Y-%m-%d %H:%M:%S")
# userId, tripId, sZone, tZone, ts, lon, lat
row_save = [str(preUserUd), str(newTripId), ts_str, str(p[0]), str(p[1]), str(p[2])]
outDate.writelines(','.join(row_save) + '\n')
# update trip id
newTripId += 1
trip = []
preTripId = tripId
preUserUd = userId
trip.append((ts, lon, lat))
# the last trip
numTrips += 1
numPoints.append(len(trip))
trip_ref = tripFilter(trip)
for tr in trip_ref:
numTrips_refine += 1
# save refined trip
for p in tr:
dts = int(p[0])
dts = datetime.datetime.fromtimestamp(dts, tz=DallasTZ)
ts_str = dts.strftime("%Y-%m-%d %H:%M:%S")
# userId, tripId, sZone, tZone, ts, lon, lat
row_save = [str(userId), str(newTripId), ts_str, str(p[0]), str(p[2]), str(p[1])]
outDate.writelines(','.join(row_save) + '\n')
sampleData.close()
outDate.close()
print("# of records : ", count)
print("# of trips before refine : ", numTrips)
print("# of trips after refine : ", numTrips_refine)
# plot the distribution of numRecords
interval = 2
bins = np.linspace(0, 100, 51)
usagesHist = np.histogram(np.array(numPoints), bins)
bins = np.array(bins[1:])
usagesHist = np.divide(usagesHist[0], float(np.sum(usagesHist[0])))
print(usagesHist)
fig = plt.figure(figsize=(6, 4))
ax = plt.subplot(1, 1, 1)
plt.bar(bins.tolist(), usagesHist.tolist(), align='edge', width=interval, linewidth=1, facecolor='#41A7D8',
edgecolor='k',
label='data')
plt.xlim(0, 30)
plt.xticks(range(0, 100, 5))
plt.xlabel(r'# of records', fontsize=12)
plt.ylabel(r"Fraction", fontsize=12)
plt.tight_layout()
plt.savefig(dataPath + 'userData/numPoints_distribution.png', dpi=150)
plt.close()
# remove trips with point outside the boundary(id==-1)
def checkNumUsers():
tripData = open(dataPath + "userData/allTrips_selected.csv", 'r')
count = 0
preTripId = ''
numTrips = 0
allUsers = set()
for row in tripData:
count += 1
if count % 1e6 == 0:
print(count, len(allUsers), numTrips)
row = row.rstrip().split(',')
tripId = (row[0], row[1]) # (user, trip)
allUsers.add(int(row[0]))
if preTripId == '':
preTripId = tripId
if tripId != preTripId:
preTripId = tripId
numTrips += 1
# process the last trip
numTrips += 1
print("# users : ", len(allUsers))
print("# trips : ", numTrips)
def tripToVector(trip):
X = []
Y = []
U = []
V = []
for p in range(len(trip)-1):
currentP = trip[p]
nextP = trip[p+1]
u = nextP[1] - currentP[1]
v = nextP[2] - currentP[2]
# if np.sqrt(u**2 + v**2) < 0.002:
# continue
if np.sqrt(u**2 + v**2) > 0.1:
# print(currentP, nextP)
continue
X.append(currentP[1]+u)
Y.append(currentP[2]+v)
U.append(u)
V.append(v)
return X, Y, U, V
def inZone(p, idx, polygons, zoneId):
lon, lat = p
pt = Point(lon, lat)
zone = -1
# iterate through spatial index
for j in idx.intersection(pt.coords[0]):
if pt.within(shape(polygons[j]['geometry'])):
zone = int(polygons[j]['properties']['zone'])
if zoneId == zone:
return 1
else:
return 0
# count # trips per user, remove users with less trips < 20
def userFilter():
numTripsLim = 300
'''
# load the data
sampleData = open(dataPath + "userData/allTrips_grid.csv", 'rb')
# header: userId, tripId, datetime, timestamp, lon, lat, grid
count = 0
userTripIDs = {}
for row in sampleData:
count += 1
if count%1e6 == 0:
print(count)
row = row.rstrip().split(',')
# print(row)
userId = int(row[0])
tripId = int(row[1])
try:
userTripIDs[userId].add(tripId)
except:
userTripIDs[userId] = set([tripId])
sampleData.close()
print("# users in Dallas Area : ", len(userTripIDs))
print("Remove users with less than 30 trips...")
selectedUsers = []
for user in userTripIDs:
if len(userTripIDs[user]) >= numTripsLim:
selectedUsers.append(user)
print("# users selected %d / %d : %.2f" % (len(selectedUsers), len(userTripIDs), len(selectedUsers)/len(userTripIDs)))
pickle.dump(selectedUsers, open(dataPath + "userData/selectedUsers_" + str(numTripsLim) + ".pkl", 'wb'),
pickle.HIGHEST_PROTOCOL)
pickle.dump(userTripIDs, open(dataPath + "userData/userTripIDs.pkl", 'wb'),
pickle.HIGHEST_PROTOCOL)
'''
userTripIDs = pickle.load(open(dataPath + "userData/userTripIDs.pkl", 'rb'))
userTripCount = []
for user in userTripIDs:
userTripCount.append(len(userTripIDs[user]))
# plot distribution of # trips
counts = Counter(userTripCount)
counts_sorted = sorted(counts.items(), key=lambda item: item[1])
totalUsers = float(np.sum([i[1] for i in counts_sorted]))
frequency = [i[1] / totalUsers for i in counts_sorted][::-1]
# plot number of users larger than thres
bins = np.linspace(0, 1000, 1001)
hist = np.histogram(userTripCount, bins)
cdf = np.cumsum(hist[0])
cdf = [totalUsers-i for i in cdf]
fig = plt.figure()
plt.plot(range(len(cdf))[::5], cdf[::5], lw=0, marker='o',
markersize=5, markerfacecolor='w', markeredgecolor='#016450')
plt.xlabel("Threshold of number of trips, D", fontsize=16)
plt.ylabel("# users with more than D trips", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.xscale("log")
plt.yscale("log")
plt.tight_layout()
plt.savefig(dataPath + 'userData/userTrips_CDF.png', dpi=300)
plt.savefig(dataPath + 'userData/userTrips_CDF.pdf')
plt.close()
fig = plt.figure()
plt.plot(range(len(frequency) - 1)[::5], frequency[1:][::5], lw=0, marker='o',
markersize=5, markerfacecolor='w', markeredgecolor='#016450')
plt.xlabel("# trips", fontsize=16)
plt.ylabel("Fraction (%)", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.xscale("log")
plt.yscale("log")
plt.tight_layout()
plt.savefig(dataPath + 'userData/userTrips_log.png', dpi=300)
plt.savefig(dataPath + 'userData/userTrips_log.pdf')
plt.close()
fig = plt.figure()
plt.plot(range(len(frequency) - 1)[::5], frequency[1:][::5], lw=0, marker='o',
markersize=5, markerfacecolor='w', markeredgecolor='#016450')
plt.xlabel("# trips", fontsize=16)
plt.ylabel("Fraction (%)", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.savefig(dataPath + 'userData/userTrips.png', dpi=300)
plt.savefig(dataPath + 'userData/userTrips.pdf')
plt.close()
selectedUsers = []
for user in userTripIDs:
if len(userTripIDs[user]) >= numTripsLim:
selectedUsers.append(user)
selectedUsers = set(selectedUsers)
print("# selected users : ", len(selectedUsers))
print("# users selected %d / %d : %.2f" % (
len(selectedUsers), len(userTripIDs), len(selectedUsers) / len(userTripIDs)))
return 0
# load the data
sampleData = open(dataPath + "userData/allTrips_grid.csv", 'rb')
outData = open(dataPath + "userData/allTrips_grid_clean.csv", 'wb')
# header: userId, tripId, datetime, timestamp, lon, lat, grid
count = 0
for row in sampleData:
count += 1
if count % 1e6 == 0:
print(count)
row = row.rstrip().split(',')
# print(row)
userId = int(row[0])
if userId not in selectedUsers:
continue
outData.writelines(','.join(row) + "\n")
sampleData.close()
outData.close()
print("# users selected %d / %d : %.2f" % (
len(selectedUsers), len(userTripIDs), len(selectedUsers) / len(userTripIDs)))
# plot user origin and destinations
def userOriginDestination():
# load the data
'''
sampleData = open(dataPath + "userData/allTrips_grid_clean.csv", 'rb')
tripData = open(dataPath + "userData/allUser_tripInf.csv", "wb")
tripData.writelines("user,tripID,sLon,sLat,tLon,tLat,traveltime\n")
# header: userId, tripId, datetime, timestamp, lon, lat, grid
count = 0
preTripId = ''
trip = []
numTrips = 0
removeUserTrip = set()
for row in sampleData:
count += 1
if count%1e6==0:
print(count, numTrips, len(removeUserTrip))
row = row.rstrip().split(',')
# print(row)
tripId = (row[0], row[1]) # (user, trip)
ts = int(float(row[3]))
lon = row[4]
lat = row[5]
# print(userId, tripId, ts, lon, lat)
if preTripId == '':
preTripId = tripId
if tripId != preTripId:
# process the last trip
traveltime = (trip[-1][0] - trip[0][0]) / 60.0 # min
if traveltime < 0:
traveltime += 24*60
if len(trip) > 5 and traveltime > 0 and traveltime < 120:
startX = trip[0][1]
targetX = trip[-1][1]
startY = trip[0][2]
targetY = trip[-1][2]
# save
row_save = [preTripId[0], preTripId[1], startX, startY, targetX, targetY, "%.2f" % traveltime]
tripData.writelines(','.join(row_save) + "\n")
numTrips += 1
else:
removeUserTrip.add(preTripId)
trip = []
preTripId = tripId
trip.append((ts, lon, lat))
# the last trip
# process the last trip
traveltime = (trip[-1][0] - trip[0][0]) / 60.0 # min
if traveltime < 0:
traveltime += 24 * 60
if len(trip) > 5 and traveltime > 0 and traveltime < 120:
startX = trip[0][1]
targetX = trip[-1][1]
startY = trip[0][2]
targetY = trip[-1][2]
# save
row_save = [tripId[0], tripId[1], startX, startY, targetX, targetY, "%.2f" % traveltime]
tripData.writelines(','.join(row_save) + "\n")
numTrips += 1
else:
removeUserTrip.add(tripId)
sampleData.close()
tripData.close()
print("# of kept trips : ", numTrips)
print("# of removed trips : ", len(removeUserTrip))
pickle.dump(removeUserTrip, open(dataPath + "userData/removeUserTrip.pkl", 'wb'), pickle.HIGHEST_PROTOCOL)
'''
'''
removeUserTrip = pickle.load(open(dataPath + "userData/removeUserTrip.pkl", 'rb'))
sampleData = open(dataPath + "userData/allTrips_grid_clean.csv", 'rb')
outData = open(dataPath + "userData/allTrips_selected.csv", 'wb')
removedIDs = {}
for userTrip in removeUserTrip:
user, trip = userTrip
try:
removedIDs[user].add(trip)
except:
removedIDs[user] = set(trip)
count = 0
for row in sampleData:
count += 1
if count % 1e6 == 0:
print(count)
row = row.rstrip().split(',')
# print(row)
user = row[0]
trip = row[1]
if user in removedIDs:
if trip in removedIDs[user]:
continue
else:
pass
outData.writelines(','.join(row) + "\n")
sampleData.close()
outData.close()
'''
sampleData = open(dataPath + "userData/allTrips_cleanTrips.csv", 'rb')
tripData = open(dataPath + "userData/allUser_tripInf.csv", "wb")
tripData.writelines("user,tripID,depTime,arrTime,sLon,sLat,tLon,tLat,traveltime\n")
# header: userId, tripId, datetime, timestamp, lon, lat, grid
count = 0
preTripId = ''
trip = []
daytimes = []
numTrips = 0
for row in sampleData:
count += 1
if count % 1e6 == 0:
print(count, numTrips)
row = row.rstrip().split(',')
# print(row)
tripId = (row[0], row[1]) # (user, trip)
daytime = row[2]
ts = int(float(row[3]))
lon = row[4]
lat = row[5]
# print(userId, tripId, ts, lon, lat)
if preTripId == '':
preTripId = tripId
if tripId != preTripId:
# process the last trip
traveltime = (trip[-1][0] - trip[0][0]) / 60.0 # min
if traveltime < 0:
traveltime += 24 * 60
if len(trip) > 5 and traveltime > 0 and traveltime < 120:
depTime = daytimes[0]
arrTime = daytimes[-1]
startX = trip[0][1]
targetX = trip[-1][1]
startY = trip[0][2]
targetY = trip[-1][2]
# save
row_save = [preTripId[0], preTripId[1], depTime, arrTime, startX, startY, targetX, targetY, "%.2f" % traveltime]
tripData.writelines(','.join(row_save) + "\n")
numTrips += 1
trip = []
daytimes = []
preTripId = tripId
trip.append((ts, lon, lat))
daytimes.append(daytime)
# the last trip
# process the last trip
traveltime = (trip[-1][0] - trip[0][0]) / 60.0 # min
if traveltime < 0:
traveltime += 24 * 60
if len(trip) > 5 and traveltime > 0 and traveltime < 120:
depTime = daytimes[0]
arrTime = daytimes[-1]
startX = trip[0][1]
targetX = trip[-1][1]
startY = trip[0][2]
targetY = trip[-1][2]
# save
row_save = [tripId[0], tripId[1], depTime, arrTime, startX, startY, targetX, targetY, "%.2f" % traveltime]
tripData.writelines(','.join(row_save) + "\n")
numTrips += 1
sampleData.close()
tripData.close()
def plotOneTrace(trip, tripId, zonePair):
X = [t[1] for t in trip]
Y = [t[2] for t in trip]
minLon, maxLon = boundaries[zonePair][:2]
minLat, maxLat = boundaries[zonePair][2:]
fig = plt.figure()
plt.plot(X, Y, color='r', marker='o', markersize=3, lw=2)
plt.title(str(tripId), fontsize=18)
plt.xlim(minLon, maxLon)
plt.ylim(minLat, maxLat)
plt.xlabel("Longitude", fontsize=16)
plt.ylabel("Latitude", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.savefig(dataPath + "Traces/" + str(tripId).zfill(5) + ".png", dpi=150)
plt.close()
def plotOneTraceInGrid(trip, tripId, zonePair, gridCentroids, cityBlocks):
X = [t[1] for t in trip]
Y = [t[2] for t in trip]
minLonZone, maxLonZone = boundaries[zonePair][:2]
minLatZone, maxLatZone = boundaries[zonePair][2:]
X_grid = []
Y_grid = []
gridList = []
# find the associated block
for i in range(len(X)):
lon = X[i]
lat = Y[i]
minLon = int(lon * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLon = round(minLon / float(1000), 3)
maxLon = round(minLon + gridWidth, 3)
minLat = int(lat * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLat = round(minLat / float(1000), 3)
maxLat = round(minLat + gridWidth, 3)
try:
blockId = cityBlocks[(minLon, maxLon, minLat, maxLat)]
if len(gridList)>0:
if blockId!=gridList[-1]:
gridList.append(blockId)
else:
gridList.append(blockId)
except:
continue
for grid in gridList:
cenLon, cenLat = gridCentroids[grid]
X_grid.append(cenLon)
Y_grid.append(cenLat)
fig = plt.figure()
plt.plot(X_grid, Y_grid, color='g', marker='o', markersize=3, lw=2)
plt.title(str(tripId), fontsize=18)
plt.xlim(minLonZone, maxLonZone)
plt.ylim(minLatZone, maxLatZone)
plt.xlabel("Longitude", fontsize=16)
plt.ylabel("Latitude", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.savefig(dataPath + "Traces/" + str(tripId).zfill(5) + "_grid.png", dpi=150)
plt.close()
def plotGridTrip(gridList, tripId, zonePair, gridCentroids):
# minLonZone, maxLonZone = boundaries[zonePair][:2]
# minLatZone, maxLatZone = boundaries[zonePair][2:]
X_grid = []
Y_grid = []
trip = []
for grid in gridList:
cenLon, cenLat = gridCentroids[grid]
X_grid.append(cenLon)
Y_grid.append(cenLat)
trip.append((cenLon, cenLat))
'''
fig = plt.figure()
plt.plot(X_grid, Y_grid, color='k', marker='o', markersize=3, lw=2)
plt.title(str(tripId), fontsize=18)
plt.xlim(minLonZone, maxLonZone)
plt.ylim(minLatZone, maxLatZone)
plt.xlabel("Longitude", fontsize=16)
plt.ylabel("Latitude", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.savefig(dataPath + "Traces/" + str(tripId).zfill(5) + "_gridRefine_cutoff.png", dpi=150)
plt.close()
'''
return trip
# trip: [(lon1, lat1), (lon2, lat2),...]
def subTripHighRes(trip):
displacements = []
durations = []
for t in range(len(trip) - 1):
dist = np.sqrt(np.square(trip[t][0]-trip[t+1][0]) + np.square(trip[t][1]-trip[t+1][1]))
duration = (trip[t + 1][0] - trip[t][0]) / 3600.0 # hour
displacements.append(dist)
durations.append(duration)
# segment the trip by large duration (1min)
durationThres = 1/60.0
displaceThres = 0.01 # ~2500m
tripSegIdx = [i + 1 for i in range(len(durations)) if durations[i] > durationThres]
tripSegIdx += [i + 1 for i in range(len(displacements)) if displacements[i] > displaceThres]
tripSegIdx = list(set(tripSegIdx))
tripSegIdx.sort()
subTrips = []
tripSegIdx = [0] + tripSegIdx + [len(trip)]
for i in range(len(tripSegIdx) - 1):
subTrip = trip[tripSegIdx[i]: tripSegIdx[i + 1]]
if len(subTrip) > 5:
subTrips.append(subTrip)
return subTrips
# generate continuous grid lists in a trip
def subTripHighRes_grid(trip, cityBlocks):
X = [t[0] for t in trip]
Y = [t[1] for t in trip]
gridList = []
# find the associated block
for i in range(len(X)):
lon = X[i]
lat = Y[i]
minLon = int(lon * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLon = round(minLon / float(1000), 3)
maxLon = round(minLon + gridWidth, 3)
minLat = int(lat * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLat = round(minLat / float(1000), 3)
maxLat = round(minLat + gridWidth, 3)
try:
blockId = cityBlocks[(minLon, maxLon, minLat, maxLat)]
if len(gridList) > 0:
if blockId != gridList[-1]:
gridList.append(blockId)
else:
gridList.append(blockId)
except:
continue
# if the grids in list is continuous (the next grid is in the 8-neighbour of the previous one)
tripSegIdx = []
for g in range(len(gridList)-1):
preG = gridList[g]
nextG = gridList[g+1]
neighbours = neighbourGrids(preG, w=2)
if nextG not in neighbours:
tripSegIdx.append(g+1)
tripSegIdx = [0] + tripSegIdx + [len(gridList)]
subGridLists = []
for i in range(len(tripSegIdx) - 1):
subTrip = gridList[tripSegIdx[i]: tripSegIdx[i + 1]]
if len(subTrip) > 5:
subGridLists.append(subTrip)
return subGridLists
def neighbourGrids(gridId, w=2):
neighbours = []
for i in range(-w,w+1):
for j in range(-w,w+1):
neighbours.append(gridId+j*numRowGrids+i)
return set(neighbours)
# convert high resolutional trip to a list of grid
def tripToGrids(trip):
X = [t[0] for t in trip]
Y = [t[1] for t in trip]
gridList = []
# find the associated block
for i in range(len(X)):
lon = X[i]
lat = Y[i]
'''
minLon = int(lon * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLon = round(minLon / float(1000), 3)
maxLon = round(minLon + gridWidth, 3)
minLat = int(lat * 1000) // int(gridWidth * 1000) * int(gridWidth * 1000)
minLat = round(minLat / float(1000), 3)
maxLat = round(minLat + gridWidth, 3)
try:
blockId = cityBlocks[(minLon, maxLon, minLat, maxLat)]
if len(gridList)>0:
if blockId!=gridList[-1]:
gridList.append(blockId)
else:
gridList.append(blockId)
except:
continue
'''
colIdx = int((lon - cityBoundary[0]) / gridWidth)
rowIdx = int((lat - cityBoundary[2]) / gridWidth)
blockId = numRowGrids * colIdx + rowIdx
if len(gridList) > 0:
if blockId != gridList[-1]:
gridList.append(blockId)
else:
gridList.append(blockId)
return gridList
# we keep the original trace if can not find highRes subtrips to fillup
def fillupGrids(preG, nextG, highResTrips):
minG = min(preG, nextG)
maxG = max(preG, nextG)
gridList = []
# find the candidate trip from highResTrips
tripCandinates = []
for trip in highResTrips:
if len(trip) < 3:
continue
if max(trip) < minG - numRowGrids - 2:
continue
if min(trip) > maxG + numRowGrids + 2:
continue
# are there nearest grids for both preG and nextG
preFlag = 0
nextFlag = 0
if preG in trip and nextG in trip:
tripCandinates.append(trip)
preIdx = trip.index(preG)
nextIdx = trip.index(nextG)
gridList = trip[preIdx:nextIdx]
return gridList
# try w=1
for g in range(len(trip)):
grid = trip[g]
neighbours = neighbourGrids(grid, w=1)
if preG in neighbours:
preFlag = 1
preIdx = g
if nextG in neighbours:
nextFlag = 1
nextIdx = g
if preFlag==1 and nextFlag==1:
gridList = trip[preIdx:nextIdx]
return gridList
# try w=1
for g in range(len(trip)):
grid = trip[g]
neighbours = neighbourGrids(grid, w=2)
if preG in neighbours:
preFlag = 1
preIdx = g
if nextG in neighbours:
nextFlag = 1
nextIdx = g
if preFlag == 1 and nextFlag == 1:
gridList = trip[preIdx:nextIdx]
return gridList
return [nextG]
def completeLowResTrip(trip, highResTrips):
# if the grids of the trip are not continuous (in 8-Neighbour)
gridList = tripToGrids(trip)
fullTrip = [gridList[0]]
for g in range(len(gridList)-1):
preG = gridList[g]
nextG = gridList[g+1]
neighbours = neighbourGrids(preG,w=2)
if nextG not in neighbours:
# try to fill up the grids
subTrip = fillupGrids(preG, nextG, highResTrips)
fullTrip.extend(subTrip)
else:
fullTrip.append(nextG)
return fullTrip
# number of trips per user
def numTripsPerUser():
totalRows = 728463382
testFraction = 0.1
numUsers = 1e5
'''
inFile = dataPath + "userData/allTrips_topOD.csv"
inData = open(inFile, 'rb')
numTrips_perUser = {} # number of trips per user in out dataset
preUserTrip = ""
traj = []
# users = set()
count = 0
for row in inData:
count += 1
if count % 1e5 == 0:
print(count)
row = row.rstrip().split(',')
user = int(row[0])
tripId = int(row[1])
userTrip = (user, tripId)
# users.add(user)
# if len(users) > numUsers:
# break
# lon = float(row[4])
# lat = float(row[5])
if preUserTrip == "":
preUserTrip = userTrip
# a new trip
if preUserTrip != userTrip:
try:
numTrips_perUser[preUserTrip[0]] += 1
except:
numTrips_perUser[preUserTrip[0]] = 1
# traj = []
preUserTrip = userTrip
# traj.append([lon, lat])
inData.close()