././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701278708.0955887 gpxpy-1.6.2/0000755000076500000240000000000014531671764011430 5ustar00tkrstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1575986770.0 gpxpy-1.6.2/LICENSE.txt0000644000076500000240000002613613573723122013252 0ustar00tkrstaff Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1575986770.0 gpxpy-1.6.2/MANIFEST.in0000644000076500000240000000013413573723122013153 0ustar00tkrstaffinclude README.md LICENSE.txt NOTICE.txt include test.py recursive-include test_files *.gpx ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1575986770.0 gpxpy-1.6.2/NOTICE.txt0000644000076500000240000000223313573723122013141 0ustar00tkrstaffGPX.py Copyright 2010-2012 Tomo Krajina This product includes software developed by Tomo Krajina (https://tkrajina.blogspot.com/). =============================================================================== Dilution of precision stuff based on Son "Sean" Pham's fork (https://github.com/famanson) =============================================================================== Time and geo bounds methods based on Yakov Istomin fork (https://github.com/Valerich) =============================================================================== Lxml library based on Isaev Igor fork (https://github.com/itoldya) =============================================================================== Python3 compatibility from Robert Smallshire (https://github.com/rob-smallshire) =============================================================================== __repr__, pep8, better docs, timedelta fix from Bryce Jasmer (https://github.com/bj1) =============================================================================== Better docs by George Titsworth (https://github.com/titsworth) =============================================================================== ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701278708.0953963 gpxpy-1.6.2/PKG-INFO0000644000076500000240000001334014531671764012526 0ustar00tkrstaffMetadata-Version: 2.1 Name: gpxpy Version: 1.6.2 Summary: GPX file parser and GPS track manipulation library Home-page: https://github.com/tkrajina/gpxpy Author: Tomo Krajina Author-email: tkrajina@gmail.com License: Apache License, Version 2.0 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Requires-Python: >=3.6 Description-Content-Type: text/markdown License-File: LICENSE.txt License-File: NOTICE.txt [![Build Status](https://travis-ci.org/tkrajina/gpxpy.svg?branch=master)](https://travis-ci.org/tkrajina/gpxpy) [![Coverage Status](https://coveralls.io/repos/github/tkrajina/gpxpy/badge.svg?branch=master)](https://coveralls.io/github/tkrajina/gpxpy?branch=master) # gpxpy -- GPX file parser This is a simple Python library for parsing and manipulating GPX files. GPX is an XML based format for GPS tracks. You can see it in action on [my online GPS track editor and organizer](http://www.trackprofiler.com). There is also a Golang port of gpxpy: [gpxgo](http://github.com/tkrajina/gpxgo). See also [srtm.py](https://github.com/tkrajina/srtm.py) if your track lacks elevation data. ## Usage ```python import gpxpy import gpxpy.gpx # Parsing an existing file: # ------------------------- gpx_file = open('test_files/cerknicko-jezero.gpx', 'r') gpx = gpxpy.parse(gpx_file) for track in gpx.tracks: for segment in track.segments: for point in segment.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevation}') for waypoint in gpx.waypoints: print(f'waypoint {waypoint.name} -> ({waypoint.latitude},{waypoint.longitude})') for route in gpx.routes: print('Route:') for point in route.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevtion}') # There are many more utility methods and functions: # You can manipulate/add/remove tracks, segments, points, waypoints and routes and # get the GPX XML file from the resulting object: print('GPX:', gpx.to_xml()) # Creating a new file: # -------------------- gpx = gpxpy.gpx.GPX() # Create first track in our GPX: gpx_track = gpxpy.gpx.GPXTrack() gpx.tracks.append(gpx_track) # Create first segment in our GPX track: gpx_segment = gpxpy.gpx.GPXTrackSegment() gpx_track.segments.append(gpx_segment) # Create points: gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1234, 5.1234, elevation=1234)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1235, 5.1235, elevation=1235)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1236, 5.1236, elevation=1236)) # You can add routes and waypoints, too... print('Created GPX:', gpx.to_xml()) ``` ## GPX version gpx.py can parse and generate GPX 1.0 and 1.1 files. The generated file will always be a valid XML document, but it may not be (strictly speaking) a valid GPX document. For example, if you set gpx.email to "my.email AT mail.com" the generated GPX tag won't confirm to the regex pattern. And the file won't be valid. Most applications will ignore such errors, but... Be aware of this! Be aware that the gpxpy object model *is not 100% equivalent* with the underlying GPX XML file schema. That's because the library object model works with both GPX 1.0 and 1.1. For example, GPX 1.0 specified a `speed` attribute for every track point, but that was removed in GPX 1.1. If you parse GPX 1.0 and serialize back with `gpx.to_xml()` everything will work fine. But if you have a GPX 1.1 object, changes in the `speed` attribute will be lost after `gpx.to_xml()`. If you want to force using 1.0, you can `gpx.to_xml(version="1.0")`. Another possibility is to use `extensions` to save the speed in GPX 1.1. ## GPX extensions gpx.py preserves GPX extensions. They are stored as [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree) DOM objects. Extensions are part of GPX 1.1, and will be ignored when serializing a GPX object in a GPX 1.0 file. ## XML parsing If lxml is available, then it will be used for XML parsing, otherwise minidom is used. Lxml is 2-3 times faster so, if you can choose -- use it. The GPX version is automatically determined when parsing by reading the version attribute in the gpx node. If this attribute is not present then the version is assumed to be 1.0. A specific version can be forced by setting the `version` parameter in the parse function. Possible values for the 'version' parameter are `1.0`, `1.1` and `None`. ## GPX max speed Gpxpy is a GPX parser and by using it you have access to all the data from the original GPX file. The additional methods to calculate stats have some additional heuristics to remove common GPS errors. For example, to calculate `max_speed` it removes the top `5%` of speeds and points with nonstandard distance (those are usually GPS errors). "Raw" max speed can be calculated with: moving_data = gpx.get_moving_data(raw=True) ## Pull requests Branches: * `master` contains the code of the latest release * `dev` branch is where code for the next release should go. Send your pull request against `dev`, not `master`! Before sending a pull request -- check that all tests are OK. Run all the static typing checks and unit tests with: $ make mypy-and-tests Run a single test with: $ python3 -m unittest test.GPXTests.test_haversine_and_nonhaversine Gpxpy runs only with python 3.6+. The code must have type hints and must pass all the mypy checks. ## GPX tools Additional command-line tools for GPX files can be downloaded here or installed with: ``` pip install gpx-cmd-tools ``` ## License GPX.py is licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698244666.0 gpxpy-1.6.2/README.md0000644000076500000240000001226714516224072012704 0ustar00tkrstaff[![Build Status](https://travis-ci.org/tkrajina/gpxpy.svg?branch=master)](https://travis-ci.org/tkrajina/gpxpy) [![Coverage Status](https://coveralls.io/repos/github/tkrajina/gpxpy/badge.svg?branch=master)](https://coveralls.io/github/tkrajina/gpxpy?branch=master) # gpxpy -- GPX file parser This is a simple Python library for parsing and manipulating GPX files. GPX is an XML based format for GPS tracks. You can see it in action on [my online GPS track editor and organizer](http://www.trackprofiler.com). There is also a Golang port of gpxpy: [gpxgo](http://github.com/tkrajina/gpxgo). See also [srtm.py](https://github.com/tkrajina/srtm.py) if your track lacks elevation data. ## Usage ```python import gpxpy import gpxpy.gpx # Parsing an existing file: # ------------------------- gpx_file = open('test_files/cerknicko-jezero.gpx', 'r') gpx = gpxpy.parse(gpx_file) for track in gpx.tracks: for segment in track.segments: for point in segment.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevation}') for waypoint in gpx.waypoints: print(f'waypoint {waypoint.name} -> ({waypoint.latitude},{waypoint.longitude})') for route in gpx.routes: print('Route:') for point in route.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevtion}') # There are many more utility methods and functions: # You can manipulate/add/remove tracks, segments, points, waypoints and routes and # get the GPX XML file from the resulting object: print('GPX:', gpx.to_xml()) # Creating a new file: # -------------------- gpx = gpxpy.gpx.GPX() # Create first track in our GPX: gpx_track = gpxpy.gpx.GPXTrack() gpx.tracks.append(gpx_track) # Create first segment in our GPX track: gpx_segment = gpxpy.gpx.GPXTrackSegment() gpx_track.segments.append(gpx_segment) # Create points: gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1234, 5.1234, elevation=1234)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1235, 5.1235, elevation=1235)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1236, 5.1236, elevation=1236)) # You can add routes and waypoints, too... print('Created GPX:', gpx.to_xml()) ``` ## GPX version gpx.py can parse and generate GPX 1.0 and 1.1 files. The generated file will always be a valid XML document, but it may not be (strictly speaking) a valid GPX document. For example, if you set gpx.email to "my.email AT mail.com" the generated GPX tag won't confirm to the regex pattern. And the file won't be valid. Most applications will ignore such errors, but... Be aware of this! Be aware that the gpxpy object model *is not 100% equivalent* with the underlying GPX XML file schema. That's because the library object model works with both GPX 1.0 and 1.1. For example, GPX 1.0 specified a `speed` attribute for every track point, but that was removed in GPX 1.1. If you parse GPX 1.0 and serialize back with `gpx.to_xml()` everything will work fine. But if you have a GPX 1.1 object, changes in the `speed` attribute will be lost after `gpx.to_xml()`. If you want to force using 1.0, you can `gpx.to_xml(version="1.0")`. Another possibility is to use `extensions` to save the speed in GPX 1.1. ## GPX extensions gpx.py preserves GPX extensions. They are stored as [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree) DOM objects. Extensions are part of GPX 1.1, and will be ignored when serializing a GPX object in a GPX 1.0 file. ## XML parsing If lxml is available, then it will be used for XML parsing, otherwise minidom is used. Lxml is 2-3 times faster so, if you can choose -- use it. The GPX version is automatically determined when parsing by reading the version attribute in the gpx node. If this attribute is not present then the version is assumed to be 1.0. A specific version can be forced by setting the `version` parameter in the parse function. Possible values for the 'version' parameter are `1.0`, `1.1` and `None`. ## GPX max speed Gpxpy is a GPX parser and by using it you have access to all the data from the original GPX file. The additional methods to calculate stats have some additional heuristics to remove common GPS errors. For example, to calculate `max_speed` it removes the top `5%` of speeds and points with nonstandard distance (those are usually GPS errors). "Raw" max speed can be calculated with: moving_data = gpx.get_moving_data(raw=True) ## Pull requests Branches: * `master` contains the code of the latest release * `dev` branch is where code for the next release should go. Send your pull request against `dev`, not `master`! Before sending a pull request -- check that all tests are OK. Run all the static typing checks and unit tests with: $ make mypy-and-tests Run a single test with: $ python3 -m unittest test.GPXTests.test_haversine_and_nonhaversine Gpxpy runs only with python 3.6+. The code must have type hints and must pass all the mypy checks. ## GPX tools Additional command-line tools for GPX files can be downloaded here or installed with: ``` pip install gpx-cmd-tools ``` ## License GPX.py is licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698244666.0 gpxpy-1.6.2/gpxinfo0000755000076500000240000001172314516224072013021 0ustar00tkrstaff#!/usr/bin/env python """ Command line utility to extract basic statistics from gpx file(s) """ import pdb import sys as mod_sys import logging as mod_logging import math as mod_math import argparse as mod_argparse import gpxpy as mod_gpxpy import gpxpy.gpx as mod_gpx from typing import * KM_TO_MILES = 0.621371 M_TO_FEET = 3.28084 def format_time(time_s: float) -> str: if not time_s: return 'n/a' elif args.seconds: return str(int(time_s)) else: mins, secs = divmod(int(time_s), 60) hrs, mins = divmod(mins, 60) return f"{hrs:02d}:{mins:02d}:{secs:02d}" def format_long_length(length: float) -> str: if args.miles: return f'{length / 1000. * KM_TO_MILES:.3f}miles' else: return f'{length / 1000.:.3f}km' def format_short_length(length: float) -> str: if args.miles: return f'{length * M_TO_FEET:.2f}ft' else: return f'{length:.2f}m' def format_speed(speed: float) -> str: if not speed: speed = 0 if args.miles: return f'{speed * KM_TO_MILES * 3600. / 1000.:.2f}mph' else: return f'{speed:.2f}m/s = {speed * 3600. / 1000.:.2f}km/h' def print_gpx_part_info(gpx_part: Union[mod_gpx.GPX, mod_gpx.GPXTrack, mod_gpx.GPXTrackSegment], indentation: str=' ') -> None: """ gpx_part may be a track or segment. """ length_2d = gpx_part.length_2d() length_3d = gpx_part.length_3d() print(f'{indentation}Length 2D: {format_long_length(length_2d or 0)}') print(f'{indentation}Length 3D: {format_long_length(length_3d)}') moving_data = gpx_part.get_moving_data() raw_moving_data = gpx_part.get_moving_data(raw=True) if moving_data: print(f'{indentation}Moving time: {format_time(moving_data.moving_time)}') print(f'{indentation}Stopped time: {format_time(moving_data.stopped_time)}') print(f'{indentation}Max speed: {format_speed(moving_data.max_speed)} (raw: {format_speed(raw_moving_data.max_speed) if raw_moving_data else "?"})') print(f'{indentation}Avg speed: {format_speed(moving_data.moving_distance / moving_data.moving_time) if moving_data.moving_time > 0 else "?"}') uphill, downhill = gpx_part.get_uphill_downhill() print(f'{indentation}Total uphill: {format_short_length(uphill)}') print(f'{indentation}Total downhill: {format_short_length(downhill)}') start_time, end_time = gpx_part.get_time_bounds() print(f'{indentation}Started: {start_time}') print(f'{indentation}Ended: {end_time}') points_no = len(list(gpx_part.walk(only_points=True))) print(f'{indentation}Points: {points_no}') if points_no > 0: distances: List[float] = [] previous_point = None for point in gpx_part.walk(only_points=True): if previous_point: distance = point.distance_2d(previous_point) distances.append(distance) previous_point = point print(f'{indentation}Avg distance between points: {format_short_length(sum(distances) / len(list(gpx_part.walk())))}') print('') def print_gpx_info(gpx: mod_gpx.GPX, gpx_file: str) -> None: print(f'File: {gpx_file}') if gpx.name: print(f' GPX name: {gpx.name}') if gpx.description: print(f' GPX description: {gpx.description}') if gpx.author_name: print(f' Author: {gpx.author_name}') if gpx.author_email: print(f' Email: {gpx.author_email}') print_gpx_part_info(gpx) for track_no, track in enumerate(gpx.tracks): for segment_no, segment in enumerate(track.segments): print(f' Track #{track_no}, Segment #{segment_no}') print_gpx_part_info(segment, indentation=' ') def run(gpx_files: List[str]) -> None: if not gpx_files: print('No GPX files given') mod_sys.exit(1) for gpx_file in gpx_files: try: gpx = mod_gpxpy.parse(open(gpx_file)) print_gpx_info(gpx, gpx_file) except Exception as e: mod_logging.exception(e) print(f'Error processing {gpx_file}') mod_sys.exit(1) def make_parser() -> mod_argparse.ArgumentParser: parser = mod_argparse.ArgumentParser(usage='%(prog)s [-s] [-m] [-d] [file ...]', description='Command line utility to extract basic statistics from gpx file(s)') parser.add_argument('-s', '--seconds', action='store_true', help='print times as N seconds, rather than HH:MM:SS') parser.add_argument('-m', '--miles', action='store_true', help='print distances and speeds using miles and feet') parser.add_argument('-d', '--debug', action='store_true', help='show detailed logging') return parser if __name__ == '__main__': args, gpx_files = make_parser().parse_known_args() if args.debug: mod_logging.basicConfig(level=mod_logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s') run(gpx_files) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701278708.0894225 gpxpy-1.6.2/gpxpy/0000755000076500000240000000000014531671764012577 5ustar00tkrstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278666.0 gpxpy-1.6.2/gpxpy/__init__.py0000644000076500000240000000246014531671712014703 0ustar00tkrstaff# 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. from typing import IO, Union, Optional, AnyStr from . import gpx as mod_gpx __version__ = '1.6.2' def parse(xml_or_file: Union[AnyStr, IO[str]], version: Optional[str] = None) -> mod_gpx.GPX: """ Parse xml (string) or file object. This is just an wrapper for GPXParser.parse() function. parser may be 'lxml', 'minidom' or None (then it will be automatically detected, lxml if possible). xml_or_file must be the xml to parse or a file-object with the XML. version may be '1.0', '1.1' or None (then it will be read from the gpx xml node if possible, if not then version 1.0 will be used). """ from . import parser as mod_parser parser = mod_parser.GPXParser(xml_or_file) return parser.parse(version) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698244666.0 gpxpy-1.6.2/gpxpy/geo.py0000644000076500000240000003606114516224072013716 0ustar00tkrstaff# 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. import logging as mod_logging import math as mod_math from . import utils as mod_utils from typing import * log = mod_logging.getLogger(__name__) # Generic geo related function and class(es) # latitude/longitude in GPX files is always in WGS84 datum # WGS84 defined the Earth semi-major axis with 6378.137 km EARTH_RADIUS = 6378.137 * 1000 # One degree in meters: ONE_DEGREE = (2*mod_math.pi*EARTH_RADIUS) / 360 # ==> 111.319 km def haversine_distance(latitude_1: float, longitude_1: float, latitude_2: float, longitude_2: float) -> float: """ Haversine distance between two points, expressed in meters. Implemented from http://www.movable-type.co.uk/scripts/latlong.html """ d_lon = mod_math.radians(longitude_1 - longitude_2) lat1 = mod_math.radians(latitude_1) lat2 = mod_math.radians(latitude_2) d_lat = lat1 - lat2 a = mod_math.pow(mod_math.sin(d_lat/2),2) + \ mod_math.pow(mod_math.sin(d_lon/2),2) * mod_math.cos(lat1) * mod_math.cos(lat2) c = 2 * mod_math.asin(mod_math.sqrt(a)) d = EARTH_RADIUS * c return d def get_course(latitude_1: float, longitude_1: float, latitude_2: float, longitude_2: float, loxodromic: bool=True) -> float: """ The initial course from one point to another, expressed in decimal degrees clockwise from true North (not magnetic) (0.0 <= value < 360.0) Use the default loxodromic model in most cases (except when visualizing the long routes of maritime transport and aeroplanes) Implemented from http://www.movable-type.co.uk/scripts/latlong.html (sections 'Bearing' and 'Rhumb lines') """ d_lon = mod_math.radians(longitude_2 - longitude_1) lat1 = mod_math.radians(latitude_1) lat2 = mod_math.radians(latitude_2) if not loxodromic: y = mod_math.sin(d_lon) * mod_math.cos(lat2) x = mod_math.cos(lat1) * mod_math.sin(lat2) - \ mod_math.sin(lat1) * mod_math.cos(lat2) * mod_math.cos(d_lon) else: radian_circle = 2*mod_math.pi if abs(d_lon) > mod_math.pi: if d_lon > 0: d_lon = - (radian_circle - d_lon) else: d_lon = radian_circle + d_lon y = d_lon delta = mod_math.pi/4 x = mod_math.log(mod_math.tan(delta + 0.5*lat2) / mod_math.tan(delta + 0.5*lat1)) course = mod_math.degrees(mod_math.atan2(y, x)) return course % 360 def length(locations: List["Location"]=[], _3d: bool=False) -> float: if not locations: return 0 length: float = 0 for previous_location, location in zip(locations, locations[1:]): if _3d: d = location.distance_3d(previous_location) else: d = location.distance_2d(previous_location) if d: length += d return length def length_2d(locations: List["Location"]=[]) -> float: """ 2-dimensional length (meters) of locations (only latitude and longitude, no elevation). """ return length(locations, False) def length_3d(locations: List["Location"]=[]) -> float: """ 3-dimensional length (meters) of locations (it uses latitude, longitude, and elevation). """ return length(locations, True) def calculate_max_speed(speeds_and_distances: List[Tuple[float, float]], extreemes_percentile: float, ignore_nonstandard_distances: bool) -> Optional[float]: """ Compute average distance and standard deviation for distance. Extremes in distances are usually extremes in speeds, so we will ignore them, here. speeds_and_distances must be a list containing pairs of (speed, distance) for every point in a track segment. In many cases the top speeds are measurement errors. For that reason extreme speeds can be removed with the extreemes_percentile (for example, a value of 0.05 will remove top 5%). """ assert speeds_and_distances if len(speeds_and_distances) > 0: assert len(speeds_and_distances[0]) == 2 # ... assert len(speeds_and_distances[-1]) == 2 if not ignore_nonstandard_distances: return max(x[0] or 0 for x in speeds_and_distances) size = len(speeds_and_distances) if size < 2: # log.debug('Segment too small to compute speed, size=%s', size) return None distances = [x[1] for x in speeds_and_distances] average_distance = sum(distances) / size standard_distance_deviation = mod_math.sqrt(sum((distance - average_distance) ** 2 for distance in distances) / size) # Ignore items where the distance is too big: filtered_speeds_and_distances = [x for x in speeds_and_distances if abs(x[1] - average_distance) <= standard_distance_deviation * 1.5] # sort by speed: speeds = [x[0] for x in filtered_speeds_and_distances] if not speeds: return None speeds.sort() # Even here there may be some extremes => ignore the last 5%: index = int(len(speeds) * (1-extreemes_percentile)) if index >= len(speeds): index = -1 return speeds[index] def calculate_uphill_downhill(elevations: List[Optional[float]]) -> Tuple[float, float]: if not elevations: return 0, 0 elevations = list(filter(lambda e: e is not None, elevations)) size = len(elevations) def __filter(n: int) -> float: current_ele = elevations[n] if current_ele is None: return False if 0 < n < size - 1: previous_ele = elevations[n-1] next_ele = elevations[n+1] if previous_ele is not None and current_ele is not None and next_ele is not None: return previous_ele*.3 + current_ele*.4 + next_ele*.3 return current_ele smoothed_elevations = list(map(__filter, range(size))) uphill, downhill = 0., 0. for prev, cur in zip(smoothed_elevations, smoothed_elevations[1:]): if prev is not None and cur is not None: d = cur - prev if d > 0: uphill += d else: downhill -= d return uphill, downhill def distance(latitude_1: float, longitude_1: float, elevation_1: Optional[float], latitude_2: float, longitude_2: float, elevation_2: Optional[float], haversine: bool=False) -> float: """ Distance between two points. If elevation is None compute a 2d distance if haversine==True -- haversine will be used for every computations, otherwise... Haversine distance will be used for distant points where elevation makes a small difference, so it is ignored. That's because haversine is 5-6 times slower than the dummy distance algorithm (which is OK for most GPS tracks). """ # If points too distant -- compute haversine distance: if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2): return haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2) coef = mod_math.cos(mod_math.radians(latitude_1)) x = latitude_1 - latitude_2 y = (longitude_1 - longitude_2) * coef distance_2d = mod_math.sqrt(x * x + y * y) * ONE_DEGREE if elevation_1 is None or elevation_2 is None or elevation_1 == elevation_2: return distance_2d return mod_math.sqrt(distance_2d ** 2 + (elevation_1 - elevation_2) ** 2) def elevation_angle(location1: "Location", location2: "Location", radians: float=False) -> Optional[float]: """ Uphill/downhill angle between two locations. """ if location1.elevation is None or location2.elevation is None: return None b = location2.elevation - location1.elevation a = location2.distance_2d(location1) if not a: return 0 angle = mod_math.atan(b / a) if radians: return angle return mod_math.degrees(angle) def distance_from_line(point: "Location", line_point_1: "Location", line_point_2: "Location") -> Optional[float]: """ Distance of point from a line given with two points. """ assert point, point assert line_point_1, line_point_1 assert line_point_2, line_point_2 a = line_point_1.distance_2d(line_point_2) if not a: return line_point_1.distance_2d(point) b = line_point_1.distance_2d(point) c = line_point_2.distance_2d(point) if a is not None and b is not None and c is not None: s = (a + b + c) / 2 return 2 * mod_math.sqrt(abs(s * (s - a) * (s - b) * (s - c))) / a return None def get_line_equation_coefficients(location1: "Location", location2: "Location") -> Iterable[float]: """ Get line equation coefficients for: latitude * a + longitude * b + c = 0 This is a normal cartesian line (not spherical!) """ if location1.longitude == location2.longitude: # Vertical line: return 0, 1, -location1.longitude else: a = (location1.latitude - location2.latitude) / (location1.longitude - location2.longitude) b = location1.latitude - location1.longitude * a return 1, -a, -b def simplify_polyline(points: List["Location"], max_distance: Optional[float]) -> List["Location"]: """Does Ramer-Douglas-Peucker algorithm for simplification of polyline """ _max_distance = max_distance if max_distance is not None else 10 if len(points) < 3: return points begin, end = points[0], points[-1] # Use a "normal" line just to detect the most distant point (not its real distance) # this is because this is faster to compute than calling distance_from_line() for # every point. # # This is an approximation and may have some errors near the poles and if # the points are too distant, but it should be good enough for most use # cases... a, b, c = get_line_equation_coefficients(begin, end) # Initialize to safe values tmp_max_distance: float = 0 tmp_max_distance_position = 1 # Check distance of all points between begin and end, exclusive for point_no, point in enumerate(points[1:-1], 1): d = abs(a * point.latitude + b * point.longitude + c) if d > tmp_max_distance: tmp_max_distance = d tmp_max_distance_position = point_no # Now that we have the most distance point, compute its real distance: real_max_distance = distance_from_line(points[tmp_max_distance_position], begin, end) # If furthest point is less than max_distance, remove all points between begin and end if real_max_distance is not None and real_max_distance < _max_distance: return [begin, end] # If furthest point is more than max_distance, use it as anchor and run # function again using (begin to anchor) and (anchor to end), remove extra anchor return (simplify_polyline(points[:tmp_max_distance_position + 1], _max_distance) + simplify_polyline(points[tmp_max_distance_position:], _max_distance)[1:]) class Location: """ Generic geographical location """ def __init__(self, latitude: float, longitude: float, elevation: Optional[float]=None) -> None: self.latitude = latitude self.longitude = longitude self.elevation = elevation def has_elevation(self) -> bool: return self.elevation is not None def remove_elevation(self) -> None: self.elevation = None def distance_2d(self, location: "Location") -> Optional[float]: if not location: return None return distance(self.latitude, self.longitude, None, location.latitude, location.longitude, None) def distance_3d(self, location: "Location") -> Optional[float]: if not location: return None return distance(self.latitude, self.longitude, self.elevation, location.latitude, location.longitude, location.elevation) def elevation_angle(self, location: "Location", radians: bool=False) -> Optional[float]: return elevation_angle(self, location, radians) def move(self, location_delta: "LocationDelta") -> None: self.latitude, self.longitude = location_delta.move(self) def __add__(self, location_delta: "LocationDelta") -> "Location": latitude, longitude = location_delta.move(self) return Location(latitude, longitude) def __str__(self) -> str: return f'[loc:{self.latitude},{self.longitude}@{self.elevation}]' def __repr__(self) -> str: if self.elevation is None: return f'Location({self.latitude}, {self.longitude})' else: return f'Location({self.latitude}, {self.longitude}, {self.elevation})' class LocationDelta: """ Intended to use similar to timestamp.timedelta, but for Locations. """ NORTH = 0 EAST = 90 SOUTH = 180 WEST = 270 def __init__(self, distance: Optional[float]=None, angle: Optional[float]=None, latitude_diff: Optional[float]=None, longitude_diff: Optional[float]=None) -> None: """ Version 1: Distance (in meters). angle_from_north *clockwise*. ...must be given Version 2: latitude_diff and longitude_diff ...must be given """ if (distance is not None) and (angle is not None): if (latitude_diff is not None) or (longitude_diff is not None): raise Exception('No lat/lon diff if using distance and angle!') self.distance = distance self.angle_from_north = angle self.move_function = self.move_by_angle_and_distance elif (latitude_diff is not None) and (longitude_diff is not None): if (distance is not None) or (angle is not None): raise Exception('No distance/angle if using lat/lon diff!') self.latitude_diff = latitude_diff self.longitude_diff = longitude_diff self.move_function = self.move_by_lat_lon_diff def move(self, location: Location) -> Tuple[float, float]: """ Move location by this timedelta. """ return self.move_function(location) def move_by_angle_and_distance(self, location: Location) -> Tuple[float, float]: coef = mod_math.cos(mod_math.radians(location.latitude)) vertical_distance_diff = mod_math.sin(mod_math.radians(90 - self.angle_from_north)) / ONE_DEGREE horizontal_distance_diff = mod_math.cos(mod_math.radians(90 - self.angle_from_north)) / ONE_DEGREE lat_diff = self.distance * vertical_distance_diff lon_diff = self.distance * horizontal_distance_diff / coef return location.latitude + lat_diff, location.longitude + lon_diff def move_by_lat_lon_diff(self, location: "Location") -> Tuple[float, float]: return location.latitude + self.latitude_diff, location.longitude + self.longitude_diff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278641.0 gpxpy-1.6.2/gpxpy/gpx.py0000644000076500000240000031463414531671661013756 0ustar00tkrstaff# 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 from typing import * log = mod_logging.getLogger(__name__) IGNORE_TOP_SPEED_PERCENTILES = 0.05 # 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', '3',)), 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', type=mod_gpxfield.INT_TYPE), ] 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', '3',)), 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', type=mod_gpxfield.INT_TYPE), 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: class TimeBounds(NamedTuple): start_time: Optional[mod_datetime.datetime] end_time: Optional[mod_datetime.datetime] class MovingData(NamedTuple): moving_time: float stopped_time: float moving_distance: float stopped_distance: float max_speed: float class UphillDownhill(NamedTuple): uphill: float downhill: float class MinimumMaximum(NamedTuple): minimum: Optional[float] maximum: Optional[float] class NearestLocationData(NamedTuple): # this is also what walk() returns/iterates over location: "GPXTrackPoint" track_no: int segment_no: int point_no: int class PointData(NamedTuple): point: "GPXTrackPoint" distance_from_start: float track_no: int segment_no: int point_no: int 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: Optional[float] = None, max_latitude: Optional[float] = None, min_longitude: Optional[float] = None, max_longitude: Optional[float] = None) -> None: self.min_latitude = min_latitude self.max_latitude = max_latitude self.min_longitude = min_longitude self.max_longitude = max_longitude def __iter__(self) -> Iterator[Any]: return (self.min_latitude, self.max_latitude, self.min_longitude, self.max_longitude,).__iter__() def _min(self, a: Optional[float], b: Optional[float]) -> Optional[float]: if a is not None and b is not None: return min(a, b) return None def _max(self, a: Optional[float], b: Optional[float]) -> Optional[float]: if a is not None and b is not None: return max(a, b) return None def max_bounds(self, bounds: "GPXBounds") -> "GPXBounds": return GPXBounds(self._min(self.min_latitude, bounds.min_latitude), self._max(self.max_latitude, bounds.max_latitude), self._min(self.min_longitude, bounds.min_longitude), self._max(self.max_longitude, bounds.max_longitude)) 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: str, original_exception: BaseException) -> None: 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: Optional[float]=None, longitude: Optional[float]=None, elevation: Optional[float]=None, time: Optional[mod_datetime.datetime]=None, name: Optional[str]=None, description: Optional[str]=None, symbol: Optional[str]=None, type: Optional[str]=None, comment: Optional[str]=None, horizontal_dilution: Optional[float]=None, vertical_dilution: Optional[float]=None, position_dilution: Optional[float]=None) -> None: mod_geo.Location.__init__(self, latitude or 0, longitude or 0, elevation) self.time = time self.magnetic_variation: Optional[float] = None self.geoid_height: Optional[float] = None self.name = name self.comment = comment self.description = description self.source: Optional[str] = None self.link = None self.link_text = None self.link_type: Optional[str] = None self.symbol = symbol self.type = type self.type_of_gpx_fix: Optional[str] = None self.satellites: Optional[int] = None self.horizontal_dilution = horizontal_dilution self.vertical_dilution = vertical_dilution self.position_dilution = position_dilution self.age_of_dgps_data: Optional[float] = None self.dgps_id: Optional[int] = None self.extensions: List[Any] = [] # TODO def __str__(self) -> str: return f'[wpt{{{self.name}}}:{self.latitude},{self.longitude}@{self.elevation}]' def __repr__(self) -> str: parts = [f'{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: parts.append(f'{attribute}={value!r}') return f'GPXWaypoint({", ".join(parts)})' def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ 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) -> None: """ Will remove time metadata. """ self.time = None def get_max_dilution_of_precision(self) -> Optional[float]: """ Only care about the max dop for filtering, no need to go into too much detail """ if self.horizontal_dilution is None: return None if self.vertical_dilution is None: return None if self.position_dilution is None: return None 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: Optional[float]=None, longitude: Optional[float]=None, elevation: Optional[float]=None, time: Optional[mod_datetime.datetime]=None, name: Optional[str]=None, description: Optional[str]=None, symbol: Optional[str]=None, type: Optional[str]=None, comment: Optional[str]=None, horizontal_dilution: Optional[float]=None, vertical_dilution: Optional[float]=None, position_dilution: Optional[float]=None) -> None: mod_geo.Location.__init__(self, latitude or 0, longitude or 0, elevation) self.time = time self.magnetic_variation: Optional[float] = None self.geoid_height: Optional[float] = None self.name = name self.comment = comment self.description = description self.source: Optional[str] = None self.link: Optional[str] = None self.link_text: Optional[str] = None self.symbol = symbol self.type: Optional[str] = type self.type_of_gpx_fix: Optional[str] = None self.satellites: Optional[int] = None self.horizontal_dilution = horizontal_dilution self.vertical_dilution = vertical_dilution self.position_dilution = position_dilution self.age_of_dgps_data: Optional[float] = None self.dgps_id: Optional[int] = None self.link_type: Optional[str] = None self.extensions: List[Any] = [] # TODO def __str__(self) -> str: return f'[rtept{{{self.name}}}:{self.latitude},{self.longitude}@{self.elevation}]' def __repr__(self) -> str: parts = [f'{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: parts.append(f'{attribute}={value!r}') return f'GPXRoutePoint({", ".join(parts)})' def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ 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) -> None: """ 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: Optional[str]=None, description: Optional[str]=None, number: Optional[int]=None) -> None: self.name = name self.comment: Optional[str] = None self.description = description self.source: Optional[str] = None self.link: Optional[str] = None self.link_text: Optional[str] = None self.number = number self.points: List[GPXRoutePoint] = [] self.link_type: Optional[str] = None self.type: Optional[str] = None self.extensions: List[Any] = [] def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ 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) -> None: """ Removes time meta data from route. """ for point in self.points: point.remove_time() def remove_elevation(self) -> None: """ Removes elevation data from route """ for point in self.points: point.remove_elevation() def length(self) -> float: """ Computes length (2-dimensional) of route. Returns: ----------- length: float Length returned in meters """ return mod_geo.length_2d(cast(List[mod_geo.Location], self.points)) def get_center(self) -> Optional[mod_geo.Location]: """ 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(0, 0) return mod_geo.Location(latitude=sum_lat / n, longitude=sum_lon / n) def walk(self, only_points: bool=False) -> Iterator[Any]: """ 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) -> int: """ 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: mod_geo.LocationDelta) -> None: """ 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) -> str: parts = [] for attribute in 'name', 'description', 'number': value = getattr(self, attribute) if value is not None: parts.append(f'{attribute}={value!r}') parts.append(f'points=[{"..." if self.points else ""}]') return f'GPXRoute({", ".join(parts)})' 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: Optional[float]=None, longitude: Optional[float]=None, elevation: Optional[float]=None, time: Optional[mod_datetime.datetime]=None, symbol: Optional[str]=None, comment: Optional[str]=None, horizontal_dilution: Optional[float]=None, vertical_dilution: Optional[float]=None, position_dilution: Optional[float]=None, speed: Optional[float]=None, name: Optional[str]=None) -> None: mod_geo.Location.__init__(self, latitude or 0, longitude or 0, elevation) self.time = time self.course = None self.speed = speed self.magnetic_variation: Optional[float] = None self.geoid_height: Optional[float] = None self.name = name self.comment = comment self.description: Optional[str] = None self.source: Optional[str] = None self.link: Optional[str] = None self.link_text: Optional[str] = None self.link_type: Optional[str] = None self.symbol: Optional[str] = symbol self.type: Optional[str] = None self.type_of_gpx_fix: Optional[str] = None self.satellites: Optional[float] = None self.horizontal_dilution = horizontal_dilution self.vertical_dilution = vertical_dilution self.position_dilution = position_dilution self.age_of_dgps_data: Optional[float] = None self.dgps_id: Optional[int] = None self.extensions: List[Any] = [] def __repr__(self) -> str: parts = [f'{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: parts.append(f'{attribute}={value!r}') return f'GPXTrackPoint({", ".join(parts)})' def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ 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) -> None: """ Will remove time metadata. """ self.time = None def time_difference(self, track_point: "GPXTrackPoint") -> Optional[float]: """ 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: "GPXTrackPoint") -> Optional[float]: """ 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 / seconds def course_between(self, track_point: "GPXTrackPoint", loxodromic: bool=True) -> Optional[float]: """ Compute the instantaneous course from one point to another. Both loxodromic (Rhumb line) and orthodromic (Great circle) navigation models are available. The default navigation model is loxodromic. There is no difference between these models in course computation when points are relatively close to each other (less than ≈150 km) In most cases the default model is OK. However, the orthodromic navigation model can be important for the long-distance (> ≈1000 km) logs acquired from maritime transport or aeroplanes Generally, the choice between these two models depends on a vehicle type, distance and navigation equipment used. More information on these two navigation models: https://www.movable-type.co.uk/scripts/latlong.html NOTE: This is a computed course, not the GPXTrackPoint course that comes in the GPX file. Parameters ---------- track_point : GPXTrackPoint loxodromic : True Set to False to use the orthodromic navigation model Returns ---------- course : float Course returned in decimal degrees, true (not magnetic) (0.0 <= value < 360.0) """ if not track_point: return None course = mod_geo.get_course(self.latitude, self.longitude, track_point.latitude, track_point.longitude, loxodromic) return course def __str__(self) -> str: return f'[trkpt:{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: Optional[List[GPXTrackPoint]]=None) -> None: self.points: List[GPXTrackPoint] = points if points else [] self.extensions: List[Any] = [] def simplify(self, max_distance: Optional[float]=None) -> None: """ Simplify using the Ramer-Douglas-Peucker algorithm: http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """ self.points = mod_geo.simplify_polyline(self.points, max_distance) # type: ignore def reduce_points(self, min_distance: float) -> None: """ 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: List[GPXTrackPoint] = [] for point in self.points: if reduced_points: distance = reduced_points[-1].distance_3d(point) if min_distance is not None and distance is not None and distance >= min_distance: reduced_points.append(point) else: # Leave first point: reduced_points.append(point) self.points = reduced_points def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ 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) -> None: """ Removes time data for all points in the segment. """ for track_point in self.points: track_point.remove_time() def remove_elevation(self) -> None: """ Removes elevation data for all points in the segment. """ for track_point in self.points: track_point.remove_elevation() def length_2d(self) -> Optional[float]: """ 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) # type: ignore def length_3d(self) -> float: """ Computes 3-dimensional length of segment (latitude, longitude, and elevation). Returns ---------- length : float Length returned in meters """ return mod_geo.length_3d(self.points) # type: ignore def move(self, location_delta: mod_geo.LocationDelta) -> None: """ 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: bool=False) -> Iterator[Any]: # Union[GPXTrackPoint, Tuple[GPXTrackPoint, int]]]: """ 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 self.points else []): if only_points: yield point else: yield point, point_no def get_points_no(self) -> int: """ 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: int) -> Tuple["GPXTrackSegment", "GPXTrackSegment"]: """ Splits the segment into two parts. 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: "GPXTrackSegment") -> None: """ Joins with another segment """ self.points += track_segment.points def remove_point(self, point_no: int) -> None: """ Removes a point specified 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: Optional[float]=None, raw: bool=False, speed_extreemes_percentiles: float=IGNORE_TOP_SPEED_PERCENTILES, ignore_nonstandard_distances: bool = True) -> Optional[MovingData]: """ 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 if raw: speed_extreemes_percentiles=0 ignore_nonstandard_distances=False moving_time = 0. stopped_time = 0. moving_distance = 0. stopped_distance = 0. speeds_and_distances = [] for previous, point in zip(self.points, self.points[1:]): # 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: float = 0 if seconds > 0 and distance is not None: # TODO: compute threshold in m/s instead this to kmh every time: speed_kmh = (distance / 1000) / (seconds / 60 ** 2) if distance: if speed_kmh <= stopped_speed_threshold: stopped_time += seconds stopped_distance += distance else: moving_time += seconds moving_distance += distance if moving_time: speeds_and_distances.append((distance / seconds, distance, )) max_speed = None if speeds_and_distances: max_speed = mod_geo.calculate_max_speed(speeds_and_distances, speed_extreemes_percentiles, ignore_nonstandard_distances) return MovingData(moving_time, stopped_time, moving_distance, stopped_distance, max_speed or 0.0) def get_time_bounds(self) -> TimeBounds: """ 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) -> Optional[GPXBounds]: """ 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 if min_lat and max_lat and min_lon and max_lon: return GPXBounds(min_lat, max_lat, min_lon, max_lon) return None def get_speed(self, point_no: int) -> Optional[float]: """ 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) if previous_point else None speed_2 = point.speed_between(next_point) if next_point else None 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: float) -> None: """ 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: Callable[[GPXTrackPoint], Any], add_missing_function: Callable[[List[GPXTrackPoint], GPXTrackPoint, GPXTrackPoint, List[float]], None]) -> None: """ Calculate missing data. Parameters ---------- get_data_function : object Returns the data from point add_missing_function : void Function with the following arguments: array with points with missing data, the point before them (with data), the point after them (with data), and distance ratios between points in the interval (the sum of distances ratios will be 1) """ if not get_data_function: raise GPXException(f'Invalid get_data_function: {get_data_function}') if not add_missing_function: raise GPXException(f'Invalid add_missing_function: {add_missing_function}') # Points (*without* data) between two points (*with* data): interval: List[GPXTrackPoint] = [] # Point (*with* data) before and after the interval: start_point = None previous_point = None for track_point in self.points: data = get_data_function(track_point) if data is None and previous_point: if not start_point: start_point = previous_point interval.append(track_point) else: if interval and start_point: distances_ratios = self._get_interval_distances_ratios(interval, start_point, track_point) add_missing_function(interval, start_point, track_point, distances_ratios) start_point = None interval = [] previous_point = track_point def _get_interval_distances_ratios(self, interval: List[GPXTrackPoint], start: GPXTrackPoint, end: GPXTrackPoint) -> List[float]: assert start, start assert end, end assert interval, interval assert len(interval) > 0, interval distances = [] distance_from_start: float = 0 previous_point = start for point in interval: dist = point.distance_3d(previous_point) if dist is not None: distance_from_start += dist distances.append(distance_from_start) previous_point = point dist = interval[-1].distance_3d(end) from_start_to_end = None if dist: from_start_to_end = distances[-1] + dist assert len(interval) == len(distances) return [(distance / from_start_to_end) if from_start_to_end else 0 for distance in distances] def get_duration(self) -> Optional[float]: """ Calculates duration or track segment Returns ------- duration: float Duration in seconds """ if not self.points or len(self.points) < 2: return 0.0 # Search for start: first = self.points[0] if not first.time: first = self.points[1] last = self.points[-1] if not last.time: last = self.points[-2] if not last.time or not first.time: log.debug('Can\'t find time') return None if last.time < first.time: log.debug('Not enough time data') return None return mod_utils.total_seconds(last.time - first.time) def get_uphill_downhill(self) -> UphillDownhill: """ Calculates the uphill and downhill elevation climbs for the track segment. If elevation for some points is not found those are simply ignored. Returns ------- uphill_downhill: UphillDownhill named tuple uphill: float Uphill elevation climbs in meters downhill: float Downhill elevation descent in meters """ if not self.points: return UphillDownhill(0, 0) elevations = [point.elevation for point in self.points] uphill, downhill = mod_geo.calculate_uphill_downhill(elevations) return UphillDownhill(uphill, downhill) def get_elevation_extremes(self) -> MinimumMaximum: """ Calculate elevation extremes of track segment Returns ------- min_max_elevation: MinimumMaximum named tuple minimum: float Minimum elevation in meters maximum: float Maximum elevation in meters """ if not self.points: return MinimumMaximum(None, None) elevations = [x.elevation for x in self.points if x.elevation is not None] if not elevations: return MinimumMaximum(None, None) return MinimumMaximum(min(elevations), max(elevations)) def get_location_at(self, time: mod_datetime.datetime) -> Optional[GPXTrackPoint]: """ Gets approx. location at given time. Note that, at the moment this method returns an instance of GPXTrackPoint in the future -- this may be a mod_geo.Location instance with approximated latitude, longitude and elevation! """ if not self.points: return None if not time: return None first_time = self.points[0].time last_time = self.points[-1].time if not first_time and not last_time: log.debug('No times for track segment') return None if first_time and time and last_time and not first_time <= time <= last_time: log.debug(f'Not in track (search for:{time}, start:{first_time}, end:{last_time})') return None for point in self.points: if point.time and time <= point.time: # TODO: If between two points -- approx position! # return mod_geo.Location(point.latitude, point.longitude) return point return None def get_nearest_location(self, location: mod_geo.Location) -> Optional[NearestLocationData]: """ Return the (location, track_point_no) on this track segment """ return min((NearestLocationData(pt, -1, -1, pt_no) for (pt, pt_no) in self.walk()) # type: ignore ,key=lambda x: x.location.distance_2d(location) if x is not None else mod_math.inf ,default=None) def smooth(self, vertical: bool=True, horizontal: bool=False, remove_extremes: bool=False) -> None: """ "Smooths" the elevation graph. Can be called multiple times. """ if len(self.points) <= 3: return elevations: List[float] = [] latitudes: List[float] = [] longitudes: List[float] = [] for point in self.points: elevations.append(point.elevation or 0) latitudes.append(point.latitude or 0) longitudes.append(point.longitude or 0) avg_distance: float = 0 avg_elevation_delta: float = 1 if remove_extremes: # compute the average distance between two points: distances: List[float] = [] elevations_delta = [] for prev, cur in zip(self.points, self.points[1:]): dist = prev.distance_2d(cur) if dist: distances.append(dist) if cur.elevation is not None and prev.elevation is not None: elevations_delta.append(abs(cur.elevation - prev.elevation)) if distances: avg_distance = 1.0 * sum(distances) / len(distances) if elevations_delta: avg_elevation_delta = 1.0 * sum(elevations_delta) / len(elevations_delta) # If The point moved more than this number * the average distance between two # points -- then is a candidate for deletion: # TODO: Make this a method parameter remove_2d_extremes_threshold = 1.75 * avg_distance remove_elevation_extremes_threshold = avg_elevation_delta * 5 # TODO: Param new_track_points = [self.points[0]] for i in range(len(self.points))[1:-1]: new_point = None point_removed = False if vertical and elevations[i - 1] and elevations[i] and elevations[i + 1]: old_elevation = self.points[i].elevation new_elevation = SMOOTHING_RATIO[0] * elevations[i - 1] + \ SMOOTHING_RATIO[1] * elevations[i] + \ SMOOTHING_RATIO[2] * elevations[i + 1] if not remove_extremes: self.points[i].elevation = new_elevation if remove_extremes: # The point must be enough distant to *both* neighbours: d1 = abs((old_elevation or 0) - elevations[i - 1]) d2 = abs((old_elevation or 0) - elevations[i + 1]) #print d1, d2, remove_2d_extremes_threshold # TODO: Remove extremes threshold is meant only for 2D, elevation must be # computed in different way! if min(d1, d2) < remove_elevation_extremes_threshold and abs((old_elevation or 0) - (new_elevation or 0)) < remove_2d_extremes_threshold: new_point = self.points[i] else: #print 'removed elevation' point_removed = True else: new_point = self.points[i] else: new_point = self.points[i] if horizontal: old_latitude = self.points[i].latitude new_latitude = SMOOTHING_RATIO[0] * latitudes[i - 1] + \ SMOOTHING_RATIO[1] * latitudes[i] + \ SMOOTHING_RATIO[2] * latitudes[i + 1] old_longitude = self.points[i].longitude new_longitude = SMOOTHING_RATIO[0] * longitudes[i - 1] + \ SMOOTHING_RATIO[1] * longitudes[i] + \ SMOOTHING_RATIO[2] * longitudes[i + 1] if not remove_extremes: self.points[i].latitude = new_latitude self.points[i].longitude = new_longitude # TODO: This is not ideal.. Because if there are points A, B and C on the same # line but B is very close to C... This would remove B (and possibly) A even though # it is not an extreme. This is the reason for this algorithm: d1 = mod_geo.distance(latitudes[i - 1], longitudes[i - 1], None, latitudes[i], longitudes[i], None) d2 = mod_geo.distance(latitudes[i + 1], longitudes[i + 1], None, latitudes[i], longitudes[i], None) dist = mod_geo.distance(latitudes[i - 1], longitudes[i - 1], None, latitudes[i + 1], longitudes[i + 1], None) #print d1, d2, d, remove_extremes if d1 + d2 > dist * 1.5 and remove_extremes: dist = mod_geo.distance(old_latitude, old_longitude, None, new_latitude, new_longitude, None) #print "d, threshold = ", d, remove_2d_extremes_threshold if dist < remove_2d_extremes_threshold: new_point = self.points[i] else: #print 'removed 2d' point_removed = True else: new_point = self.points[i] if new_point and not point_removed: new_track_points.append(new_point) new_track_points.append(self.points[- 1]) #print 'len=', len(new_track_points) self.points = new_track_points def has_times(self) -> bool: """ Returns if points in this segment contains timestamps. The first point, the last point, and 75% of the points must have times for this method to return true. """ if not self.points: return True # ... or otherwise one empty track segment would change the entire # track's "has_times" status! found = 0 for track_point in self.points: if track_point.time: found += 1 return len(self.points) > 2 and found / len(self.points) > .75 def has_elevations(self) -> bool: """ Returns if points in this segment contains elevation. The first point, the last point, and at least 75% of the points must have elevation for this method to return true. """ if not self.points: return True # ... or otherwise one empty track segment would change the entire # track's "has_times" status! found = 0 for track_point in self.points: if track_point.elevation: found += 1 return len(self.points) > 2 and found / len(self.points) > .75 def __repr__(self) -> str: return f'GPXTrackSegment(points=[{"..." if self.points else ""}])' def clone(self) -> "GPXTrackSegment": return mod_copy.deepcopy(self) class GPXTrack: 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('segments', tag='trkseg', classs=GPXTrackSegment, is_list=True), ] gpx_11_fields = [ # See GPX for text field description 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('segments', tag='trkseg', classs=GPXTrackSegment, is_list=True), ] __slots__ = ('name', 'comment', 'description', 'source', 'link', 'link_text', 'number', 'segments', 'link_type', 'type', 'extensions') def __init__(self, name: Optional[str]=None, description: Optional[str]=None, number: Optional[int]=None) -> None: self.name = name self.comment: Optional[str] = None self.description = description self.source: Optional[str] = None self.link: Optional[str] = None self.link_text: Optional[str] = None self.number = number self.segments: List[GPXTrackSegment] = [] self.link_type = None self.type = None self.extensions: List[Any] = [] # TODO def simplify(self, max_distance: Optional[float]=None) -> None: """ Simplify using the Ramer-Douglas-Peucker algorithm: http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """ for segment in self.segments: segment.simplify(max_distance=max_distance) def reduce_points(self, min_distance: float) -> None: """ Reduces the number of points in the track. Segment points will be updated in place. Parameters ---------- min_distance : float The minimum separation in meters between points """ for segment in self.segments: segment.reduce_points(min_distance) def adjust_time(self, delta: mod_datetime.timedelta) -> None: """ Adjusts the time of all segments in the track 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 segment in self.segments: segment.adjust_time(delta) def remove_time(self) -> None: """ Removes time data for all points in all segments of track. """ for segment in self.segments: segment.remove_time() def remove_elevation(self) -> None: """ Removes elevation data for all points in all segments of track. """ for segment in self.segments: segment.remove_elevation() def remove_empty(self) -> None: """ Removes empty segments in track """ result = [] for segment in self.segments: if len(segment.points) > 0: result.append(segment) self.segments = result def length_2d(self) -> float: """ Computes 2-dimensional length (meters) of track (only latitude and longitude, no elevation). This is the sum of the 2D length of all segments. Returns ---------- length : float Length returned in meters """ length: float = 0 for track_segment in self.segments: d = track_segment.length_2d() if d: length += d return length def get_time_bounds(self) -> TimeBounds: """ Gets the time bound (start and end) of the track. 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 track_segment in self.segments: point_start_time, point_end_time = track_segment.get_time_bounds() if not start_time and point_start_time: start_time = point_start_time if point_end_time: end_time = point_end_time return TimeBounds(start_time, end_time) def get_bounds(self) -> Optional[GPXBounds]: """ Gets the latitude and longitude bounds of the track. Returns ---------- bounds : Bounds named tuple min_latitude : float Minimum latitude of track in decimal degrees [-90, 90] max_latitude : float Maximum latitude of track in decimal degrees [-90, 90] min_longitude : float Minimum longitude of track in decimal degrees [-180, 180] max_longitude : float Maximum longitude of track in decimal degrees [-180, 180] """ bounds: Optional[GPXBounds] = None for track_segment in self.segments: segment_bounds = track_segment.get_bounds() if bounds is None: bounds = segment_bounds elif segment_bounds: bounds = bounds.max_bounds(segment_bounds) return bounds def walk(self, only_points: bool=False) -> Iterator[Any]: #Union[GPXTrackPoint, Tuple[GPXTrackPoint, int, int]]]: """ Generator used to iterates through track Parameters ---------- only_point s: boolean Only yield points while walking Yields ---------- point : GPXTrackPoint Point in the track segment_no : integer Index of segment containing point. This is suppressed if only_points is True. point_no : integer Index of point. This is suppressed if only_points is True. """ for segment_no, segment in enumerate(self.segments if self.segments else []): for point_no, point in enumerate(segment.points if segment.points else []): if only_points: yield point else: yield point, segment_no, point_no def get_points_no(self) -> int: """ Get the number of points in all segments in the track. Returns ---------- num_points : integer Number of points in track """ result = 0 for track_segment in self.segments: result += track_segment.get_points_no() return result def length_3d(self) -> float: """ Computes 3-dimensional length of track (latitude, longitude, and elevation). This is the sum of the 3D length of all segments. Returns ---------- length : float Length returned in meters """ length: float = 0 for track_segment in self.segments: d = track_segment.length_3d() if d: length += d return length def split(self, track_segment_no: int, track_point_no: int) -> None: """ Splits one of the segments in the track in 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 ---------- track_segment_no : integer The index of the segment to split track_point_no : integer The index of the track point in the segment to split """ new_segments = [] for i in range(len(self.segments)): segment = self.segments[i] if i == track_segment_no: segment_1, segment_2 = segment.split(track_point_no) if segment_1: new_segments.append(segment_1) if segment_2: new_segments.append(segment_2) else: new_segments.append(segment) self.segments = new_segments def join(self, track_segment_no: int, track_segment_no_2: Optional[int]=None) -> None: """ Joins two segments of this track. The segments will be split in place. Parameters ---------- track_segment_no : integer The index of the first segment to join track_segment_no_2 : integer The index of second segment to join. If track_segment_no_2 is not provided,the join will be with the next segment after track_segment_no. """ if not track_segment_no_2: track_segment_no_2 = track_segment_no + 1 if track_segment_no_2 >= len(self.segments): return new_segments = [] for i in range(len(self.segments)): segment = self.segments[i] if i == track_segment_no: second_segment = self.segments[track_segment_no_2] segment.join(second_segment) new_segments.append(segment) elif i == track_segment_no_2: # Nothing, it is already joined pass else: new_segments.append(segment) self.segments = new_segments def get_moving_data(self, stopped_speed_threshold: Optional[float]=None, raw: bool=False, speed_extreemes_percentiles: float=IGNORE_TOP_SPEED_PERCENTILES, ignore_nonstandard_distances: bool = True) -> MovingData: """ 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 track. 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 track in which movement was occurring stopped_time : float time (seconds) of track 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 track. """ moving_time = 0. stopped_time = 0. moving_distance = 0. stopped_distance = 0. max_speed = 0. for segment in self.segments: moving_data = segment.get_moving_data(stopped_speed_threshold, raw, speed_extreemes_percentiles, ignore_nonstandard_distances) if moving_data: moving_time += moving_data.moving_time stopped_time += moving_data.stopped_time moving_distance += moving_data.moving_distance stopped_distance += moving_data.stopped_distance if moving_data.max_speed is not None and moving_data.max_speed > max_speed: max_speed = moving_data.max_speed return MovingData(moving_time, stopped_time, moving_distance, stopped_distance, max_speed) def add_elevation(self, delta: float) -> None: """ Adjusts elevation data for track. Parameters ---------- delta : float Elevation delta in meters to apply to track """ for track_segment in self.segments: track_segment.add_elevation(delta) def add_missing_data(self, get_data_function: Callable[[GPXTrackPoint], Any], add_missing_function: Callable[[List[GPXTrackPoint], GPXTrackPoint, GPXTrackPoint, List[float]], None]) -> None: for track_segment in self.segments: track_segment.add_missing_data(get_data_function, add_missing_function) def move(self, location_delta: mod_geo.LocationDelta) -> None: """ Moves each point in the track. Parameters ---------- location_delta: LocationDelta object Delta (distance/angle or lat/lon offset to apply each point in each segment of the track """ for track_segment in self.segments: track_segment.move(location_delta) def get_duration(self) -> Optional[float]: """ Calculates duration or track Returns ------- duration: float Duration in seconds or None if any time data is missing """ if not self.segments: return 0.0 result = 0. for track_segment in self.segments: duration = track_segment.get_duration() if duration or duration == 0: result += duration elif duration is None: return None return result def get_uphill_downhill(self) -> UphillDownhill: """ Calculates the uphill and downhill elevation climbs for the track. If elevation for some points is not found those are simply ignored. Returns ------- uphill_downhill: UphillDownhill named tuple uphill: float Uphill elevation climbs in meters downhill: float Downhill elevation descent in meters """ if not self.segments: return UphillDownhill(0, 0) uphill: float = 0 downhill: float = 0 for track_segment in self.segments: current_uphill, current_downhill = track_segment.get_uphill_downhill() uphill += current_uphill or .0 downhill += current_downhill or .0 return UphillDownhill(uphill, downhill) def get_location_at(self, time: mod_datetime.datetime) -> List[GPXTrackPoint]: """ Gets approx. location at given time. Note that, at the moment this method returns an instance of GPXTrackPoint in the future -- this may be a mod_geo.Location instance with approximated latitude, longitude and elevation! """ result = [] for track_segment in self.segments: location = track_segment.get_location_at(time) if location: result.append(location) return result def get_elevation_extremes(self) -> MinimumMaximum: """ Calculate elevation extremes of track Returns ------- min_max_elevation: MinimumMaximum named tuple minimum: float Minimum elevation in meters maximum: float Maximum elevation in meters """ if not self.segments: return MinimumMaximum(None, None) elevations = [] for track_segment in self.segments: (_min, _max) = track_segment.get_elevation_extremes() if _min is not None: elevations.append(_min) if _max is not None: elevations.append(_max) if len(elevations) == 0: return MinimumMaximum(None, None) return MinimumMaximum(min(elevations), max(elevations)) def get_center(self) -> Optional[mod_geo.Location]: """ 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.segments: return None sum_lat: float = 0 sum_lon: float = 0 n = 0 for track_segment in self.segments: for point in track_segment.points: n += 1 sum_lat += point.latitude sum_lon += point.longitude if not n: return mod_geo.Location(0, 0) return mod_geo.Location(latitude=sum_lat / n, longitude=sum_lon / n) def smooth(self, vertical: bool=True, horizontal: bool=False, remove_extremes: bool=False) -> None: """ See: GPXTrackSegment.smooth() """ for track_segment in self.segments: track_segment.smooth(vertical, horizontal, remove_extremes) def has_times(self) -> bool: """ See GPXTrackSegment.has_times() """ if not self.segments: return False for track_segment in self.segments: if track_segment.has_times(): return True return False def has_elevations(self) -> bool: """ Returns true if track data has elevation for all segments """ if not self.segments: return False result = True for track_segment in self.segments: result = result and track_segment.has_elevations() return result def get_nearest_location(self, location: mod_geo.Location) -> Optional[NearestLocationData]: """ Returns (location, track_segment_no, track_point_no) for nearest location on track """ return min((NearestLocationData(pt, -1, seg, pt_no) for (pt, seg, pt_no) in self.walk()) # type: ignore ,key=lambda x: x.location.distance_2d(location) if x is not None else mod_math.inf ,default=None) def clone(self) -> "GPXTrack": return mod_copy.deepcopy(self) def __repr__(self) -> str: parts = [] for attribute in 'name', 'description', 'number': value = getattr(self, attribute) if value is not None: parts.append(f'{attribute}={value!r}') parts.append(f'segments={self.segments!r}') return f'GPXTrack({", ".join(parts)})' class GPX: gpx_10_fields = [ mod_gpxfield.GPXField('version', attribute='version'), mod_gpxfield.GPXField('creator', attribute='creator'), mod_gpxfield.GPXField('name'), mod_gpxfield.GPXField('description', 'desc'), mod_gpxfield.GPXField('author_name', 'author'), mod_gpxfield.GPXField('author_email', 'email'), mod_gpxfield.GPXField('link', 'url'), mod_gpxfield.GPXField('link_text', 'urlname'), mod_gpxfield.GPXField('time', type=mod_gpxfield.TIME_TYPE), mod_gpxfield.GPXField('keywords'), mod_gpxfield.GPXComplexField('bounds', classs=GPXBounds, empty_body=True), mod_gpxfield.GPXComplexField('waypoints', classs=GPXWaypoint, tag='wpt', is_list=True), mod_gpxfield.GPXComplexField('routes', classs=GPXRoute, tag='rte', is_list=True), mod_gpxfield.GPXComplexField('tracks', classs=GPXTrack, tag='trk', is_list=True), ] # Text fields serialize as empty container tags, dependents are # are listed after as 'tag:dep1:dep2:dep3'. If no dependents are # listed, it will always serialize. The container is closed with # '/tag'. Required dependents are preceded by an @. If a required # dependent is empty, nothing in the container will serialize. The # format is 'tag:@dep2'. No optional dependents need to be listed. # Extensions not yet supported gpx_11_fields = [ mod_gpxfield.GPXField('version', attribute='version'), mod_gpxfield.GPXField('creator', attribute='creator'), 'metadata:name:description:author_name:author_email:author_link:copyright_author:copyright_year:copyright_license:link:time:keywords:bounds', mod_gpxfield.GPXField('name', 'name'), mod_gpxfield.GPXField('description', 'desc'), 'author:author_name:author_email:author_link', mod_gpxfield.GPXField('author_name', 'name'), mod_gpxfield.GPXEmailField('author_email', 'email'), 'link:@author_link', mod_gpxfield.GPXField('author_link', attribute='href'), mod_gpxfield.GPXField('author_link_text', tag='text'), mod_gpxfield.GPXField('author_link_type', tag='type'), '/link', '/author', 'copyright:copyright_author:copyright_year:copyright_license', mod_gpxfield.GPXField('copyright_author', attribute='author'), mod_gpxfield.GPXField('copyright_year', tag='year'), mod_gpxfield.GPXField('copyright_license', tag='license'), '/copyright', '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('time', type=mod_gpxfield.TIME_TYPE), mod_gpxfield.GPXField('keywords'), mod_gpxfield.GPXComplexField('bounds', classs=GPXBounds, empty_body=True), mod_gpxfield.GPXExtensionsField('metadata_extensions', tag='extensions'), '/metadata', mod_gpxfield.GPXComplexField('waypoints', classs=GPXWaypoint, tag='wpt', is_list=True), mod_gpxfield.GPXComplexField('routes', classs=GPXRoute, tag='rte', is_list=True), mod_gpxfield.GPXComplexField('tracks', classs=GPXTrack, tag='trk', is_list=True), mod_gpxfield.GPXExtensionsField('extensions', is_list=True), ] __slots__ = ('version', 'creator', 'name', 'description', 'author_name', 'author_email', 'link', 'link_text', 'time', 'keywords', 'bounds', 'waypoints', 'routes', 'tracks', 'author_link', 'author_link_text', 'author_link_type', 'copyright_author', 'copyright_year', 'copyright_license', 'link_type', 'metadata_extensions', 'extensions', 'nsmap', 'schema_locations') def __init__(self) -> None: self.version: Optional[str] = None self.creator: Optional[str] = None self.name: Optional[str] = None self.description: Optional[str] = None self.link: Optional[str] = None self.link_text: Optional[str] = None self.link_type: Optional[str] = None self.time: Optional[mod_datetime.datetime] = None self.keywords: Optional[str] = None self.bounds: Optional[GPXBounds] = None self.author_name: Optional[str] = None self.author_email: Optional[str] = None self.author_link: Optional[str] = None self.author_link_text: Optional[str] = None self.author_link_type: Optional[str] = None self.copyright_author: Optional[str] = None self.copyright_year: Optional[str] = None self.copyright_license: Optional[str] = None self.metadata_extensions: List[Any] = [] # TODO self.extensions: List[Any] = [] # TODO self.waypoints: List[GPXWaypoint] = [] self.routes: List[GPXRoute] = [] self.tracks: List[GPXTrack] = [] self.nsmap: Dict[str, str] = {} self.schema_locations: List[str] = [] def simplify(self, max_distance: Optional[float]=None) -> None: """ Simplify using the Ramer-Douglas-Peucker algorithm: http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """ for track in self.tracks: track.simplify(max_distance=max_distance) def reduce_points(self, max_points_no: Optional[float]=None, min_distance: Optional[float]=None) -> None: """ Reduces the number of points. Points will be updated in place. Parameters ---------- max_points : int The maximum number of points to include in the GPX min_distance : float The minimum separation in meters between points """ if max_points_no is None and min_distance is None: raise ValueError("Either max_point_no or min_distance must be supplied") if max_points_no is not None and max_points_no < 2: raise ValueError("max_points_no must be greater than or equal to 2") points_no = len(list(self.walk())) if max_points_no is not None and points_no <= max_points_no: # No need to reduce points only if no min_distance is specified: if not min_distance: return length = self.length_3d() min_distance = min_distance or 0 max_points_no = max_points_no or 1000000000 min_distance = max(min_distance, mod_math.ceil(length / max_points_no)) for track in self.tracks: track.reduce_points(min_distance) # TODO log.debug('Track reduced to %s points', self.get_track_points_no()) def adjust_time(self, delta: mod_datetime.timedelta, all: bool=False) -> None: """ Adjusts the time of all points in all of the segments of all tracks by the specified delta. If all=True, waypoints and routes will also be adjusted by the specified delta. Parameters ---------- delta : datetime.timedelta Positive time delta will adjust times into the future Negative time delta will adjust times into the past all : bool When true, also adjusts time for waypoints and routes. """ if self.time: self.time += delta for track in self.tracks: track.adjust_time(delta) if all: for waypoint in self.waypoints: waypoint.adjust_time(delta) for route in self.routes: route.adjust_time(delta) def remove_time(self, all: bool=False) -> None: """ Removes time data of all points in all of the segments of all tracks. If all=True, time date will also be removed from waypoints and routes. Parameters ---------- all : bool When true, also removes time data for waypoints and routes. """ for track in self.tracks: track.remove_time() if all: for waypoint in self.waypoints: waypoint.remove_time() for route in self.routes: route.remove_time() def remove_elevation(self, tracks: bool=True, routes: bool=False, waypoints: bool=False) -> None: """ Removes elevation data. """ if tracks: for track in self.tracks: track.remove_elevation() if routes: for route in self.routes: route.remove_elevation() if waypoints: for waypoint in self.waypoints: waypoint.remove_elevation() def get_time_bounds(self) -> TimeBounds: """ Gets the time bounds (start and end) of the GPX file. 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 track in self.tracks: track_start_time, track_end_time = track.get_time_bounds() if not start_time: start_time = track_start_time if track_end_time: end_time = track_end_time return TimeBounds(start_time, end_time) def get_bounds(self) -> Optional[GPXBounds]: """ Gets the latitude and longitude bounds of the GPX file. Returns ---------- bounds : Bounds named tuple min_latitude : float Minimum latitude of track in decimal degrees [-90, 90] max_latitude : float Maximum latitude of track in decimal degrees [-90, 90] min_longitude : float Minimum longitude of track in decimal degrees [-180, 180] max_longitude : float Maximum longitude of track in decimal degrees [-180, 180] """ result: Optional[GPXBounds] = None for track in self.tracks: track_bounds = track.get_bounds() if not result: result = track_bounds elif track_bounds: result = track_bounds.max_bounds(result) return result def get_points_no(self) -> int: """ Get the number of points in all segments of all track. Returns ---------- num_points : integer Number of points in GPX """ result = 0 for track in self.tracks: result += track.get_points_no() return result def refresh_bounds(self) -> None: """ Compute bounds and reload min_latitude, max_latitude, min_longitude and max_longitude properties of this object """ self.bounds = self.get_bounds() def smooth(self, vertical: bool=True, horizontal: bool=False, remove_extremes: bool=False) -> None: """ See GPXTrackSegment.smooth(...) """ for track in self.tracks: track.smooth(vertical=vertical, horizontal=horizontal, remove_extremes=remove_extremes) def remove_empty(self) -> None: """ Removes segments, routes """ routes = [] for route in self.routes: if len(route.points) > 0: routes.append(route) self.routes = routes for track in self.tracks: track.remove_empty() def get_moving_data(self, stopped_speed_threshold: Optional[float]=None, raw: bool=False, speed_extreemes_percentiles: float=IGNORE_TOP_SPEED_PERCENTILES, ignore_nonstandard_distances: bool=True) -> MovingData: """ 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 track. Because of errors in the GPS recording, it may be good to calculate them on a reduced and smoothed version of the track. Something like this: 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) moving_time, stopped_time, moving_distance, stopped_distance, max_speed_ms = cloned_gpx.get_moving_data max_speed_kmh = max_speed_ms * 60. ** 2 / 1000. Experiment with your own variations to get the values you expect. Max speed is in m/s. """ moving_time = 0. stopped_time = 0. moving_distance = 0. stopped_distance = 0. max_speed = 0. for track in self.tracks: track_moving_time, track_stopped_time, track_moving_distance, track_stopped_distance, track_max_speed = track.get_moving_data(stopped_speed_threshold, raw=raw, speed_extreemes_percentiles=speed_extreemes_percentiles, ignore_nonstandard_distances=ignore_nonstandard_distances) moving_time += track_moving_time stopped_time += track_stopped_time moving_distance += track_moving_distance stopped_distance += track_stopped_distance if track_max_speed > max_speed: max_speed = track_max_speed return MovingData(moving_time, stopped_time, moving_distance, stopped_distance, max_speed) def split(self, track_no: int, track_segment_no: int, track_point_no: int) -> None: """ Splits one of the segments of a track in 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 ---------- track_no : integer The index of the track to split track_segment_no : integer The index of the segment to split track_point_no : integer The index of the track point in the segment to split """ track = self.tracks[track_no] track.split(track_segment_no=track_segment_no, track_point_no=track_point_no) def length_2d(self) -> float: """ Computes 2-dimensional length of the GPX file (only latitude and longitude, no elevation). This is the sum of 2D length of all segments in all tracks. Returns ---------- length : float Length returned in meters """ result: float = 0 for track in self.tracks: length = track.length_2d() if length: result += length return result def length_3d(self) -> float: """ Computes 3-dimensional length of the GPX file (latitude, longitude, and elevation). This is the sum of 3D length of all segments in all tracks. Returns ---------- length : float Length returned in meters """ result: float = 0 for track in self.tracks: length = track.length_3d() if length: result += length return result def walk(self, only_points: bool=False) -> Iterator[Any]: """ Generator used to iterates through points in GPX file Parameters ---------- only_point s: boolean Only yield points while walking Yields ---------- point : GPXTrackPoint Point in the track track_no : integer Index of track containing point. This is suppressed if only_points is True. segment_no : integer Index of segment containing point. This is suppressed if only_points is True. point_no : integer Index of point. This is suppressed if only_points is True. """ for track_no, track in enumerate(self.tracks if self.tracks else [] ): for segment_no, segment in enumerate(track.segments if track.segments else []): for point_no, point in enumerate(segment.points if segment.points else []): if only_points: yield point else: yield point, track_no, segment_no, point_no def get_track_points_no(self) -> int: """ Number of track points, *without* route and waypoints """ result = 0 for track in self.tracks: for segment in track.segments: result += len(segment.points) return result def get_duration(self) -> Optional[float]: """ Calculates duration of GPX file Returns ------- duration: float Duration in seconds or None if time data is not fully populated. """ if not self.tracks: return 0.0 result: float = 0.0 for track in self.tracks: duration = track.get_duration() if duration or duration == 0: result += duration elif duration is None: return None return result def get_uphill_downhill(self) -> UphillDownhill: """ Calculates the uphill and downhill elevation climbs for the gpx file. If elevation for some points is not found those are simply ignored. Returns ------- uphill_downhill: UphillDownhill named tuple uphill: float Uphill elevation climbs in meters downhill: float Downhill elevation descent in meters """ if not self.tracks: return UphillDownhill(0, 0) uphill: float = 0 downhill: float = 0 for track in self.tracks: current_uphill, current_downhill = track.get_uphill_downhill() uphill += current_uphill or 0 downhill += current_downhill or 0 return UphillDownhill(uphill, downhill) def get_location_at(self, time: mod_datetime.datetime) -> List[mod_geo.Location]: """ Gets approx. location at given time. Note that, at the moment this method returns an instance of GPXTrackPoint in the future -- this may be a mod_geo.Location instance with approximated latitude, longitude and elevation! """ result: List[mod_geo.Location] = [] for track in self.tracks: locations = track.get_location_at(time) for location in locations: result.append(location) return result def get_elevation_extremes(self) -> MinimumMaximum: """ Calculate elevation extremes of GPX file Returns ------- min_max_elevation: MinimumMaximum named tuple minimum: float Minimum elevation in meters maximum: float Maximum elevation in meters """ if not self.tracks: return MinimumMaximum(None, None) elevations = [] for track in self.tracks: (_min, _max) = track.get_elevation_extremes() if _min is not None: elevations.append(_min) if _max is not None: elevations.append(_max) if len(elevations) == 0: return MinimumMaximum(None, None) return MinimumMaximum(min(elevations), max(elevations)) def get_points_data(self, distance_2d: bool=False) -> List[PointData]: """ Returns a list of tuples containing the actual point, its distance from the start, track_no, segment_no, and segment_point_no """ distance_from_start = 0 previous_point = None # (point, distance_from_start) pairs: points = [] for track_no, track in enumerate(self.tracks): for segment_no, segment in enumerate(track.segments): for point_no, point in enumerate(segment.points): if previous_point and point_no > 0: if distance_2d: distance = point.distance_2d(previous_point) else: distance = point.distance_3d(previous_point) distance_from_start += distance points.append(PointData(point, distance_from_start, track_no, segment_no, point_no)) previous_point = point return points def get_nearest_locations(self, location: mod_geo.Location, threshold_distance: float=0.01) -> List[NearestLocationData]: """ Returns a list of locations of elements like consisting of points where the location may be on the track threshold_distance is the minimum distance from the track so that the point *may* be counted as to be "on the track". For example 0.01 means 1% of the track distance. """ assert location assert threshold_distance result: List[NearestLocationData] = [] points = self.get_points_data() if not points: return result distance: Optional[float] = points[- 1][1] threshold = (distance or 0.0) * threshold_distance min_distance_candidate = None distance_from_start_candidate = None track_no_candidate: Optional[int] = None segment_no_candidate: Optional[int] = None point_no_candidate: Optional[int] = None for point, distance_from_start, track_no, segment_no, point_no in points: distance = location.distance_3d(point) if (distance or 0.0) < threshold: if min_distance_candidate is None or distance < min_distance_candidate: min_distance_candidate = distance distance_from_start_candidate = distance_from_start track_no_candidate = track_no segment_no_candidate = segment_no point_no_candidate = point_no else: if distance_from_start_candidate is not None and point and track_no_candidate is not None and segment_no_candidate is not None and point_no_candidate is not None: result.append(NearestLocationData(point, track_no_candidate, segment_no_candidate, point_no_candidate)) min_distance_candidate = None distance_from_start_candidate = None track_no_candidate = None segment_no_candidate = None point_no_candidate = None if distance_from_start_candidate is not None and point and track_no_candidate is not None and segment_no_candidate is not None and point_no_candidate is not None: result.append(NearestLocationData(point, track_no_candidate, segment_no_candidate, point_no_candidate)) return result def get_nearest_location(self, location: mod_geo.Location) -> Optional[NearestLocationData]: """ Returns (location, track_no, track_segment_no, track_point_no) for the nearest location on map """ return min((NearestLocationData(pt, tr, seg, pt_no) for (pt,tr, seg, pt_no) in self.walk()) # type:ignore ,key=lambda x: x.location.distance_2d(location) if x is not None else mod_math.inf ,default=None) def add_elevation(self, delta: float) -> None: """ Adjusts elevation data of GPX data. Parameters ---------- delta : float Elevation delta in meters to apply to GPX data """ for track in self.tracks: track.add_elevation(delta) def add_missing_data(self, get_data_function: Callable[[GPXTrackPoint], Any], add_missing_function: Callable[[List[GPXTrackPoint], GPXTrackPoint, GPXTrackPoint, List[float]], None]) -> None: for track in self.tracks: track.add_missing_data(get_data_function, add_missing_function) def add_missing_elevations(self) -> None: def _add(interval: List[GPXTrackPoint], start: GPXTrackPoint, end: GPXTrackPoint, distances_ratios: List[float]) -> None: if (start.elevation is None) or (end.elevation is None): return assert start assert end assert interval assert len(interval) == len(distances_ratios) for point, ratio in zip(interval, distances_ratios): point.elevation = start.elevation + ratio * (end.elevation - start.elevation) self.add_missing_data(get_data_function=lambda point: point.elevation, add_missing_function=_add) def add_missing_times(self) -> None: def _add(interval: List[GPXTrackPoint], start: GPXTrackPoint, end: GPXTrackPoint, distances_ratios: List[float]) -> None: if (not start) or (not end) or (not start.time) or (not end.time): return assert interval assert len(interval) == len(distances_ratios) if end.time and start.time: seconds_between = float(mod_utils.total_seconds(end.time - start.time)) for point, ratio in zip(interval, distances_ratios): point.time = start.time + mod_datetime.timedelta(seconds=ratio * seconds_between) self.add_missing_data(get_data_function=lambda point: point.time, add_missing_function=_add) def add_missing_speeds(self) -> None: """ The missing speeds are added to a segment. The weighted harmonic mean is used to approximate the speed at a :obj:'~.GPXTrackPoint'. For this to work the speed of the first and last track point in a segment needs to be known. """ def _add(interval: List[GPXTrackPoint], start: GPXTrackPoint, end: GPXTrackPoint, distances_ratios: List[float]) -> None: if (not start) or (not end) or (not start.time) or (not end.time): return assert interval assert len(interval) == len(distances_ratios) time_dist_before = (interval[0].time_difference(start), interval[0].distance_3d(start)) time_dist_after = (interval[-1].time_difference(end), interval[-1].distance_3d(end)) # Assemble list of times and distance to neighbour points times_dists: List[Tuple[Optional[float], Optional[float]]] = [ (point.time_difference(nextpoint), point.distance_3d(nextpoint)) for point, nextpoint in zip(interval, interval[1:]) ] times_dists.insert(0, time_dist_before) times_dists.append(time_dist_after) for i, point in enumerate(interval): time_left, dist_left = times_dists[i] time_right, dist_right = times_dists[i+1] if time_left and time_right and dist_left and dist_right: point.speed = (dist_left + dist_right) / (time_left + time_right) self.add_missing_data(get_data_function=lambda point: point.speed, add_missing_function=_add) def fill_time_data_with_regular_intervals(self, start_time: Optional[mod_datetime.datetime]=None, time_delta: Optional[mod_datetime.timedelta]=None, end_time: Optional[mod_datetime.datetime]=None, force: bool=True) -> None: """ Fills the time data for all points in the GPX file. At least two of the parameters start_time, time_delta, and end_time have to be provided. If the three are provided, time_delta will be ignored and will be recalculated using start_time and end_time. The first GPX point will have a time equal to start_time. Then points are assumed to be recorded at regular intervals time_delta. If the GPX file currently contains time data, it will be overwritten, unless the force flag is set to False, in which case the function will return a GPXException error. Parameters ---------- start_time: datetime.datetime object Start time of the GPX file (corresponds to the time of the first point) time_delta: datetime.timedelta object Time interval between two points in the GPX file end_time: datetime.datetime object End time of the GPX file (corresponds to the time of the last point) force: bool Overwrite current data if the GPX file currently contains time data """ if not (start_time and end_time) and not (start_time and time_delta) and not (time_delta and end_time): raise GPXException('You must provide at least two parameters among start_time, time_step, and end_time') if self.has_times() and not force: raise GPXException('GPX file currently contains time data. Use force=True to overwrite.') point_no = self.get_points_no() if start_time and end_time: if start_time > end_time: raise GPXException('Invalid parameters: end_time must occur after start_time') time_delta = (end_time - start_time) / (point_no - 1) elif end_time and not start_time and time_delta: start_time = end_time - (point_no - 1) * time_delta if start_time: self.time = start_time i = 0 for point in self.walk(only_points=True): if i == 0: point.time = start_time elif time_delta is not None and start_time is not None: point.time = start_time + i * time_delta i += 1 def move(self, location_delta: mod_geo.LocationDelta) -> None: """ Moves each point in the gpx file (routes, waypoints, tracks). Parameters ---------- location_delta: LocationDelta LocationDelta to move each point """ for route in self.routes: route.move(location_delta) for waypoint in self.waypoints: waypoint.move(location_delta) for track in self.tracks: track.move(location_delta) def to_xml(self, version: Optional[str]=None, prettyprint: bool=True) -> str: """ FIXME: Note, this method will change self.version """ if not version: if self.version: version = self.version else: version = '1.1' if version != '1.0' and version != '1.1': raise GPXException(f'Invalid version {version}') self.version = version if not self.creator: self.creator = 'gpx.py -- https://github.com/tkrajina/gpxpy' self.nsmap['xsi'] = 'http://www.w3.org/2001/XMLSchema-instance' version_path = version.replace('.', '/') self.nsmap['defaultns'] = f'http://www.topografix.com/GPX/{version_path}' if not self.schema_locations: self.schema_locations = [ f'http://www.topografix.com/GPX/{version_path}', f'http://www.topografix.com/GPX/{version_path}/gpx.xsd', ] content = mod_gpxfield.gpx_fields_to_xml( self, 'gpx', version, custom_attributes={ 'xsi:schemaLocation': ' '.join(self.schema_locations) }, nsmap=self.nsmap, prettyprint=prettyprint ) return f'\n{content.strip()}' def has_times(self) -> bool: """ See GPXTrackSegment.has_times() """ if not self.tracks: return False result = True for track in self.tracks: result = result and track.has_times() return result def has_elevations(self) -> bool: """ See GPXTrackSegment.has_elevations()) """ if not self.tracks: return False result = True for track in self.tracks: result = result and track.has_elevations() return result def __repr__(self) -> str: parts = [] for attribute in 'waypoints', 'routes', 'tracks': value = getattr(self, attribute) if value: parts.append(f'{attribute}={value!r}') return f'GPX({", ".join(parts)})' def clone(self) -> "GPX": return mod_copy.deepcopy(self) # Add attributes and fill default values (lists or None) for all GPX elements: for var_name in dir(): var_value = vars()[var_name] if hasattr(var_value, 'gpx_10_fields') or hasattr(var_value, 'gpx_11_fields'): #print('Check/fill %s' % var_value) mod_gpxfield.gpx_check_slots_and_default_values(var_value) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278641.0 gpxpy-1.6.2/gpxpy/gpxfield.py0000644000076500000240000005431614531671661014760 0ustar00tkrstaff# Copyright 2014 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. import inspect as mod_inspect import datetime as mod_datetime import re as mod_re import copy as mod_copy from . import utils as mod_utils from typing import * class GPXFieldTypeConverter: def __init__(self, from_string: str, to_string: str) -> None: self.from_string = from_string self.to_string = to_string RE_TIMESTAMP = mod_re.compile( r'^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[T ]([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' r'(\.[0-9]{1,15})?(Z|[+-−][0-9]{2}:?(?:[0-9]{2})?)?$') class SimpleTZ(mod_datetime.tzinfo): __slots__ = ('offset',) def __init__(self, s: str="") -> None: self.offset = 0 if s and len(s) >= 2: if s[0] in ('−', '-'): mult = -1 s = s[1:] else: if s[0] == '+': s = s[1:] mult = 1 hour = int(s[:2]) if s[:2].isdigit() else 0 if len(s) >= 4: minute = int(s[-2:]) if s[-2:].isdigit() else 0 else: minute = 0 self.offset = mult * (hour * 60 + minute) def utcoffset(self, dt: Optional[mod_datetime.datetime]) -> mod_datetime.timedelta: return mod_datetime.timedelta(minutes=self.offset) def dst(self, dt: Optional[mod_datetime.datetime]) -> mod_datetime.timedelta: return mod_datetime.timedelta(0) def tzname(self, dt: Optional[mod_datetime.datetime]) -> str: if self.offset == 0: return 'Z' return f'{self.offset // 60:02}:{self.offset % 60:02}' def __copy__(self) -> mod_datetime.tzinfo: return self.__deepcopy__() def __deepcopy__(self, memodict: Optional[Dict[Any, Any]]={}) -> mod_datetime.tzinfo: return self.__class__(self.tzname(None)) def __repr__(self) -> str: return f'SimpleTZ({self.tzname(None)!r})' def __eq__(self, other: Any) -> bool: return self.offset == other.offset # type: ignore def parse_time(string: str) -> Optional[mod_datetime.datetime]: from . import gpx as mod_gpx if not string: return None m = RE_TIMESTAMP.match(string) if m: dt = [int(m.group(i)) for i in range(1, 7)] if m.group(7): f = m.group(7)[1:7] dt.append(int(f + "0" * (6 - len(f)))) else: dt.append(0) if m.group(8): dt.append(SimpleTZ(m.group(8))) # type: ignore return mod_datetime.datetime(*dt) # type: ignore raise mod_gpx.GPXException(f'Invalid time: {string}') def format_time(time: mod_datetime.datetime) -> str: return time.isoformat().replace('+00:00', 'Z') # ---------------------------------------------------------------------------------------------------- # Type converters used to convert from/to the string in the XML: # ---------------------------------------------------------------------------------------------------- class FloatConverter: def __init__(self) -> None: self.from_string = lambda string : None if string is None else float(string.strip()) self.to_string = lambda flt : mod_utils.make_str(flt) class IntConverter: def __init__(self) -> None: self.from_string = lambda string: None if string is None else int(string.strip()) self.to_string = lambda flt: str(flt) class TimeConverter: def from_string(self, string: str) -> Optional[mod_datetime.datetime]: try: return parse_time(string) except: return None def to_string(self, time: Optional[mod_datetime.datetime]) -> Optional[str]: return format_time(time) if time else None INT_TYPE = IntConverter() FLOAT_TYPE = FloatConverter() TIME_TYPE = TimeConverter() # ---------------------------------------------------------------------------------------------------- # Field converters: # ---------------------------------------------------------------------------------------------------- class AbstractGPXField: def __init__(self, attribute_field: Optional[str] = None, is_list: Optional[bool]=None) -> None: self.attribute_field = attribute_field self.is_list = is_list self.attribute: Optional[str] = None def from_xml(self, node: str, version: str) -> Any: raise Exception('Not implemented') def to_xml(self, value: Any, version: str, nsmap: Any) -> Optional[str]: raise Exception('Not implemented') class GPXField(AbstractGPXField): """ Used for to (de)serialize fields with simple field<->xml_tag mapping. """ def __init__(self, name: Optional[str], tag: Optional[str]=None, attribute: Optional[str]=None, type: Any=None, possible: Optional[Iterable[str]]=None, mandatory: Optional[bool]=None) -> None: AbstractGPXField.__init__(self) self.name = name if tag and attribute: from . import gpx as mod_gpx raise mod_gpx.GPXException('Only tag *or* attribute may be given!') self.tag: Optional[str] = None if attribute: self.tag = None self.attribute = attribute elif tag: self.tag = name if (tag is True) else tag # type: ignore self.attribute = None else: self.tag = name self.attribute = None self.type_converter = type self.possible = possible self.mandatory = mandatory def from_xml(self, node: Any, version: str) -> Any: if self.attribute: if node is not None: result = node.get(self.attribute) else: __node = node.find(self.tag) if __node is not None: result = __node.text else: result = None if result is None: if self.mandatory: from . import gpx as mod_gpx raise mod_gpx.GPXException(f'{self.name} is mandatory in {self.tag} (got {result})') return None if self.type_converter: try: result = self.type_converter.from_string(result) except Exception as e: from . import gpx as mod_gpx raise mod_gpx.GPXException(f'Invalid value for <{self.tag}>... {result} ({e})') if self.possible: if not (result in self.possible): from . import gpx as mod_gpx raise mod_gpx.GPXException(f'Invalid value "{result}", possible: {self.possible}') return result def to_xml(self, value: Any, version: str, nsmap: Any=None, prettyprint: bool=True, indent: str='') -> Optional[str]: if value is None: return '' if not prettyprint: indent = '' if self.attribute: return f'{self.attribute}="{mod_utils.make_str(value)}"' elif self.type_converter: value = self.type_converter.to_string(value) if self.tag: return mod_utils.to_xml(self.tag, content=value, escape=True, prettyprint=prettyprint, indent=indent) return '' class GPXComplexField(AbstractGPXField): def __init__(self, name: str, classs: Any, tag: Optional[str]=None, is_list: bool=False, empty_body: bool=False) -> None: AbstractGPXField.__init__(self, is_list=is_list) self.name = name self.tag = tag or name self.classs = classs self.empty_body = empty_body def from_xml(self, node: Any, version: str) -> Any: if self.is_list: result = [] for child in node: if child.tag == self.tag: result.append(gpx_fields_from_xml(self.classs, child, version)) return result else: field_node = node.find(self.tag) if field_node is None: return None return gpx_fields_from_xml(self.classs, field_node, version) def to_xml(self, value: Any, version: str, nsmap: Dict[str, str]={}, prettyprint: bool=True, indent: str='') -> str: if not prettyprint: indent = '' if self.is_list: result = [] for obj in value: result.append(gpx_fields_to_xml(obj, self.tag, version, nsmap=nsmap, prettyprint=prettyprint, indent=indent)) return ''.join(result) else: return gpx_fields_to_xml(value, self.tag, version, prettyprint=prettyprint, indent=indent, empty_body=self.empty_body) class GPXEmailField(AbstractGPXField): """ Converts GPX1.1 email tag group from/to string. """ def __init__(self, name: str, tag: Optional[str]=None): AbstractGPXField.__init__(self, is_list=False) self.name = name self.tag = tag or name def from_xml(self, node: Any, version: str) -> Any: """ Extract email address. Args: node: ETree node with child node containing self.tag version: str of the gpx output version "1.0" or "1.1" Returns: A string containing the email address. """ email_node = node.find(self.tag) if email_node is None: return '' email_id = email_node.get('id') email_domain = email_node.get('domain') return f'{email_id}@{email_domain}' def to_xml(self, value: Any, version: str, nsmap: Optional[Dict[str, str]]=None, prettyprint: bool=True, indent: str='') -> str: """ Write email address to XML Args: value: str representing an email address version: str of the gpx output version "1.0" or "1.1" Returns: None if value is empty or str of XML representation of the address. Representation starts with a \n. """ if not value: return '' if not prettyprint: indent = '' if '@' in value: pos = value.find('@') email_id = value[:pos] email_domain = value[pos+1:] else: email_id = value email_domain = 'unknown' return f'\n{indent}<{self.tag} id="{email_id}" domain="{email_domain}" />' class GPXExtensionsField(AbstractGPXField): """ GPX1.1 extensions ... key-value type. """ def __init__(self, name: str, tag: Optional[str]=None, is_list: bool=True) -> None: AbstractGPXField.__init__(self, is_list=is_list) self.name = name self.tag = tag or 'extensions' def from_xml(self, node: Any, version: str) -> Any: """ Build a list of extension Elements. Args: node: Element at the root of the extensions version: unused, only 1.1 supports extensions Returns: a list of Element objects """ result: Any = [] extensions_node = node.find(self.tag) if extensions_node is None: return result for child in extensions_node: result.append(mod_copy.deepcopy(child)) return result def _resolve_prefix(self, qname: str, nsmap: Dict[str, str]) -> str: """ Convert a tag from Clark notation into prefix notation. Convert a tag from Clark notation using the nsmap into a prefixed tag. If the tag isn't in Clark notation, return the qname back. Converts {namespace}tag -> prefix:tag Args: qname: string with the fully qualified name in Clark notation nsmap: a dict of prefix, namespace pairs Returns: string of the tag ready to be serialized. """ if nsmap is not None and '}' in qname: uri, _, localname = qname.partition("}") uri = uri.lstrip("{") qname = uri + ':' + localname for prefix, namespace in nsmap.items(): if uri == namespace: qname = prefix + ':' + localname break return qname def _ETree_to_xml(self, node: Any, nsmap: Dict[str, str]={}, prettyprint: bool=True, indent: str='') -> str: """ Serialize ETree element and all subelements. Creates a string of the ETree and all children. The prefixes are resolved through the nsmap for easier to read XML. Args: node: ETree with the extension data version: string of GPX version, must be 1.1 nsmap: dict of prefixes and URIs prettyprint: boolean, when true, indent line indent: string prepended to tag, usually 2 spaces per level Returns: string with all the prefixed tags and data for the node and its children as XML. """ if not prettyprint: indent = '' # Build element tag and text result = [] prefixedname = self._resolve_prefix(node.tag, nsmap) result.append(f'\n{indent}<{prefixedname}') for attrib, value in node.attrib.items(): attrib = self._resolve_prefix(attrib, nsmap) result.append(f' {attrib}="{value}"') result.append('>') if node.text is not None: result.append(node.text.strip()) # Build subelement nodes for child in node: result.append(self._ETree_to_xml(child, nsmap, prettyprint=prettyprint, indent=f'{indent} ')) # Add tail and close tag tail = node.tail if tail is not None: tail = tail.strip() else: tail = '' if len(node) > 0: result.append(f'\n{indent}') result.append(f'{tail}') return ''.join(result) def to_xml(self, value: Any, version: str, nsmap: Dict[str, str]={}, prettyprint: bool=True, indent: str='') -> str: """ Serialize list of ETree. Creates a string of all the ETrees in the list. The prefixes are resolved through the nsmap for easier to read XML. Args: value: list of ETrees with the extension data version: string of GPX version, must be 1.1 nsmap: dict of prefixes and URIs prettyprint: boolean, when true, indent line indent: string prepended to tag, usually 2 spaces per level Returns: string with all the prefixed tags and data for each node as XML. """ if not prettyprint: indent = '' if not value or version != "1.1": return '' result = [f'\n{indent}<{self.tag}>'] for extension in value: result.append(self._ETree_to_xml(extension, nsmap, prettyprint=prettyprint, indent=f'{indent} ')) result.append(f'\n{indent}') return ''.join(result) # ---------------------------------------------------------------------------------------------------- # Utility methods: # ---------------------------------------------------------------------------------------------------- def _check_dependents(gpx_object: Any, fieldname: str) -> Tuple[str, str]: """ Check for data in subelements. Fieldname takes the form of 'tag:dep1:dep2:dep3' for an arbitrary number of dependents. If all the gpx_object.dep attributes are empty, return a sentinel value to suppress serialization of all subelements. Args: gpx_object: GPXField object to check for data fieldname: string with tag and dependents delimited with ':' Returns: Two strings. The first is a sentinel value, '/' + tag, if all the subelements are empty and an empty string otherwise. The second is the bare tag name. """ if ':' in fieldname: children = fieldname.split(':') field = children.pop(0) for child in children: if getattr(gpx_object, child.lstrip('@')): return '', field # Child has data return f'/{field}', field # No child has data return '', fieldname # No children def gpx_fields_to_xml(instance: Any, tag: str, version: str, custom_attributes: Dict[str, str]={}, nsmap: Dict[str, str]={}, prettyprint: bool=True, indent: str='', empty_body: bool=False) -> str: if not prettyprint: indent = '' fields = instance.gpx_10_fields if version == '1.1': fields = instance.gpx_11_fields tag_open = bool(tag) body = [] if tag: body.append(f'\n{indent}<{tag}') if tag == 'gpx': # write nsmap in root node body.append(f' xmlns="{nsmap["defaultns"]}"') namespaces = set(nsmap.keys()) namespaces.remove('defaultns') for prefix in sorted(namespaces): body.append(f' xmlns:{prefix}="{nsmap[prefix]}"') if custom_attributes: # Make sure to_xml() always return attributes in the same order: for key in sorted(custom_attributes.keys()): body.append(f' {key}="{mod_utils.make_str(custom_attributes[key])}"') suppressuntil = '' for gpx_field in fields: # strings indicate non-data container tags with subelements if isinstance(gpx_field, str): # Suppress empty tags if suppressuntil: if suppressuntil == gpx_field: suppressuntil = '' else: suppressuntil, gpx_field = _check_dependents(instance, gpx_field) if not suppressuntil: if tag_open: body.append('>') tag_open = False if gpx_field[0] == '/': body.append(f'\n{indent}<{gpx_field}>') if prettyprint and len(indent) > 1: indent = indent[:-2] else: if prettyprint: indent += ' ' body.append(f'\n{indent}<{gpx_field}') tag_open = True elif not suppressuntil: value = getattr(instance, gpx_field.name) if gpx_field.attribute: body.append(' ' + gpx_field.to_xml(value, version, nsmap, prettyprint=prettyprint, indent=f'{indent} ')) elif value is not None: if tag_open: body.append('>') tag_open = False xml_value = gpx_field.to_xml(value, version, nsmap, prettyprint=prettyprint, indent=f'{indent} ') if xml_value: body.append(xml_value) if tag: if empty_body: body.append(' />') #print("tag,body:",tag,'\t',body) else: if tag_open: body.append('>') body.append('\n' + indent + '') return ''.join(body) def gpx_fields_from_xml(class_or_instance: Any, node: str, version: str) -> Any: if mod_inspect.isclass(class_or_instance): result = class_or_instance() else: result = class_or_instance fields = result.gpx_10_fields if version == '1.1': fields = result.gpx_11_fields node_path: List[Union[str, int]] = [node] for gpx_field in fields: current_node = node_path[-1] if isinstance(gpx_field, str): gpx_field = gpx_field.partition(':')[0] if gpx_field.startswith('/'): node_path.pop() else: if current_node is None: node_path.append(None) else: node_path.append(cast(str, current_node).find(gpx_field)) else: if current_node is not None: value = gpx_field.from_xml(current_node, version) setattr(result, gpx_field.name, value) elif gpx_field.attribute: value = gpx_field.from_xml(node, version) setattr(result, gpx_field.name, value) return result def gpx_check_slots_and_default_values(classs: Callable[[], Any]) -> None: """ Will fill the default values for this class. Instances will inherit those values so we don't need to fill default values for every instance. """ fields = classs.gpx_10_fields + classs.gpx_11_fields # type: ignore instance = classs() try: attributes = [x for x in dir(instance) if not x.startswith(('_', 'gpx_')) and not callable(getattr(instance, x))] except Exception as e: raise Exception(f'Error reading attributes for {classs.__name__}: {e}') attributes.sort() slots = list(classs.__slots__) slots.sort() if attributes != slots: raise Exception(f'Attributes for {classs.__name__} is\n{attributes} but should be\n{slots}') for field in fields: if not isinstance(field, str): value: Any = None if field.is_list: value = [] try: actual_value = getattr(instance, field.name) except: raise Exception(f'{classs.__name__} has no attribute {field.name}') if field.name != "latitude" and field.name != "longitude" and value != actual_value: raise Exception( f'Invalid default value {classs.__name__}.{field.name} ' f'is {actual_value} but should be {value}' ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1670747242.0 gpxpy-1.6.2/gpxpy/gpxxml.py0000644000076500000240000000412514345312152014454 0ustar00tkrstaffimport xml.dom.minidom as mod_minidom from typing import Any, AnyStr, Iterable def split_gpxs(xml: AnyStr) -> Iterable[str]: """ Split tracks in multiple xml files, without gpxpy. Each one with ont . """ dom = mod_minidom.parseString(xml) gpx_node: Any = _find_gpx_node(dom) gpx_track_nodes = [] if gpx_node: for child_node in gpx_node.childNodes: if child_node.nodeName == 'trk': gpx_track_nodes.append(child_node) gpx_node.removeChild(child_node) for gpx_track_node in gpx_track_nodes: gpx_node.appendChild(gpx_track_node) yield dom.toxml() gpx_node.removeChild(gpx_track_node) def join_gpxs(xmls: Iterable[AnyStr]) -> str: """ Join GPX files without parsing them with gpxpy. """ result = None wpt_elements = [] rte_elements = [] trk_elements = [] for xml in xmls: dom = mod_minidom.parseString(xml) if not result: result = dom gpx_node = _find_gpx_node(dom) if gpx_node: for child_node in gpx_node.childNodes: if child_node.nodeName == 'wpt': wpt_elements.append(child_node) gpx_node.removeChild(child_node) elif child_node.nodeName == 'rte': rte_elements.append(child_node) gpx_node.removeChild(child_node) elif child_node.nodeName == 'trk': trk_elements.append(child_node) gpx_node.removeChild(child_node) gpx_node = _find_gpx_node(result) if gpx_node: for wpt_element in wpt_elements: gpx_node.appendChild(wpt_element) for rte_element in rte_elements: gpx_node.appendChild(rte_element) for trk_element in trk_elements: gpx_node.appendChild(trk_element) return result.toxml() # type: ignore def _find_gpx_node(dom: Any) -> Any: for gpx_candidate_node in dom.childNodes: if gpx_candidate_node.nodeName == 'gpx': return gpx_candidate_node return None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278522.0 gpxpy-1.6.2/gpxpy/parser.py0000644000076500000240000001260714531671472014447 0ustar00tkrstaff# 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. import logging as mod_logging import re as mod_re from typing import cast, Union, AnyStr, IO, Optional try: # Load LXML or fallback to cET or ET import lxml.etree as mod_etree # type: ignore except ImportError: try: import xml.etree.cElementTree as mod_etree # type: ignore except ImportError: import xml.etree.ElementTree as mod_etree # type: ignore from . import gpx as mod_gpx from . import utils as mod_utils from . import gpxfield as mod_gpxfield log = mod_logging.getLogger(__name__) def library() -> str: """ Return the underlying ETree. Provided for convenient unittests. """ if "lxml" in str(mod_etree): return "LXML" return "STDLIB" class GPXParser: """ Parse the XML and provide new GPX instance. Methods: __init__: initialize new instance init: format XML parse: parse XML, build tree, build GPX Attributes: gpx: GPX instance of the most recently parsed XML xml: string containing the XML text """ def __init__(self, xml_or_file: Union[AnyStr, IO[str]]) -> None: """ Initialize new GPXParser instance. Arguments: xml_or_file: string or file object containing the gpx formatted xml """ self.xml = "" self.init(xml_or_file) self.gpx = mod_gpx.GPX() def init(self, xml_or_file: Union[AnyStr, IO[str]]) -> None: """ Store the XML and remove utf-8 Byte Order Mark if present. Args: xml_or_file: string or file object containing the gpx formatted xml """ text = xml_or_file.read() if hasattr(xml_or_file, 'read') else xml_or_file # type: ignore if isinstance(text, bytes): text = text.decode() self.xml = mod_utils.make_str(cast(str, text)) def parse(self, version: Optional[str]=None) -> mod_gpx.GPX: """ Parse the XML and return a GPX object. Args: version: str or None indicating the GPX Schema to use. Options are '1.0', '1.1' and None. When version is None the version is read from the file or falls back on 1.0. Returns: A GPX object loaded from the xml Raises: GPXXMLSyntaxException: XML file is invalid GPXException: XML is valid but GPX data contains errors """ # Build prefix map for reserialization and extension handlings for namespace in mod_re.findall(r'\sxmlns:?[^=]*="[^"]+"', self.xml): prefix, _, URI = namespace[6:].partition('=') prefix = prefix.lstrip(':') if prefix == '': prefix = 'defaultns' # alias default for easier handling else: if prefix.startswith("ns"): mod_etree.register_namespace("noglobal_" + prefix, URI.strip('"')) else: mod_etree.register_namespace(prefix, URI.strip('"')) self.gpx.nsmap[prefix] = URI.strip('"') schema_loc = mod_re.search(r'\sxsi:schemaLocation="[^"]+"', self.xml) if schema_loc: _, _, value = schema_loc.group(0).partition('=') self.gpx.schema_locations = value.strip('"').split() # Remove default namespace to simplify processing later self.xml = mod_re.sub(r"""\sxmlns=(['"])[^'"]+\1""", '', self.xml, count=1) # Build tree try: if library() == "LXML": # lxml does not like unicode strings when it's expecting # UTF-8. Also, XML comments result in a callable .tag(). # Strip them out to avoid handling them later. self.xml = cast(str, self.xml.encode('utf-8')) root = mod_etree.XML(self.xml, mod_etree.XMLParser(remove_comments=True)) else: root = mod_etree.XML(self.xml) except Exception as e: # The exception here can be a lxml or ElementTree exception. log.debug('Error in:\n%s\n-----------\n', self.xml, exc_info=True) # The library should work in the same way regardless of the # underlying XML parser that's why the exception thrown # here is GPXXMLSyntaxException (instead of simply throwing the # original ElementTree or lxml exception e). # # But, if the user needs the original exception (lxml or ElementTree) # it is available with GPXXMLSyntaxException.original_exception: raise mod_gpx.GPXXMLSyntaxException(f'Error parsing XML: {e}', e) if root is None: raise mod_gpx.GPXException('Document must have a `gpx` root node.') if version is None: version = root.get('version') mod_gpxfield.gpx_fields_from_xml(self.gpx, root, version) return self.gpx././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1670747242.0 gpxpy-1.6.2/gpxpy/py.typed0000644000076500000240000000000014345312152014246 0ustar00tkrstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698244666.0 gpxpy-1.6.2/gpxpy/utils.py0000644000076500000240000000477614516224072014314 0ustar00tkrstaff# 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. import sys as mod_sys import math as mod_math import xml.sax.saxutils as mod_saxutils import datetime as mod_datetime from typing import Any, AnyStr, List, Optional, cast def to_xml(tag: str, attributes: Any=None, content: Any=None, default: Any=None, escape: bool=False, prettyprint: bool=True, indent: str='') -> str: if not prettyprint: indent = '' attributes = attributes or {} result: List[str] = [f'\n{indent}<{tag}'] if content is None and default: content = default if attributes: for attribute in attributes.keys(): result.append(make_str(f' {attribute}="{attributes[attribute]}"')) if content is None: result.append('/>') else: if escape: result.append(make_str(f'>{mod_saxutils.escape(content)}')) else: result.append(make_str(f'>{content}')) return make_str(''.join(result)) def is_numeric(object: Any) -> bool: try: float(object) return True except TypeError: return False except ValueError: return False def to_number(s: str, default: float=0, nan_value: Optional[float]=None) -> float: try: result = float(s) if mod_math.isnan(result) and nan_value: return nan_value return result except TypeError: pass except ValueError: pass return default def total_seconds(timedelta: mod_datetime.timedelta) -> float: """ Some versions of python don't have the timedelta.total_seconds() method. """ if timedelta is None: return None return timedelta.total_seconds() def make_str(s: AnyStr) -> str: """ Convert a str or unicode or float object into a str type. """ if isinstance(s, float): result = str(s) if not 'e' in result: return result # scientific notation is illegal in GPX 1/1 return format(s, '.10f').rstrip('0').rstrip('.') return str(s) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701278708.0950582 gpxpy-1.6.2/gpxpy.egg-info/0000755000076500000240000000000014531671764014271 5ustar00tkrstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278708.0 gpxpy-1.6.2/gpxpy.egg-info/PKG-INFO0000644000076500000240000001334014531671764015367 0ustar00tkrstaffMetadata-Version: 2.1 Name: gpxpy Version: 1.6.2 Summary: GPX file parser and GPS track manipulation library Home-page: https://github.com/tkrajina/gpxpy Author: Tomo Krajina Author-email: tkrajina@gmail.com License: Apache License, Version 2.0 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Requires-Python: >=3.6 Description-Content-Type: text/markdown License-File: LICENSE.txt License-File: NOTICE.txt [![Build Status](https://travis-ci.org/tkrajina/gpxpy.svg?branch=master)](https://travis-ci.org/tkrajina/gpxpy) [![Coverage Status](https://coveralls.io/repos/github/tkrajina/gpxpy/badge.svg?branch=master)](https://coveralls.io/github/tkrajina/gpxpy?branch=master) # gpxpy -- GPX file parser This is a simple Python library for parsing and manipulating GPX files. GPX is an XML based format for GPS tracks. You can see it in action on [my online GPS track editor and organizer](http://www.trackprofiler.com). There is also a Golang port of gpxpy: [gpxgo](http://github.com/tkrajina/gpxgo). See also [srtm.py](https://github.com/tkrajina/srtm.py) if your track lacks elevation data. ## Usage ```python import gpxpy import gpxpy.gpx # Parsing an existing file: # ------------------------- gpx_file = open('test_files/cerknicko-jezero.gpx', 'r') gpx = gpxpy.parse(gpx_file) for track in gpx.tracks: for segment in track.segments: for point in segment.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevation}') for waypoint in gpx.waypoints: print(f'waypoint {waypoint.name} -> ({waypoint.latitude},{waypoint.longitude})') for route in gpx.routes: print('Route:') for point in route.points: print(f'Point at ({point.latitude},{point.longitude}) -> {point.elevtion}') # There are many more utility methods and functions: # You can manipulate/add/remove tracks, segments, points, waypoints and routes and # get the GPX XML file from the resulting object: print('GPX:', gpx.to_xml()) # Creating a new file: # -------------------- gpx = gpxpy.gpx.GPX() # Create first track in our GPX: gpx_track = gpxpy.gpx.GPXTrack() gpx.tracks.append(gpx_track) # Create first segment in our GPX track: gpx_segment = gpxpy.gpx.GPXTrackSegment() gpx_track.segments.append(gpx_segment) # Create points: gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1234, 5.1234, elevation=1234)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1235, 5.1235, elevation=1235)) gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1236, 5.1236, elevation=1236)) # You can add routes and waypoints, too... print('Created GPX:', gpx.to_xml()) ``` ## GPX version gpx.py can parse and generate GPX 1.0 and 1.1 files. The generated file will always be a valid XML document, but it may not be (strictly speaking) a valid GPX document. For example, if you set gpx.email to "my.email AT mail.com" the generated GPX tag won't confirm to the regex pattern. And the file won't be valid. Most applications will ignore such errors, but... Be aware of this! Be aware that the gpxpy object model *is not 100% equivalent* with the underlying GPX XML file schema. That's because the library object model works with both GPX 1.0 and 1.1. For example, GPX 1.0 specified a `speed` attribute for every track point, but that was removed in GPX 1.1. If you parse GPX 1.0 and serialize back with `gpx.to_xml()` everything will work fine. But if you have a GPX 1.1 object, changes in the `speed` attribute will be lost after `gpx.to_xml()`. If you want to force using 1.0, you can `gpx.to_xml(version="1.0")`. Another possibility is to use `extensions` to save the speed in GPX 1.1. ## GPX extensions gpx.py preserves GPX extensions. They are stored as [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree) DOM objects. Extensions are part of GPX 1.1, and will be ignored when serializing a GPX object in a GPX 1.0 file. ## XML parsing If lxml is available, then it will be used for XML parsing, otherwise minidom is used. Lxml is 2-3 times faster so, if you can choose -- use it. The GPX version is automatically determined when parsing by reading the version attribute in the gpx node. If this attribute is not present then the version is assumed to be 1.0. A specific version can be forced by setting the `version` parameter in the parse function. Possible values for the 'version' parameter are `1.0`, `1.1` and `None`. ## GPX max speed Gpxpy is a GPX parser and by using it you have access to all the data from the original GPX file. The additional methods to calculate stats have some additional heuristics to remove common GPS errors. For example, to calculate `max_speed` it removes the top `5%` of speeds and points with nonstandard distance (those are usually GPS errors). "Raw" max speed can be calculated with: moving_data = gpx.get_moving_data(raw=True) ## Pull requests Branches: * `master` contains the code of the latest release * `dev` branch is where code for the next release should go. Send your pull request against `dev`, not `master`! Before sending a pull request -- check that all tests are OK. Run all the static typing checks and unit tests with: $ make mypy-and-tests Run a single test with: $ python3 -m unittest test.GPXTests.test_haversine_and_nonhaversine Gpxpy runs only with python 3.6+. The code must have type hints and must pass all the mypy checks. ## GPX tools Additional command-line tools for GPX files can be downloaded here or installed with: ``` pip install gpx-cmd-tools ``` ## License GPX.py is licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278708.0 gpxpy-1.6.2/gpxpy.egg-info/SOURCES.txt0000644000076500000240000000263014531671764016156 0ustar00tkrstaffLICENSE.txt MANIFEST.in NOTICE.txt README.md gpxinfo setup.py test.py gpxpy/__init__.py gpxpy/geo.py gpxpy/gpx.py gpxpy/gpxfield.py gpxpy/gpxxml.py gpxpy/parser.py gpxpy/py.typed gpxpy/utils.py gpxpy.egg-info/PKG-INFO gpxpy.egg-info/SOURCES.txt gpxpy.egg-info/dependency_links.txt gpxpy.egg-info/top_level.txt test_files/Mojstrovka.gpx test_files/around-visnjan-with-car.gpx test_files/cerknicko-jezero-no-creator.gpx test_files/cerknicko-jezero-with-elevations-zero.gpx test_files/cerknicko-jezero-without-elevations.gpx test_files/cerknicko-jezero.gpx test_files/cerknicko-without-times.gpx test_files/custom_schema_locations.gpx test_files/default_schema_locations.gpx test_files/first_and_last_elevation.gpx test_files/gpx-with-node-with-comments.gpx test_files/gpx1.0_with_all_fields.gpx test_files/gpx1.1_with_all_fields.gpx test_files/gpx1.1_with_extensions.gpx test_files/gpx1.1_with_extensions_without_namespaces.gpx test_files/gpx_with_garmin_extension.gpx test_files/korita-zbevnica.gpx test_files/route.gpx test_files/track-with-empty-segment.gpx test_files/track-with-extremes.gpx test_files/track-with-less-sec-time.gpx test_files/track-with-small-floats.gpx test_files/track_with_dilution_errors.gpx test_files/track_with_speed.gpx test_files/unicode.gpx test_files/unicode2.gpx test_files/unicode_with_bom.gpx test_files/unicode_with_bom_noencoding.gpx test_files/validation_gpx10.gpx test_files/validation_gpx11.gpx././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278708.0 gpxpy-1.6.2/gpxpy.egg-info/dependency_links.txt0000644000076500000240000000000114531671764020337 0ustar00tkrstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278708.0 gpxpy-1.6.2/gpxpy.egg-info/top_level.txt0000644000076500000240000000000614531671764017017 0ustar00tkrstaffgpxpy ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1701278708.0956323 gpxpy-1.6.2/setup.cfg0000644000076500000240000000004614531671764013251 0ustar00tkrstaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1670747242.0 gpxpy-1.6.2/setup.py0000755000076500000240000000275414345312152013137 0ustar00tkrstaff#!/usr/bin/python # 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. import gpxpy import sys from setuptools import setup # type: ignore if sys.version_info < (3, 6): sys.exit('Sorry, Python < 3.6 is not supported') with open('README.md') as f: long_description = f.read() setup( name='gpxpy', version=gpxpy.__version__, description='GPX file parser and GPS track manipulation library', long_description=long_description, long_description_content_type="text/markdown", license='Apache License, Version 2.0', author='Tomo Krajina', author_email='tkrajina@gmail.com', url='https://github.com/tkrajina/gpxpy', package_data={"gpxpy": ["py.typed"]}, packages=['gpxpy', ], python_requires=">=3.6", classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], scripts=['gpxinfo'], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1701278641.0 gpxpy-1.6.2/test.py0000644000076500000240000051044514531671661012766 0ustar00tkrstaff# 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_xml(self) -> None: try: mod_gpxpy.parse('\'' 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('' 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(""" 100 """) 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('' 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: self.assertAlmostEqual(points[0].course_between(points[1], loxodromic=True), course_01, 6) # type: ignore self.assertAlmostEqual(points[1].course_between(points[2], loxodromic=True), course_12, 6) # type: ignore self.assertAlmostEqual(points[0].course_between(points[2], loxodromic=True), course_02, 6) # type: ignore # Verifying the orthodromic results course_orthodromic_01 = points[0].course_between(points[1], loxodromic=False) course_orthodromic_12 = points[1].course_between(points[2], loxodromic=False) course_orthodromic_02 = points[0].course_between(points[2], loxodromic=False) self.assertAlmostEqual(course_orthodromic_01, 188.409, 3) # type: ignore self.assertAlmostEqual(course_orthodromic_12, 355.6886, 3) # type: ignore self.assertAlmostEqual(course_orthodromic_02, 11.2136, 3) # type: ignore # Short distance tests: gpx_short = self.parse('track_with_speed.gpx') points_short = gpx_short.tracks[0].segments[0].points course_short_01 = points_short[0].course_between(points_short[1]) course_short_12 = points_short[1].course_between(points_short[2]) course_short_02 = points_short[0].course_between(points_short[2]) # When the points are not too distant (less than about 100-150km), # the orthodromic and loxodromic bearings should be almost identical: self.assertAlmostEqual(points_short[0].course_between(points_short[1], loxodromic=False), course_short_01, 3) # type: ignore self.assertAlmostEqual(points_short[1].course_between(points_short[2], loxodromic=False), course_short_12, 3) # type: ignore self.assertAlmostEqual(points_short[0].course_between(points_short[2], loxodromic=False), course_short_02, 3) # type: ignore def test_get_course(self) -> None: pts = [[-73, -150], [43.5798, 35.71265], [85, 0.12345]] # same long distance checks as in test_get_course_between self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[1][0], pts[1][1]), 312.089, 3) # type: ignore self.assertAlmostEqual(mod_geo.get_course(pts[1][0], pts[1][1], pts[2][0], pts[2][1]), 344.790, 3) # type: ignore self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[2][0], pts[2][1]), 27.5055, 3) # type: ignore self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[1][0], pts[1][1], # type: ignore loxodromic=True), 312.089, 3) self.assertAlmostEqual(mod_geo.get_course(pts[1][0], pts[1][1], pts[2][0], pts[2][1], # type: ignore loxodromic=True), 344.790, 3) self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[2][0], pts[2][1], # type: ignore loxodromic=True), 27.5055, 3) self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[1][0], pts[1][1], # type: ignore loxodromic=False), 188.409, 3) self.assertAlmostEqual(mod_geo.get_course(pts[1][0], pts[1][1], pts[2][0], pts[2][1], # type: ignore loxodromic=False), 355.6886, 3) self.assertAlmostEqual(mod_geo.get_course(pts[0][0], pts[0][1], pts[2][0], pts[2][1], # type: ignore loxodromic=False), 11.2136, 3) def test_name_comment_and_symbol(self) -> None: gpx = mod_gpx.GPX() track = mod_gpx.GPXTrack() gpx.tracks.append(track) segment = mod_gpx.GPXTrackSegment() track.segments.append(segment) point = mod_gpx.GPXTrackPoint(12, 13, name='aaa', comment='ccc', symbol='sss') segment.points.append(point) xml = gpx.to_xml() self.assertTrue('aaa' in xml) gpx2 = self.reparse(gpx) self.assertEqual(gpx2.tracks[0].segments[0].points[0].name, 'aaa') self.assertEqual(gpx2.tracks[0].segments[0].points[0].comment, 'ccc') self.assertEqual(gpx2.tracks[0].segments[0].points[0].symbol, 'sss') def test_get_bounds_and_refresh_bounds(self) -> None: gpx = mod_gpx.GPX() latitudes = [] longitudes = [] for i in range(2): track = mod_gpx.GPXTrack() for i in range(2): segment = mod_gpx.GPXTrackSegment() for i in range(10): latitude = 50. * (mod_random.random() - 0.5) longitude = 50. * (mod_random.random() - 0.5) point = mod_gpx.GPXTrackPoint(latitude=latitude, longitude=longitude) segment.points.append(point) latitudes.append(latitude) longitudes.append(longitude) track.segments.append(segment) gpx.tracks.append(track) bounds = gpx.get_bounds() print(latitudes) print(longitudes) self.assertEqual(bounds.min_latitude, min(latitudes)) # type: ignore self.assertEqual(bounds.max_latitude, max(latitudes)) # type: ignore self.assertEqual(bounds.min_longitude, min(longitudes)) # type: ignore self.assertEqual(bounds.max_longitude, max(longitudes)) # type: ignore gpx.refresh_bounds() self.assertEqual(gpx.bounds.min_latitude, min(latitudes)) # type: ignore self.assertEqual(gpx.bounds.max_latitude, max(latitudes)) # type: ignore self.assertEqual(gpx.bounds.min_longitude, min(longitudes)) # type: ignore self.assertEqual(gpx.bounds.max_longitude, max(longitudes)) # type: ignore def test_named_tuples_values_time_bounds(self) -> None: gpx = self.parse('korita-zbevnica.gpx') time_bounds = gpx.get_time_bounds() start_time, end_time = gpx.get_time_bounds() self.assertEqual(start_time, time_bounds.start_time) self.assertEqual(end_time, time_bounds.end_time) def test_named_tuples_values_moving_data(self) -> None: gpx = self.parse('korita-zbevnica.gpx') moving_data = gpx.get_moving_data() moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data() self.assertEqual(moving_time, moving_data.moving_time) self.assertEqual(stopped_time, moving_data.stopped_time) self.assertEqual(moving_distance, moving_data.moving_distance) self.assertEqual(stopped_distance, moving_data.stopped_distance) self.assertEqual(max_speed, moving_data.max_speed) def test_named_tuples_values_uphill_downhill(self) -> None: gpx = self.parse('korita-zbevnica.gpx') uphill_downhill = gpx.get_uphill_downhill() uphill, downhill = gpx.get_uphill_downhill() self.assertEqual(uphill, uphill_downhill.uphill) self.assertEqual(downhill, uphill_downhill.downhill) def test_named_tuples_values_elevation_extremes(self) -> None: gpx = self.parse('korita-zbevnica.gpx') elevation_extremes = gpx.get_elevation_extremes() minimum, maximum = gpx.get_elevation_extremes() self.assertEqual(minimum, elevation_extremes.minimum) self.assertEqual(maximum, elevation_extremes.maximum) def test_named_tuples_values_nearest_location_data(self) -> None: gpx = self.parse('korita-zbevnica.gpx') location = gpx.tracks[1].segments[0].points[2] location.latitude *= 1.00001 location.longitude *= 0.99999 nearest_location_data = gpx.get_nearest_location(location) found_location, track_no, segment_no, point_no = gpx.get_nearest_location(location) # type: ignore self.assertEqual(found_location, nearest_location_data.location) # type: ignore self.assertEqual(track_no, nearest_location_data.track_no) # type: ignore self.assertEqual(segment_no, nearest_location_data.segment_no) # type: ignore self.assertEqual(point_no, nearest_location_data.point_no) # type: ignore def test_named_tuples_values_point_data(self) -> None: gpx = self.parse('korita-zbevnica.gpx') points_datas = gpx.get_points_data() for point_data in points_datas: point, distance_from_start, track_no, segment_no, point_no = point_data self.assertEqual(point, point_data.point) self.assertEqual(distance_from_start, point_data.distance_from_start) self.assertEqual(track_no, point_data.track_no) self.assertEqual(segment_no, point_data.segment_no) self.assertEqual(point_no, point_data.point_no) def test_track_points_data(self) -> None: gpx = self.parse('korita-zbevnica.gpx') points_data_2d = gpx.get_points_data(distance_2d=True) point, distance_from_start, track_no, segment_no, point_no = points_data_2d[-1] self.assertEqual(track_no, len(gpx.tracks) - 1) self.assertEqual(segment_no, len(gpx.tracks[-1].segments) - 1) self.assertEqual(point_no, len(gpx.tracks[-1].segments[-1].points) - 1) self.assertTrue(abs(distance_from_start - gpx.length_2d()) < 0.0001) points_data_3d = gpx.get_points_data(distance_2d=False) point, distance_from_start, track_no, segment_no, point_no = points_data_3d[-1] self.assertEqual(track_no, len(gpx.tracks) - 1) self.assertEqual(segment_no, len(gpx.tracks[-1].segments) - 1) self.assertEqual(point_no, len(gpx.tracks[-1].segments[-1].points) - 1) self.assertTrue(abs(distance_from_start - gpx.length_3d()) < 0.0001) self.assertTrue(gpx.length_2d() != gpx.length_3d()) def test_walk_route_points(self) -> None: with open('test_files/route.gpx') as f: gpx = mod_gpxpy.parse(f) for point in gpx.routes[0].walk(only_points=True): self.assertTrue(point) for point, point_no in gpx.routes[0].walk(): self.assertTrue(point) self.assertEqual(point_no, len(gpx.routes[0].points) - 1) def test_walk_gpx_points(self) -> None: gpx = self.parse('korita-zbevnica.gpx') for point in gpx.walk(): self.assertTrue(point) for point, track_no, segment_no, point_no in gpx.walk(): self.assertTrue(point) self.assertEqual(track_no, len(gpx.tracks) - 1) self.assertEqual(segment_no, len(gpx.tracks[-1].segments) - 1) self.assertEqual(point_no, len(gpx.tracks[-1].segments[-1].points) - 1) def test_walk_gpx_points2(self) -> None: gpx = self.parse('korita-zbevnica.gpx') track = gpx.tracks[1] for tmp_point in track.walk(): self.assertTrue(tmp_point) for point, segment_no, point_no in track.walk(): self.assertTrue(point) self.assertEqual(segment_no, len(track.segments) - 1) self.assertEqual(point_no, len(track.segments[-1].points) - 1) def test_walk_segment_points(self) -> None: gpx = self.parse('korita-zbevnica.gpx') track = gpx.tracks[1] segment = track.segments[0] assert len(segment.points) > 0 for point in segment.walk(): self.assertTrue(point) """ for point, segment_no, point_no in track.walk(): self.assertTrue(point) self.assertEqual(segment_no, len(track.segments) - 1) self.assertEqual(point_no, len(track.segments[-1].points) - 1) """ def test_angle_0(self) -> None: loc1 = mod_geo.Location(0, 0) loc2 = mod_geo.Location(0, 1) loc1.elevation = 100 loc2.elevation = 100 angle_radians = mod_geo.elevation_angle(loc1, loc2, radians=True) angle_degrees = mod_geo.elevation_angle(loc1, loc2, radians=False) self.assertEqual(angle_radians, 0) self.assertEqual(angle_degrees, 0) def test_angle(self) -> None: loc1 = mod_geo.Location(0, 0) loc2 = mod_geo.Location(0, 1) loc1.elevation = 100 loc2.elevation = loc1.elevation + loc1.distance_2d(loc2) # type: ignore angle_radians = mod_geo.elevation_angle(loc1, loc2, radians=True) angle_degrees = mod_geo.elevation_angle(loc1, loc2, radians=False) self.assertEqual(angle_radians, mod_math.pi / 4) self.assertEqual(angle_degrees, 45) def test_angle_2(self) -> None: loc1 = mod_geo.Location(45, 45) loc2 = mod_geo.Location(46, 45) loc1.elevation = 100 loc2.elevation = loc1.elevation + 0.5 * loc1.distance_2d(loc2) # type: ignore angle_radians = mod_geo.elevation_angle(loc1, loc2, radians=True) angle_degrees = mod_geo.elevation_angle(loc1, loc2, radians=False) self.assertTrue(angle_radians < mod_math.pi / 4) # type: ignore self.assertTrue(angle_degrees < 45) # type: ignore def test_angle_3(self) -> None: loc1 = mod_geo.Location(45, 45) loc2 = mod_geo.Location(46, 45) loc1.elevation = 100 loc2.elevation = loc1.elevation + 1.5 * loc1.distance_2d(loc2) # type: ignore angle_radians = mod_geo.elevation_angle(loc1, loc2, radians=True) angle_degrees = mod_geo.elevation_angle(loc1, loc2, radians=False) self.assertTrue(angle_radians > mod_math.pi / 4) # type: ignore self.assertTrue(angle_degrees > 45) # type: ignore def test_angle_4(self) -> None: loc1 = mod_geo.Location(45, 45) loc2 = mod_geo.Location(46, 45) loc1.elevation = 100 loc2.elevation = loc1.elevation - loc1.distance_2d(loc2) # type: ignore angle_radians = mod_geo.elevation_angle(loc1, loc2, radians=True) angle_degrees = mod_geo.elevation_angle(loc1, loc2, radians=False) self.assertEqual(angle_radians, - mod_math.pi / 4) self.assertEqual(angle_degrees, - 45) def test_angle_loc(self) -> None: loc1 = mod_geo.Location(45, 45) loc2 = mod_geo.Location(46, 45) self.assertEqual(loc1.elevation_angle(loc2), mod_geo.elevation_angle(loc1, loc2)) self.assertEqual(loc1.elevation_angle(loc2, radians=True), mod_geo.elevation_angle(loc1, loc2, radians=True)) self.assertEqual(loc1.elevation_angle(loc2, radians=False), mod_geo.elevation_angle(loc1, loc2, radians=False)) def test_ignore_maximums_for_max_speed(self) -> None: gpx = mod_gpx.GPX() track = mod_gpx.GPXTrack() gpx.tracks.append(track) tmp_time = mod_datetime.datetime.now() tmp_longitude: float = 0 segment_1 = mod_gpx.GPXTrackSegment() for i in range(4): segment_1.points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=tmp_longitude, time=tmp_time)) tmp_longitude += 0.01 tmp_time += mod_datetime.timedelta(hours=1) track.segments.append(segment_1) moving_time, stopped_time, moving_distance, stopped_distance, max_speed_with_too_small_segment = gpx.get_moving_data() # Too few points: mod_logging.debug('max_speed = %s', max_speed_with_too_small_segment) self.assertTrue(max_speed_with_too_small_segment > 0) tmp_longitude = 0. segment_2 = mod_gpx.GPXTrackSegment() for i in range(55): segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=tmp_longitude, time=tmp_time)) tmp_longitude += 0.01 tmp_time += mod_datetime.timedelta(hours=1) track.segments.append(segment_2) moving_time, stopped_time, moving_distance, stopped_distance, max_speed_with_equal_speeds = gpx.get_moving_data() mod_logging.debug('max_speed = %s', max_speed_with_equal_speeds) self.assertTrue(max_speed_with_equal_speeds > 0) # When we add too few extremes, they should be ignored: for i in range(10): segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=tmp_longitude, time=tmp_time)) tmp_longitude += 0.7 tmp_time += mod_datetime.timedelta(hours=1) moving_time, stopped_time, moving_distance, stopped_distance, max_speed_with_extreemes = gpx.get_moving_data() self.assertTrue(abs(max_speed_with_extreemes - max_speed_with_equal_speeds) < 0.001) # But if there are many extremes (they are no more extremes): for i in range(100): # Sometimes add on start, sometimes on end: if i % 2 == 0: segment_2.points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=tmp_longitude, time=tmp_time)) else: segment_2.points.insert(0, mod_gpx.GPXTrackPoint(latitude=0, longitude=tmp_longitude, time=tmp_time)) tmp_longitude += 0.5 tmp_time += mod_datetime.timedelta(hours=1) moving_time, stopped_time, moving_distance, stopped_distance, max_speed_with_more_extreemes = gpx.get_moving_data() mod_logging.debug('max_speed_with_more_extreemes = %s', max_speed_with_more_extreemes) mod_logging.debug('max_speed_with_extreemes = %s', max_speed_with_extreemes) self.assertTrue(max_speed_with_more_extreemes - max_speed_with_extreemes > 10) def test_track_with_elevation_zero(self) -> None: with open('test_files/cerknicko-jezero-with-elevations-zero.gpx') as f: gpx = mod_gpxpy.parse(f) minimum, maximum = gpx.get_elevation_extremes() self.assertEqual(minimum, 0) self.assertEqual(maximum, 0) uphill, downhill = gpx.get_uphill_downhill() self.assertEqual(uphill, 0) self.assertEqual(downhill, 0) def test_track_without_elevation(self) -> None: with open('test_files/cerknicko-jezero-without-elevations.gpx') as f: gpx = mod_gpxpy.parse(f) minimum, maximum = gpx.get_elevation_extremes() self.assertEqual(minimum, None) self.assertEqual(maximum, None) uphill, downhill = gpx.get_uphill_downhill() self.assertEqual(uphill, 0) self.assertEqual(downhill, 0) def test_has_elevation_false(self) -> None: with open('test_files/cerknicko-jezero-without-elevations.gpx') as f: gpx = mod_gpxpy.parse(f) self.assertFalse(gpx.has_elevations()) def test_has_elevation_true(self) -> None: with open('test_files/cerknicko-jezero.gpx') as f: gpx = mod_gpxpy.parse(f) self.assertFalse(gpx.has_elevations()) def test_track_with_some_points_are_without_elevations(self) -> None: gpx = mod_gpx.GPX() track = mod_gpx.GPXTrack() gpx.tracks.append(track) tmp_latlong = 0 segment_1 = mod_gpx.GPXTrackSegment() for i in range(4): point = mod_gpx.GPXTrackPoint(latitude=tmp_latlong, longitude=tmp_latlong) segment_1.points.append(point) if i % 3 == 0: point.elevation = None else: point.elevation = 100 / (i + 1) track.segments.append(segment_1) minimum, maximum = gpx.get_elevation_extremes() self.assertTrue(minimum is not None) self.assertTrue(maximum is not None) uphill, downhill = gpx.get_uphill_downhill() self.assertTrue(uphill is not None) self.assertTrue(downhill is not None) def test_track_with_empty_segment(self) -> None: with open('test_files/track-with-empty-segment.gpx') as f: gpx = mod_gpxpy.parse(f) self.assertIsNotNone(gpx.tracks[0].get_bounds().min_latitude) # type: ignore self.assertIsNotNone(gpx.tracks[0].get_bounds().min_longitude) # type: ignore def test_add_missing_data_no_intervals(self) -> None: # Test only that the add_missing_function is called with the right data 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=10)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=14, elevation=100)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=15, elevation=20)) # Shouldn't be called because all points have elevation def _add_missing_function(interval: List[mod_geo.Location], start_point: mod_geo.Location, end_point: mod_geo.Location, ratios: List[float]) -> None: raise Exception() gpx.add_missing_data(get_data_function=lambda point: point.elevation, add_missing_function=_add_missing_function) # type: ignore def test_add_missing_data_one_interval(self) -> None: # Test only that the add_missing_function is called with the right data 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=10)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=14)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=15, elevation=20)) # Shouldn't be called because all points have elevation def _add_missing_function(interval: List[mod_geo.Location], start_point: mod_geo.Location, end_point: mod_geo.Location, ratios: List[float]) -> None: assert start_point assert start_point.latitude == 12 and start_point.longitude == 13 assert end_point assert end_point.latitude == 12 and end_point.longitude == 15 assert len(interval) == 1 assert interval[0].latitude == 12 and interval[0].longitude == 14 assert ratios interval[0].elevation = 314 gpx.add_missing_data(get_data_function=lambda point: point.elevation, add_missing_function=_add_missing_function) # type: ignore self.assertEqual(314, gpx.tracks[0].segments[0].points[1].elevation) def test_add_missing_data_one_interval_and_empty_points_on_start_and_end(self) -> None: # Test only that the add_missing_function is called with the right data 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)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13, elevation=10)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=14)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=15, elevation=20)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13)) # Shouldn't be called because all points have elevation def _add_missing_function(interval: List[mod_geo.Location], start_point: mod_geo.Location, end_point: mod_geo.Location, ratios: List[float]) -> None: assert start_point assert start_point.latitude == 12 and start_point.longitude == 13 assert end_point assert end_point.latitude == 12 and end_point.longitude == 15 assert len(interval) == 1 assert interval[0].latitude == 12 and interval[0].longitude == 14 assert ratios interval[0].elevation = 314 gpx.add_missing_data(get_data_function=lambda point: point.elevation, add_missing_function=_add_missing_function) # type: ignore # Points at start and end should not have elevation 314 because have # no two bounding points with elevations: self.assertEqual(None, gpx.tracks[0].segments[0].points[0].elevation) self.assertEqual(None, gpx.tracks[0].segments[0].points[-1].elevation) self.assertEqual(314, gpx.tracks[0].segments[0].points[2].elevation) def test_add_missing_speeds(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=0, longitude=0, time=mod_datetime.datetime(2013, 1, 2, 12, 0), speed=0)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0.00899, # 1 km/h over 1 km time=mod_datetime.datetime(2013, 1, 2, 13, 0))) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0.02697, # 2 km/h over 2 km time=mod_datetime.datetime(2013, 1, 2, 14, 0))) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0.03596, # 3 km/h over 1 km time=mod_datetime.datetime(2013, 1, 2, 14, 20))) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0.06293, # 9 km/h over 3 km time=mod_datetime.datetime(2013, 1, 2, 14, 40), speed=0)) gpx.add_missing_speeds() self.assertTrue(abs(3000./(2*3600) - gpx.tracks[0].segments[0].points[1].speed) < 0.01) # type: ignore self.assertTrue(abs(3000./(80*60) - gpx.tracks[0].segments[0].points[2].speed) < 0.01) # type: ignore self.assertTrue(abs(4000./(40*60) - gpx.tracks[0].segments[0].points[3].speed) < 0.01) # type: ignore def test_add_missing_elevations(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=13, longitude=12, elevation=10)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.25, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.5, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.9, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=14, longitude=12, elevation=20)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=15, longitude=12)) gpx.add_missing_elevations() self.assertTrue(abs(12.5 - gpx.tracks[0].segments[0].points[1].elevation) < 0.01) # type: ignore self.assertTrue(abs(15 - gpx.tracks[0].segments[0].points[2].elevation) < 0.01) # type: ignore self.assertTrue(abs(19 - gpx.tracks[0].segments[0].points[3].elevation) < 0.01) # type: ignore def test_add_missing_elevations_without_ele(self) -> None: xml = """ 0.0 """ gpx = mod_gpxpy.parse(xml) gpx.add_missing_elevations() self.assertTrue(gpx.tracks[0].segments[0].points[0].elevation == None) self.assertTrue(gpx.tracks[0].segments[0].points[1].elevation == None) self.assertTrue(gpx.tracks[0].segments[0].points[2].elevation == 0.0) def test_add_missing_times(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=13, longitude=12, time=mod_datetime.datetime(2013, 1, 2, 12, 0))) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.25, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.5, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.75, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=14, longitude=12, time=mod_datetime.datetime(2013, 1, 2, 13, 0))) gpx.add_missing_times() time_1 = gpx.tracks[0].segments[0].points[1].time time_2 = gpx.tracks[0].segments[0].points[2].time time_3 = gpx.tracks[0].segments[0].points[3].time self.assertEqual(2013, time_1.year) # type: ignore self.assertEqual(1, time_1.month) # type: ignore self.assertEqual(2, time_1.day) # type: ignore self.assertEqual(12, time_1.hour) # type: ignore self.assertEqual(15, time_1.minute) # type: ignore self.assertEqual(2013, time_2.year) # type: ignore self.assertEqual(1, time_2.month) # type: ignore self.assertEqual(2, time_2.day) # type: ignore self.assertEqual(12, time_2.hour) # type: ignore self.assertEqual(30, time_2.minute) # type: ignore self.assertEqual(2013, time_3.year) # type: ignore self.assertEqual(1, time_3.month) # type: ignore self.assertEqual(2, time_3.day) # type: ignore self.assertEqual(12, time_3.hour) # type: ignore self.assertEqual(45, time_3.minute) # type: ignore def test_add_missing_times_2(self) -> None: xml = '' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '18\n' xml += '\n' gpx = mod_gpxpy.parse(xml) gpx.add_missing_times() previous_time = None for point in gpx.walk(only_points=True): if point.time: if previous_time: print('point.time=', point.time, 'previous_time=', previous_time) self.assertTrue(point.time > previous_time) previous_time = point.time def test_distance_from_line(self) -> None: d = mod_geo.distance_from_line(mod_geo.Location(1, 1), mod_geo.Location(0, -1), mod_geo.Location(0, 1)) self.assertTrue(abs(d - mod_geo.ONE_DEGREE) < 100) # type: ignore def test_simplify(self) -> None: for gpx_file in mod_os.listdir('test_files'): print('Parsing:', gpx_file) with open(f'test_files/{gpx_file}', encoding='utf-8')as f: gpx = mod_gpxpy.parse(f) length_2d_original = gpx.length_2d() with open(f'test_files/{gpx_file}', encoding='utf-8') as f: gpx = mod_gpxpy.parse(f) gpx.simplify(max_distance=50) length_2d_after_distance_50 = gpx.length_2d() with open(f'test_files/{gpx_file}', encoding='utf-8') as f: gpx = mod_gpxpy.parse(f) gpx.simplify(max_distance=10) length_2d_after_distance_10 = gpx.length_2d() print(length_2d_original, length_2d_after_distance_10, length_2d_after_distance_50) # When simplifying the resulting distance should always be less than the original: self.assertTrue(length_2d_original >= length_2d_after_distance_10) self.assertTrue(length_2d_original >= length_2d_after_distance_50) # Simplify with bigger max_distance and => bigger error from original self.assertTrue(length_2d_after_distance_10 >= length_2d_after_distance_50) # The resulting distance usually shouldn't be too different from # the original (here check for 80% and 70%) self.assertTrue(length_2d_after_distance_10 >= length_2d_original * .6) self.assertTrue(length_2d_after_distance_50 >= length_2d_original * .5) def test_simplify_circular_gpx(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=13, longitude=12)) gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=13.25, longitude=12)) # Then the first point again: gpx.tracks[0].segments[0].points.append(gpx.tracks[0].segments[0].points[0]) gpx.simplify() def test_nan_elevation(self) -> None: xml = ' nan nan nan' gpx = mod_gpxpy.parse(xml) self.assertTrue(mod_math.isnan(gpx.tracks[0].segments[0].points[0].elevation)) # type: ignore self.assertTrue(mod_math.isnan(gpx.routes[0].points[0].elevation)) # type: ignore self.assertTrue(mod_math.isnan(gpx.waypoints[0].elevation)) # type: ignore def test_uphill_downhill_with_no_elevations(self) -> None: g = mod_gpx.GPX() g.tracks.append(mod_gpx.GPXTrack()) g.tracks[0].segments.append(mod_gpx.GPXTrackSegment()) g.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0, elevation=None)) g.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0, elevation=10)) g.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=0, longitude=0, elevation=20)) up, down = g.get_uphill_downhill() self.assertEqual(10, up) self.assertEqual(0, down) def test_time_difference(self) -> None: point_1 = mod_gpx.GPXTrackPoint(latitude=13, longitude=12, time=mod_datetime.datetime(2013, 1, 2, 12, 31)) point_2 = mod_gpx.GPXTrackPoint(latitude=13, longitude=12, time=mod_datetime.datetime(2013, 1, 3, 12, 32)) seconds = point_1.time_difference(point_2) self.assertEqual(seconds, 60 * 60 * 24 + 60) def test_parse_time(self) -> None: timestamps = [ '2001-10-26T21:32:52', #'2001-10-26T21:32:52+0200', '2001-10-26T19:32:52Z', #'2001-10-26T19:32:52+00:00', #'-2001-10-26T21:32:52', '2001-10-26T21:32:52.12679', '2001-10-26T21:32:52', #'2001-10-26T21:32:52+02:00', '2001-10-26T19:32:52Z', #'2001-10-26T19:32:52+00:00', #'-2001-10-26T21:32:52', '2001-10-26T21:32:52.12679', ] timestamps_without_tz = [x.replace('T', ' ').replace('Z', '') for x in timestamps] for t in timestamps_without_tz: timestamps.append(t) for timestamp in timestamps: print(f'Parsing: {timestamp}') self.assertTrue(mod_gpxfield.parse_time(timestamp) is not None) def test_dst_in_SimpleTZ(self) -> None: # No DST in UTC times. timestamps = ['2001-10-26T19:32:52Z', '2001-10-26T19:32:52+0000', '2001-10-26T19:32:52+00:00'] for timestamp in timestamps: daylight_saving_time = mod_gpxfield.parse_time(timestamp).dst() # type: ignore print(f'Testing: {timestamp}, dst = {daylight_saving_time}') self.assertTrue(daylight_saving_time in {None, mod_datetime.timedelta(0)}) def test_format_time(self) -> None: tz1 = mod_datetime.timezone(mod_datetime.timedelta(hours=2), ) tz2 = mod_datetime.timezone.utc # pase_time() doesn't work correctly for tz-unaware datetimes. times1 = [mod_datetime.datetime(*t) for t in [#(2001, 10, 26, 21, 32, 52), (2001, 10, 26, 21, 32, 52, 0, tz1), (2001, 10, 26, 19, 32, 52, 0, tz2), #(2001, 10, 26, 21, 32, 52, 126790), (2001, 10, 26, 21, 32, 52, 126790, tz1), (2001, 10, 26, 19, 32, 52, 126790, tz2)]] times2 = [] for t in times1: str_t = mod_gpxfield.format_time(t) print(str_t) t2 = mod_gpxfield.parse_time(str_t) print(t2) times2.append(t2) self.assertEqual(times1, times2) def test_get_location_at(self) -> None: gpx = mod_gpx.GPX() 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=mod_datetime.datetime(2013, 1, 2, 12, 30, 0)) p1 = mod_gpx.GPXTrackPoint(latitude=13.1, longitude=13.1, time=mod_datetime.datetime(2013, 1, 2, 12, 31, 0)) gpx.tracks[0].segments[0].points.append(p0) gpx.tracks[0].segments[0].points.append(p1) self.assertEqual(gpx.tracks[0].get_location_at(mod_datetime.datetime(2013, 1, 2, 12, 29, 30)), []) self.assertEqual(gpx.tracks[0].get_location_at(mod_datetime.datetime(2013, 1, 2, 12, 30, 0))[0], p0) self.assertEqual(gpx.tracks[0].get_location_at(mod_datetime.datetime(2013, 1, 2, 12, 30, 30))[0], p1) self.assertEqual(gpx.tracks[0].get_location_at(mod_datetime.datetime(2013, 1, 2, 12, 31, 0))[0], p1) self.assertEqual(gpx.tracks[0].get_location_at(mod_datetime.datetime(2013, 1, 2, 12, 31, 30)), []) def test_adjust_time_tracks_only(self) -> None: gpx = mod_gpx.GPX() t0 = mod_datetime.datetime(2013, 1, 2, 12, 30, 0) t1 = mod_datetime.datetime(2013, 1, 2, 12, 31, 0) t0_adjusted = t0 + mod_datetime.timedelta(seconds=1) t1_adjusted = t1 + mod_datetime.timedelta(seconds=1) gpx.tracks.append(mod_gpx.GPXTrack()) gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment()) p0 = mod_gpx.GPXTrackPoint(latitude=13.0, longitude=13.0) p1 = mod_gpx.GPXTrackPoint(latitude=13.1, longitude=13.1) gpx.tracks[0].segments[0].points.append(p0) gpx.tracks[0].segments[0].points.append(p1) 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[1].points.append(p0) gpx.tracks[0].segments[1].points.append(p1) gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.0, longitude=13.0)) gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.1, longitude=13.1, time=t0)) d1 = mod_datetime.timedelta(-1, -1) d2 = mod_datetime.timedelta(1, 2) # move back and forward to add a total of 1 second gpx.adjust_time(d1) gpx.adjust_time(d2) self.assertEqual(gpx.tracks[0].segments[0].points[0].time, None) self.assertEqual(gpx.tracks[0].segments[0].points[1].time, None) self.assertEqual(gpx.tracks[0].segments[1].points[0].time, t0_adjusted) self.assertEqual(gpx.tracks[0].segments[1].points[1].time, t1_adjusted) self.assertEqual(gpx.waypoints[0].time, None) self.assertEqual(gpx.waypoints[1].time, t0) def test_adjust_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) t0_adjusted = t0 + mod_datetime.timedelta(seconds=1) t1_adjusted = t1 + mod_datetime.timedelta(seconds=1) gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.0, longitude=13.0)) gpx.waypoints.append(mod_gpx.GPXWaypoint(latitude=13.1, longitude=13.1, time=t0)) gpx.routes.append(mod_gpx.GPXRoute()) p0 = mod_gpx.GPXRoutePoint(latitude=13.0, longitude=13.0) p1 = mod_gpx.GPXRoutePoint(latitude=13.1, longitude=13.1) gpx.routes[0].points.append(p0) gpx.routes[0].points.append(p1) gpx.routes.append(mod_gpx.GPXRoute()) p0 = mod_gpx.GPXRoutePoint(latitude=13.0, longitude=13.0, time=t0) p1 = mod_gpx.GPXRoutePoint(latitude=13.1, longitude=13.1, time=t1) gpx.routes[1].points.append(p0) gpx.routes[1].points.append(p1) d1 = mod_datetime.timedelta(-1, -1) d2 = mod_datetime.timedelta(1, 2) # move back and forward to add a total of 1 second gpx.adjust_time(d1, all=True) gpx.adjust_time(d2, all=True) self.assertEqual(gpx.waypoints[0].time, None) self.assertEqual(gpx.waypoints[1].time, t0_adjusted) self.assertEqual(gpx.routes[0].points[0].time, None) self.assertEqual(gpx.routes[0].points[1].time, None) self.assertEqual(gpx.routes[1].points[0].time, t0_adjusted) self.assertEqual(gpx.routes[1].points[1].time, t1_adjusted) def test_unicode(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_location_delta(self) -> None: location = mod_geo.Location(-20, -50) location_2 = location + mod_geo.LocationDelta(angle=45, distance=100) self.assertTrue(almostEqual(location_2.latitude - location.latitude, location_2.longitude - location.longitude)) def test_location_equator_delta_distance_111120(self) -> None: self.__test_location_delta(mod_geo.Location(0, 13), 111120) def test_location_equator_delta_distance_50(self) -> None: self.__test_location_delta(mod_geo.Location(0, -50), 50) def test_location_nonequator_delta_distance_111120(self) -> None: self.__test_location_delta(mod_geo.Location(45, 13), 111120) def test_location_nonequator_delta_distance_50(self) -> None: self.__test_location_delta(mod_geo.Location(-20, -50), 50) def test_delta_add_and_move(self) -> None: location = mod_geo.Location(45.1, 13.2) delta = mod_geo.LocationDelta(angle=20, distance=1000) location_2 = location + delta location.move(delta) self.assertTrue(almostEqual(location.latitude, location_2.latitude)) self.assertTrue(almostEqual(location.longitude, location_2.longitude)) def test_parse_gpx_with_node_with_comments(self) -> None: with open('test_files/gpx-with-node-with-comments.gpx') as f: self.assertTrue(mod_gpxpy.parse(f)) def __test_location_delta(self, location: mod_geo.Location, distance: float) -> None: angles = list(range(0, 360, 15)) print(angles) previous_location = None distances_between_points: List[float] = [] for angle in angles: new_location = location + mod_geo.LocationDelta(angle=angle, distance=distance) # All locations same distance from center self.assertTrue(almostEqual(location.distance_2d(new_location), distance)) # type: ignore if previous_location: distances_between_points.append(new_location.distance_2d(previous_location)) previous_location = new_location print(distances_between_points) # All points should be equidistant on a circle: for i in range(1, len(distances_between_points)): self.assertTrue(almostEqual(distances_between_points[0], distances_between_points[i])) def test_gpx_10_fields(self) -> None: """ Test (de) serialization all gpx1.0 fields """ with open('test_files/gpx1.0_with_all_fields.gpx') as f: xml = f.read() original_gpx = mod_gpxpy.parse(xml) # Serialize and parse again to be sure that all is preserved: reparsed_gpx = mod_gpxpy.parse(original_gpx.to_xml()) original_dom = mod_minidom.parseString(xml) reparsed_dom = mod_minidom.parseString(reparsed_gpx.to_xml()) # Validated with SAXParser in "make test" with open('test_files/validation_gpx10.gpx', 'w') as f: f.write(reparsed_gpx.to_xml()) for gpx in (original_gpx, reparsed_gpx): for dom in (original_dom, reparsed_dom): self.assertEqual(gpx.version, '1.0') self.assertEqual(get_dom_node(dom, 'gpx').attributes['version'].nodeValue, '1.0') self.assertEqual(gpx.creator, '...') self.assertEqual(get_dom_node(dom, 'gpx').attributes['creator'].nodeValue, '...') self.assertEqual(gpx.name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.description, 'example description') self.assertEqual(get_dom_node(dom, 'gpx/desc').firstChild.nodeValue, 'example description') self.assertEqual(gpx.author_name, 'example author') self.assertEqual(get_dom_node(dom, 'gpx/author').firstChild.nodeValue, 'example author') self.assertEqual(gpx.author_email, 'example@email.com') self.assertEqual(get_dom_node(dom, 'gpx/email').firstChild.nodeValue, 'example@email.com') self.assertEqual(gpx.link, 'http://example.url') self.assertEqual(get_dom_node(dom, 'gpx/url').firstChild.nodeValue, 'http://example.url') self.assertEqual(gpx.link_text, 'example urlname') self.assertEqual(get_dom_node(dom, 'gpx/urlname').firstChild.nodeValue, 'example urlname') self.assertEqual(gpx.time, mod_datetime.datetime(2013, 1, 1, 12, 0, tzinfo=None)) self.assertTrue(get_dom_node(dom, 'gpx/time').firstChild.nodeValue in ('2013-01-01T12:00:00Z', '2013-01-01T12:00:00')) self.assertEqual(gpx.keywords, 'example keywords') self.assertEqual(get_dom_node(dom, 'gpx/keywords').firstChild.nodeValue, 'example keywords') self.assertEqual(gpx.bounds.min_latitude, 1.2) # type: ignore self.assertEqual(get_dom_node(dom, 'gpx/bounds').attributes['minlat'].value, '1.2') # Waypoints: self.assertEqual(len(gpx.waypoints), 2) self.assertEqual(gpx.waypoints[0].latitude, 12.3) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lat'].value, '12.3') self.assertEqual(gpx.waypoints[0].longitude, 45.6) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lon'].value, '45.6') self.assertEqual(gpx.waypoints[0].longitude, 45.6) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lon'].value, '45.6') self.assertEqual(gpx.waypoints[0].elevation, 75.1) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/ele').firstChild.nodeValue, '75.1') self.assertEqual(gpx.waypoints[0].time, mod_datetime.datetime(2013, 1, 2, 2, 3, tzinfo=mod_gpxfield.SimpleTZ())) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/time').firstChild.nodeValue, '2013-01-02T02:03:00Z') self.assertEqual(gpx.waypoints[0].magnetic_variation, 1.1) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/magvar').firstChild.nodeValue, '1.1') self.assertEqual(gpx.waypoints[0].geoid_height, 2.0) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/geoidheight').firstChild.nodeValue, '2.0') self.assertEqual(gpx.waypoints[0].name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.waypoints[0].comment, 'example cmt') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/cmt').firstChild.nodeValue, 'example cmt') self.assertEqual(gpx.waypoints[0].description, 'example desc') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/desc').firstChild.nodeValue, 'example desc') self.assertEqual(gpx.waypoints[0].source, 'example src') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/src').firstChild.nodeValue, 'example src') self.assertEqual(gpx.waypoints[0].link, 'example url') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/url').firstChild.nodeValue, 'example url') self.assertEqual(gpx.waypoints[0].link_text, 'example urlname') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/urlname').firstChild.nodeValue, 'example urlname') self.assertEqual(gpx.waypoints[1].latitude, 13.4) self.assertEqual(get_dom_node(dom, 'gpx/wpt[1]').attributes['lat'].value, '13.4') self.assertEqual(gpx.waypoints[1].longitude, 46.7) self.assertEqual(get_dom_node(dom, 'gpx/wpt[1]').attributes['lon'].value, '46.7') self.assertEqual(len(gpx.routes), 2) self.assertEqual(gpx.routes[0].name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.routes[0].comment, 'example cmt') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/cmt').firstChild.nodeValue, 'example cmt') self.assertEqual(gpx.routes[0].description, 'example desc') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/desc').firstChild.nodeValue, 'example desc') self.assertEqual(gpx.routes[0].source, 'example src') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/src').firstChild.nodeValue, 'example src') self.assertEqual(gpx.routes[0].link, 'example url') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/url').firstChild.nodeValue, 'example url') # Rte pt: self.assertEqual(gpx.routes[0].points[0].latitude, 10) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]').attributes['lat'].value in ('10.0', '10')) self.assertEqual(gpx.routes[0].points[0].longitude, 20) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]').attributes['lon'].value in ('20.0', '20')) self.assertEqual(gpx.routes[0].points[0].elevation, 75.1) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/ele').firstChild.nodeValue, '75.1') self.assertEqual(gpx.routes[0].points[0].time, mod_datetime.datetime(2013, 1, 2, 2, 3, 3, tzinfo=mod_gpxfield.SimpleTZ())) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/time').firstChild.nodeValue, '2013-01-02T02:03:03Z') self.assertEqual(gpx.routes[0].points[0].magnetic_variation, 1.2) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/magvar').firstChild.nodeValue, '1.2') self.assertEqual(gpx.routes[0].points[0].geoid_height, 2.1) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/geoidheight').firstChild.nodeValue, '2.1') self.assertEqual(gpx.routes[0].points[0].name, 'example name r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/name').firstChild.nodeValue, 'example name r') self.assertEqual(gpx.routes[0].points[0].comment, 'example cmt r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/cmt').firstChild.nodeValue, 'example cmt r') self.assertEqual(gpx.routes[0].points[0].description, 'example desc r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/desc').firstChild.nodeValue, 'example desc r') self.assertEqual(gpx.routes[0].points[0].source, 'example src r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/src').firstChild.nodeValue, 'example src r') self.assertEqual(gpx.routes[0].points[0].link, 'example url r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/url').firstChild.nodeValue, 'example url r') self.assertEqual(gpx.routes[0].points[0].link_text, 'example urlname r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/urlname').firstChild.nodeValue, 'example urlname r') self.assertEqual(gpx.routes[0].points[0].symbol, 'example sym r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/sym').firstChild.nodeValue, 'example sym r') self.assertEqual(gpx.routes[0].points[0].type, 'example type r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/type').firstChild.nodeValue, 'example type r') self.assertEqual(gpx.routes[0].points[0].type_of_gpx_fix, '3d') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/fix').firstChild.nodeValue, '3d') self.assertEqual(gpx.routes[0].points[0].satellites, 6) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/sat').firstChild.nodeValue, '6') self.assertEqual(gpx.routes[0].points[0].vertical_dilution, 8) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/vdop').firstChild.nodeValue in ('8.0', '8')) self.assertEqual(gpx.routes[0].points[0].horizontal_dilution, 7) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/hdop').firstChild.nodeValue in ('7.0', '7')) self.assertEqual(gpx.routes[0].points[0].position_dilution, 9) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/pdop').firstChild.nodeValue in ('9.0', '9')) self.assertEqual(gpx.routes[0].points[0].age_of_dgps_data, 10) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/ageofdgpsdata').firstChild.nodeValue in ('10.0', '10')) self.assertEqual(gpx.routes[0].points[0].dgps_id, 99) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/dgpsid').firstChild.nodeValue, '99') # second rtept: self.assertEqual(gpx.routes[0].points[1].latitude, 11) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[1]').attributes['lat'].value in ('11.0', '11')) self.assertEqual(gpx.routes[0].points[1].longitude, 21) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[1]').attributes['lon'].value in ('21.0', '21')) # Rte self.assertEqual(gpx.routes[1].name, 'second route') self.assertEqual(get_dom_node(dom, 'gpx/rte[1]/name').firstChild.nodeValue, 'second route') self.assertEqual(gpx.routes[1].description, 'example desc 2') self.assertEqual(get_dom_node(dom, 'gpx/rte[1]/desc').firstChild.nodeValue, 'example desc 2') self.assertEqual(gpx.routes[0].link_text, 'example urlname') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/urlname').firstChild.nodeValue, 'example urlname') self.assertEqual(gpx.routes[0].number, 7) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/number').firstChild.nodeValue, '7') self.assertEqual(len(gpx.routes[0].points), 3) self.assertEqual(len(gpx.routes[1].points), 2) # trk: self.assertEqual(len(gpx.tracks), 2) self.assertEqual(gpx.tracks[0].name, 'example name t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/name').firstChild.nodeValue, 'example name t') self.assertEqual(gpx.tracks[0].comment, 'example cmt t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/cmt').firstChild.nodeValue, 'example cmt t') self.assertEqual(gpx.tracks[0].description, 'example desc t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/desc').firstChild.nodeValue, 'example desc t') self.assertEqual(gpx.tracks[0].source, 'example src t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/src').firstChild.nodeValue, 'example src t') self.assertEqual(gpx.tracks[0].link, 'example url t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/url').firstChild.nodeValue, 'example url t') self.assertEqual(gpx.tracks[0].link_text, 'example urlname t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/urlname').firstChild.nodeValue, 'example urlname t') self.assertEqual(gpx.tracks[0].number, 1) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/number').firstChild.nodeValue, '1') # trkpt: self.assertEqual(gpx.tracks[0].segments[0].points[0].elevation, 11.1) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/ele').firstChild.nodeValue, '11.1') self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(2013, 1, 1, 12, 0, 4, tzinfo=None)) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/time').firstChild.nodeValue in ('2013-01-01T12:00:04Z', '2013-01-01T12:00:04')) self.assertEqual(gpx.tracks[0].segments[0].points[0].magnetic_variation, 12) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/magvar').firstChild.nodeValue in ('12.0', '12')) self.assertEqual(gpx.tracks[0].segments[0].points[0].geoid_height, 13.0) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/geoidheight').firstChild.nodeValue in ('13.0', '13')) self.assertEqual(gpx.tracks[0].segments[0].points[0].name, 'example name t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/name').firstChild.nodeValue, 'example name t') self.assertEqual(gpx.tracks[0].segments[0].points[0].comment, 'example cmt t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/cmt').firstChild.nodeValue, 'example cmt t') self.assertEqual(gpx.tracks[0].segments[0].points[0].description, 'example desc t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/desc').firstChild.nodeValue, 'example desc t') self.assertEqual(gpx.tracks[0].segments[0].points[0].source, 'example src t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/src').firstChild.nodeValue, 'example src t') self.assertEqual(gpx.tracks[0].segments[0].points[0].link, 'example url t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/url').firstChild.nodeValue, 'example url t') self.assertEqual(gpx.tracks[0].segments[0].points[0].link_text, 'example urlname t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/urlname').firstChild.nodeValue, 'example urlname t') self.assertEqual(gpx.tracks[0].segments[0].points[0].symbol, 'example sym t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/sym').firstChild.nodeValue, 'example sym t') self.assertEqual(gpx.tracks[0].segments[0].points[0].type, 'example type t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/type').firstChild.nodeValue, 'example type t') self.assertEqual(gpx.tracks[0].segments[0].points[0].type_of_gpx_fix, '3d') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/fix').firstChild.nodeValue, '3d') self.assertEqual(gpx.tracks[0].segments[0].points[0].satellites, 100) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/sat').firstChild.nodeValue, '100') self.assertEqual(gpx.tracks[0].segments[0].points[0].vertical_dilution, 102.) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/vdop').firstChild.nodeValue in ('102.0', '102')) self.assertEqual(gpx.tracks[0].segments[0].points[0].horizontal_dilution, 101) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/hdop').firstChild.nodeValue in ('101.0', '101')) self.assertEqual(gpx.tracks[0].segments[0].points[0].position_dilution, 103) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/pdop').firstChild.nodeValue in ('103.0', '103')) self.assertEqual(gpx.tracks[0].segments[0].points[0].age_of_dgps_data, 104) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/ageofdgpsdata').firstChild.nodeValue in ('104.0', '104')) self.assertEqual(gpx.tracks[0].segments[0].points[0].dgps_id, 99) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/dgpsid').firstChild.nodeValue, '99') def test_gpx_11_fields(self) -> None: """ Test (de) serialization all gpx1.0 fields """ with open('test_files/gpx1.1_with_all_fields.gpx') as f: xml = f.read() original_gpx = mod_gpxpy.parse(xml) # Serialize and parse again to be sure that all is preserved: reparsed_gpx = mod_gpxpy.parse(original_gpx.to_xml('1.1')) original_dom = mod_minidom.parseString(xml) reparsed_dom = mod_minidom.parseString(reparsed_gpx.to_xml('1.1')) namespace = '{https://github.com/tkrajina/gpxpy}' for gpx in (original_gpx, reparsed_gpx): for dom in (original_dom, reparsed_dom): self.assertEqual(gpx.version, '1.1') self.assertEqual(get_dom_node(dom, 'gpx').attributes['version'].nodeValue, '1.1') self.assertEqual(gpx.creator, '...') self.assertEqual(get_dom_node(dom, 'gpx').attributes['creator'].nodeValue, '...') self.assertEqual(gpx.name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/metadata/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.description, 'example description') self.assertEqual(get_dom_node(dom, 'gpx/metadata/desc').firstChild.nodeValue, 'example description') self.assertEqual(gpx.author_name, 'author name') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/name').firstChild.nodeValue, 'author name') self.assertEqual(gpx.author_email, 'aaa@bbb.com') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/email').attributes['id'].nodeValue, 'aaa') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/email').attributes['domain'].nodeValue, 'bbb.com') self.assertEqual(gpx.author_link, 'http://link') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/link').attributes['href'].nodeValue, 'http://link') self.assertEqual(gpx.author_link_text, 'link text') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/link/text').firstChild.nodeValue, 'link text') self.assertEqual(gpx.author_link_type, 'link type') self.assertEqual(get_dom_node(dom, 'gpx/metadata/author/link/type').firstChild.nodeValue, 'link type') self.assertEqual(gpx.copyright_author, 'gpxauth') self.assertEqual(get_dom_node(dom, 'gpx/metadata/copyright').attributes['author'].nodeValue, 'gpxauth') self.assertEqual(gpx.copyright_year, '2013') self.assertEqual(get_dom_node(dom, 'gpx/metadata/copyright/year').firstChild.nodeValue, '2013') self.assertEqual(gpx.copyright_license, 'lic') self.assertEqual(get_dom_node(dom, 'gpx/metadata/copyright/license').firstChild.nodeValue, 'lic') self.assertEqual(gpx.link, 'http://link2') self.assertEqual(get_dom_node(dom, 'gpx/metadata/link').attributes['href'].nodeValue, 'http://link2') self.assertEqual(gpx.link_text, 'link text2') self.assertEqual(get_dom_node(dom, 'gpx/metadata/link/text').firstChild.nodeValue, 'link text2') self.assertEqual(gpx.link_type, 'link type2') self.assertEqual(get_dom_node(dom, 'gpx/metadata/link/type').firstChild.nodeValue, 'link type2') self.assertEqual(gpx.time, mod_datetime.datetime(2013, 1, 1, 12, 0, tzinfo=None)) self.assertTrue(get_dom_node(dom, 'gpx/metadata/time').firstChild.nodeValue in ('2013-01-01T12:00:00Z', '2013-01-01T12:00:00')) self.assertEqual(gpx.keywords, 'example keywords') self.assertEqual(get_dom_node(dom, 'gpx/metadata/keywords').firstChild.nodeValue, 'example keywords') self.assertEqual(gpx.bounds.min_latitude, 1.2) # type: ignore self.assertEqual(get_dom_node(dom, 'gpx/metadata/bounds').attributes['minlat'].value, '1.2') # TODO self.assertEqual(len(gpx.metadata_extensions), 3) aaa = mod_etree.Element(namespace+'aaa') aaa.text = 'bbb' aaa.tail = '' self.assertTrue(elements_equal(gpx.metadata_extensions[0], aaa)) bbb = mod_etree.Element(namespace+'bbb') bbb.text = 'ccc' bbb.tail = '' self.assertTrue(elements_equal(gpx.metadata_extensions[1], bbb)) ccc = mod_etree.Element(namespace+'ccc') ccc.text = 'ddd' ccc.tail = '' self.assertTrue(elements_equal(gpx.metadata_extensions[2], ccc)) # get_dom_node function is not escaped and so fails on proper namespaces #self.assertEqual(get_dom_node(dom, f'gpx/metadata/extensions/{namespace}aaa').firstChild.nodeValue, 'bbb') #self.assertEqual(get_dom_node(dom, 'gpx/metadata/extensions/bbb').firstChild.nodeValue, 'ccc') #self.assertEqual(get_dom_node(dom, 'gpx/metadata/extensions/ccc').firstChild.nodeValue, 'ddd') self.assertEqual(2, len(gpx.waypoints)) self.assertEqual(gpx.waypoints[0].latitude, 12.3) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lat'].value, '12.3') self.assertEqual(gpx.waypoints[0].longitude, 45.6) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lon'].value, '45.6') self.assertEqual(gpx.waypoints[0].longitude, 45.6) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]').attributes['lon'].value, '45.6') self.assertEqual(gpx.waypoints[0].elevation, 75.1) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/ele').firstChild.nodeValue, '75.1') self.assertEqual(gpx.waypoints[0].time, mod_datetime.datetime(2013, 1, 2, 2, 3, tzinfo=mod_gpxfield.SimpleTZ())) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/time').firstChild.nodeValue, '2013-01-02T02:03:00Z') self.assertEqual(gpx.waypoints[0].magnetic_variation, 1.1) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/magvar').firstChild.nodeValue, '1.1') self.assertEqual(gpx.waypoints[0].geoid_height, 2.0) self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/geoidheight').firstChild.nodeValue, '2.0') self.assertEqual(gpx.waypoints[0].name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.waypoints[0].comment, 'example cmt') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/cmt').firstChild.nodeValue, 'example cmt') self.assertEqual(gpx.waypoints[0].description, 'example desc') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/desc').firstChild.nodeValue, 'example desc') self.assertEqual(gpx.waypoints[0].source, 'example src') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/src').firstChild.nodeValue, 'example src') self.assertEqual(gpx.waypoints[0].link, 'http://link3') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/link').attributes['href'].nodeValue, 'http://link3') self.assertEqual(gpx.waypoints[0].link_text, 'link text3') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/link/text').firstChild.nodeValue, 'link text3') self.assertEqual(gpx.waypoints[0].link_type, 'link type3') self.assertEqual(get_dom_node(dom, 'gpx/wpt[0]/link/type').firstChild.nodeValue, 'link type3') self.assertEqual(gpx.waypoints[1].latitude, 13.4) self.assertEqual(get_dom_node(dom, 'gpx/wpt[1]').attributes['lat'].value, '13.4') self.assertEqual(gpx.waypoints[1].longitude, 46.7) self.assertEqual(get_dom_node(dom, 'gpx/wpt[1]').attributes['lon'].value, '46.7') self.assertEqual(2, len(gpx.waypoints[0].extensions)) self.assertTrue(elements_equal(gpx.waypoints[0].extensions[0], aaa)) self.assertTrue(elements_equal(gpx.waypoints[0].extensions[1], ccc)) # 1. rte self.assertEqual(gpx.routes[0].name, 'example name') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/name').firstChild.nodeValue, 'example name') self.assertEqual(gpx.routes[0].comment, 'example cmt') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/cmt').firstChild.nodeValue, 'example cmt') self.assertEqual(gpx.routes[0].description, 'example desc') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/desc').firstChild.nodeValue, 'example desc') self.assertEqual(gpx.routes[0].source, 'example src') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/src').firstChild.nodeValue, 'example src') self.assertEqual(gpx.routes[0].link, 'http://link3') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/link').attributes['href'].nodeValue, 'http://link3') self.assertEqual(gpx.routes[0].link_text, 'link text3') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/link/text').firstChild.nodeValue, 'link text3') self.assertEqual(gpx.routes[0].link_type, 'link type3') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/link/type').firstChild.nodeValue, 'link type3') self.assertEqual(gpx.routes[0].number, 7) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/number').firstChild.nodeValue, '7') self.assertEqual(gpx.routes[0].type, 'rte type') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/type').firstChild.nodeValue, 'rte type') self.assertEqual(2, len(gpx.routes[0].extensions)) rtee1 = mod_etree.Element(namespace+'rtee1') rtee1.text = '1' rtee1.tail = '' self.assertTrue(elements_equal(gpx.routes[0].extensions[0], rtee1)) rtee2 = mod_etree.Element(namespace+'rtee2') rtee2.text = '2' rtee2.tail = '' self.assertTrue(elements_equal(gpx.routes[0].extensions[1], rtee2)) # 2. rte self.assertEqual(gpx.routes[1].name, 'second route') self.assertEqual(get_dom_node(dom, 'gpx/rte[1]/name').firstChild.nodeValue, 'second route') self.assertEqual(gpx.routes[1].description, 'example desc 2') self.assertEqual(get_dom_node(dom, 'gpx/rte[1]/desc').firstChild.nodeValue, 'example desc 2') self.assertEqual(gpx.routes[1].link, None) self.assertEqual(gpx.routes[0].number, 7) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/number').firstChild.nodeValue, '7') self.assertEqual(len(gpx.routes[0].points), 3) self.assertEqual(len(gpx.routes[1].points), 2) # Rtept self.assertEqual(gpx.routes[0].points[0].latitude, 10) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]').attributes['lat'].value in ('10.0', '10')) self.assertEqual(gpx.routes[0].points[0].longitude, 20) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]').attributes['lon'].value in ('20.0', '20')) self.assertEqual(gpx.routes[0].points[0].elevation, 75.1) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/ele').firstChild.nodeValue, '75.1') self.assertEqual(gpx.routes[0].points[0].time, mod_datetime.datetime(2013, 1, 2, 2, 3, 3, tzinfo=mod_gpxfield.SimpleTZ())) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/time').firstChild.nodeValue, '2013-01-02T02:03:03Z') self.assertEqual(gpx.routes[0].points[0].magnetic_variation, 1.2) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/magvar').firstChild.nodeValue, '1.2') self.assertEqual(gpx.routes[0].points[0].geoid_height, 2.1) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/geoidheight').firstChild.nodeValue, '2.1') self.assertEqual(gpx.routes[0].points[0].name, 'example name r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/name').firstChild.nodeValue, 'example name r') self.assertEqual(gpx.routes[0].points[0].comment, 'example cmt r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/cmt').firstChild.nodeValue, 'example cmt r') self.assertEqual(gpx.routes[0].points[0].description, 'example desc r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/desc').firstChild.nodeValue, 'example desc r') self.assertEqual(gpx.routes[0].points[0].source, 'example src r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/src').firstChild.nodeValue, 'example src r') self.assertEqual(gpx.routes[0].points[0].link, 'http://linkrtept') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/link').attributes['href'].nodeValue, 'http://linkrtept') self.assertEqual(gpx.routes[0].points[0].link_text, 'rtept link') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/link/text').firstChild.nodeValue, 'rtept link') self.assertEqual(gpx.routes[0].points[0].link_type, 'rtept link type') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/link/type').firstChild.nodeValue, 'rtept link type') self.assertEqual(gpx.routes[0].points[0].symbol, 'example sym r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/sym').firstChild.nodeValue, 'example sym r') self.assertEqual(gpx.routes[0].points[0].type, 'example type r') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/type').firstChild.nodeValue, 'example type r') self.assertEqual(gpx.routes[0].points[0].type_of_gpx_fix, '3d') self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/fix').firstChild.nodeValue, '3d') self.assertEqual(gpx.routes[0].points[0].satellites, 6) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/sat').firstChild.nodeValue, '6') self.assertEqual(gpx.routes[0].points[0].vertical_dilution, 8) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/vdop').firstChild.nodeValue in ('8.0', '8')) self.assertEqual(gpx.routes[0].points[0].horizontal_dilution, 7) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/hdop').firstChild.nodeValue in ('7.0', '7')) self.assertEqual(gpx.routes[0].points[0].position_dilution, 9) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/pdop').firstChild.nodeValue in ('9.0', '9')) self.assertEqual(gpx.routes[0].points[0].age_of_dgps_data, 10) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/ageofdgpsdata').firstChild.nodeValue in ('10.0', '10')) self.assertEqual(gpx.routes[0].points[0].dgps_id, 99) self.assertEqual(get_dom_node(dom, 'gpx/rte[0]/rtept[0]/dgpsid').firstChild.nodeValue, '99') # second rtept: self.assertEqual(gpx.routes[0].points[1].latitude, 11) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[1]').attributes['lat'].value in ('11.0', '11')) self.assertEqual(gpx.routes[0].points[1].longitude, 21) self.assertTrue(get_dom_node(dom, 'gpx/rte[0]/rtept[1]').attributes['lon'].value in ('21.0', '21')) # gpx ext: self.assertEqual(1, len(gpx.extensions)) gpxext = mod_etree.Element(namespace+'gpxext') gpxext.text = '...' gpxext.tail = '' self.assertTrue(elements_equal(gpx.extensions[0], gpxext)) # trk self.assertEqual(len(gpx.tracks), 2) self.assertEqual(gpx.tracks[0].name, 'example name t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/name').firstChild.nodeValue, 'example name t') self.assertEqual(gpx.tracks[0].comment, 'example cmt t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/cmt').firstChild.nodeValue, 'example cmt t') self.assertEqual(gpx.tracks[0].description, 'example desc t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/desc').firstChild.nodeValue, 'example desc t') self.assertEqual(gpx.tracks[0].source, 'example src t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/src').firstChild.nodeValue, 'example src t') self.assertEqual(gpx.tracks[0].link, 'http://trk') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/link').attributes['href'].nodeValue, 'http://trk') self.assertEqual(gpx.tracks[0].link_text, 'trk link') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/link/text').firstChild.nodeValue, 'trk link') self.assertEqual(gpx.tracks[0].link_type, 'trk link type') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/link/type').firstChild.nodeValue, 'trk link type') self.assertEqual(gpx.tracks[0].number, 1) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/number').firstChild.nodeValue, '1') self.assertEqual(gpx.tracks[0].type, 't') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/type').firstChild.nodeValue, 't') self.assertEqual(1, len(gpx.tracks[0].extensions)) a1 = mod_etree.Element(namespace+'a1') a1.text = '2' a1.tail = '' self.assertTrue(elements_equal(gpx.tracks[0].extensions[0], a1)) # trkpt: self.assertEqual(gpx.tracks[0].segments[0].points[0].elevation, 11.1) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/ele').firstChild.nodeValue, '11.1') self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(2013, 1, 1, 12, 0, 4, tzinfo=None)) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/time').firstChild.nodeValue in ('2013-01-01T12:00:04Z', '2013-01-01T12:00:04')) self.assertEqual(gpx.tracks[0].segments[0].points[0].magnetic_variation, 12) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/magvar').firstChild.nodeValue in ('12.0', '12')) self.assertEqual(gpx.tracks[0].segments[0].points[0].geoid_height, 13.0) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/geoidheight').firstChild.nodeValue in ('13.0', '13')) self.assertEqual(gpx.tracks[0].segments[0].points[0].name, 'example name t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/name').firstChild.nodeValue, 'example name t') self.assertEqual(gpx.tracks[0].segments[0].points[0].comment, 'example cmt t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/cmt').firstChild.nodeValue, 'example cmt t') self.assertEqual(gpx.tracks[0].segments[0].points[0].description, 'example desc t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/desc').firstChild.nodeValue, 'example desc t') self.assertEqual(gpx.tracks[0].segments[0].points[0].source, 'example src t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/src').firstChild.nodeValue, 'example src t') self.assertEqual(gpx.tracks[0].segments[0].points[0].link, 'http://trkpt') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/link').attributes['href'].nodeValue, 'http://trkpt') self.assertEqual(gpx.tracks[0].segments[0].points[0].link_text, 'trkpt link') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/link/text').firstChild.nodeValue, 'trkpt link') self.assertEqual(gpx.tracks[0].segments[0].points[0].link_type, 'trkpt link type') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/link/type').firstChild.nodeValue, 'trkpt link type') self.assertEqual(gpx.tracks[0].segments[0].points[0].symbol, 'example sym t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/sym').firstChild.nodeValue, 'example sym t') self.assertEqual(gpx.tracks[0].segments[0].points[0].type, 'example type t') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/type').firstChild.nodeValue, 'example type t') self.assertEqual(gpx.tracks[0].segments[0].points[0].type_of_gpx_fix, '3d') self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/fix').firstChild.nodeValue, '3d') self.assertEqual(gpx.tracks[0].segments[0].points[0].satellites, 100) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/sat').firstChild.nodeValue, '100') self.assertEqual(gpx.tracks[0].segments[0].points[0].vertical_dilution, 102.) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/vdop').firstChild.nodeValue in ('102.0', '102')) self.assertEqual(gpx.tracks[0].segments[0].points[0].horizontal_dilution, 101) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/hdop').firstChild.nodeValue in ('101.0', '101')) self.assertEqual(gpx.tracks[0].segments[0].points[0].position_dilution, 103) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/pdop').firstChild.nodeValue in ('103.0', '103')) self.assertEqual(gpx.tracks[0].segments[0].points[0].age_of_dgps_data, 104) self.assertTrue(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/ageofdgpsdata').firstChild.nodeValue in ('104.0', '104')) self.assertEqual(gpx.tracks[0].segments[0].points[0].dgps_id, 99) self.assertEqual(get_dom_node(dom, 'gpx/trk[0]/trkseg[0]/trkpt[0]/dgpsid').firstChild.nodeValue, '99') self.assertEqual(1, len(gpx.tracks[0].segments[0].points[0].extensions)) last = mod_etree.Element(namespace+'last') last.text = 'true' last.tail = '' self.assertTrue(elements_equal(gpx.tracks[0].segments[0].points[0].extensions[0], last)) # Validated with SAXParser in "make test" # Clear extensions because those should be declared in the but # gpxpy don't have support for this (yet): reparsed_gpx.extensions = {} # type: ignore reparsed_gpx.metadata_extensions = {} # type: ignore for waypoint in reparsed_gpx.waypoints: waypoint.extensions = {} # type: ignore for route in reparsed_gpx.routes: route.extensions = {} # type: ignore for point in route.points: point.extensions = {} # type: ignore for track in reparsed_gpx.tracks: track.extensions = {} # type: ignore for segment in track.segments: segment.extensions = {} # type: ignore for point in segment.points: # type: ignore point.extensions = {} # type: ignore with open('test_files/validation_gpx11.gpx', 'w') as f: f.write(reparsed_gpx.to_xml()) def test_xml_chars_encode_decode(self) -> None: gpx = mod_gpxpy.gpx.GPX() gpx.name = "Testjkljkl" print(gpx.to_xml()) gpx_2 = mod_gpxpy.parse(gpx.to_xml()) self.assertTrue('Test<a>jkljkl</gpx>' in gpx_2.to_xml()) def test_10_to_11_conversion(self) -> None: """ This test checks that reparsing from 1.0 to 1.1 and from 1.1 to 1.0 will preserve all fields common for both versions. """ original_gpx = mod_gpx.GPX() original_gpx.creator = 'cr' original_gpx.name = 'q' original_gpx.description = 'w' original_gpx.time = mod_datetime.datetime(2014, 4, 7, 21, 17, 39, tzinfo=mod_gpxfield.SimpleTZ()) original_gpx.bounds = mod_gpx.GPXBounds(1, 2, 3, 4) original_gpx.author_name = '789' original_gpx.author_email = '256@aaa' original_gpx.link = 'http://9890' original_gpx.link_text = '77888' original_gpx.keywords = 'kw' original_waypoint = mod_gpx.GPXWaypoint() original_waypoint.latitude = 12.3 original_waypoint.longitude = 13.4 original_waypoint.elevation = 121.89 original_waypoint.time = mod_datetime.datetime(2015, 5, 8, 21, 17, 39, tzinfo=mod_gpxfield.SimpleTZ()) original_waypoint.magnetic_variation = 1 original_waypoint.geoid_height = 1 original_waypoint.name = 'n' original_waypoint.comment = 'cm' original_waypoint.description = 'des' original_waypoint.source = 'src' original_waypoint.symbol = 'sym' original_waypoint.type = 'ty' original_waypoint.type_of_gpx_fix = 'dgps' original_waypoint.satellites = 13 original_waypoint.horizontal_dilution = 14 original_waypoint.vertical_dilution = 15 original_waypoint.position_dilution = 16 original_waypoint.age_of_dgps_data = 16 original_waypoint.dgps_id = 17 original_gpx.waypoints.append(original_waypoint) original_route = mod_gpx.GPXRoute() original_route.name = 'rten' original_route.comment = 'rtecm' original_route.description = 'rtedesc' original_route.source = 'rtesrc' # TODO url original_route.number = 101 original_route_points = mod_gpx.GPXRoutePoint() original_route_points.latitude = 34.5 original_route_points.longitude = 56.6 original_route_points.elevation = 1001 original_route_points.time = mod_datetime.datetime(2015, 5, 8, 21, 17, 17, tzinfo=mod_gpxfield.SimpleTZ()) original_route_points.magnetic_variation = 12 original_route_points.geoid_height = 13 original_route_points.name = 'aaaaa' original_route_points.comment = 'wwww' original_route_points.description = 'cccc' original_route_points.source = 'qqq' # TODO url original_route_points.symbol = 'a.png' original_route_points.type = '2' original_route_points.type_of_gpx_fix = 'pps' original_route_points.satellites = 23 original_route_points.horizontal_dilution = 19 original_route_points.vertical_dilution = 20 original_route_points.position_dilution = 21 original_route_points.age_of_dgps_data = 22 original_route_points.dgps_id = 23 original_route.points.append(original_route_points) original_gpx.routes.append(original_route) original_track = mod_gpx.GPXTrack() original_track.name = 'rten' original_track.comment = 'rtecm' original_track.description = 'rtedesc' original_track.source = 'rtesrc' # TODO url original_track.number = 101 original_track_point = mod_gpx.GPXTrackPoint() original_track_point.latitude = 34.6 original_track_point.longitude = 57.6 original_track_point.elevation = 1002 original_track_point.time = mod_datetime.datetime(2016, 5, 8, 21, 17, 17, tzinfo=mod_gpxfield.SimpleTZ()) original_track_point.magnetic_variation = 13 original_track_point.geoid_height = 14 original_track_point.name = 'aaaaajkjk' original_track_point.comment = 'wwwwii' original_track_point.description = 'ciccc' original_track_point.source = 'qssqq' # TODO url original_track_point.symbol = 'ai.png' original_track_point.type = '3' original_track_point.type_of_gpx_fix = 'pps' original_track_point.satellites = 24 original_track_point.horizontal_dilution = 20 original_track_point.vertical_dilution = 21 original_track_point.position_dilution = 22 original_track_point.age_of_dgps_data = 23 original_track_point.dgps_id = 22 original_track.segments.append(mod_gpx.GPXTrackSegment()) original_track.segments[0].points.append(original_track_point) original_gpx.tracks.append(original_track) # Convert do GPX1.0: xml_10 = original_gpx.to_xml('1.0') print(xml_10) self.assertTrue('http://www.topografix.com/GPX/1/0' in xml_10) #pretty_print_xml(xml_10) gpx_1 = mod_gpxpy.parse(xml_10) # Convert do GPX1.1: xml_11 = gpx_1.to_xml('1.1') print(xml_11) self.assertTrue('http://www.topografix.com/GPX/1/1' in xml_11 and 'metadata' in xml_11) #pretty_print_xml(xml_11) gpx_2 = mod_gpxpy.parse(xml_11) # Convert do GPX1.0 again: xml_10 = gpx_2.to_xml('1.0') self.assertTrue('http://www.topografix.com/GPX/1/0' in xml_10) #pretty_print_xml(xml_10) gpx_3 = mod_gpxpy.parse(xml_10) for gpx in (gpx_1, gpx_2, gpx_3, ): self.assertTrue(gpx.creator is not None) self.assertEqual(original_gpx.creator, gpx.creator) self.assertTrue(gpx.name is not None) self.assertEqual(original_gpx.name, gpx.name) self.assertTrue(gpx.description is not None) self.assertEqual(original_gpx.description, gpx.description) self.assertTrue(gpx.keywords is not None) self.assertEqual(original_gpx.keywords, gpx.keywords) self.assertTrue(gpx.time is not None) self.assertEqual(original_gpx.time, gpx.time) self.assertTrue(gpx.author_name is not None) self.assertEqual(original_gpx.author_name, gpx.author_name) self.assertTrue(gpx.author_email is not None) self.assertEqual(original_gpx.author_email, gpx.author_email) self.assertTrue(gpx.link is not None) self.assertEqual(original_gpx.link, gpx.link) self.assertTrue(gpx.link_text is not None) self.assertEqual(original_gpx.link_text, gpx.link_text) self.assertTrue(gpx.bounds is not None) self.assertEqual(tuple(original_gpx.bounds), tuple(gpx.bounds)) # type: ignore self.assertEqual(1, len(gpx.waypoints)) self.assertTrue(gpx.waypoints[0].latitude is not None) self.assertEqual(original_gpx.waypoints[0].latitude, gpx.waypoints[0].latitude) self.assertTrue(gpx.waypoints[0].longitude is not None) self.assertEqual(original_gpx.waypoints[0].longitude, gpx.waypoints[0].longitude) self.assertTrue(gpx.waypoints[0].elevation is not None) self.assertEqual(original_gpx.waypoints[0].elevation, gpx.waypoints[0].elevation) self.assertTrue(gpx.waypoints[0].time is not None) self.assertEqual(original_gpx.waypoints[0].time, gpx.waypoints[0].time) self.assertTrue(gpx.waypoints[0].magnetic_variation is not None) self.assertEqual(original_gpx.waypoints[0].magnetic_variation, gpx.waypoints[0].magnetic_variation) self.assertTrue(gpx.waypoints[0].geoid_height is not None) self.assertEqual(original_gpx.waypoints[0].geoid_height, gpx.waypoints[0].geoid_height) self.assertTrue(gpx.waypoints[0].name is not None) self.assertEqual(original_gpx.waypoints[0].name, gpx.waypoints[0].name) self.assertTrue(gpx.waypoints[0].comment is not None) self.assertEqual(original_gpx.waypoints[0].comment, gpx.waypoints[0].comment) self.assertTrue(gpx.waypoints[0].description is not None) self.assertEqual(original_gpx.waypoints[0].description, gpx.waypoints[0].description) self.assertTrue(gpx.waypoints[0].source is not None) self.assertEqual(original_gpx.waypoints[0].source, gpx.waypoints[0].source) # TODO: Link/url self.assertTrue(gpx.waypoints[0].symbol is not None) self.assertEqual(original_gpx.waypoints[0].symbol, gpx.waypoints[0].symbol) self.assertTrue(gpx.waypoints[0].type is not None) self.assertEqual(original_gpx.waypoints[0].type, gpx.waypoints[0].type) self.assertTrue(gpx.waypoints[0].type_of_gpx_fix is not None) self.assertEqual(original_gpx.waypoints[0].type_of_gpx_fix, gpx.waypoints[0].type_of_gpx_fix) self.assertTrue(gpx.waypoints[0].satellites is not None) self.assertEqual(original_gpx.waypoints[0].satellites, gpx.waypoints[0].satellites) self.assertTrue(gpx.waypoints[0].horizontal_dilution is not None) self.assertEqual(original_gpx.waypoints[0].horizontal_dilution, gpx.waypoints[0].horizontal_dilution) self.assertTrue(gpx.waypoints[0].vertical_dilution is not None) self.assertEqual(original_gpx.waypoints[0].vertical_dilution, gpx.waypoints[0].vertical_dilution) self.assertTrue(gpx.waypoints[0].position_dilution is not None) self.assertEqual(original_gpx.waypoints[0].position_dilution, gpx.waypoints[0].position_dilution) self.assertTrue(gpx.waypoints[0].age_of_dgps_data is not None) self.assertEqual(original_gpx.waypoints[0].age_of_dgps_data, gpx.waypoints[0].age_of_dgps_data) self.assertTrue(gpx.waypoints[0].dgps_id is not None) self.assertEqual(original_gpx.waypoints[0].dgps_id, gpx.waypoints[0].dgps_id) # route(s): self.assertTrue(gpx.routes[0].name is not None) self.assertEqual(original_gpx.routes[0].name, gpx.routes[0].name) self.assertTrue(gpx.routes[0].comment is not None) self.assertEqual(original_gpx.routes[0].comment, gpx.routes[0].comment) self.assertTrue(gpx.routes[0].description is not None) self.assertEqual(original_gpx.routes[0].description, gpx.routes[0].description) self.assertTrue(gpx.routes[0].source is not None) self.assertEqual(original_gpx.routes[0].source, gpx.routes[0].source) self.assertTrue(gpx.routes[0].number is not None) self.assertEqual(original_gpx.routes[0].number, gpx.routes[0].number) self.assertTrue(gpx.routes[0].points[0].latitude is not None) self.assertEqual(original_gpx.routes[0].points[0].latitude, gpx.routes[0].points[0].latitude) self.assertTrue(gpx.routes[0].points[0].longitude is not None) self.assertEqual(original_gpx.routes[0].points[0].longitude, gpx.routes[0].points[0].longitude) self.assertTrue(gpx.routes[0].points[0].elevation is not None) self.assertEqual(original_gpx.routes[0].points[0].elevation, gpx.routes[0].points[0].elevation) self.assertTrue(gpx.routes[0].points[0].time is not None) self.assertEqual(original_gpx.routes[0].points[0].time, gpx.routes[0].points[0].time) self.assertTrue(gpx.routes[0].points[0].magnetic_variation is not None) self.assertEqual(original_gpx.routes[0].points[0].magnetic_variation, gpx.routes[0].points[0].magnetic_variation) self.assertTrue(gpx.routes[0].points[0].geoid_height is not None) self.assertEqual(original_gpx.routes[0].points[0].geoid_height, gpx.routes[0].points[0].geoid_height) self.assertTrue(gpx.routes[0].points[0].name is not None) self.assertEqual(original_gpx.routes[0].points[0].name, gpx.routes[0].points[0].name) self.assertTrue(gpx.routes[0].points[0].comment is not None) self.assertEqual(original_gpx.routes[0].points[0].comment, gpx.routes[0].points[0].comment) self.assertTrue(gpx.routes[0].points[0].description is not None) self.assertEqual(original_gpx.routes[0].points[0].description, gpx.routes[0].points[0].description) self.assertTrue(gpx.routes[0].points[0].source is not None) self.assertEqual(original_gpx.routes[0].points[0].source, gpx.routes[0].points[0].source) self.assertTrue(gpx.routes[0].points[0].symbol is not None) self.assertEqual(original_gpx.routes[0].points[0].symbol, gpx.routes[0].points[0].symbol) self.assertTrue(gpx.routes[0].points[0].type is not None) self.assertEqual(original_gpx.routes[0].points[0].type, gpx.routes[0].points[0].type) self.assertTrue(gpx.routes[0].points[0].type_of_gpx_fix is not None) self.assertEqual(original_gpx.routes[0].points[0].type_of_gpx_fix, gpx.routes[0].points[0].type_of_gpx_fix) self.assertTrue(gpx.routes[0].points[0].satellites is not None) self.assertEqual(original_gpx.routes[0].points[0].satellites, gpx.routes[0].points[0].satellites) self.assertTrue(gpx.routes[0].points[0].horizontal_dilution is not None) self.assertEqual(original_gpx.routes[0].points[0].horizontal_dilution, gpx.routes[0].points[0].horizontal_dilution) self.assertTrue(gpx.routes[0].points[0].vertical_dilution is not None) self.assertEqual(original_gpx.routes[0].points[0].vertical_dilution, gpx.routes[0].points[0].vertical_dilution) self.assertTrue(gpx.routes[0].points[0].position_dilution is not None) self.assertEqual(original_gpx.routes[0].points[0].position_dilution, gpx.routes[0].points[0].position_dilution) self.assertTrue(gpx.routes[0].points[0].age_of_dgps_data is not None) self.assertEqual(original_gpx.routes[0].points[0].age_of_dgps_data, gpx.routes[0].points[0].age_of_dgps_data) self.assertTrue(gpx.routes[0].points[0].dgps_id is not None) self.assertEqual(original_gpx.routes[0].points[0].dgps_id, gpx.routes[0].points[0].dgps_id) # track(s): self.assertTrue(gpx.tracks[0].name is not None) self.assertEqual(original_gpx.tracks[0].name, gpx.tracks[0].name) self.assertTrue(gpx.tracks[0].comment is not None) self.assertEqual(original_gpx.tracks[0].comment, gpx.tracks[0].comment) self.assertTrue(gpx.tracks[0].description is not None) self.assertEqual(original_gpx.tracks[0].description, gpx.tracks[0].description) self.assertTrue(gpx.tracks[0].source is not None) self.assertEqual(original_gpx.tracks[0].source, gpx.tracks[0].source) self.assertTrue(gpx.tracks[0].number is not None) self.assertEqual(original_gpx.tracks[0].number, gpx.tracks[0].number) self.assertTrue(gpx.tracks[0].segments[0].points[0].latitude is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].latitude, gpx.tracks[0].segments[0].points[0].latitude) self.assertTrue(gpx.tracks[0].segments[0].points[0].longitude is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].longitude, gpx.tracks[0].segments[0].points[0].longitude) self.assertTrue(gpx.tracks[0].segments[0].points[0].elevation is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].elevation, gpx.tracks[0].segments[0].points[0].elevation) self.assertTrue(gpx.tracks[0].segments[0].points[0].time is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].time, gpx.tracks[0].segments[0].points[0].time) self.assertTrue(gpx.tracks[0].segments[0].points[0].magnetic_variation is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].magnetic_variation, gpx.tracks[0].segments[0].points[0].magnetic_variation) self.assertTrue(gpx.tracks[0].segments[0].points[0].geoid_height is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].geoid_height, gpx.tracks[0].segments[0].points[0].geoid_height) self.assertTrue(gpx.tracks[0].segments[0].points[0].name is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].name, gpx.tracks[0].segments[0].points[0].name) self.assertTrue(gpx.tracks[0].segments[0].points[0].comment is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].comment, gpx.tracks[0].segments[0].points[0].comment) self.assertTrue(gpx.tracks[0].segments[0].points[0].description is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].description, gpx.tracks[0].segments[0].points[0].description) self.assertTrue(gpx.tracks[0].segments[0].points[0].source is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].source, gpx.tracks[0].segments[0].points[0].source) self.assertTrue(gpx.tracks[0].segments[0].points[0].symbol is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].symbol, gpx.tracks[0].segments[0].points[0].symbol) self.assertTrue(gpx.tracks[0].segments[0].points[0].type is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].type, gpx.tracks[0].segments[0].points[0].type) self.assertTrue(gpx.tracks[0].segments[0].points[0].type_of_gpx_fix is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].type_of_gpx_fix, gpx.tracks[0].segments[0].points[0].type_of_gpx_fix) self.assertTrue(gpx.tracks[0].segments[0].points[0].satellites is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].satellites, gpx.tracks[0].segments[0].points[0].satellites) self.assertTrue(gpx.tracks[0].segments[0].points[0].horizontal_dilution is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].horizontal_dilution, gpx.tracks[0].segments[0].points[0].horizontal_dilution) self.assertTrue(gpx.tracks[0].segments[0].points[0].vertical_dilution is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].vertical_dilution, gpx.tracks[0].segments[0].points[0].vertical_dilution) self.assertTrue(gpx.tracks[0].segments[0].points[0].position_dilution is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].position_dilution, gpx.tracks[0].segments[0].points[0].position_dilution) self.assertTrue(gpx.tracks[0].segments[0].points[0].age_of_dgps_data is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].age_of_dgps_data, gpx.tracks[0].segments[0].points[0].age_of_dgps_data) self.assertTrue(gpx.tracks[0].segments[0].points[0].dgps_id is not None) self.assertEqual(original_gpx.tracks[0].segments[0].points[0].dgps_id, gpx.tracks[0].segments[0].points[0].dgps_id) def test_min_max(self) -> None: gpx = mod_gpx.GPX() track = mod_gpx.GPXTrack() gpx.tracks.append(track) segment = mod_gpx.GPXTrackSegment() track.segments.append(segment) segment.points.append(mod_gpx.GPXTrackPoint(12, 13, elevation=100)) segment.points.append(mod_gpx.GPXTrackPoint(12, 13, elevation=200)) # Check for segment: elevation_min, elevation_max = segment.get_elevation_extremes() self.assertEqual(100, elevation_min) self.assertEqual(200, elevation_max) # Check for track: elevation_min, elevation_max = track.get_elevation_extremes() self.assertEqual(100, elevation_min) self.assertEqual(200, elevation_max) # Check for gpx: elevation_min, elevation_max = gpx.get_elevation_extremes() self.assertEqual(100, elevation_min) self.assertEqual(200, elevation_max) def test_distance_between_points_near_0_longitude(self) -> None: """ Make sure that the distance function works properly when points have longitudes on opposite sides of the 0-longitude meridian """ distance = mod_geo.distance(latitude_1=0, longitude_1=0.1, elevation_1=0, latitude_2=0, longitude_2=-0.1, elevation_2=0, haversine=True) print(distance) self.assertTrue(distance < 230000) distance = mod_geo.distance(latitude_1=0, longitude_1=0.1, elevation_1=0, latitude_2=0, longitude_2=-0.1, elevation_2=0, haversine=False) print(distance) self.assertTrue(distance < 230000) distance = mod_geo.distance(latitude_1=0, longitude_1=0.1, elevation_1=0, latitude_2=0, longitude_2=360-0.1, elevation_2=0, haversine=True) print(distance) self.assertTrue(distance < 230000) distance = mod_geo.distance(latitude_1=0, longitude_1=0.1, elevation_1=0, latitude_2=0, longitude_2=360-0.1, elevation_2=0, haversine=False) print(distance) self.assertTrue(distance < 230000) def test_zero_latlng(self) -> None: gpx = mod_gpx.GPX() track = mod_gpx.GPXTrack() gpx.tracks.append(track) segment = mod_gpx.GPXTrackSegment() track.segments.append(segment) segment.points.append(mod_gpx.GPXTrackPoint(0, 0, elevation=0)) xml = gpx.to_xml() print(xml) self.assertEqual(1, len(gpx.tracks)) self.assertEqual(1, len(gpx.tracks[0].segments)) self.assertEqual(1, len(gpx.tracks[0].segments[0].points)) self.assertEqual(0, gpx.tracks[0].segments[0].points[0].latitude) self.assertEqual(0, gpx.tracks[0].segments[0].points[0].longitude) self.assertEqual(0, gpx.tracks[0].segments[0].points[0].elevation) gpx2 = mod_gpxpy.parse(xml) self.assertEqual(1, len(gpx2.tracks)) self.assertEqual(1, len(gpx2.tracks[0].segments)) self.assertEqual(1, len(gpx2.tracks[0].segments[0].points)) self.assertEqual(0, gpx2.tracks[0].segments[0].points[0].latitude) self.assertEqual(0, gpx2.tracks[0].segments[0].points[0].longitude) self.assertEqual(0, gpx2.tracks[0].segments[0].points[0].elevation) def test_timezone_from_timestamp(self) -> None: # Test tz unaware xml = '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' gpx = mod_gpxpy.parse(xml) self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(2014, 2, 2, 10, 23, 18, tzinfo=None)) # Test tz aware xml = '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' gpx = mod_gpxpy.parse(xml) self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(2014, 2, 2, 10, 23, 18, tzinfo=mod_gpxfield.SimpleTZ('01'))) # Test deepcopy of SimpleTZ gpx = gpx.clone() t_stamp = "2014-02-02T10:23:18" self.assertTrue(t_stamp + "+01:00" in gpx.to_xml() or t_stamp + "+0100" in gpx.to_xml()) reparsed = mod_gpxpy.parse(gpx.to_xml()) self.assertTrue(t_stamp + "+01:00" in reparsed.to_xml() or t_stamp + "+0100" in reparsed.to_xml()) self.assertTrue(reparsed.tracks[0].segments[0].points[0].time.tzinfo) # type: ignore def test_timestamp_with_single_digits(self) -> None: xml = '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' gpx = mod_gpxpy.parse(xml) self.assertEqual(gpx.tracks[0].segments[0].points[0].time, mod_datetime.datetime(2014, 2, 2, 2, 23, 18, tzinfo=mod_gpxfield.SimpleTZ('-02'))) def test_read_extensions(self) -> None: """ Test extensions """ with open('test_files/gpx1.1_with_extensions.gpx') as f: xml = f.read() namespace = '{gpx.py}' root1 = mod_etree.Element(namespace + 'aaa') root1.text = 'bbb' root1.tail = 'hhh' root1.attrib[namespace+'jjj'] = 'kkk' root2 = mod_etree.Element(namespace + 'ccc') root2.text = '' root2.tail = '' subnode1 = mod_etree.SubElement(root2, namespace + 'ddd') subnode1.text = 'eee' subnode1.tail = '' subnode1.attrib[namespace+'lll'] = 'mmm' subnode1.attrib[namespace+'nnn'] = 'ooo' subnode2 = mod_etree.SubElement(subnode1, namespace + 'fff') subnode2.text = 'ggg' subnode2.tail = 'iii' gpx = mod_gpxpy.parse(xml) print("Extension 1") print(type(gpx.waypoints[0].extensions[0])) print(print_etree(gpx.waypoints[0].extensions[0])) print() self.assertTrue(elements_equal(gpx.waypoints[0].extensions[0], root1)) print("Extension 2") print(type(gpx.waypoints[0].extensions[1])) print(print_etree(gpx.waypoints[0].extensions[1])) print() self.assertTrue(elements_equal(gpx.waypoints[0].extensions[1], root2)) def test_write_read_extensions(self) -> None: namespace = '{gpx.py}' nsmap = {'ext' : namespace[1:-1]} root = mod_etree.Element(namespace + 'ccc') root.text = '' root.tail = '' subnode1 = mod_etree.SubElement(root, namespace + 'ddd') subnode1.text = 'eee' subnode1.tail = '' subnode1.attrib[namespace+'lll'] = 'mmm' subnode1.attrib[namespace+'nnn'] = 'ooo' subnode2 = mod_etree.SubElement(subnode1, namespace + 'fff') subnode2.text = 'ggg' subnode2.tail = 'iii' subnode3 = mod_etree.SubElement(root, namespace + 'aaa') subnode3.text = 'bbb' gpx = mod_gpx.GPX() gpx.nsmap = nsmap print("Inserting Waypoint Extension") gpx.waypoints.append(mod_gpx.GPXWaypoint()) gpx.waypoints[0].latitude = 5 gpx.waypoints[0].longitude = 10 gpx.waypoints[0].extensions.append(root) print("Inserting Metadata Extension") gpx.metadata_extensions.append(root) print("Inserting GPX Extension") gpx.extensions.append(root) print("Inserting Route Extension") gpx.routes.append(mod_gpx.GPXRoute()) gpx.routes[0].extensions.append(root) print("Inserting Track Extension") gpx.tracks.append(mod_gpx.GPXTrack()) gpx.tracks[0].extensions.append(root) print("Inserting Track Segment Extension") gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment()) gpx.tracks[0].segments[0].extensions.append(root) print("Inserting Track Point Extension") gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13)) gpx.tracks[0].segments[0].points[0].extensions.append(root) xml = gpx.to_xml('1.1') parsedgpx = mod_gpxpy.parse(xml) print("Reading Waypoint Extension") print(print_etree(gpx.waypoints[0].extensions[0])) print() self.assertTrue(elements_equal(gpx.waypoints[0].extensions[0], root)) print("Reading Metadata Extension") self.assertTrue(elements_equal(gpx.metadata_extensions[0], root)) print("Reading GPX Extension") self.assertTrue(elements_equal(gpx.extensions[0], root)) print("Reading Route Extension") self.assertTrue(elements_equal(gpx.routes[0].extensions[0], root)) print("Reading Track Extension") self.assertTrue(elements_equal(gpx.tracks[0].extensions[0], root)) print("Reading Track Segment Extension") self.assertTrue(elements_equal(gpx.tracks[0].segments[0].extensions[0], root)) print("Reading Track Point Extension") self.assertTrue(elements_equal(gpx.tracks[0].segments[0].points[0].extensions[0], root)) def test_no_10_extensions(self) -> None: namespace = '{gpx.py}' nsmap = {'ext' : namespace[1:-1]} root = mod_etree.Element(namespace + 'tag') root.text = 'text' root.tail = 'tail' gpx = mod_gpx.GPX() gpx.nsmap = nsmap print("Inserting Waypoint Extension") gpx.waypoints.append(mod_gpx.GPXWaypoint()) gpx.waypoints[0].latitude = 5 gpx.waypoints[0].longitude = 10 gpx.waypoints[0].extensions.append(root) print("Inserting Metadata Extension") gpx.metadata_extensions.append(root) print("Inserting GPX Extension") gpx.extensions.append(root) print("Inserting Route Extension") gpx.routes.append(mod_gpx.GPXRoute()) gpx.routes[0].extensions.append(root) print("Inserting Track Extension") gpx.tracks.append(mod_gpx.GPXTrack()) gpx.tracks[0].extensions.append(root) print("Inserting Track Segment Extension") gpx.tracks[0].segments.append(mod_gpx.GPXTrackSegment()) gpx.tracks[0].segments[0].extensions.append(root) print("Inserting Track Point Extension") gpx.tracks[0].segments[0].points.append(mod_gpx.GPXTrackPoint(latitude=12, longitude=13)) gpx.tracks[0].segments[0].points[0].extensions.append(root) xml = gpx.to_xml('1.0') self.assertFalse('extension' in xml) def test_extension_without_namespaces(self) -> None: f = open('test_files/gpx1.1_with_extensions_without_namespaces.gpx') gpx = mod_gpxpy.parse(f) self.assertEqual(2, len(gpx.waypoints[0].extensions)) self.assertEqual("bbb", gpx.waypoints[0].extensions[0].text) self.assertEqual("eee", list(gpx.waypoints[0].extensions[1])[0].text.strip()) def test_garmin_extension(self) -> None: f = open('test_files/gpx_with_garmin_extension.gpx') gpx = mod_gpxpy.parse(f) xml = gpx.to_xml() self.assertTrue("" in xml) self.assertTrue("171" in xml) print(gpx.to_xml()) def test_with_ns_namespace(self) -> None: gpx_with_ns = mod_gpxpy.parse(""" Foo Bar running 23.6000003814697265625 125 75 """) reparsed = mod_gpxpy.parse(gpx_with_ns.to_xml("1.1")) for gpx in [gpx_with_ns, reparsed]: extensions = gpx.tracks[0].segments[0].points[0].extensions self.assertEqual(1, len(extensions)) self.assertEqual("125", list(extensions[0])[0].text.strip()) self.assertEqual("75", list(extensions[0])[1].text.strip()) def test_join_gpx_xml_files(self) -> None: import gpxpy.gpxxml files = [ 'test_files/cerknicko-jezero.gpx', 'test_files/first_and_last_elevation.gpx', 'test_files/korita-zbevnica.gpx', 'test_files/Mojstrovka.gpx', ] rtes = 0 wpts = 0 trcks = 0 points = 0 xmls = [] for file_name in files: with open(file_name) as f: contents = f.read() gpx = mod_gpxpy.parse(contents) wpts += len(gpx.waypoints) rtes += len(gpx.routes) trcks += len(gpx.tracks) points += gpx.get_points_no() xmls.append(contents) result_xml = gpxpy.gpxxml.join_gpxs(xmls) result_gpx = mod_gpxpy.parse(result_xml) self.assertEqual(rtes, len(result_gpx.routes)) self.assertEqual(wpts, len(result_gpx.waypoints)) self.assertEqual(trcks, len(result_gpx.tracks)) self.assertEqual(points, result_gpx.get_points_no()) def test_small_floats(self) -> None: """GPX 1/1 does not allow scientific notation but that is what gpxpy writes right now.""" f = open('test_files/track-with-small-floats.gpx') gpx = mod_gpxpy.parse(f) xml = gpx.to_xml() self.assertNotIn('e-', xml) def test_gpx_fill_time_data_with_start_time_and_end_time(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) end_time = mod_datetime.datetime(2018, 7, 4, 1, 0, 0) gpx.fill_time_data_with_regular_intervals(start_time=start_time, end_time=end_time) time_bounds = gpx.get_time_bounds() tolerance = 1.0 start_time_diff = total_seconds(time_bounds.start_time - start_time) # type: ignore end_time_diff = total_seconds(time_bounds.end_time - end_time) # type: ignore self.assertLessEqual(mod_math.fabs(start_time_diff), tolerance) self.assertLessEqual(mod_math.fabs(end_time_diff), tolerance) def test_gpx_fill_time_data_with_start_time_and_end_time_and_time_delta(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) time_delta = mod_datetime.timedelta(seconds=60) end_time = mod_datetime.datetime(2018, 7, 4, 1, 0, 0) gpx.fill_time_data_with_regular_intervals(start_time=start_time, time_delta=time_delta, end_time=end_time) time_bounds = gpx.get_time_bounds() tolerance = 1.0 start_time_diff = total_seconds(time_bounds.start_time - start_time) # type: ignore end_time_diff = total_seconds(time_bounds.end_time - end_time) # type: ignore self.assertLessEqual(mod_math.fabs(start_time_diff), tolerance) self.assertLessEqual(mod_math.fabs(end_time_diff), tolerance) def test_gpx_fill_time_data_with_start_time_and_time_delta(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) time_delta = mod_datetime.timedelta(seconds=1) end_time = start_time + (gpx.get_points_no() - 1) * time_delta gpx.fill_time_data_with_regular_intervals(start_time=start_time, time_delta=time_delta) time_bounds = gpx.get_time_bounds() tolerance = 1.0 start_time_diff = total_seconds(time_bounds.start_time - start_time) # type: ignore end_time_diff = total_seconds(time_bounds.end_time - end_time) # type: ignore self.assertLessEqual(mod_math.fabs(start_time_diff), tolerance) self.assertLessEqual(mod_math.fabs(end_time_diff), tolerance) def test_gpx_fill_time_data_with_end_time_and_time_delta(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') end_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) time_delta = mod_datetime.timedelta(seconds=1) start_time = end_time - (gpx.get_points_no() - 1) * time_delta gpx.fill_time_data_with_regular_intervals(time_delta=time_delta, end_time=end_time) time_bounds = gpx.get_time_bounds() tolerance = 1.0 start_time_diff = total_seconds(time_bounds.start_time - start_time) # type: ignore end_time_diff = total_seconds(time_bounds.end_time - end_time) # type: ignore self.assertLessEqual(mod_math.fabs(start_time_diff), tolerance) self.assertLessEqual(mod_math.fabs(end_time_diff), tolerance) def test_gpx_fill_time_data_raises_when_not_enough_parameters(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) with self.assertRaises(mod_gpx.GPXException): gpx.fill_time_data_with_regular_intervals(start_time=start_time) def test_gpx_fill_time_data_raises_when_start_time_after_end_time(self) -> None: gpx = self.parse('cerknicko-jezero.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) end_time = mod_datetime.datetime(2018, 7, 3, 0, 0, 0) with self.assertRaises(mod_gpx.GPXException): gpx.fill_time_data_with_regular_intervals(start_time=start_time, end_time=end_time) def test_gpx_fill_time_data_raises_when_force_is_false(self) -> None: gpx = self.parse('Mojstrovka.gpx') start_time = mod_datetime.datetime(2018, 7, 4, 0, 0, 0) end_time = mod_datetime.datetime(2018, 7, 4, 1, 0, 0) gpx.fill_time_data_with_regular_intervals(start_time=start_time, end_time=end_time) with self.assertRaises(mod_gpx.GPXException): gpx.fill_time_data_with_regular_intervals(start_time=start_time, end_time=end_time, force=False) def test_single_quotes_xmlns(self) -> None: gpx = mod_gpxpy.parse(""" 100 """) self.assertEqual(1, len(gpx.tracks)) self.assertEqual(1, len(gpx.tracks[0].segments)) self.assertEqual(1, len(gpx.tracks[0].segments[0].points)) def test_default_schema_locations(self) -> None: gpx = mod_gpx.GPX() with open('test_files/default_schema_locations.gpx') as f: self.assertEqual(gpx.to_xml(), f.read()) def test_custom_schema_locations(self) -> None: gpx = mod_gpx.GPX() gpx.nsmap = { 'gpxx': 'http://www.garmin.com/xmlschemas/GpxExtensions/v3', } gpx.schema_locations = [ 'http://www.topografix.com/GPX/1/1', 'http://www.topografix.com/GPX/1/1/gpx.xsd', 'http://www.garmin.com/xmlschemas/GpxExtensions/v3', 'http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd', ] with open('test_files/custom_schema_locations.gpx') as f: self.assertEqual(gpx.to_xml(), f.read()) def test_parse_custom_schema_locations(self) -> None: gpx = self.parse('custom_schema_locations.gpx') self.assertEqual( [ 'http://www.topografix.com/GPX/1/1', 'http://www.topografix.com/GPX/1/1/gpx.xsd', 'http://www.garmin.com/xmlschemas/GpxExtensions/v3', 'http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd', ], gpx.schema_locations ) def test_no_track(self) -> None: xml = """ """ gpx = mod_gpxpy.parse(xml) self.assertEqual(0, len(gpx.tracks)) gpx2 = self.reparse(gpx) self.assertEqual(0, len(gpx2.tracks)) def test_microsecond(self) -> None: xml = ' ' gpx = mod_gpxpy.parse(xml) gpx2 = self.reparse(gpx) print(gpx2.to_xml()) self.assertEqual(207343, gpx2.tracks[0].segments[0].points[0].time.microsecond) # type: ignore self.assertTrue("