/
GPSData.py
983 lines (591 loc) · 21.7 KB
/
GPSData.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
"""Base class to save a GPS dataset."""
import GPS_module as gps
import basic_module as bam
import plot_module as pm
import stats_module
from window import window,windowSet
import numpy as np
from datetime import datetime
import matplotlib.cm as cmap
import matplotlib.pyplot as plt
class GPSData:
def __init__(self,ID,color='r'):
self.ID=ID
self.date=[]
self.lon=[]
self.lat=[]
self.color=color
self.Windows=[]
def readData(self,header,data,fixLon=True):
"""Reads data from array.
Reads in data and subsequently standardizes data and finally computes movement stats.
Args:
header (list): Header list.
data (nunmpy.ndarray): Array with GPS data.
Keyword Args:
fixLon (bool): Fixes sign error in longitude of GPS data.
"""
idx=np.where(data[:,header.index("id")].astype(int)==self.ID)[0]
self.date=data[:,header.index("date")][idx] # Still need to convert this to datetime
self.lat=data[:,header.index("lat")].astype(float)[idx]
self.lon=data[:,header.index("lon")].astype(float)[idx]
if fixLon and max(self.lon)>180:
self.lon=self.lon-360.
self.standardizeData()
self.computeMoveStats()
#self.findRestPeriods(meth='kMeans')
#self.findRestPeriods(meth='thresh')
def standardizeData(self):
"""Standardizes data by converting data to cartesian coordinates, distances between coordinates and timestamps to datetime objects.
"""
self.toCartesian()
self.computeDistances()
self.toDateTime()
def computeMoveStats(self):
"""Computes basic stats of GPS data.
Including:
* Duration of timesteps.
* Velocities.
* Movement angles.
"""
self.computeDeltaT()
self.computeVelocity()
self.computeAngle()
def findPartitions(self,n):
"""Partitions GPS data into n+1 subsets.
Args:
n (int): Number of subsets.
Returns:
tuple: Tuple containing:
* list: List of subsets (windows).
* lust: Indices that define windows.
"""
# Create random numbers
N=len(self.dt)
I=bam.getIncreasingRandInt(n,N)
# Close intervals
I=np.array(list(I)+[N])
# Array of windows
windows=[]
Idxs=[]
# Create indices interval
k=0
for i in I:
idxs=np.arange(k,i)
k=i
windows.append(window(idxs,self))
Idxs.append(idxs)
return windows,idxs
def findNPartitions(self,n,N):
"""Creates N partitions of GPS data into n+1 subsets.
Args:
n (int): Number of subsets.
N (int): Number of partitions.
Returns:
list: List of Windowsets.
"""
Windows=[]
Idxs=[]
for i in range(N):
w,I=self.findPartitions(n)
Windows.append(windowSet(w,I,self))
return Windows
def computeWindowClusters(self,n,N,show=False,add=True,nbouts=3):
"""Bins movement data in time windows and performs clustering by movement stats.
Args:
n (int): Number of windows of the dataset.
N (int): Number of window sets to be created.
Keyword Args:
show (bool): Show cluster plots.
add (bool): Add new window sets.
nbouts (int): Number of clusters/bouts/
Returns:
list: List of window sets.
"""
if add:
self.Windows=self.Windows+self.findNPartitions(n,N)
else:
self.Windows=self.findNPartitions(n,N)
for w in self.Windows:
w.performKMeans(nbouts=nbouts)
if show:
self.showClusters()
return self.Windows
def computeRangedWindowClusters(self,nMin,nMax,N,show=False,add=True,nbouts=3,printStatus=True):
"""Bins movement data in time windows and performs clustering by movement stats for a range of different window sizes.
Args:
nMin (int): Minimal number of windows of the dataset.
nMax (int): Maximal number of windows of the dataset.
N (int): Number of window sets to be created.
Keyword Args:
show (bool): Show cluster plots.
add (bool): Add new window sets.
nbouts (int): Number of clusters/bouts/
Returns:
list: List of window sets.
"""
ns=np.arange(nMin,nMax)
for n in ns:
print "Computing window set with n = ", n ," windows."
self.Windows=self.computeWindowClusters(n,N,show=show,add=add,nbouts=nbouts)
return self.Windows
def findBestWindowSet(self):
"""Returns the optimal partition of all window sets by minimal kmean scores.
Returns:
window.windowSet: Optimal window set.
"""
scores=[]
for w in self.Windows:
scores.append(w.kMeansScore)
return self.Windows[scores.index(min(scores))]
def showClusters(self,axes=None):
# Get number of window sets
N=len(self.Windows)
# Compute number of plots displayed
Nx=int(np.ceil(N/2.))
Ny=int(np.floor(N/2.))
# Show scatter plot for each window set
proj=N*['3d']
fig,axes=pm.makeSubplot([Nx,Ny],proj=proj)
for i,w in enumerate(self.Windows):
w.plotClusters(ax=axes[i],var='dta')
# Show labeled trajectories for each set
fig,axes=pm.makeSubplot([Nx,Ny])
for i,w in enumerate(self.Windows):
w.showClustersOnTracks(ax=axes[i])
def plotLonLatTraj(self,ax=None,onMap=True,lw=2):
"""Plots trajectory in lon/lat of this specific dataset.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes or basemap to plot in.
onMap (bool): Plot on map.
lw (str): Linewidth of plot.
color (str): Color of trajectory.
Returns:
matplotlib.axes: Modified axes.
"""
ax=pm.plotLonLatTraj(self.lon,self.lat,ax=ax,onMap=onMap,color=self.color,lw=lw)
return ax
def plotCartTraj(self,ax=None,vel=[],showVel=True,centered=True,showCenter=True):
"""Plots cartesian trajectory of specific dataset.
.. note:: Creates new figure if axes is not specified.
Args:
x (numpy.ndarray): Array with x-coordinates.
y (numpy.ndarray): Array with y-coordinates.
Keyword Args:
ax (matplotlib.axes): Axes to plot in.
vel (list): List of velocities or other values.
showVel (bool): Show velocities.
centered (bool): Show centered coordinates.
showCenter (bool): Display center.
Returns:
matplotlib.axes: Modified axes.
"""
if centered:
x=np.array(self.xC)
y=np.array(self.yC)
else:
x=np.array(self.x)
y=np.array(self.y)
if showVel and len(vel)==0:
vel=self.v
if centered:
pm.plotCartTraj(x,y,ax=ax,vel=vel,showVel=showVel,centered=centered,showCenter=showCenter,center=[0,0,0],color=self.color)
else:
pm.plotCartTraj(x,y,ax=ax,vel=vel,showVel=showVel,centered=centered,showCenter=showCenter,center=self.center,color=self.color)
return ax
def toCartesian(self,r=6378137,e=8.1819190842622e-2,h=0):
"""Converts the GPS data to cartesian coordinates."""
self.x,self.y,self.z=gps.toCartesian(self.lat,self.lon,r=r,e=e,h=h)
def centerCartesian(self,c):
"""Centers cartesian coordinates around center.
Args:
c (list): Coordinates of center.
"""
self.xC=self.x-c[0]
self.yC=self.y-c[1]
self.flipCoords()
#self.transform2KM(self.xC,self.yC)
self.center=-1*np.array(c)/1000.
def flipCoords(self):
"""Multiplies all coordinates by -1 such that lon/lat plots look the same as cartesian."""
self.xC=-1*self.xC
self.yC=-1*self.yC
def transform2KM(self,x,y):
"""Transforms distances to km.
Args:
x (numpy.ndarray): Cartesian x-coordinates in m.
y (numpy.ndarray): Cartesian y-coordinates in m.
Returns:
tuple: Tuple containing:
* numpy.ndarray: x-coordinates in km.
* numpy.ndarray: y-coordinates in km.
"""
return x/1000.,y/1000.
def computeDistances(self):
"""Computes distances of all steps."""
self.d=gps.computeDistances(self.x,self.y)
def toDateTime(self):
"""Converts dates to datetime objects."""
self.date=list(self.date)
self.date=[datetime.strptime(t, '%Y-%m-%d %H:%M:%S') for t in self.date]
def computeAngle(self):
"""Computes all turning angles."""
angles=[]
# Get directions
for i in range(len(self.x)-2):
# Define movement vectors
vec1=np.array([self.x[i+1]-self.x[i],self.y[i+1]-self.y[i]])
vec2=np.array([self.x[i+2]-self.x[i+1],self.y[i+2]-self.y[i+1]])
# Compute angles
angle = bam.direcAngle(vec1,vec2)
angles.append(angle)
self.angles=angles
return self.angles
def computeDeltaT(self):
"""Computes deltaT between timepoints in seconds."""
self.dt=[]
for i in range(len(self.date)-1):
t=self.date[i+1]-self.date[i]
self.dt.append(t.seconds)
self.t=[self.dt[0]]
for d in self.dt[1:]:
self.t.append(self.t[-1]+d)
self.dt=np.array(self.dt)
self.t=np.array(self.t)
def computeVelocity(self):
"""Computes velocity for each step."""
self.v=self.d/np.array(self.dt)
#def showBouts(self,ax):
#self.findBouts()
#ax.scatter(self.dt,self.d,c=self.bouts.labels_)
#plt.draw()
#def findBouts(self,meth='kMeans',nBouts=3):
#self.bouts=stats_module.performKMeans(self.dt,self.d,nBouts)
#print len(np.where(self.bouts.labels_>1.5)[0])
#print len(np.where(self.bouts.labels_>0.5)[0])
#def findRestPeriods(self,meth='thresh',thresh=3600.):
#if meth=='thresh':
#restIdx=np.where(self.dt>thresh)[0]
#if meth=='PCA':
#stats_module.performPCA(self.dt,self.d,2)
#if meth=='kMeans':
#x=stats_module.performKMeans(self.dt,self.d,2)
#restIdx=np.where(x.labels_>0.1)[0]
#self.restIdx=restIdx
#def showAllPlots(self):
#"""Shows all plots for one individual."""
## Create figure
#fig,axes=pm.makeSubplot([3,5],sup="Individual "+str(self.ID))
## Draw map
#m=pm.drawMap(axes[0])
## Plot trajectories into basemap
#self.plotLonLatTraj(m)
## Plot trajectories in cartesian coordinates
#self.plotCartTraj(axes[1])
## Histogram over distances
#self.plotDHist(axes[2])
## Histogram over velocities
#self.plotVHist(axes[3])
#self.plotDvsV(axes[4])
#self.plotDOverT(axes[5])
#self.plotVOverT(axes[6])
#self.plotPhiOverT(axes[7])
#self.plotPhivsV(axes[8])
#self.plotPhivsD(axes[9])
#self.plotDT(axes[10])
#self.plotDTvsD(axes[11])
#def plotDHist(self,ax,bins=100):
#"""Creates histogram of steplength distribution of individual."""
#ax=self.plotHist(ax,self.d,bins=bins,xlabel="Stepsize (m)",ylabel="Frequency",title="Overall stepsizes")
#plt.draw()
#return ax
#def plotVHist(self,ax,bins=100):
#"""Creates histogram of speed distribution of individual."""
#self.plotHist(ax,self.v,bins=bins,xlabel="Velocity (m/s)",ylabel="Frequency",title="Overall velocities")
#plt.draw()
#return ax
#def plotHist(self,ax,x,bins=100,xlabel="",ylabel="",title=""):
#"""Histogram plotting function."""
#pm.setLabels(ax,xlabel=xlabel,ylabel=ylabel,title=title)
#ax.hist(x,bins=bins)
#return ax
#def makeVSPlot(self,ax,vX,vY,scaleX=1,scaleY=1,xlabel="",ylabel="",title="",color=None):
#"""Creates scatter plot of two variables against each other."""
#if color==None:
#color=self.color
#ax.scatter(np.array(vX)/scaleX,np.array(vY)/scaleY,color=color)
#pm.setLabels(ax,xlabel=xlabel,ylabel=ylabel,title=title)
#return ax
#def makeOverPlot(self,ax,vX,vY,scaleX=1,scaleY=1,xlabel="",ylabel="",title="",color=None):
#"""Creates line plot of two variables against each other."""
#if color==None:
#color=self.color
#ax.plot(np.array(vX)/scaleX,np.array(vY)/scaleY,color=color)
#pm.setLabels(ax,xlabel=xlabel,ylabel=ylabel,title=title)
#return ax
#def plotDvsV(self,ax):
#"""Creates scatter plot showing steplength vs speed of individual."""
#self.makeVSPlot(ax,self.d,self.v,xlabel="Stepsize (m)",ylabel="Velocity (m/s)",title="D vs V")
#def plotDOverT(self,ax):
#"""Creates line plot showing time vs distance of individual."""
#self.makeOverPlot(ax,self.t,self.d,scaleX=3600.,xlabel="Time (h)",ylabel="Stepsize (m)",title="Stepsize over Time")
#def plotVOverT(self,ax):
#"""Creates line plot showing time vs velocity of individual."""
#self.makeOverPlot(ax,self.t,self.v,scaleX=3600.,xlabel="Time (h)",ylabel="Velocity (m/s)",title="Velocity over Time")
#def plotPhiOverT(self,ax):
#"""Creates line plot showing time vs angles of individual."""
#self.makeOverPlot(ax,self.t[1:],self.angles,scaleX=3600.,xlabel="Time (h)",ylabel="Phi (radians)",title="Turning angles over Time")
#def plotDTvsD(self,ax):
#"""Creates scatter plot showing dt vs steplength of individual."""
#self.makeVSPlot(ax,self.dt,self.d,scaleX=3600.,xlabel="Duration (h)",ylabel="Stepsize (m)",title="DT vs D")
#def plotPhivsV(self,ax):
#"""Creates scatter plot showing angles vs velocity of individual."""
#self.makeVSPlot(ax,self.angles,self.v[:-1],xlabel="Turning angle (radians)",ylabel="Velocity (m/s)",title="Phi vs V")
#def plotPhivsD(self,ax):
#"""Creates scatter plot showing angles vs steplengths of individual."""
#self.makeVSPlot(ax,self.angles,self.d[:-1],xlabel="Turning angle (radians)",ylabel="Distance (m)",title="Phi vs D")
#def plotDT(self,ax):
#"""Creates scatter plot showing angles vs steplengths of individual."""
#self.makeOverPlot(ax,np.arange(len(self.dt)),self.dt,scaleX=100.,scaleY=3600.,xlabel="Timepoint (100s)",ylabel="Time inbetween (h)",title="Datapoint vs. DeltaT")
#def cleanUpData(self):
## Create figure
#fig,axes=pm.makeSubplot([2,2],sup="Individual "+str(self.ID),proj=[None,None,None,'3d'])
## Scatter of kmeans
#axes[0].scatter(self.dt[self.restIdx],self.d[self.restIdx],color='r')
#axes[0].scatter(np.delete(self.dt, self.restIdx),np.delete(self.d, self.restIdx),color='b')
##
#vel=np.zeros(np.shape(self.dt))
#vel[self.restIdx]=1
#self.plotCartTraj(axes[1],vel=vel)
#plt.draw()
##self.showBouts(axes[2])
#print len(self.angles)
#print self.dt.shape
##raw_input()
#axes[3].scatter(self.dt,self.d,[0]+list(self.angles))
#plt.draw()
#raw_input()
#def swoopWin(self,lenWin=60.*60.):
#wins=[]
#win=[]
#sumT=0
#for i,t in enumerate(self.dt):
#sumT=sumT+t
#if sumT>lenWin:
#win=[i]
#wins.append(win)
#sumT=t
#else:
#win.append(i)
#return wins
class GPSDataset:
def __init__(self):
self.data={}
self.IDs=[]
def loadFile(self,fn):
"""Loads GPS data from file and creates a GPSData object for each individual.
Args:
fn (str): Path to gps data text file.
"""
# Load data
self.rawData=np.loadtxt(fn,dtype=str,delimiter=',')
self.header=bam.removeQuotationMarksFromArr(list(self.rawData[0]))
# Sort by individual
self.data=self.getIndividuals()
def getIndividuals(self):
"""Finds individuals in data and assigns data into dict and GPS data."""
# Create dict
newdata={}
# Get list of IDs
self.IDs=np.unique(self.rawData[1:,self.header.index("id")]).astype(int)
# Create list of colors
colors=self.getColors()
for i,ID in enumerate(self.IDs):
g=GPSData(ID,color=colors[i])
g.readData(self.header,self.rawData[1:])
newdata[ID]=g
self.data=newdata
return self.data
def centerCartesian(self,c):
"""Centers all GPS datasets around center.
Args:
c (list): Coordinates of center.
"""
for ID in self.IDs:
self.data[ID].centerCartesian(c)
def getColors(self,cpick='jet'):
"""Creates a list of distinct colors for each individual.
Keyword Args:
cpick (str): Colormap to pick colors from.
Returns:
list: List of colors.
"""
# Get number of individuals
n=len(self.IDs)
return pm.getColors(n,cpick=cpick)
def collectProp(self,prop):
"""Collects defined property from all individuals.
Args:
prop (str): Name of property.
Returns:
list: Collected properties.
"""
p=[]
for ID in self.IDs:
p=p+list(getattr(self.data[ID],prop))
return p
def collectDistances(self):
"""Collects all distances of all individuals.
Returns:
list: Collected distances.
"""
return self.collectProp('d')
def collectVelocities(self):
"""Collects all velocities of all individuals.
Returns:
list: Collected distances.
"""
return self.collectProp('v')
def collectAngles(self):
"""Collects all angles of all individuals.
Returns:
list: Collected angles.
"""
return self.collectProp('angles')
def collectDeltaTs(self):
"""Collects all angles of all individuals.
Returns:
list: Collected angles.
"""
return self.collectProp('dt')
def propHist(self,prop,ax=None,bins=100,xlabel="",ylabel="",title="",xlim=[],ylim=[]):
"""Creates a histogram of a specific property.
.. note:: Creates new figure if axes is not specified.
Args:
p (list): List of values to make hist of.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
xlabel (str): Label of x-axis.
ylabel (str): Label of y-axis.
title (str): Plot title.
xlim (list): Limits of x-axis.
ylim (list): Limits of y-axis.
Returns:
matplotlib.axes: Modified axes.
"""
# Collect property
p=self.collectProp(prop)
# Make hist
ax=pm.plotHist(p,ax=ax,bins=bins,xlabel=xlabel,ylabel=ylabel,title=title,xlim=xlim,ylim=ylim)
return ax
def plotDHist(self,ax=None,bins=100):
"""Creates a histogram of all distances of all individuals.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
matplotlib.axes: Modified axes.
"""
ax=self.propHist('d',ax=ax,bins=bins,xlabel="Stepsize (m)",ylabel="Frequency",title="Overall stepsizes")
return ax
def plotVHist(self,ax=None,bins=100):
"""Creates a histogram of all velocities of all individuals.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
matplotlib.axes: Modified axes.
"""
ax=self.propHist('v',ax=ax,bins=bins,xlabel="Velocity (m/s)",ylabel="Frequency",title="Overall velocities")
return ax
def plotAnglesHist(self,ax=None,bins=100):
"""Creates a histogram of all angles of all individuals.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
matplotlib.axes: Modified axes.
"""
ax=self.propHist('angles',ax=ax,bins=bins,xlabel="Angle (radians)",ylabel="Frequency",title="Overall angles")
return ax
def plotDeltaTHist(self,ax=None,bins=100):
"""Creates a histogram of all delta ts of all individuals.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
matplotlib.axes: Modified axes.
"""
ax=self.propHist('dt',ax=ax,bins=bins,xlabel="dt (s)",ylabel="Frequency",title="Overall dt")
return ax
def showStats(self,axes=[],bins=100):
"""Creates four histograms showing overall movement stats of all dataset.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
list: List of modified axes.
"""
# Create axes if not specified
if len(axes)!=4:
fig,axes=pm.makeSubplot([2,2])
self.plotDHist(ax=axes[0],bins=bins)
self.plotVHist(ax=axes[1],bins=bins)
self.plotAnglesHist(ax=axes[2],bins=bins)
self.plotDeltaTHist(ax=axes[3],bins=bins)
return axes
def plotLonLatTraj(self,ax=None,onMap=True,lw=2):
"""Plots trajectory in lon/lat for all datasets.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes or basemap to plot in.
onMap (bool): Plot on map.
lw (str): Linewidth of plot.
Returns:
matplotlib.axes: Modified axes.
"""
for ID in self.IDs:
ax=self.data[ID].plotLonLatTraj(ax=ax,onMap=onMap,lw=lw)
return ax
def plotCartTraj(self,ax=None,showVel=True,centered=True,showCenter=True):
"""Plots cartesian trajectory for all datasets.
.. note:: Creates new figure if axes is not specified.
Args:
x (numpy.ndarray): Array with x-coordinates.
y (numpy.ndarray): Array with y-coordinates.
Keyword Args:
ax (matplotlib.axes): Axes to plot in.
showVel (bool): Show velocities.
centered (bool): Show centered coordinates.
showCenter (bool): Display center.
Returns:
matplotlib.axes: Modified axes.
"""
for ID in self.IDs:
ax=self.data[ID].plotCartTraj(ax=ax,showVel=showVel,centered=centered,showCenter=showCenter)
return ax
def showData(self,axes=[],lw=2,onMap=True,bins=100,showVel=False,centered=True,showCenter=False):
"""Shows basic stats histograms and movement trajectories of all data sets.
.. note:: Creates new figure if axes is not specified.
Keyword Args:
ax (matplotlib.axes): Axes.
bins (int): Number of bins.
Returns:
list: List of modified axes.
"""
# Create axes if not specified
if len(axes)!=6:
fig,axes=pm.makeSubplot([3,2])
if onMap:
ax=pm.drawMap(axes[0])
self.plotLonLatTraj(ax=ax,onMap=onMap,lw=lw)
self.plotCartTraj(ax=axes[1],showVel=showVel,centered=centered,showCenter=showCenter)
self.showStats(axes=axes[2:])
return axes