├── .coveragerc ├── .github └── workflows │ ├── ci-tests.yml │ └── publish-tags.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yaml ├── AUTHORS.md ├── CHANGELOG.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py └── index.rst ├── environment.yml ├── examples ├── README.md ├── basic_examples.ipynb └── compare_providers.ipynb ├── poetry.lock ├── pyproject.toml ├── requirements.txt ├── requirements_dev.txt ├── routingpy ├── __init__.py ├── client_base.py ├── client_default.py ├── convert.py ├── direction.py ├── exceptions.py ├── expansion.py ├── isochrone.py ├── matrix.py ├── raster.py ├── routers │ ├── __init__.py │ ├── google.py │ ├── graphhopper.py │ ├── heremaps.py │ ├── mapbox_osrm.py │ ├── openrouteservice.py │ ├── opentripplanner_v2.py │ ├── osrm.py │ └── valhalla.py ├── utils.py └── valhalla_attributes.py ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── raster_example.tiff ├── test_base.py ├── test_convert.py ├── test_google.py ├── test_graphhopper.py ├── test_helper.py ├── test_heremaps.py ├── test_mapbox_osrm.py ├── test_openrouteservice.py ├── test_opentripplanner_v2.py ├── test_osrm.py ├── test_utils.py └── test_valhalla.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = 3 | */.venv/* 4 | */docs/* 5 | */test.py 6 | -------------------------------------------------------------------------------- /.github/workflows/ci-tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths-ignore: 8 | - '.gitignore' 9 | - '**.md' 10 | - '**.rst' 11 | pull_request: 12 | branches: 13 | - master 14 | paths-ignore: 15 | - '.gitignore' 16 | - '**.md' 17 | - '**.rst' 18 | 19 | jobs: 20 | build: 21 | runs-on: ubuntu-20.04 22 | strategy: 23 | matrix: 24 | python_version: [ 25 | 3.9, # only lowest & highest version should be enough, :cross_fingers: 26 | # 3.10, 27 | # '3.11', 28 | '3.12' 29 | # pypy3 # didn't build on CI anymore, happy for help: https://github.com/gis-ops/routing-py/issues/60 30 | ] 31 | steps: 32 | - uses: actions/checkout@v3 33 | 34 | - name: Set up Python ${{ matrix.python_version }} 35 | uses: actions/setup-python@v4 36 | with: 37 | python-version: ${{ matrix.python_version }} 38 | cache: pip 39 | 40 | - uses: actions/cache@v3 41 | with: 42 | path: ~/.cache/pre-commit 43 | key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} 44 | 45 | - name: Install dependencies 46 | run: | 47 | pip install -r requirements_dev.txt 48 | 49 | - name: style & lint checks 50 | run: | 51 | pre-commit run --all-files --color=always 52 | 53 | - name: pytest and coverage 54 | run: | 55 | pip install -e . 56 | coverage run --source=routingpy --module pytest 57 | coverage lcov --include "routingpy/*" 58 | env: 59 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 60 | -------------------------------------------------------------------------------- /.github/workflows/publish-tags.yml: -------------------------------------------------------------------------------- 1 | name: Publish wheels 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - "*" 7 | tags: 8 | - "*" 9 | 10 | jobs: 11 | build_wheels: 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up Python 3.10 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: "3.10" 20 | 21 | - name: Build Wheels 22 | run: | 23 | pip install -r requirements_dev.txt 24 | python -m build --wheel 25 | 26 | - name: Upload wheels 27 | uses: actions/upload-artifact@v2 28 | with: 29 | path: dist/*.whl 30 | 31 | upload_all: 32 | needs: [build_wheels] 33 | runs-on: ubuntu-latest 34 | 35 | steps: 36 | - name: Set up python 37 | uses: actions/setup-python@v2 38 | with: 39 | python-version: "3.10" 40 | 41 | - name: Download artifact 42 | uses: actions/download-artifact@v2 43 | with: 44 | name: artifact 45 | path: dist 46 | 47 | - uses: pypa/gh-action-pypi-publish@v1.4.2 48 | with: 49 | user: nilsnolde 50 | password: ${{ secrets.PYPI_PASS }} 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | routingpy/__version__.py 2 | examples/*with_keys* 3 | **/.ipynb* 4 | conda/ 5 | dist/ 6 | *egg-info/** 7 | .coverage 8 | htmlcov/ 9 | **/build 10 | examples.py 11 | test.py 12 | .venv/ 13 | *.pyc 14 | *.idea/ 15 | .DS_Store 16 | 17 | # Visual Studio Code 18 | .vscode 19 | .history 20 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/psf/black 3 | rev: 23.9.1 4 | hooks: 5 | - id: black 6 | language_version: python3 7 | # temp exlude osrm: black fails to reformat for some reason 8 | args: [routingpy, tests, --exclude, routingpy/routers/mapbox_osrm.py] 9 | - repo: https://github.com/charliermarsh/ruff-pre-commit 10 | rev: v0.0.290 11 | hooks: 12 | - id: ruff 13 | - repo: https://github.com/pycqa/isort 14 | rev: 5.12.0 15 | hooks: 16 | - id: isort 17 | name: isort (python) 18 | args: [--filter-files] 19 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | build: 4 | os: ubuntu-20.04 5 | tools: 6 | python: "3.9" 7 | 8 | sphinx: 9 | configuration: docs/conf.py 10 | 11 | python: 12 | install: 13 | - requirements: requirements_dev.txt 14 | -------------------------------------------------------------------------------- /AUTHORS.md: -------------------------------------------------------------------------------- 1 | Nils Nolde 2 | Timothy Ellersiek 3 | Christian Beiwinkel 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 6 | 7 | **Unreleased** is available in Github's `master` branch, but not on PyPI. 8 | 9 | ## **Unreleased** 10 | 11 | ### Fixed 12 | 13 | - Fixes taking into account the `preference` parameter when calculating isochrones and matrix with Valhalla ([#120](https://github.com/gis-ops/routingpy/issues/120)) 14 | - Google's matrix checks each response element's status code [#122](https://github.com/gis-ops/routingpy/pull/122) 15 | 16 | ## [v1.3.0](https://pypi.org/project/routingpy/1.3.0/) 17 | 18 | ### Added 19 | - Valhalla `/expansion` examples in the Jupyter Notebook 20 | - OpenTripPlanner v2 support for routing & isochrones 21 | 22 | ### Fixed 23 | - Google router's `duration` and `distance` attributes not being calculated correctly in single route response ([#107](https://github.com/gis-ops/routingpy/issues/107)) 24 | - pointer issue when requesting multiple times with the same connection 25 | 26 | ### Removed 27 | - `MapboxValhalla` provider, since Mapbox doesn't expose a public Valhalla endpoint anymore 28 | 29 | ## [v1.2.1](https://pypi.org/project/routingpy/1.2.1/) 30 | ### Fixed 31 | - Graphhopper 7.0 deprecated the "vehicle" parameter for the new "profile" parammeter 32 | 33 | 34 | ## [v1.2.0](https://pypi.org/project/routingpy/1.2.0/) 35 | ### Fixed 36 | - Unit conversion did not work properly in ors' directions method 37 | - Docstring for `intersections` parameter in ors' isochrones method was missing 38 | - `profile` parameter was unnecessarily passed to POST params in ors' isochrones and matrix methods 39 | - switched Graphhopper to POST endpoints & fixed any outdated parameters 40 | 41 | ## [v1.1.0](https://pypi.org/project/routingpy/1.1.0/) 42 | 43 | ### Added 44 | - Added Valhalla's trace_attributes endpoint 45 | 46 | ## [v1.0.4](https://pypi.org/project/routingpy/1.0.4/) 47 | 48 | ### Fixed 49 | - Passing a Valhalla.Waypoint to isochrones resulted in an unhandled exception 50 | 51 | ## [v1.0.3](https://pypi.org/project/routingpy/1.0.3/) 52 | 53 | ### Fixed 54 | - OSRM does have a weird URL concept for profiles, so revert [#64](https://github.com/gis-ops/routing-py/issues/64)) 55 | 56 | ### Added 57 | - `interval_type` to `Isochrone` and `Expansions` objects 58 | 59 | ## [v1.0.2](https://pypi.org/project/routingpy/1.0.2/) 60 | 61 | ### Fixed 62 | - Valhalla's 'matrix' endpoint couldn't deal with NULL entries 63 | 64 | ## [v1.0.0](https://pypi.org/project/routingpy/1.0.0/) 65 | 66 | ### Changed 67 | - made all `parse_*` functions public so they can be used by super projects 68 | 69 | ### Fixed 70 | - OSRM wasn't requesting the right endpoints: profile is meaningless 71 | - GraphHopper parsing fails with not encoded points ([#54](https://github.com/gis-ops/routing-py/issues/54)) 72 | - Allow "narrative" argument for Valhalla's directions endpoint 73 | 74 | ## [0.4.0](https://pypi.org/project/routingpy/0.4.0/) 75 | 76 | ### Added 77 | - support for Valhalla's `/expansion` endpoint 78 | - support for HereMaps kwargs arguments 79 | 80 | ### Fixed 81 | - enhanced error handling for directions with Google [#15](https://github.com/gis-ops/routing-py/issues/15) 82 | - fixed MapboxOSRM client, removing unused parameters and unifying Isochrones interface [#21](https://github.com/gis-ops/routing-py/issues/21) 83 | - fixed bug that caused HereMaps client to use wrong API endpoints [#28](https://github.com/gis-ops/routing-py/pull/28) 84 | - fixed bug that caused HereMaps Isochrones to return lists of `list_reverseiterator`s instead of coordinates [#29](https://github.com/gis-ops/routing-py/issues/29) 85 | - updated jupyter notebooks examples 86 | - switched coordinate order of OSRM 87 | - if no get_params are defined, omit "?" from the request URL 88 | 89 | ### Changed 90 | 91 | - BREAKING: pulled client stuff into a separate Client class which gets passed to the individual router instances with the default being the same as before [#24](https://github.com/gis-ops/routing-py/pull/24) 92 | 93 | 94 | ## [0.3.3](https://github.com/gis-ops/routing-py/releases/tag/0.3.3) 95 | ### Added 96 | - 2020/2021 Valhalla HTTP API improvements 97 | ### Fixed 98 | - README local OSRM description 99 | 100 | ## [0.3.2](https://github.com/gis-ops/routing-py/releases/tag/0.3.2) 101 | ### Fixed 102 | - HERE isochrones had lat, lon instead of lon, lat ([#14](https://github.com/gis-ops/routing-py/issues/14)) 103 | 104 | ## [0.3.1](https://github.com/gis-ops/routing-py/releases/tag/0.3.2) 105 | ### Fixed 106 | - HERE routers can now also be used with api key 107 | - HERE isochrones had lat, lon instead of lon, lat ([#14](https://github.com/gis-ops/routing-py/issues/14)) 108 | - Set Google router's profile queryparam correctly (was set to "profile" now is "mode") 109 | 110 | ## [0.3.0](https://github.com/gis-ops/routing-py/releases/tag/0.3.0) 2020-08-09 111 | ### Added 112 | - GeoJSON support for Graphhopper's isochrones 113 | - [MyBinder](https://mybinder.org/v2/gh/gis-ops/routing-py/master?filepath=examples) notebook collection 114 | ### Fixed 115 | - Add departure and arrival parameter for HERE isochrones API 116 | - OSRM Mapbox isochrone ranges were using floats (#2) 117 | - OSRM matrix ouputs distances array now (#6) 118 | - Graphhopper isochrones used wrong vehicle parameter 119 | ### Changed 120 | - Profile parameter for HERE behaves now like other routers 121 | - ORS alternative_routes parameter (#4) 122 | - Brought Graphhopper support to its v1.x release 123 | - Minimum Python version > 3.6.1 (for Pandas 1.x) 124 | ### Deprecated 125 | - 126 | 127 | ## [0.2](https://github.com/gis-ops/routing-py/releases/tag/v0.2) 2019-04-30 128 | ### Added 129 | - Example notebook to compare providers 130 | ### Fixed 131 | - Here matrix did not allow `sources` and `destinations` to be optional 132 | - Base class used sorted(params) which messed up the order of parameters for Graphhopper endpoints 133 | - MapboxOSRM directions was parsing geometry to \[lat, lon\] 134 | - README not valid on PyPI, wasn't rendered 135 | - add to PyPI and Conda 136 | ### Changed 137 | - 138 | ### Deprecated 139 | - 140 | 141 | ## [0.1 - First Release](https://github.com/gis-ops/routing-py/releases/tag/v0.1) 2019-04-14 142 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Thanks for considering to make a contribution to the vast landscape of routing engine APIs. We'd be really happy to 4 | eventually be able to cover all remote open source routing API's, but have to rely on community contributions as this is a big task. 5 | 6 | > Note: when this project first came about, the goal was to support commercial and open source APIs. This has since changed and we only focus on the open source ones these days, eventually phasing out the commercial ones as they grow stale. 7 | 8 | ## Table of Contents 9 | 10 | 11 | 12 | - [Issues](#issues) 13 | - [Submitting fixes](#submitting-fixes) 14 | - [Setup](#setup) 15 | - [Tests](#tests) 16 | - [Documentation](#documentation) 17 | - [Adding router](#adding-router) 18 | 19 | 20 | 21 | ## Issues 22 | 23 | - Please only submit actual technical issues and use [Stack Overflow](stackoverflow.com/) for questions using the tag `routingpy`. 24 | 25 | - Please make sure you don't submit a duplicate by browsing open and closed issues first and consult the [CHANGELOG](https://github.com/gis-ops/routingpy/blob/master/CHANGELOG.md) for already fixed issues 26 | 27 | ## Pull requests 28 | 29 | > **Important note**: please open an issue before starting to work on a fix or feature. This helps you save time and frustration. :-) 30 | 31 | We welcome patches and fixes to existing clients and want to make sure everything goes smoothly for you while submitting a PR. 32 | 33 | We use the PSF's [`black`](https://github.com/psf/black) to make sure the code style is consistent, and `flake8` as a linter. 34 | 35 | When contributing, we expect you to: 36 | 37 | - close an existing issue. If there is none yet for your fix, please [create one](https://github.com/gis-ops/routingpy/issues/new). 38 | - write/adapt unit tests and/or mock API tests, depending on the introduced or fixed functionality 39 | - limit the number of commits to a minimum, i.e. responsible use of [`git commit --amend [--no-edit]`](https://www.atlassian.com/git/tutorials/rewriting-history#git-commit--amend) 40 | - use meaningful commit messages, e.g. `commit -m "[bugfix] heremaps used [lat, long] as locations input parameter"` 41 | - you can branch off `master` and put a PR against `master` as well 42 | 43 | ### Setup 44 | 45 | 1. Create and activate a new virtual environment (optional, but recommended): 46 | 47 | ```bash 48 | # From the root of your git project 49 | python -m venv .venv 50 | source .venv/bin/activate 51 | ``` 52 | 53 | 2. Install development dependencies: 54 | 55 | ```bash 56 | # From the root of your git project 57 | pip install -r requirements_dev.txt 58 | # or 59 | poetry install 60 | ``` 61 | 62 | 3. Run tests to check if all goes well: 63 | 64 | ```bash 65 | # From the root of your git project 66 | pytest -v 67 | ``` 68 | 69 | 4. Please install the pre-commit hook, so your code gets auto-formatted and linted before committing it: 70 | 71 | ```bash 72 | # From the root of your git project 73 | pre-commit install 74 | ``` 75 | 76 | ### Tests 77 | 78 | We only do mocked tests as routing results heavily depend on underlying data, which, at least in the case of the FOSS routing 79 | engines, changes on a very regular basis due to OpenStreetMap updates. All queries and most mocked responses are located in 80 | `test/test_helper.py` in `dict`s. This unfortunately also means, that our tests are less API tests and more unit tests and can't catch 81 | updates on providers' API changes. 82 | 83 | ```bash 84 | # From the root of your git project 85 | coverage run --source=routingpy --module pytest 86 | ``` 87 | 88 | ### Documentation 89 | 90 | If you add or remove new functionality which is exposed to the user/developer, please make sure to document these in the 91 | docstrings. To build the documentation: 92 | 93 | ```bash 94 | # From the root of your git project 95 | cd docs 96 | make hmtl 97 | ``` 98 | 99 | The documentation will have been added to `routingpy/docs/build/html` and you can open `index.html` in your web browser to view 100 | the changes. 101 | 102 | We realize that _re-structured text_ is not the most user-friendly format, but it is the currently best available 103 | documentation format for Python projects. You'll find lots of copy/paste material in the existing implementations. 104 | 105 | ## Adding router 106 | 107 | Let's add all the open source routers in the world:) 108 | 109 | It's really easy: 110 | 111 | 1. **New class** Create a new router module in `routingpy/routers` and base the new class on `routingpy/routers/base.py:Router`. 112 | Also, check if the service hasn't been added before. E.g. if the router 113 | you want to add is based on `GraphHopper`, you probably want to subclass `routingpy/routers/graphhopper.py:Graphhopper` class. 114 | Additionally, import the new router class in `routingpy/routers/init.py`. 115 | 116 | 2. **Implementations** Implement the services the routing engine has to offer. The bare minimum is implementing the `directions` method. 117 | If the routing engine also offers `isochrones` and `matrix`, we'd require you to add those too. If you want to add an 118 | endpoint that doesn't exist yet in `routingpy/routers/base.py:Router`, please [consult us first](mailto:enquiry@gis-ops.com?subject=contributing%20to%20routingpy), as we need to make sure 119 | to be similarly consistent across different routing engines as we are with the existing endpoints. 120 | 121 | 3. **Tests** Create a new test module testing the functionality, **not** the API. 122 | Use `@responses.activate` decorators for this. 123 | To run the new tests and ensure consistency, refer to the [Tests](#tests) section above. **Don't store secrets** in the tests. 124 | 125 | 4. **Document** Please use docstring documentation for all user-exposed functionality, similar to other router implementations. 126 | Also, please register the new module in `docs/indes.rst`'s `Routers` section. To build the docs, refer to the 127 | [documentation section](#documentation) for details. Don't forget to add your name to the list of `AUTHORS.md`. 128 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | #### Here's what I did 6 | 7 | 8 | --- 9 | #### Here's what I got 10 | 11 | 12 | --- 13 | #### Here's what I was expecting 14 | 15 | 16 | --- 17 | #### Here's what I think could be improved 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.md 2 | include LICENSE 3 | include README.rst 4 | recursive-exclude tests * 5 | global-exclude __pycache__ 6 | global-exclude *.py[co] 7 | global-exclude .DS_Store -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | In case anyone has interest to take over this repository, please write me on my public email. To be eligible you should have a proven track record of FOSS python projects and ideally some PyPI package management experience. 2 | 3 | routingpy 4 | ========== 5 | 6 | .. image:: https://github.com/gis-ops/routing-py/workflows/tests/badge.svg 7 | :target: https://github.com/gis-ops/routing-py/actions/workflows/ci-tests.yml 8 | :alt: tests 9 | 10 | .. image:: https://readthedocs.org/projects/routingpy/badge/?version=latest 11 | :target: https://routingpy.readthedocs.io/en/latest/?badge=latest 12 | :alt: Documentation Status 13 | 14 | .. image:: https://mybinder.org/badge_logo.svg 15 | :target: https://mybinder.org/v2/gh/gis-ops/routing-py/master?filepath=examples 16 | :alt: MyBinder.org 17 | 18 | 19 | *One lib to route them all* - **routingpy** is a Python 3 client for several 20 | popular routing webservices. 21 | 22 | Inspired by `geopy `_ and its great community of contributors, **routingpy** enables 23 | easy and consistent access to third-party spatial webservices to request **route directions**, **isochrones** 24 | or **time-distance matrices**. 25 | 26 | **routingpy** currently includes support for the following services: 27 | 28 | - `Mapbox, OSRM`_ 29 | - `Openrouteservice`_ 30 | - `Here Maps`_ 31 | - `Google Maps`_ 32 | - `Graphhopper`_ 33 | - `OpenTripPlannerV2`_ 34 | - `Local Valhalla`_ 35 | - `Local OSRM`_ 36 | 37 | This list is hopefully growing with time and contributions by other developers. An up-to-date list is always available 38 | in our documentation_. 39 | 40 | **routing-py** is tested against CPython versions 3.8, 3.9, 3.10, 3.11. PyPy3 is currently not supported, see `#60 `_. 41 | 42 | © routingpy contributors 2022 under the `Apache 2.0 License`_. 43 | 44 | .. image:: https://user-images.githubusercontent.com/10322094/57357720-e180c080-7173-11e9-97a4-cecb4670065d.jpg 45 | :alt: routing-py-image 46 | 47 | 48 | Why routingpy? 49 | --------------- 50 | 51 | You want to 52 | 53 | - get from A to B by transit, foot, bike, car or hgv 54 | - compute a region of reachability 55 | - calculate a time distance matrix for a N x M table 56 | 57 | and don't know which provider to use? Great. Then **routingpy** is exactly what you're looking for. 58 | 59 | For the better or worse, every provider works on different spatial global datasets and uses a plethora of algorithms on top. 60 | While Google or HERE build on top of proprietary datasets, providers such as Mapbox or Graphhopper consume OpenStreetMap data 61 | for their base network. Also, all providers offer a different amount of options one can use to restrict the wayfinding. 62 | Ultimately this means that **results may differ** - and our experience tells us: they do, and not 63 | too little. This calls for a careful evaluation which service provider to use for which specific use case. 64 | 65 | With **routingpy** we have made an attempt to simplify this process for you. 66 | 67 | Installation 68 | ------------ 69 | 70 | .. image:: https://badge.fury.io/py/routingpy.svg 71 | :target: https://badge.fury.io/py/routingpy 72 | :alt: PyPI version 73 | 74 | **Recommended**: Install via poetry_: 75 | 76 | .. code:: bash 77 | 78 | poetry add routingpy 79 | 80 | Install using ``pip`` with 81 | 82 | .. code:: bash 83 | 84 | pip install routingpy 85 | 86 | Or the lastest from source 87 | 88 | .. code:: bash 89 | 90 | pip install git+git://github.com/gis-ops/routingpy 91 | 92 | 93 | API 94 | ----------- 95 | 96 | Every provider has its own specifications and features. However the basic blueprints are the same across all. We tried hard 97 | to make the transition from one provider to the other as seamless as possible. We follow two dogmas for all implementations: 98 | 99 | - All basic parameters have to be the same for all routers for each endpoint 100 | 101 | - All routers still retain their special parameters for their endpoints, which make them unique in the end 102 | 103 | This naturally means that usually those **basic parameters are not named the same way** as the endpoints they query. However, 104 | all **provider specific parameters are named the exact same** as their remote counterparts. 105 | 106 | The following table gives you an overview which basic arguments are abstracted: 107 | 108 | +-----------------------+-------------------+--------------------------------------------------------------+ 109 | | Endpoint | Argument | Function | 110 | +=======================+===================+==============================================================+ 111 | | ``directions`` | locations | | Specify the locations to be visited in order. Usually this | 112 | | | | | is done with ``[Lon, Lat]`` tuples, but some routers offer | 113 | | | | | additional options to create a location element. | 114 | | +-------------------+--------------------------------------------------------------+ 115 | | | profile | | The mode of transport, i.e. car, bicycle, pedestrian. Each | 116 | | | | | router specifies their own profiles. | 117 | +-----------------------+-------------------+--------------------------------------------------------------+ 118 | | ``isochrones`` | locations | | Specify the locations to calculate isochrones for. Usually | 119 | | | | | this is done with ``[Lon, Lat]`` tuples, but some routers | 120 | | | | | offer additional options to create a location element. | 121 | | +-------------------+--------------------------------------------------------------+ 122 | | | profile | | The mode of transport, i.e. car, bicycle, pedestrian. Each | 123 | | | | | router specifies their own profiles. | 124 | | +-------------------+--------------------------------------------------------------+ 125 | | | intervals | | The ranges to calculate isochrones for. Either in seconds | 126 | | | | | or in meters, depending on ``interval_type``. | 127 | | +-------------------+--------------------------------------------------------------+ 128 | | | intervals _type | | The dimension of ``intervals``, which takes router | 129 | | | | | dependent values, but generally describes time or distance | 130 | +-----------------------+-------------------+--------------------------------------------------------------+ 131 | | ``matrix`` | locations | | Specify all locations you want to calculate a matrix | 132 | | | | | for. If ``sources`` or ``destinations`` is not set, this | 133 | | | | | will return a symmetrical matrix. Usually this is done | 134 | | | | | with ``[Lon, Lat]`` tuples, but some routers offer | 135 | | | | | additional options to create a location element. | 136 | | +-------------------+--------------------------------------------------------------+ 137 | | | profile | | The mode of transport, i.e. car, bicycle, pedestrian. Each | 138 | | | | | router specifies their own profiles. | 139 | | +-------------------+--------------------------------------------------------------+ 140 | | | sources | | The indices of the ``locations`` parameter iterable to | 141 | | | | | take as sources for the matrix calculation. If not | 142 | | | | | specified all ``locations`` are considered to be sources. | 143 | | +-------------------+--------------------------------------------------------------+ 144 | | | destinations | | The indices of the ``locations`` parameter iterable to | 145 | | | | | take as destinations for the matrix calculation. If not | 146 | | | | | specified all ``locations`` are considered to be | 147 | | | | | destinations. | 148 | +-----------------------+-------------------+--------------------------------------------------------------+ 149 | 150 | Contributing 151 | ------------ 152 | 153 | We :heart: contributions and realistically think that's the only way to support and maintain most 154 | routing engines in the long run. To get you started, we created a `Contribution guideline <./CONTRIBUTING.md>`_. 155 | 156 | Examples 157 | -------- 158 | 159 | Follow our examples to understand how simple **routingpy** is to use. 160 | 161 | On top of the examples listed below, find interactive notebook(s) on mybinder.org_. 162 | 163 | Basic Usage 164 | ~~~~~~~~~~~ 165 | 166 | Get all attributes 167 | ++++++++++++++++++ 168 | 169 | **routingpy** is designed to take the burden off your shoulder to parse the JSON response of each provider, exposing 170 | the most important information of the response as attributes of the response object. The actual JSON is always accessible via 171 | the ``raw`` attribute: 172 | 173 | .. code:: python 174 | 175 | from routingpy import Valhalla 176 | from pprint import pprint 177 | 178 | # Some locations in Berlin 179 | coords = [[13.413706, 52.490202], [13.421838, 52.514105], 180 | [13.453649, 52.507987], [13.401947, 52.543373]] 181 | client = Valhalla() 182 | 183 | route = client.directions(locations=coords, profile='pedestrian') 184 | isochrones = client.isochrones(locations=coords[0], profile='pedestrian', intervals=[600, 1200]) 185 | matrix = client.matrix(locations=coords, profile='pedestrian') 186 | 187 | pprint((route.geometry, route.duration, route.distance, route.raw)) 188 | pprint((isochrones.raw, isochrones[0].geometry, isochrones[0].center, isochrones[0].interval)) 189 | pprint((matrix.durations, matrix.distances, matrix.raw)) 190 | 191 | 192 | Multi Provider 193 | ++++++++++++++ 194 | 195 | Easily calculate routes, isochrones and matrices for multiple providers: 196 | 197 | .. code:: python 198 | 199 | from routingpy import Graphhopper, ORS, MapboxOSRM 200 | from shapely.geometry import Polygon 201 | 202 | # Define the clients and their profile parameter 203 | apis = ( 204 | (ORS(api_key='ors_key'), 'cycling-regular'), 205 | (Graphhopper(api_key='gh_key'), 'bike'), 206 | (MapboxOSRM(api_key='mapbox_key'), 'cycling') 207 | ) 208 | # Some locations in Berlin 209 | coords = [[13.413706, 52.490202], [13.421838, 52.514105], 210 | [13.453649, 52.507987], [13.401947, 52.543373]] 211 | 212 | for api in apis: 213 | client, profile = api 214 | route = client.directions(locations=coords, profile=profile) 215 | print("Direction - {}:\n\tDuration: {}\n\tDistance: {}".format(client.__class__.__name__, 216 | route.duration, 217 | route.distance)) 218 | isochrones = client.isochrones(locations=coords[0], profile=profile, intervals=[600, 1200]) 219 | for iso in isochrones: 220 | print("Isochrone {} secs - {}:\n\tArea: {} sqm".format(client.__class__.__name__, 221 | iso.interval, 222 | Polygon(iso.geometry).area)) 223 | matrix = client.matrix(locations=coords, profile=profile) 224 | print("Matrix - {}:\n\tDurations: {}\n\tDistances: {}".format(client.__class__.__name__, 225 | matrix.durations, 226 | matrix.distances)) 227 | 228 | 229 | Dry run - Debug 230 | +++++++++++++++ 231 | 232 | Often it is crucial to examine the request before it is sent. Mostly useful for debugging: 233 | 234 | .. code:: python 235 | 236 | from routingpy import ORS 237 | 238 | client = ORS(api_key='ors_key') 239 | route = client.directions( 240 | locations = [[13.413706, 52.490202], [13.421838, 52.514105]], 241 | profile='driving-hgv', 242 | dry_run=True 243 | ) 244 | 245 | 246 | Advanced Usage 247 | ~~~~~~~~~~~~~~ 248 | 249 | Local instance of FOSS router 250 | +++++++++++++++++++++++++++++ 251 | 252 | All FOSS routing engines can be run locally, such as openrouteservice, Valhalla, OSRM and GraphHopper. To be able 253 | to use **routingpy** with a local installation, just change the ``base_url`` of the client. This assumes that you did 254 | not change the URL(s) of the exposed endpoint(s): 255 | 256 | .. code:: python 257 | 258 | from routingpy import Valhalla 259 | 260 | # no trailing slash, api_key is not necessary 261 | client = Valhalla(base_url='http://localhost:8088/v1') 262 | 263 | Proxies, Rate limiters and API errors 264 | +++++++++++++++++++++++++++++++++++++ 265 | 266 | Proxies are easily set up using following ``requests`` scheme for proxying. Also, when batch requesting, **routingpy** 267 | can be set up to resume its requests when the remote API rate limits (i.e. responds 268 | with HTTP 429). Also, it can be set up to ignore API errors and instead print them as warnings to ``stdout``. Be careful, 269 | when ignoring ``RouterApiErrors``, those often count towards your rate limit. 270 | 271 | All these parameters, and more, can optionally be **globally set** for all router modules or individually per instance: 272 | 273 | .. code:: python 274 | 275 | from routingpy import Graphhopper, ORS 276 | from routingpy.routers import options 277 | 278 | request_kwargs = dict(proxies=dict(https='129.125.12.0')) 279 | 280 | client = Graphhopper( 281 | api_key='gh_key', 282 | retry_over_query_limit=False, 283 | skip_api_error=True, 284 | requests_kwargs=request_kwargs 285 | ) 286 | 287 | # Or alternvatively, set these options globally: 288 | options.default_proxies = {'https': '129.125.12.0'} 289 | options.default_retry_over_query_limit = False 290 | options.default_skip_api_error = True 291 | 292 | 293 | .. _Mapbox, OSRM: https://docs.mapbox.com/api/navigation 294 | .. _Openrouteservice: https://openrouteservice.org/dev/#/api-docs 295 | .. _Here Maps: https://developer.here.com/documentation 296 | .. _Google Maps: https://developers.google.com/maps/documentation 297 | .. _Graphhopper: https://graphhopper.com/api/1/docs 298 | .. _OpenTripPlannerV2: https://docs.opentripplanner.org/en/latest/ 299 | .. _Local Valhalla: https://valhalla.github.io/valhalla/ 300 | .. _Local OSRM: https://github.com/Project-OSRM/osrm-backend/wiki 301 | .. _documentation: https://routingpy.readthedocs.io/en/latest 302 | .. _routing-py.routers: https://routingpy.readthedocs.io/en/latest/#module-routingpy.routers 303 | .. _Apache 2.0 License: https://github.com/gis-ops/routing-py/blob/master/LICENSE 304 | .. _mybinder.org: https://mybinder.org/v2/gh/gis-ops/routing-py/master?filepath=examples 305 | .. _poetry: https://github.com/sdispater/poetry 306 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -m sphinx 7 | SPHINXPROJ = routing-py 8 | SOURCEDIR = . 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # GeoPy documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Oct 24 19:28:11 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import os 16 | import sys 17 | 18 | sys.path.insert(0, os.path.abspath("..")) 19 | 20 | # If extensions (or modules to document with autodoc) are in another directory, 21 | # add these directories to sys.path here. If the directory is relative to the 22 | # documentation root, use os.path.abspath to make it absolute, like shown here. 23 | # sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinxnotes.strike"] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ["_templates"] 37 | 38 | # The suffix of source filenames. 39 | source_suffix = ".rst" 40 | 41 | # The encoding of source files. 42 | # source_encoding = 'utf-8-sig' 43 | 44 | # The master toctree document. 45 | master_doc = "index" 46 | 47 | # General information about the project. 48 | project = "routingpy" 49 | copyright = "2022, routingpy Contributors" 50 | 51 | # The version info for the project you're documenting, acts as replacement for 52 | # |version| and |release|, also used in various other places throughout the 53 | # built documents. 54 | # 55 | # The full version, including alpha/beta/rc tags. 56 | version = "" 57 | release = "" 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | # language = None 62 | 63 | # There are two options for replacing |today|: either, you set today to some 64 | # non-false value, then it is used: 65 | # today = '' 66 | # Else, today_fmt is used as the format for a strftime call. 67 | # today_fmt = '%B %d, %Y' 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | exclude_patterns = ["_build"] 72 | 73 | # The reST default role (used for this markup: `text`) to use for all 74 | # documents. 75 | # default_role = None 76 | 77 | # If true, '()' will be appended to :func: etc. cross-reference text. 78 | # add_function_parentheses = True 79 | 80 | # If true, the current module name will be prepended to all description 81 | # unit titles (such as .. function::). 82 | # add_module_names = True 83 | 84 | # If true, sectionauthor and moduleauthor directives will be shown in the 85 | # output. They are ignored by default. 86 | # show_authors = False 87 | 88 | # The name of the Pygments (syntax highlighting) style to use. 89 | pygments_style = "default" 90 | 91 | # A list of ignored prefixes for module index sorting. 92 | # modindex_common_prefix = [] 93 | 94 | # If true, keep warnings as "system message" paragraphs in the built documents. 95 | # keep_warnings = False 96 | 97 | # -- Options for HTML output ---------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = "sphinx_rtd_theme" 102 | # html_theme = 'alabaster' 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | # html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | # html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | # html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | # html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | # html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | # TODO: add favicon (and icon) 126 | # html_favicon = '_static/favicon.ico' 127 | 128 | # Add any paths that contain custom static files (such as style sheets) here, 129 | # relative to this directory. They are copied after the builtin static files, 130 | # so a file named "default.css" will overwrite the builtin "default.css". 131 | html_static_path = ["_static"] 132 | 133 | # Add any extra paths that contain custom files (such as robots.txt or 134 | # .htaccess) here, relative to this directory. These files are copied 135 | # directly to the root of the documentation. 136 | # html_extra_path = [] 137 | 138 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 139 | # using the given strftime format. 140 | # html_last_updated_fmt = '%b %d, %Y' 141 | 142 | # If true, SmartyPants will be used to convert quotes and dashes to 143 | # typographically correct entities. 144 | # html_use_smartypants = True 145 | 146 | # Custom sidebar templates, maps document names to template names. 147 | # html_sidebars = {} 148 | 149 | # Additional templates that should be rendered to pages, maps page names to 150 | # template names. 151 | # html_additional_pages = {} 152 | 153 | # If false, no module index is generated. 154 | # html_domain_indices = True 155 | 156 | # If false, no index is generated. 157 | # html_use_index = True 158 | 159 | # If true, the index is split into individual pages for each letter. 160 | # html_split_index = False 161 | 162 | # If true, links to the reST sources are added to the pages. 163 | # html_show_sourcelink = True 164 | 165 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 166 | # html_show_sphinx = True 167 | 168 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 169 | # html_show_copyright = True 170 | 171 | # If true, an OpenSearch description file will be output, and all pages will 172 | # contain a tag referring to it. The value of this option must be the 173 | # base URL from which the finished HTML is served. 174 | # html_use_opensearch = '' 175 | 176 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 177 | # html_file_suffix = None 178 | 179 | # Output file base name for HTML help builder. 180 | htmlhelp_basename = "RoutingPyDoc" 181 | 182 | # # -- Options for LaTeX output --------------------------------------------- 183 | # 184 | # latex_elements = { 185 | # # The paper size ('letterpaper' or 'a4paper'). 186 | # #'papersize': 'letterpaper', 187 | # 188 | # # The font size ('10pt', '11pt' or '12pt'). 189 | # #'pointsize': '10pt', 190 | # 191 | # # Additional stuff for the LaTeX preamble. 192 | # #'preamble': '', 193 | # } 194 | # 195 | # # Grouping the document tree into LaTeX files. List of tuples 196 | # # (source start file, target name, title, 197 | # # author, documentclass [howto, manual, or own class]). 198 | # latex_documents = [ 199 | # ('index', 'GeoPy.tex', 'GeoPy Documentation', 200 | # 'GeoPy Contributors', 'manual'), 201 | # ] 202 | # 203 | # # The name of an image file (relative to this directory) to place at the top of 204 | # # the title page. 205 | # #latex_logo = None 206 | # 207 | # # For "manual" documents, if this is true, then toplevel headings are parts, 208 | # # not chapters. 209 | # #latex_use_parts = False 210 | # 211 | # # If true, show page references after internal links. 212 | # #latex_show_pagerefs = False 213 | # 214 | # # If true, show URL addresses after external links. 215 | # #latex_show_urls = False 216 | # 217 | # # Documents to append as an appendix to all manuals. 218 | # #latex_appendices = [] 219 | # 220 | # # If false, no module index is generated. 221 | # #latex_domain_indices = True 222 | # 223 | # 224 | # # -- Options for manual page output --------------------------------------- 225 | # 226 | # # One entry per manual page. List of tuples 227 | # # (source start file, name, description, authors, manual section). 228 | # man_pages = [ 229 | # ('index', 'geopy', 'GeoPy Documentation', 230 | # ['GeoPy Contributors'], 1) 231 | # ] 232 | # 233 | # # If true, show URL addresses after external links. 234 | # #man_show_urls = False 235 | # 236 | # 237 | # # -- Options for Texinfo output ------------------------------------------- 238 | # 239 | # # Grouping the document tree into Texinfo files. List of tuples 240 | # # (source start file, target name, title, author, 241 | # # dir menu entry, description, category) 242 | # texinfo_documents = [ 243 | # ('index', 'GeoPy', 'GeoPy Documentation', 244 | # 'GeoPy Contributors', 'GeoPy', 'One line description of project.', 245 | # 'Miscellaneous'), 246 | # ] 247 | # 248 | # # Documents to append as an appendix to all manuals. 249 | # #texinfo_appendices = [] 250 | # 251 | # # If false, no module index is generated. 252 | # #texinfo_domain_indices = True 253 | # 254 | # # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | # #texinfo_show_urls = 'footnote' 256 | # 257 | # # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | # #texinfo_no_detailmenu = False 259 | # 260 | # 261 | # # Example configuration for intersphinx: refer to the Python standard library. 262 | # intersphinx_mapping = {'http://docs.python.org/': None} 263 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to routingpy's documentation! 2 | ===================================== 3 | 4 | :Documentation: https://routingpy.readthedocs.io/ 5 | :Source Code: https://github.com/gis-ops/routing-py 6 | :Issue Tracker: https://github.com/gis-ops/routing-py/issues 7 | :PyPI: https://pypi.org/project/routingpy 8 | :MyBinder Interactive Examples: https://mybinder.org/v2/gh/gis-ops/routing-py/master?filepath=examples 9 | 10 | .. automodule:: routingpy 11 | :members: __doc__ 12 | 13 | .. toctree:: 14 | :maxdepth: 4 15 | :caption: Contents 16 | 17 | index 18 | 19 | 20 | Installation 21 | ~~~~~~~~~~~~ 22 | 23 | :: 24 | 25 | pip install routingpy 26 | 27 | Routers 28 | ~~~~~~~~~ 29 | 30 | .. automodule:: routingpy.routers 31 | :members: __doc__ 32 | 33 | .. autofunction:: routingpy.routers.get_router_by_name 34 | 35 | Default Options Object 36 | ---------------------- 37 | 38 | .. autoclass:: routingpy.routers.options 39 | :members: 40 | :undoc-members: 41 | 42 | Google 43 | ------ 44 | 45 | .. autoclass:: routingpy.routers.Google 46 | :members: 47 | 48 | .. automethod:: __init__ 49 | 50 | Graphhopper 51 | ----------- 52 | 53 | .. autoclass:: routingpy.routers.Graphhopper 54 | :members: 55 | 56 | .. automethod:: __init__ 57 | 58 | HereMaps 59 | -------- 60 | 61 | .. autoclass:: routingpy.routers.HereMaps 62 | :members: 63 | 64 | .. automethod:: __init__ 65 | 66 | MapboxOSRM 67 | ---------- 68 | 69 | .. autoclass:: routingpy.routers.MapboxOSRM 70 | :members: 71 | 72 | .. automethod:: __init__ 73 | 74 | MapboxValhalla 75 | -------------- 76 | 77 | .. autoclass:: routingpy.routers.MapboxValhalla 78 | :members: 79 | :inherited-members: 80 | :show-inheritance: 81 | 82 | .. automethod:: __init__ 83 | 84 | OpenTripPlannerV2 85 | -------------- 86 | 87 | .. autoclass:: routingpy.routers.OpenTripPlannerV2 88 | :members: 89 | :inherited-members: 90 | :show-inheritance: 91 | 92 | .. automethod:: __init__ 93 | 94 | ORS 95 | --- 96 | 97 | .. autoclass:: routingpy.routers.ORS 98 | :members: 99 | 100 | .. automethod:: __init__ 101 | 102 | OSRM 103 | ---- 104 | 105 | .. autoclass:: routingpy.routers.OSRM 106 | :members: 107 | 108 | .. automethod:: __init__ 109 | 110 | Valhalla 111 | -------- 112 | 113 | .. autoclass:: routingpy.routers.Valhalla 114 | :members: 115 | 116 | .. automethod:: __init__ 117 | 118 | Client 119 | ~~~~~~~ 120 | .. autoclass:: routingpy.client_default.Client 121 | :members: 122 | 123 | .. automethod:: __init__ 124 | 125 | Data 126 | ~~~~ 127 | 128 | .. autoclass:: routingpy.direction.Directions 129 | :members: raw 130 | 131 | .. autoclass:: routingpy.direction.Direction 132 | :members: geometry, duration, distance 133 | 134 | .. autoclass:: routingpy.isochrone.Isochrones 135 | :members: raw 136 | 137 | .. autoclass:: routingpy.isochrone.Isochrone 138 | :members: geometry, center, range 139 | 140 | .. autoclass:: routingpy.matrix.Matrix 141 | :members: durations, distances, raw 142 | 143 | .. autoclass:: routingpy.expansion.Expansions 144 | :members: expansions, center, raw 145 | 146 | .. autoclass:: routingpy.expansion.Edge 147 | :members: geometry, distance, duration, cost, edge_id, status 148 | 149 | .. autofunction:: routingpy.utils.decode_polyline5 150 | 151 | .. autofunction:: routingpy.utils.decode_polyline6 152 | 153 | Exceptions 154 | ~~~~~~~~~~ 155 | 156 | .. autoclass:: routingpy.exceptions.RouterError 157 | :show-inheritance: 158 | 159 | .. autoclass:: routingpy.exceptions.RouterApiError 160 | :show-inheritance: 161 | 162 | .. autoclass:: routingpy.exceptions.RouterServerError 163 | :show-inheritance: 164 | 165 | .. autoclass:: routingpy.exceptions.RouterNotFound 166 | :show-inheritance: 167 | 168 | .. autoclass:: routingpy.exceptions.Timeout 169 | :show-inheritance: 170 | 171 | .. autoclass:: routingpy.exceptions.RetriableRequest 172 | :show-inheritance: 173 | 174 | .. autoclass:: routingpy.exceptions.OverQueryLimit 175 | :show-inheritance: 176 | 177 | Changelog 178 | ~~~~~~~~~ 179 | 180 | See our `Changelog.md`_. 181 | 182 | .. _Changelog.md: https://github.com/gis-ops/routingpy/CHANGELOG.md 183 | 184 | Indices and search 185 | ================== 186 | 187 | * :ref:`genindex` 188 | * :ref:`search` 189 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: routingpy-examples 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - pandas 7 | - shapely 8 | - contextily 9 | - python 10 | - jupyter 11 | - pyproj 12 | - geopandas 13 | - descartes 14 | - pip: 15 | - routingpy 16 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | ## Jupyter Notebook examples 2 | 3 | We created a small collection of notebook examples to show the basic (and more advanced) usage of **routingpy**. 4 | 5 | This collection is also available as out-of-the-box interactive notebooks on [mybinder.org](https://mybinder.org/v2/gh/gis-ops/routing-py/master?filepath=examples). 6 | 7 | [Contributions](../CONTRIBUTING.md) welcome:) -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=45", "wheel", "setuptools_scm>=6.2"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.poetry] 6 | name = "routingpy" 7 | version = "1.2.1" 8 | description = "One lib to route them all." 9 | authors = [ 10 | "Nils Nolde ", 11 | "Tim Ellersiek ", 12 | "Christian Beiwinkel ", 13 | ] 14 | license = "Apache2" 15 | readme = 'README.rst' 16 | 17 | [tool.poetry.dependencies] 18 | python = "^3.9.0" 19 | requests = "^2.20.0" 20 | # For the Jupyter notebooks: 21 | shapely = { version = "^2.0.0", optional = true } 22 | ipykernel = { version = "^6.0.0", optional = true } 23 | matplotlib = { version = "^3.4.1", optional = true } 24 | contextily = { version = "^1.1.0", optional = true } 25 | geopandas = { version = "^0.8.2", optional = true } 26 | descartes = { version = "^1.0.0", optional = true } 27 | 28 | [tool.poetry.extras] 29 | notebooks = [ 30 | "shapely", 31 | "ipykernel", 32 | "geopandas", 33 | "contextily", 34 | "matplotlib", 35 | "descartes", 36 | ] 37 | 38 | [tool.poetry.group.dev.dependencies] 39 | sphinx = "^4.4.0" 40 | sphinx-rtd-theme = "^1.0.0" 41 | sphinxnotes-strike = "^1.2" 42 | responses = "^0.10.0" 43 | coverage = "^7.0.0" 44 | pre-commit = "^2.7.1" 45 | pytest = "^7.0.0" 46 | build = "^0.7.0" 47 | setuptools-scm = "^7.0.0" 48 | 49 | [tool.setuptools_scm] 50 | write_to = "routingpy/__version__.py" 51 | write_to_template = """ 52 | __version__ = "{version}" 53 | """ 54 | version_scheme = "post-release" 55 | 56 | [tool.black] 57 | line-length = 105 58 | exclude = ''' 59 | /( 60 | \.git 61 | | \.venv 62 | | dist 63 | | build 64 | )/ 65 | ''' 66 | 67 | [tool.isort] 68 | profile = "black" 69 | line_length = 105 70 | src_paths = ["routingpy", "tests"] 71 | skip = [".venv", "build", "dist"] 72 | 73 | [tool.ruff] 74 | # Enable the pycodestyle (`E`) and Pyflakes (`F`) rules by default. 75 | # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or 76 | # McCabe complexity (`C901`) by default. 77 | select = ["E", "F"] 78 | ignore = ["E203", "E266", "E501", "F403", "E722", "F405"] 79 | 80 | # Exclude a variety of commonly ignored directories. 81 | exclude = [ 82 | ".bzr", 83 | ".direnv", 84 | ".eggs", 85 | ".git", 86 | ".git-rewrite", 87 | ".hg", 88 | ".mypy_cache", 89 | ".nox", 90 | ".pants.d", 91 | ".pytype", 92 | ".ruff_cache", 93 | ".svn", 94 | ".tox", 95 | ".venv", 96 | "__pypackages__", 97 | "_build", 98 | "buck-out", 99 | "build", 100 | "dist", 101 | "node_modules", 102 | "venv", 103 | "__pycache__", 104 | "docs", 105 | "examples", 106 | ] 107 | per-file-ignores = {} 108 | 109 | line-length = 105 110 | 111 | # Allow unused variables when underscore-prefixed. 112 | dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" 113 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2023.7.22 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 2 | charset-normalizer==3.2.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 3 | idna==3.4 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 4 | requests==2.31.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 5 | urllib3==2.0.4 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 6 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | alabaster==0.7.13 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 2 | babel==2.12.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 3 | build==0.7.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 4 | certifi==2023.7.22 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 5 | cfgv==3.3.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 6 | charset-normalizer==3.2.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 7 | colorama==0.4.6 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" and (sys_platform == "win32" or os_name == "nt") 8 | coverage==7.2.7 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 9 | distlib==0.3.7 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 10 | docutils==0.17.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 11 | exceptiongroup==1.1.2 ; python_full_version >= "3.8.0" and python_version < "3.11" 12 | filelock==3.12.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 13 | identify==2.5.26 ; python_version >= "3.8" and python_full_version < "4.0.0" 14 | idna==3.4 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 15 | imagesize==1.4.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 16 | importlib-metadata==6.8.0 ; python_version >= "3.8" and python_version < "3.10" 17 | iniconfig==2.0.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 18 | jinja2==3.1.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 19 | markupsafe==2.1.3 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 20 | nodeenv==1.8.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 21 | packaging==23.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 22 | pep517==0.13.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 23 | platformdirs==3.10.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 24 | pluggy==1.2.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 25 | pre-commit==2.21.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 26 | pygments==2.15.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 27 | pytest==7.4.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 28 | pytz==2023.3 ; python_full_version >= "3.8.0" and python_version < "3.9" 29 | pyyaml==6.0.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 30 | requests==2.31.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 31 | responses==0.10.16 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 32 | setuptools-scm==7.1.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 33 | setuptools==68.0.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 34 | six==1.16.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 35 | snowballstemmer==2.2.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 36 | sphinx-rtd-theme==1.2.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 37 | sphinx==4.5.0 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 38 | sphinxcontrib-applehelp==1.0.4 ; python_version >= "3.8" and python_full_version < "4.0.0" 39 | sphinxcontrib-devhelp==1.0.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 40 | sphinxcontrib-htmlhelp==2.0.1 ; python_version >= "3.8" and python_full_version < "4.0.0" 41 | sphinxcontrib-jquery==4.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 42 | sphinxcontrib-jsmath==1.0.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 43 | sphinxcontrib-qthelp==1.0.3 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 44 | sphinxcontrib-serializinghtml==1.1.5 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 45 | sphinxnotes-strike==1.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 46 | tomli==2.0.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 47 | typing-extensions==4.7.1 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 48 | urllib3==2.0.4 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 49 | virtualenv==20.24.2 ; python_full_version >= "3.8.0" and python_full_version < "4.0.0" 50 | zipp==3.16.2 ; python_version >= "3.8" and python_version < "3.10" 51 | -------------------------------------------------------------------------------- /routingpy/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | **routingpy** is a Python 3 client for a lot of popular web routing services. 19 | 20 | Using **routingpy** you can easily request **directions**, **isochrones** and 21 | **matrices** from many reliable online providers in a consistent fashion. Base parameters 22 | are the same for all services, while still preserving each service's special parameters (for 23 | more info, please look at our `README`_. 24 | Take a look at our `Examples`_ to see how simple you can compare routes from different providers. 25 | 26 | **routingpy** is tested against 3.8, 3.9, 3.10, 3.11 :strike:`and PyPy3` (`#60 `_). 27 | 28 | .. _`README`: https://github.com/gis-ops/routing-py#api 29 | .. _`Examples`: https://github.com/gis-ops/routing-py#examples 30 | """ 31 | 32 | from .routers import * # noqa: F401 33 | 34 | # Delete so options is only available over routingpy.routers.options 35 | del options # noqa: F821 36 | -------------------------------------------------------------------------------- /routingpy/client_base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | Core client functionality, common across all routers. 19 | """ 20 | 21 | 22 | try: 23 | from .__version__ import __version__ 24 | except (ModuleNotFoundError, ImportError): 25 | __version__ = "None" 26 | 27 | from abc import ABCMeta, abstractmethod 28 | from datetime import timedelta 29 | from urllib.parse import urlencode 30 | 31 | import requests 32 | 33 | _DEFAULT_USER_AGENT = "routingpy/v{}".format(__version__) 34 | _RETRIABLE_STATUSES = set([503]) 35 | 36 | 37 | class options(object): 38 | """ 39 | Contains default configuration options for all routers, e.g. `timeout` and `proxies`. Each router can take the same 40 | configuration values, which will override the values set in `options` object. 41 | 42 | Example for overriding default values for `user_agent` and proxies: 43 | 44 | >>> from routingpy.routers import options 45 | >>> from routingpy.routers import MapboxValhalla 46 | >>> options.default_user_agent = 'amazing_routing_app' 47 | >>> options.default_proxies = {'https': '129.125.12.0'} 48 | >>> router = MapboxValhalla(my_key) 49 | >>> print(router.client.headers) 50 | {'User-Agent': 'amazing_routing_app', 'Content-Type': 'application/json'} 51 | >>> print(router.client.proxies) 52 | {'https': '129.125.12.0'} 53 | 54 | Attributes: 55 | self.default_timeout: 56 | Combined connect and read timeout for HTTP requests, in 57 | seconds. Specify "None" for no timeout. Integer. 58 | 59 | self.default_retry_timeout: 60 | Timeout across multiple retriable requests, in 61 | seconds. Integer. 62 | 63 | self.default_retry_over_query_limit: 64 | If True, client will not raise an exception 65 | on HTTP 429, but instead jitter a sleeping timer to pause between 66 | requests until HTTP 200 or retry_timeout is reached. Boolean. 67 | 68 | self.default_skip_api_error: 69 | Continue with batch processing if a :class:`routingpy.exceptions.RouterApiError` is 70 | encountered (e.g. no route found). If False, processing will discontinue and raise an error. Boolean. 71 | 72 | self.default_user_agent: 73 | User-Agent to send with the requests to routing API. String. 74 | 75 | self.default_proxies: 76 | Proxies passed to the requests library. Dictionary. 77 | """ 78 | 79 | default_timeout = 60 80 | default_retry_timeout = 60 81 | default_retry_over_query_limit = True 82 | default_skip_api_error = False 83 | default_user_agent = _DEFAULT_USER_AGENT 84 | default_proxies = None 85 | 86 | 87 | # To avoid trouble when respecting timeout for individual routers (i.e. can't be None, since that's no timeout) 88 | DEFAULT = type("object", (object,), {"__repr__": lambda self: "DEFAULT"})() 89 | 90 | 91 | class BaseClient(metaclass=ABCMeta): 92 | """Abstract base class every client inherits from. Authentication is handled in each subclass.""" 93 | 94 | def __init__( 95 | self, 96 | base_url, 97 | user_agent=None, 98 | timeout=DEFAULT, 99 | retry_timeout=None, 100 | retry_over_query_limit=None, 101 | skip_api_error=None, 102 | **kwargs 103 | ): 104 | """ 105 | :param base_url: The base URL for the request. All routers must provide a default. 106 | Should not have a trailing slash. 107 | :type base_url: string 108 | 109 | :param user_agent: User-Agent to send with the requests to routing API. 110 | Overrides ``options.default_user_agent``. 111 | :type user_agent: string 112 | 113 | :param timeout: Combined connect and read timeout for HTTP requests, in 114 | seconds. Specify "None" for no timeout. 115 | :type timeout: int 116 | 117 | :param retry_timeout: Timeout across multiple retriable requests, in 118 | seconds. 119 | :type retry_timeout: int 120 | 121 | :param retry_over_query_limit: If True, client will not raise an exception 122 | on HTTP 429, but instead jitter a sleeping timer to pause between 123 | requests until HTTP 200 or retry_timeout is reached. 124 | :type retry_over_query_limit: bool 125 | 126 | :param skip_api_error: Continue with batch processing if a :class:`routingpy.exceptions.RouterApiError` is 127 | encountered (e.g. no route found). If False, processing will discontinue and raise an error. Default False. 128 | :type skip_api_error: bool 129 | 130 | :param **kwargs: Additional keyword arguments. 131 | :type **kwargs: dict 132 | """ 133 | self.base_url = base_url 134 | 135 | self.retry_over_query_limit = ( 136 | retry_over_query_limit 137 | if retry_over_query_limit is False 138 | else options.default_retry_over_query_limit 139 | ) 140 | self.retry_timeout = timedelta(seconds=retry_timeout or options.default_retry_timeout) 141 | 142 | self.skip_api_error = skip_api_error or options.default_skip_api_error 143 | 144 | self.headers = { 145 | "User-Agent": user_agent or options.default_user_agent, 146 | "Content-Type": "application/json", 147 | } 148 | 149 | self.timeout = timeout if timeout != DEFAULT else options.default_timeout 150 | 151 | self.kwargs = kwargs 152 | 153 | self._req = None 154 | 155 | @abstractmethod 156 | def _request( 157 | self, 158 | url, 159 | get_params={}, 160 | post_params=None, 161 | first_request_time=None, 162 | retry_counter=0, 163 | dry_run=None, 164 | ): 165 | """Performs HTTP GET/POST with credentials, returning the body as 166 | JSON. 167 | 168 | :param url: URL path for the request. Should begin with a slash. 169 | :type url: string 170 | 171 | :param get_params: HTTP GET parameters. 172 | :type get_params: dict or list of tuples 173 | 174 | :param post_params: HTTP POST parameters. Only specified by calling method. 175 | :type post_params: dict 176 | 177 | :param first_request_time: The time of the first request (None if no 178 | retries have occurred). 179 | :type first_request_time: :class:`datetime.datetime` 180 | 181 | :param retry_counter: The number of this retry, or zero for first attempt. 182 | :type retry_counter: int 183 | 184 | :param dry_run: If true, only prints URL and parameters. true or false. 185 | :type dry_run: bool 186 | 187 | :raises routingpy.exceptions.RouterApiError: when the API returns an error due to faulty configuration. 188 | :raises routingpy.exceptions.RouterServerError: when the API returns a server error. 189 | :raises routingpy.exceptions.RouterError: when anything else happened while requesting. 190 | :raises routingpy.exceptions.JSONParseError: when the JSON response can't be parsed. 191 | :raises routingpy.exceptions.Timeout: when the request timed out. 192 | :raises routingpy.exceptions.TransportError: when something went wrong while trying to 193 | execute a request. 194 | 195 | :returns: raw JSON response. 196 | :rtype: dict 197 | """ 198 | pass 199 | 200 | @staticmethod 201 | def _generate_auth_url(path, params): 202 | """Returns the path and query string portion of the request URL, first 203 | adding any necessary parameters. 204 | 205 | :param path: The path portion of the URL. 206 | :type path: string 207 | 208 | :param params: URL parameters. 209 | :type params: dict or list of key/value tuples 210 | 211 | :rtype: string 212 | 213 | """ 214 | 215 | if not params: 216 | return path 217 | 218 | if isinstance(params, dict): 219 | params = sorted(dict(**params).items()) 220 | elif isinstance(params, (list, tuple)): 221 | params = params 222 | 223 | return path + "?" + requests.utils.unquote_unreserved(urlencode(params)) 224 | -------------------------------------------------------------------------------- /routingpy/client_default.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | 18 | import copy 19 | import json 20 | import random 21 | import time 22 | import warnings 23 | from datetime import datetime 24 | 25 | import requests 26 | 27 | from . import exceptions 28 | from .client_base import _RETRIABLE_STATUSES, DEFAULT, BaseClient, options 29 | from .utils import get_ordinal 30 | 31 | 32 | class Client(BaseClient): 33 | """Default client class for requests handling, which is passed to each router. Uses the requests package.""" 34 | 35 | def __init__( 36 | self, 37 | base_url, 38 | user_agent=None, 39 | timeout=DEFAULT, 40 | retry_timeout=None, 41 | retry_over_query_limit=None, 42 | skip_api_error=None, 43 | **kwargs 44 | ): 45 | """ 46 | :param base_url: The base URL for the request. All routers must provide a default. 47 | Should not have a trailing slash. 48 | :type base_url: string 49 | 50 | :param user_agent: User-Agent to send with the requests to routing API. 51 | Overrides ``options.default_user_agent``. 52 | :type user_agent: string 53 | 54 | :param timeout: Combined connect and read timeout for HTTP requests, in 55 | seconds. Specify "None" for no timeout. 56 | :type timeout: int 57 | 58 | :param retry_timeout: Timeout across multiple retriable requests, in 59 | seconds. 60 | :type retry_timeout: int 61 | 62 | :param retry_over_query_limit: If True, client will not raise an exception 63 | on HTTP 429, but instead jitter a sleeping timer to pause between 64 | requests until HTTP 200 or retry_timeout is reached. 65 | :type retry_over_query_limit: bool 66 | 67 | :param skip_api_error: Continue with batch processing if a :class:`routingpy.exceptions.RouterApiError` is 68 | encountered (e.g. no route found). If False, processing will discontinue and raise an error. Default False. 69 | :type skip_api_error: bool 70 | 71 | :param kwargs: Additional arguments, such as headers or proxies. 72 | :type kwargs: dict 73 | """ 74 | 75 | self._session = requests.Session() 76 | super(Client, self).__init__( 77 | base_url, 78 | user_agent=user_agent, 79 | timeout=timeout, 80 | retry_timeout=retry_timeout, 81 | retry_over_query_limit=retry_over_query_limit, 82 | skip_api_error=skip_api_error, 83 | **kwargs 84 | ) 85 | 86 | self.kwargs = kwargs or {} 87 | try: 88 | self.headers.update(self.kwargs["headers"]) 89 | except KeyError: 90 | pass 91 | 92 | self.kwargs["headers"] = self.headers 93 | self.kwargs["timeout"] = self.timeout 94 | 95 | self.proxies = self.kwargs.get("proxies") or options.default_proxies 96 | if self.proxies: 97 | self.kwargs["proxies"] = self.proxies 98 | 99 | def _request( 100 | self, 101 | url, 102 | get_params={}, 103 | post_params=None, 104 | first_request_time=None, 105 | retry_counter=0, 106 | dry_run=None, 107 | ): 108 | """Performs HTTP GET/POST with credentials, returning the body as 109 | JSON. 110 | 111 | :param url: URL path for the request. Should begin with a slash. 112 | :type url: string 113 | 114 | :param get_params: HTTP GET parameters. 115 | :type get_params: dict or list of tuples 116 | 117 | :param post_params: HTTP POST parameters. Only specified by calling method. 118 | :type post_params: dict 119 | 120 | :param first_request_time: The time of the first request (None if no 121 | retries have occurred). 122 | :type first_request_time: :class:`datetime.datetime` 123 | 124 | :param retry_counter: The number of this retry, or zero for first attempt. 125 | :type retry_counter: int 126 | 127 | :param dry_run: If true, only prints URL and parameters. true or false. 128 | :type dry_run: bool 129 | 130 | :raises routingpy.exceptions.RouterApiError: when the API returns an error due to faulty configuration. 131 | :raises routingpy.exceptions.RouterServerError: when the API returns a server error. 132 | :raises routingpy.exceptions.RouterError: when anything else happened while requesting. 133 | :raises routingpy.exceptions.JSONParseError: when the JSON response can't be parsed. 134 | :raises routingpy.exceptions.Timeout: when the request timed out. 135 | :raises routingpy.exceptions.TransportError: when something went wrong while trying to 136 | execute a request. 137 | 138 | :returns: raw JSON response or GeoTIFF image 139 | :rtype: dict or bytes 140 | """ 141 | 142 | if not first_request_time: 143 | first_request_time = datetime.now() 144 | 145 | elapsed = datetime.now() - first_request_time 146 | if elapsed > self.retry_timeout: 147 | raise exceptions.Timeout() 148 | 149 | if retry_counter > 0: 150 | # 0.5 * (1.5 ^ i) is an increased sleep time of 1.5x per iteration, 151 | # starting at 0.5s when retry_counter=1. The first retry will occur 152 | # at 1, so subtract that first. 153 | delay_seconds = 1.5 ** (retry_counter - 1) 154 | 155 | # Jitter this value by 50% and pause. 156 | time.sleep(delay_seconds * (random.random() + 0.5)) 157 | 158 | authed_url = self._generate_auth_url(url, get_params) 159 | 160 | final_requests_kwargs = copy.copy(self.kwargs) 161 | 162 | # Determine GET/POST. 163 | requests_method = self._session.get 164 | if post_params is not None: 165 | requests_method = self._session.post 166 | if final_requests_kwargs["headers"]["Content-Type"] == "application/json": 167 | final_requests_kwargs["json"] = post_params 168 | else: 169 | # Send as x-www-form-urlencoded key-value pair string (e.g. Mapbox API) 170 | final_requests_kwargs["data"] = post_params 171 | 172 | # Only print URL and parameters for dry_run 173 | if dry_run: 174 | print( 175 | "url:\n{}\nParameters:\n{}".format( 176 | self.base_url + authed_url, json.dumps(final_requests_kwargs, indent=2) 177 | ) 178 | ) 179 | return 180 | 181 | try: 182 | response = requests_method(self.base_url + authed_url, **final_requests_kwargs) 183 | self._req = response.request 184 | 185 | except requests.exceptions.Timeout: 186 | raise exceptions.Timeout() 187 | 188 | tried = retry_counter + 1 189 | 190 | if response.status_code in _RETRIABLE_STATUSES: 191 | # Retry request. 192 | warnings.warn( 193 | "Server down.\nRetrying for the {}{} time.".format(tried, get_ordinal(tried)), 194 | UserWarning, 195 | ) 196 | return self._request(url, get_params, post_params, first_request_time, retry_counter + 1) 197 | 198 | try: 199 | return self._get_body(response) 200 | 201 | except exceptions.RouterApiError: 202 | if self.skip_api_error: 203 | warnings.warn( 204 | "Router {} returned an API error with " 205 | "the following message:\n{}".format(self.__class__.__name__, response.text) 206 | ) 207 | return 208 | 209 | raise 210 | 211 | except exceptions.RetriableRequest as e: 212 | if isinstance(e, exceptions.OverQueryLimit) and not self.retry_over_query_limit: 213 | raise 214 | 215 | warnings.warn( 216 | "Rate limit exceeded.\nRetrying for the {}{} time.".format(tried, get_ordinal(tried)), 217 | UserWarning, 218 | ) 219 | # Retry request. 220 | return self._request(url, get_params, post_params, first_request_time, retry_counter + 1) 221 | 222 | @property 223 | def req(self): 224 | """Holds the :class:`requests.PreparedRequest` property for the last request.""" 225 | return self._req 226 | 227 | @staticmethod 228 | def _get_body(response): 229 | status_code = response.status_code 230 | content_type = response.headers["content-type"] 231 | 232 | if status_code == 200: 233 | if content_type == "image/tiff": 234 | return response.content 235 | 236 | else: 237 | try: 238 | return response.json() 239 | 240 | except json.decoder.JSONDecodeError: 241 | raise exceptions.JSONParseError( 242 | "Can't decode JSON response:{}".format(response.text) 243 | ) 244 | 245 | if status_code == 429: 246 | raise exceptions.OverQueryLimit(status_code, response.text) 247 | 248 | if 400 <= status_code < 500: 249 | raise exceptions.RouterApiError(status_code, response.text) 250 | 251 | if 500 <= status_code: 252 | raise exceptions.RouterServerError(status_code, response.text) 253 | 254 | if status_code != 200: 255 | raise exceptions.RouterError(status_code, response.text) 256 | -------------------------------------------------------------------------------- /routingpy/convert.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Converts Python types to string representations suitable for GET queries. 18 | """ 19 | import datetime 20 | 21 | 22 | def delimit_list(arg, delimiter=","): 23 | """Convert list to delimiter-separated string""" 24 | if not is_list(arg): 25 | raise TypeError("Expected a list or tuple, " "but got {}".format(type(arg).__name__)) 26 | return delimiter.join(map(str, arg)) 27 | 28 | 29 | def convert_bool(boolean): 30 | """Convert to stringified boolean""" 31 | 32 | return str(boolean).lower() 33 | 34 | 35 | def format_float(arg): 36 | """Formats a float value to be as short as possible. 37 | 38 | Trims extraneous trailing zeros and period to give API 39 | args the best possible chance of fitting within 2000 char 40 | URL length restrictions. 41 | 42 | For example: 43 | 44 | format_float(40) -> "40" 45 | format_float(40.0) -> "40" 46 | format_float(40.1) -> "40.1" 47 | format_float(40.001) -> "40.001" 48 | format_float(40.0010) -> "40.001" 49 | 50 | :param arg: The lat or lng float. 51 | :type arg: float 52 | 53 | :rtype: string 54 | """ 55 | return "{}".format(round(float(arg), 6)).rstrip("0").rstrip(".") 56 | 57 | 58 | def is_list(arg): 59 | """Checks if arg is list-like.""" 60 | if isinstance(arg, dict): 61 | return False 62 | if isinstance(arg, str): # Python 3-only, as str has __iter__ 63 | return False 64 | return ( 65 | not _has_method(arg, "strip") and _has_method(arg, "__getitem__") or _has_method(arg, "__iter__") 66 | ) 67 | 68 | 69 | def _has_method(arg, method): 70 | """Returns true if the given object has a method with the given name. 71 | 72 | :param arg: the object 73 | 74 | :param method: the method name 75 | :type method: string 76 | 77 | :rtype: bool 78 | """ 79 | return hasattr(arg, method) and callable(getattr(arg, method)) 80 | 81 | 82 | def seconds_to_iso8601(seconds): 83 | """Convert the given number of seconds to ISO 8601 duration format. 84 | 85 | Example: 86 | >>> seconds_to_iso8601(3665) 87 | 'PT1H1M5S' 88 | 89 | :param seconds: The number of seconds to convert. 90 | :type seconds: int 91 | 92 | :returns: The duration in ISO 8601 format. 93 | :rtype: string 94 | """ 95 | duration = datetime.timedelta(seconds=seconds) 96 | hours = duration.seconds // 3600 97 | minutes = (duration.seconds // 60) % 60 98 | seconds = duration.seconds % 60 99 | 100 | iso8601_duration = "PT" 101 | if hours: 102 | iso8601_duration += f"{hours}H" 103 | 104 | if minutes: 105 | iso8601_duration += f"{minutes}M" 106 | 107 | if seconds or not (hours or minutes): 108 | iso8601_duration += f"{seconds}S" 109 | 110 | return iso8601_duration 111 | -------------------------------------------------------------------------------- /routingpy/direction.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | :class:`.Direction` returns directions results. 19 | """ 20 | from typing import List, Optional 21 | 22 | 23 | class Directions(object): 24 | """ 25 | Contains a list of :class:`Direction`, when the router returned multiple alternative routes, and the complete raw 26 | response, which can be accessed via the property ``raw``. 27 | """ 28 | 29 | def __init__(self, directions=None, raw=None): 30 | """ 31 | Initialize a :class:`Directions` instance to hold multiple :class:`Direction` instances in a list-like fashion. 32 | 33 | :param directions: List of :class:`Direction` objects 34 | :type directions: list of :class:`Direction` 35 | 36 | :param raw: The whole raw directions response of the routing engine. 37 | :type raw: dict 38 | """ 39 | self._directions = directions 40 | self._raw = raw 41 | 42 | @property 43 | def raw(self) -> Optional[dict]: 44 | """ 45 | Returns the directions raw, unparsed response. For details, consult the routing engine's API documentation. 46 | :rtype: dict or None 47 | """ 48 | return self._raw 49 | 50 | def __repr__(self): # pragma: no cover 51 | return "Directions({}, {})".format(self._directions, self.raw) 52 | 53 | def __getitem__(self, item): 54 | return self._directions[item] 55 | 56 | def __iter__(self): 57 | return iter(self._directions) 58 | 59 | def __len__(self): 60 | return len(self._directions) 61 | 62 | 63 | class Direction(object): 64 | """ 65 | Contains a parsed directions' response. Access via properties ``geometry``, ``duration`` and ``distance``. 66 | """ 67 | 68 | def __init__(self, geometry=None, duration=None, distance=None, raw=None): 69 | """ 70 | Initialize a :class:`Direction` object to hold the properties of a directions request. 71 | 72 | :param geometry: The geometry list in [[lon1, lat1], [lon2, lat2]] order. 73 | :type geometry: list of list 74 | 75 | :param duration: The duration of the direction in seconds. 76 | :type duration: int or float 77 | 78 | :param distance: The distance of the direction in meters. 79 | :type distance: int 80 | 81 | :param raw: The raw response of an individual direction (for multiple alternative routes) or the whole direction 82 | response. 83 | :type raw: dict 84 | """ 85 | self._geometry = geometry 86 | self._duration = duration 87 | self._distance = distance 88 | self._raw = raw 89 | 90 | @property 91 | def geometry(self) -> Optional[List[List[float]]]: 92 | """ 93 | The geometry of the route as [[lon1, lat1], [lon2, lat2], ...] list. 94 | 95 | :rtype: list or None 96 | """ 97 | return self._geometry 98 | 99 | @property 100 | def duration(self) -> int: 101 | """ 102 | The duration of the entire trip in seconds. 103 | 104 | :rtype: int 105 | """ 106 | return self._duration 107 | 108 | @property 109 | def distance(self) -> int: 110 | """ 111 | The distance of the entire trip in meters. 112 | 113 | :rtype: int 114 | """ 115 | return self._distance 116 | 117 | @property 118 | def raw(self) -> Optional[dict]: 119 | """ 120 | Returns the route's raw, unparsed response. For details, consult the routing engine's API documentation. 121 | 122 | :rtype: dict or None 123 | """ 124 | return self._raw 125 | 126 | def __repr__(self): # pragma: no cover 127 | return "Direction({}, {}, {})".format(self.geometry, self.duration, self.distance) 128 | -------------------------------------------------------------------------------- /routingpy/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | Defines exceptions that are thrown by the various routing clients. 19 | """ 20 | 21 | 22 | class RouterError(Exception): # pragma: no cover 23 | """Represents an exception returned by the remote or local API.""" 24 | 25 | def __init__(self, status, message=None): 26 | self.status = status 27 | self.message = message 28 | 29 | def __str__(self): 30 | if self.message is None: 31 | return self.status 32 | else: 33 | return "%s (%s)" % (self.status, self.message) 34 | 35 | 36 | class RouterApiError(RouterError): 37 | """Represents an exception returned by a routing engine, i.e. 400 <= HTTP status code <= 500""" 38 | 39 | 40 | class RouterServerError(RouterError): 41 | """Represents an exception returned by a server, i.e. 500 <= HTTP""" 42 | 43 | 44 | class RouterNotFound(Exception): 45 | """Represents an exception raised when router can not be found by name.""" 46 | 47 | 48 | class Timeout(Exception): # pragma: no cover 49 | """The request timed out.""" 50 | 51 | pass 52 | 53 | 54 | class JSONParseError(Exception): # pragma: no cover 55 | """The Json response can't be parsed..""" 56 | 57 | pass 58 | 59 | 60 | class RetriableRequest(Exception): # pragma: no cover 61 | """Signifies that the request can be retried.""" 62 | 63 | pass 64 | 65 | 66 | class OverQueryLimit(RouterError, RetriableRequest): 67 | """Signifies that the request failed because the client exceeded its query rate limit. 68 | 69 | Normally we treat this as a retriable condition, but we allow the calling code to specify that these requests should 70 | not be retried. 71 | """ 72 | 73 | pass 74 | -------------------------------------------------------------------------------- /routingpy/expansion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | :class:`Expansion` returns expansion results. 19 | """ 20 | from typing import List, Optional, Tuple, Union 21 | 22 | 23 | class Edge: 24 | """ 25 | Contains a parsed single line string of an edge and its attributes, if specified in the request. 26 | Access via properties ``geometry``, ``distances`` ``durations``, ``costs``, ``edge_ids``, ``statuses``. 27 | """ 28 | 29 | def __init__( 30 | self, geometry=None, distances=None, durations=None, costs=None, edge_ids=None, statuses=None 31 | ): 32 | self._geometry = geometry 33 | self._distance = distances 34 | self._duration = durations 35 | self._cost = costs 36 | self._edge_id = edge_ids 37 | self._status = statuses 38 | 39 | @property 40 | def geometry(self) -> Optional[List[List[float]]]: 41 | """ 42 | The geometry of the edge as [[lon1, lat1], [lon2, lat2]] list. 43 | 44 | :rtype: list or None 45 | """ 46 | return self._geometry 47 | 48 | @property 49 | def distance(self) -> Optional[int]: 50 | """ 51 | The accumulated distance in meters for the edge in order of graph traversal. 52 | 53 | :rtype: int or None 54 | """ 55 | return self._distance 56 | 57 | @property 58 | def duration(self) -> Optional[int]: 59 | """ 60 | The accumulated duration in seconds for the edge in order of graph traversal. 61 | 62 | :rtype: int or None 63 | """ 64 | return self._duration 65 | 66 | @property 67 | def cost(self) -> Optional[int]: 68 | """ 69 | The accumulated cost for the edge in order of graph traversal. 70 | 71 | :rtype: int or None 72 | """ 73 | return self._cost 74 | 75 | @property 76 | def edge_id(self) -> Optional[int]: 77 | """ 78 | The internal edge IDs for each edge in order of graph traversal. 79 | 80 | :rtype: int or None 81 | """ 82 | return self._edge_id 83 | 84 | @property 85 | def status(self) -> Optional[str]: 86 | """ 87 | The edge states for each edge in order of graph traversal. 88 | Can be one of "r" (reached), "s" (settled), "c" (connected). 89 | 90 | :rtype: str or None 91 | """ 92 | return self._status 93 | 94 | def __repr__(self): # pragma: no cover 95 | return "Edge({})".format(", ".join([f"{k[1:]}: {v}" for k, v in vars(self).items() if v])) 96 | 97 | 98 | class Expansions: 99 | """ 100 | Contains a list of :class:`Edge`, which can be iterated over or accessed by index. The property ¸`raw`` contains 101 | the complete raw response of the expansion request. 102 | """ 103 | 104 | def __init__( 105 | self, 106 | edges: Optional[List[Edge]] = None, 107 | center: Optional[Union[List[float], Tuple[float]]] = None, 108 | interval_type: Optional[str] = None, 109 | raw: Optional[dict] = None, 110 | ): 111 | self._edges = edges 112 | self._center = center 113 | self._interval_type = interval_type 114 | self._raw = raw 115 | 116 | @property 117 | def raw(self) -> Optional[dict]: 118 | """ 119 | Returns the expansion's raw, unparsed response. For details, consult the documentation 120 | at https://valhalla.readthedocs.io/en/latest/api/expansion/api-reference/. 121 | 122 | :rtype: dict or None 123 | """ 124 | return self._raw 125 | 126 | @property 127 | def center(self) -> Optional[Union[List[float], Tuple[float]]]: 128 | """ 129 | The center coordinate in [lon, lat] of the expansion, which is the location from the user input. 130 | 131 | :rtype: list of float or None 132 | """ 133 | return self._center 134 | 135 | @property 136 | def interval_type(self) -> Optional[str]: 137 | """ 138 | Was it based on 'distance' or 'time'? 139 | 140 | :return: str or None 141 | """ 142 | return self._interval_type 143 | 144 | def __repr__(self): # pragma: no cover 145 | if len(self._edges) < 10: 146 | return "Expansions({}, {})".format(self._edges, self.raw) 147 | else: 148 | return "Expansions({}, ..., {})".format( 149 | ", ".join([str(e) for e in self._edges[:3]]), 150 | ", ".join(str(e) for e in self._edges[-3:]), 151 | ) 152 | 153 | def __getitem__(self, item): 154 | return self._edges[item] 155 | 156 | def __iter__(self): 157 | return iter(self._edges) 158 | 159 | def __len__(self): 160 | return len(self._edges) 161 | -------------------------------------------------------------------------------- /routingpy/isochrone.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | :class:`Isochrone` returns isochrones results. 19 | """ 20 | from typing import List, Optional, Tuple, Union 21 | 22 | 23 | class Isochrones(object): 24 | """ 25 | Contains a list of :class:`Isochrone`, which can be iterated over or accessed by index. The property ¸`raw`` contains 26 | the complete raw response of the isochrones request. 27 | """ 28 | 29 | def __init__(self, isochrones=None, raw=None): 30 | self._isochrones = isochrones 31 | self._raw = raw 32 | 33 | @property 34 | def raw(self) -> Optional[dict]: 35 | """ 36 | Returns the isochrones' raw, unparsed response. For details, consult the routing engine's API documentation. 37 | 38 | :rtype: dict or None 39 | """ 40 | return self._raw 41 | 42 | def __repr__(self): # pragma: no cover 43 | return "Isochrones({}, {})".format(self._isochrones, self.raw) 44 | 45 | def __getitem__(self, item): 46 | return self._isochrones[item] 47 | 48 | def __iter__(self): 49 | return iter(self._isochrones) 50 | 51 | def __len__(self): 52 | return len(self._isochrones) 53 | 54 | 55 | class Isochrone(object): 56 | """ 57 | Contains a parsed single isochrone response. Access via properties ``geometry``, ``interval``, ``center``, ``interval_type``. 58 | """ 59 | 60 | def __init__(self, geometry=None, interval=None, center=None, interval_type=None): 61 | self._geometry = geometry 62 | self._interval = int(interval) 63 | self._center = center 64 | self._interval_type = interval_type 65 | 66 | @property 67 | def geometry(self) -> Optional[List[List[float]]]: 68 | """ 69 | The geometry of the isochrone as [[lon1, lat1], [lon2, lat2], ...] list. 70 | 71 | :rtype: list or None 72 | """ 73 | return self._geometry 74 | 75 | @property 76 | def center(self) -> Optional[Union[List[float], Tuple[float]]]: 77 | """ 78 | The center coordinate in [lon, lat] of the isochrone. Might deviate from the input coordinate. 79 | Not available for all routing engines (e.g. GraphHopper, Mapbox OSRM or Valhalla). 80 | In this case, it will use the location from the user input. 81 | 82 | :rtype: list of float or None 83 | """ 84 | return self._center 85 | 86 | @property 87 | def interval(self) -> Optional[int]: 88 | """ 89 | The interval of the isochrone in seconds or in meters. 90 | 91 | :return: int 92 | """ 93 | return self._interval 94 | 95 | @property 96 | def interval_type(self) -> Optional[str]: 97 | """ 98 | Was it based on 'distance' or 'time'? 99 | 100 | :return: str or None 101 | """ 102 | return self._interval_type 103 | 104 | def __repr__(self): # pragma: no cover 105 | return "Isochrone({}, {})".format(self.geometry, self.interval) 106 | -------------------------------------------------------------------------------- /routingpy/matrix.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | :class:`Matrix` returns matrix results. 19 | """ 20 | from typing import List, Optional 21 | 22 | 23 | class Matrix(object): 24 | """ 25 | Contains a parsed matrix response. Access via properties ``geometry`` and ``raw``. 26 | """ 27 | 28 | def __init__(self, durations=None, distances=None, raw=None): 29 | self._durations = durations 30 | self._distances = distances 31 | self._raw = raw 32 | 33 | @property 34 | def durations(self) -> Optional[List[List[float]]]: 35 | """ 36 | The durations matrix as list akin to:: 37 | 38 | [ 39 | [ 40 | duration(origin1-destination1), 41 | duration(origin1-destination2), 42 | duration[origin1-destination3), 43 | ... 44 | ], 45 | [ 46 | duration(origin2-destination1), 47 | duration(origin2-destination2), 48 | duration[origin3-destination3), 49 | ... 50 | ], 51 | ... 52 | ] 53 | 54 | :rtype: list or None 55 | """ 56 | return self._durations 57 | 58 | @property 59 | def distances(self) -> Optional[List[List[float]]]: 60 | """ 61 | The distance matrix as list akin to:: 62 | 63 | [ 64 | [ 65 | duration(origin1-destination1), 66 | duration(origin1-destination2), 67 | duration[origin1-destination3), 68 | ... 69 | ], 70 | [ 71 | duration(origin2-destination1), 72 | duration(origin2-destination2), 73 | duration[origin3-destination3), 74 | ... 75 | ], 76 | ... 77 | ] 78 | 79 | :rtype: list or None 80 | """ 81 | return self._distances 82 | 83 | @property 84 | def raw(self) -> Optional[dict]: 85 | """ 86 | Returns the matrices raw, unparsed response. For details, consult the routing engine's API documentation. 87 | 88 | :rtype: dict or None 89 | """ 90 | return self._raw 91 | 92 | def __repr__(self): # pragma: no cover 93 | return "Matrix({}, {})".format(self.durations, self.distances) 94 | -------------------------------------------------------------------------------- /routingpy/raster.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """ 18 | :class:`Raster` returns rasters results. 19 | """ 20 | from typing import Optional 21 | 22 | 23 | class Raster(object): 24 | """ 25 | Contains a parsed single raster response. Access via properties ``image``, ``max_travel_time`` 26 | """ 27 | 28 | def __init__(self, image=None, max_travel_time=None): 29 | self._image = image 30 | self._max_travel_time = max_travel_time 31 | 32 | @property 33 | def image(self) -> Optional[bytes]: 34 | """ 35 | The image of the raster. 36 | 37 | :rtype: bytes 38 | """ 39 | return self._image 40 | 41 | @property 42 | def max_travel_time(self) -> int: 43 | """ 44 | The max travel time of the raster in seconds. 45 | 46 | :return: int 47 | """ 48 | return self._max_travel_time 49 | 50 | def __repr__(self): # pragma: no cover 51 | return "Raster({})".format(self.max_travel_time) 52 | -------------------------------------------------------------------------------- /routingpy/routers/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Every routing service below has a separate module in ``routingpy.routers``, which hosts a class abstracting the service's 3 | API. Each router has at least a ``directions`` method, many offer additionally ``matrix`` and/or ``isochrones`` methods. 4 | Other available provider endpoints are allowed and generally encouraged. However, please refer 5 | to our `contribution guidelines`_ for general instructions. 6 | 7 | The requests are handled via a client class derived from :class:`routingpy.client_base.BaseClient`. 8 | 9 | **routingpy**'s dogma is, that all routers expose the same mandatory arguments for common methods in an 10 | attempt to be consistent for the same method across different routers. Unlike other collective libraries, 11 | we additionally chose to preserve each router's special arguments, only abstracting the most basic arguments, such as 12 | locations and profile (car, bike, pedestrian etc.), among others (full list here_). 13 | 14 | .. _`contribution guidelines`: https://github.com/gis-ops/routing-py/blob/master/CONTRIBUTING.md 15 | .. _here: https://github.com/gis-ops/routing-py#api 16 | """ 17 | from ..client_base import options # noqa: F401 18 | from ..exceptions import RouterNotFound 19 | from .google import Google 20 | from .graphhopper import Graphhopper 21 | from .heremaps import HereMaps 22 | from .mapbox_osrm import MapboxOSRM 23 | from .openrouteservice import ORS 24 | from .opentripplanner_v2 import OpenTripPlannerV2 25 | from .osrm import OSRM 26 | from .valhalla import Valhalla 27 | 28 | # Provide synonyms 29 | _SERVICE_TO_ROUTER = { 30 | "google": Google, 31 | "graphhopper": Graphhopper, 32 | "here": HereMaps, 33 | "heremaps": HereMaps, 34 | "mapbox_osrm": MapboxOSRM, 35 | "mapbox-osrm": MapboxOSRM, 36 | "mapbox": MapboxOSRM, 37 | "mapboxosrm": MapboxOSRM, 38 | "openrouteservice": ORS, 39 | "opentripplanner": OpenTripPlannerV2, 40 | "opentripplanner_v2": OpenTripPlannerV2, 41 | "ors": ORS, 42 | "osrm": OSRM, 43 | "otp": OpenTripPlannerV2, 44 | "otp_v2": OpenTripPlannerV2, 45 | "valhalla": Valhalla, 46 | } 47 | 48 | 49 | def get_router_by_name(router_name): 50 | """ 51 | Given a router's name, try to return the router class. 52 | 53 | >>> from routingpy.routers import get_router_by_name 54 | >>> router = get_router_by_name("ors")(api_key='') 55 | >>> print(router) 56 | routingpy.routers.openrouteservice.ORS 57 | >>> route = router.directions(**params) 58 | 59 | If the string given is not recognized, a 60 | :class:`routingpy.exceptions.RouterNotFound` exception is raised and the available list of router names is printed. 61 | 62 | :param router_name: Name of the router as string. 63 | :type router_name: str 64 | 65 | :rtype: Union[:class:`routingpy.routers.google.Google`, :class:`routingpy.routers.graphhopper.Graphhopper`, :class:`routingpy.routers.heremaps.HereMaps`, :class:`routingpy.routers.mapbox_osrm.MapBoxOSRM`, :class:`routingpy.routers.mapbox_valhalla.MapBoxValhalla`, :class:`routingpy.routers.openrouteservice.ORS`, :class:`routingpy.routers.osrm.OSRM`, :class:`routingpy.routers.otp_v2.OpenTripPlannerV2`, :class:`routingpy.routers.valhalla.Valhalla`] 66 | 67 | """ 68 | try: 69 | return _SERVICE_TO_ROUTER[router_name.lower()] 70 | except KeyError: 71 | raise RouterNotFound( 72 | "Unknown router '{}'; options are: {}".format(router_name, _SERVICE_TO_ROUTER.keys()) 73 | ) 74 | -------------------------------------------------------------------------------- /routingpy/routers/opentripplanner_v2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | import datetime 18 | from typing import List, Optional # noqa: F401 19 | 20 | from .. import convert, utils 21 | from ..client_base import DEFAULT 22 | from ..client_default import Client 23 | from ..direction import Direction, Directions 24 | from ..isochrone import Isochrone, Isochrones 25 | from ..raster import Raster 26 | 27 | 28 | class OpenTripPlannerV2: 29 | """Performs requests over OpenTripPlannerV2 GraphQL API.""" 30 | 31 | _DEFAULT_BASE_URL = "http://localhost:8080" 32 | 33 | def __init__( 34 | self, 35 | base_url: Optional[str] = _DEFAULT_BASE_URL, 36 | user_agent: Optional[str] = None, 37 | timeout: Optional[int] = DEFAULT, 38 | retry_timeout: Optional[int] = None, 39 | retry_over_query_limit: Optional[bool] = False, 40 | skip_api_error: Optional[bool] = None, 41 | client=Client, 42 | **client_kwargs, 43 | ): 44 | """ 45 | Initializes an OpenTripPlannerV2 client. 46 | 47 | :param base_url: The base URL for the request. Defaults to localhost. Should not have a 48 | trailing slash. 49 | :type base_url: str 50 | 51 | :param user_agent: User Agent to be used when requesting. 52 | Default :attr:`routingpy.routers.options.default_user_agent`. 53 | :type user_agent: str 54 | 55 | :param timeout: Combined connect and read timeout for HTTP requests, in seconds. 56 | Specify ``None`` for no timeout. 57 | Default :attr:`routingpy.routers.options.default_timeout`. 58 | :type timeout: int or None 59 | 60 | :param retry_timeout: Timeout across multiple retriable requests, in seconds. 61 | Default :attr:`routingpy.routers.options.default_retry_timeout`. 62 | :type retry_timeout: int 63 | 64 | :param retry_over_query_limit: If True, client will not raise an exception on HTTP 429, 65 | but instead jitter a sleeping timer to pause between requests until HTTP 200 or 66 | retry_timeout is reached. 67 | Default :attr:`routingpy.routers.options.default_retry_over_query_limit`. 68 | :type retry_over_query_limit: bool 69 | 70 | :param skip_api_error: Continue with batch processing if a 71 | :class:`routingpy.exceptions.RouterApiError` is encountered (e.g. no route found). 72 | If False, processing will discontinue and raise an error. 73 | Default :attr:`routingpy.routers.options.default_skip_api_error`. 74 | :type skip_api_error: bool 75 | 76 | :param client: A client class for request handling. Needs to be derived from 77 | :class:`routingpy.client_base.BaseClient` 78 | :type client: abc.ABCMeta 79 | 80 | :param client_kwargs: Additional arguments passed to the client, such as headers or proxies. 81 | :type client_kwargs: dict 82 | """ 83 | 84 | self.client = client( 85 | base_url, 86 | user_agent, 87 | timeout, 88 | retry_timeout, 89 | retry_over_query_limit, 90 | skip_api_error, 91 | **client_kwargs, 92 | ) 93 | 94 | def directions( 95 | self, 96 | locations: List[List[float]], 97 | profile: Optional[str] = "WALK,TRANSIT", 98 | date: Optional[datetime.date] = datetime.datetime.now().date(), 99 | time: Optional[datetime.time] = datetime.datetime.now().time(), 100 | arrive_by: Optional[bool] = False, 101 | num_itineraries: Optional[int] = 3, 102 | dry_run: Optional[bool] = None, 103 | ): 104 | """ 105 | Get directions between an origin point and a destination point. 106 | 107 | :param locations: List of coordinates for departure and arrival points as 108 | [[lon,lat], [lon,lat]]. 109 | :type locations: list of list of float 110 | 111 | :param profile: Comma-separated list of transportation modes that the user is willing to 112 | use. Default: "WALK,TRANSIT" 113 | :type profile: str 114 | 115 | :param date: Date of departure or arrival. Default value: current date. 116 | :type date: datetime.date 117 | 118 | :param time: Time of departure or arrival. Default value: current time. 119 | :type time: datetime.time 120 | 121 | :arrive_by: Whether the itinerary should depart at the specified time (False), or arrive to 122 | the destination at the specified time (True). Default value: False. 123 | :type arrive_by: bool 124 | 125 | :param num_itineraries: The maximum number of itineraries to return. Default value: 3. 126 | :type num_itineraries: int 127 | 128 | :param dry_run: Print URL and parameters without sending the request. 129 | :type dry_run: bool 130 | 131 | :returns: One or multiple route(s) from provided coordinates and restrictions. 132 | :rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions` 133 | """ 134 | transport_modes = [{"mode": mode} for mode in profile.strip().split(",")] 135 | query = f""" 136 | {{ 137 | plan( 138 | date: "{ date.strftime("%Y-%m-%d") }" 139 | time: "{ time.strftime("%H:%M:%S") }" 140 | from: {{lat: {locations[0][1]}, lon: {locations[0][0]}}} 141 | to: {{lat: {locations[1][1]}, lon: {locations[1][0]}}} 142 | transportModes: {str(transport_modes).replace("'", "")} 143 | numItineraries: {num_itineraries} 144 | arriveBy: {"true" if arrive_by else "false"} 145 | ) {{ 146 | itineraries {{ 147 | duration 148 | startTime 149 | endTime 150 | legs {{ 151 | startTime 152 | endTime 153 | duration 154 | distance 155 | mode 156 | legGeometry {{ 157 | points 158 | }} 159 | }} 160 | }} 161 | }} 162 | }} 163 | """ 164 | params = {"query": query} 165 | response = self.client._request( 166 | "/otp/routers/default/index/graphql", post_params=params, dry_run=dry_run 167 | ) 168 | return self._parse_directions_response(response, num_itineraries) 169 | 170 | def _parse_directions_response(self, response, num_itineraries): 171 | if response is None: # pragma: no cover 172 | return Directions() if num_itineraries > 1 else Direction() 173 | 174 | routes = [] 175 | for itinerary in response["data"]["plan"]["itineraries"]: 176 | geometry, distance = self._parse_legs(itinerary["legs"]) 177 | routes.append( 178 | Direction( 179 | geometry=geometry, 180 | duration=int(itinerary["duration"]), 181 | distance=distance, 182 | raw=itinerary, 183 | ) 184 | ) 185 | 186 | if num_itineraries > 1: 187 | return Directions(routes, raw=response) 188 | 189 | elif routes: 190 | return routes[0] 191 | 192 | else: 193 | return Direction() 194 | 195 | def _parse_legs(self, legs): 196 | distance = 0 197 | geometry = [] 198 | for leg in legs: 199 | points = utils.decode_polyline5(leg["legGeometry"]["points"]) 200 | geometry.extend(list(reversed(points))) 201 | distance += int(leg["distance"]) 202 | 203 | return geometry, distance 204 | 205 | def isochrones( 206 | self, 207 | locations: List[float], 208 | profile: Optional[str] = "WALK,TRANSIT", 209 | time: Optional[datetime.datetime] = datetime.datetime.now(datetime.timezone.utc), 210 | cutoffs: Optional[List[int]] = [3600], 211 | arrive_by: Optional[bool] = False, 212 | dry_run: Optional[bool] = None, 213 | ): 214 | """Gets isochrones for a range of time values around a given set of coordinates. 215 | 216 | :param locations: Origin of the search as [lon,lat]. 217 | :type locations: list of float 218 | 219 | :param profile: Comma-separated list of transportation modes that the user is willing to 220 | use. Default: "WALK,TRANSIT" 221 | :type profile: str 222 | 223 | :time: Departure date and time (timezone aware). The default value is now (UTC). 224 | :type time: datetime.datetime 225 | 226 | :cutoff: The maximum travel duration in seconds. The default value is one hour. 227 | 228 | :arrive_by: Set to False when searching from the location and True when searching to the 229 | location. Default value: False. 230 | :type arrive_by: bool 231 | 232 | :param dry_run: Print URL and parameters without sending the request. 233 | :param dry_run: bool 234 | 235 | :returns: An isochrone with the specified range. 236 | :rtype: :class:`routingpy.isochrone.Isochrones` 237 | """ 238 | params = [ 239 | ("location", convert.delimit_list(reversed(locations), ",")), 240 | ("time", time.isoformat()), 241 | ("modes", profile), 242 | ("arriveBy", "true" if arrive_by else "false"), 243 | ] 244 | for cutoff in cutoffs: 245 | params.append(("cutoff", convert.seconds_to_iso8601(cutoff))) 246 | 247 | response = self.client._request( 248 | "/otp/traveltime/isochrone", 249 | get_params=params, 250 | dry_run=dry_run, 251 | ) 252 | return self._parse_isochrones_response(response) 253 | 254 | def _parse_isochrones_response(self, response): 255 | if response is None: # pragma: no cover 256 | return Isochrones() 257 | 258 | isochrones = [] 259 | for feature in response["features"]: 260 | isochrones.append( 261 | Isochrone( 262 | geometry=feature["geometry"]["coordinates"][0], 263 | interval=feature["properties"]["time"], 264 | interval_type="time", 265 | ) 266 | ) 267 | 268 | return Isochrones(isochrones=isochrones, raw=response) 269 | 270 | def raster( 271 | self, 272 | locations: List[float], 273 | profile: Optional[str] = "WALK,TRANSIT", 274 | time: Optional[datetime.datetime] = datetime.datetime.now(), 275 | cutoff: Optional[int] = 3600, 276 | arrive_by: Optional[bool] = False, 277 | dry_run: Optional[bool] = None, 278 | ): 279 | """Get raster for a time value around a given set of coordinates. 280 | 281 | :param locations: Origin of the search as [lon,lat]. 282 | :type locations: list of float 283 | 284 | :param profile: Comma-separated list of transportation modes that the user is willing to 285 | use. Default: "WALK,TRANSIT" 286 | :type profile: str 287 | 288 | :time: Departure date and time (timezone aware). The default value is now (UTC). 289 | :type time: datetime.datetime 290 | 291 | :cutoff: The maximum travel duration in seconds. The default value is one hour. 292 | 293 | :arrive_by: Set to False when searching from the location and True when searching to the 294 | location. Default value: False. 295 | :type arrive_by: bool 296 | 297 | :param dry_run: Print URL and parameters without sending the request. 298 | :param dry_run: bool 299 | 300 | :returns: A raster with the specified range. 301 | :rtype: :class:`routingpy.raster.Raster` 302 | """ 303 | params = [ 304 | ("location", convert.delimit_list(reversed(locations), ",")), 305 | ("time", time.isoformat()), 306 | ("modes", profile), 307 | ("arriveBy", "true" if arrive_by else "false"), 308 | ("cutoff", convert.seconds_to_iso8601(cutoff)), 309 | ] 310 | response = self.client._request( 311 | "/otp/traveltime/surface", 312 | get_params=params, 313 | dry_run=dry_run, 314 | ) 315 | return self._parse_rasters_response(response, cutoff) 316 | 317 | def _parse_rasters_response(self, response, max_travel_time): 318 | if response is None: # pragma: no cover 319 | return Raster() 320 | 321 | return Raster(image=response, max_travel_time=max_travel_time) 322 | 323 | def matrix(self): # pragma: no cover 324 | raise NotImplementedError 325 | -------------------------------------------------------------------------------- /routingpy/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | 18 | import logging 19 | 20 | logger = logging.getLogger("routingpy") 21 | 22 | 23 | def _trans(value, index): 24 | """ 25 | Copyright (c) 2014 Bruno M. Custódio 26 | Copyright (c) 2016 Frederick Jansen 27 | 28 | https://github.com/hicsail/polyline/commit/ddd12e85c53d394404952754e39c91f63a808656 29 | """ 30 | byte, result, shift = None, 0, 0 31 | 32 | while byte is None or byte >= 0x20: 33 | byte = ord(value[index]) - 63 34 | index += 1 35 | result |= (byte & 0x1F) << shift 36 | shift += 5 37 | comp = result & 1 38 | 39 | return ~(result >> 1) if comp else (result >> 1), index 40 | 41 | 42 | def _decode(expression, precision=5, is3d=False, order="lnglat"): 43 | """ 44 | Copyright (c) 2014 Bruno M. Custódio 45 | Copyright (c) 2016 Frederick Jansen 46 | 47 | https://github.com/hicsail/polyline/commit/ddd12e85c53d394404952754e39c91f63a808656 48 | """ 49 | coordinates, index, lat, lng, z, length, factor = ( 50 | [], 51 | 0, 52 | 0, 53 | 0, 54 | 0, 55 | len(expression), 56 | float(10**precision), 57 | ) 58 | 59 | while index < length: 60 | lat_change, index = _trans(expression, index) 61 | lng_change, index = _trans(expression, index) 62 | lat += lat_change 63 | lng += lng_change 64 | if not is3d: 65 | coordinates.append(_get_coords(lat, lng, factor, order=order)) 66 | else: 67 | z_change, index = _trans(expression, index) 68 | z += z_change 69 | coordinates.append((*_get_coords(lat, lng, factor, order=order), z / 100)) 70 | 71 | return coordinates 72 | 73 | 74 | def decode_polyline5(polyline, is3d=False, order="lnglat"): 75 | """Decodes an encoded polyline string which was encoded with a precision of 5. 76 | 77 | :param polyline: An encoded polyline, only the geometry. 78 | :type polyline: str 79 | 80 | :param is3d: Specifies if geometry contains Z component. Currently only GraphHopper and OpenRouteService 81 | support this. Default False. 82 | :type is3d: bool 83 | 84 | :param order: Specifies the order in which the coordinates are returned. 85 | Options: latlng, lnglat. Defaults to 'lnglat'. 86 | :type order: str 87 | 88 | :returns: List of decoded coordinates with precision 5. 89 | :rtype: list 90 | """ 91 | return _decode(polyline, precision=5, is3d=is3d, order=order) 92 | 93 | 94 | def decode_polyline6(polyline, is3d=False, order="lnglat"): 95 | """Decodes an encoded polyline string which was encoded with a precision of 6. 96 | 97 | :param polyline: An encoded polyline, only the geometry. 98 | :type polyline: str 99 | 100 | :param is3d: Specifies if geometry contains Z component. Currently only GraphHopper and OpenRouteService 101 | support this. Default False. 102 | :type is3d: bool 103 | 104 | :param order: Specifies the order in which the coordinates are returned. 105 | Options: latlng, lnglat. Defaults to 'lnglat'. 106 | :type order: str 107 | 108 | :returns: List of decoded coordinates with precision 6. 109 | :rtype: list 110 | """ 111 | 112 | return _decode(polyline, precision=6, is3d=is3d, order=order) 113 | 114 | 115 | def get_ordinal(number): 116 | """Produces an ordinal (1st, 2nd, 3rd, 4th) from a number""" 117 | 118 | if number == 1: 119 | return "st" 120 | elif number == 2: 121 | return "nd" 122 | elif number == 3: 123 | return "rd" 124 | else: 125 | return "th" 126 | 127 | 128 | def _get_coords(lat, lng, factor, order="lnglat"): 129 | """Determines coordinate order.""" 130 | if order not in ("lnglat", "latlng"): 131 | raise ValueError(f"order must be either 'latlng' or 'lnglat', not {order}.") 132 | return (lat / factor, lng / factor) if order == "latlng" else (lng / factor, lat / factor) 133 | -------------------------------------------------------------------------------- /routingpy/valhalla_attributes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | 18 | from enum import Enum 19 | from typing import List, Optional, Tuple, Union 20 | 21 | from routingpy.utils import decode_polyline6 22 | 23 | 24 | class MatchDiscontinuity(str, Enum): 25 | BEGIN = "begin" 26 | END = "end" 27 | NONE = "" 28 | 29 | 30 | class MatchType(str, Enum): 31 | UNMATCHED = "unmatched" 32 | MATCHED = "matched" 33 | INTERPOLATED = "interpolated" 34 | NONE = "" 35 | 36 | 37 | class Traversability(str, Enum): 38 | FORWARD = "forward" 39 | BACKWARD = "backward" 40 | BOTH = "both" 41 | NONE = "" 42 | 43 | 44 | class DrivingSide(str, Enum): 45 | RIGHT = "right" 46 | LEFT = "left" 47 | NONE = "" 48 | 49 | 50 | class Sidewalk(str, Enum): 51 | RIGHT = "right" 52 | LEFT = "left" 53 | BOTH = "both" 54 | NONE = "" 55 | 56 | 57 | class Surface(str, Enum): 58 | PAVED_SMOOTH = "paved_smooth" 59 | PAVED = "paved" 60 | PAVED_ROUGH = "paved_rough" 61 | COMPACTED = "compacted" 62 | DIRT = "dirt" 63 | GRAVEL = "gravel" 64 | PATH = "path" 65 | IMPASSABLE = "impassable" 66 | NONE = "" 67 | 68 | 69 | class RoadClass(str, Enum): 70 | MOTORWAY = "motorway" 71 | TRUCK = "trunk" 72 | PRIMARY = "primary" 73 | SECONDARY = "secondary" 74 | TERTIARY = "tertiary" 75 | UNCLASSIFIED = "unclassified" 76 | RESIDENTIAL = "residential" 77 | SERVICE_OTHER = "service_other" 78 | NONE = "" 79 | 80 | 81 | class Use(str, Enum): 82 | TRAM = "tram" 83 | ROAD = "road" 84 | RAMP = "ramp" 85 | TURN_CHANNEL = "turn_channel" 86 | TRACK = "track" 87 | DRIVEWAY = "driveway" 88 | ALLEY = "alley" 89 | PARKING_AISLE = "parking_aisle" 90 | EMERGENCY_ACCESS = "emergency_access" 91 | DRIVE_TROUGH = "drive_through" 92 | CULDESAC = "culdesac" 93 | CYCLEWAY = "cycleway" 94 | MOUNTAIN_BIKE = "mountain_bike" 95 | SIDEWALK = "sidewalk" 96 | FOOTWAY = "footway" 97 | STEPS = "steps" 98 | OTHER = "other" 99 | RAIL_FERRY = "rail-ferry" 100 | FERRY = "ferry" 101 | RAIL = "rail" 102 | BUS = "bus" 103 | RAIL_CONNECTION = "rail_connection" 104 | BUS_CONNECTION = "bus_connnection" 105 | TRANSIT_CONNECTION = "transit_connection" 106 | NONE = "" 107 | 108 | 109 | class MatchedEdge: 110 | """ 111 | Contains a parsed single line string and its attributes, if specified in the request. 112 | Access via properties ``geometry``, ``distances`` ``durations``, ``costs``, ``edge_ids``, ``statuses``. 113 | """ 114 | 115 | def __init__(self, edge: dict, coords: List[List[float]]): 116 | self._geometry = coords 117 | self._traversability: Optional[Traversability] = ( 118 | Traversability(edge.get("traversability", "")) or None 119 | ) 120 | self._toll: Optional[bool] = edge.get("toll") 121 | self._use: Optional[Use] = Use(edge.get("use")) or None 122 | self._tunnel: Optional[bool] = edge.get("tunnel") 123 | self._names: Optional[List[str]] = edge.get("names") 124 | 125 | driving_side = edge.get("drive_on_right") 126 | if driving_side is True: 127 | self._driving_side = DrivingSide("right") 128 | elif driving_side is False: 129 | self._driving_side = DrivingSide("right") 130 | else: 131 | self._driving_side = None 132 | 133 | self._roundabout: Optional[bool] = edge.get("roundabout") 134 | self._bridge: Optional[bool] = edge.get("bridge") 135 | self._surface: Optional[Surface] = Surface(edge.get("surface", "")) or None 136 | self._edge_id: Optional[int] = edge.get("id") 137 | self._osm_way_id: Optional[int] = edge.get("way_id") 138 | self._speed_limit = edge.get("speed_limit") 139 | self._cycle_lane = edge.get("cycle_lane") 140 | self._sidewalk = Sidewalk(edge.get("sidewalk")) or None 141 | self._lane_count: Optional[int] = edge.get("lane_count") 142 | self._mean_elevation: Optional[int] = edge.get("mean_elevation") 143 | self._weighted_grade: Optional[int] = edge.get("weighted_grade") 144 | self._road_class: Optional[RoadClass] = RoadClass(edge.get("road_class", "")) or None 145 | self._speed: Optional[int] = edge.get("speed") 146 | self._length: Optional[int] = edge.get("length") 147 | 148 | @property 149 | def geometry(self) -> List[List[float]]: 150 | """ 151 | The geometry of the edge as [[lon1, lat1], [lon2, lat2]] list. 152 | """ 153 | return self._geometry 154 | 155 | @property 156 | def traversability(self) -> Optional[Traversability]: 157 | """ 158 | The traversability of the edge, one of :class:`Traversability`. 159 | """ 160 | return self._traversability 161 | 162 | @property 163 | def toll(self) -> Optional[bool]: 164 | """ 165 | Is this a toll road? 166 | """ 167 | return self._toll 168 | 169 | @property 170 | def use(self) -> Optional[Use]: 171 | """ 172 | The Use of this edge as :class:`Use`. 173 | """ 174 | return self._use 175 | 176 | @property 177 | def tunnel(self) -> Optional[bool]: 178 | """ 179 | Is this part of a tunnel? 180 | """ 181 | return self._tunnel 182 | 183 | @property 184 | def names(self) -> Optional[List[str]]: 185 | """ 186 | Returns the list of names and aliases. 187 | """ 188 | return self._names 189 | 190 | @property 191 | def driving_side(self) -> Optional[DrivingSide]: 192 | """ 193 | Returns the :class:`DrivingSide` of the road. 194 | """ 195 | return self._driving_side 196 | 197 | @property 198 | def roundabout(self) -> Optional[bool]: 199 | """ 200 | Is this part of a roundabout? 201 | """ 202 | return self._roundabout 203 | 204 | @property 205 | def bridge(self) -> Optional[bool]: 206 | """ 207 | Is this part of a bridge? 208 | """ 209 | return self._bridge 210 | 211 | @property 212 | def surface(self) -> Optional[Surface]: 213 | """ 214 | Returns the :class:`Surface` value for this road. 215 | """ 216 | return self._surface 217 | 218 | @property 219 | def edge_id(self) -> Optional[int]: 220 | """ 221 | Returns the edge's GraphId? 222 | """ 223 | return self._edge_id 224 | 225 | @property 226 | def osm_way_id(self) -> Optional[int]: 227 | """ 228 | Returns the way's OSM ID. 229 | """ 230 | return self._osm_way_id 231 | 232 | @property 233 | def speed_limit(self) -> Optional[int]: 234 | """ 235 | The legal speed limit, if available 236 | """ 237 | return self._speed_limit 238 | 239 | @property 240 | def cycle_lane(self) -> Optional[str]: 241 | """ 242 | Returns the type (if any) of bicycle lane along this edge. 243 | """ 244 | return self._cycle_lane 245 | 246 | @property 247 | def sidewalk(self) -> Optional[Sidewalk]: 248 | """ 249 | Returns the :class:`Sidewalk` value for this road. 250 | """ 251 | return self._sidewalk 252 | 253 | @property 254 | def lane_count(self) -> Optional[int]: 255 | """ 256 | How many lanes does this road have? 257 | """ 258 | return self._lane_count 259 | 260 | @property 261 | def mean_elevation(self) -> Optional[int]: 262 | """ 263 | The mean elevation of this edge in meters. 264 | """ 265 | return self._mean_elevation 266 | 267 | @property 268 | def weighted_grade(self) -> Optional[float]: 269 | """ 270 | The weighted grade factor. Valhalla manufactures a weighted_grade from elevation data. 271 | It is a measure used for hill avoidance in routing - sort of a relative energy use along 272 | an edge. But since an edge in Valhalla can possibly go up and down over several hills it 273 | might not equate to what most folks think of as grade. 274 | """ 275 | return self._weighted_grade 276 | 277 | @property 278 | def road_class(self) -> Optional[RoadClass]: 279 | """ 280 | Returns the :class:`RoadClass` of this edge. 281 | """ 282 | return self._road_class 283 | 284 | @property 285 | def speed(self) -> Optional[int]: 286 | """ 287 | Returns the actual speed of the edge, as used by Valhalla. 288 | """ 289 | return self._speed 290 | 291 | @property 292 | def length(self) -> Optional[int]: 293 | """ 294 | The length of this edge in meters. 295 | """ 296 | return self._length 297 | 298 | def __repr__(self): # pragma: no cover 299 | return "Edge({})".format(", ".join([f"{k[1:]}: {v}" for k, v in vars(self).items() if v])) 300 | 301 | 302 | class MatchedPoint: 303 | """ 304 | A single matched point 305 | """ 306 | 307 | def __init__(self, point: dict): 308 | self._geometry: List[float] = [point["lon"], point["lat"]] 309 | self._match_type = MatchType(point.get("type", "")) or None 310 | self._dist_along_edge: Optional[float] = point.get("distance_along_edge") 311 | self._dist_from_input: Optional[int] = point.get("distance_from_trace_point") 312 | self._edge_index: Optional[int] = point.get("distance_along_edge") 313 | self._discontinuity: Optional[MatchDiscontinuity] = None 314 | if point.get("begin_route_discontinuity"): 315 | self._discontinuity = MatchDiscontinuity("begin") 316 | elif point.get("end_route_discontinuity"): 317 | self._discontinuity = MatchDiscontinuity("end") 318 | 319 | @property 320 | def geometry(self) -> Union[Tuple[float, float], List[float]]: 321 | """ 322 | The geometry of the point as [lon1, lat1] list. 323 | """ 324 | return self._geometry 325 | 326 | @property 327 | def match_type(self) -> MatchType: 328 | """ 329 | Returns the match type. 330 | """ 331 | return self._match_type 332 | 333 | @property 334 | def distance_along_edge(self) -> Optional[float]: 335 | """ 336 | Returns the relative distance along the matched edge. E.g. if the point 337 | projects to the center of an edge, the return value will be 0.5. 338 | """ 339 | return self._dist_along_edge 340 | 341 | @property 342 | def distance_from_input(self) -> Optional[int]: 343 | """ 344 | Returns the distance of the matched point from the corresponding input location. 345 | """ 346 | return self._dist_from_input 347 | 348 | @property 349 | def edge_index(self) -> Optional[int]: 350 | """ 351 | Returns the edge index. 352 | """ 353 | return self._edge_index 354 | 355 | @property 356 | def discontinuity(self) -> Optional[MatchDiscontinuity]: 357 | """ 358 | Returns the :class:`MatchDiscontinuity` status. 359 | """ 360 | return self._discontinuity 361 | 362 | 363 | class MatchedResults: 364 | """ 365 | Contains a list of :class:`Expansion`, which can be iterated over or accessed by index. The property ¸`raw`` contains 366 | the complete raw response of the expansion request. 367 | """ 368 | 369 | def __init__(self, response: Optional[dict] = None): 370 | self._edges: List[MatchedEdge] = list() 371 | self._points: List[MatchedPoint] = list() 372 | self._raw = response 373 | 374 | if not response: 375 | return 376 | 377 | geometry = decode_polyline6(response["shape"]) 378 | # fill the edges 379 | for edge in response["edges"]: 380 | coords: List[List[float]] = geometry[ 381 | response.get("begin_shape_index") 382 | or 0 : (response.get("end_shape_index") or (len(geometry) - 1)) + 1 383 | ] 384 | self._edges.append(MatchedEdge(edge, coords)) 385 | 386 | # and the nodes 387 | for pt in response["matched_points"]: 388 | self._points.append(MatchedPoint(pt)) 389 | 390 | @property 391 | def raw(self) -> Optional[dict]: 392 | """ 393 | Returns the trace_attribute's raw, unparsed response. For details, consult the documentation 394 | at https://valhalla.readthedocs.io/en/latest/api/map-matching/api-reference/. 395 | 396 | :rtype: dict or None 397 | """ 398 | return self._raw 399 | 400 | @property 401 | def matched_edges(self) -> Optional[List[MatchedEdge]]: 402 | """Returns the list of :class:`MatchedEdge`""" 403 | return self._edges 404 | 405 | @property 406 | def matched_points(self) -> Optional[List[MatchedPoint]]: 407 | """Returns the list of :class:`MatchedEdge`""" 408 | return self._points 409 | 410 | def __repr__(self): # pragma: no cover 411 | if len(self._edges) < 10 and len(self._points) < 10: 412 | return "Expansions({}, {}, {})".format(self._edges, self._points, self.raw) 413 | else: 414 | return "Expansions({}, ..., {}; {}, ..., {})".format( 415 | ", ".join([str(e) for e in self._edges[:3]]), 416 | ", ".join(str(e) for e in self._edges[-3:]), 417 | ", ".join([str(e) for e in self._points[:3]]), 418 | ", ".join(str(e) for e in self._points[-3:]), 419 | ) 420 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | # ignore some errors to play nicely with black 3 | ignore = E203,E266,E501,W503,F403,E722,F405 4 | max-complexity = 15 5 | max-line-length = 105 6 | exclude = .venv,.git,__pycache__,docs,dist,examples 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright 2021 Kenneth Reitz 4 | # 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 7 | # use this file except in compliance with the License. You may obtain a copy of 8 | # the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 15 | # License for the specific language governing permissions and limitations under 16 | # the License. 17 | # 18 | 19 | import os 20 | 21 | from setuptools import find_packages, setup 22 | 23 | here = os.path.abspath(os.path.dirname(__file__)) 24 | 25 | description = "One lib to route them all." 26 | 27 | try: 28 | with open(os.path.join(here, "README.rst"), encoding="utf-8") as f: 29 | long_description = "\n" + f.read() 30 | except FileNotFoundError: 31 | long_description = description 32 | 33 | setup( 34 | name="routingpy", 35 | description=description, 36 | long_description=long_description, 37 | long_description_content_type="text/x-rst", 38 | author="Nils Nolde", 39 | author_email="nils@gis-ops.com", 40 | python_requires=">=3.8.0", 41 | url="https://github.com/gis-ops/routing-py", 42 | packages=find_packages(exclude=["*tests*"]), 43 | install_requires=["requests>=2.20.0"], 44 | license="Apache 2.0", 45 | classifiers=[ 46 | "License :: OSI Approved :: Apache Software License", 47 | "Programming Language :: Python", 48 | "Programming Language :: Python :: 3", 49 | "Programming Language :: Python :: 3.8", 50 | "Programming Language :: Python :: 3.9", 51 | "Programming Language :: Python :: 3.10", 52 | "Programming Language :: Python :: Implementation :: CPython", 53 | "Programming Language :: Python :: Implementation :: PyPy", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | 18 | import unittest 19 | from urllib.parse import parse_qsl, urlparse 20 | 21 | 22 | class TestCase(unittest.TestCase): 23 | def assertURLEqual(self, first, second, msg=None): 24 | """Check that two arguments are equivalent URLs. Ignores the order of 25 | query arguments. 26 | """ 27 | first_parsed = urlparse(first) 28 | second_parsed = urlparse(second) 29 | self.assertEqual(first_parsed[:3], second_parsed[:3], msg) 30 | 31 | first_qsl = sorted(parse_qsl(first_parsed.query)) 32 | second_qsl = sorted(parse_qsl(second_parsed.query)) 33 | self.assertEqual(first_qsl, second_qsl, msg) 34 | -------------------------------------------------------------------------------- /tests/raster_example.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nilsnolde/routingpy/d4ab72e61e2e7d6a6af0c7fd55b11350454d90ca/tests/raster_example.tiff -------------------------------------------------------------------------------- /tests/test_base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for client module.""" 18 | 19 | import time 20 | 21 | import requests 22 | import responses 23 | 24 | import routingpy 25 | import tests as _test 26 | from routingpy import client_default 27 | from routingpy.routers import options 28 | 29 | 30 | class ClientMock(client_default.Client): 31 | def __init__(self, *args, **kwargs): 32 | super(ClientMock, self).__init__(*args, **kwargs) 33 | 34 | def directions(self, *args, **kwargs): 35 | return self._request(*args, **kwargs) 36 | 37 | def isochrones(self): 38 | pass 39 | 40 | def matrix(self): 41 | pass 42 | 43 | 44 | class BaseTest(_test.TestCase): 45 | def setUp(self): 46 | self.client = ClientMock("https://httpbin.org/") 47 | self.params = {"c": "d", "a": "b", "1": "2"} 48 | 49 | def test_router_by_name(self): 50 | for s in routingpy.routers._SERVICE_TO_ROUTER.keys(): 51 | routingpy.routers.get_router_by_name(s) 52 | 53 | with self.assertRaises(routingpy.exceptions.RouterNotFound): 54 | routingpy.routers.get_router_by_name("orsm") 55 | 56 | def test_options(self): 57 | options.default_user_agent = "my_agent" 58 | options.default_timeout = 10 59 | options.default_retry_timeout = 10 60 | options.default_retry_over_query_limit = False 61 | options.default_proxies = {"https": "192.103.10.102"} 62 | new_client = ClientMock("https://foo.bar") 63 | req_kwargs = { 64 | "timeout": options.default_timeout, 65 | "headers": {"User-Agent": options.default_user_agent, "Content-Type": "application/json"}, 66 | "proxies": options.default_proxies, 67 | } 68 | self.assertEqual(req_kwargs, new_client.kwargs) 69 | self.assertEqual(new_client.retry_over_query_limit, options.default_retry_over_query_limit) 70 | 71 | def test_urlencode(self): 72 | encoded_params = self.client._generate_auth_url("directions", self.params) 73 | self.assertEqual("directions?1=2&a=b&c=d", encoded_params) 74 | 75 | @responses.activate 76 | def test_skip_api_error(self): 77 | query = self.params 78 | responses.add( 79 | responses.POST, 80 | "https://httpbin.org/post", 81 | json=query, 82 | status=400, 83 | content_type="application/json", 84 | ) 85 | 86 | client = ClientMock(base_url="https://httpbin.org", skip_api_error=False) 87 | print(client.skip_api_error) 88 | with self.assertRaises(routingpy.exceptions.RouterApiError): 89 | client.directions(url="/post", post_params=self.params) 90 | 91 | client = ClientMock(base_url="https://httpbin.org", skip_api_error=True) 92 | client.directions(url="/post", post_params=self.params) 93 | self.assertEqual(responses.calls[1].response.json(), query) 94 | 95 | @responses.activate 96 | def test_retry_timeout(self): 97 | query = self.params 98 | responses.add( 99 | responses.POST, 100 | "https://httpbin.org/post", 101 | json=query, 102 | status=429, 103 | content_type="application/json", 104 | ) 105 | 106 | client = ClientMock(base_url="https://httpbin.org", retry_over_query_limit=True, retry_timeout=3) 107 | with self.assertRaises(routingpy.exceptions.OverQueryLimit): 108 | client.directions(url="/post", post_params=query) 109 | 110 | @responses.activate 111 | def test_raise_over_query_limit(self): 112 | query = self.params 113 | responses.add( 114 | responses.POST, 115 | "https://httpbin.org/post", 116 | json=query, 117 | status=429, 118 | content_type="application/json", 119 | ) 120 | 121 | with self.assertRaises(routingpy.exceptions.OverQueryLimit): 122 | client = ClientMock(base_url="https://httpbin.org", retry_over_query_limit=False) 123 | client.directions(url="/post", post_params=query) 124 | 125 | @responses.activate 126 | def test_raise_timeout_retriable_requests(self): 127 | # Mock query gives 503 as HTTP status, code should try a few times to 128 | # request the same and then fail on Timeout() error. 129 | retry_timeout = 3 130 | query = self.params 131 | responses.add( 132 | responses.POST, 133 | "https://httpbin.org/post", 134 | json=query, 135 | status=503, 136 | content_type="application/json", 137 | ) 138 | 139 | client = ClientMock(base_url="https://httpbin.org", retry_timeout=retry_timeout) 140 | 141 | start = time.time() 142 | with self.assertRaises(routingpy.exceptions.Timeout): 143 | client.directions(url="/post", post_params=self.params) 144 | end = time.time() 145 | self.assertTrue(retry_timeout < end - start < 2 * retry_timeout) 146 | 147 | @responses.activate 148 | def test_dry_run(self): 149 | # Test that nothing is requested when dry_run is 'true' 150 | 151 | responses.add( 152 | responses.POST, 153 | "https://api.openrouteservice.org/directions", 154 | json=None, 155 | status=200, 156 | content_type="application/json", 157 | ) 158 | 159 | self.client.directions(get_params={"format_out": "geojson"}, url="directions/", dry_run="true") 160 | 161 | self.assertEqual(0, len(responses.calls)) 162 | 163 | def test_headers(self): 164 | # Test that existing request_kwargs keys are not scrubbed 165 | 166 | timeout = {"holaDieWaldFee": 600} 167 | headers = {"headers": {"X-Rate-Limit": "50"}} 168 | 169 | client = ClientMock("https://httpbin.org", **dict(timeout, **headers)) 170 | 171 | self.assertTrue(timeout.items() <= {**timeout, **client.kwargs}.items()) 172 | self.assertTrue( 173 | headers["headers"].items() <= {**headers["headers"], **client.kwargs["headers"]}.items() 174 | ) 175 | 176 | @responses.activate 177 | def test_req_property(self): 178 | # Test if the req property is a PreparedRequest 179 | 180 | responses.add( 181 | responses.GET, 182 | "https://httpbin.org/routes?a=b", 183 | json={}, 184 | status=200, 185 | content_type="application/json", 186 | ) 187 | 188 | self.client.directions(url="routes", get_params={"a": "b"}) 189 | 190 | assert isinstance(self.client.req, requests.PreparedRequest) 191 | self.assertEqual("https://httpbin.org/routes?a=b", self.client.req.url) 192 | -------------------------------------------------------------------------------- /tests/test_convert.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for convert module.""" 18 | 19 | import tests as _test 20 | from routingpy import convert 21 | 22 | 23 | class UtilsTest(_test.TestCase): # noqa: E741 24 | def test_delimit_list(self): 25 | l = [(8.68864, 49.42058), (8.68092, 49.41578)] # noqa: E741 26 | s = convert.delimit_list([convert.delimit_list(pair, ",") for pair in l], "|") 27 | self.assertEqual(s, "8.68864,49.42058|8.68092,49.41578") 28 | 29 | def test_delimit_list_error(self): 30 | falses = ["8", 8, {"a": "b", 3: "a", 4: 4}] 31 | for f in falses: 32 | with self.assertRaises(TypeError): 33 | convert.delimit_list(f) 34 | -------------------------------------------------------------------------------- /tests/test_google.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the Google module.""" 18 | 19 | from copy import deepcopy 20 | 21 | import responses 22 | 23 | import tests as _test 24 | from routingpy import Google 25 | from routingpy.direction import Direction, Directions 26 | from routingpy.exceptions import RouterApiError, RouterServerError 27 | from routingpy.matrix import Matrix 28 | from tests.test_helper import * 29 | 30 | 31 | class GoogleTest(_test.TestCase): 32 | name = "google" 33 | 34 | def setUp(self): 35 | self.key = "sample_key" 36 | self.client = Google(api_key=self.key) 37 | 38 | @responses.activate 39 | def test_full_directions(self): 40 | query = ENDPOINTS_QUERIES[self.name]["directions"] 41 | 42 | responses.add( 43 | responses.GET, 44 | "https://maps.googleapis.com/maps/api/directions/json", 45 | status=200, 46 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 47 | content_type="application/json", 48 | ) 49 | 50 | routes = self.client.directions(**query) 51 | self.assertEqual(1, len(responses.calls)) 52 | self.assertURLEqual( 53 | "https://maps.googleapis.com/maps/api/directions/json?alternatives=true&arrival_time=1567512000&" 54 | "avoid=tolls%7Cferries&destination=49.445776%2C8.780916&key=sample_key&language=de&origin=49.420577%2C8.688641&" 55 | "mode=driving®ion=de&traffic_model=optimistic&transit_mode=bus%7Crail&transit_routing_preference=less_walking&" 56 | "units=metrics&waypoints=49.415776%2C8.680916", 57 | responses.calls[0].request.url, 58 | ) 59 | 60 | self.assertIsInstance(routes, Directions) 61 | self.assertIsInstance(routes[0], Direction) 62 | self.assertIsInstance(routes[0].geometry, list) 63 | self.assertIsInstance(routes[0].distance, int) 64 | self.assertIsInstance(routes[0].duration, int) 65 | self.assertIsInstance(routes[0].raw, dict) 66 | 67 | @responses.activate 68 | def test_full_directions_no_alternatives(self): 69 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 70 | query["alternatives"] = False 71 | 72 | responses.add( 73 | responses.GET, 74 | "https://maps.googleapis.com/maps/api/directions/json", 75 | status=200, 76 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 77 | content_type="application/json", 78 | ) 79 | 80 | routes = self.client.directions(**query) 81 | self.assertEqual(1, len(responses.calls)) 82 | self.assertURLEqual( 83 | "https://maps.googleapis.com/maps/api/directions/json?alternatives=false&arrival_time=1567512000&" 84 | "avoid=tolls%7Cferries&destination=49.445776%2C8.780916&key=sample_key&language=de&origin=49.420577%2C8.688641&" 85 | "mode=driving®ion=de&traffic_model=optimistic&transit_mode=bus%7Crail&transit_routing_preference=less_walking&" 86 | "units=metrics&waypoints=49.415776%2C8.680916", 87 | responses.calls[0].request.url, 88 | ) 89 | 90 | self.assertIsInstance(routes, Direction) 91 | self.assertIsInstance(routes.geometry, list) 92 | self.assertIsInstance(routes.duration, int) 93 | self.assertIsInstance(routes.distance, int) 94 | self.assertIsInstance(routes.raw, dict) 95 | 96 | @responses.activate 97 | def test_waypoint_generator_directions(self): 98 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 99 | query["locations"] = [ 100 | PARAM_LINE_MULTI[1], 101 | Google.WayPoint("osazgqo@/@", "enc", False), 102 | Google.WayPoint(PARAM_LINE_MULTI[1], "coords", True), 103 | Google.WayPoint( 104 | "EiNNYXJrdHBsLiwgNjkxMTcgSGVpZGVsYmVyZywgR2VybWFueSIuKiwKFAoSCdubgq0HwZdHEdclR2bm32EmEhQKEgmTG6mCBsGXRxF38ZZ8m5j3VQ", 105 | "place_id", 106 | False, 107 | ), 108 | PARAM_LINE_MULTI[0], 109 | ] 110 | query["optimize"] = True 111 | 112 | responses.add( 113 | responses.GET, 114 | "https://maps.googleapis.com/maps/api/directions/json", 115 | status=200, 116 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 117 | content_type="application/json", 118 | ) 119 | 120 | self.client.directions(**query) 121 | 122 | self.assertEqual(1, len(responses.calls)) 123 | self.assertURLEqual( 124 | "https://maps.googleapis.com/maps/api/directions/json?alternatives=true&arrival_time=1567512000&" 125 | "avoid=tolls%7Cferries&destination=49.420577%2C8.688641&key=sample_key&language=de&" 126 | "origin=49.415776%2C8.680916&mode=driving®ion=de&traffic_model=optimistic&transit_mode=bus%7Crail&t" 127 | "ransit_routing_preference=less_walking&units=metrics&waypoints=optimize%3Atrue%7Cvia%3Aenc%3Aosazgqo%40%2F%40%3A%7C49.415776%2C8.680916%7C" 128 | "via%3Aplace_id%3AEiNNYXJrdHBsLiwgNjkxMTcgSGVpZGVsYmVyZywgR2VybWFueSIuKiwKFAoSCdubgq0HwZdHEdclR2bm32EmEhQKEgmTG6mCBsGXRxF38ZZ8m5j3VQ", 129 | responses.calls[0].request.url, 130 | ) 131 | 132 | # Test if 'bla' triggers a ValueError 133 | query["locations"].insert(1, Google.WayPoint(PARAM_LINE_MULTI[0], "bla", True)) 134 | 135 | with self.assertRaises(ValueError): 136 | self.client.directions(**query) 137 | 138 | # Test if origin=WayPoint triggers a TypeError 139 | query["coordinates"] = [ 140 | Google.WayPoint("osazgqo@/@", "enc", False), 141 | Google.WayPoint(PARAM_LINE_MULTI[1], "coords", True), 142 | ] 143 | 144 | with self.assertRaises(TypeError): 145 | self.client.directions(**query) 146 | 147 | @responses.activate 148 | def test_full_matrix(self): 149 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 150 | 151 | responses.add( 152 | responses.GET, 153 | "https://maps.googleapis.com/maps/api/distancematrix/json", 154 | status=200, 155 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 156 | content_type="application/json", 157 | ) 158 | 159 | matrix = self.client.matrix(**query) 160 | 161 | self.assertEqual(1, len(responses.calls)) 162 | self.assertURLEqual( 163 | "https://maps.googleapis.com/maps/api/distancematrix/json?arrival_time=1567512000&avoid=tolls%7Cferries&" 164 | "destinations=49.420577%2C8.688641%7C49.415776%2C8.680916%7C49.445776%2C8.780916&key=sample_key&language=de&" 165 | "origins=49.420577%2C8.688641%7C49.415776%2C8.680916%7C49.445776%2C8.780916&mode=driving®ion=de&" 166 | "traffic_model=optimistic&transit_mode=bus%7Crail&transit_routing_preference=less_walking&units=metrics", 167 | responses.calls[0].request.url, 168 | ) 169 | 170 | self.assertIsInstance(matrix, Matrix) 171 | self.assertIsInstance(matrix.durations, list) 172 | self.assertIsInstance(matrix.distances, list) 173 | 174 | @responses.activate 175 | def test_few_sources_destinations_matrix(self): 176 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 177 | query["sources"] = [1] 178 | query["destinations"] = [0] 179 | 180 | responses.add( 181 | responses.GET, 182 | "https://maps.googleapis.com/maps/api/distancematrix/json", 183 | status=200, 184 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 185 | content_type="application/json", 186 | ) 187 | 188 | matrix = self.client.matrix(**query) 189 | 190 | self.assertEqual(1, len(responses.calls)) 191 | self.assertURLEqual( 192 | "https://maps.googleapis.com/maps/api/distancematrix/json?arrival_time=1567512000&avoid=tolls%7Cferries&" 193 | "destinations=49.420577%2C8.688641&key=sample_key&language=de&origins=49.415776%2C8.680916&mode=driving&" 194 | "region=de&traffic_model=optimistic&transit_mode=bus%7Crail&transit_routing_preference=less_walking&" 195 | "units=metrics", 196 | responses.calls[0].request.url, 197 | ) 198 | 199 | self.assertIsInstance(matrix, Matrix) 200 | self.assertIsInstance(matrix.durations, list) 201 | self.assertIsInstance(matrix.distances, list) 202 | 203 | @responses.activate 204 | def test_waypoint_generator_matrix(self): 205 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 206 | query["locations"] = [ 207 | PARAM_LINE_MULTI[1], 208 | Google.WayPoint("osazgqo@/@", "enc", False), 209 | Google.WayPoint(PARAM_LINE_MULTI[1], "coords", True), 210 | Google.WayPoint( 211 | "EiNNYXJrdHBsLiwgNjkxMTcgSGVpZGVsYmVyZywgR2VybWFueSIuKiwKFAoSCdubgq0HwZdHEdclR2bm32EmEhQKEgmTG6mCBsGXRxF38ZZ8m5j3VQ", 212 | "place_id", 213 | False, 214 | ), 215 | PARAM_LINE_MULTI[0], 216 | ] 217 | 218 | responses.add( 219 | responses.GET, 220 | "https://maps.googleapis.com/maps/api/distancematrix/json", 221 | status=200, 222 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 223 | content_type="application/json", 224 | ) 225 | 226 | self.client.matrix(**query) 227 | 228 | self.assertEqual(1, len(responses.calls)) 229 | self.assertURLEqual( 230 | "https://maps.googleapis.com/maps/api/distancematrix/json?arrival_time=1567512000&avoid=tolls%7Cferries&" 231 | "destinations=49.415776%2C8.680916%7Cvia%3Aenc%3Aosazgqo%40%2F%40%3A%7C49.415776%2C8.680916%7Cvia%3Aplace_id%3A" 232 | "EiNNYXJrdHBsLiwgNjkxMTcgSGVpZGVsYmVyZywgR2VybWFueSIuKiwKFAoSCdubgq0HwZdHEdclR2bm32EmEhQKEgmTG6mCBsGXRxF38ZZ8m5j3VQ%7C49.420577%2C8.688641&" 233 | "key=sample_key&language=de&origins=49.415776%2C8.680916%7Cvia%3Aenc%3Aosazgqo%40%2F%40%3A%7C49.415776%2C8.680916%7Cvia%3Aplace_id%3AEiNNYXJrdHBsLiwgNjkxMTcgSGVpZGVsYmVyZywgR2VybWFueSIuKiwKFAoSCdubgq0HwZdHEdclR2bm32EmEhQKEgmTG6mCBsGXRxF38ZZ8m5j3VQ%7C49.420577%2C8.688641&" 234 | "mode=driving®ion=de&traffic_model=optimistic&transit_mode=bus%7Crail&transit_routing_preference=less_walking&units=metrics", 235 | responses.calls[0].request.url, 236 | ) 237 | 238 | def test_status_codes(self): 239 | error_responses = ENDPOINTS_ERROR_RESPONSES[self.name] 240 | 241 | for alternatives in [True, False]: 242 | with self.assertRaises(RouterApiError): 243 | self.client.parse_direction_json( 244 | error_responses["ZERO_RESULTS"], alternatives=alternatives 245 | ) 246 | 247 | with self.assertRaises(RouterServerError): 248 | self.client.parse_direction_json( 249 | error_responses["UNKNOWN_ERROR"], alternatives=alternatives 250 | ) 251 | -------------------------------------------------------------------------------- /tests/test_graphhopper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the Graphhopper module.""" 18 | 19 | import json 20 | from copy import deepcopy 21 | 22 | import responses 23 | 24 | import tests as _test 25 | from routingpy import Graphhopper 26 | from routingpy.direction import Direction, Directions 27 | from routingpy.isochrone import Isochrone, Isochrones 28 | from routingpy.matrix import Matrix 29 | from routingpy.utils import decode_polyline5 30 | from tests.test_helper import * 31 | 32 | 33 | class GraphhopperTest(_test.TestCase): 34 | name = "graphhopper" 35 | 36 | def setUp(self): 37 | self.key = "sample_key" 38 | self.client = Graphhopper(api_key=self.key) 39 | 40 | @responses.activate 41 | def test_full_directions(self): 42 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 43 | query["algorithm"] = None 44 | query["fake_option"] = 42 45 | expected = deepcopy(ENDPOINTS_EXPECTED[self.name]["directions"]) 46 | 47 | responses.add( 48 | responses.POST, 49 | "https://graphhopper.com/api/1/route", 50 | status=200, 51 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 52 | content_type="application/json", 53 | ) 54 | 55 | routes = self.client.directions(**query) 56 | self.assertEqual(1, len(responses.calls)) 57 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 58 | self.assertIsInstance(routes, Direction) 59 | self.assertIsInstance(routes.geometry, list) 60 | self.assertIsInstance(routes.duration, int) 61 | self.assertIsInstance(routes.distance, int) 62 | self.assertIsInstance(routes.raw, dict) 63 | 64 | @responses.activate 65 | def test_full_directions_alternatives(self): 66 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 67 | 68 | responses.add( 69 | responses.POST, 70 | "https://graphhopper.com/api/1/route", 71 | status=200, 72 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 73 | content_type="application/json", 74 | ) 75 | 76 | routes = self.client.directions(**query) 77 | self.assertEqual(1, len(responses.calls)) 78 | self.assertIsInstance(routes, Directions) 79 | self.assertEqual(3, len(routes)) 80 | self.assertIsInstance(routes[0], Direction) 81 | self.assertIsInstance(routes[0].geometry, list) 82 | self.assertIsInstance(routes[0].duration, int) 83 | self.assertIsInstance(routes[0].distance, int) 84 | self.assertIsInstance(routes[0].raw, dict) 85 | 86 | @responses.activate 87 | def test_full_directions_not_encoded(self): 88 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 89 | query["points_encoded"] = False 90 | query["algorithm"] = None 91 | 92 | res = ENDPOINTS_RESPONSES[self.name]["directions"] 93 | res["paths"][0]["points"] = dict(coordinates=decode_polyline5(res["paths"][0]["points"])) 94 | 95 | responses.add( 96 | responses.POST, 97 | "https://graphhopper.com/api/1/route", 98 | status=200, 99 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 100 | content_type="application/json", 101 | ) 102 | 103 | route = self.client.directions(**query) 104 | self.assertEqual(1, len(responses.calls)) 105 | 106 | self.assertIsInstance(route, Direction) 107 | self.assertIsInstance(route.geometry, list) 108 | self.assertIsInstance(route.duration, int) 109 | self.assertIsInstance(route.distance, int) 110 | self.assertIsInstance(route.raw, dict) 111 | 112 | @responses.activate 113 | def test_full_isochrones(self): 114 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["isochrones"]) 115 | query["buckets"] = 3 116 | query["fake_option"] = 42 117 | 118 | responses.add( 119 | responses.GET, 120 | "https://graphhopper.com/api/1/isochrone", 121 | status=200, 122 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 123 | content_type="application/json", 124 | ) 125 | 126 | isochrones = self.client.isochrones(**query) 127 | self.assertEqual(1, len(responses.calls)) 128 | self.assertURLEqual( 129 | "https://graphhopper.com/api/1/isochrone?buckets=3&debug=false&key=sample_key&" 130 | "point=48.23424%2C8.34234&profile=car&reverse_flow=true&time_limit=1000&type=json&fake_option=42", 131 | responses.calls[0].request.url, 132 | ) 133 | 134 | self.assertIsInstance(isochrones, Isochrones) 135 | self.assertEqual(3, len(isochrones)) 136 | self.assertIsInstance(isochrones.raw, dict) 137 | for iso in isochrones: 138 | self.assertIsInstance(iso, Isochrone) 139 | self.assertIsInstance(iso.geometry, list) 140 | self.assertIsInstance(iso.interval, int) 141 | self.assertIsInstance(iso.center, list) 142 | self.assertEqual(iso.interval_type, "time") 143 | 144 | @responses.activate 145 | def test_full_matrix(self): 146 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 147 | query["fake_option"] = 42 148 | 149 | responses.add( 150 | responses.GET, 151 | "https://graphhopper.com/api/1/matrix", 152 | status=200, 153 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 154 | content_type="application/json", 155 | ) 156 | 157 | matrix = self.client.matrix(**query) 158 | self.assertEqual(1, len(responses.calls)) 159 | self.assertURLEqual( 160 | "https://graphhopper.com/api/1/matrix?key=sample_key&out_array=distances&out_array=times&out_array=weights&" 161 | "point=49.415776%2C8.680916&point=49.420577%2C8.688641&point=49.445776%2C8.780916&profile=car&debug=true&fake_option=42", 162 | responses.calls[0].request.url, 163 | ) 164 | 165 | self.assertIsInstance(matrix, Matrix) 166 | self.assertIsInstance(matrix.durations, list) 167 | self.assertIsInstance(matrix.distances, list) 168 | self.assertIsInstance(matrix.raw, dict) 169 | 170 | @responses.activate 171 | def test_few_sources_destinations_matrix(self): 172 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 173 | query["sources"] = [0, 1, 2] 174 | query["destinations"] = [0, 1, 2] 175 | 176 | responses.add( 177 | responses.GET, 178 | "https://graphhopper.com/api/1/matrix", 179 | status=200, 180 | json={}, 181 | content_type="application/json", 182 | ) 183 | self.client.matrix(**query) 184 | 185 | query["sources"] = None 186 | query["destinations"] = None 187 | 188 | responses.add( 189 | responses.GET, 190 | "https://graphhopper.com/api/1/matrix", 191 | status=200, 192 | json={}, 193 | content_type="application/json", 194 | ) 195 | 196 | self.client.matrix(**query) 197 | 198 | self.assertEqual(2, len(responses.calls)) 199 | self.assertURLEqual( 200 | "https://graphhopper.com/api/1/matrix?from_point=49.415776%2C8.680916&from_point=49.420577%2C8.688641&" 201 | "from_point=49.445776%2C8.780916&key=sample_key&out_array=distances" 202 | "&out_array=times&out_array=weights&profile=car&to_point=49.415776%2C8.680916&to_point=49.420577%2C8.688641&" 203 | "&to_point=49.445776%2C8.780916&debug=true", 204 | responses.calls[0].request.url, 205 | ) 206 | self.assertURLEqual( 207 | "https://graphhopper.com/api/1/matrix?point=49.415776%2C8.680916&point=49.420577%2C8.688641&" 208 | "point=49.445776%2C8.780916&key=sample_key&out_array=distances" 209 | "&out_array=times&out_array=weights&profile=car" 210 | "&debug=true", 211 | responses.calls[1].request.url, 212 | ) 213 | 214 | def test_index_sources_matrix(self): 215 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 216 | query["sources"] = [100] 217 | 218 | self.assertRaises(IndexError, lambda: self.client.matrix(**query)) 219 | 220 | def test_index_destinations_matrix(self): 221 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 222 | query["destinations"] = [100] 223 | 224 | self.assertRaises(IndexError, lambda: self.client.matrix(**query)) 225 | -------------------------------------------------------------------------------- /tests/test_mapbox_osrm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the Graphhopper module.""" 18 | 19 | from collections import Counter 20 | from copy import deepcopy 21 | 22 | import responses 23 | 24 | import tests as _test 25 | from routingpy import MapboxOSRM, convert 26 | from routingpy.direction import Direction, Directions 27 | from routingpy.isochrone import Isochrone, Isochrones 28 | from routingpy.matrix import Matrix 29 | from tests.test_helper import * 30 | 31 | 32 | class MapboxOSRMTest(_test.TestCase): 33 | name = "mapbox_osrm" 34 | 35 | def setUp(self): 36 | self.client = MapboxOSRM(api_key="sample_key") 37 | 38 | @responses.activate 39 | def test_full_directions(self): 40 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 41 | query["alternatives"] = False 42 | 43 | responses.add( 44 | responses.POST, 45 | "https://api.mapbox.com/directions/v5/mapbox/{}".format(query["profile"]), 46 | status=200, 47 | json=ENDPOINTS_RESPONSES["mapbox_osrm"]["directions"], 48 | content_type="application/x-www-form-urlencoded", 49 | ) 50 | 51 | routes = self.client.directions(**query) 52 | self.assertEqual(1, len(responses.calls)) 53 | 54 | # python 3.5 dict doesn't guarantee the order when added input to x-www-form-urlencoded 55 | expected_url = ( 56 | "coordinates=8.688641%2C49.420577%3B8.680916%2C49.415776%3B8.780916%2C49.445776&" 57 | "radiuses=500%3B500%3B500&bearings=50%2C50%3B50%2C50%3B50%2C50&alternatives=false&steps=true&" 58 | "continue_straight=true&annotations=duration%2Cdistance%2Cspeed&geometries=geojson&" 59 | "overview=simplified&exclude=motorway&approaches=%3Bcurb%3Bcurb%3Bcurb&banner_instuctions=true&" 60 | "language=de&roundabout_exits=true&voide_instructions=true&voice_units=metric&" 61 | "waypoint_names=a%3Bb%3Bc&waypoint_targets=%3B8.688641%2C49.420577%3B8.680916%2C49.415776%3B" 62 | "8.780916%2C49.445776" 63 | ).split("&") 64 | called_url = responses.calls[0].request.body.split("&") 65 | self.assertTrue(Counter(expected_url) == Counter(called_url)) 66 | 67 | self.assertIsInstance(routes, Direction) 68 | self.assertIsInstance(routes.geometry, list) 69 | self.assertIsInstance(routes.duration, int) 70 | self.assertIsInstance(routes.distance, int) 71 | self.assertIsInstance(routes.raw, dict) 72 | 73 | @responses.activate 74 | def test_full_directions_alternatives(self): 75 | query = ENDPOINTS_QUERIES[self.name]["directions"] 76 | 77 | responses.add( 78 | responses.POST, 79 | "https://api.mapbox.com/directions/v5/mapbox/{}".format(query["profile"]), 80 | status=200, 81 | json=ENDPOINTS_RESPONSES["mapbox_osrm"]["directions"], 82 | content_type="application/x-www-form-urlencoded", 83 | ) 84 | 85 | routes = self.client.directions(**query) 86 | 87 | self.assertEqual(1, len(responses.calls)) 88 | 89 | # python 3.5 dict doesn't guarantee the order when added input to x-www-form-urlencoded 90 | expected_url = ( 91 | "coordinates=8.688641%2C49.420577%3B8.680916%2C49.415776%3B8.780916%2C49.445776&" 92 | "radiuses=500%3B500%3B500&bearings=50%2C50%3B50%2C50%3B50%2C50&alternatives=3&steps=true&" 93 | "continue_straight=true&annotations=duration%2Cdistance%2Cspeed&geometries=geojson&" 94 | "overview=simplified&exclude=motorway&approaches=%3Bcurb%3Bcurb%3Bcurb&banner_instuctions=true&" 95 | "language=de&roundabout_exits=true&voide_instructions=true&voice_units=metric&" 96 | "waypoint_names=a%3Bb%3Bc&waypoint_targets=%3B8.688641%2C49.420577%3B8.680916%2C49.415776%3B" 97 | "8.780916%2C49.445776" 98 | ).split("&") 99 | called_url = responses.calls[0].request.body.split("&") 100 | self.assertTrue(Counter(expected_url) == Counter(called_url)) 101 | 102 | self.assertIsInstance(routes, Directions) 103 | self.assertEqual(1, len(routes)) 104 | self.assertIsInstance(routes[0], Direction) 105 | self.assertIsInstance(routes[0].geometry, list) 106 | self.assertIsInstance(routes[0].duration, int) 107 | self.assertIsInstance(routes[0].distance, int) 108 | self.assertIsInstance(routes.raw, dict) 109 | 110 | @responses.activate 111 | def test_full_isochrones(self): 112 | query = ENDPOINTS_QUERIES[self.name]["isochrones"] 113 | 114 | responses.add( 115 | responses.GET, 116 | "https://api.mapbox.com/isochrone/v1/mapbox/{}/{}".format( 117 | query["profile"], 118 | convert.delimit_list(query["locations"]), 119 | ), 120 | status=200, 121 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 122 | content_type="application/json", 123 | ) 124 | 125 | iso = self.client.isochrones(**query) 126 | 127 | self.assertEqual(1, len(responses.calls)) 128 | self.assertURLEqual( 129 | "https://api.mapbox.com/isochrone/v1/mapbox/driving/8.34234,48.23424?access_token=sample_key&" 130 | "contours_colors=ff0000%2C00FF00&contours_minutes=10%2C20&denoise=0.1&generalize=0.5&polygons=True", 131 | responses.calls[0].request.url, 132 | ) 133 | self.assertIsInstance(iso, Isochrones) 134 | self.assertEqual(2, len(iso)) 135 | for ischrone in iso: 136 | self.assertIsInstance(ischrone, Isochrone) 137 | self.assertIsInstance(ischrone.geometry, list) 138 | self.assertIsInstance(ischrone.interval, int) 139 | self.assertIsInstance(ischrone.center, list) 140 | 141 | @responses.activate 142 | def test_full_matrix(self): 143 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 144 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 145 | 146 | responses.add( 147 | responses.GET, 148 | "https://api.mapbox.com/directions-matrix/v1/mapbox/{}/{}".format(query["profile"], coords), 149 | status=200, 150 | json=ENDPOINTS_RESPONSES["mapbox_osrm"]["matrix"], 151 | content_type="application/json", 152 | ) 153 | 154 | matrix = self.client.matrix(**query) 155 | 156 | self.assertEqual(1, len(responses.calls)) 157 | self.assertURLEqual( 158 | "https://api.mapbox.com/directions-matrix/v1/mapbox/driving/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?" 159 | "access_token=sample_key&annotations=distance%2Cduration&fallback_speed=50", 160 | responses.calls[0].request.url, 161 | ) 162 | self.assertIsInstance(matrix, Matrix) 163 | self.assertIsInstance(matrix.distances, list) 164 | self.assertIsInstance(matrix.durations, list) 165 | self.assertIsInstance(matrix.raw, dict) 166 | 167 | @responses.activate 168 | def test_few_sources_destinations_matrix(self): 169 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 170 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 171 | 172 | query["sources"] = [1, 2] 173 | query["destinations"] = [0, 2] 174 | 175 | responses.add( 176 | responses.GET, 177 | "https://api.mapbox.com/directions-matrix/v1/mapbox/{}/{}".format(query["profile"], coords), 178 | status=200, 179 | json=ENDPOINTS_RESPONSES["mapbox_osrm"]["matrix"], 180 | content_type="application/json", 181 | ) 182 | 183 | self.client.matrix(**query) 184 | 185 | self.assertEqual(1, len(responses.calls)) 186 | self.assertURLEqual( 187 | "https://api.mapbox.com/directions-matrix/v1/mapbox/driving/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?" 188 | "access_token=sample_key&annotations=distance%2Cduration&destinations=0%3B2&fallback_speed=50&sources=1%3B2", 189 | responses.calls[0].request.url, 190 | ) 191 | -------------------------------------------------------------------------------- /tests/test_openrouteservice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the openrouteservice module.""" 18 | 19 | import json 20 | from copy import deepcopy 21 | 22 | import responses 23 | from requests.structures import CaseInsensitiveDict 24 | 25 | import tests as _test 26 | from routingpy import ORS 27 | from routingpy.direction import Direction 28 | from routingpy.isochrone import Isochrone, Isochrones 29 | from routingpy.matrix import Matrix 30 | from tests.test_helper import * 31 | 32 | 33 | class ORSTest(_test.TestCase): 34 | name = "ors" 35 | 36 | def setUp(self): 37 | self.key = "sample_key" 38 | self.client = ORS(api_key=self.key) 39 | 40 | @responses.activate 41 | def test_directions_json(self): 42 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 43 | 44 | responses.add( 45 | responses.POST, 46 | "https://api.openrouteservice.org/v2/directions/{}/json".format(query["profile"]), 47 | status=200, 48 | json=ENDPOINTS_RESPONSES[self.name]["directions"]["json"], 49 | content_type="application/json", 50 | ) 51 | 52 | routes = self.client.directions(**query, format="json") 53 | 54 | query["coordinates"] = query["locations"] 55 | del query["locations"] 56 | del query["profile"] 57 | 58 | self.assertEqual(1, len(responses.calls)) 59 | self.assertEqual(query, json.loads(responses.calls[0].request.body.decode("utf-8"))) 60 | 61 | self.assertIsInstance(routes, Direction) 62 | self.assertIsInstance(routes.geometry, list) 63 | self.assertIsInstance(routes.duration, int) 64 | self.assertIsInstance(routes.distance, int) 65 | self.assertIsInstance(routes.raw, dict) 66 | 67 | @responses.activate 68 | def test_directions_geojson(self): 69 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 70 | 71 | responses.add( 72 | responses.POST, 73 | "https://api.openrouteservice.org/v2/directions/{}/geojson".format(query["profile"]), 74 | status=200, 75 | json=ENDPOINTS_RESPONSES[self.name]["directions"]["geojson"], 76 | content_type="application/json", 77 | ) 78 | 79 | routes = self.client.directions(**query, format="geojson") 80 | 81 | query["coordinates"] = query["locations"] 82 | del query["locations"] 83 | del query["profile"] 84 | 85 | self.assertEqual(1, len(responses.calls)) 86 | self.assertEqual(query, json.loads(responses.calls[0].request.body.decode("utf-8"))) 87 | 88 | self.assertIsInstance(routes, Direction) 89 | self.assertIsInstance(routes.geometry, list) 90 | self.assertIsInstance(routes.duration, int) 91 | self.assertIsInstance(routes.distance, int) 92 | self.assertIsInstance(routes.raw, dict) 93 | 94 | @responses.activate 95 | def test_full_isochrones(self): 96 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["isochrones"]) 97 | 98 | responses.add( 99 | responses.POST, 100 | "https://api.openrouteservice.org/v2/isochrones/{}/geojson".format(query["profile"]), 101 | status=200, 102 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 103 | content_type="application/json", 104 | ) 105 | 106 | isochrones = self.client.isochrones(**query) 107 | 108 | expected = query 109 | expected["locations"] = [expected["locations"]] 110 | expected["range"] = expected["intervals"] 111 | expected["range_type"] = expected["interval_type"] 112 | del expected["intervals"] 113 | del expected["interval_type"] 114 | del expected["profile"] 115 | 116 | self.assertEqual(1, len(responses.calls)) 117 | self.assertEqual(expected, json.loads(responses.calls[0].request.body.decode("utf-8"))) 118 | 119 | self.assertIsInstance(isochrones, Isochrones) 120 | self.assertEqual(4, len(isochrones)) 121 | self.assertIsInstance(isochrones.raw, dict) 122 | for iso in isochrones: 123 | self.assertIsInstance(iso, Isochrone) 124 | self.assertIsInstance(iso.geometry, list) 125 | self.assertIsInstance(iso.center, list) 126 | self.assertIsInstance(iso.interval, int) 127 | self.assertEqual(iso.interval_type, "distance") 128 | 129 | @responses.activate 130 | def test_full_matrix(self): 131 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 132 | 133 | responses.add( 134 | responses.POST, 135 | "https://api.openrouteservice.org/v2/matrix/{}/json".format(query["profile"]), 136 | status=200, 137 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 138 | content_type="application/json", 139 | ) 140 | 141 | matrix = self.client.matrix(**query) 142 | 143 | expected = query 144 | del expected["profile"] 145 | 146 | self.assertEqual(1, len(responses.calls)) 147 | self.assertEqual(expected, json.loads(responses.calls[0].request.body.decode("utf-8"))) 148 | 149 | self.assertIsInstance(matrix, Matrix) 150 | self.assertIsInstance(matrix.durations, list) 151 | self.assertIsInstance(matrix.distances, list) 152 | self.assertIsInstance(matrix.raw, dict) 153 | 154 | @responses.activate 155 | def test_key_in_header(self): 156 | # Test that API key is being put in the Authorization header 157 | query = ENDPOINTS_QUERIES["ors"]["directions"] 158 | 159 | responses.add( 160 | responses.POST, 161 | "https://api.openrouteservice.org/v2/directions/{}/geojson".format(query["profile"]), 162 | json=ENDPOINTS_RESPONSES[self.name]["directions"]["geojson"], 163 | status=200, 164 | content_type="application/json", 165 | ) 166 | 167 | self.client.directions(**query) 168 | 169 | header_dict = CaseInsensitiveDict({"Authorization": self.key}) 170 | self.assertTrue( 171 | header_dict.items() <= {**header_dict, **responses.calls[0].request.headers}.items() 172 | ) 173 | 174 | @responses.activate 175 | def test_alternative_routes_error(self): 176 | # Test that alternative route works and also throws right errors 177 | query = deepcopy(ENDPOINTS_QUERIES["ors"]["directions"]) 178 | query["alternative_routes"] = {"target_count": 0, "a": 0, "weight_factor": 0} 179 | 180 | responses.add( 181 | responses.POST, 182 | "https://api.openrouteservice.org/v2/directions/{}/geojson".format(query["profile"]), 183 | json=ENDPOINTS_RESPONSES[self.name]["directions"]["geojson"], 184 | status=200, 185 | content_type="application/json", 186 | ) 187 | 188 | with self.assertRaises(ValueError): 189 | self.client.directions(**query) 190 | 191 | query["alternative_routes"] = [0, 1, 2, 3] 192 | 193 | with self.assertRaises(TypeError): 194 | self.client.directions(**query) 195 | -------------------------------------------------------------------------------- /tests/test_opentripplanner_v2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the OpenTripPlannerV2 module.""" 18 | 19 | import urllib.parse 20 | from copy import deepcopy 21 | 22 | import responses 23 | 24 | import tests as _test 25 | from routingpy import OpenTripPlannerV2, convert 26 | from routingpy.direction import Direction, Directions 27 | from routingpy.isochrone import Isochrone, Isochrones 28 | from routingpy.raster import Raster 29 | from tests.test_helper import * 30 | 31 | 32 | class OpenTripPlannerV2Test(_test.TestCase): 33 | name = "otp_v2" 34 | 35 | def setUp(self): 36 | self.client = OpenTripPlannerV2() 37 | 38 | @responses.activate 39 | def test_directions(self): 40 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 41 | responses.add( 42 | responses.POST, 43 | "http://localhost:8080/otp/routers/default/index/graphql", 44 | status=200, 45 | json=ENDPOINTS_RESPONSES["otp_v2"]["directions"], 46 | content_type="application/json", 47 | ) 48 | routes = self.client.directions(**query) 49 | self.assertEqual(1, len(responses.calls)) 50 | self.assertURLEqual( 51 | "http://localhost:8080/otp/routers/default/index/graphql", 52 | responses.calls[0].request.url, 53 | ) 54 | self.assertIsInstance(routes, Direction) 55 | self.assertIsInstance(routes.distance, int) 56 | self.assertIsInstance(routes.duration, int) 57 | self.assertIsInstance(routes.geometry, list) 58 | self.assertIsInstance(routes.raw, dict) 59 | 60 | @responses.activate 61 | def test_directions_alternative(self): 62 | query = ENDPOINTS_QUERIES[self.name]["directions_alternative"] 63 | responses.add( 64 | responses.POST, 65 | "http://localhost:8080/otp/routers/default/index/graphql", 66 | status=200, 67 | json=ENDPOINTS_RESPONSES["otp_v2"]["directions"], 68 | content_type="application/json", 69 | ) 70 | routes = self.client.directions(**query) 71 | self.assertEqual(1, len(responses.calls)) 72 | self.assertURLEqual( 73 | "http://localhost:8080/otp/routers/default/index/graphql", 74 | responses.calls[0].request.url, 75 | ) 76 | self.assertIsInstance(routes, Directions) 77 | self.assertEqual(1, len(routes)) 78 | for route in routes: 79 | self.assertIsInstance(route, Direction) 80 | self.assertIsInstance(route.duration, int) 81 | self.assertIsInstance(route.distance, int) 82 | self.assertIsInstance(route.geometry, list) 83 | self.assertIsInstance(route.raw, dict) 84 | 85 | @responses.activate 86 | def test_isochrones(self): 87 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["isochrones"]) 88 | url = "http://localhost:8080/otp/traveltime/isochrone" 89 | params = [ 90 | ("location", convert.delimit_list(reversed(query["locations"]), ",")), 91 | ("time", query["time"].isoformat()), 92 | ("modes", query["profile"]), 93 | ("arriveBy", "false"), 94 | ] 95 | for cutoff in query["cutoffs"]: 96 | params.append(("cutoff", convert.seconds_to_iso8601(cutoff))) 97 | 98 | responses.add( 99 | responses.GET, 100 | url + "?" + urllib.parse.urlencode(params), 101 | status=200, 102 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 103 | content_type="application/json", 104 | ) 105 | isochrones = self.client.isochrones(**query) 106 | self.assertEqual(1, len(responses.calls)) 107 | self.assertIsInstance(isochrones, Isochrones) 108 | self.assertEqual(2, len(isochrones)) 109 | self.assertIsInstance(isochrones.raw, dict) 110 | for isochrone in isochrones: 111 | self.assertIsInstance(isochrone, Isochrone) 112 | self.assertIsInstance(isochrone.geometry, list) 113 | self.assertIsInstance(isochrone.interval, int) 114 | self.assertEqual(isochrone.interval_type, "time") 115 | 116 | @responses.activate 117 | def test_raster(self): 118 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["raster"]) 119 | url = "http://localhost:8080/otp/traveltime/surface" 120 | params = [ 121 | ("location", convert.delimit_list(reversed(query["locations"]), ",")), 122 | ("time", query["time"].isoformat()), 123 | ("modes", query["profile"]), 124 | ("arriveBy", "false"), 125 | ("cutoff", convert.seconds_to_iso8601(query["cutoff"])), 126 | ] 127 | with open("tests/raster_example.tiff", "rb") as raster_file: 128 | image = raster_file.read() 129 | responses.add( 130 | responses.GET, 131 | url + "?" + urllib.parse.urlencode(params), 132 | status=200, 133 | body=image, 134 | content_type="image/tiff", 135 | ) 136 | raster = self.client.raster(**query) 137 | self.assertIsInstance(raster, Raster) 138 | self.assertEqual(raster.image, image) 139 | self.assertEqual(raster.max_travel_time, query["cutoff"]) 140 | -------------------------------------------------------------------------------- /tests/test_osrm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the OSRM module.""" 18 | 19 | from copy import deepcopy 20 | 21 | import responses 22 | 23 | import tests as _test 24 | from routingpy import OSRM, convert 25 | from routingpy.direction import Direction, Directions 26 | from routingpy.matrix import Matrix 27 | from tests.test_helper import * 28 | 29 | 30 | class OSRMTest(_test.TestCase): 31 | name = "osrm" 32 | 33 | def setUp(self): 34 | self.client = OSRM() 35 | 36 | @responses.activate 37 | def test_full_directions(self): 38 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 39 | query["alternatives"] = False 40 | query["fallback_speed"] = 42 41 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 42 | 43 | responses.add( 44 | responses.GET, 45 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/{coords}", 46 | status=200, 47 | json=ENDPOINTS_RESPONSES["osrm"]["directions_geojson"], 48 | content_type="application/json", 49 | ) 50 | 51 | routes = self.client.directions(**query) 52 | self.assertEqual(1, len(responses.calls)) 53 | self.assertURLEqual( 54 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?" 55 | "alternatives=false&annotations=true&bearings=50%2C50%3B50%2C50%3B50%2C50&continue_straight=true&" 56 | "geometries=geojson&overview=simplified&radiuses=500%3B500%3B500&steps=true&fallback_speed=42", 57 | responses.calls[0].request.url, 58 | ) 59 | self.assertIsInstance(routes, Direction) 60 | self.assertIsInstance(routes.distance, int) 61 | self.assertIsInstance(routes.duration, int) 62 | self.assertIsInstance(routes.geometry, list) 63 | self.assertIsInstance(routes.raw, dict) 64 | 65 | @responses.activate 66 | def test_full_directions_alternatives(self): 67 | query = ENDPOINTS_QUERIES[self.name]["directions"] 68 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 69 | 70 | responses.add( 71 | responses.GET, 72 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/{coords}", 73 | status=200, 74 | json=ENDPOINTS_RESPONSES["osrm"]["directions_geojson"], 75 | content_type="application/json", 76 | ) 77 | 78 | routes = self.client.directions(**query) 79 | self.assertEqual(1, len(responses.calls)) 80 | self.assertURLEqual( 81 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?" 82 | "alternatives=true&annotations=true&bearings=50%2C50%3B50%2C50%3B50%2C50&continue_straight=true&" 83 | "geometries=geojson&overview=simplified&radiuses=500%3B500%3B500&steps=true", 84 | responses.calls[0].request.url, 85 | ) 86 | self.assertIsInstance(routes, Directions) 87 | self.assertEqual(1, len(routes)) 88 | for route in routes: 89 | self.assertIsInstance(route, Direction) 90 | self.assertIsInstance(route.duration, int) 91 | self.assertIsInstance(route.distance, int) 92 | self.assertIsInstance(route.geometry, list) 93 | self.assertIsInstance(route.raw, dict) 94 | 95 | @responses.activate 96 | def test_directions_polyline5(self): 97 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 98 | query["geometries"] = "polyline" 99 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 100 | 101 | responses.add( 102 | responses.GET, 103 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/{coords}", 104 | status=200, 105 | json=ENDPOINTS_RESPONSES["osrm"]["directions_polyline"], 106 | content_type="application/json", 107 | ) 108 | 109 | routes = self.client.directions(**query) 110 | self.assertEqual(1, len(responses.calls)) 111 | self.assertIsInstance(routes, Directions) 112 | self.assertEqual( 113 | routes[0].geometry, 114 | [ 115 | (8.4201, 49.00585), 116 | (8.42081, 49.00655), 117 | (8.42431, 49.0055), 118 | (8.424, 49.0031), 119 | (8.42706, 49.00007), 120 | (8.42977, 48.99931), 121 | (8.43061, 48.99861), 122 | (8.43029, 48.99733), 123 | (8.42693, 48.99557), 124 | (8.41368, 48.99343), 125 | (8.40377, 48.99001), 126 | (8.39766, 48.98914), 127 | (8.39105, 48.98963), 128 | (8.37727, 48.99326), 129 | (8.37446, 48.99509), 130 | (8.36855, 49.00109), 131 | (8.36562, 49.00498), 132 | (8.36039, 49.00826), 133 | (8.35546, 49.00985), 134 | (8.35302, 49.01329), 135 | (8.35314, 49.01578), 136 | (8.35509, 49.01875), 137 | (8.3599, 49.03112), 138 | (8.36915, 49.03059), 139 | (8.36984, 49.03056), 140 | (8.36965, 49.02964), 141 | (8.36776, 49.02721), 142 | (8.36538, 49.02735), 143 | (8.36605, 49.0228), 144 | (8.3655, 49.02084), 145 | (8.36188, 49.01628), 146 | (8.35694, 49.01146), 147 | (8.3583, 49.01009), 148 | (8.35403, 49.00863), 149 | (8.34494, 49.0016), 150 | (8.34374, 48.99962), 151 | (8.34198, 48.99366), 152 | (8.30189, 48.96147), 153 | (8.30051, 48.9617), 154 | (8.29851, 48.96001), 155 | (8.29766, 48.96046), 156 | (8.29873, 48.96137), 157 | ], 158 | ) 159 | 160 | @responses.activate 161 | def test_directions_polyline6(self): 162 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 163 | query["geometries"] = "polyline6" 164 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 165 | 166 | responses.add( 167 | responses.GET, 168 | f"https://routing.openstreetmap.de/routed-bike/route/v1/{query['profile']}/{coords}", 169 | status=200, 170 | json=ENDPOINTS_RESPONSES["osrm"]["directions_polyline6"], 171 | content_type="application/json", 172 | ) 173 | 174 | routes = self.client.directions(**query) 175 | self.assertEqual(1, len(responses.calls)) 176 | self.assertIsInstance(routes, Directions) 177 | self.assertEqual( 178 | routes[0].geometry, 179 | [ 180 | (8.420095, 49.005852), 181 | (8.420812, 49.006554), 182 | (8.424311, 49.005502), 183 | (8.424003, 49.003102), 184 | (8.427062, 49.000065), 185 | (8.429772, 48.999306), 186 | (8.430605, 48.998613), 187 | (8.430293, 48.99733), 188 | (8.426928, 48.99557), 189 | (8.413683, 48.993431), 190 | (8.403766, 48.990011), 191 | (8.397659, 48.989135), 192 | (8.391053, 48.989626), 193 | (8.377274, 48.993257), 194 | (8.374464, 48.995086), 195 | (8.36855, 49.001092), 196 | (8.365623, 49.00498), 197 | (8.360386, 49.008261), 198 | (8.355457, 49.00985), 199 | (8.353019, 49.013291), 200 | (8.353144, 49.015775), 201 | (8.355086, 49.018752), 202 | (8.359899, 49.031121), 203 | (8.369147, 49.030589), 204 | (8.369837, 49.030558), 205 | (8.369651, 49.029636), 206 | (8.36776, 49.027214), 207 | (8.365381, 49.027346), 208 | (8.366047, 49.0228), 209 | (8.365496, 49.020841), 210 | (8.361875, 49.016277), 211 | (8.356935, 49.011464), 212 | (8.358296, 49.010093), 213 | (8.354033, 49.008632), 214 | (8.344937, 49.001596), 215 | (8.343743, 48.999617), 216 | (8.341978, 48.993659), 217 | (8.301892, 48.961471), 218 | (8.300508, 48.961703), 219 | (8.298506, 48.960006), 220 | (8.297656, 48.960459), 221 | (8.298731, 48.96137), 222 | ], 223 | ) 224 | 225 | @responses.activate 226 | def test_full_matrix(self): 227 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 228 | query["fallback_speed"] = 42 229 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 230 | 231 | responses.add( 232 | responses.GET, 233 | f"https://routing.openstreetmap.de/routed-bike/table/v1/{query['profile']}/{coords}", 234 | status=200, 235 | json=ENDPOINTS_RESPONSES["osrm"]["matrix"], 236 | content_type="application/json", 237 | ) 238 | 239 | matrix = self.client.matrix(**query) 240 | 241 | print(responses.calls[0].request.url) 242 | self.assertEqual(1, len(responses.calls)) 243 | self.assertURLEqual( 244 | f"https://routing.openstreetmap.de/routed-bike/table/v1/{query['profile']}/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?annotations=distance%2Cduration&bearings=50%2C50%3B50%2C50%3B50%2C50&fallback_speed=42&radiuses=500%3B500%3B500", 245 | responses.calls[0].request.url, 246 | ) 247 | self.assertIsInstance(matrix, Matrix) 248 | self.assertIsInstance(matrix.durations, list) 249 | self.assertIsInstance(matrix.distances, list) 250 | self.assertIsInstance(matrix.raw, dict) 251 | 252 | @responses.activate 253 | def test_few_sources_destinations_matrix(self): 254 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 255 | coords = convert.delimit_list([convert.delimit_list(pair) for pair in query["locations"]], ";") 256 | 257 | query["sources"] = [1, 2] 258 | query["destinations"] = [0, 2] 259 | 260 | responses.add( 261 | responses.GET, 262 | f"https://routing.openstreetmap.de/routed-bike/table/v1/{query['profile']}/{coords}", 263 | status=200, 264 | json=ENDPOINTS_RESPONSES["osrm"]["matrix"], 265 | content_type="application/json", 266 | ) 267 | 268 | self.client.matrix(**query) 269 | 270 | self.assertEqual(1, len(responses.calls)) 271 | print(responses.calls[0].request.url) 272 | self.assertURLEqual( 273 | f"https://routing.openstreetmap.de/routed-bike/table/v1/{query['profile']}/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?annotations=distance%2Cduration&bearings=50%2C50%3B50%2C50%3B50%2C50&destinations=0%3B2&radiuses=500%3B500%3B500&sources=1%3B2", 274 | responses.calls[0].request.url, 275 | ) 276 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for utils module.""" 18 | 19 | import tests as _test 20 | from routingpy import utils 21 | 22 | 23 | class UtilsTest(_test.TestCase): 24 | def setUp(self): 25 | self.coords2d_5prec = r"smslH__`t@~\fo@" 26 | self.coords3d_5prec = r"smslH__`t@_sV~\fo@etjG" 27 | self.coords2d_6prec = r"aqkg}Aa_iqO`kHxaN" 28 | self.coords3d_6prec = r"aqkg}Aa_iqO_sV`kHxaNetjG" 29 | 30 | def test_polyline5_2d_decoding(self): 31 | decoded = [(8.68864, 49.42058), (8.68092, 49.41578)] 32 | self.assertEqual(decoded, utils.decode_polyline5(self.coords2d_5prec)) 33 | 34 | def test_polyline5_3d_decoding(self): 35 | decoded = [(8.68864, 49.42058, 120.96), (8.68092, 49.41578, 1491.39)] 36 | self.assertEqual(decoded, utils.decode_polyline5(self.coords3d_5prec, True)) 37 | 38 | def test_polyline6_2d_decoding(self): 39 | decoded = [(8.688641, 49.420577), (8.680916, 49.415776)] 40 | self.assertEqual(decoded, utils.decode_polyline6(self.coords2d_6prec)) 41 | 42 | def test_polyline6_3d_decoding(self): 43 | decoded = [(8.688641, 49.420577, 120.96), (8.680916, 49.415776, 1491.39)] 44 | self.assertEqual(decoded, utils.decode_polyline6(self.coords3d_6prec, True)) 45 | 46 | def test_polyline6_3d_decoding_latlng(self): 47 | decoded = [(49.420577, 8.688641, 120.96), (49.415776, 8.680916, 1491.39)] 48 | self.assertEqual(decoded, utils.decode_polyline6(self.coords3d_6prec, True, order="latlng")) 49 | 50 | def test_get_ordinal(self): 51 | self.assertEqual(utils.get_ordinal(0), "th") 52 | self.assertEqual(utils.get_ordinal(1), "st") 53 | self.assertEqual(utils.get_ordinal(2), "nd") 54 | self.assertEqual(utils.get_ordinal(3), "rd") 55 | -------------------------------------------------------------------------------- /tests/test_valhalla.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2021 GIS OPS UG 3 | # 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | # use this file except in compliance with the License. You may obtain a copy of 7 | # the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations under 15 | # the License. 16 | # 17 | """Tests for the Valhalla module.""" 18 | 19 | import json 20 | from copy import deepcopy 21 | 22 | import responses 23 | 24 | import tests as _test 25 | from routingpy import Valhalla 26 | from routingpy.direction import Direction 27 | from routingpy.expansion import Expansions 28 | from routingpy.isochrone import Isochrone, Isochrones 29 | from routingpy.matrix import Matrix 30 | from routingpy.valhalla_attributes import ( 31 | MatchedEdge, 32 | MatchedPoint, 33 | MatchedResults, 34 | RoadClass, 35 | Sidewalk, 36 | Surface, 37 | ) 38 | from tests.test_helper import * 39 | 40 | 41 | class ValhallaTest(_test.TestCase): 42 | name = "valhalla" 43 | 44 | def setUp(self): 45 | self.client = Valhalla("https://api.mapbox.com/valhalla/v1") 46 | 47 | @responses.activate 48 | def test_full_directions(self): 49 | query = ENDPOINTS_QUERIES[self.name]["directions"] 50 | expected = ENDPOINTS_EXPECTED[self.name]["directions"] 51 | 52 | responses.add( 53 | responses.POST, 54 | "https://api.mapbox.com/valhalla/v1/route", 55 | status=200, 56 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 57 | content_type="application/json", 58 | ) 59 | routes = self.client.directions(**query) 60 | 61 | self.assertEqual(1, len(responses.calls)) 62 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 63 | self.assertIsInstance(routes, Direction) 64 | self.assertIsInstance(routes.distance, int) 65 | self.assertIsInstance(routes.duration, int) 66 | self.assertIsInstance(routes.geometry, list) 67 | self.assertIsInstance(routes.raw, dict) 68 | 69 | @responses.activate 70 | def test_waypoint_generator(self): 71 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["directions"]) 72 | expected = deepcopy(ENDPOINTS_EXPECTED[self.name]["directions"]) 73 | 74 | extra_params = { 75 | "type": "break", 76 | "heading": PARAM_INT_SMALL, 77 | "heading_tolerance": PARAM_INT_SMALL, 78 | "minimum_reachability": PARAM_INT_SMALL, 79 | "radius": PARAM_INT_SMALL, 80 | "rank_candidates": True, 81 | } 82 | 83 | query["locations"].append(Valhalla.Waypoint(PARAM_POINT, **extra_params)) 84 | expected["locations"].append({"lat": PARAM_POINT[1], "lon": PARAM_POINT[0], **extra_params}) 85 | 86 | responses.add( 87 | responses.POST, 88 | "https://api.mapbox.com/valhalla/v1/route", 89 | status=200, 90 | json=ENDPOINTS_RESPONSES[self.name]["directions"], 91 | content_type="application/json", 92 | ) 93 | self.client.directions(**query) 94 | 95 | self.assertEqual(1, len(responses.calls)) 96 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 97 | 98 | @responses.activate 99 | def test_full_isochrones(self): 100 | query = ENDPOINTS_QUERIES[self.name]["isochrones"] 101 | expected = ENDPOINTS_EXPECTED[self.name]["isochrones"] 102 | 103 | responses.add( 104 | responses.POST, 105 | "https://api.mapbox.com/valhalla/v1/isochrone", 106 | status=200, 107 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 108 | content_type="application/json", 109 | ) 110 | 111 | iso = self.client.isochrones(**query) 112 | 113 | self.assertEqual(1, len(responses.calls)) 114 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 115 | self.assertIsInstance(iso, Isochrones) 116 | self.assertIsInstance(iso.raw, dict) 117 | self.assertEqual(2, len(iso)) 118 | for i in iso: 119 | self.assertIsInstance(i, Isochrone) 120 | self.assertIsInstance(i.geometry, list) 121 | self.assertIsInstance(i.interval, int) 122 | self.assertIsInstance(i.center, list) 123 | self.assertEqual(i.interval_type, "time") 124 | 125 | @responses.activate 126 | def test_isodistances(self): 127 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["isochrones"]) 128 | expected = deepcopy(ENDPOINTS_EXPECTED[self.name]["isochrones"]) 129 | 130 | query["interval_type"] = "distance" 131 | expected["contours"] = [ 132 | {"distance": 0.6, "color": "ff0000"}, 133 | {"distance": 1.2, "color": "00FF00"}, 134 | ] 135 | 136 | responses.add( 137 | responses.POST, 138 | "https://api.mapbox.com/valhalla/v1/isochrone", 139 | status=200, 140 | json=ENDPOINTS_RESPONSES[self.name]["isochrones"], 141 | content_type="application/json", 142 | ) 143 | 144 | iso = self.client.isochrones(**query) 145 | 146 | self.assertEqual(1, len(responses.calls)) 147 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 148 | for i in iso: 149 | self.assertIsInstance(i, Isochrone) 150 | self.assertEqual(i.interval_type, "distance") 151 | 152 | # TODO: test colors having less items than range 153 | @responses.activate 154 | def test_full_matrix(self): 155 | query = ENDPOINTS_QUERIES[self.name]["matrix"] 156 | expected = ENDPOINTS_EXPECTED[self.name]["matrix"] 157 | 158 | responses.add( 159 | responses.POST, 160 | "https://api.mapbox.com/valhalla/v1/sources_to_targets", 161 | status=200, 162 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 163 | content_type="application/json", 164 | ) 165 | 166 | matrix = self.client.matrix(**query) 167 | 168 | self.assertEqual(1, len(responses.calls)) 169 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 170 | self.assertIsInstance(matrix, Matrix) 171 | self.assertIsInstance(matrix.durations, list) 172 | self.assertIsInstance(matrix.distances, list) 173 | self.assertIsInstance(matrix.raw, dict) 174 | 175 | @responses.activate 176 | def test_few_sources_destinations_matrix(self): 177 | query = deepcopy(ENDPOINTS_QUERIES[self.name]["matrix"]) 178 | query["sources"] = [2] 179 | query["destinations"] = [0] 180 | 181 | expected = deepcopy(ENDPOINTS_EXPECTED[self.name]["matrix"]) 182 | del expected["sources"][0] 183 | del expected["sources"][0] 184 | del expected["targets"][1] 185 | del expected["targets"][1] 186 | 187 | responses.add( 188 | responses.POST, 189 | "https://api.mapbox.com/valhalla/v1/sources_to_targets", 190 | status=200, 191 | json=ENDPOINTS_RESPONSES[self.name]["matrix"], 192 | content_type="application/json", 193 | ) 194 | 195 | self.client.matrix(**query) 196 | 197 | self.assertEqual(1, len(responses.calls)) 198 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 199 | 200 | @responses.activate 201 | def test_expansion(self): 202 | query = ENDPOINTS_QUERIES[self.name]["expansion"] 203 | expected = ENDPOINTS_EXPECTED[self.name]["expansion"] 204 | responses.add( 205 | responses.POST, 206 | "https://api.mapbox.com/valhalla/v1/expansion", 207 | status=200, 208 | json=ENDPOINTS_RESPONSES[self.name]["expansion"], 209 | content_type="application/json", 210 | ) 211 | expansion = self.client.expansion(**query) 212 | 213 | self.assertEqual(1, len(responses.calls)) 214 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 215 | 216 | self.assertIsInstance(expansion, Expansions) 217 | self.assertIsInstance(expansion.center, list) 218 | self.assertEqual(expansion.interval_type, "time") 219 | self.assertIsInstance(expansion.raw, dict) 220 | 221 | @responses.activate 222 | def test_trace_attributes(self): 223 | query = ENDPOINTS_QUERIES[self.name]["trace_attributes"] 224 | expected = ENDPOINTS_EXPECTED[self.name]["trace_attributes"] 225 | responses.add( 226 | responses.POST, 227 | "https://api.mapbox.com/valhalla/v1/trace_attributes", 228 | status=200, 229 | json=ENDPOINTS_RESPONSES[self.name]["trace_attributes"], 230 | content_type="application/json", 231 | ) 232 | matched = self.client.trace_attributes(**query) 233 | 234 | self.assertEqual(1, len(responses.calls)) 235 | self.assertEqual(json.loads(responses.calls[0].request.body.decode("utf-8")), expected) 236 | 237 | self.assertIsInstance(matched, MatchedResults) 238 | self.assertIsInstance(matched.matched_edges, list) 239 | for edge in matched.matched_edges: 240 | self.assertIsInstance(edge, MatchedEdge) 241 | self.assertIsInstance(edge.surface, Surface) 242 | self.assertIsInstance(edge.sidewalk, Sidewalk) 243 | self.assertIsInstance(edge.road_class, RoadClass) 244 | for pt in matched.matched_points: 245 | self.assertIsInstance(pt, MatchedPoint) 246 | self.assertEqual(pt.match_type, "matched") 247 | self.assertGreaterEqual(pt.edge_index, 0) 248 | --------------------------------------------------------------------------------