-
Notifications
You must be signed in to change notification settings - Fork 224
/
test.py
3587 lines (2705 loc) · 166 KB
/
test.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
# 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.
"""
Run all tests with:
$ python -m unittest test
Run lxml parser test with:
$ python -m unittest test.LxmlTest
Run single test with:
$ python -m unittest test.GPXTests.test_method
"""
import logging as mod_logging
import os as mod_os
import time as mod_time
import codecs as mod_codecs
import copy as mod_copy
import datetime as mod_datetime
import random as mod_random
import math as mod_math
import sys as mod_sys
import unittest as mod_unittest
import xml.dom.minidom as mod_minidom
try:
# Load LXML or fallback to cET or ET
import lxml.etree as mod_etree # type: ignore
except:
try:
import xml.etree.cElementTree as mod_etree # type: ignore
except:
import xml.etree.ElementTree as mod_etree # type: ignore
import gpxpy as mod_gpxpy
import gpxpy.gpx as mod_gpx
import gpxpy.gpxxml as mod_gpxxml
import gpxpy.gpxfield as mod_gpxfield
import gpxpy.parser as mod_parser
import gpxpy.geo as mod_geo
from gpxpy.utils import make_str
from gpxpy.utils import total_seconds
from typing import *
mod_logging.basicConfig(level=mod_logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
def equals(object1: Any, object2: Any, ignore: Any=None) -> bool:
""" Testing purposes only """
if not object1 and not object2:
return True
if not object1 or not object2:
print('Not obj2')
return False
if not object1.__class__ == object2.__class__:
print('Not obj1')
return False
attributes: List[str] = []
for attr in dir(object1):
if not ignore or not attr in ignore:
if not hasattr(object1, '__call__') and not attr.startswith('_'):
if not attr in attributes:
attributes.append(attr)
for attr in attributes:
attr1 = getattr(object1, attr)
attr2 = getattr(object2, attr)
if attr1 == attr2:
return True
if not attr1 and not attr2:
return True
if not attr1 or not attr2:
print(f'Object differs in attribute {attr} ({attr1} - {attr2})')
return False
if not equals(attr1, attr2):
print(f'Object differs in attribute {attr} ({attr1} - {attr2})')
return False
return True
def almostEqual(number1: float, number2: float) -> bool:
return 1 - number1 / number2 < 0.999999
def get_dom_node(dom: Any, path: str) -> Any:
path_parts = path.split('/')
result = dom
for path_part in path_parts:
if '[' in path_part:
tag_name = path_part.split('[')[0]
n = int(path_part.split('[')[1].replace(']', ''))
else:
tag_name = path_part
n = 0
candidates = []
for child in result.childNodes:
if child.nodeName == tag_name:
candidates.append(child)
try:
result = candidates[n]
except Exception:
raise Exception(f'Can\'t fint {n}th child of {path_part}')
return result
##def pretty_print_xml(xml):
## dom = mod_minidom.parseString(xml)
## print(dom.toprettyxml())
## input()
def node_strip(text: str) -> str:
if text is None:
return ''
return text.strip()
def elements_equal(e1: Any, e2: Any) -> bool:
if node_strip(e1.tag) != node_strip(e2.tag): return False
if node_strip(e1.text) != node_strip(e2.text): return False
if node_strip(e1.tail) != node_strip(e2.tail): return False
if e1.attrib != e2.attrib: return False
if len(e1) != len(e2): return False
return all(elements_equal(c1, c2) for c1, c2 in zip(e1, e2))
def print_etree(e1: Any, indent: str='') -> str:
tag = [f'{indent}tag: |{e1.tag}|\n']
for att, value in e1.attrib.items():
tag.append(f'{indent}-att: |{att}| = |{value}|\n')
tag.append(f'{indent}-text: |{e1.text}|\n')
tag.append(f'{indent}-tail: |{e1.tail}|\n')
for subelem in e1:
tag.append(print_etree(subelem, indent+'__|'))
return ''.join(tag)
class GPXTests(mod_unittest.TestCase):
"""
Add tests here.
"""
def parse(self, file: Any, encoding: Optional[str]=None, version: Optional[str]=None) -> mod_gpx.GPX:
with open(f'test_files/{file}', encoding=encoding) as f:
parser = mod_parser.GPXParser(f)
return parser.parse(version)
def reparse(self, gpx: mod_gpx.GPX) -> mod_gpx.GPX:
xml = gpx.to_xml()
parser = mod_parser.GPXParser(xml)
gpx = parser.parse()
if not gpx:
print('Parser error while reparsing')
return gpx
def test_simple_parse_function(self) -> None:
# Must not throw any exception:
with open('test_files/korita-zbevnica.gpx', encoding='utf-8') as f:
mod_gpxpy.parse(f)
def test_parse_bytes(self) -> None:
# Must not throw any exception:
with open('test_files/korita-zbevnica.gpx', encoding='utf-8') as f:
byts = f.read().encode(encoding='utf-8')
print(type(byts))
mod_gpxpy.parse(byts)
def test_simple_parse_function_invalid_root_tag(self) -> None:
try:
mod_gpxpy.parse('<kml></kml>')
self.fail()
except mod_gpx.GPXException as e:
print(str(e))
self.assertTrue(('Document must have a `gpx` root node.' in str(e)) or ('expected \'>\'' in str(e)))
self.assertTrue(isinstance(e, mod_gpx.GPXException))
def test_simple_parse_function_invalid_xml(self) -> None:
try:
mod_gpxpy.parse('<gpx></gpx')
self.fail()
except mod_gpx.GPXException as e:
self.assertTrue(('unclosed token: line 1, column 5' in str(e)) or ('expected \'>\'' in str(e)))
self.assertTrue(isinstance(e, mod_gpx.GPXXMLSyntaxException))
self.assertTrue(e.__cause__)
try:
# more checks if lxml:
import lxml.etree as mod_etree
import xml.parsers.expat as mod_expat
self.assertTrue(isinstance(e.__cause__, mod_etree.XMLSyntaxError)
or isinstance(e.__cause__, mod_expat.ExpatError))
except:
pass
def test_creator_field(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
self.assertEqual(gpx.creator, "GPSBabel - http://www.gpsbabel.org")
def test_no_creator_field(self) -> None:
gpx = self.parse('cerknicko-jezero-no-creator.gpx')
self.assertEqual(gpx.creator, None)
def test_to_xml_creator(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
xml = gpx.to_xml()
self.assertTrue('creator="GPSBabel - http://www.gpsbabel.org"' in xml)
gpx2 = self.reparse(gpx)
self.assertEqual(gpx2.creator, "GPSBabel - http://www.gpsbabel.org")
def test_waypoints_equality_after_reparse(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
gpx2 = self.reparse(gpx)
self.assertTrue(equals(gpx.waypoints, gpx2.waypoints))
self.assertTrue(equals(gpx.routes, gpx2.routes))
self.assertTrue(equals(gpx.tracks, gpx2.tracks))
self.assertTrue(equals(gpx, gpx2))
def test_waypoint_time(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
self.assertTrue(gpx.waypoints[0].time)
self.assertTrue(isinstance(gpx.waypoints[0].time, mod_datetime.datetime))
def test_add_elevation(self) -> None:
gpx = mod_gpx.GPX()
gpx.tracks.append(mod_gpx.GPXTrack())
gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment())
gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13, elevation=100))
gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13))
gpx.add_elevation(10)
self.assertEqual(gpx.tracks[0].segments[0].points[0].elevation, 110)
self.assertEqual(gpx.tracks[0].segments[0].points[1].elevation, None)
gpx.add_elevation(-20)
self.assertEqual(gpx.tracks[0].segments[0].points[0].elevation, 90)
self.assertEqual(gpx.tracks[0].segments[0].points[1].elevation, None)
def test_get_duration(self) -> None:
gpx = mod_gpx.GPX()
gpx.tracks.append(mod_gpx.GPXTrack())
gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment())
gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13,
time=mod_datetime.datetime(2013, 1, 1, 12, 30)))
self.assertEqual(gpx.get_duration(), 0)
gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment())
gpx.tracks[0].segments[1].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13))
self.assertEqual(gpx.get_duration(), 0)
gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment())
gpx.tracks[0].segments[2].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13,
time=mod_datetime.datetime(2013, 1, 1, 12, 30)))
gpx.tracks[0].segments[2].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13,
time=mod_datetime.datetime(2013, 1, 1, 12, 31)))
self.assertEqual(gpx.get_duration(), 60)
def test_remove_elevation(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
for point, track_no, segment_no, point_no in gpx.walk():
self.assertTrue(point.elevation is not None)
gpx.remove_elevation(tracks=True, waypoints=True, routes=True)
for point, track_no, segment_no, point_no in gpx.walk():
self.assertTrue(point.elevation is None)
xml = gpx.to_xml()
self.assertFalse('<ele>' in xml)
def test_remove_time_tracks_only(self) -> None:
gpx = self.parse('cerknicko-jezero.gpx')
for point, track_no, segment_no, point_no in gpx.walk():
self.assertTrue(point.time is not None)
gpx.remove_time()
for point, track_no, segment_no, point_no in gpx.walk():
self.assertTrue(point.time is None)
def test_remove_time_all(self) -> None:
gpx = mod_gpx.GPX()
t0 = mod_datetime.datetime(2018, 7, 15, 12, 30, 0)
t1 = mod_datetime.datetime(2018, 7, 15, 12, 31, 0)
gpx.tracks.append(mod_gpx.GPXTrack())
gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment())
p0 = mod_gpx.GPXTrackPoint(latitude=13.0, longitude=13.0, time=t0)
p1 = mod_gpx.GPXTrackPoint(latitude=13.1, longitude=13.1, time=t1)
gpx.tracks[0].segments[0].points.append(p0)
gpx.tracks[0].segments[0].points.append(p1)
gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.0, longitude=13.0, time=t0))
gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.1, longitude=13.1, time=t1))
gpx.routes.append(mod_gpx.GPXRoute())
p0 = mod_gpx.GPXRoutePoint(latitude=13.0, longitude=13.0, time=t0) # type: ignore
p1 = mod_gpx.GPXRoutePoint(latitude=13.1, longitude=13.1, time=t1) # type: ignore
gpx.routes[0].points.append(p0) # type: ignore
gpx.routes[0].points.append(p1) # type: ignore
gpx.remove_time(all=True)
for point, track_no, segment_no, point_no in gpx.walk():
self.assertTrue(point.time is None)
for point in gpx.waypoints:
self.assertTrue(point.time is None)
for route in gpx.routes:
for point, _ in route.walk():
self.assertTrue(point.time is None)
def test_has_times_false(self) -> None:
gpx = self.parse('cerknicko-without-times.gpx')
self.assertFalse(gpx.has_times())
def test_has_times(self) -> None:
gpx = self.parse('korita-zbevnica.gpx')
self.assertTrue(len(gpx.tracks) == 4)
# Empty -- True
self.assertTrue(gpx.tracks[0].has_times())
# Not times ...
self.assertTrue(not gpx.tracks[1].has_times())
# Times OK
self.assertTrue(gpx.tracks[2].has_times())
self.assertTrue(gpx.tracks[3].has_times())
def test_total_time_support_less_one_sec(self) -> None:
start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0)
end_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0, 994000)
d_time = end_time - start_time
moving_time = total_seconds(d_time)
self.assertEqual(0.994, moving_time)
def test_total_time_none(self) -> None:
moving_time = total_seconds(None) #type: ignore
self.assertIsNone(moving_time)
def test_unicode_name(self) -> None:
gpx = self.parse('unicode.gpx', encoding='utf-8')
name = gpx.waypoints[0].name
self.assertTrue(make_str(name) == 'šđčćž') # type: ignore
def test_unicode_2(self) -> None:
with open('test_files/unicode2.gpx', encoding='utf-8') as f:
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
gpx.to_xml()
def test_unicode_bom(self) -> None:
# TODO: Check that this file has the BOM and is unicode before checking gpxpy handling
gpx = self.parse('unicode_with_bom.gpx', encoding='utf-8')
name = gpx.waypoints[0].name
self.assertTrue(make_str(name) == 'test') # type: ignore
def test_unicode_bom_noencoding(self) -> None:
gpx = self.parse('unicode_with_bom_noencoding.gpx', encoding='utf-8')
name = gpx.waypoints[0].name
self.assertTrue(make_str(name) == 'bom noencoding ő') # type: ignore
def test_force_version(self) -> None:
gpx = self.parse('unicode_with_bom.gpx', version = '1.1', encoding='utf-8')
# TODO: Implement new test. Current gpx is not valid (extensions using default namespace).
# I don't want to edit this file without easy verification that it has the BOM and is unicode
## security = gpx.waypoints[0].extensions['security']
##
## self.assertTrue(make_str(security) == 'Open')
def test_nearest_location_1(self) -> None:
def test_nearest_gpx(gpx: mod_gpx.GPX) -> None:
def test_nearest(gpx: mod_gpx.GPX,loc: mod_geo.Location) -> None:
def test_nearest_part(gpx_part: Union[mod_gpx.GPX, mod_gpx.GPXTrack, mod_gpx.GPXTrackSegment], loc: mod_geo.Location) -> mod_gpx.NearestLocationData:
nearest_loc_info = gpx_part.get_nearest_location(loc)
print(gpx_part,nearest_loc_info)
self.assertTrue(nearest_loc_info is not None)
location = nearest_loc_info.location # type: ignore
nearest_nearest_loc_info = gpx_part.get_nearest_location(location)
self.assertTrue(nearest_nearest_loc_info == nearest_loc_info)
return nearest_loc_info # type: ignore
nearest_loc_info =test_nearest_part( gpx, loc)
location=nearest_loc_info.location
point = gpx.tracks[nearest_loc_info.track_no].segments[nearest_loc_info.segment_no].points[nearest_loc_info.point_no]
self.assertTrue(point.distance_2d(location) < 0.001) # type: ignore
self.assertTrue(point.distance_2d(nearest_loc_info.location) < 0.001) # type: ignore
test_nearest_part( gpx.tracks[nearest_loc_info.track_no], loc)
test_nearest_part( gpx.tracks[nearest_loc_info.track_no].segments[nearest_loc_info.segment_no], loc)
test_nearest(gpx,mod_geo.Location(45.451058791, 14.027903696))
test_nearest(gpx,mod_geo.Location(1, 1))
test_nearest(gpx,mod_geo.Location(50,50))
gpx = self.parse('korita-zbevnica.gpx')
test_nearest_gpx(gpx)
gpx.tracks[0].segments[0].points = None # type: ignore
test_nearest_gpx(gpx)
gpx.tracks[0].segments = None # type: ignore
test_nearest_gpx(gpx)
gpx.tracks = None # type: ignore
self.assertTrue( gpx.get_nearest_location(mod_geo.Location(1, 1)) is None)
def test_long_timestamps(self) -> None:
# Check if timestamps in format: 1901-12-13T20:45:52.2073437Z work
gpx = self.parse('Mojstrovka.gpx')
# %Y-%m-%dT%H:%M:%SZ'
self.assertEqual(gpx.tracks[0].segments[0].points[0].elevation, 1614.678000)
self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(1901, 12, 13, 20, 45, 52, 207343, tzinfo=mod_gpxfield.SimpleTZ()))
self.assertEqual(gpx.tracks[0].segments[0].points[1].time, mod_datetime.datetime(1901, 12, 13, 20, 45, 52, 207000, tzinfo=mod_gpxfield.SimpleTZ()))
def test_reduce_gpx_file(self) -> None:
f = open('test_files/Mojstrovka.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
max_reduced_points_no = 50
started = mod_time.time()
points_original = gpx.get_track_points_no()
time_original = mod_time.time() - started
gpx.reduce_points(max_reduced_points_no)
points_reduced = gpx.get_track_points_no()
result = gpx.to_xml()
started = mod_time.time()
parser = mod_parser.GPXParser(result)
parser.parse()
time_reduced = mod_time.time() - started
print(time_original)
print(points_original)
print(time_reduced)
print(points_reduced)
self.assertTrue(points_reduced < points_original)
self.assertTrue(points_reduced < max_reduced_points_no)
def test_smooth_without_removing_extreemes_preserves_point_count(self) -> None:
gpx = self.parse('first_and_last_elevation.gpx')
l = len(list(gpx.walk()))
gpx.smooth(vertical=True, horizontal=False)
self.assertEqual(l, len(list(gpx.walk())))
def test_smooth_without_removing_extreemes_preserves_point_count_2(self) -> None:
gpx = self.parse('first_and_last_elevation.gpx')
l = len(list(gpx.walk()))
gpx.smooth(vertical=False, horizontal=True)
self.assertEqual(l, len(list(gpx.walk())))
def test_smooth_without_removing_extreemes_preserves_point_count_3(self) -> None:
gpx = self.parse('first_and_last_elevation.gpx')
l = len(list(gpx.walk()))
gpx.smooth(vertical=True, horizontal=True)
self.assertEqual(l, len(list(gpx.walk())))
def test_clone_and_smooth(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
original_2d = gpx.length_2d()
original_3d = gpx.length_3d()
cloned_gpx = gpx.clone()
cloned_gpx.reduce_points(2000, min_distance=10)
cloned_gpx.smooth(vertical=True, horizontal=True)
cloned_gpx.smooth(vertical=True, horizontal=False)
print('2d:', gpx.length_2d())
print('2d cloned and smoothed:', cloned_gpx.length_2d())
print('3d:', gpx.length_3d())
print('3d cloned and smoothed:', cloned_gpx.length_3d())
self.assertTrue(gpx.length_3d() == original_3d)
self.assertTrue(gpx.length_2d() == original_2d)
self.assertTrue(gpx.length_3d() > cloned_gpx.length_3d())
self.assertTrue(gpx.length_2d() > cloned_gpx.length_2d())
def test_reduce_by_min_distance(self) -> None:
with open('test_files/cerknicko-jezero.gpx') as f:
gpx = mod_gpxpy.parse(f)
min_distance_before_reduce = 1000000
for point, track_no, segment_no, point_no in gpx.walk():
if point_no > 0:
previous_point = gpx.tracks[track_no].segments[segment_no].points[point_no - 1]
if point.distance_3d(previous_point) < min_distance_before_reduce:
min_distance_before_reduce = point.distance_3d(previous_point)
gpx.reduce_points(min_distance=10)
min_distance_after_reduce = 1000000
for point, track_no, segment_no, point_no in gpx.walk():
if point_no > 0:
previous_point = gpx.tracks[track_no].segments[segment_no].points[point_no - 1]
if point.distance_3d(previous_point) < min_distance_after_reduce:
min_distance_after_reduce = point.distance_3d(previous_point)
self.assertTrue(min_distance_before_reduce < min_distance_after_reduce)
self.assertTrue(min_distance_before_reduce < 10)
self.assertTrue(10 < min_distance_after_reduce)
def test_moving_stopped_times(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
print(gpx.get_track_points_no())
#gpx.reduce_points(1000, min_distance=5)
print(gpx.get_track_points_no())
length = gpx.length_3d()
print(f'Distance: {length}')
gpx.reduce_points(2000, min_distance=10)
gpx.smooth(vertical=True, horizontal=True)
gpx.smooth(vertical=True, horizontal=False)
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data(stopped_speed_threshold=0.1)
print('-----')
print(f'Length: {length}')
print(f'Moving time: {moving_time} ({moving_time / 60.}min)')
print(f'Stopped time: {stopped_time} ({stopped_time / 60.}min)')
print(f'Moving distance: {moving_distance}')
print(f'Stopped distance: {stopped_distance}')
print(f'Max speed: {max_speed}m/s')
print('-----')
# TODO: More tests and checks
self.assertTrue(moving_distance < length)
print('Dakle:', moving_distance, length)
self.assertTrue(moving_distance > 0.75 * length)
self.assertTrue(stopped_distance < 0.1 * length)
def test_split_on_impossible_index(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
track = gpx.tracks[0]
before = len(track.segments)
track.split(1000, 10)
after = len(track.segments)
self.assertTrue(before == after)
def test_split(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
track = gpx.tracks[1]
track_points_no = track.get_points_no()
before = len(track.segments)
track.split(0, 10)
after = len(track.segments)
self.assertTrue(before + 1 == after)
print('Points in first (split) part:', len(track.segments[0].points))
# From 0 to 10th point == 11 points:
self.assertTrue(len(track.segments[0].points) == 11)
self.assertTrue(len(track.segments[0].points) + len(track.segments[1].points) == track_points_no)
# Now split the second track
track.split(1, 20)
self.assertTrue(len(track.segments[1].points) == 21)
self.assertTrue(len(track.segments[0].points) + len(track.segments[1].points) + len(track.segments[2].points) == track_points_no)
def test_split_and_join(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
track = gpx.tracks[1]
original_track = track.clone()
track.split(0, 10)
track.split(1, 20)
self.assertTrue(len(track.segments) == 3)
track.join(1)
self.assertTrue(len(track.segments) == 2)
track.join(0)
self.assertTrue(len(track.segments) == 1)
# Check that this split and joined track is the same as the original one:
self.assertTrue(equals(track, original_track))
def test_remove_point_from_segment(self) -> None:
f = open('test_files/cerknicko-jezero.gpx')
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
track = gpx.tracks[1]
segment = track.segments[0]
original_segment = segment.clone()
segment.remove_point(3)
print(segment.points[0])
print(original_segment.points[0])
self.assertTrue(equals(segment.points[0], original_segment.points[0]))
self.assertTrue(equals(segment.points[1], original_segment.points[1]))
self.assertTrue(equals(segment.points[2], original_segment.points[2]))
# ...but:
self.assertTrue(equals(segment.points[3], original_segment.points[4]))
self.assertTrue(len(segment.points) + 1 == len(original_segment.points))
def test_distance(self) -> None:
distance = mod_geo.distance(48.56806, 21.43467, None, 48.599214, 21.430878, False)
print(distance)
self.assertTrue(3450 < distance < 3500)
def test_haversine_and_nonhaversine(self) -> None:
haversine_dist = mod_geo.distance(0, 0, 0, 0.1, 0.1, 0, haversine=True)
nonhaversine_dist = mod_geo.distance(0, 0, 0, 0.1, 0.1, 0, haversine=False)
print("haversine_dist=", haversine_dist)
print("nonhaversine_dist=", nonhaversine_dist)
self.assertTrue(haversine_dist != nonhaversine_dist)
self.assertAlmostEqual(haversine_dist, nonhaversine_dist, delta=15)
def test_haversine_distance(self) -> None:
loc1 = mod_geo.Location(1, 2)
loc2 = mod_geo.Location(2, 3)
self.assertEqual(loc1.distance_2d(loc2),
mod_geo.distance(loc1.latitude, loc1.longitude, None, loc2.latitude, loc2.longitude, False))
loc1 = mod_geo.Location(1, 2)
loc2 = mod_geo.Location(3, 4)
self.assertEqual(loc1.distance_2d(loc2),
mod_geo.distance(loc1.latitude, loc1.longitude, None, loc2.latitude, loc2.longitude, False))
loc1 = mod_geo.Location(1, 2)
loc2 = mod_geo.Location(3.1, 4)
self.assertEqual(loc1.distance_2d(loc2),
mod_geo.haversine_distance(loc1.latitude, loc1.longitude, loc2.latitude, loc2.longitude))
loc1 = mod_geo.Location(1, 2)
loc2 = mod_geo.Location(2, 4.1)
self.assertEqual(loc1.distance_2d(loc2),
mod_geo.haversine_distance(loc1.latitude, loc1.longitude, loc2.latitude, loc2.longitude))
def test_horizontal_smooth_remove_extremes(self) -> None:
with open('test_files/track-with-extremes.gpx') as f:
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
points_before = gpx.get_track_points_no()
gpx.smooth(vertical=False, horizontal=True, remove_extremes=True)
points_after = gpx.get_track_points_no()
print(points_before)
print(points_after)
self.assertTrue(points_before - 2 == points_after)
def test_vertical_smooth_remove_extremes(self) -> None:
with open('test_files/track-with-extremes.gpx') as f:
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
points_before = gpx.get_track_points_no()
gpx.smooth(vertical=True, horizontal=False, remove_extremes=True)
points_after = gpx.get_track_points_no()
print(points_before)
print(points_after)
self.assertTrue(points_before - 1 == points_after)
def test_horizontal_and_vertical_smooth_remove_extremes(self) -> None:
with open('test_files/track-with-extremes.gpx') as f:
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
points_before = gpx.get_track_points_no()
gpx.smooth(vertical=True, horizontal=True, remove_extremes=True)
points_after = gpx.get_track_points_no()
print(points_before)
print(points_after)
self.assertTrue(points_before - 3 == points_after)
def test_positions_on_track(self) -> None:
gpx = mod_gpx.GPX()
track = mod_gpx.GPXTrack()
gpx.tracks.append(track)
segment = mod_gpx.GPXTrackSegment()
track.segments.append(segment)
location_to_find_on_track = None
for i in range(1000):
latitude = 45 + i * 0.001
longitude = 45 + i * 0.001
elevation = 100 + i * 2
point = mod_gpx.GPXTrackPoint(latitude=latitude, longitude=longitude, elevation=elevation)
segment.points.append(point)
if i == 500:
location_to_find_on_track = mod_gpx.GPXWaypoint(latitude=latitude, longitude=longitude)
result = gpx.get_nearest_locations(location_to_find_on_track) # type: ignore
self.assertTrue(len(result) == 1)
def test_spaces_in_elevation(self) -> None:
gpx = mod_gpxpy.parse("""<?xml version='1.0' encoding='UTF-8'?>
<gpx version='1.1' creator='GPSMID' xmlns='http://www.topografix.com/GPX/1/1'>
<trk><trkseg><trkpt lat='40.61262' lon='10.592117'><ele>
100
</ele><time>2018-01-01T09:00:00Z</time></trkpt></trkseg></trk>
</gpx>""")
self.assertEqual(100, gpx.tracks[0].segments[0].points[0].elevation)
def test_positions_on_track_2(self) -> None:
gpx = mod_gpx.GPX()
track = mod_gpx.GPXTrack()
gpx.tracks.append(track)
location_to_find_on_track = None
# first segment:
segment = mod_gpx.GPXTrackSegment()
track.segments.append(segment)
for i in range(1000):
latitude = 45 + i * 0.001
longitude = 45 + i * 0.001
elevation = 100 + i * 2
point = mod_gpx.GPXTrackPoint(latitude=latitude, longitude=longitude, elevation=elevation)
segment.points.append(point)
if i == 500:
location_to_find_on_track = mod_gpx.GPXWaypoint(latitude=latitude, longitude=longitude)
# second segment
segment = mod_gpx.GPXTrackSegment()
track.segments.append(segment)
for i in range(1000):
latitude = 45.0000001 + i * 0.001
longitude = 45.0000001 + i * 0.001
elevation = 100 + i * 2
point = mod_gpx.GPXTrackPoint(latitude=latitude, longitude=longitude, elevation=elevation)
segment.points.append(point)
result = gpx.get_nearest_locations(location_to_find_on_track) # type: ignore
print('Found', result)
self.assertTrue(len(result) == 2)
def test_bounds(self) -> None:
gpx = mod_gpx.GPX()
track = mod_gpx.GPXTrack()
segment_1 = mod_gpx.GPXTrackSegment()
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=-12, longitude=13))
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=-100, longitude=-5))
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=100, longitude=-13))
track.segments.append(segment_1)
segment_2 = mod_gpx.GPXTrackSegment()
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=-12, longitude=100))
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=-10, longitude=-5))
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=10, longitude=-100))
track.segments.append(segment_2)
gpx.tracks.append(track)
bounds = gpx.get_bounds()
self.assertEqual(bounds.min_latitude, -100) # type: ignore
self.assertEqual(bounds.max_latitude, 100) # type: ignore
self.assertEqual(bounds.min_longitude, -100) # type: ignore
self.assertEqual(bounds.max_longitude, 100) # type: ignore
# Test refresh bounds:
gpx.refresh_bounds()
self.assertEqual(gpx.bounds.min_latitude, -100) # type: ignore
self.assertEqual(gpx.bounds.max_latitude, 100) # type: ignore
self.assertEqual(gpx.bounds.min_longitude, -100) # type: ignore
self.assertEqual(gpx.bounds.max_longitude, 100) # type: ignore
def test_bounds_xml(self) -> None:
track = mod_gpx.GPX()
track.bounds = mod_gpx.GPXBounds(1, 2, 3, 4)
xml = track.to_xml()
print(xml)
self.assertTrue('<bounds minlat="1" maxlat="2" minlon="3" maxlon="4" />' in xml)
def test_time_bounds(self) -> None:
gpx = mod_gpx.GPX()
track = mod_gpx.GPXTrack()
segment_1 = mod_gpx.GPXTrackSegment()
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=-12, longitude=13))
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=-100, longitude=-5, time=mod_datetime.datetime(2001, 1, 12)))
segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=100, longitude=-13, time=mod_datetime.datetime(2003, 1, 12)))
track.segments.append(segment_1)
segment_2 = mod_gpx.GPXTrackSegment()
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=-12, longitude=100, time=mod_datetime.datetime(2010, 1, 12)))
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=-10, longitude=-5, time=mod_datetime.datetime(2011, 1, 12)))
segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=10, longitude=-100))
track.segments.append(segment_2)
gpx.tracks.append(track)
bounds = gpx.get_time_bounds()
self.assertEqual(bounds.start_time, mod_datetime.datetime(2001, 1, 12))
self.assertEqual(bounds.end_time, mod_datetime.datetime(2011, 1, 12))
def test_speed(self) -> None:
gpx = self.parse('track_with_speed.gpx')
gpx2 = self.reparse(gpx)
self.assertTrue(equals(gpx.waypoints, gpx2.waypoints))
self.assertTrue(equals(gpx.routes, gpx2.routes))
self.assertTrue(equals(gpx.tracks, gpx2.tracks))
self.assertTrue(equals(gpx, gpx2))
self.assertEqual(gpx.tracks[0].segments[0].points[0].speed, 1.2)
self.assertEqual(gpx.tracks[0].segments[0].points[1].speed, 2.2)
self.assertEqual(gpx.tracks[0].segments[0].points[2].speed, 3.2)
def test_speed_ignore_top_speed_percentiles(self) -> None:
gpx = self.parse('cerknicko-jezero-with-elevations-zero.gpx')
moving_data_1 = gpx.get_moving_data()
moving_data_2 = gpx.get_moving_data(speed_extreemes_percentiles=0.05)
self.assertEqual(moving_data_1.max_speed, moving_data_2.max_speed)
for i in range(0, 11, 1):
data_1 = gpx.get_moving_data(speed_extreemes_percentiles=0.1*(i-1))
data_2 = gpx.get_moving_data(speed_extreemes_percentiles=0.1*i)
print(0.1*i, data_2.max_speed)
self.assertTrue(data_1.max_speed >= data_2.max_speed)
def test_raw_max_speed(self) -> None:
for gpx_file in ("around-visnjan-with-car.gpx", "korita-zbevnica.gpx"):
gpx = self.parse(gpx_file)
raw_moving_data = gpx.get_moving_data(speed_extreemes_percentiles=0, ignore_nonstandard_distances=False)
max_speed = 0.0
for track in gpx.tracks:
for segment in track.segments:
for pt_no, pt in enumerate(segment.points):
if pt_no > 0:
speed = segment.points[pt_no].speed_between(segment.points[pt_no - 1])
#print(speed)
if speed:
max_speed = max(speed, max_speed)
print(max_speed)
print("raw=", raw_moving_data.max_speed)
print("calculated=", max_speed)
self.assertEqual(max_speed, raw_moving_data.max_speed)
def test_dilutions(self) -> None:
gpx = self.parse('track_with_dilution_errors.gpx')
gpx2 = self.reparse(gpx)
self.assertTrue(equals(gpx.waypoints, gpx2.waypoints))
self.assertTrue(equals(gpx.routes, gpx2.routes))
self.assertTrue(equals(gpx.tracks, gpx2.tracks))
self.assertTrue(equals(gpx, gpx2))
for test_gpx in (gpx, gpx2):
self.assertTrue(test_gpx.waypoints[0].horizontal_dilution == 100.1)
self.assertTrue(test_gpx.waypoints[0].vertical_dilution == 101.1)
self.assertTrue(test_gpx.waypoints[0].position_dilution == 102.1)
self.assertTrue(test_gpx.routes[0].points[0].horizontal_dilution == 200.1)
self.assertTrue(test_gpx.routes[0].points[0].vertical_dilution == 201.1)
self.assertTrue(test_gpx.routes[0].points[0].position_dilution == 202.1)
self.assertTrue(test_gpx.tracks[0].segments[0].points[0].horizontal_dilution == 300.1)
self.assertTrue(test_gpx.tracks[0].segments[0].points[0].vertical_dilution == 301.1)
self.assertTrue(test_gpx.tracks[0].segments[0].points[0].position_dilution == 302.1)
def test_subsecond_speed(self) -> None:
t1 = mod_datetime.datetime(2020, 1, 1, 0, 0, 0, 0)
pt1 = mod_gpx.GPXTrackPoint(0, 0, time=t1)
pt2 = mod_gpx.GPXTrackPoint(1, 1, time=t1 + mod_datetime.timedelta(milliseconds=500))
print(pt1.time)
print(pt2.time)
speed = pt1.speed_between(pt2)
self.assertTrue(speed > 0) # type: ignore
def test_course_between(self) -> None:
gpx = mod_gpx.GPX()
track = mod_gpx.GPXTrack()
segment = mod_gpx.GPXTrackSegment()
points = segment.points
# The points are extremely distant.
# Therefore, the computed orthodromic and loxodromic courses
# should diverge significantly.
points.append(mod_gpx.GPXTrackPoint(latitude=-73, longitude=-150))
points.append(mod_gpx.GPXTrackPoint(latitude=43.5798, longitude=35.71265))
points.append(mod_gpx.GPXTrackPoint(latitude=85, longitude=0.12345))
track.segments.append(segment)
gpx.tracks.append(track)
self.assertEqual(points[0].course_between(points[0]), 0)
# self.assertIsNone(points[2].course_between(None))
course_01 = points[0].course_between(points[1])
course_12 = points[1].course_between(points[2])
course_02 = points[0].course_between(points[2])
self.assertAlmostEqual(course_01, 312.089, 3) # type: ignore
self.assertAlmostEqual(course_12, 344.790, 3) # type: ignore
self.assertAlmostEqual(course_02, 27.5055, 3) # type: ignore
# The default computational model should be loxodromic: