forked from tecodan/xavc_rtmd2srt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpx(replace).py
2769 lines (2301 loc) · 97 KB
/
gpx(replace).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 -*-
# Copyright 2011 Tomo Krajina
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
GPX related stuff
"""
import logging as mod_logging
import math as mod_math
import collections as mod_collections
import copy as mod_copy
import datetime as mod_datetime
from . import utils as mod_utils
from . import geo as mod_geo
from . import gpxfield as mod_gpxfield
log = mod_logging.getLogger(__name__)
# GPX date format to be used when writing the GPX output:
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
# GPX date format(s) used for parsing. The T between date and time and Z after
# time are allowed, too:
DATE_FORMATS = [
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
]
# Used in smoothing, sum must be 1:
SMOOTHING_RATIO = (0.4, 0.2, 0.4)
# When computing stopped time -- this is the minimum speed between two points,
# if speed is less than this value -- we'll assume it is zero
DEFAULT_STOPPED_SPEED_THRESHOLD = 1
# Fields used for all point elements (route point, track point, waypoint):
GPX_10_POINT_FIELDS = [
mod_gpxfield.GPXField('latitude', attribute='lat', type=mod_gpxfield.FLOAT_TYPE, mandatory=True),
mod_gpxfield.GPXField('longitude', attribute='lon', type=mod_gpxfield.FLOAT_TYPE, mandatory=True),
mod_gpxfield.GPXField('elevation', 'ele', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('time', type=mod_gpxfield.TIME_TYPE),
mod_gpxfield.GPXField('magnetic_variation', 'magvar', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('geoid_height', 'geoidheight', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('name'),
mod_gpxfield.GPXField('comment', 'cmt'),
mod_gpxfield.GPXField('description', 'desc'),
mod_gpxfield.GPXField('source', 'src'),
mod_gpxfield.GPXField('link', 'url'),
mod_gpxfield.GPXField('link_text', 'urlname'),
mod_gpxfield.GPXField('symbol', 'sym'),
mod_gpxfield.GPXField('type'),
mod_gpxfield.GPXField('type_of_gpx_fix', 'fix', possible=('none', '2d', '3d', 'dgps', 'pps',)),
mod_gpxfield.GPXField('satellites', 'sat', type=mod_gpxfield.INT_TYPE),
mod_gpxfield.GPXField('horizontal_dilution', 'hdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('vertical_dilution', 'vdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('position_dilution', 'pdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('age_of_dgps_data', 'ageofdgpsdata', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('dgps_id', 'dgpsid'),
]
GPX_11_POINT_FIELDS = [
# See GPX for description of text fields
mod_gpxfield.GPXField('latitude', attribute='lat', type=mod_gpxfield.FLOAT_TYPE, mandatory=True),
mod_gpxfield.GPXField('longitude', attribute='lon', type=mod_gpxfield.FLOAT_TYPE, mandatory=True),
mod_gpxfield.GPXField('elevation', 'ele', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('time', type=mod_gpxfield.TIME_TYPE),
mod_gpxfield.GPXField('magnetic_variation', 'magvar', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('geoid_height', 'geoidheight', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('name'),
mod_gpxfield.GPXField('comment', 'cmt'),
mod_gpxfield.GPXField('description', 'desc'),
mod_gpxfield.GPXField('source', 'src'),
'link:@link',
mod_gpxfield.GPXField('link', attribute='href'),
mod_gpxfield.GPXField('link_text', tag='text'),
mod_gpxfield.GPXField('link_type', tag='type'),
'/link',
mod_gpxfield.GPXField('symbol', 'sym'),
mod_gpxfield.GPXField('type'),
mod_gpxfield.GPXField('type_of_gpx_fix', 'fix', possible=('none', '2d', '3d', 'dgps', 'pps',)),
mod_gpxfield.GPXField('satellites', 'sat', type=mod_gpxfield.INT_TYPE),
mod_gpxfield.GPXField('horizontal_dilution', 'hdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('vertical_dilution', 'vdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('position_dilution', 'pdop', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('age_of_dgps_data', 'ageofdgpsdata', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('dgps_id', 'dgpsid'),
mod_gpxfield.GPXExtensionsField('extensions', is_list=True),
]
# GPX1.0 track points have two more fields after time
# Note that this is not true for GPX1.1
GPX_TRACK_POINT_FIELDS = GPX_10_POINT_FIELDS[:4] \
+ [ \
mod_gpxfield.GPXField('course', type=mod_gpxfield.FLOAT_TYPE), \
mod_gpxfield.GPXField('speed', type=mod_gpxfield.FLOAT_TYPE) \
] \
+ GPX_10_POINT_FIELDS[4:]
# When possible, the result of various methods are named tuples defined here:
TimeBounds = mod_collections.namedtuple(
'TimeBounds',
('start_time', 'end_time'))
MovingData = mod_collections.namedtuple(
'MovingData',
('moving_time', 'stopped_time', 'moving_distance', 'stopped_distance', 'max_speed'))
UphillDownhill = mod_collections.namedtuple(
'UphillDownhill',
('uphill', 'downhill'))
MinimumMaximum = mod_collections.namedtuple(
'MinimumMaximum',
('minimum', 'maximum'))
NearestLocationData = mod_collections.namedtuple(
'NearestLocationData',
('location', 'track_no', 'segment_no', 'point_no'))
PointData = mod_collections.namedtuple(
'PointData',
('point', 'distance_from_start', 'track_no', 'segment_no', 'point_no'))
class GPXException(Exception):
"""
Exception used for invalid GPX files. It is used when the XML file is
valid but something is wrong with the GPX data.
"""
pass
class GPXBounds:
gpx_10_fields = gpx_11_fields = [
mod_gpxfield.GPXField('min_latitude', attribute='minlat', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('max_latitude', attribute='maxlat', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('min_longitude', attribute='minlon', type=mod_gpxfield.FLOAT_TYPE),
mod_gpxfield.GPXField('max_longitude', attribute='maxlon', type=mod_gpxfield.FLOAT_TYPE),
]
__slots__ = ('min_latitude', 'max_latitude', 'min_longitude', 'max_longitude')
def __init__(self, min_latitude=None, max_latitude=None, min_longitude=None, max_longitude=None):
self.min_latitude = min_latitude
self.max_latitude = max_latitude
self.min_longitude = min_longitude
self.max_longitude = max_longitude
def __iter__(self):
return (self.min_latitude, self.max_latitude, self.min_longitude, self.max_longitude,).__iter__()
class GPXXMLSyntaxException(GPXException):
"""
Exception used when the XML syntax is invalid.
The __cause__ can be a minidom or lxml exception (See http://www.python.org/dev/peps/pep-3134/).
"""
def __init__(self, message, original_exception):
GPXException.__init__(self, message)
self.__cause__ = original_exception
class GPXWaypoint(mod_geo.Location):
gpx_10_fields = GPX_10_POINT_FIELDS
gpx_11_fields = GPX_11_POINT_FIELDS
__slots__ = ('latitude', 'longitude', 'elevation', 'time',
'magnetic_variation', 'geoid_height', 'name', 'comment',
'description', 'source', 'link', 'link_text', 'symbol',
'type', 'type_of_gpx_fix', 'satellites',
'horizontal_dilution', 'vertical_dilution',
'position_dilution', 'age_of_dgps_data', 'dgps_id',
'link_type', 'extensions')
def __init__(self, latitude=None, longitude=None, elevation=None, time=None,
name=None, description=None, symbol=None, type=None,
comment=None, horizontal_dilution=None, vertical_dilution=None,
position_dilution=None, type_of_gpx_fix=None):
mod_geo.Location.__init__(self, latitude, longitude, elevation)
self.latitude = latitude
self.longitude = longitude
self.elevation = elevation
self.time = time
self.magnetic_variation = None
self.geoid_height = None
self.name = name
self.comment = comment
self.description = description
self.source = None
self.link = None
self.link_text = None
self.link_type = None
self.symbol = symbol
self.type = type
self.type_of_gpx_fix = type_of_gpx_fix
self.satellites = None
self.horizontal_dilution = horizontal_dilution
self.vertical_dilution = vertical_dilution
self.position_dilution = position_dilution
self.age_of_dgps_data = None
self.dgps_id = None
self.extensions = []
def __str__(self):
return '[wpt{%s}:%s,%s@%s]' % (self.name, self.latitude, self.longitude, self.elevation)
def __repr__(self):
representation = '%s, %s' % (self.latitude, self.longitude)
for attribute in 'elevation', 'time', 'name', 'description', 'symbol', 'type', 'comment', \
'horizontal_dilution', 'vertical_dilution', 'position_dilution':
value = getattr(self, attribute)
if value is not None:
representation += ', %s=%s' % (attribute, repr(value))
return 'GPXWaypoint(%s)' % representation
def adjust_time(self, delta):
"""
Adjusts the time of the point by the specified delta
Parameters
----------
delta : datetime.timedelta
Positive time delta will adjust time into the future
Negative time delta will adjust time into the past
"""
if self.time:
self.time += delta
def remove_time(self):
""" Will remove time metadata. """
self.time = None
def get_max_dilution_of_precision(self):
"""
Only care about the max dop for filtering, no need to go into too much detail
"""
return max(self.horizontal_dilution, self.vertical_dilution, self.position_dilution)
class GPXRoutePoint(mod_geo.Location):
gpx_10_fields = GPX_10_POINT_FIELDS
gpx_11_fields = GPX_11_POINT_FIELDS
__slots__ = ('latitude', 'longitude', 'elevation', 'time',
'magnetic_variation', 'geoid_height', 'name', 'comment',
'description', 'source', 'link', 'link_text', 'symbol',
'type', 'type_of_gpx_fix', 'satellites',
'horizontal_dilution', 'vertical_dilution',
'position_dilution', 'age_of_dgps_data', 'dgps_id',
'link_type', 'extensions')
def __init__(self, latitude=None, longitude=None, elevation=None, time=None, name=None,
description=None, symbol=None, type=None, comment=None,
horizontal_dilution=None, vertical_dilution=None,
position_dilution=None, type_of_gpx_fix=None):
mod_geo.Location.__init__(self, latitude, longitude, elevation)
self.latitude = latitude
self.longitude = longitude
self.elevation = elevation
self.time = time
self.magnetic_variation = None
self.geoid_height = None
self.name = name
self.comment = comment
self.description = description
self.source = None
self.link = None
self.link_text = None
self.symbol = symbol
self.type = type
self.type_of_gpx_fix = type_of_gpx_fix
self.satellites = None
self.horizontal_dilution = horizontal_dilution
self.vertical_dilution = vertical_dilution
self.position_dilution = position_dilution
self.age_of_dgps_data = None
self.dgps_id = None
self.link_type = None
self.extensions = []
def __str__(self):
return '[rtept{%s}:%s,%s@%s]' % (self.name, self.latitude, self.longitude, self.elevation)
def __repr__(self):
representation = '%s, %s' % (self.latitude, self.longitude)
for attribute in 'elevation', 'time', 'name', 'description', 'symbol', 'type', 'comment', \
'horizontal_dilution', 'vertical_dilution', 'position_dilution':
value = getattr(self, attribute)
if value is not None:
representation += ', %s=%s' % (attribute, repr(value))
return 'GPXRoutePoint(%s)' % representation
def adjust_time(self, delta):
"""
Adjusts the time of the point by the specified delta
Parameters
----------
delta : datetime.timedelta
Positive time delta will adjust time into the future
Negative time delta will adjust time into the past
"""
if self.time:
self.time += delta
def remove_time(self):
""" Will remove time metadata. """
self.time = None
class GPXRoute:
gpx_10_fields = [
mod_gpxfield.GPXField('name'),
mod_gpxfield.GPXField('comment', 'cmt'),
mod_gpxfield.GPXField('description', 'desc'),
mod_gpxfield.GPXField('source', 'src'),
mod_gpxfield.GPXField('link', 'url'),
mod_gpxfield.GPXField('link_text', 'urlname'),
mod_gpxfield.GPXField('number', type=mod_gpxfield.INT_TYPE),
mod_gpxfield.GPXComplexField('points', tag='rtept', classs=GPXRoutePoint, is_list=True),
]
gpx_11_fields = [
# See GPX for description of text fields
mod_gpxfield.GPXField('name'),
mod_gpxfield.GPXField('comment', 'cmt'),
mod_gpxfield.GPXField('description', 'desc'),
mod_gpxfield.GPXField('source', 'src'),
'link:@link',
mod_gpxfield.GPXField('link', attribute='href'),
mod_gpxfield.GPXField('link_text', tag='text'),
mod_gpxfield.GPXField('link_type', tag='type'),
'/link',
mod_gpxfield.GPXField('number', type=mod_gpxfield.INT_TYPE),
mod_gpxfield.GPXField('type'),
mod_gpxfield.GPXExtensionsField('extensions', is_list=True),
mod_gpxfield.GPXComplexField('points', tag='rtept', classs=GPXRoutePoint, is_list=True),
]
__slots__ = ('name', 'comment', 'description', 'source', 'link',
'link_text', 'number', 'points', 'link_type', 'type',
'extensions')
def __init__(self, name=None, description=None, number=None):
self.name = name
self.comment = None
self.description = description
self.source = None
self.link = None
self.link_text = None
self.number = number
self.points = []
self.link_type = None
self.type = None
self.extensions = []
def adjust_time(self, delta):
"""
Adjusts the time of the all the points in the route by the specified delta.
Parameters
----------
delta : datetime.timedelta
Positive time delta will adjust time into the future
Negative time delta will adjust time into the past
"""
for point in self.points:
point.adjust_time(delta)
def remove_time(self):
""" Removes time meta data from route. """
for point in self.points:
point.remove_time()
def remove_elevation(self):
""" Removes elevation data from route """
for point in self.points:
point.remove_elevation()
def length(self):
"""
Computes length (2-dimensional) of route.
Returns:
-----------
length: float
Length returned in meters
"""
return mod_geo.length_2d(self.points)
def get_center(self):
"""
Get the center of the route.
Returns
-------
center: Location
latitude: latitude of center in degrees
longitude: longitude of center in degrees
elevation: not calculated here
"""
if not self.points:
return None
if not self.points:
return None
sum_lat = 0.
sum_lon = 0.
n = 0.
for point in self.points:
n += 1.
sum_lat += point.latitude
sum_lon += point.longitude
if not n:
return mod_geo.Location(float(0), float(0))
return mod_geo.Location(latitude=sum_lat / n, longitude=sum_lon / n)
def walk(self, only_points=False):
"""
Generator for iterating over route points
Parameters
----------
only_points: boolean
Only yield points (no index yielded)
Yields
------
point: GPXRoutePoint
A point in the GPXRoute
point_no: int
Not included in yield if only_points is true
"""
for point_no, point in enumerate(self.points):
if only_points:
yield point
else:
yield point, point_no
def get_points_no(self):
"""
Get the number of points in route.
Returns
----------
num_points : integer
Number of points in route
"""
return len(self.points)
def move(self, location_delta):
"""
Moves each point in the route.
Parameters
----------
location_delta: LocationDelta
LocationDelta to move each point
"""
for route_point in self.points:
route_point.move(location_delta)
def __repr__(self):
representation = ''
for attribute in 'name', 'description', 'number':
value = getattr(self, attribute)
if value is not None:
representation += '%s%s=%s' % (', ' if representation else '', attribute, repr(value))
representation += '%spoints=[%s])' % (', ' if representation else '', '...' if self.points else '')
return 'GPXRoute(%s)' % representation
class GPXTrackPoint(mod_geo.Location):
gpx_10_fields = GPX_TRACK_POINT_FIELDS
gpx_11_fields = GPX_11_POINT_FIELDS
__slots__ = ('latitude', 'longitude', 'elevation', 'time', 'course',
'speed', 'magnetic_variation', 'geoid_height', 'name',
'comment', 'description', 'source', 'link', 'link_text',
'symbol', 'type', 'type_of_gpx_fix', 'satellites',
'horizontal_dilution', 'vertical_dilution',
'position_dilution', 'age_of_dgps_data', 'dgps_id',
'link_type', 'extensions')
def __init__(self, latitude=None, longitude=None, elevation=None, time=None, symbol=None, comment=None,
horizontal_dilution=None, vertical_dilution=None, position_dilution=None, speed=None, course=None,
name=None, type_of_gpx_fix=None):
mod_geo.Location.__init__(self, latitude, longitude, elevation)
self.latitude = latitude
self.longitude = longitude
self.elevation = elevation
self.time = time
self.course = course
self.speed = speed
self.magnetic_variation = None
self.geoid_height = None
self.name = name
self.comment = comment
self.description = None
self.source = None
self.link = None
self.link_text = None
self.link_type = None
self.symbol = symbol
self.type = None
self.type_of_gpx_fix = type_of_gpx_fix
self.satellites = None
self.horizontal_dilution = horizontal_dilution
self.vertical_dilution = vertical_dilution
self.position_dilution = position_dilution
self.age_of_dgps_data = None
self.dgps_id = None
self.extensions = []
def __repr__(self):
representation = '%s, %s' % (self.latitude, self.longitude)
for attribute in 'elevation', 'time', 'symbol', 'comment', 'horizontal_dilution', \
'vertical_dilution', 'position_dilution', 'speed', 'name':
value = getattr(self, attribute)
if value is not None:
representation += ', %s=%s' % (attribute, repr(value))
return 'GPXTrackPoint(%s)' % representation
def adjust_time(self, delta):
"""
Adjusts the time of the point by the specified delta
Parameters
----------
delta : datetime.timedelta
Positive time delta will adjust time into the future
Negative time delta will adjust time into the past
"""
if self.time:
self.time += delta
def remove_time(self):
""" Will remove time metadata. """
self.time = None
def time_difference(self, track_point):
"""
Get time difference between specified point and this point.
Parameters
----------
track_point : GPXTrackPoint
Returns
----------
time_difference : float
Time difference returned in seconds
"""
if not self.time or not track_point or not track_point.time:
return None
time_1 = self.time
time_2 = track_point.time
if time_1 == time_2:
return 0
if time_1 > time_2:
delta = time_1 - time_2
else:
delta = time_2 - time_1
return mod_utils.total_seconds(delta)
def speed_between(self, track_point):
"""
Compute the speed between specified point and this point.
NOTE: This is a computed speed, not the GPXTrackPoint speed that comes
the GPX file.
Parameters
----------
track_point : GPXTrackPoint
Returns
----------
speed : float
Speed returned in meters/second
"""
if not track_point:
return None
seconds = self.time_difference(track_point)
length = self.distance_3d(track_point)
if not length:
length = self.distance_2d(track_point)
if not seconds or length is None:
return None
return length / float(seconds)
def __str__(self):
return '[trkpt:%s,%s@%s@%s]' % (self.latitude, self.longitude, self.elevation, self.time)
class GPXTrackSegment:
gpx_10_fields = [
mod_gpxfield.GPXComplexField('points', tag='trkpt', classs=GPXTrackPoint, is_list=True),
]
gpx_11_fields = [
mod_gpxfield.GPXComplexField('points', tag='trkpt', classs=GPXTrackPoint, is_list=True),
mod_gpxfield.GPXExtensionsField('extensions', is_list=True),
]
__slots__ = ('points', 'extensions', )
def __init__(self, points=None):
self.points = points if points else []
self.extensions = []
def simplify(self, max_distance=None):
"""
Simplify using the Ramer-Douglas-Peucker algorithm: http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
"""
if not max_distance:
max_distance = 10
self.points = mod_geo.simplify_polyline(self.points, max_distance)
def reduce_points(self, min_distance):
"""
Reduces the number of points in the track segment. Segment points will
be updated in place.
Parameters
----------
min_distance : float
The minimum separation in meters between points
"""
reduced_points = []
for point in self.points:
if reduced_points:
distance = reduced_points[-1].distance_3d(point)
if distance >= min_distance:
reduced_points.append(point)
else:
# Leave first point:
reduced_points.append(point)
self.points = reduced_points
def _find_next_simplified_point(self, pos, max_distance):
for candidate in range(pos + 1, len(self.points) - 1):
for i in range(pos + 1, candidate):
d = mod_geo.distance_from_line(self.points[i],
self.points[pos],
self.points[candidate])
if d > max_distance:
return candidate - 1
return None
def adjust_time(self, delta):
"""
Adjusts the time of all points in the segment by the specified delta
Parameters
----------
delta : datetime.timedelta
Positive time delta will adjust point times into the future
Negative time delta will adjust point times into the past
"""
for track_point in self.points:
track_point.adjust_time(delta)
def remove_time(self):
""" Removes time data for all points in the segment. """
for track_point in self.points:
track_point.remove_time()
def remove_elevation(self):
""" Removes elevation data for all points in the segment. """
for track_point in self.points:
track_point.remove_elevation()
def length_2d(self):
"""
Computes 2-dimensional length (meters) of segment (only latitude and
longitude, no elevation).
Returns
----------
length : float
Length returned in meters
"""
return mod_geo.length_2d(self.points)
def length_3d(self):
"""
Computes 3-dimensional length of segment (latitude, longitude, and
elevation).
Returns
----------
length : float
Length returned in meters
"""
return mod_geo.length_3d(self.points)
def move(self, location_delta):
"""
Moves each point in the segment.
Parameters
----------
location_delta: LocationDelta object
Delta (distance/angle or lat/lon offset to apply each point in the
segment
"""
for track_point in self.points:
track_point.move(location_delta)
def walk(self, only_points=False):
"""
Generator for iterating over segment points
Parameters
----------
only_points: boolean
Only yield points (no index yielded)
Yields
------
point: GPXTrackPoint
A point in the sement
point_no: int
Not included in yield if only_points is true
"""
for point_no, point in enumerate(self.points):
if only_points:
yield point
else:
yield point, point_no
def get_points_no(self):
"""
Gets the number of points in segment.
Returns
----------
num_points : integer
Number of points in segment
"""
if not self.points:
return 0
return len(self.points)
def split(self, point_no):
"""
Splits the segment into two parts. If one of the split segments is
empty it will not be added in the result. The segments will be split
in place.
Parameters
----------
point_no : integer
The index of the track point in the segment to split
"""
part_1 = self.points[:point_no + 1]
part_2 = self.points[point_no + 1:]
return GPXTrackSegment(part_1), GPXTrackSegment(part_2)
def join(self, track_segment):
""" Joins with another segment """
self.points += track_segment.points
def remove_point(self, point_no):
""" Removes a point specificed by index from the segment """
if point_no < 0 or point_no >= len(self.points):
return
part_1 = self.points[:point_no]
part_2 = self.points[point_no + 1:]
self.points = part_1 + part_2
def get_moving_data(self, stopped_speed_threshold=None):
"""
Return a tuple of (moving_time, stopped_time, moving_distance,
stopped_distance, max_speed) that may be used for detecting the time
stopped, and max speed. Not that those values are not absolutely true,
because the "stopped" or "moving" information aren't saved in the segment.
Because of errors in the GPS recording, it may be good to calculate
them on a reduced and smoothed version of the track.
Parameters
----------
stopped_speed_threshold : float
speeds (km/h) below this threshold are treated as if having no
movement. Default is 1 km/h.
Returns
----------
moving_data : MovingData : named tuple
moving_time : float
time (seconds) of segment in which movement was occurring
stopped_time : float
time (seconds) of segment in which no movement was occurring
stopped_distance : float
distance (meters) travelled during stopped times
moving_distance : float
distance (meters) travelled during moving times
max_speed : float
Maximum speed (m/s) during the segment.
"""
if not stopped_speed_threshold:
stopped_speed_threshold = DEFAULT_STOPPED_SPEED_THRESHOLD
moving_time = 0.
stopped_time = 0.
moving_distance = 0.
stopped_distance = 0.
speeds_and_distances = []
for i in range(1, len(self.points)):
previous = self.points[i - 1]
point = self.points[i]
# Won't compute max_speed for first and last because of common GPS
# recording errors, and because smoothing don't work well for those
# points:
if point.time and previous.time:
timedelta = point.time - previous.time
if point.elevation and previous.elevation:
distance = point.distance_3d(previous)
else:
distance = point.distance_2d(previous)
seconds = mod_utils.total_seconds(timedelta)
speed_kmh = 0
if seconds > 0:
# TODO: compute threshold in m/s instead this to kmh every time:
speed_kmh = (distance / 1000.) / (mod_utils.total_seconds(timedelta) / 60. ** 2)
#print speed, stopped_speed_threshold
if speed_kmh <= stopped_speed_threshold:
stopped_time += mod_utils.total_seconds(timedelta)
stopped_distance += distance
else:
moving_time += mod_utils.total_seconds(timedelta)
moving_distance += distance
if distance and moving_time:
speeds_and_distances.append((distance / mod_utils.total_seconds(timedelta), distance, ))
max_speed = None
if speeds_and_distances:
max_speed = mod_geo.calculate_max_speed(speeds_and_distances)
return MovingData(moving_time, stopped_time, moving_distance, stopped_distance, max_speed)
def get_time_bounds(self):
"""
Gets the time bound (start and end) of the segment.
returns
----------
time_bounds : TimeBounds named tuple
start_time : datetime
Start time of the first segment in track
end time : datetime
End time of the last segment in track
"""
start_time = None
end_time = None
for point in self.points:
if point.time:
if not start_time:
start_time = point.time
if point.time:
end_time = point.time
return TimeBounds(start_time, end_time)
def get_bounds(self):
"""
Gets the latitude and longitude bounds of the segment.
Returns
----------
bounds : Bounds named tuple
min_latitude : float
Minimum latitude of segment in decimal degrees [-90, 90]
max_latitude : float
Maximum latitude of segment in decimal degrees [-90, 90]
min_longitude : float
Minimum longitude of segment in decimal degrees [-180, 180]
max_longitude : float
Maximum longitude of segment in decimal degrees [-180, 180]
"""
min_lat = None
max_lat = None
min_lon = None
max_lon = None
for point in self.points:
if min_lat is None or point.latitude < min_lat:
min_lat = point.latitude
if max_lat is None or point.latitude > max_lat:
max_lat = point.latitude
if min_lon is None or point.longitude < min_lon:
min_lon = point.longitude
if max_lon is None or point.longitude > max_lon:
max_lon = point.longitude
return GPXBounds(min_lat, max_lat, min_lon, max_lon)
def get_speed(self, point_no):
"""
Computes the speed at the specified point index.
Parameters
----------
point_no : integer
index of the point used to compute speed
Returns
----------
speed : float
Speed returned in m/s
"""
point = self.points[point_no]
previous_point = None
next_point = None
if 0 < point_no < len(self.points):
previous_point = self.points[point_no - 1]
if 0 <= point_no < len(self.points) - 1:
next_point = self.points[point_no + 1]
#log.debug('previous: %s' % previous_point)
#log.debug('next: %s' % next_point)
speed_1 = point.speed_between(previous_point)
speed_2 = point.speed_between(next_point)
if speed_1:
speed_1 = abs(speed_1)
if speed_2:
speed_2 = abs(speed_2)
if speed_1 and speed_2:
return (speed_1 + speed_2) / 2.
if speed_1:
return speed_1
return speed_2
def add_elevation(self, delta):
"""
Adjusts elevation data for segment.
Parameters
----------
delta : float
Elevation delta in meters to apply to track
"""
log.debug('delta = %s' % delta)
if not delta:
return
for track_point in self.points:
if track_point.elevation is not None:
track_point.elevation += delta
def add_missing_data(self, get_data_function, add_missing_function):
"""
Calculate missing data.
Parameters
----------