/
trajectory.py
1136 lines (976 loc) · 35.2 KB
/
trajectory.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 -*-
import warnings
from shapely.affinity import translate
from shapely.geometry import Point, LineString
from datetime import datetime
from pandas import DataFrame, to_datetime, Series
from pandas.core.indexes.datetimes import DatetimeIndex
from geopandas import GeoDataFrame
from geopy.distance import geodesic
try:
from pyproj import CRS
except ImportError:
from fiona.crs import from_epsg
from .overlay import clip, intersection, intersects, create_entry_and_exit_points
from .time_range_utils import SpatioTemporalRange
from .geometry_utils import (
azimuth,
calculate_initial_compass_bearing,
measure_distance_geodesic,
measure_distance_euclidean,
)
from .trajectory_plotter import _TrajectoryPlotter
TRAJ_ID_COL_NAME = "traj_id"
SPEED_COL_NAME = "speed"
ACCELERATION_COL_NAME = "acceleration"
DIRECTION_COL_NAME = "direction"
DISTANCE_COL_NAME = "distance"
TIMEDELTA_COL_NAME = "timedelta"
class MissingCRSWarning(UserWarning, ValueError):
pass
class Trajectory:
def __init__(
self,
df,
traj_id,
obj_id=None,
t=None,
x=None,
y=None,
crs="epsg:4326",
parent=None,
):
"""
Create Trajectory from GeoDataFrame or DataFrame.
Parameters
----------
df : GeoDataFrame or DataFrame
GeoDataFrame with point geometry column and timestamp index
traj_id : any
Trajectory ID
obj_id : any
Moving object ID
t : string
Name of the DataFrame column containing the timestamp
x : string
Name of the DataFrame column containing the x coordinate
y : string
Name of the DataFrame column containing the y coordinate
crs : string
CRS of the x/y coordinates
parent : Trajectory
Parent trajectory
Examples
--------
Creating a trajectory from scratch:
>>> import pandas as pd
>>> import geopandas as gpd
>>> import movingpandas as mpd
>>> from fiona.crs import from_epsg
>>>
>>> df = pd.DataFrame([
... {'geometry':Point(0,0), 't':datetime(2018,1,1,12,0,0)},
... {'geometry':Point(6,0), 't':datetime(2018,1,1,12,6,0)},
... {'geometry':Point(6,6), 't':datetime(2018,1,1,12,10,0)},
... {'geometry':Point(9,9), 't':datetime(2018,1,1,12,15,0)}
... ]).set_index('t')
>>> gdf = gpd.GeoDataFrame(df, crs=from_epsg(31256))
>>> traj = mpd.Trajectory(gdf, 1)
For more examples, see the tutorial notebooks_.
.. _notebooks: https://mybinder.org/v2/gh/anitagraser/movingpandas/binder-tag?filepath=tutorials/0_getting_started.ipynb
""" # noqa: E501
if len(df) < 2:
raise ValueError("The input DataFrame must have at least two rows.")
if not isinstance(df, GeoDataFrame):
if x is None or y is None:
raise ValueError(
"The input DataFrame needs to be a GeoDataFrame or x and y columns"
"need to be specified."
)
df = GeoDataFrame(
df.drop([x, y], axis=1),
crs=crs,
geometry=[Point(xy) for xy in zip(df[x], df[y])],
)
if not isinstance(df.index, DatetimeIndex):
if t is None:
raise TypeError(
"The input DataFrame needs a DatetimeIndex or a timestamp column"
"needs to be specified. Use Pandas' set_index() method to create an"
"index or specify the timestamp column name."
)
df[t] = to_datetime(df[t])
df = df.set_index(t).tz_localize(None)
self.id = traj_id
self.obj_id = obj_id
df.sort_index(inplace=True)
self.df = df[~df.index.duplicated(keep="first")]
self.crs = df.crs
self.parent = parent
if self.crs is None:
warnings.warn(
"Trajectory generated without CRS. Computations will use Euclidean"
"distances.",
category=MissingCRSWarning,
)
self.is_latlon = False
return
try:
crs = CRS.from_user_input(self.crs)
self.is_latlon = crs.is_geographic
except NameError:
self.is_latlon = self.crs["init"] == from_epsg(4326)["init"]
def __str__(self):
try:
line = self.to_linestring()
except RuntimeError:
return "Invalid trajectory!"
return (
"Trajectory {id} ({t0} to {tn}) | Size: {n} | Length: {len:.1f}m\n"
"Bounds: {bbox}\n{wkt}".format(
id=self.id,
t0=self.get_start_time(),
tn=self.get_end_time(),
n=self.size(),
wkt=line.wkt[:100],
bbox=self.get_bbox(),
len=self.get_length(),
)
)
def __repr__(self):
return self.__str__()
def __len__(self):
return self.get_length()
def __eq__(self, other):
# TODO: make bullet proof
return (
str(self) == str(other)
and self.crs == other.crs
and self.parent == other.parent
)
def size(self):
"""
Returns number of rows in Trajectory.df
Returns
-------
size : int
Number of rows
"""
return len(self.df.index)
def copy(self):
"""
Return a copy of the trajectory.
Returns
-------
Trajectory
"""
return Trajectory(self.df.copy(), self.id, parent=self.parent)
def plot(self, *args, **kwargs):
"""
Generate a plot using GeoPandas default plotting (Matplotlib).
Parameters
----------
args :
These parameters will be passed to the TrajectoryPlotter
kwargs :
These parameters will be passed to the TrajectoryPlotter
Returns
-------
Matplotlib plot
Examples
--------
Plot speed along trajectory (with legend and specified figure size):
>>> trajectory.plot(column='speed', legend=True, figsize=(9,5))
"""
return _TrajectoryPlotter(self, *args, **kwargs).plot()
def hvplot(self, *args, **kwargs):
"""
Generate an interactive plot using HoloViews.
The following parameters are set by default: geo=True, tiles='OSM'.
Parameters
----------
args :
These parameters will be passed to the TrajectoryPlotter
kwargs :
These parameters will be passed to the TrajectoryPlotter
Returns
-------
Holoviews plot
Examples
--------
Plot speed along trajectory (with legend and specified figure size):
>>> trajectory.hvplot(c='speed', line_width=7.0, width=700, height=400, colorbar=True)
""" # noqa: E501
return _TrajectoryPlotter(self, *args, **kwargs).hvplot()
def is_valid(self):
"""
Return whether the trajectory meets minimum requirements.
Returns
-------
bool
"""
if len(self.df) < 2:
return False
if not self.get_start_time() < self.get_end_time():
return False
return True
def to_crs(self, crs):
"""
Returns the trajectory reprojected to the target CRS.
Parameters
----------
crs : pyproj.CRS
Target coordinate reference system
Returns
-------
Trajectory
Examples
--------
Reproject a trajectory to EPSG:4088
>>> from pyproj import CRS
>>> reprojected = trajectory.to_crs(CRS(4088))
"""
temp = self.copy()
temp.crs = crs
temp.df = temp.df.to_crs(crs)
if type(crs) == CRS:
temp.is_latlon = crs.is_geographic
else:
temp.is_latlon = crs["init"] == from_epsg(4326)["init"]
return temp
def get_speed_column_name(self):
"""
Return name of the speed column
Returns
-------
string
"""
if hasattr(self, "speed_col_name"):
return self.speed_col_name
else:
return SPEED_COL_NAME
def get_distance_column_name(self):
"""
Return name of the distance column
Returns
-------
string
"""
if hasattr(self, "distance_col_name"):
return self.distance_col_name
else:
return DISTANCE_COL_NAME
def get_direction_column_name(self):
"""
Return name of the direction column
Returns
-------
string
"""
if hasattr(self, "direction_col_name"):
return self.direction_col_name
else:
return DIRECTION_COL_NAME
def get_timedelta_column_name(self):
"""
Return name of the timedelta column
Returns
-------
string
"""
if hasattr(self, "timedelta_col_name"):
return self.timedelta_col_name
else:
return TIMEDELTA_COL_NAME
def get_geom_column_name(self):
"""
Return name of the geometry column
Returns
-------
string
"""
return self.df.geometry.name
def to_linestring(self):
"""
Return trajectory geometry as LineString.
Returns
-------
shapely LineString
"""
try:
return point_gdf_to_linestring(self.df, self.get_geom_column_name())
except RuntimeError:
raise RuntimeError("Cannot generate LineString")
def to_linestringm_wkt(self):
"""
Return the WKT string of the trajectory LineStringM representation.
Returns
-------
string
WKT of trajectory as LineStringM
"""
# Shapely only supports x, y, z. Therefore, this is a bit hacky!
coords = ""
for index, row in self.df.iterrows():
pt = row[self.get_geom_column_name()]
t = to_unixtime(index)
coords += "{} {} {}, ".format(pt.x, pt.y, t)
wkt = "LINESTRING M ({})".format(coords[:-2])
return wkt
def to_point_gdf(self):
"""
Return the trajectory's points as GeoDataFrame.
Returns
-------
GeoDataFrame
"""
return self.df
def to_line_gdf(self):
"""
Return the trajectory's line segments as GeoDataFrame.
Returns
-------
GeoDataFrame
"""
line_gdf = self._to_line_df()
line_gdf.drop(columns=[self.get_geom_column_name(), "prev_pt"], inplace=True)
line_gdf.reset_index(drop=True, inplace=True)
line_gdf.rename(columns={"line": "geometry"}, inplace=True)
line_gdf.set_geometry("geometry", inplace=True)
return line_gdf
def to_traj_gdf(self, wkt=False):
"""
Return a GeoDataFrame with one row containing the trajectory as a
single LineString.
Returns
-------
GeoDataFrame
"""
properties = {
TRAJ_ID_COL_NAME: self.id,
"start_t": self.get_start_time(),
"end_t": self.get_end_time(),
"geometry": self.to_linestring(),
"length": self.get_length(),
"direction": self.get_direction(),
}
if wkt:
properties["wkt"] = self.to_linestringm_wkt()
df = DataFrame([properties])
traj_gdf = GeoDataFrame(df, crs=self.crs)
return traj_gdf
def get_start_location(self):
"""
Return the trajectory's start location.
Returns
-------
shapely Point
Trajectory start location
"""
return self.df.geometry.iloc[0]
def get_end_location(self):
"""Return the trajectory's end location.
Returns
-------
shapely Point
Trajectory end location
"""
return self.df.geometry.iloc[-1]
def get_bbox(self):
"""
Return the trajectory's bounding box.
Returns
-------
tuple
Bounding box values (minx, miny, maxx, maxy)
"""
return tuple(self.df.total_bounds.tolist()) # (minx, miny, maxx, maxy)
def get_start_time(self):
"""
Return the trajectory's start time.
Returns
-------
datetime.datetime
Trajectory start time
"""
return self.df.index.min().to_pydatetime()
def get_end_time(self):
"""
Return the trajectory's end time.
Returns
-------
datetime.datetime
Trajectory end time
"""
return self.df.index.max().to_pydatetime()
def get_duration(self):
"""
Return the trajectory's duration from start to end.
Returns
-------
datetime.timedelta
Trajectory duration
"""
return self.get_end_time() - self.get_start_time()
def get_row_at(self, t, method="nearest"):
"""
Return row of the trajectory's DataFrame at time t.
Parameters
----------
t : datetime.datetime
Timestamp to extract a row for
method : str
Interpolation method (Pandas get_loc method)
Returns
-------
Pandas series
Row of the DataFrame at time t
"""
try:
return self.df.loc[t]
except KeyError:
index = self.df.index.sort_values().drop_duplicates()
idx = index.get_indexer([t], method=method)[0]
return self.df.iloc[idx]
def interpolate_position_at(self, t):
"""
Compute and return interpolated position at time t.
Parameters
----------
t : datetime.datetime
Timestamp to interpolate at
Returns
-------
shapely Point
Interpolated position along the trajectory at time t
"""
prev_row = self.get_row_at(t, "ffill")
next_row = self.get_row_at(t, "bfill")
t_diff = next_row.name - prev_row.name
t_diff_at = t - prev_row.name
line = LineString(
[
prev_row[self.get_geom_column_name()],
next_row[self.get_geom_column_name()],
]
)
if t_diff == 0 or line.length == 0:
return prev_row[self.get_geom_column_name()]
interpolated_position = line.interpolate(t_diff_at / t_diff * line.length)
return interpolated_position
def get_position_at(self, t, method="interpolated"):
"""
Compute and return position at time t.
Parameters
----------
t : datetime.datetime
Timestamp to extract a row for
method : str
Interpolation method
Returns
-------
shapely Point
Position at time t
Examples
--------
If the trajectory contains a position at the given timestamp, it is
returned:
>>> traj.get_position_at(datetime(2018, 1, 1, 12, 6))
Point (6 0)
If there is no trajectory position for the given timestamp, the default
behaviour is to interpolate the location:
>>> traj.get_position_at(datetime(2018, 1, 1, 12, 9))
POINT (6 4.5)
To get the trajectory position closest to the given timestamp, specify
method='nearest':
>>> traj.get_position_at(datetime(2018, 1, 1, 12, 9), method='nearest')
POINT (6 6)
"""
if method not in ["nearest", "interpolated", "ffill", "bfill"]:
raise ValueError(
"Invalid method {}. Must be one of [nearest, interpolated, ffill,"
"bfill]".format(method)
)
if method == "interpolated":
return self.interpolate_position_at(t)
else:
row = self.get_row_at(t, method)
try:
return row[self.get_geom_column_name()][0]
except TypeError:
return row[self.get_geom_column_name()]
def get_linestring_between(self, t1, t2, method="interpolated"):
"""
Return LineString of segment between times t1 and t2.
Parameters
----------
t1 : datetime.datetime
Start time for the segment
t2 : datetime.datetime
End time for the segment
method : str
Extraction method
Returns
-------
shapely LineString
Extracted trajectory segment
"""
if method not in ["interpolated", "within"]:
raise ValueError(
"Invalid split method {}. Must be one of [interpolated, within]".format(
method
)
)
if method == "interpolated":
st_range = SpatioTemporalRange(
self.get_position_at(t1), self.get_position_at(t2), t1, t2
)
temp_df = create_entry_and_exit_points(self, st_range)
temp_df = temp_df[t1:t2]
return point_gdf_to_linestring(temp_df, self.get_geom_column_name())
else:
try:
return point_gdf_to_linestring(
self.get_segment_between(t1, t2).df, self.get_geom_column_name()
)
except RuntimeError:
raise RuntimeError(
"Cannot generate linestring between {0} and {1}".format(t1, t2)
)
def get_segment_between(self, t1, t2):
"""
Return Trajectory segment between times t1 and t2.
Parameters
----------
t1 : datetime.datetime
Start time for the segment
t2 : datetime.datetime
End time for the segment
Returns
-------
Trajectory
Extracted trajectory segment
"""
segment = Trajectory(self.df[t1:t2], "{}_{}".format(self.id, t1), parent=self)
if not segment.is_valid():
raise RuntimeError(
"Failed to extract valid trajectory segment between {} and {}".format(
t1, t2
)
)
return segment
def _compute_distance(self, row):
pt0 = row["prev_pt"]
pt1 = row[self.get_geom_column_name()]
if not isinstance(pt0, Point):
return 0.0
if pt0 == pt1:
return 0.0
if self.is_latlon:
dist_meters = measure_distance_geodesic(pt0, pt1)
else: # The following distance will be in CRS units that might not be meters!
dist_meters = measure_distance_euclidean(pt0, pt1)
return dist_meters
def _add_prev_pt(self, force=True):
"""
Create a shifted geometry column with previous positions.
"""
if "prev_pt" not in self.df.columns or force:
# TODO: decide on default enforcement behavior
self.df = self.df.assign(prev_pt=self.df.geometry.shift())
def get_length(self):
"""
Return the length of the trajectory.
Length is calculated using CRS units, except if the CRS is geographic
(e.g. EPSG:4326 WGS84) then length is calculated in metres.
Returns
-------
float
Length of the trajectory
"""
pt_tuples = [(pt.y, pt.x) for pt in self.df.geometry.tolist()]
if self.is_latlon:
return geodesic(*pt_tuples).m
else: # The following distance will be in CRS units that might not be meters!
return LineString(pt_tuples).length
def get_direction(self):
"""
Return the direction of the trajectory.
The direction is calculated between the trajectory's start and end
location. Direction values are in degrees, starting North turning
clockwise.
Returns
-------
float
Direction of the trajectory in degrees
"""
pt0 = self.get_start_location()
pt1 = self.get_end_location()
if self.is_latlon:
return calculate_initial_compass_bearing(pt0, pt1)
else:
return azimuth(pt0, pt1)
def get_sampling_interval(self):
"""
Return the sampling interval of the trajectory.
The sampling interval is computed as the median time difference between
consecutive rows in the trajectory's DataFrame.
Returns
-------
datetime.timedelta
Sampling interval
"""
if hasattr(self, "timedelta_col_name"):
if self.timedelta_col_name in self.df.columns:
return self.df[self.timedelta_col_name].median()
return self._get_df_with_timedelta()[TIMEDELTA_COL_NAME].median()
def _compute_heading(self, row):
pt0 = row["prev_pt"]
pt1 = row[self.get_geom_column_name()]
if not isinstance(pt0, Point):
return 0.0
if pt0 == pt1:
return 0.0
if self.is_latlon:
return calculate_initial_compass_bearing(pt0, pt1)
else:
return azimuth(pt0, pt1)
def _compute_speed(self, row):
pt0 = row["prev_pt"]
pt1 = row[self.get_geom_column_name()]
if not isinstance(pt0, Point):
return 0.0
if not isinstance(pt1, Point):
raise ValueError("Invalid trajectory! Got {} instead of point!".format(pt1))
if pt0 == pt1:
return 0.0
if self.is_latlon:
dist_meters = measure_distance_geodesic(pt0, pt1)
else: # The following distance will be in CRS units that might not be meters!
dist_meters = measure_distance_euclidean(pt0, pt1)
return dist_meters / row["delta_t"].total_seconds()
def _connect_prev_pt_and_geometry(self, row):
pt0 = row["prev_pt"]
pt1 = row[self.get_geom_column_name()]
if not isinstance(pt0, Point):
return None
if not isinstance(pt1, Point):
raise ValueError("Invalid trajectory! Got {} instead of point!".format(pt1))
if pt0 == pt1:
# to avoid intersection issues with zero length lines
pt1 = translate(pt1, 0.00000001, 0.00000001)
return LineString(list(pt0.coords) + list(pt1.coords))
def add_traj_id(self, overwrite=False):
"""
Add trajectory id column and values to the trajectory's DataFrame.
Parameters
----------
overwrite : bool
Whether to overwrite existing trajectory id values (default: False)
"""
if TRAJ_ID_COL_NAME in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already contains a {TRAJ_ID_COL_NAME} column! "
f"Use overwrite=True to overwrite exiting values."
)
self.df[TRAJ_ID_COL_NAME] = self.id
def add_direction(self, overwrite=False, name=DIRECTION_COL_NAME):
"""
Add direction column and values to the trajectory's DataFrame.
The direction is calculated between consecutive locations.
Direction values are in degrees, starting North turning clockwise.
Parameters
----------
overwrite : bool
Whether to overwrite existing direction values (default: False)
"""
self.direction_col_name = name
if self.direction_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.direction_col_name}! "
"Use overwrite=True to overwrite exiting values or update the "
"name arg."
)
self._add_prev_pt()
self.df[name] = self.df.apply(self._compute_heading, axis=1)
# set the direction in the first row to the direction of the second row
self.df.at[self.get_start_time(), name] = self.df.iloc[1][name]
self.df.drop(columns=["prev_pt"], inplace=True)
def add_distance(self, overwrite=False, name=DISTANCE_COL_NAME):
"""
Add distance column and values to the trajectory's DataFrame.
Distance is calculated as CRS units, except if the CRS is geographic
(e.g. EPSG:4326 WGS84) then distance is calculated in meters.
Parameters
----------
overwrite : bool
Whether to overwrite existing distance values (default: False)
"""
self.distance_col_name = name
if self.distance_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.distance_col_name}! "
"Use overwrite=True to overwrite exiting values or update the "
"name arg."
)
self.df = self._get_df_with_distance(name)
def add_speed(self, overwrite=False, name=SPEED_COL_NAME):
"""
Add speed column and values to the trajectory's DataFrame.
Speed is calculated as CRS units per second, except if the CRS is
geographic (e.g. EPSG:4326 WGS84) then speed is calculated in meters
per second.
Parameters
----------
overwrite : bool
Whether to overwrite existing speed values (default: False)
name : str
Name of the speed column (default: "speed")
"""
self.speed_col_name = name
if self.speed_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.speed_col_name}! "
f"Use overwrite=True to overwrite exiting values or update the "
f"name arg."
)
self.df = self._get_df_with_speed(name)
def add_acceleration(self, overwrite=False, name=ACCELERATION_COL_NAME):
"""
Add acceleration column and values to the trajectory's DataFrame.
Acceleration is calculated as CRS units per second squared,
except if the CRS is geographic (e.g. EPSG:4326 WGS84) then speed is
calculated in meters per second squared.
"""
self.acceleration_col_name = name
if self.acceleration_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.acceleration_col_name}! "
f"Use overwrite=True to overwrite exiting values or update the "
f"name arg."
)
self.df = self._get_df_with_acceleration(name)
def add_timedelta(self, overwrite=False, name=TIMEDELTA_COL_NAME):
"""
Add timedelta column and values to the trajectory's DataFrame.
Timedelta is calculated as the time difference between the current
and the previous row. Values are instances of datetime.timedelta.
Parameters
----------
overwrite : bool
Whether to overwrite existing timedelta values (default: False)
name : str
Name of the timedelta column (default: "timedelta")
"""
self.timedelta_col_name = name
if self.timedelta_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.timedelta_col_name}! "
f"Use overwrite=True to overwrite exiting values or update the "
f"name arg."
)
self.df = self._get_df_with_timedelta(name)
def _get_df_with_timedelta(self, name=TIMEDELTA_COL_NAME):
temp_df = self.df.copy()
times = Series(index=temp_df.index, data=temp_df.index)
temp_df[name] = times.diff().values
return temp_df
def _get_df_with_distance(self, name=DISTANCE_COL_NAME):
temp_df = self.df.copy()
temp_df = temp_df.assign(prev_pt=temp_df.geometry.shift())
try:
temp_df[name] = temp_df.apply(self._compute_distance, axis=1)
except ValueError as e:
raise e
# set the distance in the first row to zero
temp_df.at[self.get_start_time(), name] = 0
temp_df = temp_df.drop(columns=["prev_pt"])
return temp_df
def _get_df_with_speed(self, name=SPEED_COL_NAME):
temp_df = self._get_df_with_timedelta(name="delta_t")
temp_df = temp_df.assign(prev_pt=temp_df.geometry.shift())
try:
temp_df[name] = temp_df.apply(self._compute_speed, axis=1)
except ValueError as e:
raise e
# set the speed in the first row to the speed of the second row
temp_df.at[self.get_start_time(), name] = temp_df.iloc[1][name]
temp_df = temp_df.drop(columns=["prev_pt", "delta_t"])
return temp_df
def _get_df_with_acceleration(self, name=ACCELERATION_COL_NAME):
# Avoid computed speed again if already computed
if hasattr(self, "speed_col_name"):
temp_df = self.df.copy()
else:
temp_df = self._get_df_with_speed(name=SPEED_COL_NAME)
speed_column_name = self.get_speed_column_name()
temp_df[name] = (
temp_df[speed_column_name].diff()
/ temp_df.index.to_series().diff().dt.total_seconds()
)
# set the acceleration in the first row to the acceleration of the
# second row
temp_df.at[self.get_start_time(), name] = temp_df.iloc[1][name]
if hasattr(self, "speed_col_name"):
return temp_df
else:
return temp_df.drop(columns=[speed_column_name])
def intersects(self, polygon):
"""
Return whether the trajectory intersects the given polygon.
Parameters
----------
polygon : shapely.geometry.Polygon
Polygon to test for intersections
Returns
-------
bool
"""
return intersects(self, polygon)
def distance(self, other):
"""
Return the minimum distance to the other geometric object (based on shapely
https://shapely.readthedocs.io/en/stable/manual.html#object.distance).
Parameters
----------
other : shapely.geometry or Trajectory
Other geometric object or trajectory
Returns
-------
float
Distance
"""
if self.is_latlon:
message = (
f"Distance is computed using Euclidean geometry but "
f"the trajectory coordinate system is {self.crs}."
)
warnings.warn(message, UserWarning)
if type(other) == Trajectory:
other = other.to_linestring()
return self.to_linestring().distance(other)
def hausdorff_distance(self, other):
"""
Return the Hausdorff distance to the other geometric object (based on shapely
https://shapely.readthedocs.io/en/stable/manual.html#object.hausdorff_distance).
The Hausdorff distance between two geometries is the furthest distance
that a point on either geometry can be from the nearest point to it on
the other geometry.
Parameters
----------
other : shapely.geometry or Trajectory
Other geometric object or trajectory
Returns