diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index fbf9e0e..0000000 --- a/.coveragerc +++ /dev/null @@ -1,3 +0,0 @@ -[run] -omit = - */h3/unstable/* diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 0729f41..0000000 --- a/.flake8 +++ /dev/null @@ -1,14 +0,0 @@ -# https://lintlyci.github.io/Flake8Rules/ -[flake8] -max-line-length = 88 -include = - #W292 No newline at end of file - W292, -ignore = - # E251 unexpected spaces around keyword / parameter equals - E251, - # sometimes I just want to line up decimal points... - # E201 whitespace after '[' - E201, - # E241 multiple spaces after ',' - E241, diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml new file mode 100644 index 0000000..9cc00a2 --- /dev/null +++ b/.github/workflows/build_docs.yml @@ -0,0 +1,41 @@ +name: build_docs + +on: + push: + branches: [master] + pull_request: + branches: ['*'] + +permissions: + contents: write + +jobs: + build-docs: + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v6.0.2 + with: + submodules: recursive + + - uses: astral-sh/setup-uv@v7 + with: + python-version: '3.11' + + - uses: extractions/setup-just@v2 + + - name: Build the book + run: just docs + + - name: Upload artifacts + uses: actions/upload-artifact@v6.0.0 + with: + name: html + path: docs/_build/html + + - name: Upload to GitHub Pages + uses: peaceiris/actions-gh-pages@v4 + if: github.ref == 'refs/heads/master' + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: docs/_build/html diff --git a/.github/workflows/coverage-lint.yml b/.github/workflows/coverage-lint.yml deleted file mode 100644 index e1d0bbd..0000000 --- a/.github/workflows/coverage-lint.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: coverage-lint - -on: - push: - branches: [master] - pull_request: - branches: [master] - -jobs: - tests: - name: Coverage and Lint - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - with: - submodules: recursive - - - uses: actions/setup-python@v3.1.1 - with: - python-version: 3.8 - - - name: Install from source - run: | - pip install --upgrade pip setuptools wheel - pip install .[all] - - - name: Lint - run: flake8 src/h3 setup.py tests - - - name: Pylint - # As a test for visibility of API bindings, we want to ensure that pylint has no - # `import-error` warnings for h3 imports. - run: pylint --disable=all --enable=import-error tests/ - - - name: Coverage - run: | - pip install Cython - cythonize -i tests/cython_example.pyx - pytest --cov=h3 --full-trace --cov-report=xml - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v3.0.0 - with: - file: ./coverage.xml - fail_ci_if_error: true - - - name: Copy Cython annotations to project dir - run: | - mkdir annotations - cp _skbuild/*/cmake-build/src/h3/_cy/*.html ./annotations - - - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v3 - with: - path: ./annotations diff --git a/.github/workflows/deploy_docs.yml b/.github/workflows/deploy_docs.yml deleted file mode 100644 index d932763..0000000 --- a/.github/workflows/deploy_docs.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: deploy_docs - -# todo: we want to build on PRs, but keep it from pushing to deploy... - -on: - push: - branches: - - master - -# This job installs dependencies, builds the book, and pushes it to `gh-pages` -jobs: - build-docs: - name: Build docs - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - with: - submodules: recursive - - - uses: actions/setup-python@v3.1.1 - with: - python-version: 3.8 - - - name: Install dependencies - run: | - pip install --upgrade pip setuptools wheel - pip install -r requirements.in - pip install .[all] - - - name: Lint - # run: flake8 --ignore=E501 h3.py - run: flake8 src/h3 - - # Build the book - - name: Build the book - run: | - jupyter-book build docs/ --warningiserror --keep-going --all - - # Deploy the book's HTML to gh-pages branch - - name: GitHub Pages action - uses: peaceiris/actions-gh-pages@v3.7.3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: docs/_build/html diff --git a/.github/workflows/lint_and_coverage.yml b/.github/workflows/lint_and_coverage.yml new file mode 100644 index 0000000..8ec1ef1 --- /dev/null +++ b/.github/workflows/lint_and_coverage.yml @@ -0,0 +1,38 @@ +name: lint_and_coverage + +on: + push: + branches: [master] + pull_request: + branches: ['*'] + +permissions: + contents: read + +jobs: + linting: + name: Lint and Coverage + runs-on: ubuntu-24.04 + + steps: + - uses: actions/checkout@v6.0.2 + with: + submodules: recursive + + - uses: astral-sh/setup-uv@v7 + with: + python-version: '3.11' + + - uses: extractions/setup-just@v2 + + - name: Lint + run: just lint + + - name: Install + run: uv sync + + - name: Coverage - Library + run: just ci-test + + - name: Coverage - Cython + run: just ci-test-cython diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f2c5682..f7a9854 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,7 +4,7 @@ on: push: branches: [master] pull_request: - branches: [master] + branches: ['*'] jobs: tests: @@ -13,25 +13,22 @@ jobs: strategy: matrix: - os: [macos-latest, windows-latest, ubuntu-latest] - python-version: ['2.7', '3.5', '3.6', '3.7', '3.8', '3.9', '3.10'] - exclude: - - os: windows-latest - python-version: 2.7 - - os: windows-latest - python-version: 3.5 + os: [macos-latest, windows-latest, ubuntu-22.04] + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.14t', '3.15', '3.15t'] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6.0.2 with: submodules: recursive - - uses: actions/setup-python@v3.1.1 + - uses: astral-sh/setup-uv@v7 with: - python-version: "${{ matrix.python-version }}" + python-version: '${{ matrix.python-version }}' + + - uses: extractions/setup-just@v2 ## Start Windows stuff - - uses: ilammy/msvc-dev-cmd@v1.10.0 + - uses: ilammy/msvc-dev-cmd@v1.13.0 if: startsWith(matrix.os, 'windows') - name: Set Windows Compiler @@ -41,13 +38,11 @@ jobs: echo "CXX=cl.exe" >> $GITHUB_ENV ## End Windows stuff - - name: Install from source - run: | - pip install --upgrade pip setuptools wheel - pip install .[all] + - name: Install + run: uv sync - name: Tests - run: | - pip install Cython - cythonize -i tests/cython_example.pyx - pytest tests --cov=h3 --full-trace + run: just ci-test + + - name: Cython Tests + run: just ci-test-cython diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 5f75525..1de5a80 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -4,7 +4,7 @@ on: push: branches: [master] pull_request: - branches: [master] + branches: ['*'] types: # Opened, synchronize, and reopened are the default types # We add ready_for_review to additionally trigger when converting from draft to non-draft @@ -19,115 +19,149 @@ on: jobs: make_sdist: - name: SDist if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6.0.2 with: submodules: recursive + - uses: astral-sh/setup-uv@v7 + with: + python-version: '3.11' + + - name: Make sdist - run: | - pipx run build --sdist + run: uv build --sdist + # Test the sdist, NOT the local checkout. + # Use a fresh venv + uv pip install (not uv sync, which would build from source). - name: Install from sdist run: | - pip install --upgrade pip setuptools wheel + uv venv cp dist/h3-*.tar.gz h3.tar.gz - pip install h3.tar.gz[all] + uv pip install h3.tar.gz[numpy] pytest pytest-cov - name: Test sdist - run: pytest --cov=h3 --full-trace + # run pytest directly from the venv to avoid `uv run` syncing from the local checkout + run: .venv/bin/pytest - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v6.0.0 with: + name: temp_result_sdist path: ./dist - make_cibw_v1_wheels: - name: "cibuildwheel v1: ${{ matrix.name }}" - if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} - runs-on: ${{ matrix.os }} - strategy: - matrix: - # Only build for platforms that cibw v2 doesn't support - include: - - os: macos-latest - build: "cp27-macosx_x86_64" - name: macOS Intel - - os: ubuntu-latest - build: "cp27-manylinux_x86_64" - name: Linux Intel 64-bit - - steps: - - uses: actions/checkout@v3 - with: - submodules: recursive - - ## Build - - - uses: pypa/cibuildwheel@v1.12.0 - env: - CIBW_TEST_REQUIRES: pytest numpy - CIBW_TEST_COMMAND: pytest {project}/tests - CIBW_ARCHS_LINUX: auto aarch64 - CIBW_BUILD: ${{ matrix.build }} - - - name: Check with Twine - run: | - pipx run twine check wheelhouse/* - - - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v3 - with: - path: wheelhouse/*.whl - - make_cibw_v2_wheels: - name: "cibuildwheel v2: ${{ matrix.name }}" + make_wheels: + name: 'cibw: ${{ matrix.name }}' if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ${{ matrix.os }} strategy: matrix: include: - - os: macos-latest - build: "cp*-macosx*" - name: macOS + - os: macos-15 + build: 'cp*-macosx_arm64' + name: macOS15 + - os: windows-latest - build: "cp3*-win_amd64" + build: 'cp3*-win_amd64' name: Windows 64-bit - - os: ubuntu-latest - build: "cp*-manylinux_x86_64" + + - os: windows-11-arm + build: 'cp311-win_arm64' + name: Windows ARM64 3.11 + - os: windows-11-arm + build: 'cp312-win_arm64' + name: Windows ARM64 3.12 + - os: windows-11-arm + build: 'cp313-win_arm64' + name: Windows ARM64 3.13 + - os: windows-11-arm + build: 'cp314-win_arm64' + name: Windows ARM64 3.14 + - os: windows-11-arm + build: 'cp314t-win_arm64' + name: Windows ARM64 3.14t + - os: windows-11-arm + build: 'cp315-win_arm64' + name: Windows ARM64 3.15 + - os: windows-11-arm + build: 'cp315t-win_arm64' + name: Windows ARM64 3.15t + + - os: ubuntu-22.04 + build: 'cp*-manylinux_x86_64' name: Linux Intel glibc 64-bit - - os: ubuntu-latest - build: "cp*-musllinux_x86_64" - name: Linux Intel musl 64-bit - - os: ubuntu-latest - build: "cp36-manylinux_aarch64" - name: Linux Aarch64 3.6 - - os: ubuntu-latest - build: "cp37-manylinux_aarch64" - name: Linux Aarch64 3.7 - - os: ubuntu-latest - build: "cp38-manylinux_aarch64" - name: Linux Aarch64 3.8 - - os: ubuntu-latest - build: "cp39-manylinux_aarch64" - name: Linux Aarch64 3.9 - - os: ubuntu-latest - build: "cp310-manylinux_aarch64" + + - os: ubuntu-22.04 + build: 'cp310-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.10 + - os: ubuntu-22.04 + build: 'cp311-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.11 + - os: ubuntu-22.04 + build: 'cp312-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.12 + - os: ubuntu-22.04 + build: 'cp313-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.13 + - os: ubuntu-22.04 + build: 'cp314-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.14 + - os: ubuntu-22.04 + build: 'cp314t-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.14t + - os: ubuntu-22.04 + build: 'cp315-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.15 + - os: ubuntu-22.04 + build: 'cp315t-musllinux_x86_64' + name: Linux Intel musl 64-bit 3.15t + + - os: ubuntu-22.04 + build: 'cp310-manylinux_aarch64' name: Linux Aarch64 3.10 + - os: ubuntu-22.04 + build: 'cp311-manylinux_aarch64' + name: Linux Aarch64 3.11 + - os: ubuntu-22.04 + build: 'cp312-manylinux_aarch64' + name: Linux Aarch64 3.12 + - os: ubuntu-22.04 + build: 'cp313-manylinux_aarch64' + name: Linux Aarch64 3.13 + - os: ubuntu-22.04 + build: 'cp314-manylinux_aarch64' + name: Linux Aarch64 3.14 + - os: ubuntu-22.04 + build: 'cp314t-manylinux_aarch64' + name: Linux Aarch64 3.14t + - os: ubuntu-22.04 + build: 'cp315-manylinux_aarch64' + name: Linux Aarch64 3.15 + - os: ubuntu-22.04 + build: 'cp315t-manylinux_aarch64' + name: Linux Aarch64 3.15t steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6.0.2 with: submodules: recursive - ## Setup Env + - uses: astral-sh/setup-uv@v7 - - uses: ilammy/msvc-dev-cmd@v1.10.0 - if: runner.os == 'Windows' + - name: Set MSVC for Windows-x64 + uses: microsoft/setup-msbuild@v2 + if: matrix.os == 'windows-latest' + with: + msbuild-architecture: x64 + + - name: Set MSVC for Windows-ARM64 + uses: microsoft/setup-msbuild@v2 + if: matrix.os == 'windows-11-arm' + with: + msbuild-architecture: arm64 - name: Set Windows variables if: runner.os == 'Windows' @@ -138,41 +172,69 @@ jobs: - name: Set up QEMU if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v1.2.0 + uses: docker/setup-qemu-action@v3.7.0 with: platforms: aarch64 - ## Build - - - uses: pypa/cibuildwheel@v2.4.0 + - uses: pypa/cibuildwheel@v4.2.1 env: - CIBW_TEST_REQUIRES: pytest numpy + CIBW_BUILD_FRONTEND: 'build[uv]' + CIBW_TEST_REQUIRES: pytest pytest-cov numpy CIBW_TEST_COMMAND: pytest {project}/tests CIBW_ARCHS_LINUX: auto aarch64 - CIBW_ARCHS_MACOS: x86_64 arm64 CIBW_BUILD: ${{ matrix.build }} - CIBW_SKIP: ${{ matrix.skip }} - name: Check with Twine - run: | - pipx run twine check wheelhouse/* + run: uvx twine check wheelhouse/* - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v6.0.0 with: + name: temp_result_${{ matrix.os }}-${{ strategy.job-index }} path: wheelhouse/*.whl - upload_all: - needs: [make_sdist, make_cibw_v1_wheels, make_cibw_v2_wheels] + merge: + needs: [make_sdist, make_wheels] runs-on: ubuntu-latest - if: github.event_name == 'release' && github.event.action == 'published' - steps: - - uses: actions/download-artifact@v3 + - name: Merge Artifacts + uses: actions/upload-artifact/merge@v6 with: - name: artifact + name: wheels_and_sdist + pattern: temp_result_* + delete-merged: true + retention-days: 7 + compression-level: 9 + + check_merged: + needs: [merge] + runs-on: ubuntu-latest + steps: + - uses: astral-sh/setup-uv@v7 + with: + enable-cache: false + ignore-empty-workdir: true + + - name: Download merged artifacts + uses: actions/download-artifact@v7.0.0 + with: + name: wheels_and_sdist path: dist - - uses: pypa/gh-action-pypi-publish@v1.5.0 + - name: Check all wheels and sdist with Twine + run: uvx twine check dist/* + + to_pypi: + needs: [check_merged] + if: github.event_name == 'release' && github.event.action == 'published' + runs-on: ubuntu-latest + + steps: + - uses: actions/download-artifact@v7.0.0 + with: + name: wheels_and_sdist + path: dist + + - uses: pypa/gh-action-pypi-publish@v1.13.0 with: password: ${{ secrets.pypi_password }} diff --git a/.gitignore b/.gitignore index 5bd718f..1141de9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,72 +1,57 @@ -h3c/ +# Byte-compiled / optimized *.py[cod] -.cache/ -h3/out/ - -# Generated C code from Cython test -tests/*.c -# Cython HTML annotations -*.html +__pycache__/ # C extensions *.so -# Packages -*.egg +# Generated C code from Cython test +tests/**/*.c +# Cython HTML annotations +*.html + +# Build artifacts +build/ +dist/ *.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -# Installer logs -pip-log.txt - -# Unit test / coverage reports +# Coverage .coverage coverage.xml -.tox -nosetests.xml -.noseids -.pytest_cache - -# Mr Developer -.mr.developer.cfg -.project -.pydevproject - -*.csv -build/ -env/ -env_docs/ -docs/_build/ +coverage.lcov htmlcov/ -# vim/emacs backup files +# Test +.pytest_cache/ + +# Tools +.ruff_cache/ +.cache/ + +# Docs +_build/ +docs/_build/ + +# Environment +.venv/ +uv.lock + +# OS +.DS_Store + +# Editor backup files *~ \#*\# .\#* .*.sw* -#DB snapshots -db_snapshots/ - -#OSX -.DS_Store - -node_modules/ -bower_components/ -.sass-cache/ +# IDE .idea/ -.unison.* +# IPython / Jupyter .ipynb_checkpoints/ -_skbuild/ -# might want to remove this later when distributing -MANIFEST +# Legacy build dirs +_skbuild/ +h3c/ +h3/out/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bf87cf..0b6ee3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,6 @@ -# Versioning +# CHANGELOG + +## Versioning The H3 core library adheres to [Semantic Versioning](http://semver.org/). H3-Py has a `major.minor.patch` version scheme. The major and minor version @@ -13,15 +15,158 @@ avoid adding features or APIs which do not map onto the [H3 core API](https://uber.github.io/h3/#/documentation/api-reference/). ## Unreleased +- Fix wheels for Python 3.14.6 free-threading +- Add Python 3.14t, 3.15 and 3.15t wheels +- Support `unit='rads'` in `average_hexagon_area` and `average_hexagon_edge_length` (#509) +- Add `container` option to `h3shape_to_geo` (#495) +- Fix Android cross-compilation with Buildozer (#494) +- Raise `ValueError` instead of `assert` in `geo_to_h3shape` (#500, #502) +- Fix `LatLngPoly` loop length check for closed rings (#505) +- Return `False` from `is_valid_*` for out-of-range integers (#507) +- Handle empty GeoJSON Polygon in `geo_to_h3shape` (#511) +- Fix duplicate cells from `h3shape_to_cells_experimental` for `LatLngMultiPoly` (#512) -- None +## [4.5.0] - 2026-05-29 + +- Final v4.5 release includes all v4.5.x changes below + +## [4.5.0a3] - 2026-05-22 + +- Update `h3lib` to v4.5.0 release (#491) + +## [4.5.0a2] - 2026-02-27 + +- `cells_to_h3shape`/`cells_to_geo` now handle all valid cell sets, including + sets that would produce global polygons crossing the antimeridian, poles, or are larger than a hemisphere + - Duplicate cells now raise `H3DuplicateInputError` + - Mixed-resolution cells now raise `H3ResMismatchError` + - Internal: switch from linked-list to array-based C API for cells-to-polygon conversion + +## [4.5.0a1] - 2026-02-25 + +- Update `h3lib` with draft v4.5 changes +- Drop Python 3.8 and 3.9 (EOL); minimum is now Python 3.10 +- Document Python 3.14 support +- Migrate build tooling from Makefile/pip to justfile/uv, including CI + +## [4.4.2] - 2026-01-29 + +- Check for error from `cellsToLinkedMultiPolygon` (#477) + +## [4.4.1] - 2025-12-15 + +- Fix PyPI publishing issue (#474) + +## [4.4.0] - 2025-12-12 (never published on PyPI) + +- Update `h3lib` to v4.4.1. (#470) + - Add new error codes: + - `H3IndexInvalidError` + - `H3BaseCellDomainError` + - `H3DigitDomainError` + - `H3DeletedDigitError` + - Add new functions: + - `is_valid_index` + - `get_index_digit` + - `construct_cell` + - `deconstruct_cell` + +## [4.3.1] - 2025-08-10 + +- Build wheels for Windows on ARM64 (#463) + +## [4.3.0] - 2025-06-17 + +- Update `h3lib` to v4.3.0. (#461) + - Uses `gridRing` (uber/h3#1016) instead of Cython fallback logic. + +## [4.2.2] - 2025-03-10 + +- Update h3lib to v4.2.1. (#450) + +## [4.2.1] - 2025-01-31 + +- Correct pyproject.toml links for PyPI (#441) +- Update coverage badge (#443) + +## [4.2.0] - 2025-01-26 + +- Update h3lib to v4.2.0. (#432) +- Add `h3shape_to_cells_experimental` (#436) + - Add `polygon_to_cells_experimental` alias + +## [4.1.2] - 2024-10-26 + +- Build Python 3.13 wheels (#425) + +## [4.1.1] - 2024-10-13 + +- Make sure docs and PyPI page are up-to-date. + +## [4.1.0] - 2024-10-13 + +- Final v4.1 release inculdes all v4.x changes below. + +## [4.1.0b3] - 2024-10-05 + +- Allow for `str` subtypes, like `numpy.str_` (#408) + +## [4.1.0b2] - 2024-09-27 + +- Add `cell_to_child_pos`, `child_pos_to_cell`, `cell_to_children_size` (#405) + +## [4.1.0b1] - 2024-09-26 + +- Bump h3lib to v4.1.0 (#402) +- Add `polygon_to_cells` alias (#399) + +## [4.0.0b7] - 2024-09-04 + +- Use `pyproject.toml` and `scikit-build-core` (#378) + +## [4.0.0b6] - 2024-09-03 + +- Added bindings for `cellToVertex`, `cellToVertexes`, `vertexToLatLng`, and `isValidVertex` (#388) + +## [4.0.0b5] - 2024-05-19 + +- Rename `H3Poly` and `H3MultiPoly` to `LatLngPoly` and `LatLngMultiPoly` (#364) +- Add ability to convert from `__geo_interface__` objects with Z-coordinate (#371) + +## [4.0.0b4] - 2024-04-14 + +No changes, just testing: #360 + +## [4.0.0b3] - 2024-03-11 + +- Change supported Python versions to 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 (#324, #325, #347, #348) +- New `h3.Polygon()`/GeoJSON interface (#301) +- Use functions instead of methods for the interface functions (#334) +- Use `list` instead of `set` for unordered Python outputs (#339) + +## [4.0.0b2] - 2022-11-23 + +- Build Python 3.11 wheels (#297) + +## [4.0.0b1] - 2022-08-23 + +Beta release; feedback welcome! + +- Move to v4.0 of the core C library (#250) + + Function name changes: https://github.com/uber/h3/blob/master/dev-docs/RFCs/v4.0.0/names_for_concepts_types_functions.md + + New error system + + New interfaces for `polygon_to_cells` and `cells_to_polygons` + involving a new `h3.Polygon` class +- Expose the Cython API (#234) + + Note: The Cython API is not yet stable, and should only be used for + experimentation ## [3.7.4] - 2022-04-14 - Website and API documentation; along with docstring cleanup. - Add support for linters and IDE tooling (#213) - Remove Py 3.5 wheel for Windows (#214) -- Py 3.10 wheels and on more architectures (#220, #221, #223, #225) +- Py 3.10 wheels and on more architectures (#220, #221, #223, #225) - Greatly reduce sdist size (#227, #229) ## [3.7.3] - 2021-06-12 @@ -65,7 +210,7 @@ avoid adding features or APIs which do not map onto the ## [3.6.2] - 2020-06-02 -- Improve error reporting on `hex2int` (https://github.com/uber/h3-py/pull/127) +- Improve error reporting on `str_to_int` (https://github.com/uber/h3-py/pull/127) - Build Linux wheels for Python 2.7 ## [3.6.1] - 2020-05-29 diff --git a/CMakeLists.txt b/CMakeLists.txt index 00d9fe4..52a76f1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,16 +1,44 @@ -cmake_minimum_required(VERSION 3.7.2) +cmake_minimum_required(VERSION 3.15...3.26) -project(h3) +# --- BEGIN ANDROID CROSS-COMPILATION FIX --- +# Buildozer/python-for-android uses standard pip install which doesn't natively +# pass a CMake toolchain file to scikit-build-core. This detects the Android compiler +# from the environment and forces CMake into cross-compilation mode to prevent +# it from building host (x86_64) binaries. +if("$ENV{CC}" MATCHES "android" AND NOT DEFINED CMAKE_SYSTEM_NAME) + message(STATUS "Detected Android cross-compilation via environment variables. Setting CMAKE_SYSTEM_NAME=Android") + set(CMAKE_SYSTEM_NAME Android) +endif() +# --- END ANDROID CROSS-COMPILATION FIX --- + +project(${SKBUILD_PROJECT_NAME} LANGUAGES C) set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Always make a release build set(CMAKE_BUILD_TYPE Release) +find_package( + Python + COMPONENTS Interpreter Development.Module + REQUIRED) + # Avoid building tooling we won't need for release -set(BUILD_BENCHMARKS OFF CACHE BOOL "" FORCE) -set(BUILD_FILTERS OFF CACHE BOOL "" FORCE) -set(BUILD_GENERATORS OFF CACHE BOOL "" FORCE) -set(BUILD_TESTING OFF CACHE BOOL "" FORCE) +# See all options with `cmake -LA` in an `h3/build` directory, +# or at https://h3geo.org/docs/next/core-library/compilation-options/ +macro(turn_off option_name) + set(${option_name} OFF CACHE BOOL "" FORCE) +endmacro() +turn_off(BUILD_ALLOC_TESTS) +turn_off(BUILD_BENCHMARKS) +turn_off(BUILD_FILTERS) +turn_off(BUILD_FUZZERS) +turn_off(BUILD_GENERATORS) +turn_off(BUILD_TESTING) +turn_off(ENABLE_COVERAGE) +turn_off(ENABLE_DOCS) +turn_off(ENABLE_FORMAT) +turn_off(ENABLE_LIBFUZZER) +turn_off(ENABLE_LINTING) # Build the core library as static set(BUILD_SHARED_LIBS OFF) @@ -25,4 +53,4 @@ install( FILES "${CMAKE_CURRENT_BINARY_DIR}/src/h3lib/src/h3lib/include/h3api.h" DESTINATION - src/h3/_cy) + ${SKBUILD_PROJECT_NAME}/_cy) diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 47de939..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,27 +0,0 @@ -# MANIFEST.in commands specified here: -# https://packaging.python.org/en/latest/guides/using-manifest-in/#manifest-in-commands - -include CHANGELOG.md -include CMakeLists.txt -include LICENSE -include makefile -include pyproject.toml -include readme.md -include requirements.in -include setup.py - -graft src/h3/ - -prune src/h3lib/ - -include src/h3lib/LICENSE -include src/h3lib/README.md -include src/h3lib/VERSION -include src/h3lib/CMakeLists.txt - -graft src/h3lib/scripts -graft src/h3lib/examples -graft src/h3lib/cmake -graft src/h3lib/src/h3lib -graft src/h3lib/src/apps -exclude MANIFEST.in diff --git a/dev_notes.md b/dev_notes.md index 51c1c5f..65b4f62 100644 --- a/dev_notes.md +++ b/dev_notes.md @@ -2,11 +2,21 @@ ## Install for development -- `git clone git@github.com:uber/h3-py.git` +This repo uses [`just`](https://github.com/casey/just) for running common development commands. + +To get started: + +- `git clone --recurse-submodules git@github.com:uber/h3-py.git` + - or fork the repository and `git clone --recurse-submodules https://github.com/{username}/h3-py.git` - `cd h3-py` -- `make init` -- `make test` -- `make lint` +- `just lint` +- `just test` +- `just test-cython` + +To build and view docs: + +- `just docs` +- `just view` ## Docstrings @@ -35,10 +45,21 @@ git add h3lib git commit ... ``` +## Resetting the submodule + +For when moving between `h3-py` branches using different versions of the +`h3lib` submodule. + +```sh +git submodule deinit -f . +git submodule update --init +``` + ## Releasing a new version - update `CHANGELOG.md` to reflect any changes since the last release -- update the `h3-py` version in `src/h3/_version.py` +- update the `h3-py` version in `pyproject.toml` +- if updating the C `h3lib` version, update the version badge on the readme - create PR, get reviews, and merge with these changes - go to https://github.com/uber/h3-py/releases and "Draft a new release" - set the tag version and the release to the version. e.g., `v3.7.2` diff --git a/docs/_config.yml b/docs/_config.yml index 1a4a8c8..37ee18c 100644 --- a/docs/_config.yml +++ b/docs/_config.yml @@ -1,11 +1,6 @@ -####################################################################################### -# A default configuration that will be loaded for all jupyter books -# See the documentation for help and more options: -# https://jupyterbook.org/customize/config.html - title: h3-py author: 'Uber Technologies' -copyright: "2021" +copyright: "2024" logo: logo.svg html: diff --git a/docs/_toc.yml b/docs/_toc.yml index 9d53f89..1238199 100644 --- a/docs/_toc.yml +++ b/docs/_toc.yml @@ -1,34 +1,16 @@ -# Table of contents # Learn more at https://jupyterbook.org/customize/toc.html format: jb-book - root: intro parts: -- caption: Getting started +- caption: h3-py chapters: + - file: api_quick + - file: api_verbose + - file: polygon_tutorial - file: api_comparison - - file: api_reference -- caption: Contributing +- caption: Sundries chapters: - - file: contributing - # - file: jupyter_book_notes - file: _changelog - title: Change log - -- caption: External links - chapters: - - url: https://github.com/uber/h3-py-notebooks - title: Example Notebooks - - url: https://h3geo.org/ - title: H3 Project Homepage - - url: https://github.com/uber/h3-py - title: h3-py on GitHub - - url: https://github.com/uber/h3 - title: H3 on GitHub - - url: https://github.com/uber/h3/discussions - title: GitHub Discussions - - url: https://stackoverflow.com/questions/tagged/h3 - title: H3 Stack Overflow - - url: https://join.slack.com/t/h3-core/shared_invite/zt-g6u5r1hf-W_~uVJmfeiWtMQuBGc1NNg - title: H3 Slack + - file: contributing + - file: project_links diff --git a/docs/api_comparison.md b/docs/api_comparison.md index 3700f1c..bcf9991 100644 --- a/docs/api_comparison.md +++ b/docs/api_comparison.md @@ -1,4 +1,4 @@ -# API comparison +# Comparison of APIs The `h3-py` library provides several APIs which share the same functions, but differ in their input and output types: @@ -37,7 +37,7 @@ needs, based on speed and convenience. ```{tip} Note that the APIs are all 100% compatible, and it is easy to convert -between them with functions like `h3_to_string` (links!) and `string_to_h3`. +between them with functions like `int_to_str` (links!) and `str_to_int`. For example, one common pattern is to use `h3.api.numpy_int` for any computationally-heavy work, and convert the output to `str` and `list`/`set` @@ -54,11 +54,11 @@ using `list` and `set` for collections. ```python >>> import h3 ->>> h = h3.geo_to_h3(0, 0, 0) +>>> h = h3.latlng_to_cell(0, 0, 0) >>> h '8075fffffffffff' ->>> h3.hex_ring(h, 1) +>>> h3.grid_ring(h, 1) {'8055fffffffffff', '8059fffffffffff', '807dfffffffffff', @@ -87,11 +87,11 @@ H3 indexes are represented as Python `int`s, using `list` and `set` for collecti ```python >>> import h3.api.basic_int as h3 ->>> h = h3.geo_to_h3(0, 0, 0) +>>> h = h3.latlng_to_cell(0, 0, 0) >>> h 578536630256664575 ->>> h3.hex_ring(h, 1) +>>> h3.grid_ring(h, 1) {577973680303243263, 578044049047420927, 578677367745019903, @@ -110,11 +110,11 @@ no-copy `numpy` arrays instead of Python `list`s and `set`s. ```python >>> import h3.api.numpy_int as h3 ->>> h = h3.geo_to_h3(0, 0, 0) +>>> h = h3.latlng_to_cell(0, 0, 0) >>> h 578536630256664575 ->>> h3.hex_ring(h, 1) +>>> h3.grid_ring(h, 1) array([578782920861286399, 578044049047420927, 577973680303243263, 578677367745019903, 579169948954263551], dtype=uint64) ``` @@ -141,11 +141,11 @@ In fact, `h3.api.numpy_int` is essentially just a light wrapper around ```python >>> import h3.api.memview_int as h3 ->>> h = h3.geo_to_h3(0, 0, 0) +>>> h = h3.latlng_to_cell(0, 0, 0) >>> h 578536630256664575 ->>> mv = h3.hex_ring(h, 1) +>>> mv = h3.grid_ring(h, 1) >>> mv @@ -175,8 +175,8 @@ For example, consider the setup: ```python >>> import h3.api.memview_int as h3 >>> import numpy as np ->>> h = h3.geo_to_h3(0, 0, 0) ->>> mv = h3.hex_ring(h, 1) +>>> h = h3.latlng_to_cell(0, 0, 0) +>>> mv = h3.grid_ring(h, 1) >>> list(mv) [578782920861286399, 578044049047420927, @@ -200,7 +200,7 @@ Running `a = np.asarray(mv)` **does not create a copy**, so modifying `mv` also modifies `a`: ```python ->>> mv = h3.hex_ring(h, 1) +>>> mv = h3.grid_ring(h, 1) >>> a = np.asarray(mv) >>> mv[0] = 0 >>> a @@ -228,15 +228,15 @@ import h3.api.numpy_int def compute(h3_lib, N=100): - h = h3_lib.geo_to_h3(0, 0, 9) - out = h3_lib.k_ring(h, N) - out = h3_lib.compact(out) + h = h3_lib.latlng_to_cell(0, 0, 9) + out = h3_lib.grid_disk(h, N) + out = h3_lib.compact_cells(out) return out def compute_and_convert(h3_lib, N=100): out = compute(h3_lib, N) - out = [h3.h3_to_string(h) for h in out] + out = [h3.int_to_str(h) for h in out] return out ``` diff --git a/docs/api_quick.md b/docs/api_quick.md new file mode 100644 index 0000000..6694ed4 --- /dev/null +++ b/docs/api_quick.md @@ -0,0 +1,200 @@ +# API Quick Reference + +```{tip} +Function names changed significantly with `h3-py` `v4.0` to align with the C library: https://h3geo.org/docs/library/migration-3.x/functions +``` + +We list the functions that are shared between the +[provided APIs](api_comparison). +The APIs differ only in their input/output types +(e.g., `int` vs. `str` or `list` vs `numpy.array`). + +These functions correspond to those explained in the +[H3 C library documentation](https://h3geo.org/docs/api/indexing), +and should be generally aligned with the +[other language bindings](https://h3geo.org/docs/community/bindings). + +## Identification + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + is_valid_cell + is_pentagon + is_res_class_III + is_valid_directed_edge + is_valid_vertex + is_valid_index +``` + +## Index representation + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + int_to_str + str_to_int +``` + + +## Cell properties + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + get_res0_cells + get_pentagons + get_num_cells + get_resolution + get_base_cell_number + get_index_digit + construct_cell + deconstruct_cell +``` + +## Geographic coordinates + +Functions relating H3 objects to geographic (lat/lng) coordinates. + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + latlng_to_cell + cell_to_latlng + cell_area + edge_length + cell_to_boundary + directed_edge_to_boundary + great_circle_distance + average_hexagon_area + average_hexagon_edge_length +``` + +## Hierarchical relationships + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + cell_to_parent + cell_to_children + cell_to_center_child + cell_to_children_size + cell_to_child_pos + child_pos_to_cell + compact_cells + uncompact_cells +``` + +## Cell grid relationships + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + grid_ring + grid_disk + grid_distance + are_neighbor_cells + grid_path_cells +``` + +## Edges + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + cells_to_directed_edge + directed_edge_to_cells + get_directed_edge_origin + get_directed_edge_destination + origin_to_directed_edges +``` + +## Vertexes + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + cell_to_vertex + cell_to_vertexes + vertex_to_latlng +``` + +## Polygon interface + +The ``LatLngPoly`` and ``LatLngMultiPoly`` objects and their related functions allow users to represent (multi)polygons of lat/lng points and convert back and forth between H3 cells. + +The objects and functions also compatible with the popular [``__geo_interface__`` protocol](https://gist.github.com/sgillies/2217756), which is used by Python geospatial libraries like [GeoPandas](https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.__geo_interface__.html) and many plotting libraries. + +See the [polygon tutorial](./polygon_tutorial.ipynb) for a walkthrough. + +```{tip} +As with other `h3-py` functions, the polygon interface expects coordinate pairs in **lat/lng** order. +Note that this is reversed from [``__geo_interface__``](https://gist.github.com/sgillies/2217756) objects, which are given in **lng/lat** order. +``` + +### Polygon objects + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + H3Shape + LatLngPoly + LatLngMultiPoly +``` + +### Conversion functions + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + h3shape_to_geo + geo_to_h3shape + h3shape_to_cells + cells_to_h3shape + geo_to_cells + cells_to_geo +``` + +#### Additional functions + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + polygon_to_cells + polygon_to_cells_experimental + h3shape_to_cells_experimental +``` + + +## Specialized functions + +### `h3-py` library + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + versions +``` + +### IJ-indexing + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + get_icosahedron_faces + cell_to_local_ij + local_ij_to_cell +``` diff --git a/docs/api_reference.md b/docs/api_reference.md deleted file mode 100644 index fee1b42..0000000 --- a/docs/api_reference.md +++ /dev/null @@ -1,129 +0,0 @@ -# API reference - -This page lists the functions that are common to each of the -[provided APIs](api_comparison). -The APIs differ only in their input/output types -(e.g., `int` vs. `str` or `set` vs `numpy.array`). - -These functions align with those explained in the -[core H3 documentation](https://h3geo.org/docs/api/indexing). - -## Summaries - -There is no strict hierarchy for H3 functions, -but we'll try to group functions in a reasonably logical manner. - -### Identification - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - h3_is_valid - h3_is_pentagon - h3_is_res_class_III - h3_is_res_class_iii - h3_unidirectional_edge_is_valid - versions -``` - -### Cells - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - geo_to_h3 - h3_to_geo - h3_to_string - string_to_h3 - get_res0_indexes - get_pentagon_indexes - num_hexagons - h3_get_resolution - compact - uncompact -``` - -### Geographic coordinates - -Functions relating H3 objects to geographic (lat/lng) coordinates. - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - point_dist - hex_area - cell_area - edge_length - exact_edge_length - h3_to_geo_boundary - get_h3_unidirectional_edge_boundary - polyfill - polyfill_geojson - polyfill_polygon - h3_set_to_multi_polygon -``` - -### Hierarchical relationships - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - h3_to_parent - h3_to_children - h3_to_center_child -``` - -### Cell grid relationships - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - hex_range - hex_range_distances - hex_ranges - hex_ring - k_ring - k_ring_distances - h3_distance - h3_indexes_are_neighbors - h3_line -``` - -### Edges - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - get_h3_unidirectional_edge - get_destination_h3_index_from_unidirectional_edge - get_h3_indexes_from_unidirectional_edge - get_h3_unidirectional_edges_from_hexagon - get_origin_h3_index_from_unidirectional_edge -``` - -### IJ-indexing - -```{eval-rst} -.. currentmodule:: h3 - -.. autosummary:: - h3_get_base_cell - h3_get_faces - experimental_h3_to_local_ij - experimental_local_ij_to_h3 -``` - - -## Definitions - -```{eval-rst} -.. automodule:: h3 - :members: - :imported-members: -``` diff --git a/docs/api_verbose.md b/docs/api_verbose.md new file mode 100644 index 0000000..83e5219 --- /dev/null +++ b/docs/api_verbose.md @@ -0,0 +1,10 @@ +# API Verbose Reference + +This page gives the full documentation for each function and object. +Refer back to [](api_quick.md) for context and logical groupings. + +```{eval-rst} +.. automodule:: h3 + :members: + :imported-members: +``` diff --git a/docs/contributing.md b/docs/contributing.md index b6bfcde..a76bfb5 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,33 +1,12 @@ # Contributing -```{attention} -This page still a work in progress. -``` +Contributions from the community are welcome! -## Python and Cython - -todo - -## Project organization - -todo - -## Docstring conventions - -https://numpydoc.readthedocs.io/en/latest/format.html - -## Website - -### TODOs - -- release PDF version of docs with each library verison/release? -- page on "anatomy of an H3 index" - -### Other projects with nice docs - -For reference, here are some other projects whose docs we should -consider when styling our own: - -- https://toolz.readthedocs.io/en/latest/api.html -- http://xarray.pydata.org/ -- https://docs.dask.org/en/latest/api.html +Please feel free to +[file an issue](https://github.com/uber/h3-py/issues), +open a +[pull request](https://github.com/uber/h3-py/pulls), +or start a +[discussion in Github](https://github.com/uber/h3-py/discussions) +or in the +[H3 Slack](https://join.slack.com/t/h3-core/shared_invite/zt-g6u5r1hf-W_~uVJmfeiWtMQuBGc1NNg). \ No newline at end of file diff --git a/docs/polygon_tutorial.ipynb b/docs/polygon_tutorial.ipynb new file mode 100644 index 0000000..e8df06a --- /dev/null +++ b/docs/polygon_tutorial.ipynb @@ -0,0 +1,933 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "03ee1f11-7a60-4761-aaf7-673ea04e7dca", + "metadata": {}, + "source": [ + "# Polygon Tutorial\n", + "\n", + "`h3-py` can convert between sets of cells and GeoJSON-like polygon and multipolygon shapes.\n", + "\n", + "We use the abstract base class `H3Shape` and its concrete child classes `LatLngPoly` and `LatLngMultiPoly`\n", + "to represent these shapes. \n", + "Any references or function names that use \"H3Shape\" will apply to both `LatLngPoly` and `LatLngMultiPoly` objects.\n", + "\n", + "`h3-py` is also compatible with Python objects that implement `__geo_interface__` (https://gist.github.com/sgillies/2217756),\n", + "making it easy to interface with other Python geospatial libraries.\n", + "We'll refer to any such object as a \"geo\" or \"geo object\".\n", + "\n", + "`LatLngPoly` and `LatLngMultiPoly` both implement `__geo_interface__` (making them geo objects themselves),\n", + "and can be created from other geo objects, like Shapely's `Polygon` or `MultiPolygon` objects that occur\n", + "when using `geopandas`.\n", + "\n", + "Below, we'll explain the `h3-py` API for working with these shapes, and how the library interacts\n", + "with other Python geospatial libraries.\n", + "\n", + "To start, we'll import relevant libraries, and define some plotting helper functions to visualize the shapes we're dealing with." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f5454f0-f65e-491c-b534-f1ef08320263", + "metadata": {}, + "outputs": [], + "source": [ + "import h3\n", + "\n", + "import geopandas\n", + "import geodatasets\n", + "import contextily as cx\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "def plot_df(df, column=None, ax=None):\n", + " \"Plot based on the `geometry` column of a GeoPandas dataframe\"\n", + " df = df.copy()\n", + " df = df.to_crs(epsg=3857) # web mercator\n", + "\n", + " if ax is None:\n", + " _, ax = plt.subplots(figsize=(8,8))\n", + " ax.get_xaxis().set_visible(False)\n", + " ax.get_yaxis().set_visible(False)\n", + "\n", + " df.plot(\n", + " ax=ax,\n", + " alpha=0.5, edgecolor='k',\n", + " column=column, categorical=True,\n", + " legend=True, legend_kwds={'loc': 'upper left'},\n", + " )\n", + " cx.add_basemap(ax, crs=df.crs, source=cx.providers.CartoDB.Positron)\n", + "\n", + "\n", + "def plot_shape(shape, ax=None):\n", + " df = geopandas.GeoDataFrame({'geometry': [shape]}, crs='EPSG:4326')\n", + " plot_df(df, ax=ax)\n", + "\n", + "\n", + "def plot_cells(cells, ax=None):\n", + " shape = h3.cells_to_h3shape(cells)\n", + " plot_shape(shape, ax=ax)\n", + "\n", + "\n", + "def plot_shape_and_cells(shape, res=9):\n", + " fig, axs = plt.subplots(1,2, figsize=(10,5), sharex=True, sharey=True)\n", + " plot_shape(shape, ax=axs[0])\n", + " plot_cells(h3.h3shape_to_cells(shape, res), ax=axs[1])\n", + " fig.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "id": "c5a41e2b-0c9e-45f5-8005-51af2ef8af32", + "metadata": {}, + "source": [ + "# LatLngPoly\n", + "\n", + "We can create a simple `LatLngPoly` object by providing a list of the **latitude/longitude pairs** that describe its exterior.\n", + "Optionally, holes can be added to the polygon by appending additional lat/lng lists do describe them." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1e9e3e2a-a4cf-43df-a498-ee7d15a8cc4b", + "metadata": {}, + "outputs": [], + "source": [ + "outer = [\n", + " (37.804, -122.412),\n", + " (37.778, -122.507),\n", + " (37.733, -122.501)\n", + "]\n", + "\n", + "poly = h3.LatLngPoly(outer)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6872b341-afc9-4405-b27a-b5f2b8a19847", + "metadata": {}, + "outputs": [], + "source": [ + "hole1 = [\n", + " (37.782, -122.449),\n", + " (37.779, -122.465),\n", + " (37.788, -122.454),\n", + "]\n", + "\n", + "poly = h3.LatLngPoly(outer, hole1)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2d7ae0fb-fa96-46fe-8d06-7778575642dd", + "metadata": {}, + "outputs": [], + "source": [ + "hole2 = [\n", + " (37.771, -122.484),\n", + " (37.761, -122.481),\n", + " (37.758, -122.494),\n", + " (37.769, -122.496),\n", + "]\n", + "\n", + "poly = h3.LatLngPoly(outer, hole1, hole2)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "markdown", + "id": "62317cfd-8a0e-4c8a-b899-131acdec4305", + "metadata": {}, + "source": [ + "## String representation and attributes\n", + "\n", + "The `LatLngPoly` string representation given by its `__repr__` shows the number of vertices in the outer loop of the polygon, followed\n", + "by the number of vertices in each hole.\n", + "\n", + "A representation like\n", + "\n", + "```\n", + "\n", + "```\n", + "\n", + "denotes a polygon whose outer boundary consists of 3 vertices and which has 2 holes,\n", + "with 3 and 4 vertices respectively.\n", + "\n", + "We can access the coordinates describing the polygon through the attributes:\n", + "\n", + "- `LatLngPoly.outer` gives the list of lat/lng points making up the outer loop of the polygon.\n", + "- `LatLngPoly.holes` gives each of the lists of lat/lng points making up the holes of the polygon." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "97c8aa44-12fb-4c47-9254-d931522575ed", + "metadata": {}, + "outputs": [], + "source": [ + "poly = h3.LatLngPoly(outer, hole1, hole2)\n", + "poly" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "150ae04c-bae2-4b7e-88d0-f5fcf0835e7b", + "metadata": {}, + "outputs": [], + "source": [ + "poly.outer" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84061e68-60f3-4df4-a279-a0630af7dcc2", + "metadata": {}, + "outputs": [], + "source": [ + "poly.holes" + ] + }, + { + "cell_type": "markdown", + "id": "ae175854-6770-44aa-b796-8d9390f7c856", + "metadata": {}, + "source": [ + "## `__geo_interface__`\n", + "\n", + "`LatLngPoly.__geo_interface__` gives a GeoJSON representation of the polygon as described in https://gist.github.com/sgillies/2217756\n", + "\n", + "**Note the differences in this representation**: Points are given in **lng/lat** order (but the `LatLngPoly` constructor expects **lat/lng** order), and the last vertex repeats the first." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fb79c742-27aa-481c-971b-28c100109efe", + "metadata": {}, + "outputs": [], + "source": [ + "d = poly.__geo_interface__\n", + "d" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fc1b0ae8-bcce-4e5f-ad88-57e3797518f4", + "metadata": {}, + "outputs": [], + "source": [ + "print(poly.outer)\n", + "print(poly.holes)" + ] + }, + { + "cell_type": "markdown", + "id": "8f567fae-9f4e-472f-afcd-bd6f7bb32cba", + "metadata": {}, + "source": [ + "We can create an `LatLngPoly` object from a GeoJSON-like dictionary or an object that implements `__geo_interface__` using `h3.geo_to_h3shape()`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42d7d580-2bba-4cd3-8d13-2434323e4081", + "metadata": {}, + "outputs": [], + "source": [ + "h3.geo_to_h3shape(d)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c70b6fa3-d85d-420e-a295-a75a32bf3dad", + "metadata": {}, + "outputs": [], + "source": [ + "class MockGeo:\n", + " def __init__(self, d):\n", + " self.d = d\n", + "\n", + " @property\n", + " def __geo_interface__(self):\n", + " return self.d\n", + "\n", + "\n", + "geo = MockGeo(d)\n", + "h3.geo_to_h3shape(geo)" + ] + }, + { + "cell_type": "markdown", + "id": "0ab82119-9d9e-465d-94b5-61083e9d9df3", + "metadata": {}, + "source": [ + "Also note that `LatLngPoly.__geo_interface__` is equivalent to calling `h3.h3shape_to_geo()` on an `LatLngPoly` object." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd9bd77d-ed1e-46bb-991a-f0cfc10f634b", + "metadata": {}, + "outputs": [], + "source": [ + "poly.__geo_interface__ == h3.h3shape_to_geo(poly)" + ] + }, + { + "cell_type": "markdown", + "id": "55c31b56-c65d-4e06-bf60-edf96bb57e93", + "metadata": {}, + "source": [ + "## Polygon to cells\n", + "\n", + "We can get all the H3 cells whose centroids fall within an `LatLngPoly` by using `h3.h3shape_to_cells()` and specifying the resolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6c310200-30f2-4b24-a967-d705ffc05bd6", + "metadata": {}, + "outputs": [], + "source": [ + "h3.h3shape_to_cells(poly, res=7)" + ] + }, + { + "cell_type": "markdown", + "id": "ec0d8ac7-ba97-46c4-8740-3a12a00e318d", + "metadata": {}, + "source": [ + "We'll use a helper function to show a few different resolutions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ac7cd51-1c7e-4509-94b4-92e59fd22c2a", + "metadata": {}, + "outputs": [], + "source": [ + "plot_shape_and_cells(poly, 7)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b0330d60-0adc-46e7-9689-7be1ba957dfc", + "metadata": {}, + "outputs": [], + "source": [ + "plot_shape_and_cells(poly, 9)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1fd40b0a-34fd-4ac7-9c3a-c367e5041cd8", + "metadata": {}, + "outputs": [], + "source": [ + "plot_shape_and_cells(poly, 10)" + ] + }, + { + "cell_type": "markdown", + "id": "faa6a726-2adc-40cc-9e1e-5d4ee66a08ea", + "metadata": {}, + "source": [ + "## H3 Polygons don't need to follow the right-hand rule\n", + "\n", + "`LatLngPoly` objects do not need to follow the \"right-hand rule\", unlike GeoJSON Polygons. \n", + "The right-hand rule requires that vertices in outer loops are listed in counterclockwise\n", + "order and holes are listed in clockwise order.\n", + "`h3-py` accepts loops in any order and will usually interpret them as the user intended, for example,\n", + "converting to sets of cells. However, `h3-py` won't re-order your loops to\n", + "conform to the right-hand rule, so be careful if you're using `__geo_interface__` to plot them.\n", + "\n", + "Obeying the right-hand rule is only a concern when creating `LatLngPoly` objects from external input; `LatLngPoly` or `LatLngMultiPoly`\n", + "objects created through `h3.cells_to_h3shape()` **will respect the right-hand rule**.\n", + "\n", + "For example, if we reverse the order of one of the holes in our example polygon above,\n", + "the hole won't be rendered correctly, but the conversion to cells will remain unchanged." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "34ef8624-c852-419d-9e98-e9ec70ec6bc0", + "metadata": {}, + "outputs": [], + "source": [ + "# Respects right-hand rule\n", + "poly = h3.LatLngPoly(outer, hole1, hole2)\n", + "plot_shape_and_cells(poly, res=10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e52ae550-e34d-406b-9c82-b283fd34a170", + "metadata": {}, + "outputs": [], + "source": [ + "# Does not respect right-hand-rule; second hole is reversed\n", + "# Conversion to cells still works, tho!\n", + "poly = h3.LatLngPoly(outer, hole1[::-1], hole2)\n", + "plot_shape_and_cells(poly, res=10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1940071-eb32-44bc-b07c-2a2eef14b21e", + "metadata": {}, + "outputs": [], + "source": [ + "# Does not respect right-hand-rule; outer loop and second hole are both reversed\n", + "# Conversion to cells still works, tho!\n", + "poly = h3.LatLngPoly(outer[::-1], hole1[::-1], hole2)\n", + "plot_shape_and_cells(poly, res=10)" + ] + }, + { + "cell_type": "markdown", + "id": "b0b13d4a-a376-4a8f-b314-898d9cf94c59", + "metadata": {}, + "source": [ + "# LatLngMultiPoly\n", + "\n", + "An `LatLngMultiPoly` can be created from `LatLngPoly` objects. The string representation of the `LatLngMultiPoly`\n", + "gives the number of vertices in the outer loop of each `LatLngPoly`, along with the number of vertices\n", + "in each hole (if there are any).\n", + "\n", + "For example `` represents an `LatLngMultiPoly` consisting of two `LatLngPoly` polygons:\n", + "\n", + "- the first polygon has 3 outer vertices and no holes\n", + "- the second polygon has 4 outer vertices and 1 hole with 5 vertices" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16b0b4b2-2cfb-461d-bd69-511c87e208a3", + "metadata": {}, + "outputs": [], + "source": [ + "poly1 = h3.LatLngPoly([(37.804, -122.412), (37.778, -122.507), (37.733, -122.501)])\n", + "poly2 = h3.LatLngPoly(\n", + " [(37.803, -122.408), (37.736, -122.491), (37.738, -122.380), (37.787, -122.39)],\n", + " [(37.760, -122.441), (37.772, -122.427), (37.773, -122.404), (37.758, -122.401), (37.745, -122.428)]\n", + ")\n", + "mpoly = h3.LatLngMultiPoly(poly1, poly2)\n", + "\n", + "print(poly1)\n", + "print(poly2)\n", + "print(mpoly)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f2faf991-9d3b-4e0a-8fd4-8c31e19fd07b", + "metadata": {}, + "outputs": [], + "source": [ + "plot_shape(mpoly)" + ] + }, + { + "cell_type": "markdown", + "id": "850912ae-85f1-470c-aeea-1140f549fc95", + "metadata": {}, + "source": [ + "## MultiPolygon to cells\n", + "\n", + "`h3.h3shape_to_cells()` works on both `LatLngMultiPoly` and `LatLngPoly` objects (both are subclasses of `H3Shape`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "944564c0-8198-49ae-81de-cf980dc4b348", + "metadata": {}, + "outputs": [], + "source": [ + "cells = h3.h3shape_to_cells(mpoly, res=9)\n", + "plot_cells(cells)" + ] + }, + { + "cell_type": "markdown", + "id": "f3712d99-cbe2-4f42-80e3-0acf3fcb8e25", + "metadata": {}, + "source": [ + "## LatLngMultiPoly affordances\n", + "\n", + "- Calling `len()` on an `LatLngMultiPoly` gives the number of polygons\n", + "- You can iterate through a `LatLngMultiPoly`, with the elements being the underlying `LatLngPoly`s" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "217d6e5a-bb8b-4923-b311-0f84ebf48872", + "metadata": {}, + "outputs": [], + "source": [ + "len(mpoly)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03f6cd31-b18f-4fe7-b259-78741f12c95d", + "metadata": {}, + "outputs": [], + "source": [ + "for p in mpoly:\n", + " print(p)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4eca4cec-2881-4ed1-a65c-3aea38ac9c63", + "metadata": {}, + "outputs": [], + "source": [ + "list(mpoly)" + ] + }, + { + "cell_type": "markdown", + "id": "2fd0a70c-d0cf-487c-b492-6b459dc13a30", + "metadata": {}, + "source": [ + "## `__geo_interface__`\n", + "\n", + "`LatLngMultiPoly` implements `__geo_interface__`, and `LatLngMultiPoly` objects can also be created through `h3.geo_to_h3shape()`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2731474c-b3f8-4438-8932-62af21f8d6cf", + "metadata": {}, + "outputs": [], + "source": [ + "d = mpoly.__geo_interface__\n", + "d" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5cc947e-0672-492d-a4bf-f303afbb5cfa", + "metadata": {}, + "outputs": [], + "source": [ + "geo = MockGeo(d)\n", + "h3.geo_to_h3shape(geo)" + ] + }, + { + "cell_type": "markdown", + "id": "a2b71ee2-deed-4336-8b2c-2ab740555188", + "metadata": {}, + "source": [ + "# Cells to LatLngPoly or LatLngMultiPoly\n", + "\n", + "If you have a set of H3 cells that you would like to visualize, you may want to convert them to `LatLngPoly` or `LatLngMultiPoly` objects using `h3.cells_to_h3shape()` and then use `__geo_interface__` to get their GeoJSON representation. Or you could\n", + "use `h3.cells_to_geo()` to get the GeoJSON dictionary directly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a2305120-adf4-4cee-9e2a-58e793e55cfb", + "metadata": {}, + "outputs": [], + "source": [ + "h = h3.latlng_to_cell(37.804, -122.412, res=9)\n", + "cells = h3.grid_ring(h, 2)\n", + "cells" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3e242238-af2c-45a3-acd0-8daf3773a2bd", + "metadata": {}, + "outputs": [], + "source": [ + "plot_cells(cells)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a9d124ff-4e49-4e34-a6be-4a49bc00bcd9", + "metadata": {}, + "outputs": [], + "source": [ + "h3.cells_to_h3shape(cells)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b3ca5d18-a78a-4bc6-80d9-d98099da924d", + "metadata": {}, + "outputs": [], + "source": [ + "str(h3.cells_to_geo(cells))[:200]" + ] + }, + { + "cell_type": "markdown", + "id": "0ae6d480-4807-4ca1-ac20-4095a20ded31", + "metadata": {}, + "source": [ + "# API Summary\n", + "\n", + "```\n", + "\"Geo object\" <-> H3Shape <-> H3 cells\n", + "```\n", + "\n", + "\"Geo objects\" are any Python object that implements `__geo_interface__`. This is a widely used\n", + "standard in geospatial Python and is used by libraries like `geopandas` and Shapely.\n", + "\n", + "`H3Shape` is an abstract class implemented by `LatLngPoly` and `LatLngMultiPoly`, each of which\n", + "implement `__geo_interface__` and can be created from external \"Geo objects\":\n", + "\n", + "- `geo_to_h3shape()`\n", + "- `h3shape_to_geo()`\n", + "\n", + "`H3Shape` objects can be converted to and from sets of H3 cells:\n", + "\n", + "- `h3shape_to_cells()`\n", + "- `cells_to_h3shape()`\n", + "\n", + "For convience, we provide functions that hide the intermediate `H3Shape` representation:\n", + "\n", + "- `geo_to_cells()`\n", + "- `cells_to_geo()`\n", + "\n", + "## Equivalance notes\n", + "\n", + "Note that if an object `a` is an `H3Shape`\n", + "then the following two expressions are equivalent:\n", + "\n", + "- `h3shape_to_geo(a)`\n", + "- `a.__geo_interface__`\n", + "\n", + "Also note that if `a` is an `H3Shape`, then `a` \"passes through\" `geo_to_h3shape()`:\n", + "\n", + "```python\n", + "geo_to_h3shape(a) == a\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "5838f6c8-aacb-4813-be7c-756c87945476", + "metadata": {}, + "source": [ + "# Interfacing with GeoPandas and other libraries\n", + "\n", + "The `__geo_interface__` compatibility allows `h3-py` to work with `geopandas` and other geospatial libraries easily.\n", + "\n", + "To demonstrate, we start with a GeoPandas `GeoDataFrame` describing the five New York City boroughs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a872e2a1-dd51-4262-bc98-800500121bc0", + "metadata": {}, + "outputs": [], + "source": [ + "df = geopandas.read_file(geodatasets.get_path('nybb'))\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bbca69dc-1722-4be4-a1bb-329d7e77ec83", + "metadata": {}, + "outputs": [], + "source": [ + "plot_df(df, column='BoroName')" + ] + }, + { + "cell_type": "markdown", + "id": "a060b933-8f32-402b-ac61-7cd04dcf70df", + "metadata": {}, + "source": [ + "## Use a compatible CRS before applying H3 functions\n", + "\n", + "The function `h3.geo_to_cells(geo, res)` takes some \"geo object\" that implements `__geo_interface__` (https://gist.github.com/sgillies/2217756) — like a Shapely Polygon or MultiPolygon — and converts it to the set of cells whose centroids are contained in `geo`.\n", + "\n", + "**Common Pitfall**: Be careful about what CRS you are using. `h3-py` expects coordinates as latitude-longitude pairs. The CRS of the current dataframe (EPSG:2263) gives coordinates in feet! You should first convert the data to something compatible. A common choice is **EPSG:4326/WGS84**. You'll get incorrect results if you apply `h3.geo_to_cells` without converting." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83fced81-89f1-4795-84b8-c852c8c3f938", + "metadata": {}, + "outputs": [], + "source": [ + "# Original CRS\n", + "df.crs" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dfaf3b8a-2e53-4adf-87a5-ef9fe616df32", + "metadata": {}, + "outputs": [], + "source": [ + "df.geometry[0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "00e1026a-0a0c-448f-9223-8ce6d4d5a9a3", + "metadata": {}, + "outputs": [], + "source": [ + "# Converting to EPSG:4326/WGS84\n", + "df = df.to_crs(epsg=4326)\n", + "df.crs" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "81071108-3c13-4e10-8608-892ed3742054", + "metadata": {}, + "outputs": [], + "source": [ + "# Note that the `geometry` column now has coordinates in degrees\n", + "df" + ] + }, + { + "cell_type": "markdown", + "id": "01ca62b0-61f3-4204-bb0f-a14c9859cd4d", + "metadata": {}, + "source": [ + "## Converting a geo to H3 cells\n", + "\n", + "First, we select one of the boroughs and get the Shapely `MultiPolygon` describing it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0be200e1-2536-4430-90ef-38dc72a75f9f", + "metadata": {}, + "outputs": [], + "source": [ + "geo = df.geometry[0]\n", + "type(geo)" + ] + }, + { + "cell_type": "markdown", + "id": "0a3c3c9c-b547-4a69-9030-fb88f486c4aa", + "metadata": {}, + "source": [ + "Note that Shapely `MultiPolygon` objects implement `__geo_interface__`, so we can use `h3.geo_to_cells()` to get the associated set of H3 cells at various resolutions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1a12743-b5e2-4cd1-a7fd-848e920fa928", + "metadata": {}, + "outputs": [], + "source": [ + "h3.geo_to_cells(geo, res=6)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "27d24ca5-123f-4462-b37d-bcba6acc4f64", + "metadata": {}, + "outputs": [], + "source": [ + "plot_cells(h3.geo_to_cells(geo, res=9))" + ] + }, + { + "cell_type": "markdown", + "id": "e00d088e-47b9-4bca-a8b3-d22dab747be3", + "metadata": {}, + "source": [ + "## Converting all geos in a GeoDataFrame to cells\n", + "\n", + "We can apply `geo_to_cells()` to each of the Shapely geometries in the `df.geometry` column." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9901cc3-cd8d-4543-a8fb-98178010700e", + "metadata": {}, + "outputs": [], + "source": [ + "cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8))\n", + "cell_column" + ] + }, + { + "cell_type": "markdown", + "id": "502efd48-2c0b-4860-8796-7ea2e4e88687", + "metadata": {}, + "source": [ + "## Converting cells to \"geo objects\"\n", + "\n", + "If we assign `df.geometry = cell_column` we'll get an error because the `geometry` column of a `geopandas.GeoDataFrame` must contain valid geometry objects.\n", + "We can obtain compatible objects by converting the cells to `H3Shape` by applying `h3.cells_to_h3shape()`.\n", + "\n", + "(Note that, unfortunately, Pandas has some logic to identify iterable members of a series and then renders a tuple of the elements, rather than our preferred `LatLngMultiPoly.__repr__` representation.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c5cb00c-9796-4356-8e2a-8dc50c86103c", + "metadata": {}, + "outputs": [], + "source": [ + "shape_column = cell_column.apply(h3.cells_to_h3shape)\n", + "shape_column" + ] + }, + { + "cell_type": "markdown", + "id": "1965d53f-2bba-4840-a627-1bbf55405be3", + "metadata": {}, + "source": [ + "Note that the column now consists of `LatLngPoly` and `LatLngMultiPoly` objects." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b3eedce-2570-4708-992e-e6d739eecc2f", + "metadata": {}, + "outputs": [], + "source": [ + "shape_column[0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "014bc63d-5cfa-4a65-95e6-390ddddd1703", + "metadata": {}, + "outputs": [], + "source": [ + "shape_column[1]" + ] + }, + { + "cell_type": "markdown", + "id": "6ae6afb2-8267-492a-836e-cf371df91e89", + "metadata": {}, + "source": [ + "Now, if we assign `df.geometry = shape_column`, our `H3Shape` objects will automatically be converted to Shapely Polygon and MultiPolygon objects via `__geo_interface__`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c5cd4cf-226b-405f-9c36-7f1ccc09c342", + "metadata": {}, + "outputs": [], + "source": [ + "df.geometry = shape_column\n", + "df.geometry" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2608ce79-f2c5-4dbc-bf22-a28255343aea", + "metadata": {}, + "outputs": [], + "source": [ + "type(df.geometry[0])" + ] + }, + { + "cell_type": "markdown", + "id": "d568b20e-88cb-4269-99ce-dc96a73d93d1", + "metadata": {}, + "source": [ + "## Visualizing H3 cells\n", + "\n", + "We took some Shapely geometry objects, converted them to H3 cells, and converted those back to Shapely geometry objects in a `geopandas.GeoDataFrame`. \n", + "\n", + "We can visualize the results with our helper function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63ab3ec1-49c2-482d-8b84-154dd8196eda", + "metadata": {}, + "outputs": [], + "source": [ + "plot_df(df, column='BoroName')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/project_links.md b/docs/project_links.md new file mode 100644 index 0000000..d9f9d63 --- /dev/null +++ b/docs/project_links.md @@ -0,0 +1,19 @@ +# Project Links + +## H3 + +Links for the overall H3 project including the core C library and all language bindings (including +Python!). + +- [H3 Project Homepage](https://h3geo.org/) +- [H3 on GitHub](https://github.com/uber/h3) +- [H3 Project GitHub Discussions](https://github.com/uber/h3/discussions) +- [H3 on Stack Overflow](https://stackoverflow.com/questions/tagged/h3) +- [H3 on Slack](https://join.slack.com/t/h3-core/shared_invite/zt-g6u5r1hf-W_~uVJmfeiWtMQuBGc1NNg) + +## h3-py + +Links specific to the H3 Python bindings. + +- [Example Notebooks](https://github.com/uber/h3-py-notebooks) +- [h3-py on GitHub](https://github.com/uber/h3-py) diff --git a/justfile b/justfile new file mode 100644 index 0000000..d8e44fb --- /dev/null +++ b/justfile @@ -0,0 +1,61 @@ +# disable editable installs so uv sync does a full build of the C extension +export UV_NO_EDITABLE := "1" + +_: + just --list + +# force-rebuild the C extension to avoid stale builds +reinstall: + uv cache clean h3 + uv sync --reinstall-package h3 + +# locally, always reinstall before testing +test: reinstall ci-test +test-cython: reinstall ci-test-cython + +fix: + uvx ruff check --fix + +lab: + uv sync --group docs + uv run jupyter lab + +view: + open docs/_build/html/index.html + +purge: + just _rm .venv + just _rm '*.pytest_cache' + just _rm .DS_Store + just _rm '*.egg-info' + just _rm dist + just _rm '*.ipynb_checkpoints' + just _rm __pycache__ + just _rm uv.lock + just _rm .coverage + just _rm build + just _rm _build + just _rm _skbuild + just _rm .ruff_cache + uv cache clean h3 + +_rm pattern: + -@find . -name "{{pattern}}" -prune -exec rm -rf {} + + + +# Recipes below are used by CI workflows (.github/workflows/). +# Changes here may break CI — update the workflows accordingly. + +ci-test: + uv run pytest tests/test_lib --cov=h3 --cov=tests/test_lib --cov-fail-under=100 + +ci-test-cython: + uv run --with cython --with setuptools cythonize tests/test_cython/cython_example.pyx + uv run pytest tests/test_cython --cov=tests/test_cython + +lint: + uvx ruff check + +docs: + uv sync --group docs + uv run jupyter-book build docs/ --warningiserror --keep-going --all diff --git a/makefile b/makefile deleted file mode 100644 index 6e44c02..0000000 --- a/makefile +++ /dev/null @@ -1,47 +0,0 @@ -.PHONY: init clear rebuild purge test lint lab ipython - - -build-docs: - env/bin/jupyter-book build docs/ --warningiserror --keep-going --all - -open: - open docs/_build/html/index.html - - -init: purge - git submodule update --init - python -m venv env - env/bin/pip install --upgrade pip wheel setuptools - env/bin/pip install .[all] - env/bin/pip install -r requirements.in - -clear: - -env/bin/pip uninstall -y h3 - -@rm -rf MANIFEST - -@rm -rf annotations - -@rm -rf .pytest_cache tests/__pycache__ __pycache__ _skbuild dist .coverage - -@find . -type d -name '*.egg-info' | xargs rm -r - -@find . -type f -name '*.pyc' | xargs rm -r - -@find . -type d -name '*.ipynb_checkpoints' | xargs rm -r - -rebuild: clear - env/bin/pip install .[all] - -purge: clear - -@rm -rf env - -annotations: rebuild - mkdir -p annotations - cp _skbuild/*/cmake-build/src/h3/_cy/*.html ./annotations - -test: - env/bin/cythonize -i tests/cython_example.pyx - env/bin/pytest tests --cov=h3 --cov-report term-missing --durations=10 - -lint: - env/bin/flake8 src/h3 setup.py tests - env/bin/pylint --disable=all --enable=import-error tests/ - -lab: - env/bin/pip install jupyterlab - env/bin/jupyter lab diff --git a/pyproject.toml b/pyproject.toml index ce6867f..4430799 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,143 @@ [build-system] -requires = [ - 'scikit-build', - 'cython', - 'cmake', +requires = ['scikit-build-core', 'cython'] +build-backend = 'scikit_build_core.build' + +[project] +name = 'h3' +version = '4.5.0' +description = "Uber's hierarchical hexagonal geospatial indexing system" +readme = 'readme.md' +license = {file = 'LICENSE'} +authors = [ + { name = 'Uber Technologies', email = 'ajfriend@gmail.com' }, +] +maintainers = [ + { name = 'AJ Friend', email = 'ajfriend@gmail.com' }, +] +requires-python = '>=3.10' + +dependencies = [] + +classifiers = [ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: C', + 'Programming Language :: Cython', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', + 'Programming Language :: Python :: 3.15', + 'Programming Language :: Python :: Free Threading', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: POSIX :: Linux', + 'Operating System :: Microsoft :: Windows', + 'Topic :: Scientific/Engineering :: GIS', +] + +[project.urls] +Homepage = 'https://github.com/uber/h3-py' +Documentation = 'https://uber.github.io/h3-py/' +'Bug Tracker' = 'https://github.com/uber/h3-py/issues' +Discussions = 'https://github.com/uber/h3-py/discussions' +Changelog = 'https://uber.github.io/h3-py/_changelog.html' + + +[project.optional-dependencies] +numpy = ['numpy'] + +[dependency-groups] +dev = ['pytest', 'pytest-cov', 'numpy'] +docs = [ + 'numpy', + 'jupyter-book<2', + 'sphinx>=7.3.3', # https://github.com/sphinx-doc/sphinx/issues/12290 + 'jupyterlab', + 'jupyterlab-geojson', + 'geopandas', + 'geodatasets', + 'matplotlib', + 'contextily', + 'cartopy', + 'geoviews', +] + +[tool.pytest.ini_options] +addopts = "--cov-report=term-missing --durations=10" + +[tool.coverage.run] +omit = [ + '*/h3/api/basic_int/__init__.py', + '*/h3/api/memview_int/__init__.py', + '*/h3/api/numpy_int/__init__.py' +] + + +[tool.uv] +default-groups = ['dev'] + +[tool.scikit-build] +sdist.exclude = [ + 'src/h3lib', + 'docs', + 'dev_notes.md', + 'justfile', + '.github', + '.gitignore', + '.gitmodules', +] +sdist.include = [ + 'src/h3lib/LICENSE', + 'src/h3lib/README.md', + 'src/h3lib/VERSION', + 'src/h3lib/CMakeLists.txt', + 'src/h3lib/h3.pc.in', + 'src/h3lib/cmake/*', + 'src/h3lib/src/h3lib/*' +] + + +[tool.ruff] +src = [ + 'src', + 'tests', +] +line-length = 88 + +[tool.ruff.lint] +flake8-quotes.inline-quotes = 'single' + +# https://docs.astral.sh/ruff/rules/ +preview = true # https://docs.astral.sh/ruff/preview/#selecting-single-preview-rules +select = [ + 'A', + # 'B', # todo + # 'COM', # todo + 'E', + 'F', + 'Q', + 'W', + # 'D', # todo. this is nice! + # 'PL', # todo. some interesting ideas + # 'DOC', # todo: interesting +] +ignore = [ + 'E221', # Multiple spaces before operator + 'E231', # Missing whitespace after ',' + 'E241', # Multiple spaces after ',' + 'E251', # Unexpected spaces around keyword / parameter equals + 'E272', # Multiple spaces before keyword + 'E731', # Do not assign a `lambda` expression, use a `def` + # 'PLR2004', +] + +[tool.ruff.lint.per-file-ignores] +'*.ipynb' = [ + 'E501', # Line too long (104 > 88) +] +'test*.py' = [ + # 'D', # maybe just the need for docstring ] diff --git a/readme.md b/readme.md index e060f05..8cb052b 100644 --- a/readme.md +++ b/readme.md @@ -1,24 +1,22 @@ -H3 Logo +H3 Logo # **h3-py**: Uber's H3 Hexagonal Hierarchical Geospatial Indexing System in Python - - [![PyPI version](https://badge.fury.io/py/h3.svg)](https://badge.fury.io/py/h3) [![PyPI downloads](https://img.shields.io/pypi/dm/h3.svg)](https://pypistats.org/packages/h3) [![conda](https://img.shields.io/conda/vn/conda-forge/h3-py.svg)](https://anaconda.org/conda-forge/h3-py) -[![version](https://img.shields.io/badge/h3-v3.7.1-blue.svg)](https://github.com/uber/h3/releases/tag/v3.7.1) +[![version](https://img.shields.io/badge/h3-v4.5.0-blue.svg)](https://github.com/uber/h3/releases/tag/v4.5.0) [![version](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/uber/h3-py/blob/master/LICENSE) [![Tests](https://github.com/uber/h3-py/workflows/tests/badge.svg)](https://github.com/uber/h3-py/actions) -[![codecov](https://codecov.io/gh/uber/h3-py/branch/master/graph/badge.svg)](https://codecov.io/gh/uber/h3-py) +[![Coverage 100%](https://img.shields.io/badge/coverage-100%25-green.svg)](https://github.com/uber/h3-py/blob/master/.github/workflows/lint_and_coverage.yml#L31) + Python bindings for the [H3 core library](https://h3geo.org/). - Documentation: [uber.github.io/h3-py](https://uber.github.io/h3-py) - GitHub repo: [github.com/uber/h3-py](https://github.com/uber/h3-py) - ## Installation From [PyPI](https://pypi.org/project/h3/): @@ -41,7 +39,7 @@ conda install h3-py >>> import h3 >>> lat, lng = 37.769377, -122.388903 >>> resolution = 9 ->>> h3.geo_to_h3(lat, lng, resolution) +>>> h3.latlng_to_cell(lat, lng, resolution) '89283082e73ffff' ``` @@ -49,12 +47,12 @@ conda install h3-py ## APIs [api_comparison]: https://uber.github.io/h3-py/api_comparison -[api_reference]: https://uber.github.io/h3-py/api_reference +[api_quick]: https://uber.github.io/h3-py/api_quick We provide [multiple APIs][api_comparison] in `h3-py`. - All APIs have the same set of functions; - see the [API reference][api_reference]. + see the [API reference][api_quick]. - The APIs differ only in their input/output formats; see the [API comparison page][api_comparison]. @@ -93,5 +91,5 @@ Use `h3.versions()` to see the version numbers for both ```python >>> import h3 >>> h3.versions() -{'c': '3.6.3', 'python': '3.6.1'} +{'c': '4.1.0', 'python': '4.1.1'} ``` diff --git a/requirements.in b/requirements.in deleted file mode 100644 index 6412c77..0000000 --- a/requirements.in +++ /dev/null @@ -1,14 +0,0 @@ -# Required for pip-compile until -# https://github.com/jazzband/pip-tools/issues/1047 is resolved. -# -# In the meantime, this information is duplicated from -# pyproject.toml - -scikit-build -cython -cmake - -# for docs - -jupyter-book -flake8 diff --git a/setup.py b/setup.py deleted file mode 100644 index 23353b1..0000000 --- a/setup.py +++ /dev/null @@ -1,44 +0,0 @@ -import os -from setuptools import find_packages -from skbuild import setup - -here = os.path.abspath(os.path.dirname(__file__)) - -about = {} -with open(os.path.join(here, 'src', 'h3', '_version.py')) as f: - exec(f.read(), about) - - -def long_desc(): - here = os.path.abspath(os.path.dirname(__file__)) - fname = os.path.join(here, 'readme.md') - with open(fname) as f: - long_description = f.read() - - return long_description - - -setup( - name = 'h3', - version = about['__version__'], - description = about['__description__'], - long_description = long_desc(), - long_description_content_type = 'text/markdown', - license = about['__license__'], - author = about['__author__'], - author_email = about['__author_email__'], - url = about['__url__'], - classifiers = about['__classifiers__'], - include_package_data=True, - packages = find_packages( - 'src', - exclude = ["*.tests", "*.tests.*", "tests.*", "tests"], - ), - package_dir = {'': 'src'}, - cmake_languages = ('C'), - extras_require={ - 'numpy': ['numpy'], - 'test': ['pytest', 'pytest-cov', 'flake8', 'pylint'], - 'all': ['numpy', 'pytest', 'pytest-cov', 'flake8', 'pylint'], - }, -) diff --git a/src/h3/__init__.py b/src/h3/__init__.py index 717f9cb..1e4f4b8 100644 --- a/src/h3/__init__.py +++ b/src/h3/__init__.py @@ -3,14 +3,31 @@ from .api.basic_str import * from ._version import __version__ -#todo: remove in 4.0; only here for backward compatibility -from .api import basic_str as h3 - - from ._cy import ( + UnknownH3ErrorCode, + H3BaseException, + + H3GridNavigationError, + H3MemoryError, H3ValueError, - H3CellError, - H3ResolutionError, - H3EdgeError, - H3DistanceError, + + H3FailedError, + H3DomainError, + H3LatLngDomainError, + H3ResDomainError, + H3CellInvalidError, + H3DirEdgeInvalidError, + H3UndirEdgeInvalidError, + H3VertexInvalidError, + H3PentagonError, + H3DuplicateInputError, + H3NotNeighborsError, + H3ResMismatchError, + H3MemoryAllocError, + H3MemoryBoundsError, + H3OptionInvalidError, + H3IndexInvalidError, + H3BaseCellDomainError, + H3DigitDomainError, + H3DeletedDigitError, ) diff --git a/src/h3/_cy/CMakeLists.txt b/src/h3/_cy/CMakeLists.txt index 0d7e78c..2cb2b6f 100644 --- a/src/h3/_cy/CMakeLists.txt +++ b/src/h3/_cy/CMakeLists.txt @@ -1,28 +1,35 @@ -find_package(Cython MODULE REQUIRED) -find_package(PythonExtensions MODULE REQUIRED) +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -# Build Cython annotations -set(CYTHON_ANNOTATE TRUE) - macro(add_cython_file filename) - add_cython_target(${filename} C PY3) - add_library(${filename} MODULE ${filename} ${LIB_SOURCE_FILES} ${CONFIGURED_API_HEADER}) - python_extension_module(${filename}) + add_custom_command( + OUTPUT "${filename}.c" + COMMENT + "Making ${CMAKE_CURRENT_BINARY_DIR}/${filename}.c from ${CMAKE_CURRENT_SOURCE_DIR}/${filename}.pyx" + COMMAND Python::Interpreter -m cython + "${CMAKE_CURRENT_SOURCE_DIR}/${filename}.pyx" --output-file "${filename}.c" -I ${CMAKE_CURRENT_SOURCE_DIR} + DEPENDS "${filename}.pyx" + VERBATIM) + + python_add_library(${filename} MODULE "${filename}.c" WITH_SOABI) + set_property(TARGET ${filename} PROPERTY C_STANDARD 99) - target_link_libraries(${filename} h3) - install(TARGETS ${filename} LIBRARY DESTINATION src/h3/_cy) + target_link_libraries(${filename} PRIVATE h3) + install(TARGETS ${filename} LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}/_cy) endmacro() # GLOB pattern is recommended against # https://cmake.org/cmake/help/v3.14/command/file.html?highlight=file#filesystem -add_cython_file(util) -add_cython_file(geo) add_cython_file(cells) add_cython_file(edges) +add_cython_file(error_system) +add_cython_file(latlng) +add_cython_file(memory) +add_cython_file(vertex) + add_cython_file(to_multipoly) -add_cython_file(unstable_vect) +add_cython_file(util) # Include pyx and pxd files in distribution for use by Cython API install( @@ -31,11 +38,16 @@ install( cells.pyx edges.pxd edges.pyx - geo.pxd - geo.pyx + error_system.pyx h3lib.pxd + latlng.pxd + latlng.pyx + memory.pxd + memory.pyx util.pxd util.pyx + vertex.pxd + vertex.pyx DESTINATION - src/h3/_cy + ${SKBUILD_PROJECT_NAME}/_cy ) diff --git a/src/h3/_cy/__init__.py b/src/h3/_cy/__init__.py index bb4dfc0..70fa087 100644 --- a/src/h3/_cy/__init__.py +++ b/src/h3/_cy/__init__.py @@ -14,65 +14,109 @@ function interface and input conversion (string to int, for instance). """ from .cells import ( - is_cell, + is_valid_index, + is_valid_cell, is_pentagon, - get_base_cell, - resolution, - parent, - distance, - disk, - ring, - children, - compact, - uncompact, - num_hexagons, - mean_hex_area, + get_base_cell_number, + get_resolution, + get_index_digit, + construct_cell, + cell_to_parent, + grid_distance, + grid_disk, + grid_ring, + cell_to_children_size, + cell_to_children, + cell_to_child_pos, + child_pos_to_cell, + compact_cells, + uncompact_cells, + get_num_cells, + average_hexagon_area, cell_area, - line, + grid_path_cells, is_res_class_iii, - get_pentagon_indexes, - get_res0_indexes, - center_child, - get_faces, - experimental_h3_to_local_ij, - experimental_local_ij_to_h3, + get_pentagons, + get_res0_cells, + cell_to_center_child, + get_icosahedron_faces, + cell_to_local_ij, + local_ij_to_cell, ) from .edges import ( - are_neighbors, - edge, - is_edge, - edge_origin, - edge_destination, - edge_cells, - edges_from_cell, - mean_edge_length, + are_neighbor_cells, + cells_to_directed_edge, + is_valid_directed_edge, + get_directed_edge_origin, + get_directed_edge_destination, + directed_edge_to_cells, + origin_to_directed_edges, + average_hexagon_edge_length, edge_length, ) -from .geo import ( - geo_to_h3, - h3_to_geo, - polyfill_polygon, - polyfill_geojson, - polyfill, - cell_boundary, - edge_boundary, - point_dist, +from .latlng import ( + latlng_to_cell, + cell_to_latlng, + polygon_to_cells, + polygons_to_cells, + polygon_to_cells_experimental, + polygons_to_cells_experimental, + cell_to_boundary, + directed_edge_to_boundary, + great_circle_distance, +) + +from .vertex import ( + cell_to_vertex, + cell_to_vertexes, + vertex_to_latlng, + is_valid_vertex, ) from .to_multipoly import ( - h3_set_to_multi_polygon + cells_to_multi_polygon ) from .util import ( c_version, - hex2int, - int2hex, - from_iter, + str_to_int, + int_to_str, +) + +from .memory import ( + iter_to_mv, +) + +from .error_system import ( + UnknownH3ErrorCode, + H3BaseException, + + H3GridNavigationError, + H3MemoryError, H3ValueError, - H3CellError, - H3ResolutionError, - H3EdgeError, - H3DistanceError, + + H3FailedError, + H3DomainError, + H3LatLngDomainError, + H3ResDomainError, + H3CellInvalidError, + H3DirEdgeInvalidError, + H3UndirEdgeInvalidError, + H3VertexInvalidError, + H3PentagonError, + H3DuplicateInputError, + H3NotNeighborsError, + H3ResMismatchError, + H3MemoryAllocError, + H3MemoryBoundsError, + H3OptionInvalidError, + H3IndexInvalidError, + H3BaseCellDomainError, + H3DigitDomainError, + H3DeletedDigitError, + + get_H3_ERROR_END, + error_code_to_exception, ) diff --git a/src/h3/_cy/cells.pxd b/src/h3/_cy/cells.pxd index 1071938..1bc31b8 100644 --- a/src/h3/_cy/cells.pxd +++ b/src/h3/_cy/cells.pxd @@ -1,25 +1,30 @@ from .h3lib cimport bool, int64_t, H3int -cpdef bool is_cell(H3int h) +cpdef bool is_valid_index(H3int h) +cpdef bool is_valid_cell(H3int h) cpdef bool is_pentagon(H3int h) -cpdef int get_base_cell(H3int h) except -1 -cpdef int resolution(H3int h) except -1 -cpdef int distance(H3int h1, H3int h2) except -1 -cpdef H3int[:] disk(H3int h, int k) -cpdef H3int[:] _ring_fallback(H3int h, int k) -cpdef H3int[:] ring(H3int h, int k) -cpdef H3int parent(H3int h, res=*) except 0 -cpdef H3int[:] children(H3int h, res=*) -cpdef H3int center_child(H3int h, res=*) except 0 -cpdef H3int[:] compact(const H3int[:] hu) -cpdef H3int[:] uncompact(const H3int[:] hc, int res) -cpdef int64_t num_hexagons(int resolution) except -1 -cpdef double mean_hex_area(int resolution, unit=*) except -1 +cpdef int get_base_cell_number(H3int h) except -1 +cpdef int get_resolution(H3int h) except -1 +cpdef int get_index_digit(H3int h, int res) except -1 +cpdef H3int construct_cell(int baseCellNumber, const int[:] digits) except 0 +cpdef int grid_distance(H3int h1, H3int h2) except -1 +cpdef H3int[:] grid_disk(H3int h, int k) +cpdef H3int[:] grid_ring(H3int h, int k) +cpdef H3int cell_to_parent(H3int h, res=*) except 0 +cpdef int64_t cell_to_children_size(H3int h, res=*) except -1 +cpdef H3int[:] cell_to_children(H3int h, res=*) +cpdef H3int cell_to_center_child(H3int h, res=*) except 0 +cpdef int64_t cell_to_child_pos(H3int child, int parent_res) except -1 +cpdef H3int child_pos_to_cell(H3int parent, int child_res, int64_t child_pos) except 0 +cpdef H3int[:] compact_cells(const H3int[:] hu) +cpdef H3int[:] uncompact_cells(const H3int[:] hc, int res) +cpdef int64_t get_num_cells(int resolution) except -1 +cpdef double average_hexagon_area(int resolution, unit=*) except -1 cpdef double cell_area(H3int h, unit=*) except -1 -cpdef H3int[:] line(H3int start, H3int end) +cpdef H3int[:] grid_path_cells(H3int start, H3int end) cpdef bool is_res_class_iii(H3int h) -cpdef H3int[:] get_pentagon_indexes(int res) -cpdef H3int[:] get_res0_indexes() -cpdef get_faces(H3int h) -cpdef (int, int) experimental_h3_to_local_ij(H3int origin, H3int h) except * -cpdef H3int experimental_local_ij_to_h3(H3int origin, int i, int j) except 0 +cpdef H3int[:] get_pentagons(int res) +cpdef H3int[:] get_res0_cells() +cpdef get_icosahedron_faces(H3int h) +cpdef (int, int) cell_to_local_ij(H3int origin, H3int h) except * +cpdef H3int local_ij_to_cell(H3int origin, int i, int j) except 0 diff --git a/src/h3/_cy/cells.pyx b/src/h3/_cy/cells.pyx index 4206b81..f0667e5 100644 --- a/src/h3/_cy/cells.pyx +++ b/src/h3/_cy/cells.pyx @@ -1,112 +1,132 @@ +# cython: freethreading_compatible=True cimport h3lib -from .h3lib cimport bool, int64_t, H3int -from libc cimport stdlib +from .h3lib cimport bool, int64_t, H3int, H3ErrorCodes from .util cimport ( check_cell, - check_res, + check_index, check_distance, - create_ptr, - create_mv, - empty_memory_view, # want to drop this import if possible ) -from .util import H3ValueError, H3ResolutionError +from .util import EARTH_RADIUS_KM + +from .error_system cimport ( + H3Error, + check_for_error, + check_for_error_msg, +) + +from .memory cimport ( + H3MemoryManager, + int_mv, +) # todo: add notes about Cython exception handling +cpdef bool is_valid_index(H3int h): + """Validates an H3 index (cell, vertex, or directed edge). + + Returns + ------- + boolean + """ + return h3lib.isValidIndex(h) == 1 # bool is a python type, so we don't need the except clause -cpdef bool is_cell(H3int h): +cpdef bool is_valid_cell(H3int h): """Validates an H3 cell (hexagon or pentagon) Returns ------- boolean """ - return h3lib.h3IsValid(h) == 1 + return h3lib.isValidCell(h) == 1 + cpdef bool is_pentagon(H3int h): - return h3lib.h3IsPentagon(h) == 1 + return h3lib.isPentagon(h) == 1 -cpdef int get_base_cell(H3int h) except -1: + +cpdef int get_base_cell_number(H3int h) except -1: check_cell(h) - return h3lib.h3GetBaseCell(h) + return h3lib.getBaseCellNumber(h) -cpdef int resolution(H3int h) except -1: +cpdef int get_resolution(H3int h) except -1: """Returns the resolution of an H3 Index 0--15 """ check_cell(h) - return h3lib.h3GetResolution(h) + return h3lib.getResolution(h) + +cpdef int get_index_digit(H3int h, int res) except -1: + cdef: + int digit + + check_index(h) + + check_for_error( + h3lib.getIndexDigit(h, res, &digit) + ) + + return digit + +cpdef H3int construct_cell(int base_cell_number, const int[:] digits) except 0: + cdef: + H3int out + int res = len(digits) + H3Error err + + if res > 0: + err = h3lib.constructCell(res, base_cell_number, &digits[0], &out) + else: + err = h3lib.constructCell(res, base_cell_number, NULL, &out) + + check_for_error(err) + + return out -cpdef int distance(H3int h1, H3int h2) except -1: - """ compute the hex-distance between two hexagons +cpdef int grid_distance(H3int h1, H3int h2) except -1: + """ Compute the grid distance between two cells """ + cdef: + int64_t distance + check_cell(h1) check_cell(h2) - d = h3lib.h3Distance(h1,h2) + check_for_error( + h3lib.gridDistance(h1, h2, &distance) + ) - if d < 0: - s = 'Cells are too far apart to compute distance: {} and {}' - s = s.format(hex(h1), hex(h2)) - raise H3ValueError(s) + return distance - return d - -cpdef H3int[:] disk(H3int h, int k): +cpdef H3int[:] grid_disk(H3int h, int k): """ Return cells at grid distance `<= k` from `h`. """ + cdef: + int64_t n + check_cell(h) check_distance(k) - n = h3lib.maxKringSize(k) + check_for_error( + h3lib.maxGridDiskSize(k, &n) + ) - ptr = create_ptr(n) # todo: return a "smart" pointer that knows its length? - h3lib.kRing(h, k, ptr) - mv = create_mv(ptr, n) + hmm = H3MemoryManager(n) + check_for_error( + h3lib.gridDisk(h, k, hmm.ptr) + ) + mv = hmm.to_mv() return mv -cpdef H3int[:] _ring_fallback(H3int h, int k): - """ - `ring` tries to call `h3lib.hexRing` first; if that fails, we call - this function, which relies on `h3lib.kRingDistances`. - - Failures for `h3lib.hexRing` happen when the algortihm runs into a pentagon. - """ - check_cell(h) - check_distance(k) - - n = h3lib.maxKringSize(k) - # array of h3 cells - ptr = create_ptr(n) - - # array of cell distances from `h` - dist_ptr = stdlib.calloc(n, sizeof(int)) - if dist_ptr is NULL: - raise MemoryError() - - h3lib.kRingDistances(h, k, ptr, dist_ptr) - - distances = dist_ptr - distances.callback_free_data = stdlib.free - - for i,v in enumerate(distances): - if v != k: - ptr[i] = 0 - - mv = create_mv(ptr, n) - - return mv - -cpdef H3int[:] ring(H3int h, int k): +cpdef H3int[:] grid_ring(H3int h, int k): """ Return cells at grid distance `== k` from `h`. Collection is "hollow" for k >= 1. """ @@ -114,262 +134,326 @@ cpdef H3int[:] ring(H3int h, int k): check_distance(k) n = 6*k if k > 0 else 1 - ptr = create_ptr(n) - - flag = h3lib.hexRing(h, k, ptr) - - # if we drop into the failure state, we might be tempted to not create - # this mv, but creating the mv is exactly what guarantees that we'll free - # the memory. context manager would be better here, if we can figure out - # how to do that - mv = create_mv(ptr, n) - - if flag != 0: - mv = _ring_fallback(h, k) + hmm = H3MemoryManager(n) + check_for_error( + h3lib.gridRing(h, k, hmm.ptr) + ) + mv = hmm.to_mv() return mv -cpdef H3int parent(H3int h, res=None) except 0: - check_cell(h) +cpdef H3int cell_to_parent(H3int h, res=None) except 0: + cdef: + H3int parent + check_cell(h) if res is None: - res = resolution(h) - 1 - if res > resolution(h): + res = get_resolution(h) - 1 + + err = h3lib.cellToParent(h, res, &parent) + if err: msg = 'Invalid parent resolution {} for cell {}.' msg = msg.format(res, hex(h)) - raise H3ResolutionError(msg) + check_for_error_msg(err, msg) - check_res(res) + return parent - return h3lib.h3ToParent(h, res) -cpdef H3int[:] children(H3int h, res=None): +cpdef int64_t cell_to_children_size(H3int h, res=None) except -1: + cdef: + int64_t n + check_cell(h) - if res is None: - res = resolution(h) + 1 - if res < resolution(h): + res = get_resolution(h) + 1 + + err = h3lib.cellToChildrenSize(h, res, &n) + if err: msg = 'Invalid child resolution {} for cell {}.' msg = msg.format(res, hex(h)) - raise H3ResolutionError(msg) + check_for_error_msg(err, msg) - check_res(res) + return n - n = h3lib.maxH3ToChildrenSize(h, res) - ptr = create_ptr(n) - h3lib.h3ToChildren(h, res, ptr) - mv = create_mv(ptr, n) +cpdef H3int[:] cell_to_children(H3int h, res=None): + check_cell(h) + if res is None: + res = get_resolution(h) + 1 + + n = cell_to_children_size(h, res) + + hmm = H3MemoryManager(n) + check_for_error( + h3lib.cellToChildren(h, res, hmm.ptr) + ) + mv = hmm.to_mv() return mv -cpdef H3int center_child(H3int h, res=None) except 0: - check_cell(h) + +cpdef H3int cell_to_center_child(H3int h, res=None) except 0: + cdef: + H3int child + + check_cell(h) if res is None: - res = resolution(h) + 1 - if res < resolution(h): + res = get_resolution(h) + 1 + + err = h3lib.cellToCenterChild(h, res, &child) + if err: msg = 'Invalid child resolution {} for cell {}.' msg = msg.format(res, hex(h)) - raise H3ResolutionError(msg) + check_for_error_msg(err, msg) - check_res(res) - - return h3lib.h3ToCenterChild(h, res) + return child +cpdef int64_t cell_to_child_pos(H3int child, int parent_res) except -1: + cdef: + int64_t child_pos -cpdef H3int[:] compact(const H3int[:] hu): + check_cell(child) + err = h3lib.cellToChildPos(child, parent_res, &child_pos) + if err: + msg = "Couldn't find child pos of cell {} at res {}." + msg = msg.format(hex(child), parent_res) + check_for_error_msg(err, msg) + + return child_pos + + +cpdef H3int child_pos_to_cell(H3int parent, int child_res, int64_t child_pos) except 0: + cdef: + H3int child + + check_cell(parent) + err = h3lib.childPosToCell(child_pos, parent, child_res, &child) + if err: + msg = "Couldn't find child with pos {} at res {} from parent {}." + msg = msg.format(child_pos, child_res, hex(parent)) + check_for_error_msg(err, msg) + + return child + + +cpdef H3int[:] compact_cells(const H3int[:] hu): + # todo: fix this with my own Cython object "wrapper" class? + # everything has a .ptr interface? # todo: the Clib can handle 0-len arrays because it **avoids** # dereferencing the pointer, but Cython's syntax of # `&hu[0]` **requires** a dereference. For Cython, checking for array # length of zero and returning early seems like the easiest solution. # note: open to better ideas! + if len(hu) == 0: - return empty_memory_view() + return H3MemoryManager(0).to_mv() for h in hu: ## todo: should we have an array version? would that be faster? check_cell(h) - ptr = create_ptr(len(hu)) - flag = h3lib.compact(&hu[0], ptr, len(hu)) - mv = create_mv(ptr, len(hu)) - - if flag != 0: - raise H3ValueError('Could not compact set of hexagons!') + cdef size_t n = len(hu) + hmm = H3MemoryManager(n) + check_for_error( + h3lib.compactCells(&hu[0], hmm.ptr, n) + ) + mv = hmm.to_mv() return mv + # todo: https://stackoverflow.com/questions/50684977/cython-exception-type-for-a-function-returning-a-typed-memoryview # apparently, memoryviews are python objects, so we don't need to do the except clause -cpdef H3int[:] uncompact(const H3int[:] hc, int res): +cpdef H3int[:] uncompact_cells(const H3int[:] hc, int res): # todo: the Clib can handle 0-len arrays because it **avoids** # dereferencing the pointer, but Cython's syntax of # `&hc[0]` **requires** a dereference. For Cython, checking for array # length of zero and returning early seems like the easiest solution. # note: open to better ideas! + cdef: + int64_t n + + if len(hc) == 0: - return empty_memory_view() + return H3MemoryManager(0).to_mv() for h in hc: check_cell(h) - N = h3lib.maxUncompactSize(&hc[0], len(hc), res) - - ptr = create_ptr(N) - flag = h3lib.uncompact( - &hc[0], len(hc), - ptr, N, - res + check_for_error( + h3lib.uncompactCellsSize(&hc[0], len(hc), res, &n) ) - mv = create_mv(ptr, N) - if flag != 0: - raise H3ValueError('Could not uncompact set of hexagons!') + hmm = H3MemoryManager(n) + check_for_error( + h3lib.uncompactCells( + &hc[0], # todo: symmetry here with the wrapper object might be nice. hc.ptr / hc.n + len(hc), + hmm.ptr, + hmm.n, + res + ) + ) + + mv = hmm.to_mv() return mv -cpdef int64_t num_hexagons(int resolution) except -1: - check_res(resolution) +cpdef int64_t get_num_cells(int resolution) except -1: + cdef: + int64_t num_cells - return h3lib.numHexagons(resolution) + check_for_error( + h3lib.getNumCells(resolution, &num_cells) + ) + + return num_cells -cpdef double mean_hex_area(int resolution, unit='km^2') except -1: - check_res(resolution) +cpdef double average_hexagon_area(int resolution, unit='km^2') except -1: + cdef: + double area - area = h3lib.hexAreaKm2(resolution) + check_for_error( + h3lib.getHexagonAreaAvgKm2(resolution, &area) + ) # todo: multiple units convert = { 'km^2': 1.0, - 'm^2': 1000*1000.0 + 'm^2': 1000*1000.0, + 'rads^2': 1.0/(EARTH_RADIUS_KM*EARTH_RADIUS_KM), } try: area *= convert[unit] except: - raise H3ValueError('Unknown unit: {}'.format(unit)) + raise ValueError('Unknown unit: {}'.format(unit)) return area cpdef double cell_area(H3int h, unit='km^2') except -1: - check_cell(h) + cdef: + double area if unit == 'rads^2': - area = h3lib.cellAreaRads2(h) + err = h3lib.cellAreaRads2(h, &area) elif unit == 'km^2': - area = h3lib.cellAreaKm2(h) + err = h3lib.cellAreaKm2(h, &area) elif unit == 'm^2': - area = h3lib.cellAreaM2(h) + err = h3lib.cellAreaM2(h, &area) else: - raise H3ValueError('Unknown unit: {}'.format(unit)) + raise ValueError('Unknown unit: {}'.format(unit)) + + check_for_error(err) return area -cpdef H3int[:] line(H3int start, H3int end): - check_cell(start) - check_cell(end) +cdef _could_not_find_line(err, start, end): + msg = "Couldn't find line between cells {} and {}" + msg = msg.format(hex(start), hex(end)) - n = h3lib.h3LineSize(start, end) + check_for_error_msg(err, msg) - if n < 0: - s = "Couldn't find line between cells {} and {}" - s = s.format(hex(start), hex(end)) - raise H3ValueError(s) +cpdef H3int[:] grid_path_cells(H3int start, H3int end): + cdef: + int64_t n - ptr = create_ptr(n) - flag = h3lib.h3Line(start, end, ptr) - mv = create_mv(ptr, n) + # todo: can we segfault here with invalid inputs? + # Can we trust the c library to validate the start/end cells? + # probably applies to all size/work pairs of functions... + err = h3lib.gridPathCellsSize(start, end, &n) - if flag != 0: - s = "Couldn't find line between cells {} and {}" - s = s.format(hex(start), hex(end)) - raise H3ValueError(s) + _could_not_find_line(err, start, end) + + hmm = H3MemoryManager(n) + err = h3lib.gridPathCells(start, end, hmm.ptr) + + _could_not_find_line(err, start, end) + + # todo: probably here too? + mv = hmm.to_mv() return mv cpdef bool is_res_class_iii(H3int h): - return h3lib.h3IsResClassIII(h) == 1 + return h3lib.isResClassIII(h) == 1 -cpdef H3int[:] get_pentagon_indexes(int res): - check_res(res) +cpdef H3int[:] get_pentagons(int res): + n = h3lib.pentagonCount() - n = h3lib.pentagonIndexCount() - - ptr = create_ptr(n) - h3lib.getPentagonIndexes(res, ptr) - mv = create_mv(ptr, n) + hmm = H3MemoryManager(n) + check_for_error( + h3lib.getPentagons(res, hmm.ptr) + ) + mv = hmm.to_mv() return mv -cpdef H3int[:] get_res0_indexes(): - n = h3lib.res0IndexCount() +cpdef H3int[:] get_res0_cells(): + n = h3lib.res0CellCount() - ptr = create_ptr(n) - h3lib.getRes0Indexes(ptr) - mv = create_mv(ptr, n) + hmm = H3MemoryManager(n) + check_for_error( + h3lib.getRes0Cells(hmm.ptr) + ) + mv = hmm.to_mv() return mv +# oh, this is returning a set?? +# todo: convert to int[:]? +cpdef get_icosahedron_faces(H3int h): + cdef: + int n + int[:] faces ## todo: weird, this needs to be specified to avoid errors. cython bug? -cpdef get_faces(H3int h): - check_cell(h) + check_for_error( + h3lib.maxFaceCount(h, &n) + ) - n = h3lib.maxFaceCount(h) + faces = int_mv(n) + check_for_error( + h3lib.getIcosahedronFaces(h, &faces[0]) + ) - cdef int* ptr = stdlib.calloc(n, sizeof(int)) - if (n > 0) and (not ptr): - raise MemoryError() + # todo: wait? do faces start from 0 or 1? + # we could do this check/processing in the int_mv object + out = [f for f in faces if f >= 0] - h3lib.h3GetFaces(h, ptr) + return out - faces = ptr - faces = {f for f in faces if f >= 0} - stdlib.free(ptr) - return faces - - -cpdef (int, int) experimental_h3_to_local_ij(H3int origin, H3int h) except *: +cpdef (int, int) cell_to_local_ij(H3int origin, H3int h) except *: cdef: - int flag h3lib.CoordIJ c - check_cell(origin) - check_cell(h) - - flag = h3lib.experimentalH3ToLocalIj(origin, h, &c) - - if flag != 0: - s = "Couldn't find local (i,j) between cells {} and {}." - s = s.format(hex(origin), hex(h)) - raise H3ValueError(s) + err = h3lib.cellToLocalIj(origin, h, 0, &c) + if err: + msg = "Couldn't find local (i,j) between cells {} and {}." + msg = msg.format(hex(origin), hex(h)) + check_for_error_msg(err, msg) return c.i, c.j - -cpdef H3int experimental_local_ij_to_h3(H3int origin, int i, int j) except 0: +cpdef H3int local_ij_to_cell(H3int origin, int i, int j) except 0: cdef: - int flag h3lib.CoordIJ c H3int out - check_cell(origin) - c.i, c.j = i, j - flag = h3lib.experimentalLocalIjToH3(origin, &c, &out) - - if flag != 0: - s = "Couldn't find cell at local ({},{}) from cell {}." - s = s.format(i, j, hex(origin)) - raise H3ValueError(s) + err = h3lib.localIjToCell(origin, &c, 0, &out) + if err: + msg = "Couldn't find cell at local ({},{}) from cell {}." + msg = msg.format(i, j, hex(origin)) + check_for_error_msg(err, msg) return out diff --git a/src/h3/_cy/edges.pxd b/src/h3/_cy/edges.pxd index 465b82d..b7fcf84 100644 --- a/src/h3/_cy/edges.pxd +++ b/src/h3/_cy/edges.pxd @@ -1,11 +1,11 @@ from .h3lib cimport bool, H3int -cpdef bool are_neighbors(H3int h1, H3int h2) -cpdef H3int edge(H3int origin, H3int destination) except 1 -cpdef bool is_edge(H3int e) -cpdef H3int edge_origin(H3int e) except 1 -cpdef H3int edge_destination(H3int e) except 1 -cpdef (H3int, H3int) edge_cells(H3int e) except * -cpdef H3int[:] edges_from_cell(H3int origin) -cpdef double mean_edge_length(int resolution, unit=*) except -1 +cpdef bool are_neighbor_cells(H3int h1, H3int h2) +cpdef H3int cells_to_directed_edge(H3int origin, H3int destination) except * +cpdef bool is_valid_directed_edge(H3int e) +cpdef H3int get_directed_edge_origin(H3int e) except 1 +cpdef H3int get_directed_edge_destination(H3int e) except 1 +cpdef (H3int, H3int) directed_edge_to_cells(H3int e) except * +cpdef H3int[:] origin_to_directed_edges(H3int origin) +cpdef double average_hexagon_edge_length(int resolution, unit=*) except -1 cpdef double edge_length(H3int e, unit=*) except -1 diff --git a/src/h3/_cy/edges.pyx b/src/h3/_cy/edges.pyx index 6560006..7364bd5 100644 --- a/src/h3/_cy/edges.pyx +++ b/src/h3/_cy/edges.pyx @@ -1,100 +1,118 @@ +# cython: freethreading_compatible=True cimport h3lib from .h3lib cimport bool, H3int -from .util cimport ( - check_cell, - check_edge, - check_res, - create_ptr, - create_mv, -) +from .error_system cimport check_for_error -from .util import H3ValueError +from .util import EARTH_RADIUS_KM -cpdef bool are_neighbors(H3int h1, H3int h2): - check_cell(h1) - check_cell(h2) +from .memory cimport H3MemoryManager - return h3lib.h3IndexesAreNeighbors(h1, h2) == 1 +# todo: make bint +cpdef bool are_neighbor_cells(H3int h1, H3int h2): + cdef: + int out + + err = h3lib.areNeighborCells(h1, h2, &out) + + # note: we are intentionally not raising an error here, and just + # returning false. + # todo: is this choice consistent across the Python and C libs? + if err: + return False + + return out == 1 -cpdef H3int edge(H3int origin, H3int destination) except 1: - check_cell(origin) - check_cell(destination) +cpdef H3int cells_to_directed_edge(H3int origin, H3int destination) except *: + cdef: + int neighbor_out + H3int out - if h3lib.h3IndexesAreNeighbors(origin, destination) != 1: - s = 'Cells are not neighbors: {} and {}' - s = s.format(hex(origin), hex(destination)) - raise H3ValueError(s) + check_for_error( + h3lib.cellsToDirectedEdge(origin, destination, &out) + ) - return h3lib.getH3UnidirectionalEdge(origin, destination) + return out -cpdef bool is_edge(H3int e): - return h3lib.h3UnidirectionalEdgeIsValid(e) == 1 +cpdef bool is_valid_directed_edge(H3int e): + return h3lib.isValidDirectedEdge(e) == 1 -cpdef H3int edge_origin(H3int e) except 1: - # without the check, with an invalid input, the function will just return 0 - check_edge(e) +cpdef H3int get_directed_edge_origin(H3int e) except 1: + cdef: + H3int out - return h3lib.getOriginH3IndexFromUnidirectionalEdge(e) + check_for_error( + h3lib.getDirectedEdgeOrigin(e, &out) + ) -cpdef H3int edge_destination(H3int e) except 1: - check_edge(e) + return out - return h3lib.getDestinationH3IndexFromUnidirectionalEdge(e) +cpdef H3int get_directed_edge_destination(H3int e) except 1: + cdef: + H3int out -cpdef (H3int, H3int) edge_cells(H3int e) except *: - check_edge(e) + check_for_error( + h3lib.getDirectedEdgeDestination(e, &out) + ) - return edge_origin(e), edge_destination(e) + return out -cpdef H3int[:] edges_from_cell(H3int origin): +cpdef (H3int, H3int) directed_edge_to_cells(H3int e) except *: + # todo: use directed_edge_to_cells in h3lib + return get_directed_edge_origin(e), get_directed_edge_destination(e) + +cpdef H3int[:] origin_to_directed_edges(H3int origin): """ Returns the 6 (or 5 for pentagons) directed edges for the given origin cell """ - check_cell(origin) - ptr = create_ptr(6) - h3lib.getH3UnidirectionalEdgesFromHexagon(origin, ptr) - mv = create_mv(ptr, 6) + hmm = H3MemoryManager(6) + check_for_error( + h3lib.originToDirectedEdges(origin, hmm.ptr) + ) + mv = hmm.to_mv() return mv -cpdef double mean_edge_length(int resolution, unit='km') except -1: - check_res(resolution) +cpdef double average_hexagon_edge_length(int resolution, unit='km') except -1: + cdef: + double length - length = h3lib.edgeLengthKm(resolution) + check_for_error( + h3lib.getHexagonEdgeLengthAvgKm(resolution, &length) + ) # todo: multiple units convert = { 'km': 1.0, - 'm': 1000.0 + 'm': 1000.0, + 'rads': 1.0/EARTH_RADIUS_KM, } try: length *= convert[unit] except: - raise H3ValueError('Unknown unit: {}'.format(unit)) + raise ValueError('Unknown unit: {}'.format(unit)) return length cpdef double edge_length(H3int e, unit='km') except -1: - check_edge(e) - - # todo: maybe kick this logic up to the python level - # it might be a little cleaner, because we can do the "switch statement" - # with a dict, but would require exposing more C functions + cdef: + double length if unit == 'rads': - length = h3lib.exactEdgeLengthRads(e) + err = h3lib.edgeLengthRads(e, &length) elif unit == 'km': - length = h3lib.exactEdgeLengthKm(e) + err = h3lib.edgeLengthKm(e, &length) elif unit == 'm': - length = h3lib.exactEdgeLengthM(e) + err = h3lib.edgeLengthM(e, &length) else: - raise H3ValueError('Unknown unit: {}'.format(unit)) + raise ValueError('Unknown unit: {}'.format(unit)) + + check_for_error(err) return length diff --git a/src/h3/_cy/error_system.pxd b/src/h3/_cy/error_system.pxd new file mode 100644 index 0000000..4a1e3b4 --- /dev/null +++ b/src/h3/_cy/error_system.pxd @@ -0,0 +1,6 @@ +from .h3lib cimport H3Error + +cpdef error_code_to_exception(H3Error err) +cdef check_for_error(H3Error err) +cdef check_for_error_msg(H3Error err, str msg) +cpdef H3Error get_H3_ERROR_END() diff --git a/src/h3/_cy/error_system.pyx b/src/h3/_cy/error_system.pyx new file mode 100644 index 0000000..5fe5cd9 --- /dev/null +++ b/src/h3/_cy/error_system.pyx @@ -0,0 +1,261 @@ +# cython: freethreading_compatible=True +""" +Exceptions from the h3-py library have three possible sources: + +- the Python code +- the Cython code +- the underlying H3 C library code + +The Python and Cython `h3-py` code will only raise standard Python +built-in exceptions; **no custom** exception classes will be used. + +Conversely, many functions in the H3 C library return a `uint32_t` +error code (aliased as type `H3Error`). +When these errors happen (and `h3-py` can't recover from them internally), +they are passed up to the Python/Cython code, where their +`uint32_t` error values are converted to **custom** Python exception types. +These custom exception classes all inherit from `H3BaseException`. + +There is a 1-1 correspondence between the concrete subclasses of +`H3BaseException` and the H3 C library `H3ErrorCodes` values. +The correspondence is intentional, so that the user can refer to the +H3 C library documentation on these errors. + +The (`uint32_t` <-> Exception) correspondence should be clear from +the names of each error/exception, but the explicit mapping is given by +a dictionary in the code below. + +Note that some "abstract" subclasses of `H3BaseException` are also included to +group the exceptions by type. (We say "abstract" because Python has no easy +way to make true abstract exception classes.) + +These "abstract" exceptions will never be raised directly by `h3-py`, but they +allow the user to catch general groups of errors. +Note that `h3-py` will only ever directly raise +the "concrete" exception classes. + +Summarizing, all exceptions originating from the C library inherit from +`H3BaseException`, which has both "abstract" and "concrete" subclasses. + +**Abstract classes**: + +- H3BaseException +- H3ValueError +- H3MemoryError +- H3GridNavigationError + +**Concrete classes**: + +- H3FailedError +- H3DomainError +- H3LatLngDomainError +- H3ResDomainError +- H3CellInvalidError +- H3DirEdgeInvalidError +- H3UndirEdgeInvalidError +- H3VertexInvalidError +- H3PentagonError +- H3DuplicateInputError +- H3NotNeighborsError +- H3ResMismatchError +- H3MemoryAllocError +- H3MemoryBoundsError +- H3OptionInvalidError +- H3IndexInvalidError +- H3BaseCellDomainError +- H3DigitDomainError +- H3DeletedDigitError + + +# TODO: add tests verifying that concrete exception classes have the right error codes associated with them +""" + +from contextlib import contextmanager + +from .h3lib cimport ( + H3Error, + + # H3ErrorCodes enum values + E_SUCCESS, + E_FAILED, + E_DOMAIN, + E_LATLNG_DOMAIN, + E_RES_DOMAIN, + E_CELL_INVALID, + E_DIR_EDGE_INVALID, + E_UNDIR_EDGE_INVALID, + E_VERTEX_INVALID, + E_PENTAGON, + E_DUPLICATE_INPUT, + E_NOT_NEIGHBORS, + E_RES_MISMATCH, + E_MEMORY_ALLOC, + E_MEMORY_BOUNDS, + E_OPTION_INVALID, + E_INDEX_INVALID, + E_BASE_CELL_DOMAIN, + E_DIGIT_DOMAIN, + E_DELETED_DIGIT, + H3_ERROR_END # sentinel value +) + +@contextmanager +def _the_error(obj): + """ + Syntactic maple syrup for grouping exception definitions. + The associated `with` statement ends up as a not-half-bad + approximation to a valid sentence fragment. + + This provides sort of a "pretend scope", in that it allows for + block indentation which helps to visually indicate the "scope" + of the `... as e` statement. Just note that Python doesn't treat the + `with` block as a "true" separate scope. + + Note that this doesn't actually do anything context-manager-y, outside + of the variable assignment and block indentation. + """ + yield obj + + +# +# Base exception for C library error codes +# +class H3BaseException(Exception): + """ Base H3 exception class. + + Concrete subclasses of this class correspond to specific + error codes from the C library. + + Base/abstract subclasses will have `h3_error_code = None`, while + concrete subclasses will have `h3_error_code` equal to their associated + C library error code. + """ + h3_error_code = None + + +# +# A few "abstract" exceptions; organizational. +# +with _the_error(H3BaseException) as e: + class H3ValueError(e, ValueError): ... + class H3MemoryError(e, MemoryError): ... + class H3GridNavigationError(e, RuntimeError): ... + + +# +# Concrete exceptions +# +class UnknownH3ErrorCode(H3BaseException): + """ + Indicates that the h3-py Python bindings have received an + unrecognized error code from the C library. + + This should never happen. Please report if you get this error. + + Note that this exception is *outside* of the + H3BaseException class hierarchy. + """ + pass + +with _the_error(H3BaseException) as e: + class H3FailedError(e): ... + +with _the_error(H3GridNavigationError) as e: + class H3PentagonError(e): ... + +with _the_error(H3MemoryError) as e: + class H3MemoryAllocError(e): ... + class H3MemoryBoundsError(e): ... + +with _the_error(H3ValueError) as e: + class H3DomainError(e): ... + class H3LatLngDomainError(e): ... + class H3ResDomainError(e): ... + class H3CellInvalidError(e): ... + class H3DirEdgeInvalidError(e): ... + class H3UndirEdgeInvalidError(e): ... + class H3VertexInvalidError(e): ... + class H3DuplicateInputError(e): ... + class H3NotNeighborsError(e): ... + class H3ResMismatchError(e): ... + class H3OptionInvalidError(e): ... + class H3IndexInvalidError(e): ... + class H3BaseCellDomainError(e): ... + class H3DigitDomainError(e): ... + class H3DeletedDigitError(e): ... + + +""" +This defines a mapping between uint32_t error codes and concrete Python +exception classes. +Note that we intentionally omit E_SUCCESS, as it isn't an actual error. +""" +error_mapping = { + E_FAILED: H3FailedError, + E_DOMAIN: H3DomainError, + E_LATLNG_DOMAIN: H3LatLngDomainError, + E_RES_DOMAIN: H3ResDomainError, + E_CELL_INVALID: H3CellInvalidError, + E_DIR_EDGE_INVALID: H3DirEdgeInvalidError, + E_UNDIR_EDGE_INVALID: H3UndirEdgeInvalidError, + E_VERTEX_INVALID: H3VertexInvalidError, + E_PENTAGON: H3PentagonError, + E_DUPLICATE_INPUT: H3DuplicateInputError, + E_NOT_NEIGHBORS: H3NotNeighborsError, + E_RES_MISMATCH: H3ResMismatchError, + E_MEMORY_ALLOC: H3MemoryAllocError, + E_MEMORY_BOUNDS: H3MemoryBoundsError, + E_OPTION_INVALID: H3OptionInvalidError, + E_INDEX_INVALID: H3IndexInvalidError, + E_BASE_CELL_DOMAIN: H3BaseCellDomainError, + E_DIGIT_DOMAIN: H3DigitDomainError, + E_DELETED_DIGIT: H3DeletedDigitError, +} + +# Go back and modify the class definitions so that each concrete exception +# stores its associated error code. +for code, ex in error_mapping.items(): + ex.h3_error_code = code + + +# +# Helper functions +# + +# TODO: Move the helpers to util? +# TODO: Unclear how/where to expose these functions. cdef/cpdef? + +cpdef error_code_to_exception(H3Error err): + """ + Return Python exception corresponding to integer error code + given via the H3ErrorCodes enum in `h3api.h.in` in the C library. + """ + if err == E_SUCCESS: + return None + elif err in error_mapping: + return error_mapping[err] + else: + return UnknownH3ErrorCode(err) + +cdef check_for_error(H3Error err): + ex = error_code_to_exception(err) + if ex: + raise ex + +cpdef H3Error get_H3_ERROR_END(): + """ + Return integer H3_ERROR_END from the H3ErrorCodes enum + in `h3api.h.in` in the C library, which is one greater than + the last valid error code. + """ + return H3_ERROR_END + +# todo: There's no easy way to do `*args` in `cdef` functions, but I'm also +# not sure this even needs to be a Cython `cdef` function at all, or that +# any of the other helper functions need to be in Cython. +# todo: Revisit after we've played with this a bit. +# todo: also: maybe the extra messages aren't that much more helpful... +cdef check_for_error_msg(H3Error err, str msg): + ex = error_code_to_exception(err) + if ex: + raise ex(msg) diff --git a/src/h3/_cy/geo.pxd b/src/h3/_cy/geo.pxd deleted file mode 100644 index 1a2c1c3..0000000 --- a/src/h3/_cy/geo.pxd +++ /dev/null @@ -1,7 +0,0 @@ -from .h3lib cimport H3int - -cpdef H3int geo_to_h3(double lat, double lng, int res) except 1 -cpdef (double, double) h3_to_geo(H3int h) except * -cpdef double point_dist( - double lat1, double lng1, - double lat2, double lng2, unit=*) except -1 diff --git a/src/h3/_cy/geo.pyx b/src/h3/_cy/geo.pyx deleted file mode 100644 index dc2c1d7..0000000 --- a/src/h3/_cy/geo.pyx +++ /dev/null @@ -1,278 +0,0 @@ -cimport h3lib -from h3lib cimport bool, H3int -from .util cimport ( - check_cell, - check_edge, - check_res, - create_ptr, - create_mv, - deg2coord, - coord2deg, -) -from libc cimport stdlib - -from .util import H3ValueError - - -cpdef H3int geo_to_h3(double lat, double lng, int res) except 1: - cdef: - h3lib.GeoCoord c - - check_res(res) - - c = deg2coord(lat, lng) - - return h3lib.geoToH3(&c, res) - - -cpdef (double, double) h3_to_geo(H3int h) except *: - """Map an H3 cell into its centroid geo-coordinate (lat/lng)""" - cdef: - h3lib.GeoCoord c - - check_cell(h) - - h3lib.h3ToGeo(h, &c) - - return coord2deg(c) - - -cdef h3lib.Geofence make_geofence(geos, bool lnglat_order=False) except *: - """ - - The returned `Geofence` must be freed with a call to `free_geofence`. - - Parameters - ---------- - geos : list or tuple - GeoFence: A sequence of >= 3 (lat, lng) pairs where the last - element may or may not be same as the first (to form a closed loop). - The order of the pairs may be either clockwise or counterclockwise. - lnglat_order : bool - If True, assume coordinate pairs like (lng, lat) - If False, assume coordinate pairs like (lat, lng) - """ - cdef: - h3lib.Geofence gf - - gf.numVerts = len(geos) - - gf.verts = stdlib.calloc(gf.numVerts, sizeof(h3lib.GeoCoord)) - - if lnglat_order: - latlng = (g[::-1] for g in geos) - else: - latlng = geos - - for i, (lat, lng) in enumerate(latlng): - gf.verts[i] = deg2coord(lat, lng) - - return gf - - -cdef free_geofence(h3lib.Geofence* gf): - stdlib.free(gf.verts) - gf.verts = NULL - - -cdef class GeoPolygon: - cdef: - h3lib.GeoPolygon gp - - def __cinit__(self, outer, holes=None, bool lnglat_order=False): - """ - - Parameters - ---------- - outer : list or tuple - GeoFence - A GeoFence is a sequence of >= 3 (lat, lng) pairs where the last - element may or may not be same as the first (to form a closed loop). - The order of the pairs may be either clockwise or counterclockwise. - holes : list or tuple - A sequence of GeoFences - lnglat_order : bool - If True, assume coordinate pairs like (lng, lat) - If False, assume coordinate pairs like (lat, lng) - - """ - if holes is None: - holes = [] - - self.gp.geofence = make_geofence(outer, lnglat_order) - self.gp.numHoles = len(holes) - self.gp.holes = NULL - - if len(holes) > 0: - self.gp.holes = stdlib.calloc(len(holes), sizeof(h3lib.Geofence)) - for i, hole in enumerate(holes): - self.gp.holes[i] = make_geofence(hole, lnglat_order) - - - def __dealloc__(self): - free_geofence(&self.gp.geofence) - - for i in range(self.gp.numHoles): - free_geofence(&self.gp.holes[i]) - - stdlib.free(self.gp.holes) - - -def polyfill_polygon(outer, int res, holes=None, bool lnglat_order=False): - """ Set of hexagons whose center is contained in a polygon. - - The polygon is defined as in the GeoJson standard, with an exterior - LinearRing `outer` and a list of LinearRings `holes`, which define any - holes in the polygon. - - Each LinearRing may be in clockwise or counter-clockwise order - (right-hand rule or not), and may or may not be a closed loop (where the last - element is equal to the first). - The GeoJSON spec requires the right-hand rule, and a closed loop, but - this function will work with any input format. - - Parameters - ---------- - outer : list or tuple - A LinearRing, a sequence of (lat/lng) or (lng/lat) pairs - res : int - The resolution of the output hexagons - holes : list or tuple - A collection of LinearRings, describing any holes in the polygon - lnglat_order : bool - If True, assume coordinate pairs like (lng, lat) - If False, assume coordinate pairs like (lat, lng) - """ - - check_res(res) - gp = GeoPolygon(outer, holes=holes, lnglat_order=lnglat_order) - - n = h3lib.maxPolyfillSize(&gp.gp, res) - ptr = create_ptr(n) - - h3lib.polyfill(&gp.gp, res, ptr) - mv = create_mv(ptr, n) - - return mv - - -def polyfill_geojson(geojson, int res): - """ Set of hexagons whose center is contained in a GeoJson Polygon object. - - The polygon is defined exactly as in the GeoJson standard, so - `geojson` should be a dictionary like: - { - 'type': 'Polygon', - 'coordinates': [...] - } - - 'coordinates' should be a list of LinearRings, where the first ring describes - the exterior boundary of the Polygon, and any subsequent LinearRings - describe holes in the polygon. - - Note that we don't provide an option for the order of the coordinates, - as the GeoJson standard requires them to be in lng/lat order. - - Parameters - ---------- - geojson : dict - res : int - The resolution of the output hexagons - """ - - # todo: this one could handle multipolygons... - - if geojson['type'] != 'Polygon': - raise ValueError('Only Polygon GeoJSON supported') - - coords = geojson['coordinates'] - - out = polyfill_polygon(coords[0], res, holes=coords[1:], lnglat_order=True) - - return out - - -def polyfill(dict geojson, int res, bool geo_json_conformant=False): - """ Light wrapper around `polyfill_geojson` to provide backward compatibility. - """ - - try: - gj_type = geojson['type'] - except KeyError: - raise KeyError("`geojson` dict must have key 'type'.") from None - - if gj_type != 'Polygon': - raise ValueError('Only Polygon GeoJSON supported') - - if geo_json_conformant: - out = polyfill_geojson(geojson, res) - else: - coords = geojson['coordinates'] - out = polyfill_polygon(coords[0], res, holes=coords[1:], lnglat_order=False) - - return out - - -def cell_boundary(H3int h, bool geo_json=False): - """Compose an array of geo-coordinates that outlines a hexagonal cell""" - cdef: - h3lib.GeoBoundary gb - - check_cell(h) - - h3lib.h3ToGeoBoundary(h, &gb) - - verts = tuple( - coord2deg(gb.verts[i]) - for i in range(gb.num_verts) - ) - - if geo_json: - #lat/lng -> lng/lat and last point same as first - verts += (verts[0],) - verts = tuple(v[::-1] for v in verts) - - return verts - - -def edge_boundary(H3int edge, bool geo_json=False): - """ Returns the GeoBoundary containing the coordinates of the edge - """ - cdef: - h3lib.GeoBoundary gb - - check_edge(edge) - - h3lib.getH3UnidirectionalEdgeBoundary(edge, &gb) - - # todo: move this verts transform into the GeoBoundary object - verts = tuple( - coord2deg(gb.verts[i]) - for i in range(gb.num_verts) - ) - - if geo_json: - #lat/lng -> lng/lat and last point same as first - verts += (verts[0],) - verts = tuple(v[::-1] for v in verts) - - return verts - - -cpdef double point_dist( - double lat1, double lng1, - double lat2, double lng2, unit='km') except -1: - - a = deg2coord(lat1, lng1) - b = deg2coord(lat2, lng2) - - if unit == 'rads': - d = h3lib.pointDistRads(&a, &b) - elif unit == 'km': - d = h3lib.pointDistKm(&a, &b) - elif unit == 'm': - d = h3lib.pointDistM(&a, &b) - else: - raise H3ValueError('Unknown unit: {}'.format(unit)) - - return d diff --git a/src/h3/_cy/h3lib.pxd b/src/h3/_cy/h3lib.pxd index 5fa05cc..6ee3b41 100644 --- a/src/h3/_cy/h3lib.pxd +++ b/src/h3/_cy/h3lib.pxd @@ -1,168 +1,191 @@ -from libc cimport stdint +# cython: c_string_type=unicode, c_string_encoding=utf8 from cpython cimport bool -from libc.stdint cimport int64_t +from libc.stdint cimport uint32_t, uint64_t, int64_t -ctypedef stdint.uint64_t H3int -ctypedef basestring H3str +ctypedef object H3str -cdef extern from "h3api.h": +cdef extern from 'h3api.h': cdef int H3_VERSION_MAJOR cdef int H3_VERSION_MINOR cdef int H3_VERSION_PATCH - ctypedef stdint.uint64_t H3Index + ctypedef uint64_t H3int 'H3Index' - ctypedef struct GeoCoord: + ctypedef uint32_t H3Error + ctypedef enum H3ErrorCodes: + E_SUCCESS = 0 + E_FAILED = 1 + E_DOMAIN = 2 + E_LATLNG_DOMAIN = 3 + E_RES_DOMAIN = 4 + E_CELL_INVALID = 5 + E_DIR_EDGE_INVALID = 6 + E_UNDIR_EDGE_INVALID = 7 + E_VERTEX_INVALID = 8 + E_PENTAGON = 9 + E_DUPLICATE_INPUT = 10 + E_NOT_NEIGHBORS = 11 + E_RES_MISMATCH = 12 + E_MEMORY_ALLOC = 13 + E_MEMORY_BOUNDS = 14 + E_OPTION_INVALID = 15 + E_INDEX_INVALID = 16 + E_BASE_CELL_DOMAIN = 17 + E_DIGIT_DOMAIN = 18 + E_DELETED_DIGIT = 19 + H3_ERROR_END # sentinel value + + ctypedef struct LatLng: double lat # in radians - double lng "lon" # in radians + double lng # in radians - ctypedef struct GeoBoundary: - int num_verts "numVerts" - GeoCoord verts[10] # MAX_CELL_BNDRY_VERTS - - ctypedef struct Geofence: - int numVerts - GeoCoord *verts - - ctypedef struct GeoPolygon: - Geofence geofence - int numHoles - Geofence *holes - - ctypedef struct GeoMultiPolygon: - int numPolygons - GeoPolygon *polygons - - ctypedef struct LinkedGeoCoord: - GeoCoord data "vertex" - LinkedGeoCoord *next - - # renaming these for clarity - ctypedef struct LinkedGeoLoop: - LinkedGeoCoord *data "first" - LinkedGeoCoord *_data_last "last" # not needed in Cython bindings - LinkedGeoLoop *next - - ctypedef struct LinkedGeoPolygon: - LinkedGeoLoop *data "first" - LinkedGeoLoop *_data_last "last" # not needed in Cython bindings - LinkedGeoPolygon *next + ctypedef struct CellBoundary: + int num_verts 'numVerts' + LatLng verts[10] # MAX_CELL_BNDRY_VERTS ctypedef struct CoordIJ: int i int j - H3Index geoToH3(const GeoCoord *g, int res) nogil + ctypedef struct GeoLoop: + int numVerts + LatLng *verts - void h3ToGeo(H3Index h3, GeoCoord *g) nogil + ctypedef struct GeoPolygon: + GeoLoop geoloop + int numHoles + GeoLoop *holes - void h3ToGeoBoundary(H3Index h3, GeoBoundary *gp) - - int maxKringSize(int k) - - int hexRange(H3Index origin, int k, H3Index *out) - - int hexRangeDistances(H3Index origin, int k, H3Index *out, int *distances) - - int h3Distance(H3Index origin, H3Index h3) - - int hexRanges(H3Index *h3Set, int length, int k, H3Index *out) - - void kRing(H3Index origin, int k, H3Index *out) - - void kRingDistances(H3Index origin, int k, H3Index *out, int *distances) - - int hexRing(H3Index origin, int k, H3Index *out) - - int maxPolyfillSize(const GeoPolygon *geoPolygon, int res) - - void polyfill(const GeoPolygon *geoPolygon, int res, H3Index *out) - - void h3SetToLinkedGeo(const H3Index *h3Set, const int numHexes, LinkedGeoPolygon *out) - - void destroyLinkedPolygon(LinkedGeoPolygon *polygon) + int isValidCell(H3int h) nogil + int isPentagon(H3int h) nogil + int isResClassIII(H3int h) nogil + int isValidDirectedEdge(H3int edge) nogil + int isValidVertex(H3int v) nogil + int isValidIndex(H3int h) nogil double degsToRads(double degrees) nogil - double radsToDegs(double radians) nogil - stdint.int64_t numHexagons(int res) + int getResolution(H3int h) nogil + int getBaseCellNumber(H3int h) nogil + H3Error getIndexDigit(H3int h, int res, int *out) nogil + H3Error constructCell(int res, int baseCellNumber, const int *digits, H3int *out) nogil - int h3GetResolution(H3Index h) nogil + H3Error latLngToCell(const LatLng *g, int res, H3int *out) nogil + H3Error cellToLatLng(H3int h, LatLng *) nogil + H3Error gridDistance(H3int h1, H3int h2, int64_t *distance) nogil - int h3GetBaseCell(H3Index h) + H3Error cellToVertex(H3int cell, int vertexNum, H3int *out) nogil + H3Error cellToVertexes(H3int cell, H3int *vertexes) nogil + H3Error vertexToLatLng(H3int vertex, LatLng *coord) nogil - H3Index stringToH3(const char *str) + H3Error maxGridDiskSize(int k, int64_t *out) nogil # num/out/N? + H3Error gridDisk(H3int h, int k, H3int *out) nogil - void h3ToString(H3Index h, char *str, size_t sz) + H3Error cellToParent( H3int h, int parentRes, H3int *parent) nogil + H3Error cellToCenterChild(H3int h, int childRes, H3int *child) nogil + H3Error cellToChildPos(H3int child, int parentRes, int64_t *out) nogil + H3Error childPosToCell(int64_t childPos, H3int parent, int childRes, H3int *child) nogil - int h3IsValid(H3Index h) + H3Error cellToChildrenSize(H3int h, int childRes, int64_t *num) nogil # num/out/N? + H3Error cellToChildren( H3int h, int childRes, H3int *children) nogil - H3Index h3ToParent(H3Index h, int parentRes) nogil + H3Error compactCells( + const H3int *cells_u, + H3int *cells_c, + const int num_u + ) nogil + H3Error uncompactCellsSize( + const H3int *cells_c, + const int64_t num_c, + const int res, + int64_t *num_u + ) nogil + H3Error uncompactCells( + const H3int *cells_c, + const int num_c, + H3int *cells_u, + const int num_u, + const int res + ) nogil - int maxH3ToChildrenSize(H3Index h, int childRes) + H3Error getNumCells(int res, int64_t *out) nogil + int pentagonCount() nogil + int res0CellCount() nogil + H3Error getPentagons(int res, H3int *out) nogil + H3Error getRes0Cells(H3int *out) nogil - void h3ToChildren(H3Index h, int childRes, H3Index *children) + H3Error gridPathCellsSize(H3int start, H3int end, int64_t *size) nogil + H3Error gridPathCells(H3int start, H3int end, H3int *out) nogil - int compact(const H3Index *h3Set, H3Index *compactedSet, const int numHexes) + H3Error getHexagonAreaAvgKm2(int res, double *out) nogil + H3Error getHexagonAreaAvgM2(int res, double *out) nogil - int maxUncompactSize(const H3Index *compactedSet, const int numHexes, const int res) + H3Error cellAreaRads2(H3int h, double *out) nogil + H3Error cellAreaKm2(H3int h, double *out) nogil + H3Error cellAreaM2(H3int h, double *out) nogil - int uncompact(const H3Index *compactedSet, const int numHexes, H3Index *h3Set, const int maxHexes, const int res) + H3Error maxFaceCount(H3int h, int *out) nogil + H3Error getIcosahedronFaces(H3int h3, int *out) nogil - int h3IsResClassIII(H3Index h) + H3Error cellToLocalIj(H3int origin, H3int h3, uint32_t mode, CoordIJ *out) nogil + H3Error localIjToCell(H3int origin, const CoordIJ *ij, uint32_t mode, H3int *out) nogil - int h3IsPentagon(H3Index h) + H3Error gridDiskDistances(H3int origin, int k, H3int *out, int *distances) nogil + H3Error gridRing(H3int origin, int k, H3int *out) nogil + H3Error gridRingUnsafe(H3int origin, int k, H3int *out) nogil - int pentagonIndexCount() + H3Error areNeighborCells(H3int origin, H3int destination, int *out) nogil + H3Error cellsToDirectedEdge(H3int origin, H3int destination, H3int *out) nogil + H3Error getDirectedEdgeOrigin(H3int edge, H3int *out) nogil + H3Error getDirectedEdgeDestination(H3int edge, H3int *out) nogil + H3Error originToDirectedEdges(H3int origin, H3int *edges) nogil + # todo: directedEdgeToCells - void getPentagonIndexes(int res, H3Index *out) + H3Error getHexagonEdgeLengthAvgKm(int res, double *out) nogil + H3Error getHexagonEdgeLengthAvgM(int res, double *out) nogil - int res0IndexCount() + H3Error edgeLengthRads(H3int edge, double *out) nogil + H3Error edgeLengthKm(H3int edge, double *out) nogil + H3Error edgeLengthM(H3int edge, double *out) nogil - void getRes0Indexes(H3Index *out) + H3Error cellToBoundary(H3int h3, CellBoundary *gp) nogil + H3Error directedEdgeToBoundary(H3int edge, CellBoundary *gb) nogil - H3Index h3ToCenterChild(H3Index h, int res) + double greatCircleDistanceRads(const LatLng *a, const LatLng *b) nogil + double greatCircleDistanceKm(const LatLng *a, const LatLng *b) nogil + double greatCircleDistanceM(const LatLng *a, const LatLng *b) nogil - int h3IndexesAreNeighbors(H3Index origin, H3Index destination) + H3Error maxPolygonToCellsSize(const GeoPolygon *geoPolygon, int res, uint32_t flags, uint64_t *count) + H3Error polygonToCells(const GeoPolygon *geoPolygon, int res, uint32_t flags, H3int *out) - H3Index getH3UnidirectionalEdge(H3Index origin, H3Index destination) + H3Error maxPolygonToCellsSizeExperimental(const GeoPolygon *geoPolygon, int res, uint32_t flags, uint64_t *count) + H3Error polygonToCellsExperimental(const GeoPolygon *geoPolygon, int res, uint32_t flags, uint64_t sz, H3int *out) - int h3UnidirectionalEdgeIsValid(H3Index edge) + ctypedef struct GeoMultiPolygon: + int numPolygons + GeoPolygon *polygons - H3Index getOriginH3IndexFromUnidirectionalEdge(H3Index edge) + # int hexRange(H3int origin, int k, H3int *out) - H3Index getDestinationH3IndexFromUnidirectionalEdge(H3Index edge) + # int hexRangeDistances(H3int origin, int k, H3int *out, int *distances) - void getH3IndexesFromUnidirectionalEdge(H3Index edge, H3Index *originDestination) + # int hexRanges(H3int *h3Set, int length, int k, H3int *out) - void getH3UnidirectionalEdgesFromHexagon(H3Index origin, H3Index *edges) + # void h3SetToLinkedGeo(const H3int *h3Set, const int numCells, LinkedGeoPolygon *out) - void getH3UnidirectionalEdgeBoundary(H3Index edge, GeoBoundary *gb) + # void destroyLinkedPolygon(LinkedGeoPolygon *polygon) - int h3LineSize(H3Index start, H3Index end) - int h3Line(H3Index start, H3Index end, H3Index *out) + # H3int stringToH3(const char *str) - int maxFaceCount(H3Index h3) - void h3GetFaces(H3Index h3, int *out) + # void h3ToString(H3int h, char *str, size_t sz) - int experimentalH3ToLocalIj(H3Index origin, H3Index h3, CoordIJ *out) - int experimentalLocalIjToH3(H3Index origin, const CoordIJ *ij, H3Index *out) + # void getH3intesFromUnidirectionalEdge(H3int edge, H3int *originDestination) - double hexAreaKm2(int res) nogil - double hexAreaM2(int res) nogil - double cellAreaRads2(H3Index h) nogil - double cellAreaKm2(H3Index h) nogil - double cellAreaM2(H3Index h) nogil - - double edgeLengthKm(int res) nogil - double edgeLengthM(int res) nogil - - double exactEdgeLengthRads(H3Index edge) nogil - double exactEdgeLengthKm(H3Index edge) nogil - double exactEdgeLengthM(H3Index edge) nogil - - double pointDistRads(const GeoCoord *a, const GeoCoord *b) nogil - double pointDistKm(const GeoCoord *a, const GeoCoord *b) nogil - double pointDistM(const GeoCoord *a, const GeoCoord *b) nogil +# cellsToMultiPolygon and destroyGeoMultiPolygon are temporarily excluded +# from the public API, so we use an internal header until they're moved +# back into h3api.h +cdef extern from 'cellsToMultiPoly.h': + H3Error cellsToMultiPolygon(const H3int *cells, const int64_t numCells, GeoMultiPolygon *out) + void destroyGeoMultiPolygon(GeoMultiPolygon *mpoly) diff --git a/src/h3/_cy/latlng.pxd b/src/h3/_cy/latlng.pxd new file mode 100644 index 0000000..40dfc34 --- /dev/null +++ b/src/h3/_cy/latlng.pxd @@ -0,0 +1,7 @@ +from .h3lib cimport H3int + +cpdef H3int latlng_to_cell(double lat, double lng, int res) except 1 +cpdef (double, double) cell_to_latlng(H3int h) except * +cpdef double great_circle_distance( + double lat1, double lng1, + double lat2, double lng2, unit=*) except -1 diff --git a/src/h3/_cy/latlng.pyx b/src/h3/_cy/latlng.pyx new file mode 100644 index 0000000..630d3ad --- /dev/null +++ b/src/h3/_cy/latlng.pyx @@ -0,0 +1,330 @@ +# cython: freethreading_compatible=True +from libc.stdint cimport uint64_t + +cimport h3lib +from h3lib cimport bool, H3int + +from .util cimport ( + check_cell, + check_edge, + check_res, + deg2coord, + coord2deg +) + +from .error_system cimport check_for_error + +from .memory cimport H3MemoryManager + +# TODO: We might be OK with taking the GIL for the functions in this module +from libc.stdlib cimport ( + # malloc as h3_malloc, # not used + calloc as h3_calloc, + realloc as h3_realloc, + free as h3_free, +) + + +cpdef H3int latlng_to_cell(double lat, double lng, int res) except 1: + cdef: + h3lib.LatLng c + H3int out + + c = deg2coord(lat, lng) + + check_for_error( + h3lib.latLngToCell(&c, res, &out) + ) + + return out + + +cpdef (double, double) cell_to_latlng(H3int h) except *: + """Map an H3 cell into its centroid geo-coordinate (lat/lng)""" + cdef: + h3lib.LatLng c + + check_cell(h) + # todo: think about: if you give this an invalid cell, should it still return a lat/lng? + # idea: safe and unsafe APIs? + + check_for_error( + h3lib.cellToLatLng(h, &c) + ) + + return coord2deg(c) + + +cdef h3lib.GeoLoop make_geoloop(latlngs) except *: + """ + The returned `GeoLoop` must be freed with a call to `free_geoloop`. + + Parameters + ---------- + latlngs : list or tuple + GeoLoop: A sequence of >= 3 (lat, lng) pairs where the last + element may or may not be same as the first (to form a closed loop). + The order of the pairs may be either clockwise or counterclockwise. + """ + cdef: + h3lib.GeoLoop gl + + gl.numVerts = len(latlngs) + + # todo: need for memory management + # can automatically free? + gl.verts = h3_calloc(gl.numVerts, sizeof(h3lib.LatLng)) + + for i, (lat, lng) in enumerate(latlngs): + gl.verts[i] = deg2coord(lat, lng) + + return gl + + +cdef free_geoloop(h3lib.GeoLoop* gl): + h3_free(gl.verts) + gl.verts = NULL + + +cdef class GeoPolygon: + cdef: + h3lib.GeoPolygon gp + + def __cinit__(self, outer, holes=None): + """ + + Parameters + ---------- + outer : list or tuple + GeoLoop + A GeoLoop is a sequence of >= 3 (lat, lng) pairs where the last + element may or may not be same as the first (to form a closed loop). + The order of the pairs may be either clockwise or counterclockwise. + holes : list or tuple + A sequence of GeoLoops + """ + if holes is None: + holes = [] + + self.gp.geoloop = make_geoloop(outer) + self.gp.numHoles = len(holes) + self.gp.holes = NULL + + if len(holes) > 0: + self.gp.holes = h3_calloc(len(holes), sizeof(h3lib.GeoLoop)) + for i, hole in enumerate(holes): + self.gp.holes[i] = make_geoloop(hole) + + + def __dealloc__(self): + free_geoloop(&self.gp.geoloop) + + for i in range(self.gp.numHoles): + free_geoloop(&self.gp.holes[i]) + + h3_free(self.gp.holes) + + +def polygon_to_cells(outer, int res, holes=None): + """ Get the set of cells whose center is contained in a polygon. + + The polygon is defined similarity to the GeoJson standard, with an exterior + `outer` ring of lat/lng points, and a list of `holes`, each of which are also + rings of lat/lng points. + + Each ring may be in clockwise or counter-clockwise order + (right-hand rule or not), and may or may not be a closed loop (where the last + element is equal to the first). + The GeoJSON spec requires the right-hand rule and a closed loop, but + this function relaxes those constraints. + + Unlike the GeoJson standard, the elements of the lat/lng pairs of each + ring are in lat/lng order, instead of lng/lat order. + + We'll handle translation to different formats in the Python code, + rather than the Cython code. + + Parameters + ---------- + outer : list or tuple + A ring given by a sequence of lat/lng pairs. + res : int + The resolution of the output hexagons + holes : list or tuple + A collection of rings, each given by a sequence of lat/lng pairs. + These describe any the "holes" in the polygon. + """ + cdef: + uint64_t n + + check_res(res) + + if not outer: + return H3MemoryManager(0).to_mv() + + gp = GeoPolygon(outer, holes=holes) + + check_for_error( + h3lib.maxPolygonToCellsSize(&gp.gp, res, 0, &n) + ) + + hmm = H3MemoryManager(n) + check_for_error( + h3lib.polygonToCells(&gp.gp, res, 0, hmm.ptr) + ) + mv = hmm.to_mv() + + return mv + + +def polygons_to_cells(polygons, int res): + mvs = [ + polygon_to_cells(outer=poly.outer, res=res, holes=poly.holes) + for poly in polygons + ] + + n = sum(map(len, mvs)) + hmm = H3MemoryManager(n) + + # probably super inefficient, but it is working! + # tood: move this to C + k = 0 + for mv in mvs: + for v in mv: + hmm.ptr[k] = v + k += 1 + + return hmm.to_mv() + + +def polygon_to_cells_experimental(outer, int res, int flag, holes=None): + """ Get the set of cells whose center is contained in a polygon. + + The polygon is defined similarity to the GeoJson standard, with an exterior + `outer` ring of lat/lng points, and a list of `holes`, each of which are also + rings of lat/lng points. + + Each ring may be in clockwise or counter-clockwise order + (right-hand rule or not), and may or may not be a closed loop (where the last + element is equal to the first). + The GeoJSON spec requires the right-hand rule and a closed loop, but + this function relaxes those constraints. + + Unlike the GeoJson standard, the elements of the lat/lng pairs of each + ring are in lat/lng order, instead of lng/lat order. + + We'll handle translation to different formats in the Python code, + rather than the Cython code. + + Parameters + ---------- + outer : list or tuple + A ring given by a sequence of lat/lng pairs. + res : int + The resolution of the output hexagons + flag : int + Polygon to cells flag, such as containment mode. + holes : list or tuple + A collection of rings, each given by a sequence of lat/lng pairs. + These describe any the "holes" in the polygon. + """ + cdef: + uint64_t n + + check_res(res) + + if not outer: + return H3MemoryManager(0).to_mv() + + gp = GeoPolygon(outer, holes=holes) + + check_for_error( + h3lib.maxPolygonToCellsSizeExperimental(&gp.gp, res, flag, &n) + ) + + hmm = H3MemoryManager(n) + check_for_error( + h3lib.polygonToCellsExperimental(&gp.gp, res, flag, n, hmm.ptr) + ) + mv = hmm.to_mv() + + return mv + + +def polygons_to_cells_experimental(polygons, int res, int flag): + mvs = [ + polygon_to_cells_experimental(outer=poly.outer, res=res, holes=poly.holes, flag=flag) + for poly in polygons + ] + + n = sum(map(len, mvs)) + hmm = H3MemoryManager(n) + + # probably super inefficient, but it is working! + # tood: move this to C + # a cell can overlap more than one polygon, so skip the ones already added + seen = set() + k = 0 + for mv in mvs: + for v in mv: + if v not in seen: + seen.add(v) + hmm.ptr[k] = v + k += 1 + + return hmm.to_mv() + + +def cell_to_boundary(H3int h): + """Compose an array of geo-coordinates that outlines a hexagonal cell""" + cdef: + h3lib.CellBoundary gb + + check_cell(h) + + h3lib.cellToBoundary(h, &gb) + + verts = tuple( + coord2deg(gb.verts[i]) + for i in range(gb.num_verts) + ) + + return verts + + +def directed_edge_to_boundary(H3int edge): + """ Returns the CellBoundary containing the coordinates of the edge + """ + cdef: + h3lib.CellBoundary gb + + check_edge(edge) + + h3lib.directedEdgeToBoundary(edge, &gb) + + # todo: move this verts transform into the CellBoundary object + verts = tuple( + coord2deg(gb.verts[i]) + for i in range(gb.num_verts) + ) + + return verts + + +cpdef double great_circle_distance( + double lat1, double lng1, + double lat2, double lng2, unit='km') except -1: + + a = deg2coord(lat1, lng1) + b = deg2coord(lat2, lng2) + + if unit == 'rads': + d = h3lib.greatCircleDistanceRads(&a, &b) + elif unit == 'km': + d = h3lib.greatCircleDistanceKm(&a, &b) + elif unit == 'm': + d = h3lib.greatCircleDistanceM(&a, &b) + else: + raise ValueError('Unknown unit: {}'.format(unit)) + + return d diff --git a/src/h3/_cy/memory.pxd b/src/h3/_cy/memory.pxd new file mode 100644 index 0000000..5e259e2 --- /dev/null +++ b/src/h3/_cy/memory.pxd @@ -0,0 +1,12 @@ +from .h3lib cimport H3int + +cdef class H3MemoryManager: + cdef: + size_t n + H3int* ptr + + cdef H3int[:] to_mv(self) + cdef H3int[:] to_mv_keep_zeros(self) + +cdef int[:] int_mv(size_t n) +cpdef H3int[:] iter_to_mv(cells) diff --git a/src/h3/_cy/memory.pyx b/src/h3/_cy/memory.pyx new file mode 100644 index 0000000..963b00d --- /dev/null +++ b/src/h3/_cy/memory.pyx @@ -0,0 +1,249 @@ +# cython: freethreading_compatible=True +from cython.view cimport array +from .h3lib cimport H3int + +""" +### Memory allocation options + +We have a few options for the memory allocation functions. +There's a trade-off between using the Python allocators which let Python +track memory usage and offers some optimizations vs the system +allocators, which do not need to acquire the GIL. +""" + +""" +System allocation functions. These do not acquire the GIL. +""" +from libc.stdlib cimport ( + # malloc as h3_malloc, # not used + calloc as h3_calloc, + realloc as h3_realloc, + free as h3_free, +) + + +""" +PyMem_Raw* functions should just be wrappers around system allocators +also given in libc.stdlib. These functions do not acquire the GIL. + +Note that these do not have a calloc function until py 3.5 and Cython 3.0, +so we would need to zero-out memory manually. + +https://python.readthedocs.io/en/stable/c-api/memory.html#raw-memory-interface +""" +# from cpython.mem cimport ( +# PyMem_RawMalloc as h3_malloc, +# # PyMem_RawCalloc as h3_calloc, # only in Python >=3.5 (and Cython >=3.0?) +# PyMem_RawRealloc as h3_realloc, +# PyMem_RawFree as h3_free, +# ) + + +""" +These functions use the Python allocator (instead of the system allocator), +which offers some optimizations for Python, and allows Python to track +memory usage. However, these functions must acquire the GIL. + +Note that these do not have a calloc function until py 3.5 and Cython 3.0, +so we would need to zero-out memory manually. + +https://cython.readthedocs.io/en/stable/src/tutorial/memory_allocation.html +https://python.readthedocs.io/en/stable/c-api/memory.html#memory-interface +""" +# from cpython.mem cimport ( +# PyMem_Malloc as h3_malloc, +# # PyMem_Calloc as h3_calloc, # only in Python >=3.5 (and Cython >=3.0?) +# PyMem_Realloc as h3_realloc, +# PyMem_Free as h3_free, +# ) + + +cdef size_t move_nonzeros(H3int* a, size_t n): + """ Move nonzero elements to front of array `a` of length `n`. + Return the number of nonzero elements. + + Loop invariant: Everything *before* `i` or *after* `j` is "done". + Move `i` and `j` inwards until they equal, and exit. + You can move `i` forward until there's a zero in front of it. + You can move `j` backward until there's a nonzero to the left of it. + Anything to the right of `j` is "junk" that can be reallocated. + + | a | b | 0 | c | d | ... | + ^ ^ + i j + + + | a | b | d | c | d | ... | + ^ ^ + i j + """ + cdef: + size_t i = 0 + size_t j = n + + while i < j: + if a[j-1] == 0: + j -= 1 + continue + + if a[i] != 0: + i += 1 + continue + + # if we're here, we know: + # a[i] == 0 + # a[j-1] != 0 + # i < j + # so we can swap! (actually, move a[j-1] -> a[i]) + a[i] = a[j-1] + j -= 1 + + return i + + +cdef H3int[:] empty_memory_view(): + # todo: get rid of this? + # there's gotta be a better way to do this... + # create an empty cython.view.array? + cdef: + H3int a[1] + + return (a)[:0] + + +cdef _remove_zeros(H3MemoryManager x): + x.n = move_nonzeros(x.ptr, x.n) + + if x.n == 0: + h3_free(x.ptr) + x.ptr = NULL + else: + x.ptr = h3_realloc(x.ptr, x.n*sizeof(H3int)) + if not x.ptr: + raise MemoryError() + + +cdef H3int[:] _copy_to_mv(const H3int* ptr, size_t n): + cdef: + array arr + + arr = ptr + arr.callback_free_data = h3_free + + return arr + + +cdef H3int[:] _create_mv(H3MemoryManager x): + if x.n == 0: + h3_free(x.ptr) + x.ptr = NULL + mv = empty_memory_view() + else: + mv = _copy_to_mv(x.ptr, x.n) + + # responsibility for the memory moves from this object to the array/memoryview + x.ptr = NULL + x.n = 0 + + return mv + + +""" +TODO: The not None declaration for the argument automatically rejects None values as input, which would otherwise be allowed. The reason why None is allowed by default is that it is conveniently used for return arguments: + https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html#syntax + +TODO: potential optimization: https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html#performance-disabling-initialization-checks + +## future improvements: + +- abolish any appearance of &thing[0]. (i.e., identical interfaces) +- can i make the interface for all these memory views identical? +""" + +cdef class H3MemoryManager: + """ + Cython object in charge of allocating and freeing memory for arrays + of H3 indexes. + + Initially allocates memory and provides access through `self.ptr` and + `self.n`. + + The `to_mv()` function removes responsibility for the allocated memory + from this object to a memory view object. A memory view object automatically + deallocates its memory during garbage collection. + + If the H3MemoryManager is garbage collected before running `to_mv()`, + it will deallocate its memory itself. + + This pattern is useful for a few reasons: + + - provide convenient access to the raw memory pointer and length for passing + to h3lib functions + - remove zeroes from the array output (some h3lib functions may return + results with zeros/H3NULL values) + - cython and python array types have weird interfaces; memoryviews are + much cleaner + + If we find a better way to do these then this class may no longer be + necessary. + + TODO: consider a context manager pattern + """ + def __cinit__(self, size_t n): + self.n = n + self.ptr = h3_calloc(self.n, sizeof(H3int)) + + if not self.ptr: + raise MemoryError() + + cdef H3int[:] to_mv_keep_zeros(self): + # todo: this could be a private method + return _create_mv(self) + + cdef H3int[:] to_mv(self): + _remove_zeros(self) + return _create_mv(self) + + def __dealloc__(self): + # If the memory has been handed off to a memoryview, this pointer + # should be NULL, and deallocing on NULL is fine. + # If the pointer is *not* NULL, then this means the MemoryManager + # has is still responsible for the memory (it hasn't given the memory away to another object). + h3_free(self.ptr) + + +""" +todo: combine with the H3MemoryManager using fused types? +https://cython.readthedocs.io/en/stable/src/userguide/fusedtypes.html +""" +cdef int[:] int_mv(size_t n): + cdef: + array arr + + if n == 0: + raise MemoryError() + else: + ptr = h3_calloc(n, sizeof(int)) + if ptr is NULL: + raise MemoryError() + + arr = ptr + arr.callback_free_data = h3_free + + return arr + + +cpdef H3int[:] iter_to_mv(cells): + """ cells needs to be an iterable that knows its size... + or should we have it match the np.fromiter function, which infers if not available? + """ + cdef: + H3int[:] mv + + n = len(cells) + mv = H3MemoryManager(n).to_mv_keep_zeros() + + for i,h in enumerate(cells): + mv[i] = h + + return mv diff --git a/src/h3/_cy/to_multipoly.pyx b/src/h3/_cy/to_multipoly.pyx index 8e5ca55..cb5e5e2 100644 --- a/src/h3/_cy/to_multipoly.pyx +++ b/src/h3/_cy/to_multipoly.pyx @@ -1,75 +1,46 @@ +# cython: freethreading_compatible=True cimport h3lib from h3lib cimport H3int from .util cimport check_cell, coord2deg +from .error_system cimport check_for_error -# todo: it's driving me crazy that these three functions are all essentially the same linked list walker... -# grumble: no way to do iterators in with cdef functions! -cdef walk_polys(const h3lib.LinkedGeoPolygon* L): - out = [] - while L: - out += [walk_loops(L.data)] - L = L.next - - return out +cdef _loop_to_list(const h3lib.GeoLoop *loop): + return [coord2deg(loop.verts[v]) for v in range(loop.numVerts)] -cdef walk_loops(const h3lib.LinkedGeoLoop* L): - out = [] - while L: - out += [walk_coords(L.data)] - L = L.next - - return out +cdef _poly_to_lists(const h3lib.GeoPolygon *poly): + return ( + [_loop_to_list(&poly.geoloop)] + + [_loop_to_list(&poly.holes[h]) for h in range(poly.numHoles)] + ) -cdef walk_coords(const h3lib.LinkedGeoCoord* L): - out = [] - while L: - out += [coord2deg(L.data)] - L = L.next - - return out - -# todo: tuples instead of lists? -def _to_multi_polygon(const H3int[:] hexes): +def _to_multi_polygon(const H3int[:] cells): cdef: - h3lib.LinkedGeoPolygon polygon + h3lib.GeoMultiPolygon mpoly + H3int cell - for h in hexes: - check_cell(h) + for cell in cells: + check_cell(cell) - h3lib.h3SetToLinkedGeo(&hexes[0], len(hexes), &polygon) + check_for_error( + h3lib.cellsToMultiPolygon(&cells[0], len(cells), &mpoly) + ) - out = walk_polys(&polygon) - - # we're still responsible for cleaning up the passed in `polygon`, - # but not a problem here, since it is stack allocated - h3lib.destroyLinkedPolygon(&polygon) + try: + out = [ + _poly_to_lists(&mpoly.polygons[p]) + for p in range(mpoly.numPolygons) + ] + finally: + h3lib.destroyGeoMultiPolygon(&mpoly) return out -def _geojson_loop(loop): - """ Swap lat/lng order and close loop. - """ - loop = [e[::-1] for e in loop] - loop += [loop[0]] - - return loop - - -def h3_set_to_multi_polygon(const H3int[:] hexes, geo_json=False): - # todo: gotta be a more elegant way to handle these... - if len(hexes) == 0: +def cells_to_multi_polygon(const H3int[:] cells): + if len(cells) == 0: return [] - multipoly = _to_multi_polygon(hexes) - - if geo_json: - multipoly = [ - [_geojson_loop(loop) for loop in poly] - for poly in multipoly - ] - - return multipoly + return _to_multi_polygon(cells) diff --git a/src/h3/_cy/unstable_vect.pyx b/src/h3/_cy/unstable_vect.pyx deleted file mode 100644 index 316ac12..0000000 --- a/src/h3/_cy/unstable_vect.pyx +++ /dev/null @@ -1,89 +0,0 @@ -cimport h3lib -from h3lib cimport H3int -from .util cimport deg2coord - -from cython cimport boundscheck, wraparound -from libc.math cimport sqrt, sin, cos, asin - -cdef double haversineDistance(double th1, double ph1, double th2, double ph2) nogil: - cdef: - double dx, dy, dz - double R = 6371.0088 - - ph1 -= ph2 - - dz = sin(th1) - sin(th2) - dx = cos(ph1) * cos(th1) - cos(th2) - dy = sin(ph1) * cos(th1) - - return asin(sqrt(dx*dx + dy*dy + dz*dz) / 2)*2*R - - -@boundscheck(False) -@wraparound(False) -cpdef void haversine_vect( - const H3int[:] a, - const H3int[:] b, - double[:] out -) nogil: - - cdef h3lib.GeoCoord p1, p2 - - with nogil: - # todo: add these back in when cython 3.0 comes out - #assert len(a) == len(b) - #assert len(a) <= len(out) - - for i in range(len(a)): - h3lib.h3ToGeo(a[i], &p1) - h3lib.h3ToGeo(b[i], &p2) - out[i] = haversineDistance( - p1.lat, p1.lng, - p2.lat, p2.lng - ) - - -@boundscheck(False) -@wraparound(False) -cpdef void geo_to_h3_vect( - const double[:] lat, - const double[:] lng, - int res, - H3int[:] out -) nogil: - - cdef h3lib.GeoCoord c - - with nogil: - for i in range(len(lat)): - c = deg2coord(lat[i], lng[i]) - out[i] = h3lib.geoToH3(&c, res) - - -@boundscheck(False) -@wraparound(False) -cpdef void h3_to_parent_vect( - const H3int[:] h, - int[:] res, - H3int[:] out -) nogil: - - cdef Py_ssize_t i - - with nogil: - for i in range(len(h)): - out[i] = h3lib.h3ToParent(h[i], res[i]) - - -@boundscheck(False) -@wraparound(False) -cpdef void h3_get_resolution_vect( - const H3int[:] h, - int[:] out, -) nogil: - - cdef Py_ssize_t i - - with nogil: - for i in range(len(h)): - out[i] = h3lib.h3GetResolution(h[i]) diff --git a/src/h3/_cy/util.pxd b/src/h3/_cy/util.pxd index 06cc26a..b584d3a 100644 --- a/src/h3/_cy/util.pxd +++ b/src/h3/_cy/util.pxd @@ -1,18 +1,14 @@ -from .h3lib cimport H3int, H3str, GeoCoord +from .h3lib cimport H3int, H3str, LatLng -cdef GeoCoord deg2coord(double lat, double lng) nogil -cdef (double, double) coord2deg(GeoCoord c) nogil - -cpdef H3int hex2int(H3str h) except? 0 -cpdef H3str int2hex(H3int x) - -cdef H3int* create_ptr(size_t n) except? NULL -cdef H3int[:] create_mv(H3int* ptr, size_t n) +cdef LatLng deg2coord(double lat, double lng) nogil +cdef (double, double) coord2deg(LatLng c) nogil +cpdef H3int str_to_int(H3str h) except? 0 +cpdef H3str int_to_str(H3int x) cdef check_cell(H3int h) cdef check_edge(H3int e) +cdef check_vertex(H3int v) +cdef check_index(H3int h) cdef check_res(int res) cdef check_distance(int k) - -cdef H3int[:] empty_memory_view() # want to drop this if possible diff --git a/src/h3/_cy/util.pyx b/src/h3/_cy/util.pyx index dbf17da..74e8f80 100644 --- a/src/h3/_cy/util.pyx +++ b/src/h3/_cy/util.pyx @@ -1,13 +1,31 @@ -from libc cimport stdlib -from cython.view cimport array -from .h3lib cimport H3int, H3str, h3IsValid, h3UnidirectionalEdgeIsValid +# cython: freethreading_compatible=True +from .h3lib cimport ( + H3int, + H3str, + isValidCell, + isValidDirectedEdge, + isValidVertex, + isValidIndex, +) cimport h3lib +from .error_system import ( + H3ResDomainError, + H3DomainError, + H3DirEdgeInvalidError, + H3CellInvalidError, + H3VertexInvalidError, + H3IndexInvalidError, +) -cdef h3lib.GeoCoord deg2coord(double lat, double lng) nogil: +# Must match EARTH_RADIUS_KM in h3lib's constants.h, which is not part of the +# public h3api.h header. Used to convert km based averages to radians. +EARTH_RADIUS_KM = 6371.007180918475 + +cdef h3lib.LatLng deg2coord(double lat, double lng) nogil: cdef: - h3lib.GeoCoord c + h3lib.LatLng c c.lat = h3lib.degsToRads(lat) c.lng = h3lib.degsToRads(lng) @@ -15,7 +33,7 @@ cdef h3lib.GeoCoord deg2coord(double lat, double lng) nogil: return c -cdef (double, double) coord2deg(h3lib.GeoCoord c) nogil: +cdef (double, double) coord2deg(h3lib.LatLng c) nogil: return ( h3lib.radsToDegs(c.lat), h3lib.radsToDegs(c.lng) @@ -32,11 +50,11 @@ cpdef basestring c_version(): return '{}.{}.{}'.format(*v) -cpdef H3int hex2int(H3str h) except? 0: +cpdef H3int str_to_int(H3str h) except? 0: return int(h, 16) -cpdef H3str int2hex(H3int x): +cpdef H3str int_to_str(H3int x): """ Convert H3 integer to hex string representation Need to be careful in Python 2 because `hex(x)` may return a string @@ -48,21 +66,6 @@ cpdef H3str int2hex(H3int x): return '{:x}'.format(x) -class H3ValueError(ValueError): - pass - -class H3CellError(H3ValueError): - pass - -class H3EdgeError(H3ValueError): - pass - -class H3ResolutionError(H3ValueError): - pass - -class H3DistanceError(H3ValueError): - pass - cdef check_cell(H3int h): """ Check if valid H3 "cell" (hexagon or pentagon). @@ -72,126 +75,32 @@ cdef check_cell(H3int h): we want the error message to be informative to the user in either case. - We use the builtin `hex` function instead of `int2hex` to + We use the builtin `hex` function instead of `int_to_str` to prepend `0x` to indicate that this **integer** representation is incorrect, but in a format that is easily compared to `str` inputs. """ - if h3IsValid(h) == 0: - raise H3CellError('Integer is not a valid H3 cell: {}'.format(hex(h))) + if isValidCell(h) == 0: + raise H3CellInvalidError('Integer is not a valid H3 cell: {}'.format(hex(h))) cdef check_edge(H3int e): - if h3UnidirectionalEdgeIsValid(e) == 0: - raise H3EdgeError('Integer is not a valid H3 edge: {}'.format(hex(e))) + if isValidDirectedEdge(e) == 0: + raise H3DirEdgeInvalidError('Integer is not a valid H3 edge: {}'.format(hex(e))) + +cdef check_vertex(H3int v): + if isValidVertex(v) == 0: + raise H3VertexInvalidError('Integer is not a valid H3 vertex: {}'.format(hex(v))) + +cdef check_index(H3int h): + if isValidIndex(h) == 0: + raise H3IndexInvalidError('Integer is not a valid H3 index: {}'.format(hex(h))) cdef check_res(int res): if (res < 0) or (res > 15): - raise H3ResolutionError(res) + raise H3ResDomainError(res) cdef check_distance(int k): if k < 0: - raise H3DistanceError( + raise H3DomainError( 'Grid distances must be nonnegative. Received: {}'.format(k) ) - - -## todo: can i turn these two into a context manager? -cdef H3int* create_ptr(size_t n) except? NULL: - cdef H3int* ptr = stdlib.calloc(n, sizeof(H3int)) - if (n > 0) and (not ptr): - raise MemoryError() - - return ptr - - -cdef H3int[:] create_mv(H3int* ptr, size_t n): - cdef: - array x - - n = move_nonzeros(ptr, n) - if n <= 0: - stdlib.free(ptr) - return empty_memory_view() - - ptr = stdlib.realloc(ptr, n*sizeof(H3int)) - - if ptr is NULL: - raise MemoryError() - - x = ptr - x.callback_free_data = stdlib.free - - return x - - -cpdef H3int[:] from_iter(hexes): - """ hexes needs to be an iterable that knows its size... - or should we have it match the np.fromiter function, which infers if not available? - """ - cdef: - array x - size_t n - n = len(hexes) - - if n == 0: - return empty_memory_view() - - x = create_ptr(n) - x.callback_free_data = stdlib.free - - for i,h in enumerate(hexes): - x[i] = h - - return x - - -cdef size_t move_nonzeros(H3int* a, size_t n): - """ Move nonzero elements to front of array `a` of length `n`. - Return the number of nonzero elements. - - Loop invariant: Everything *before* `i` or *after* `j` is "done". - Move `i` and `j` inwards until they equal, and exit. - You can move `i` forward until there's a zero in front of it. - You can move `j` backward until there's a nonzero to the left of it. - Anything to the right of `j` is "junk" that can be reallocated. - - | a | b | 0 | c | d | ... | - ^ ^ - i j - - - | a | b | d | c | d | ... | - ^ ^ - i j - """ - cdef: - size_t i = 0 - size_t j = n - - while i < j: - if a[j-1] == 0: - j -= 1 - continue - - if a[i] != 0: - i += 1 - continue - - # if we're here, we know: - # a[i] == 0 - # a[j-1] != 0 - # i < j - # so we can swap! (actually, move a[j-1] -> a[i]) - a[i] = a[j-1] - j -= 1 - - return i - - -cdef H3int[:] empty_memory_view(): - # there's gotta be a better way to do this... - # create an empty cython.view.array? - cdef: - H3int a[1] - - return (a)[:0] diff --git a/src/h3/_cy/vertex.pxd b/src/h3/_cy/vertex.pxd new file mode 100644 index 0000000..98d890c --- /dev/null +++ b/src/h3/_cy/vertex.pxd @@ -0,0 +1,6 @@ +from .h3lib cimport bool, H3int + +cpdef H3int cell_to_vertex(H3int h, int vertex_num) except 1 +cpdef H3int[:] cell_to_vertexes(H3int h) +cpdef (double, double) vertex_to_latlng(H3int v) except * +cpdef bool is_valid_vertex(H3int v) diff --git a/src/h3/_cy/vertex.pyx b/src/h3/_cy/vertex.pyx new file mode 100644 index 0000000..99cc5ef --- /dev/null +++ b/src/h3/_cy/vertex.pyx @@ -0,0 +1,55 @@ +# cython: freethreading_compatible=True +cimport h3lib +from h3lib cimport bool, H3int + +from .util cimport ( + check_cell, + check_vertex, + coord2deg +) + +from .error_system cimport check_for_error + +from .memory cimport H3MemoryManager + + +cpdef H3int cell_to_vertex(H3int h, int vertex_num) except 1: + cdef: + H3int out + + check_cell(h) + + check_for_error( + h3lib.cellToVertex(h, vertex_num, &out) + ) + + return out + +cpdef H3int[:] cell_to_vertexes(H3int h): + cdef: + H3int out + + check_cell(h) + + hmm = H3MemoryManager(6) + check_for_error( + h3lib.cellToVertexes(h, hmm.ptr) + ) + mv = hmm.to_mv() + + return mv + +cpdef (double, double) vertex_to_latlng(H3int v) except *: + cdef: + h3lib.LatLng c + + check_vertex(v) + + check_for_error( + h3lib.vertexToLatLng(v, &c) + ) + + return coord2deg(c) + +cpdef bool is_valid_vertex(H3int v): + return h3lib.isValidVertex(v) == 1 diff --git a/src/h3/_h3shape.py b/src/h3/_h3shape.py new file mode 100644 index 0000000..68d18c2 --- /dev/null +++ b/src/h3/_h3shape.py @@ -0,0 +1,388 @@ +from abc import ABCMeta, abstractmethod + + +class H3Shape(metaclass=ABCMeta): + """ + Abstract parent class of ``LatLngPoly`` and ``LatLngMultiPoly``. + """ + @property + @abstractmethod + def __geo_interface__(self): + """ https://github.com/pytest-dev/pytest-cov/issues/428 """ + + +class LatLngPoly(H3Shape): + """ + Container for loops of lat/lng points describing a polygon, possibly with holes. + + Attributes + ---------- + outer : list[tuple[float, float]] + List of lat/lng points describing the outer loop of the polygon + + holes : list[list[tuple[float, float]]] + List of loops of lat/lng points describing the holes of the polygon + + Examples + -------- + + A polygon with a single outer ring consisting of 4 points, having no holes: + + >>> LatLngPoly( + ... [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), (37.82, -122.54)], + ... ) + + + The same polygon, but with one hole consisting of 3 points: + + >>> LatLngPoly( + ... [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), (37.82, -122.54)], + ... [(37.76, -122.51), (37.76, -122.44), (37.81, -122.51)], + ... ) + + + The same as above, but with one additional hole, made up of 5 points: + + >>> LatLngPoly( + ... [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), (37.82, -122.54)], + ... [(37.76, -122.51), (37.76, -122.44), (37.81, -122.51)], + ... [(37.71, -122.43), (37.71, -122.37), (37.73, -122.37), (37.75, -122.41), + ... (37.73, -122.43)], + ... ) + + """ + def __init__(self, outer, *holes): + loops = [outer] + list(holes) + for loop in loops: + if len(loop) > 0 and len(_open_ring(loop)) < 3: + raise ValueError('Non-empty LatLngPoly loops need at least 3 points.') + + point_dimensions = set(map(len, loop)) + # empty set is possible for empty polygons, so we check if a subset + if not (point_dimensions <= {2}): + raise ValueError('LatLngPoly only accepts 2D points: lat/lng.') + + self.outer = tuple(_open_ring(outer)) + self.holes = tuple( + _open_ring(hole) + for hole in holes + ) + + def __repr__(self): + return ''.format(self.loopcode) + + def __len__(self): + """ + Should this be the number of points in the outer loop, + the number of holes (or +1 for the outer loop)? + """ + raise NotImplementedError('No clear definition of length for LatLngPoly.') + + @property + def loopcode(self): + """ Short code for describing the length of the outer loop and each hole + + Example: ``[382/(18, 6, 6)]`` indicates an outer loop of 382 points, + along with 3 holes with 18, 6, and 6 points, respectively. + + Example: ``[15]`` indicates an outer loop of 15 points and no holes. + """ + outer = len(self.outer) + holes = tuple(map(len, self.holes)) + + outer = str(outer) + + if holes: + out = outer + '/' + str(holes) + else: + out = outer + + return '[' + out + ']' + + @property + def __geo_interface__(self): + ll2 = _polygon_to_LL2(self) + gj_dict = _LL2_to_geojson_dict(ll2) + + return gj_dict + + +class LatLngMultiPoly(H3Shape): + """ + Container for multiple ``LatLngPoly`` polygons. + + Attributes + ---------- + polys : list[LatLngPoly] + List of lat/lng points describing the outer loop of the polygon + """ + def __init__(self, *polys): + self.polys = tuple(polys) + + for p in self.polys: + if not isinstance(p, LatLngPoly): + raise ValueError('LatLngMultiPoly requires each input to be an LatLngPoly object, instead got: ' + str(p)) # noqa + + def __repr__(self): + out = [p.loopcode for p in self.polys] + out = ', '.join(out) + out = ''.format(out) + return out + + def __iter__(self): + return iter(self.polys) + + def __len__(self): + """ Give the number of polygons in this multi-polygon. + """ + + """ + TODO: Pandas series or dataframe representation changes depending + on if __len__ is defined. + + I'd prefer the one that states `LatLngMultiPoly`. + It seems like Pandas is assuming an iterable is best-described + by its elements when choosing the representation. + + when __len__ *IS NOT* defined: + + 0 + 1 , , ) + 1 (, , , , , , <... + """ + return len(self.polys) + + def __getitem__(self, index): + return self.polys[index] + + @property + def __geo_interface__(self): + ll3 = _mpoly_to_LL3(self) + gj_dict = _LL3_to_geojson_dict(ll3) + + return gj_dict + + +""" +Helpers for cells_to_geojson and geojson_to_cells. + +Dealing with GeoJSON Polygons and MultiPolygons can be confusing because +there are so many nested lists. To help keep track, we use the following +symbols to denote different levels of nesting. + +LL0: lat/lng or lng/lat pair +LL1: list of LL0s +LL2: list of LL1s (i.e., a polygon with holes) +LL3: list of LL2s (i.e., several polygons with holes) +""" + + +def _mpoly_to_LL3(mpoly): + ll3 = tuple( + _polygon_to_LL2(poly) + for poly in mpoly + ) + + return ll3 + + +def _LL3_to_mpoly(ll3): + polys = [ + _LL2_to_polygon(ll2) + for ll2 in ll3 + ] + + mpoly = LatLngMultiPoly(*polys) + + return mpoly + + +def _polygon_to_LL2(poly): + ll2 = [poly.outer] + list(poly.holes) + ll2 = tuple( + _close_ring(_swap_latlng(ll1)) + for ll1 in ll2 + ) + + return ll2 + + +def _remove_z(ll1): + ll1 = [(a, b) for a, b, *z in ll1] + return ll1 + + +def _LL2_to_polygon(ll2): + if len(ll2) == 0: + # empty GeoJSON Polygon, like `shapely.Polygon().__geo_interface__` + return LatLngPoly([]) + + ll2 = [ + _remove_z(ll1) + for ll1 in ll2 + ] + + ll2 = [ + _swap_latlng(ll1) + for ll1 in ll2 + ] + h3poly = LatLngPoly(*ll2) + + return h3poly + + +def _LL2_to_geojson_dict(ll2): + gj_dict = { + 'type': 'Polygon', + 'coordinates': ll2, + } + + return gj_dict + + +def _LL3_to_geojson_dict(ll3): + gj_dict = { + 'type': 'MultiPolygon', + 'coordinates': ll3, + } + + return gj_dict + + +def _swap_latlng(ll1): + ll1 = tuple( + (b, a) for a, b in ll1 + ) + return ll1 + + +def _close_ring(ll1): + """ + Idempotent + """ + if ll1 and (ll1[0] != ll1[-1]): + ll1 = tuple(ll1) + (ll1[0],) + + return ll1 + + +def _open_ring(ll1): + """ + Idempotent + """ + if ll1 and (ll1[0] == ll1[-1]): + ll1 = ll1[:-1] + + return ll1 + + +def geo_to_h3shape(geo): + """ + Translate from ``__geo_interface__`` to H3Shape. + + ``geo`` either implements ``__geo_interface__`` or is a dict matching the format + + Returns + ------- + H3Shape + """ + + # geo can be dict, a __geo_interface__, a string, LatLngPoly or LatLngMultiPoly + if isinstance(geo, H3Shape): + return geo + + if hasattr(geo, '__geo_interface__'): + # get dict + geo = geo.__geo_interface__ + + if not isinstance(geo, dict): + raise ValueError( + 'geo must be a dict or implement __geo_interface__, got: ' + + str(type(geo)) + ) + + t = geo['type'] + coord = geo['coordinates'] + + if t == 'Polygon': + ll2 = coord + shape = _LL2_to_polygon(ll2) + elif t == 'MultiPolygon': + ll3 = coord + shape = _LL3_to_mpoly(ll3) + else: + raise ValueError('Unrecognized type: ' + str(t)) + + return shape + + +def h3shape_to_geo(h3shape, container='auto'): + """ + Translate from an ``H3Shape`` to a ``__geo_interface__`` dict. + + ``h3shape`` should be either ``LatLngPoly`` or ``LatLngMultiPoly`` + + Parameters + ---------- + container : str, optional + Specify the desired GeoJSON output container. + Options: 'auto', 'Polygon', 'MultiPolygon', 'Feature', + 'FeatureCollection', or 'GeometryCollection'. + Default is 'auto' (returns the simplest valid geometry). + + Returns + ------- + dict + """ + base_geo = h3shape.__geo_interface__ + + # Return immediately if no wrapping is needed + if container == 'auto' or container == base_geo['type']: + return base_geo + + # Upgrade a Polygon to a MultiPolygon if explicitly requested + if container == 'MultiPolygon' and base_geo['type'] == 'Polygon': + return { + 'type': 'MultiPolygon', + 'coordinates': (base_geo['coordinates'],) + } + + if container == 'Feature': + return { + 'type': 'Feature', + 'geometry': base_geo, + 'properties': {} + } + + if container == 'FeatureCollection': + return { + 'type': 'FeatureCollection', + 'features': [{ + 'type': 'Feature', + 'geometry': base_geo, + 'properties': {} + }] + } + + if container == 'GeometryCollection': + return { + 'type': 'GeometryCollection', + 'geometries': [base_geo] + } + + # If we reach here, the requested container is either unknown or + # insufficient for the data (e.g., requesting a Polygon for MultiPolygon data). + raise ValueError( + f"Requested container '{container}' is invalid or insufficient " + f"for data of type '{base_geo['type']}'." + ) diff --git a/src/h3/_version.py b/src/h3/_version.py index eb5cae0..712565a 100644 --- a/src/h3/_version.py +++ b/src/h3/_version.py @@ -1,24 +1,3 @@ -__version__ = '3.7.4' -__description__ = 'Hierarchical hexagonal geospatial indexing system' -__url__ = 'https://github.com/uber/h3-py' -__license__ = "Apache 2.0 License" -__author__ = 'Uber Technologies' -__author_email__ = 'AJ Friend ' -__classifiers__ = [ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: C", - "Programming Language :: Cython", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Operating System :: MacOS :: MacOS X", - "Operating System :: POSIX :: Linux", - "Operating System :: Microsoft :: Windows", - "Topic :: Scientific/Engineering :: GIS", -] +from importlib import metadata + +__version__ = metadata.version(__package__ or __name__) diff --git a/src/h3/api/__init__.py b/src/h3/api/__init__.py index 9bc858a..435b13a 100644 --- a/src/h3/api/__init__.py +++ b/src/h3/api/__init__.py @@ -3,3 +3,4 @@ from . import basic_int from . import basic_str from . import memview_int +from . import numpy_int diff --git a/src/h3/api/_api_template.py b/src/h3/api/_api_template.py deleted file mode 100644 index 499c040..0000000 --- a/src/h3/api/_api_template.py +++ /dev/null @@ -1,980 +0,0 @@ -""" -Module to DRY-up code which is repeated across API modules. - -Definitions of types --------------------- -H3Index: - An unsigned 64-bit integer representing a valid H3 cell or - unidirectional edge. - Depending on the API, an H3Index may be represented as an - unsigned integer type, or as a hexadecimal string. - -H3 cell: - A pentagon or hexagon that can be represented by an H3Index. - -H3Cell: - H3Index representation of an H3 cell. - -H3Edge: - H3Index representation of an H3 unidirectional edge. - - -Definitions of collections --------------------------- -Collection types vary between APIs. We'll use the following terms: - -unordered collection: - Inputs and outputs are interpreted as *unordered* collections. - Examples: `set`, `numpy.ndarray`. - -ordered collection: - Inputs and outputs are interpreted as *ordered* collections. - Examples: `list`, `numpy.ndarray`. - -Notes --------------------- -todo: how do we lint these functions and docstrings? it seems to currently -be skipped due to it being inside the `_api_functions` function. -""" - -from .. import _cy - - -class _API_FUNCTIONS(object): - def __init__( - self, - _in_scalar, - _out_scalar, - _in_collection, - _out_unordered, - _out_ordered, - ): - self._in_scalar = _in_scalar - self._out_scalar = _out_scalar - self._in_collection = _in_collection - self._out_unordered = _out_unordered - self._out_ordered = _out_ordered - - @staticmethod - def versions(): - """ - Version numbers for the Python (wrapper) and C (wrapped) libraries. - - Versions are output as strings of the form ``'X.Y.Z'``. - C and Python should match on ``X`` (major) and ``Y`` (minor), - but may differ on ``Z`` (patch). - - Returns - ------- - dict like ``{'c': 'X.Y.Z', 'python': 'A.B.C'}`` - """ - from .._version import __version__ - - v = { - 'c': _cy.c_version(), - 'python': __version__, - } - - return v - - @staticmethod - def string_to_h3(h): - """ - Converts a hexadecimal string to an H3 64-bit integer index. - - Parameters - ---------- - h : str - Hexadecimal string like ``'89754e64993ffff'`` - - Returns - ------- - int - Unsigned 64-bit integer - """ - return _cy.hex2int(h) - - @staticmethod - def h3_to_string(x): - """ - Converts an H3 64-bit integer index to a hexadecimal string. - - Parameters - ---------- - x : int - Unsigned 64-bit integer - - Returns - ------- - str - Hexadecimal string like ``'89754e64993ffff'`` - """ - return _cy.int2hex(x) - - @staticmethod - def num_hexagons(resolution): - """ - Return the total number of *cells* (hexagons and pentagons) - for the given resolution. - - Returns - ------- - int - """ - return _cy.num_hexagons(resolution) - - @staticmethod - def hex_area(resolution, unit='km^2'): - """ - Return the average area of an H3 *hexagon* - for the given resolution. - - This average *excludes* pentagons. - - Returns - ------- - float - """ - # todo: `mean_hex_area` in 4.0 - return _cy.mean_hex_area(resolution, unit) - - @staticmethod - def edge_length(resolution, unit='km'): - """ - Return the average *hexagon* edge length - for the given resolution. - - This average *excludes* pentagons. - - Returns - ------- - float - """ - # todo: `mean_edge_length` in 4.0 - return _cy.mean_edge_length(resolution, unit) - - def h3_is_valid(self, h): - """ - Validates an H3 cell (hexagon or pentagon). - - Returns - ------- - bool - """ - try: - h = self._in_scalar(h) - return _cy.is_cell(h) - except (ValueError, TypeError): - return False - - def h3_unidirectional_edge_is_valid(self, edge): - """ - Validates an H3 unidirectional edge. - - Returns - ------- - bool - """ - try: - e = self._in_scalar(edge) - return _cy.is_edge(e) - except (ValueError, TypeError): - return False - - def geo_to_h3(self, lat, lng, resolution): - """ - Return the cell containing the (lat, lng) point - for a given resolution. - - Returns - ------- - H3Cell - - """ - return self._out_scalar(_cy.geo_to_h3(lat, lng, resolution)) - - def h3_to_geo(self, h): - """ - Return the center point of an H3 cell as a lat/lng pair. - - Parameters - ---------- - h : H3Cell - - Returns - ------- - lat : float - Latitude - lng : float - Longitude - """ - return _cy.h3_to_geo(self._in_scalar(h)) - - def h3_get_resolution(self, h): - """ - Return the resolution of an H3 cell. - - Parameters - ---------- - h : H3Cell - - Returns - ------- - int - """ - # todo: could also work for edges - return _cy.resolution(self._in_scalar(h)) - - def h3_to_parent(self, h, res=None): - """ - Get the parent of a cell. - - Parameters - ---------- - h : H3Cell - res : int or None, optional - The resolution for the parent - If ``None``, then ``res = resolution(h) - 1`` - - Returns - ------- - H3Cell - """ - h = self._in_scalar(h) - p = _cy.parent(h, res) - p = self._out_scalar(p) - - return p - - def h3_distance(self, h1, h2): - """ - Compute the H3 distance between two cells. - - The H3 distance is defined as the length of the shortest - path between the cells in the graph formed by connecting - adjacent cells. - - This function will return an H3ValueError if the - cells are too far apart to compute the distance. - - Parameters - ---------- - h1 : H3Cell - h2 : H3Cell - - Returns - ------- - int - """ - h1 = self._in_scalar(h1) - h2 = self._in_scalar(h2) - - d = _cy.distance(h1, h2) - - return d - - def h3_to_geo_boundary(self, h, geo_json=False): - """ - Return tuple of lat/lng pairs describing the cell boundary. - - Parameters - ---------- - h : H3Cell - geo_json : bool, optional - If ``True``, return output in GeoJson format: - lng/lat pairs (opposite order), and - have the last pair be the same as the first. - If ``False`` (default), return lat/lng pairs, with the last - pair distinct from the first. - - Returns - ------- - tuple of (float, float) tuples - """ - return _cy.cell_boundary(self._in_scalar(h), geo_json) - - def k_ring(self, h, k=1): - """ - Return unordered set of cells with H3 distance ``<= k`` from ``h``. - That is, the "filled-in" disk. - - Parameters - ---------- - h : H3Cell - k : int - Size of disk. - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.disk(self._in_scalar(h), k) - - return self._out_unordered(mv) - - def hex_range(self, h, k=1): - """ - Alias for `k_ring`. - "Filled-in" disk. - - Notes - ----- - This name differs from the C API. - """ - mv = _cy.disk(self._in_scalar(h), k) - - return self._out_unordered(mv) - - def hex_ring(self, h, k=1): - """ - Return unordered set of cells with H3 distance ``== k`` from ``h``. - That is, the "hollow" ring. - - Parameters - ---------- - h : H3Cell - k : int - Size of ring. - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.ring(self._in_scalar(h), k) - - return self._out_unordered(mv) - - def hex_range_distances(self, h, K): - """ - Ordered list of the "hollow" rings around ``h``, - up to and including distance ``K``. - - Parameters - ---------- - h : H3Cell - K : int - Largest distance considered. - - Returns - ------- - ordered collection of (unordered collection of H3Cell) - """ - h = self._in_scalar(h) - - out = [ - self._out_unordered(_cy.ring(h, k)) - for k in range(K + 1) - ] - - return out - - def hex_ranges(self, hexes, K): - """ - Returns the dictionary ``{h: hex_range_distances(h, K) for h in hexes}`` - - Returns - ------- - Dict[H3Cell, List[ UnorderedCollection[H3Cell] ]] - """ - # todo: can we drop this function? the user can implement if needed. - # TODO: should we call `out_scalar` on the dict keys? - out = {h: self.hex_range_distances(h, K) for h in hexes} - - return out - - def k_ring_distances(self, h, K): - """Alias for `hex_range_distances`.""" - return self.hex_range_distances(h, K) - - def h3_to_children(self, h, res=None): - """ - Children of a hexagon. - - Parameters - ---------- - h : H3Cell - res : int or None, optional - The resolution for the children. - If ``None``, then ``res = resolution(h) + 1`` - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.children(self._in_scalar(h), res) - - return self._out_unordered(mv) - - # todo: nogil for expensive C operation? - def compact(self, hexes): - """ - Compact a collection of H3 cells by combining - smaller cells into larger cells, if all child cells - are present. - - Parameters - ---------- - hexes : iterable of H3Cell - - Returns - ------- - unordered collection of H3Cell - """ - # todo: does compact work on mixed-resolution collections? - hu = self._in_collection(hexes) - hc = _cy.compact(hu) - - return self._out_unordered(hc) - - def uncompact(self, hexes, res): - """ - Reverse the `compact` operation. - - Return a collection of H3 cells, all of resolution ``res``. - - Parameters - ---------- - hexes : iterable of H3Cell - res : int - Resolution of desired output cells. - - Returns - ------- - unordered collection of H3Cell - - Raises - ------ - todo: add test to make sure an error is returned when input - contains hex smaller than output res. - https://github.com/uber/h3/blob/master/src/h3lib/lib/h3Index.c#L425 - """ - hc = self._in_collection(hexes) - hu = _cy.uncompact(hc, res) - - return self._out_unordered(hu) - - def h3_set_to_multi_polygon(self, hexes, geo_json=False): - """ - Get GeoJSON-like MultiPolygon describing the outline of the area - covered by a set of H3 cells. - - Parameters - ---------- - hexes : unordered collection of H3Cell - geo_json : bool, optional - If `True`, output geo sequences will be lng/lat pairs, with the - last the same as the first. - If `False`, output geo sequences will be lat/lng pairs, with the - last distinct from the first. - Defaults to `False` - - Returns - ------- - list - List of "polygons". - Each polygon is a list of "geo sequences" like - ``[outer, hole1, hole2, ...]``. The holes may not be present. - Each geo sequence is a list of lat/lng or lng/lat pairs. - """ - # todo: this function output does not match with `polyfill`. - # This function returns a list of polygons, while `polyfill` returns - # a GeoJSON-like dictionary object. - hexes = self._in_collection(hexes) - return _cy.h3_set_to_multi_polygon(hexes, geo_json=geo_json) - - def polyfill_polygon(self, outer, res, holes=None, lnglat_order=False): - mv = _cy.polyfill_polygon(outer, res, holes=holes, lnglat_order=lnglat_order) - - return self._out_unordered(mv) - - def polyfill_geojson(self, geojson, res): - mv = _cy.polyfill_geojson(geojson, res) - - return self._out_unordered(mv) - - def polyfill(self, geojson, res, geo_json_conformant=False): - """ - Get set of hexagons whose *centers* are contained within - a GeoJSON-style polygon. - - Parameters - ---------- - geojson : dict - GeoJSON-style input dictionary describing a polygon (optionally - including holes). - - Dictionary should be formatted like: - - .. code-block:: text - - { - 'type': 'Polygon', - 'coordinates': [outer, hole1, hole2, ...], - } - - `outer`, `hole1`, etc., are lists of geo coordinate tuples. - The holes are optional. - - res : int - Desired output resolution for cells. - geo_json_conformant : bool, optional - When ``True``, ``outer``, ``hole1``, etc. must be sequences of - lng/lat pairs, with the last the same as the first. - When ``False``, they must be sequences of lat/lng pairs, - with the last not needing to match the first. - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.polyfill(geojson, res, geo_json_conformant=geo_json_conformant) - - return self._out_unordered(mv) - - def h3_is_pentagon(self, h): - """ - Identify if an H3 cell is a pentagon. - - Parameters - ---------- - h : H3Index - - Returns - ------- - bool - ``True`` if input is a valid H3 cell which is a pentagon. - - Notes - ----- - A pentagon should *also* pass ``h3_is_cell()``. - Will return ``False`` for valid H3Edge. - """ - return _cy.is_pentagon(self._in_scalar(h)) - - def h3_get_base_cell(self, h): - """ - Return the base cell *number* (``0`` to ``121``) of the given cell. - - The base cell *number* and the H3Index are two different representations - of the same cell: the parent cell of resolution ``0``. - - The base cell *number* is encoded within the corresponding - H3Index. - - todo: could work with edges - - Parameters - ---------- - h : H3Cell - - Returns - ------- - int - """ - return _cy.get_base_cell(self._in_scalar(h)) - - def h3_indexes_are_neighbors(self, h1, h2): - """ - Returns ``True`` if ``h1`` and ``h2`` are neighboring cells. - - Parameters - ---------- - h1 : H3Cell - h2 : H3Cell - - Returns - ------- - bool - """ - h1 = self._in_scalar(h1) - h2 = self._in_scalar(h2) - - return _cy.are_neighbors(h1, h2) - - def get_h3_unidirectional_edge(self, origin, destination): - """ - Create an H3 Index denoting a unidirectional edge. - - The edge is constructed from neighboring cells ``origin`` and - ``destination``. - - Parameters - ---------- - origin : H3Cell - destination : H3Cell - - Raises - ------ - ValueError - When cells are not adjacent. - - Returns - ------- - H3Edge - """ - o = self._in_scalar(origin) - d = self._in_scalar(destination) - e = _cy.edge(o, d) - e = self._out_scalar(e) - - return e - - def get_origin_h3_index_from_unidirectional_edge(self, e): - """ - Origin cell from an H3 directed edge. - - Parameters - ---------- - e : H3Edge - - Returns - ------- - H3Cell - """ - e = self._in_scalar(e) - o = _cy.edge_origin(e) - o = self._out_scalar(o) - - return o - - def get_destination_h3_index_from_unidirectional_edge(self, e): - """ - Destination cell from an H3 directed edge. - - Parameters - ---------- - e : H3Edge - - Returns - ------- - H3Cell - """ - e = self._in_scalar(e) - d = _cy.edge_destination(e) - d = self._out_scalar(d) - - return d - - def get_h3_indexes_from_unidirectional_edge(self, e): - """ - Return (origin, destination) tuple from H3 directed edge - - Parameters - ---------- - e : H3Edge - - Returns - ------- - H3Cell - Origin cell of edge - H3Cell - Destination cell of edge - """ - e = self._in_scalar(e) - o, d = _cy.edge_cells(e) - o, d = self._out_scalar(o), self._out_scalar(d) - - return o, d - - def get_h3_unidirectional_edges_from_hexagon(self, origin): - """ - Return all directed edges starting from ``origin`` cell. - - Parameters - ---------- - origin : H3Cell - - Returns - ------- - unordered collection of H3Edge - """ - mv = _cy.edges_from_cell(self._in_scalar(origin)) - - return self._out_unordered(mv) - - def get_h3_unidirectional_edge_boundary(self, edge, geo_json=False): - return _cy.edge_boundary(self._in_scalar(edge), geo_json=geo_json) - - def h3_line(self, start, end): - """ - Returns the ordered collection of cells denoting a - minimum-length non-unique path between cells. - - Parameters - ---------- - start : H3Cell - end : H3Cell - - Returns - ------- - ordered collection of H3Cell - Starting with ``start``, and ending with ``end``. - """ - mv = _cy.line(self._in_scalar(start), self._in_scalar(end)) - - return self._out_ordered(mv) - - def h3_is_res_class_III(self, h): - """ - Determine if cell has orientation "Class II" or "Class III". - - The orientation of pentagons/hexagons on the icosahedron can be one - of two types: "Class II" or "Class III". - - All cells within a resolution have the same type, and the type - alternates between resolutions. - - "Class II" cells have resolutions: 0,2,4,6,8,10,12,14 - "Class III" cells have resolutions: 1,3,5,7,9,11,13,15 - - Parameters - ---------- - h : H3Cell - - Returns - ------- - bool - ``True`` if ``h`` is "Class III". - ``False`` if ``h`` is "Class II". - - References - ---------- - 1. https://uber.github.io/h3/#/documentation/core-library/coordinate-systems - """ - return _cy.is_res_class_iii(self._in_scalar(h)) - - def h3_is_res_class_iii(self, h): - """Alias for `h3_is_res_class_III`.""" - return self.h3_is_res_class_III(h) - - def get_pentagon_indexes(self, resolution): - """ - Return all pentagons at a given resolution. - - Parameters - ---------- - resolution : int - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.get_pentagon_indexes(resolution) - - return self._out_unordered(mv) - - def get_res0_indexes(self): - """ - Return all cells at resolution 0. - - Parameters - ---------- - None - - Returns - ------- - unordered collection of H3Cell - """ - mv = _cy.get_res0_indexes() - - return self._out_unordered(mv) - - def h3_to_center_child(self, h, res=None): - """ - Get the center child of a cell at some finer resolution. - - Parameters - ---------- - h : H3Cell - res : int or None, optional - The resolution for the child cell - If ``None``, then ``res = resolution(h) + 1`` - - Returns - ------- - H3Cell - """ - h = self._in_scalar(h) - p = _cy.center_child(h, res) - p = self._out_scalar(p) - - return p - - def h3_get_faces(self, h): - """ - Return icosahedron faces intersecting a given H3 cell. - - There are twenty possible faces, ranging from 0--19. - - Note: Every interface returns a Python ``set`` of ``int``. - - Parameters - ---------- - h : H3Cell - - Returns - ------- - Python ``set`` of ``int`` - """ - h = self._in_scalar(h) - faces = _cy.get_faces(h) - - return faces - - def experimental_h3_to_local_ij(self, origin, h): - """ - Return local (i,j) coordinates of cell ``h`` in relation to ``origin`` cell - - - Parameters - ---------- - origin : H3Cell - Origin/central cell for defining i,j coordinates. - h: H3Cell - Destination cell whose i,j coordinates we'd like, based off - of the origin cell. - - - Returns - ------- - Tuple (i, j) of integer local coordinates of cell ``h`` - - - Notes - ----- - - The ``origin`` cell does not define (0, 0) for the IJ coordinate space. - (0, 0) refers to the center of the base cell containing origin at the - resolution of `origin`. - Subtracting the IJ coordinates of ``origin`` from every cell would get - you the property of (0, 0) being the ``origin``. - - This is done so we don't need to keep recomputing the coordinates of - ``origin`` if not needed. - """ - origin = self._in_scalar(origin) - h = self._in_scalar(h) - - i, j = _cy.experimental_h3_to_local_ij(origin, h) - - return i, j - - def experimental_local_ij_to_h3(self, origin, i, j): - """ - Return cell at local (i,j) position relative to the ``origin`` cell. - - Parameters - ---------- - origin : H3Cell - Origin/central cell for defining i,j coordinates. - i, j: int - Integer coordinates with respect to ``origin`` cell. - - - Returns - ------- - H3Cell at local (i,j) position relative to the ``origin`` cell - - - Notes - ----- - - The ``origin`` cell does not define (0, 0) for the IJ coordinate space. - (0, 0) refers to the center of the base cell containing origin at the - resolution of ``origin``. - Subtracting the IJ coordinates of ``origin`` from every cell would get - you the property of (0, 0) being the ``origin``. - - This is done so we don't need to keep recomputing the coordinates of - ``origin`` if not needed. - """ - origin = self._in_scalar(origin) - - h = _cy.experimental_local_ij_to_h3(origin, i, j) - h = self._out_scalar(h) - - return h - - def cell_area(self, h, unit='km^2'): - """ - Compute the spherical surface area of a specific H3 cell. - - Parameters - ---------- - h : H3Cell - unit: str - Unit for area result (``'km^2'``, 'm^2', or 'rads^2') - - - Returns - ------- - The area of the H3 cell in the given units - - - Notes - ----- - This function breaks the cell into spherical triangles, and computes - their spherical area. - The function uses the spherical distance calculation given by - `point_dist`. - """ - h = self._in_scalar(h) - - return _cy.cell_area(h, unit=unit) - - def exact_edge_length(self, e, unit='km'): - """ - Compute the spherical length of a specific H3 edge. - - Parameters - ---------- - h : H3Cell - unit: str - Unit for length result ('km', 'm', or 'rads') - - - Returns - ------- - The length of the edge in the given units - - - Notes - ----- - This function uses the spherical distance calculation given by - `point_dist`. - """ - e = self._in_scalar(e) - - return _cy.edge_length(e, unit=unit) - - @staticmethod - def point_dist(point1, point2, unit='km'): - """ - Compute the spherical distance between two (lat, lng) points. - - todo: do we handle lat/lng points consistently in the api? what - about (lat1, lng1, lat2, lng2) as the input? How will this work - for vectorized versions? - - Parameters - ---------- - point1 : tuple - (lat, lng) tuple in degrees - point2 : tuple - (lat, lng) tuple in degrees - unit: str - Unit for distance result ('km', 'm', or 'rads') - - - Returns - ------- - Spherical (or "haversine") distance between the points - """ - lat1, lng1 = point1 - lat2, lng2 = point2 - - return _cy.point_dist( - lat1, lng1, - lat2, lng2, - unit=unit - ) diff --git a/src/h3/api/basic_int/__init__.py b/src/h3/api/basic_int/__init__.py index 977b40b..8eac4b1 100644 --- a/src/h3/api/basic_int/__init__.py +++ b/src/h3/api/basic_int/__init__.py @@ -1 +1,1392 @@ -from ._public_api import * # noqa +# This file is **symlinked** across the APIs to ensure they are exactly the same. +from typing import Literal +from array import array + +from ... import _cy +from ..._h3shape import ( + H3Shape, + LatLngPoly, + LatLngMultiPoly, + geo_to_h3shape, + h3shape_to_geo, +) + +from ._convert import ( + _in_scalar, + _out_scalar, + _in_collection, + _out_collection, +) + + +def versions(): + """ + Version numbers for the Python (wrapper) and C (wrapped) libraries. + + Versions are output as strings of the form ``'X.Y.Z'``. + C and Python should match on ``X`` (major) and ``Y`` (minor), + but may differ on ``Z`` (patch). + + Returns + ------- + dict like ``{'c': 'X.Y.Z', 'python': 'A.B.C'}`` + """ + from ..._version import __version__ + + v = { + 'c': _cy.c_version(), + 'python': __version__, + } + + return v + + +def str_to_int(h): + """ + Converts a hexadecimal string to an H3 64-bit integer index. + + Parameters + ---------- + h : str + Hexadecimal string like ``'89754e64993ffff'`` + + Returns + ------- + int + Unsigned 64-bit integer + """ + return _cy.str_to_int(h) + + +def int_to_str(x): + """ + Converts an H3 64-bit integer index to a hexadecimal string. + + Parameters + ---------- + x : int + Unsigned 64-bit integer + + Returns + ------- + str + Hexadecimal string like ``'89754e64993ffff'`` + """ + return _cy.int_to_str(x) + + +def get_num_cells(res): + """ + Return the total number of *cells* (hexagons and pentagons) + for the given resolution. + + Returns + ------- + int + """ + return _cy.get_num_cells(res) + + +def average_hexagon_area(res, unit='km^2'): + """ + Return the average area of an H3 *hexagon* + for the given resolution. + + This average *excludes* pentagons. + + Parameters + ---------- + res : int + H3 resolution + unit: str + Unit for area result (``'km^2'``, ``'m^2'``, or ``'rads^2'``) + + Returns + ------- + float + """ + return _cy.average_hexagon_area(res, unit) + + +def average_hexagon_edge_length(res, unit='km'): + """ + Return the average *hexagon* edge length + for the given resolution. + + This average *excludes* pentagons. + + Parameters + ---------- + res : int + H3 resolution + unit: str + Unit for length result (``'km'``, ``'m'``, or ``'rads'``) + + Returns + ------- + float + """ + return _cy.average_hexagon_edge_length(res, unit) + + +def is_valid_index(h): + """Validates *any* H3 index (cell, vertex, or directed edge). + + Returns + ------- + bool + """ + try: + h = _in_scalar(h) + return _cy.is_valid_index(h) + except (ValueError, TypeError, OverflowError): + return False + + +def is_valid_cell(h): + """ + Validates an H3 cell (hexagon or pentagon). + + Returns + ------- + bool + """ + try: + h = _in_scalar(h) + return _cy.is_valid_cell(h) + except (ValueError, TypeError, OverflowError): + return False + + +def is_valid_directed_edge(edge): + """ + Validates an H3 directed edge. + + Returns + ------- + bool + """ + try: + e = _in_scalar(edge) + return _cy.is_valid_directed_edge(e) + except (ValueError, TypeError, OverflowError): + return False + + +def latlng_to_cell(lat, lng, res): + """ + Return the cell containing the (lat, lng) point + for a given resolution. + + Returns + ------- + H3Cell + + """ + return _out_scalar(_cy.latlng_to_cell(lat, lng, res)) + + +def cell_to_latlng(h): + """ + Return the center point of an H3 cell as a lat/lng pair. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + lat : float + Latitude + lng : float + Longitude + """ + h = _in_scalar(h) + return _cy.cell_to_latlng(h) + + +def get_resolution(h): + """ + Return the resolution of an H3 cell. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + int + """ + # todo: could also work for edges + h = _in_scalar(h) + return _cy.get_resolution(h) + + +def cell_to_parent(h, res=None): + """ + Get the parent of a cell. + + Parameters + ---------- + h : H3Cell + res : int or None, optional + The resolution for the parent + If ``None``, then ``res = resolution(h) - 1`` + + Returns + ------- + H3Cell + """ + h = _in_scalar(h) + p = _cy.cell_to_parent(h, res) + p = _out_scalar(p) + + return p + + +def grid_distance(h1, h2): + """ + Compute the grid distance between two cells. + + The grid distance is defined as the length of the shortest + path between the cells in the graph formed by connecting + adjacent cells. + + This function will raise an exception if the + cells are too far apart to compute the distance. + + Parameters + ---------- + h1 : H3Cell + h2 : H3Cell + + Returns + ------- + int + """ + h1 = _in_scalar(h1) + h2 = _in_scalar(h2) + + d = _cy.grid_distance(h1, h2) + + return d + + +def cell_to_boundary(h): + """ + Return tuple of lat/lng pairs describing the cell boundary. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + tuple of (lat, lng) tuples + """ + h = _in_scalar(h) + return _cy.cell_to_boundary(h) + + +def grid_disk(h, k=1): + """ + Return unordered collection of cells with grid distance ``<= k`` from ``h``. + That is, the "filled-in" disk. + + Parameters + ---------- + h : H3Cell + k : int + Size of disk. + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + h = _in_scalar(h) + mv = _cy.grid_disk(h, k) + + return _out_collection(mv) + + +def grid_ring(h, k=1): + """ + Return unordered collection of cells with grid distance ``== k`` from ``h``. + That is, the "hollow" ring. + + Parameters + ---------- + h : H3Cell + k : int + Size of ring. + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + h = _in_scalar(h) + mv = _cy.grid_ring(h, k) + + return _out_collection(mv) + + +def cell_to_children_size(h, res=None): + """ + Number of children at resolution ``res`` of given cell. + + Parameters + ---------- + h : H3Cell + res : int or None, optional + The resolution for the children. + If ``None``, then ``res = resolution(h) + 1`` + + Returns + ------- + int + Count of children + """ + h = _in_scalar(h) + return _cy.cell_to_children_size(h, res) + + +def cell_to_children(h, res=None): + """ + Children of a cell as an unordered collection. + + Parameters + ---------- + h : H3Cell + res : int or None, optional + The resolution for the children. + If ``None``, then ``res = resolution(h) + 1`` + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + h = _in_scalar(h) + mv = _cy.cell_to_children(h, res) + + return _out_collection(mv) + + +def cell_to_child_pos(child, res_parent): + """ + Child position index of given cell, with respect to its parent at ``res_parent``. + + The reverse operation can be done with ``child_pos_to_cell``. + + Parameters + ---------- + child : H3Cell + res_parent : int + + Returns + ------- + int + Integer index of the child with respect to parent cell. + """ + child = _in_scalar(child) + return _cy.cell_to_child_pos(child, res_parent) + + +def child_pos_to_cell(parent, res_child, child_pos): + """ + Get child H3 cell from a parent cell, child resolution, and child position index. + + The reverse operation can be done with ``cell_to_child_pos``. + + Parameters + ---------- + parent : H3Cell + res_child : int + Child cell resolution + child_pos : int + Integer position of child cell, releative to parent. + + + Returns + ------- + H3Cell + """ + parent = _in_scalar(parent) + child = _cy.child_pos_to_cell(parent, res_child, child_pos) + child = _out_scalar(child) + + return child + + +# todo: nogil for expensive C operation? +def compact_cells(cells): + """ + Compact a collection of H3 cells by combining + smaller cells into larger cells, if all child cells + are present. Input cells must all share the same resolution. + + Parameters + ---------- + cells : iterable of H3 Cells + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + hu = _in_collection(cells) + hc = _cy.compact_cells(hu) + + return _out_collection(hc) + + +def uncompact_cells(cells, res): + """ + Reverse the ``compact_cells`` operation. + + Return a collection of H3 cells, all of resolution ``res``. + + Parameters + ---------- + cells : iterable of H3Cell + res : int + Resolution of desired output cells. + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + + hc = _in_collection(cells) + hu = _cy.uncompact_cells(hc, res) + + return _out_collection(hu) + + +def polygon_to_cells(h3shape, res): + """ + Alias for ``h3shape_to_cells``. + """ + return h3shape_to_cells(h3shape, res) + + +def h3shape_to_cells(h3shape, res): + """ + Return the collection of H3 cells at a given resolution whose center points + are contained within an ``LatLngPoly`` or ``LatLngMultiPoly``. + + Parameters + ---------- + h3shape : ``H3Shape`` + res : int + Resolution of the output cells + + Returns + ------- + list of H3Cell + + Examples + -------- + + >>> poly = LatLngPoly( + ... [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), + ... (37.82, -122.54)], + ... ) + >>> h3.h3shape_to_cells(poly, 6) + ['862830807ffffff', + '862830827ffffff', + '86283082fffffff', + '862830877ffffff', + '862830947ffffff', + '862830957ffffff', + '86283095fffffff'] + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + + # todo: not sure if i want this dispatch logic here. maybe in the objects? + if isinstance(h3shape, LatLngPoly): + poly = h3shape + mv = _cy.polygon_to_cells(poly.outer, res=res, holes=poly.holes) + elif isinstance(h3shape, LatLngMultiPoly): + mpoly = h3shape + mv = _cy.polygons_to_cells(mpoly.polys, res=res) + elif isinstance(h3shape, H3Shape): + raise ValueError('Unrecognized H3Shape: ' + str(h3shape)) + else: + raise ValueError('Unrecognized type: ' + str(type(h3shape))) + + return _out_collection(mv) + + +def polygon_to_cells_experimental( + h3shape: H3Shape, + res: int, + contain: Literal['center', 'full', 'overlap', 'bbox_overlap'] = 'center', +): + """ + Alias for ``h3shape_to_cells_experimental``. + """ + return h3shape_to_cells_experimental(h3shape, res, contain) + + +def h3shape_to_cells_experimental( + h3shape: H3Shape, + res: int, + contain: Literal['center', 'full', 'overlap', 'bbox_overlap'] = 'center', +): + """ + Experimental function similar to ``h3shape_to_cells``, but with support for + multiple cell containment modes. + + Using ``contain='center'`` should give identical behavior as + ``h3shape_to_cells``. + + Note that this function is **experimental** and has no API stability gaurantees + across versions, so it may change in the future. + + + Parameters + ---------- + h3shape : ``H3Shape`` + res : int + Resolution of the output cells + contain : {'center', 'full', 'overlap', 'bbox_overlap'}, optional + Specifies the containment condition. + - 'center': Cell center is contained in shape + - 'full': Cell is fully contained in shape + - 'overlap': Cell is partially contained in shape + - 'bbox_overlap': Cell bounding box is partially contained in shape + + Default is 'center'. + + Returns + ------- + list of H3Cell + + Examples + -------- + + >>> poly = LatLngPoly( + ... [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), + ... (37.82, -122.54)], + ... ) + >>> h3.h3shape_to_cells_experimental(poly, 6, 'center') + ['862830807ffffff', + '862830827ffffff', + '86283082fffffff', + '862830877ffffff', + '862830947ffffff', + '862830957ffffff', + '86283095fffffff'] + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + + contain_modes = { + 'center': 0, + 'full': 1, + 'overlap': 2, + 'bbox_overlap': 3, + } + + flag = contain_modes[contain] + + # todo: not sure if i want this dispatch logic here. maybe in the objects? + if isinstance(h3shape, LatLngPoly): + poly = h3shape + mv = _cy.polygon_to_cells_experimental( + poly.outer, + res = res, + holes = poly.holes, + flag = flag, + ) + elif isinstance(h3shape, LatLngMultiPoly): + mpoly = h3shape + mv = _cy.polygons_to_cells_experimental(mpoly.polys, res=res, flag=flag) + elif isinstance(h3shape, H3Shape): + raise ValueError('Unrecognized H3Shape: ' + str(h3shape)) + else: + raise ValueError('Unrecognized type: ' + str(type(h3shape))) + + return _out_collection(mv) + + +def cells_to_h3shape(cells, *, tight=True): + """ + Return an ``H3Shape`` describing the area covered by a collection of H3 cells. + Will return ``LatLngPoly`` or ``LatLngMultiPoly``. + + Parameters + ---------- + cells : iterable of H3 cells + tight : bool + If True, return ``LatLngPoly`` if possible. + If False, always return ``LatLngMultiPoly``. + + Returns + ------- + LatLngPoly | LatLngMultiPoly + + Examples + -------- + + >>> cells = ['8428309ffffffff', '842830dffffffff'] + >>> h3.cells_to_h3shape(cells, tight=True) + + >>> h3.cells_to_h3shape(cells, tight=False) + + """ + cells = _in_collection(cells) + mpoly = _cy.cells_to_multi_polygon(cells) + + polys = [LatLngPoly(*poly) for poly in mpoly] + out = LatLngMultiPoly(*polys) + + if tight and len(out) == 1: + out = out[0] + + return out + + +def geo_to_cells(geo, res): + """Convert from ``__geo_interface__`` to cells. + + Parameters + ---------- + geo : an object implementing ``__geo_interface__`` or a dictionary in that format. + Both ``LatLngPoly`` and ``LatLngMultiPoly`` implement the interface. + res : int + Resolution of desired output cells. + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + h3shape = geo_to_h3shape(geo) + return h3shape_to_cells(h3shape, res) + + +def cells_to_geo(cells, tight=True): + """ + Convert from cells to a ``__geo_interface__`` dict. + + Parameters + ---------- + cells : iterable of H3 Cells + tight : bool + When ``True``, returns an ``LatLngPoly`` when possible. + When ``False``, always returns an ``LatLngMultiPoly``. + + Returns + ------- + dict + in `__geo_interface__` format + """ + h3shape = cells_to_h3shape(cells, tight=tight) + return h3shape_to_geo(h3shape) + + +def is_pentagon(h): + """ + Identify if an H3 cell is a pentagon. + + Parameters + ---------- + h : H3Index + + Returns + ------- + bool + ``True`` if input is a valid H3 cell which is a pentagon. + + Notes + ----- + A pentagon should *also* pass ``is_valid_cell()``. + Will return ``False`` for valid H3Edge. + """ + return _cy.is_pentagon(_in_scalar(h)) + + +def get_base_cell_number(h): + """ + Return the base cell *number* (``0`` to ``121``) of the given cell. + + The base cell *number* and the H3Index are two different representations + of the same cell: the parent cell of resolution ``0``. + + The base cell *number* is encoded within the corresponding + H3Index. + + todo: could work with edges + + Parameters + ---------- + h : H3Cell + + Returns + ------- + int + + Examples + -------- + >>> h = construct_cell(57, 2, 1, 4) + >>> h + '83728cfffffffff' + >> get_base_cell_number(h) + 57 + """ + return _cy.get_base_cell_number(_in_scalar(h)) + + +def get_index_digit(h, res): + """ + Get the index digit of a cell at the given resolution. + + Parameters + ---------- + h : H3Cell + Cell whose index digit will be returned. + res : int + Resolution (``>= 1``) at which to read the digit. + + Returns + ------- + int + The index digit at the requested resolution. + + Examples + -------- + >>> h = construct_cell(7, 2, 1, 4) + >>> h + '830e8cfffffffff' + >>> get_index_digit(h, 1) + 2 + >>> get_index_digit(h, 2) + 1 + >>> get_index_digit(h, 3) + 4 + """ + return _cy.get_index_digit(_in_scalar(h), res) + + +def construct_cell(base_cell_number, *digits, res=None): + """ + Construct cell from base cell and digits. + + Parameters + ---------- + base_cell_number : int + Base cell *number* (``0`` to ``121``). + *digits : int + Sequence of index digits (``0`` to ``6``). + Length of digits will be the resulting resolution of the output cell. + res : int, optional + Resolution of the constructed cell. If provided, it must equal + ``len(digits)``; otherwise it is inferred from the number of digits. + + Returns + ------- + H3Cell + The constructed cell. + + Examples + -------- + >>> construct_cell(7, 2, 1, 4) # resolution 3 cell + '830e8cfffffffff' + + >>> construct_cell(15, 0, 0, 5, 3) # resolution 4 cell + '841e057ffffffff' + + >>> construct_cell(15, 0, 0, 5, 3, res=4) + '841e057ffffffff' + """ + if (res is not None) and (len(digits) != res): + raise ValueError('Resolution must match number of digits.') + + digits = array('i', digits) + o = _cy.construct_cell(base_cell_number, digits) + return _out_scalar(o) + + +def deconstruct_cell(h): + """ + Deconstruct cell into base cell and digits. + + Parameters + ---------- + h : H3Cell + Cell to deconstruct. + + Returns + ------- + list of int + [base_cell_number, digit1, digit2, ..., digitN] + + Examples + -------- + >>> h = construct_cell(7, 2, 1, 4) # resolution 3 cell + >>> h + '830e8cfffffffff' + >>> deconstruct_cell(h) + (7, 2, 1, 4) + + >>> h = construct_cell(15, 0, 0, 5, 3) # resolution 4 cell + >>> h + '841e057ffffffff' + >>> deconstruct_cell(h) + (15, 0, 0, 5, 3) + >>> construct_cell(*deconstruct_cell(h), 0) == cell_to_center_child(h) + """ + res = get_resolution(h) + bc = get_base_cell_number(h) + digits = [get_index_digit(h, r + 1) for r in range(res)] + + return [bc, *digits] + + +def are_neighbor_cells(h1, h2): + """ + Returns ``True`` if ``h1`` and ``h2`` are neighboring cells. + + Parameters + ---------- + h1 : H3Cell + h2 : H3Cell + + Returns + ------- + bool + """ + h1 = _in_scalar(h1) + h2 = _in_scalar(h2) + + return _cy.are_neighbor_cells(h1, h2) + + +def cells_to_directed_edge(origin, destination): + """ + Create an H3 Index denoting a unidirectional edge. + + The edge is constructed from neighboring cells ``origin`` and + ``destination``. + + Parameters + ---------- + origin : H3Cell + destination : H3Cell + + Raises + ------ + ValueError + When cells are not adjacent. + + Returns + ------- + H3Edge + """ + o = _in_scalar(origin) + d = _in_scalar(destination) + e = _cy.cells_to_directed_edge(o, d) + e = _out_scalar(e) + + return e + + +def get_directed_edge_origin(e): + """ + Origin cell from an H3 directed edge. + + Parameters + ---------- + e : H3Edge + + Returns + ------- + H3Cell + """ + e = _in_scalar(e) + o = _cy.get_directed_edge_origin(e) + o = _out_scalar(o) + + return o + + +def get_directed_edge_destination(e): + """ + Destination cell from an H3 directed edge. + + Parameters + ---------- + e : H3Edge + + Returns + ------- + H3Cell + """ + e = _in_scalar(e) + d = _cy.get_directed_edge_destination(e) + d = _out_scalar(d) + + return d + + +def directed_edge_to_cells(e): + """ + Return (origin, destination) tuple from H3 directed edge + + Parameters + ---------- + e : H3Edge + + Returns + ------- + H3Cell + Origin cell of edge + H3Cell + Destination cell of edge + """ + e = _in_scalar(e) + o, d = _cy.directed_edge_to_cells(e) + o, d = _out_scalar(o), _out_scalar(d) + + return o, d + + +def origin_to_directed_edges(origin): + """ + Return all directed edges starting from ``origin`` cell. + + Parameters + ---------- + origin : H3Cell + + Returns + ------- + unordered collection of H3Edge + """ + mv = _cy.origin_to_directed_edges(_in_scalar(origin)) + + return _out_collection(mv) + + +def directed_edge_to_boundary(edge): + """ + Returns points representing the edge (line of points + describing the boundary between two cells). + + Parameters + ---------- + edge : H3Edge + + Returns + ------- + tuple of (lat, lng) tuples + """ + return _cy.directed_edge_to_boundary(_in_scalar(edge)) + + +def grid_path_cells(start, end): + """ + Returns the ordered collection of cells denoting a + minimum-length non-unique path between cells. + + Parameters + ---------- + start : H3Cell + end : H3Cell + + Returns + ------- + ordered collection of H3Cell + Starting with ``start``, and ending with ``end``. + """ + mv = _cy.grid_path_cells(_in_scalar(start), _in_scalar(end)) + + return _out_collection(mv) + + +def is_res_class_III(h): + """ + Determine if cell has orientation "Class II" or "Class III". + + The orientation of pentagons/hexagons on the icosahedron can be one + of two types: "Class II" or "Class III". + + All cells within a resolution have the same type, and the type + alternates between resolutions. + + "Class II" cells have resolutions: 0,2,4,6,8,10,12,14 + "Class III" cells have resolutions: 1,3,5,7,9,11,13,15 + + Parameters + ---------- + h : H3Cell + + Returns + ------- + bool + ``True`` if ``h`` is "Class III". + ``False`` if ``h`` is "Class II". + + References + ---------- + 1. https://uber.github.io/h3/#/documentation/core-library/coordinate-systems + """ + return _cy.is_res_class_iii(_in_scalar(h)) + + +def get_pentagons(res): + """ + Return all pentagons at a given resolution. + + Parameters + ---------- + res : int + Resolution of the pentagons + + Returns + ------- + unordered collection of H3Cell + """ + mv = _cy.get_pentagons(res) + + return _out_collection(mv) + + +def get_res0_cells(): + """ + Return all cells at resolution 0. + + Parameters + ---------- + None + + Returns + ------- + unordered collection of H3Cell + + Notes + ----- + There is currently no guaranteed order of the output cells. + """ + mv = _cy.get_res0_cells() + + return _out_collection(mv) + + +def cell_to_center_child(h, res=None): + """ + Get the center child of a cell at some finer resolution. + + Parameters + ---------- + h : H3Cell + res : int or None, optional + The resolution for the child cell + If ``None``, then ``res = resolution(h) + 1`` + + Returns + ------- + H3Cell + """ + h = _in_scalar(h) + p = _cy.cell_to_center_child(h, res) + p = _out_scalar(p) + + return p + + +def get_icosahedron_faces(h): + """ + Return icosahedron faces intersecting a given H3 cell. + + There are twenty possible faces, ranging from 0--19. + + Note: Every interface returns a Python ``set`` of ``int``. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + Python ``set`` of ``int`` + """ + h = _in_scalar(h) + faces = _cy.get_icosahedron_faces(h) + + return faces + + +def cell_to_local_ij(origin, h): + """ + Return local (i,j) coordinates of cell ``h`` in relation to ``origin`` cell + + + Parameters + ---------- + origin : H3Cell + Origin/central cell for defining i,j coordinates. + h: H3Cell + Destination cell whose i,j coordinates we'd like, based off + of the origin cell. + + + Returns + ------- + Tuple (i, j) of integer local coordinates of cell ``h`` + + + Notes + ----- + + The ``origin`` cell does not define (0, 0) for the IJ coordinate space. + (0, 0) refers to the center of the base cell containing origin at the + resolution of `origin`. + Subtracting the IJ coordinates of ``origin`` from every cell would get + you the property of (0, 0) being the ``origin``. + + This is done so we don't need to keep recomputing the coordinates of + ``origin`` if not needed. + """ + origin = _in_scalar(origin) + h = _in_scalar(h) + + i, j = _cy.cell_to_local_ij(origin, h) + + return i, j + + +def local_ij_to_cell(origin, i, j): + """ + Return cell at local (i,j) position relative to the ``origin`` cell. + + Parameters + ---------- + origin : H3Cell + Origin/central cell for defining i,j coordinates. + i, j: int + Integer coordinates with respect to ``origin`` cell. + + + Returns + ------- + H3Cell at local (i,j) position relative to the ``origin`` cell + + + Notes + ----- + + The ``origin`` cell does not define (0, 0) for the IJ coordinate space. + (0, 0) refers to the center of the base cell containing origin at the + resolution of ``origin``. + Subtracting the IJ coordinates of ``origin`` from every cell would get + you the property of (0, 0) being the ``origin``. + + This is done so we don't need to keep recomputing the coordinates of + ``origin`` if not needed. + """ + origin = _in_scalar(origin) + + h = _cy.local_ij_to_cell(origin, i, j) + h = _out_scalar(h) + + return h + + +def cell_area(h, unit='km^2'): + """ + Compute the spherical surface area of a specific H3 cell. + + Parameters + ---------- + h : H3Cell + unit: str + Unit for area result (``'km^2'``, ``'m^2'``, or ``'rads^2'``) + + + Returns + ------- + The area of the H3 cell in the given units + + + Notes + ----- + This function breaks the cell into spherical triangles, and computes + their spherical area. + The function uses the spherical distance calculation given by + ``great_circle_distance()``. + """ + h = _in_scalar(h) + + return _cy.cell_area(h, unit=unit) + + +def edge_length(e, unit='km'): + """ + Compute the spherical length of a specific H3 edge. + + Parameters + ---------- + h : H3Cell + unit: str + Unit for length result (``'km'``, ``'m'``, or ``'rads'``) + + + Returns + ------- + The length of the edge in the given units + + + Notes + ----- + This function uses the spherical distance calculation given by + ``great_circle_distance()``. + """ + e = _in_scalar(e) + + return _cy.edge_length(e, unit=unit) + + +def great_circle_distance(latlng1, latlng2, unit='km'): + """ + Compute the spherical distance between two (lat, lng) points. + AKA: great circle distance or "haversine" distance. + + todo: overload to allow two cell inputs? + + Parameters + ---------- + latlng1 : tuple + (lat, lng) tuple in degrees + latlng2 : tuple + (lat, lng) tuple in degrees + unit: str + Unit for distance result (``'km'``, ``'m'``, or ``'rads'``) + + Returns + ------- + The spherical distance between the points in the given units + """ + lat1, lng1 = latlng1 + lat2, lng2 = latlng2 + return _cy.great_circle_distance( + lat1, lng1, + lat2, lng2, + unit = unit + ) + + +def cell_to_vertex(h, vertex_num): + """ + Return a (specified) vertex of an H3 cell. + + Parameters + ---------- + h : H3Cell + vertex_num : int + Vertex number (0-5) + + Returns + ------- + The vertex + """ + h = _in_scalar(h) + h = _cy.cell_to_vertex(h, vertex_num) + return _out_scalar(h) + + +def cell_to_vertexes(h): + """ + Return a list of vertexes of an H3 cell. + The list will be of length 5 for pentagons and 6 for hexagons. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + A list of vertexes + """ + h = _in_scalar(h) + mv = _cy.cell_to_vertexes(h) + return _out_collection(mv) + + +def vertex_to_latlng(v): + """ + Return latitude and longitude of a vertex. + + Returns + ------- + lat : float + Latitude + lng : float + Longitude + """ + v = _in_scalar(v) + return _cy.vertex_to_latlng(v) + + +def is_valid_vertex(v): + """ + Validates an H3 vertex. + + Returns + ------- + bool + """ + try: + v = _in_scalar(v) + return _cy.is_valid_vertex(v) + except (ValueError, TypeError, OverflowError): + return False + + +if _out_scalar is _in_scalar: # pragma: no cover + # When _out_scalar is identity (basic_int, numpy_int, memview_int), + # bind scalar functions directly to their _cy counterparts to eliminate + # Python call frame and identity wrapper overhead (Issue #501). + # + # Coverage is only measured on the basic_str copy of this file, where + # this branch is never taken; it is exercised by the int API tests. + for _name in ( + 'latlng_to_cell', + 'cell_to_parent', + 'cell_to_center_child', + 'cells_to_directed_edge', + 'get_directed_edge_origin', + 'get_directed_edge_destination', + 'directed_edge_to_cells', + 'local_ij_to_cell', + 'cell_to_vertex', + ): + _fn = globals()[_name] + _cy_fn = getattr(_cy, _name) + _cy_fn.__doc__ = _fn.__doc__ + globals()[_name] = _cy_fn + del _name, _fn, _cy_fn diff --git a/src/h3/api/basic_int/_binding.py b/src/h3/api/basic_int/_binding.py deleted file mode 100644 index a232287..0000000 --- a/src/h3/api/basic_int/_binding.py +++ /dev/null @@ -1,36 +0,0 @@ -""" -This API handles H3 Indexes of type `int`, using -basic Python collections (`set`, `list`, `tuple`). -`h3` will interpret these Indexes as unsigned 64-bit integers. - -Input collections: - -- `Iterable[int]` - -Output collections: - -- `Set[int]` for unordered -- `List[int]` for ordered -""" - -from ... import _cy -from .._api_template import _API_FUNCTIONS - - -def _id(x): - return x - - -def _in_collection(hexes): - it = list(hexes) - - return _cy.from_iter(it) - - -_binding = _API_FUNCTIONS( - _in_scalar=_id, - _out_scalar=_id, - _in_collection=_in_collection, - _out_unordered=set, # todo: should this be an (immutable) frozenset? - _out_ordered=list, # todo: should this be an (immutable) tuple? -) diff --git a/src/h3/api/basic_int/_convert.py b/src/h3/api/basic_int/_convert.py new file mode 100644 index 0000000..51f4728 --- /dev/null +++ b/src/h3/api/basic_int/_convert.py @@ -0,0 +1,17 @@ +from ... import _cy + + +def _in_scalar(x): + return x + + +_out_scalar = _in_scalar + + +def _in_collection(cells): + it = list(cells) + + return _cy.iter_to_mv(it) + + +_out_collection = list diff --git a/src/h3/api/basic_int/_public_api.py b/src/h3/api/basic_int/_public_api.py deleted file mode 100644 index 50b51fc..0000000 --- a/src/h3/api/basic_int/_public_api.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Binding of public API names to module scope - -Prior to binding the API to module scope explicitly, we dynamically modified the -`globals` object when `h3` was imported, which caused problems with static tooling not -being able to understand the H3 API. - -This file exists to avoid dynamically modifying `globals` and support static tooling. -""" -from ._binding import _binding - -cell_area = _binding.cell_area -compact = _binding.compact -edge_length = _binding.edge_length -exact_edge_length = _binding.exact_edge_length -experimental_h3_to_local_ij = _binding.experimental_h3_to_local_ij -experimental_local_ij_to_h3 = _binding.experimental_local_ij_to_h3 -geo_to_h3 = _binding.geo_to_h3 -get_destination_h3_index_from_unidirectional_edge = ( - _binding.get_destination_h3_index_from_unidirectional_edge -) -get_h3_indexes_from_unidirectional_edge = ( - _binding.get_h3_indexes_from_unidirectional_edge -) -get_h3_unidirectional_edge = _binding.get_h3_unidirectional_edge -get_h3_unidirectional_edge_boundary = _binding.get_h3_unidirectional_edge_boundary -get_h3_unidirectional_edges_from_hexagon = ( - _binding.get_h3_unidirectional_edges_from_hexagon -) -get_origin_h3_index_from_unidirectional_edge = ( - _binding.get_origin_h3_index_from_unidirectional_edge -) -get_pentagon_indexes = _binding.get_pentagon_indexes -get_res0_indexes = _binding.get_res0_indexes -h3_distance = _binding.h3_distance -h3_get_base_cell = _binding.h3_get_base_cell -h3_get_faces = _binding.h3_get_faces -h3_get_resolution = _binding.h3_get_resolution -h3_indexes_are_neighbors = _binding.h3_indexes_are_neighbors -h3_is_pentagon = _binding.h3_is_pentagon -h3_is_res_class_III = _binding.h3_is_res_class_III -h3_is_res_class_iii = _binding.h3_is_res_class_iii -h3_is_valid = _binding.h3_is_valid -h3_line = _binding.h3_line -h3_set_to_multi_polygon = _binding.h3_set_to_multi_polygon -h3_to_center_child = _binding.h3_to_center_child -h3_to_children = _binding.h3_to_children -h3_to_geo = _binding.h3_to_geo -h3_to_geo_boundary = _binding.h3_to_geo_boundary -h3_to_parent = _binding.h3_to_parent -h3_to_string = _binding.h3_to_string -h3_unidirectional_edge_is_valid = _binding.h3_unidirectional_edge_is_valid -hex_area = _binding.hex_area -hex_range = _binding.hex_range -hex_range_distances = _binding.hex_range_distances -hex_ranges = _binding.hex_ranges -hex_ring = _binding.hex_ring -k_ring = _binding.k_ring -k_ring_distances = _binding.k_ring_distances -num_hexagons = _binding.num_hexagons -point_dist = _binding.point_dist -polyfill = _binding.polyfill -polyfill_geojson = _binding.polyfill_geojson -polyfill_polygon = _binding.polyfill_polygon -string_to_h3 = _binding.string_to_h3 -uncompact = _binding.uncompact -versions = _binding.versions diff --git a/src/h3/api/basic_str/__init__.py b/src/h3/api/basic_str/__init__.py deleted file mode 100644 index 977b40b..0000000 --- a/src/h3/api/basic_str/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from ._public_api import * # noqa diff --git a/src/h3/api/basic_str/__init__.py b/src/h3/api/basic_str/__init__.py new file mode 120000 index 0000000..92056a2 --- /dev/null +++ b/src/h3/api/basic_str/__init__.py @@ -0,0 +1 @@ +../basic_int/__init__.py \ No newline at end of file diff --git a/src/h3/api/basic_str/_binding.py b/src/h3/api/basic_str/_binding.py deleted file mode 100644 index 765fdbb..0000000 --- a/src/h3/api/basic_str/_binding.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -This API handles H3 Indexes of type `str`, using -basic Python collections (`set`, `list`, `tuple`). -`h3` will interpret these Indexes as hexadecimal -representations of unsigned 64-bit integers. - -Input collections: - -- `Iterable[str]` - -Output collections: - -- `Set[str]` for unordered -- `List[str]` for ordered -""" - -from ... import _cy -from .._api_template import _API_FUNCTIONS - - -def _in_collection(hexes): - it = [_cy.hex2int(h) for h in hexes] - - return _cy.from_iter(it) - - -def _out_unordered(mv): - # todo: should this be an (immutable) frozenset? - return set(_cy.int2hex(h) for h in mv) - - -def _out_ordered(mv): - # todo: should this be an (immutable) tuple? - return list(_cy.int2hex(h) for h in mv) - - -_binding = _API_FUNCTIONS( - _in_scalar = _cy.hex2int, - _out_scalar = _cy.int2hex, - _in_collection = _in_collection, - _out_unordered = _out_unordered, - _out_ordered = _out_ordered, -) diff --git a/src/h3/api/basic_str/_convert.py b/src/h3/api/basic_str/_convert.py new file mode 100644 index 0000000..a6c0ba0 --- /dev/null +++ b/src/h3/api/basic_str/_convert.py @@ -0,0 +1,14 @@ +from ... import _cy + +_in_scalar = _cy.str_to_int +_out_scalar = _cy.int_to_str + + +def _in_collection(cells): + it = [_cy.str_to_int(h) for h in cells] + + return _cy.iter_to_mv(it) + + +def _out_collection(mv): + return list(_cy.int_to_str(h) for h in mv) diff --git a/src/h3/api/basic_str/_public_api.py b/src/h3/api/basic_str/_public_api.py deleted file mode 120000 index c4a6ebd..0000000 --- a/src/h3/api/basic_str/_public_api.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/_public_api.py \ No newline at end of file diff --git a/src/h3/api/memview_int/__init__.py b/src/h3/api/memview_int/__init__.py deleted file mode 100644 index 977b40b..0000000 --- a/src/h3/api/memview_int/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from ._public_api import * # noqa diff --git a/src/h3/api/memview_int/__init__.py b/src/h3/api/memview_int/__init__.py new file mode 120000 index 0000000..92056a2 --- /dev/null +++ b/src/h3/api/memview_int/__init__.py @@ -0,0 +1 @@ +../basic_int/__init__.py \ No newline at end of file diff --git a/src/h3/api/memview_int/_binding.py b/src/h3/api/memview_int/_binding.py deleted file mode 100644 index 96efb77..0000000 --- a/src/h3/api/memview_int/_binding.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -This API handles H3 Indexes of type `int` (specifically, `uint64`), -using Python `memoryview` objects for collections. -`h3` will interpret these Indexes as unsigned 64-bit integers. - -Input collections: - -- `memoryview[uint64]`, i.e., anything that supports the buffer protocol - - `dtype` must be `uint64`. for example, `long` will raise an error - - `list` or `set` inputs will not be accepted - -Output collections: - -- `memoryview[uint64]` for unordered -- `memoryview[uint64]` for ordered -""" - -from .._api_template import _API_FUNCTIONS - - -def _id(x): - return x - - -_binding = _API_FUNCTIONS( - _in_scalar = _id, - _out_scalar = _id, - _in_collection = _id, - _out_unordered = _id, - _out_ordered = _id, -) diff --git a/src/h3/api/memview_int/_convert.py b/src/h3/api/memview_int/_convert.py new file mode 100644 index 0000000..2f054fd --- /dev/null +++ b/src/h3/api/memview_int/_convert.py @@ -0,0 +1,8 @@ +def _id(x): + return x + + +_in_scalar = _id +_out_scalar = _id +_in_collection = _id +_out_collection = _id diff --git a/src/h3/api/memview_int/_public_api.py b/src/h3/api/memview_int/_public_api.py deleted file mode 120000 index c4a6ebd..0000000 --- a/src/h3/api/memview_int/_public_api.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/_public_api.py \ No newline at end of file diff --git a/src/h3/api/numpy_int/__init__.py b/src/h3/api/numpy_int/__init__.py deleted file mode 100644 index 977b40b..0000000 --- a/src/h3/api/numpy_int/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from ._public_api import * # noqa diff --git a/src/h3/api/numpy_int/__init__.py b/src/h3/api/numpy_int/__init__.py new file mode 120000 index 0000000..92056a2 --- /dev/null +++ b/src/h3/api/numpy_int/__init__.py @@ -0,0 +1 @@ +../basic_int/__init__.py \ No newline at end of file diff --git a/src/h3/api/numpy_int/_binding.py b/src/h3/api/numpy_int/_binding.py deleted file mode 100644 index c00275e..0000000 --- a/src/h3/api/numpy_int/_binding.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -This API handles H3 Indexes of type `int` (specifically, `uint64`), -using `numpy.array` objects for collections. -`h3` will interpret these Indexes as unsigned 64-bit integers. - -This API is **optional**, and will only work if the -user has `numpy` installed. - -Input collections: - -- `Iterable[int]` - - works for `lists`, but not `sets` - - will attempt to convert `int` to `uint64` - - no memory copy is made if input dtype is `uint64` - -Output collections: - -- `np.ndarray[np.uint64]` for unordered -- `np.ndarray[np.uint64]` for ordered -""" - -import numpy as np - -from .._api_template import _API_FUNCTIONS - - -def _id(x): - return x - - -def _in_collection(x): - # array is copied only if dtype does not match - # `list`s should work, but not `set`s of integers - return np.asarray(x, dtype='uint64') - - -_binding = _API_FUNCTIONS( - _in_scalar = _id, - _out_scalar = _id, - _in_collection = _in_collection, - _out_unordered = np.asarray, - _out_ordered = np.asarray, -) diff --git a/src/h3/api/numpy_int/_convert.py b/src/h3/api/numpy_int/_convert.py new file mode 100644 index 0000000..6b293cc --- /dev/null +++ b/src/h3/api/numpy_int/_convert.py @@ -0,0 +1,15 @@ +def _in_scalar(x): + return x + + +_out_scalar = _in_scalar + + +def _in_collection(x): + import numpy as np + # array is copied only if dtype does not match + # `list`s should work, but not `set`s of integers + return np.asarray(x, dtype='uint64') + + +_out_collection = _in_collection diff --git a/src/h3/api/numpy_int/_public_api.py b/src/h3/api/numpy_int/_public_api.py deleted file mode 120000 index c4a6ebd..0000000 --- a/src/h3/api/numpy_int/_public_api.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/_public_api.py \ No newline at end of file diff --git a/src/h3/unstable/__init__.py b/src/h3/unstable/__init__.py deleted file mode 100644 index 5c1839c..0000000 --- a/src/h3/unstable/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# flake8: noqa - -import warnings -warnings.warn( - 'Modules under `h3.unstable` are experimental, and may change at any time.' -) - -from . import v4 -from . import vect diff --git a/src/h3/unstable/v4.py b/src/h3/unstable/v4.py deleted file mode 100644 index 833cd6e..0000000 --- a/src/h3/unstable/v4.py +++ /dev/null @@ -1,125 +0,0 @@ -# flake8: noqa - -from ..api.basic_str import ( - # todo: implement is_valid_index - - compact as - compact_cells, - - edge_length as - get_hexagon_edge_length_avg, - - geo_to_h3 as - point_to_cell, - - get_destination_h3_index_from_unidirectional_edge as - get_directed_edge_destination, - - get_h3_indexes_from_unidirectional_edge as - directed_edge_to_cells, - - get_h3_unidirectional_edge as - cells_to_directed_edge, - - get_h3_unidirectional_edge_boundary as - directed_edge_to_boundary, - - get_h3_unidirectional_edges_from_hexagon as - origin_to_directed_edges, - - get_origin_h3_index_from_unidirectional_edge as - get_directed_edge_origin, - - get_pentagon_indexes as - get_pentagons, - - get_res0_indexes as - get_res0_cells, - - h3_distance as - grid_distance, - - h3_get_base_cell as - get_base_cell_number, - - h3_get_faces as - get_icosahedron_faces, - - h3_get_resolution as - get_resolution, - - h3_indexes_are_neighbors as - are_neighbor_cells, - - h3_is_pentagon as - is_pentagon, - - h3_is_res_class_III as - is_res_class_III, - - h3_is_valid as - is_valid_cell, - - h3_line as - grid_path_cells, - - h3_set_to_multi_polygon as - cells_to_multipolygon, - - h3_to_center_child as - cell_to_center_child, - - h3_to_children as - cell_to_children, - - h3_to_geo as - cell_to_point, - - h3_to_geo_boundary as - cell_to_boundary, - - h3_to_parent as - cell_to_parent, - - h3_to_string as - int_to_str, - - h3_unidirectional_edge_is_valid as - is_valid_directed_edge, - - hex_area as - get_hexagon_area_avg, - - # hex_range as _, - # hex_range_distances as _, # not sure we want this one; easy for user to implement - # hex_ranges as _, - - hex_ring as - grid_ring, - - k_ring as - grid_disk, - - k_ring_distances as - grid_disk_distances, - - num_hexagons as - get_num_cells, - - polyfill as - polygon_to_cells, - - polyfill_geojson as - geojson_to_cells, # still need to figure out the final polyfill interface - - #polyfill_polygon as _, - - string_to_h3 as - str_to_int, - - uncompact as - uncompact_cells, - - versions as - versions, -) diff --git a/src/h3/unstable/vect.py b/src/h3/unstable/vect.py deleted file mode 100644 index 122c07d..0000000 --- a/src/h3/unstable/vect.py +++ /dev/null @@ -1,105 +0,0 @@ -from .._cy import unstable_vect as _vect - -import numpy as np - - -def h3_to_parent(h, res=None): - """ - Get parent of arrays of cells. - - Parameters - ---------- - h : array of H3Cells - res: int or None, optional - The resolution for the parent - If `None`, then `res = resolution(h) - 1` - - Returns - ------- - array of H3Cells - """ - h = np.array(h, dtype=np.uint64) - out = np.zeros(len(h), dtype=np.uint64) - - if res is None: - res = h3_get_resolution(h) - 1 - else: - res = np.full(h.shape, res, dtype=np.intc) - - _vect.h3_to_parent_vect(h, res, out) - - return out - - -def h3_get_resolution(h): - """ - Return the resolution of an array of H3 cells. - - Parameters - ---------- - h : H3Cell - - Returns - ------- - array of int - """ - h = np.array(h, dtype=np.uint64) - out = np.zeros(len(h), dtype=np.intc) - - _vect.h3_get_resolution_vect(h, out) - - return out - - -def geo_to_h3(lats, lngs, res): - """ - Convert arrays describing lat/lng pairs to cells. - - Parameters - ---------- - lats, lngs : arrays of floats - - res: int - Resolution for output cells. - - Returns - ------- - array of H3Cells - """ - lats = np.array(lats, dtype=np.float64) - lngs = np.array(lngs, dtype=np.float64) - - assert len(lats) == len(lngs) - - out = np.zeros(len(lats), dtype='uint64') - - _vect.geo_to_h3_vect(lats, lngs, res, out) - - return out - - -def cell_haversine(a, b): - """ - Compute haversine distance between the centers of cells given in - arrays a and b. - - - Parameters - ---------- - a, b : arrays of H3Cell - - Returns - ------- - float - Haversine distance in kilometers - """ - a = np.array(a, dtype=np.uint64) - b = np.array(b, dtype=np.uint64) - - assert len(a) == len(b) - - out = np.zeros(len(a), dtype='double') - - _vect.haversine_vect(a, b, out) - - return out diff --git a/src/h3lib b/src/h3lib index ee292a9..1b536c3 160000 --- a/src/h3lib +++ b/src/h3lib @@ -1 +1 @@ -Subproject commit ee292a96906767162f2f530b46fc2428b2555748 +Subproject commit 1b536c34225191ba24a75a840f634d4a48c3b206 diff --git a/tests/readme.md b/tests/readme.md new file mode 100644 index 0000000..0aba346 --- /dev/null +++ b/tests/readme.md @@ -0,0 +1,18 @@ +We separate the `h3-py` tests into two groups, organized by subfolder. + +We do this because we expect 100% coverage on the library tests, but are +still working through getting full coverage on the Cython tests. + + +## `test_lib` + +The tests in this folder are for the main `h3-py` Python API for folks +who are using the pure-Python library functionality. + +## `test_cython` + +The tests in this folder are for the advanced Cython API, that allows +for other *Cython* packages or scripts to use the Cython code provided +by the `h3-py` internals. + +Note that the "Cython API" of `h3-py` is not currently externally supported. diff --git a/tests/test_api_bindings_match.py b/tests/test_api_bindings_match.py deleted file mode 100644 index 9bcb60b..0000000 --- a/tests/test_api_bindings_match.py +++ /dev/null @@ -1,16 +0,0 @@ -import inspect - - -def test_api_copy_match(): - import h3 - import h3.api.numpy_int - - apis = [ - h3.api.basic_int._public_api, - h3.api.basic_str._public_api, - h3.api.memview_int._public_api, - h3.api.numpy_int._public_api, - ] - - api_set = {inspect.getsource(api) for api in apis} - assert len(api_set) == 1 diff --git a/tests/test_basic_int.py b/tests/test_basic_int.py deleted file mode 100644 index d5c47c0..0000000 --- a/tests/test_basic_int.py +++ /dev/null @@ -1,48 +0,0 @@ -import h3.api.basic_int as h3 - - -def test_int_output(): - lat = 37.7752702151959 - lng = -122.418307270836 - - assert h3.geo_to_h3(lat, lng, 9) == 617700169958293503 - assert h3.geo_to_h3(lat, lng, 9) == 0x8928308280fffff - - -def test_k_ring(): - expected = { - 617700169957507071, - 617700169957769215, - 617700169958031359, - 617700169958293503, - 617700169961177087, - 617700169964847103, - 617700169965109247, - } - - out = h3.k_ring(617700169958293503, 1) - assert out == expected - - -def test_compact(): - h = 617700169958293503 - hexes = h3.h3_to_children(h) - - assert h3.compact(hexes) == {h} - - -def test_get_faces(): - h = 577832942814887935 - expected = {2, 3, 7, 8, 12} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579873636396040191 - expected = {13} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579768083279773695 - expected = {16, 15} - out = h3.h3_get_faces(h) - assert out == expected diff --git a/tests/test_basic_str.py b/tests/test_basic_str.py deleted file mode 100644 index f765678..0000000 --- a/tests/test_basic_str.py +++ /dev/null @@ -1,20 +0,0 @@ -import h3.api.basic_str as h3 - - -def test1(): - assert h3.geo_to_h3(37.7752702151959, -122.418307270836, 9) == '8928308280fffff' - - -def test5(): - expected = { - '89283082873ffff', - '89283082877ffff', - '8928308283bffff', - '89283082807ffff', - '8928308280bffff', - '8928308280fffff', - '89283082803ffff' - } - - out = h3.k_ring('8928308280fffff', 1) - assert out == expected diff --git a/tests/test_cells_and_edges.py b/tests/test_cells_and_edges.py deleted file mode 100644 index 173033a..0000000 --- a/tests/test_cells_and_edges.py +++ /dev/null @@ -1,621 +0,0 @@ -import h3 -import pytest - -from h3 import ( - H3ValueError, - H3CellError, - H3ResolutionError, - H3EdgeError, - H3DistanceError, -) - - -def approx2(a, b): - if len(a) != len(b): - return False - - return all( - x == pytest.approx(y) - for x, y in zip(a, b) - ) - - -def test1(): - assert h3.geo_to_h3(37.7752702151959, -122.418307270836, 9) == '8928308280fffff' - - -def test2(): - h = '8928308280fffff' - expected = (37.77670234943567, -122.41845932318311) - - assert h3.h3_to_geo(h) == pytest.approx(expected) - - -def test3(): - expected = ( - (37.775197782893386, -122.41719971841658), - (37.77688044840226, -122.41612835779264), - (37.778385004930925, -122.4173879761762), - (37.77820687262238, -122.41971895414807), - (37.77652420699321, -122.42079024541877), - (37.775019673792606, -122.4195306280734), - ) - - out = h3.h3_to_geo_boundary('8928308280fffff') - assert approx2(out, expected) - - -def test4(): - expected = ( - (-122.41719971841658, 37.775197782893386), - (-122.41612835779264, 37.77688044840226), - (-122.4173879761762, 37.778385004930925), - (-122.41971895414807, 37.77820687262238), - (-122.42079024541877, 37.77652420699321), - (-122.4195306280734, 37.775019673792606), - (-122.41719971841658, 37.775197782893386) - ) - - out = h3.h3_to_geo_boundary('8928308280fffff', geo_json=True) - assert approx2(out, expected) - - -def test_k_ring_distance(): - with pytest.raises(H3DistanceError): - h3.k_ring('8928308280fffff', -10) - - -def test_hex_ring_distance(): - with pytest.raises(H3DistanceError): - h3.hex_ring('8928308280fffff', -10) - - -def test5(): - expected = { - '89283082873ffff', - '89283082877ffff', - '8928308283bffff', - '89283082807ffff', - '8928308280bffff', - '8928308280fffff', - '89283082803ffff' - } - - out = h3.k_ring('8928308280fffff', 1) - assert out == expected - - -def test6(): - expected = {'8928308280fffff'} - out = h3.hex_ring('8928308280fffff', 0) - assert out == expected - - -def test7(): - expected = { - '89283082803ffff', - '89283082807ffff', - '8928308280bffff', - '8928308283bffff', - '89283082873ffff', - '89283082877ffff' - } - - out = h3.hex_ring('8928308280fffff', 1) - assert out == expected - - -def test8(): - assert h3.h3_is_valid('89283082803ffff') - assert not h3.h3_is_valid('abc') - - # looks like it might be valid, but it isn't! - h_bad = '8a28308280fffff' - assert not h3.h3_is_valid(h_bad) - - # other methods should validate and raise exception if bad input - with pytest.raises(H3CellError): - h3.h3_get_resolution(h_bad) - - -def test9(): - assert h3.h3_get_resolution('8928308280fffff') == 9 - assert h3.h3_get_resolution('8a28308280f7fff') == 10 - - -def test_parent(): - h = '8928308280fffff' - - assert h3.h3_to_parent(h, 7) == '872830828ffffff' - assert h3.h3_to_parent(h, 8) == '8828308281fffff' - assert h3.h3_to_parent(h, 9) == h - - with pytest.raises(H3ResolutionError): - h3.h3_to_parent(h, 10) - - -def test_children(): - h = '8928308280fffff' - - # one above should raise an exception - with pytest.raises(H3ResolutionError): - h3.h3_to_children(h, 8) - - # same resolution is set of just cell itself - out = h3.h3_to_children(h, 9) - assert out == {h} - - # one below should give children - expected = { - '8a28308280c7fff', - '8a28308280cffff', - '8a28308280d7fff', - '8a28308280dffff', - '8a28308280e7fff', - '8a28308280effff', - '8a28308280f7fff' - } - out = h3.h3_to_children(h, 10) - assert out == expected - - # finest resolution cell should return error for children - h = '8f04ccb2c45e225' - with pytest.raises(H3ResolutionError): - h3.h3_to_children(h) - - -def test_center_child(): - h = '8928308280fffff' - - # one above should raise an exception - with pytest.raises(H3ResolutionError): - h3.h3_to_center_child(h, 8) - - # same resolution should be same cell - assert h3.h3_to_center_child(h, 9) == h - - # one below should give direct child - expected = '8a28308280c7fff' - assert h3.h3_to_center_child(h, 10) == expected - - # finest resolution hex should return error for child - h = '8f04ccb2c45e225' - with pytest.raises(H3ResolutionError): - h3.h3_to_center_child(h) - - -def test_distance(): - h = '8a28308280c7fff' - assert h3.h3_distance(h, h) == 0 - - n = h3.hex_ring(h, 1).pop() - assert h3.h3_distance(h, n) == 1 - - n = h3.hex_ring(h, 2).pop() - assert h3.h3_distance(h, n) == 2 - - -def test_distance_error(): - h1 = '8353b0fffffffff' - h2 = '835804fffffffff' - - with pytest.raises(H3ValueError): - h3.h3_distance(h1, h2) - - -def test_compact(): - - # lat/lngs for State of Maine - maine = [ - (45.137451890638886, -67.13734351262877), - (44.8097, -66.96466), - (44.3252, -68.03252), - (43.98, -69.06), - (43.68405, -70.11617), - (43.090083319667144, -70.64573401557249), - (43.08003225358635, -70.75102474636725), - (43.21973948828747, -70.79761105007827), - (43.36789581966826, -70.98176001655037), - (43.46633942318431, -70.94416541205806), - (45.3052400000002, -71.08482), - (45.46022288673396, -70.6600225491012), - (45.914794623389355, -70.30495378282376), - (46.69317088478567, -70.00014034695016), - (47.44777598732787, -69.23708614772835), - (47.184794623394396, -68.90478084987546), - (47.35462921812177, -68.23430497910454), - (47.066248887716995, -67.79035274928509), - (45.702585354182816, -67.79141211614706), - (45.137451890638886, -67.13734351262877) - ] - - res = 5 - - h_uncomp = h3.polyfill_polygon(maine, res) - h_comp = h3.compact(h_uncomp) - - expected = {'852b114ffffffff', '852b189bfffffff', '852b1163fffffff', '842ba9bffffffff', '842bad3ffffffff', '852ba9cffffffff', '842badbffffffff', '852b1e8bfffffff', '852a346ffffffff', '842b1e3ffffffff', '852b116ffffffff', '842b185ffffffff', '852b1bdbfffffff', '852bad47fffffff', '852ba9c3fffffff', '852b106bfffffff', '852a30d3fffffff', '842b1edffffffff', '852b12a7fffffff', '852b1027fffffff', '842baddffffffff', '852a349bfffffff', '852b1227fffffff', '852a3473fffffff', '852b117bfffffff', '842ba99ffffffff', '852a341bfffffff', '852ba9d3fffffff', '852b1067fffffff', '852a3463fffffff', '852baca7fffffff', '852b116bfffffff', '852b1c6bfffffff', '852a3493fffffff', '852ba9dbfffffff', '852b180bfffffff', '842bad7ffffffff', '852b1063fffffff', '842ba93ffffffff', '852a3693fffffff', '852ba977fffffff', '852b1e9bfffffff', '852bad53fffffff', '852b100ffffffff', '852b102bfffffff', '852a3413fffffff', '852ba8b7fffffff', '852bad43fffffff', '852b1c6ffffffff', '852a340bfffffff', '852b103bfffffff', '852b1813fffffff', '852b12affffffff', '842a34dffffffff', '852b1873fffffff', '852b106ffffffff', '852b115bfffffff', '852baca3fffffff', '852b114bfffffff', '852b1143fffffff', '852a348bfffffff', '852a30d7fffffff', '852b181bfffffff', '842a345ffffffff', '852b1e8ffffffff', '852b1883fffffff', '852b1147fffffff', '852a3483fffffff', '852b12a3fffffff', '852a346bfffffff', '852ba9d7fffffff', '842b18dffffffff', '852b188bfffffff', '852a36a7fffffff', '852bacb3fffffff', '852b187bfffffff', '852bacb7fffffff', '842b1ebffffffff', '842b1e5ffffffff', '852ba8a7fffffff', '842bad9ffffffff', '852a36b7fffffff', '852a347bfffffff', '832b13fffffffff', '852ba9c7fffffff', '832b1afffffffff', '842ba91ffffffff', '852bad57fffffff', '852ba8affffffff', '852b1803fffffff', '842b1e7ffffffff', '852bad4ffffffff', '852b102ffffffff', '852b1077fffffff', '852b1237fffffff', '852b1153fffffff', '852a3697fffffff', '852a36b3fffffff', '842bad1ffffffff', '842b1e1ffffffff', '852b186bfffffff', '852b1023fffffff'} # noqa - - assert h_comp == expected - - return h_uncomp, h_comp, res - - -def test_uncompact(): - - h_uncomp, h_comp, res = test_compact() - - out = h3.uncompact(h_comp, res) - - assert out == h_uncomp - - -def test_num_hexagons(): - expected = { - 0: 122, - 1: 842, - 2: 5882, - 9: 4842432842, - 15: 569707381193162, - } - - out = { - k: h3.num_hexagons(k) - for k in expected - } - - assert expected == out - - -def test_hex_area(): - expected_in_km2 = { - 0: 4250546.848, - 1: 607220.9782, - 2: 86745.85403, - 9: 0.1053325, - 15: 9e-07, - } - - out = { - k: h3.hex_area(k, unit='km^2') - for k in expected_in_km2 - } - - assert out == pytest.approx(expected_in_km2) - - -def test_hex_edge_length(): - expected_in_km = { - 0: 1107.712591000, - 1: 418.676005500, - 2: 158.244655800, - 9: 0.174375668, - 15: 0.000509713, - } - - out = { - res: h3.edge_length(res, unit='km') - for res in expected_in_km - } - - assert out == pytest.approx(expected_in_km) - - -def test_edge(): - h1 = '8928308280fffff' - h2 = '89283082873ffff' - - assert not h3.h3_indexes_are_neighbors(h1, h1) - assert h3.h3_indexes_are_neighbors(h1, h2) - - e = h3.get_h3_unidirectional_edge(h1, h2) - - assert e == '12928308280fffff' - assert h3.h3_unidirectional_edge_is_valid(e) - assert not h3.h3_is_valid(e) - - assert h3.get_origin_h3_index_from_unidirectional_edge(e) == h1 - assert h3.get_destination_h3_index_from_unidirectional_edge(e) == h2 - - assert h3.get_h3_indexes_from_unidirectional_edge(e) == (h1, h2) - - -def test_edges_from_cell(): - h = '8928308280fffff' - edges = h3.get_h3_unidirectional_edges_from_hexagon(h) - destinations = { - h3.get_destination_h3_index_from_unidirectional_edge(e) - for e in edges - } - neighbors = h3.hex_ring(h, 1) - - assert neighbors == destinations - - -def test_edge_boundary(): - h1 = '8928308280fffff' - h2 = '89283082873ffff' - e = h3.get_h3_unidirectional_edge(h1, h2) - - expected = ( - (37.77688044840226, -122.41612835779266), - (37.778385004930925, -122.41738797617619) - ) - - out = h3.get_h3_unidirectional_edge_boundary(e) - - assert out[0] == pytest.approx(expected[0]) - assert out[1] == pytest.approx(expected[1]) - - -def test_validation(): - h = '8a28308280fffff' # invalid cell - - with pytest.raises(H3CellError): - h3.h3_get_base_cell(h) - - with pytest.raises(H3CellError): - h3.h3_get_resolution(h) - - with pytest.raises(H3CellError): - h3.h3_to_parent(h, 9) - - with pytest.raises(H3CellError): - h3.h3_distance(h, h) - - with pytest.raises(H3CellError): - h3.k_ring(h, 1) - - with pytest.raises(H3CellError): - h3.hex_ring(h, 1) - - with pytest.raises(H3CellError): - h3.h3_to_children(h, 11) - - with pytest.raises(H3CellError): - h3.compact({h}) - - with pytest.raises(H3CellError): - h3.uncompact({h}, 10) - - -def test_validation2(): - h = '8928308280fffff' - - with pytest.raises(H3ResolutionError): - h3.h3_to_children(h, 17) - - assert not h3.h3_indexes_are_neighbors(h, h) - - -def test_validation_geo(): - h = '8a28308280fffff' # invalid cell - - with pytest.raises(H3CellError): - h3.h3_to_geo(h) - - with pytest.raises(H3ResolutionError): - h3.geo_to_h3(0, 0, 17) - - with pytest.raises(H3CellError): - h3.h3_to_geo_boundary(h) - - with pytest.raises(H3CellError): - h3.h3_indexes_are_neighbors(h, h) - - -def test_edges(): - h = '8928308280fffff' - - with pytest.raises(H3ValueError): - h3.get_h3_unidirectional_edge(h, h) - - h2 = h3.hex_ring(h, 2).pop() - with pytest.raises(H3ValueError): - h3.get_h3_unidirectional_edge(h, h2) - - e_bad = '14928308280ffff1' - assert not h3.h3_unidirectional_edge_is_valid(e_bad) - - with pytest.raises(H3EdgeError): - h3.get_origin_h3_index_from_unidirectional_edge(e_bad) - - with pytest.raises(H3EdgeError): - h3.get_destination_h3_index_from_unidirectional_edge(e_bad) - - with pytest.raises(H3EdgeError): - h3.get_h3_indexes_from_unidirectional_edge(e_bad) - - -def test_line(): - h1 = '8928308280fffff' - h2 = '8928308287bffff' - - out = h3.h3_line(h1, h2) - - expected = [ - '8928308280fffff', - '89283082873ffff', - '8928308287bffff' - ] - - assert out == expected - - -def test_versions(): - from packaging.version import Version - - v = h3.versions() - - assert v['python'] == h3.__version__ - - v_c = Version(v['c']) - v_p = Version(v['python']) - - # of X.Y.Z, X and Y must match - assert v_c.release[:2] == v_p.release[:2] - - -def test_str_int_convert(): - s = '8928308280fffff' - i = h3.string_to_h3(s) - - assert h3.h3_to_string(i) == s - - -def test_hex2int_fail(): - h_invalid = {} - - assert not h3.h3_is_valid(h_invalid) - - -def test_edge_is_valid_fail(): - e_invalid = {} - assert not h3.h3_unidirectional_edge_is_valid(e_invalid) - - -def test_get_pentagons(): - out = h3.get_pentagon_indexes(0) - - expected = { - '8009fffffffffff', - '801dfffffffffff', - '8031fffffffffff', - '804dfffffffffff', - '8063fffffffffff', - '8075fffffffffff', - '807ffffffffffff', - '8091fffffffffff', - '80a7fffffffffff', - '80c3fffffffffff', - '80d7fffffffffff', - '80ebfffffffffff', - } - - assert out == expected - - out = h3.get_pentagon_indexes(5) - - expected = { - '85080003fffffff', - '851c0003fffffff', - '85300003fffffff', - '854c0003fffffff', - '85620003fffffff', - '85740003fffffff', - '857e0003fffffff', - '85900003fffffff', - '85a60003fffffff', - '85c20003fffffff', - '85d60003fffffff', - '85ea0003fffffff', - } - - assert out == expected - - for i in range(16): - assert len(h3.get_pentagon_indexes(i)) == 12 - - -def test_uncompact_cell_input(): - # `uncompact` takes in a collection of cells, not a single cell. - # Since a python string is seen as a Iterable collection, - # inputting a single cell string can raise weird errors. - - # Ensure we get a reasonably helpful answer - with pytest.raises(H3CellError): - h3.uncompact('8001fffffffffff', 1) - - -def test_get_res0_indexes(): - out = h3.get_res0_indexes() - - assert len(out) == 122 - - # subset - pentagons = h3.get_pentagon_indexes(0) - assert pentagons < out - - # all valid - assert all(map(h3.h3_is_valid, out)) - - # resolution - assert all(map( - lambda h: h3.h3_get_resolution(h) == 0, - out - )) - - # verify a few concrete cells - sub = { - '8001fffffffffff', - '8003fffffffffff', - '8005fffffffffff', - } - assert sub < out - - -def test_get_faces_invalid(): - h = '8a28308280fffff' # invalid cell - - with pytest.raises(H3CellError): - h3.h3_get_faces(h) - - -def test_get_faces(): - h = '804dfffffffffff' - expected = {2, 3, 7, 8, 12} - out = h3.h3_get_faces(h) - assert out == expected - - h = '80c1fffffffffff' - expected = {13} - out = h3.h3_get_faces(h) - assert out == expected - - h = '80bbfffffffffff' - expected = {16, 15} - out = h3.h3_get_faces(h) - assert out == expected - - -def test_to_local_ij_error(): - h = h3.geo_to_h3(0, 0, 0) - - # error if we cross a face - nb = h3.hex_ring(h, k=2) - with pytest.raises(H3ValueError): - [h3.experimental_h3_to_local_ij(h, p) for p in nb] - - # should be fine if we do not cross a face - nb = h3.hex_ring(h, k=1) - out = {h3.experimental_h3_to_local_ij(h, p) for p in nb} - expected = {(-1, 0), (0, -1), (0, 1), (1, 0), (1, 1)} - - assert out == expected - - -def test_from_local_ij_error(): - h = h3.geo_to_h3(0, 0, 0) - - baddies = [(1, -1), (-1, 1), (-1, -1)] - for i, j in baddies: - with pytest.raises(H3ValueError): - h3.experimental_local_ij_to_h3(h, i, j) - - # inverting output should give good data - nb = h3.hex_ring(h, k=1) - goodies = {h3.experimental_h3_to_local_ij(h, p) for p in nb} - - out = { - h3.experimental_local_ij_to_h3(h, i, j) - for i, j in goodies - } - - assert out == nb - - -def test_to_local_ij_self(): - h = h3.geo_to_h3(0, 0, 9) - out = h3.experimental_h3_to_local_ij(h, h) - - assert out == (-858, -2766) diff --git a/tests/__init__.py b/tests/test_cython/__init__.py similarity index 100% rename from tests/__init__.py rename to tests/test_cython/__init__.py diff --git a/tests/cython_example.pyx b/tests/test_cython/cython_example.pyx similarity index 62% rename from tests/cython_example.pyx rename to tests/test_cython/cython_example.pyx index e8d2859..0185f76 100644 --- a/tests/cython_example.pyx +++ b/tests/test_cython/cython_example.pyx @@ -1,11 +1,12 @@ +#cython: language_level=3 from cython cimport boundscheck, wraparound from h3._cy.h3lib cimport H3int -from h3._cy.geo cimport geo_to_h3 +from h3._cy.latlng cimport latlng_to_cell @boundscheck(False) @wraparound(False) -cpdef void geo_to_h3_vect( +cpdef void latlng_to_cell_vect( const double[:] lat, const double[:] lng, int res, @@ -15,4 +16,4 @@ cpdef void geo_to_h3_vect( cdef Py_ssize_t i for i in range(len(lat)): - out[i] = geo_to_h3(lat[i], lng[i], res) + out[i] = latlng_to_cell(lat[i], lng[i], res) diff --git a/tests/test_cython.py b/tests/test_cython/test_cython.py similarity index 57% rename from tests/test_cython.py rename to tests/test_cython/test_cython.py index 30566b1..1833de3 100644 --- a/tests/test_cython.py +++ b/tests/test_cython/test_cython.py @@ -3,16 +3,16 @@ import numpy as np # Avoid checking for import-error here because cython_example may not have # been compiled yet. try: - from .cython_example import geo_to_h3_vect # pylint: disable=import-error + from .cython_example import latlng_to_cell_vect # pylint: disable=import-error except ImportError: - geo_to_h3_vect = None + latlng_to_cell_vect = None np.random.seed(0) def test_cython_api(): - if geo_to_h3_vect is None: - print("Not running Cython test because cython example was not compiled") + if latlng_to_cell_vect is None: + print('Not running Cython test because cython example was not compiled') return N = 100000 @@ -22,7 +22,7 @@ def test_cython_api(): lats = np.array(lats, dtype=np.float64) lngs = np.array(lngs, dtype=np.float64) - out = np.zeros(len(lats), dtype="uint64") - geo_to_h3_vect(lats, lngs, res, out) + out = np.zeros(len(lats), dtype='uint64') + latlng_to_cell_vect(lats, lngs, res, out) assert out[0] == 617284541015654399 diff --git a/tests/test_h3.py b/tests/test_h3.py deleted file mode 100644 index 09a1e7d..0000000 --- a/tests/test_h3.py +++ /dev/null @@ -1,986 +0,0 @@ -import pytest -from pytest import approx - -import h3 - - -def test_nested_import(): - """ Test that we can import `h3.h3` - For backwards-compatibility - """ - from h3 import h3 - assert h3.geo_to_h3(37.3615593, -122.0553238, 5) == '85283473fffffff' - - -def shift_circular_list(start_element, elements_list): - # We shift the circular list so that it starts from start_element, - start_index = elements_list.index(start_element) - return elements_list[start_index:] + elements_list[:start_index] - - -def test_h3_is_valid(): - assert h3.h3_is_valid('85283473fffffff') - assert h3.h3_is_valid('850dab63fffffff') - assert not h3.h3_is_valid('lolwut') - - # H3 0.x Addresses are not considered valid - assert not h3.h3_is_valid('5004295803a88') - - for res in range(16): - assert h3.h3_is_valid(h3.geo_to_h3(37, -122, res)) - - -def test_geo_to_h3(): - assert h3.geo_to_h3(37.3615593, -122.0553238, 5) == '85283473fffffff' - - -def test_h3_get_resolution(): - for res in range(16): - h = h3.geo_to_h3(37.3615593, -122.0553238, res) - assert h3.h3_get_resolution(h) == res - - -def test_silly_geo_to_h3(): - lat, lng = 37.3615593, -122.0553238 - - expected0 = '85283473fffffff' - out0 = h3.geo_to_h3(lat, lng, 5) - assert out0 == expected0 - - out1 = h3.geo_to_h3(lat + 180.0, lng + 360.0, 5) - expected1 = '85ca2d53fffffff' - assert out1 == expected1 - - -def test_h3_to_geo(): - latlng = h3.h3_to_geo('85283473fffffff') - assert latlng == approx((37.34579337536848, -121.97637597255124)) - - -def test_h3_to_geo_boundary(): - out = h3.h3_to_geo_boundary('85283473fffffff') - - expected = [ - [37.271355866731895, -121.91508032705622], - [37.353926450852256, -121.86222328902491], - [37.42834118609435, -121.9235499963016], - [37.42012867767778, -122.0377349642703], - [37.33755608435298, -122.09042892904395], - [37.26319797461824, -122.02910130919], - ] - - assert len(out) == len(expected) - - for o, e in zip(out, expected): - assert o == approx(e) - - -def test_h3_to_geo_boundary_geo_json(): - out = h3.h3_to_geo_boundary('85283473fffffff', True) - - expected = [ - [-121.91508032705622, 37.271355866731895], - [-121.86222328902491, 37.353926450852256], - [-121.9235499963016, 37.42834118609435], - [-122.0377349642703, 37.42012867767778], - [-122.09042892904395, 37.33755608435298], - [-122.02910130919, 37.26319797461824], - [-121.91508032705622, 37.271355866731895], - ] - - assert len(out) == len(expected) - - for o, e in zip(out, expected): - assert o == approx(e) - - -def test_k_ring(): - h = '8928308280fffff' - out = h3.k_ring(h, 1) - - assert len(out) == 1 + 6 - - expected = { - '8928308280bffff', - '89283082807ffff', - '89283082877ffff', - h, - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - - assert out == expected - - -def test_k_ring2(): - h = '8928308280fffff' - out = h3.k_ring(h, 2) - - assert len(out) == 1 + 6 + 12 - - expected = { - '89283082813ffff', - '89283082817ffff', - '8928308281bffff', - '89283082863ffff', - '89283082823ffff', - '89283082873ffff', - '89283082877ffff', - h, - '8928308287bffff', - '89283082833ffff', - '8928308282bffff', - '8928308283bffff', - '89283082857ffff', - '892830828abffff', - '89283082847ffff', - '89283082867ffff', - '89283082803ffff', - '89283082807ffff', - '8928308280bffff', - } - - assert out == expected - - -def test_k_ring_pentagon(): - h = '821c07fffffffff' # a pentagon cell - out = h3.k_ring(h, 1) - - assert len(out) == 1 + 5 - - expected = { - '821c2ffffffffff', - '821c27fffffffff', - h, - '821c17fffffffff', - '821c1ffffffffff', - '821c37fffffffff', - } - - assert out == expected - - -def test_k_ring_distances(): - h = '8928308280fffff' - out = h3.k_ring_distances(h, 1) - - assert [len(x) for x in out] == [1, 6] - - expected = [ - {h}, - { - '8928308280bffff', - '89283082807ffff', - '89283082877ffff', - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - ] - - assert out == expected - - out = h3.k_ring_distances('870800003ffffff', 2) - - assert [len(x) for x in out] == [1, 6, 11] - - -def test_polyfill(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [37.813318999983238, -122.4089866999972145], - [37.7866302000007224, -122.3805436999997056], - [37.7198061999978478, -122.3544736999993603], - [37.7076131999975672, -122.5123436999983966], - [37.7835871999971715, -122.5247187000021967], - [37.8151571999998453, -122.4798767000009008] - ] - ] - } - - out = h3.polyfill(geo, 9) - assert len(out) > 1000 - - -def test_polyfill_bogus_geo_json(): - with pytest.raises(ValueError): - bad_geo = {'type': 'whatwhat'} - h3.polyfill(bad_geo, 9) - - -def test_polyfill_with_hole(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [37.813318999983238, -122.4089866999972145], - [37.7866302000007224, -122.3805436999997056], - [37.7198061999978478, -122.3544736999993603], - [37.7076131999975672, -122.5123436999983966], - [37.7835871999971715, -122.5247187000021967], - [37.8151571999998453, -122.4798767000009008], - ], - [ - [37.7869802, -122.4471197], - [37.7664102, -122.4590777], - [37.7710682, -122.4137097], - ] - ] - } - - out = h3.polyfill(geo, 9) - assert len(out) > 1000 - - -def test_polyfill_with_two_holes(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [37.813318999983238, -122.4089866999972145], - [37.7866302000007224, -122.3805436999997056], - [37.7198061999978478, -122.3544736999993603], - [37.7076131999975672, -122.5123436999983966], - [37.7835871999971715, -122.5247187000021967], - [37.8151571999998453, -122.4798767000009008], - ], - [ - [37.7869802, -122.4471197], - [37.7664102, -122.4590777], - [37.7710682, -122.4137097], - ], - [ - [37.747976, -122.490025], - [37.731550, -122.503758], - [37.725440, -122.452603], - ] - ] - } - - out = h3.polyfill(geo, 9) - assert len(out) > 1000 - - -def test_polyfill_geo_json_compliant(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [-122.4089866999972145, 37.813318999983238], - [-122.3805436999997056, 37.7866302000007224], - [-122.3544736999993603, 37.7198061999978478], - [-122.5123436999983966, 37.7076131999975672], - [-122.5247187000021967, 37.7835871999971715], - [-122.4798767000009008, 37.8151571999998453], - ] - ] - } - - out = h3.polyfill(geo, 9, True) - assert len(out) > 1000 - - -def test_polyfill_down_under(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [151.1979259, -33.8555555], - [151.2074556, -33.8519779], - [151.224743, -33.8579597], - [151.2254986, -33.8582212], - [151.235313348, -33.8564183032], - [151.234799568, -33.8594049408], - [151.233485084, -33.8641069037], - [151.233181742, -33.8715791334], - [151.223980353, -33.8876967719], - [151.219388501, -33.8873877027], - [151.2189209, -33.8869995], - [151.2181177, -33.886283399999996], - [151.2157995, -33.8851287], - [151.2156925, -33.8852471], - [151.2141233, -33.8851287], - [151.2116267, -33.8847438], - [151.2083456, -33.8834707], - [151.2080246, -33.8827601], - [151.2059204, -33.8816053], - [151.2043868, -33.8827601], - [151.2028176, -33.8838556], - [151.2022826, -33.8839148], - [151.2011057, -33.8842405], - [151.1986114, -33.8842819], - [151.1986091, -33.8842405], - [151.1948287, -33.8773416], - [151.1923322, -33.8740845], - [151.1850566, -33.8697019], - [151.1902636, -33.8625354], - [151.1986805, -33.8612915], - [151.1979259, -33.8555555], - ] - ] - } - - out = h3.polyfill(geo, 9, True) - assert len(out) > 10 - - -def test_polyfill_far_east(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [142.86483764648438, 41.92578147109541], - [142.86483764648438, 42.29965889253408], - [143.41552734375, 42.29965889253408], - [143.41552734375, 41.92578147109541], - [142.86483764648438, 41.92578147109541], - ] - ] - } - - out = h3.polyfill(geo, 9, True) - assert len(out) > 10 - - -def test_polyfill_southern_tip(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [-67.642822265625, -55.41654360858007], - [-67.642822265625, -54.354955689554096], - [-64.742431640625, -54.354955689554096], - [-64.742431640625, -55.41654360858007], - [-67.642822265625, -55.41654360858007], - ] - ] - } - - out = h3.polyfill(geo, 9, True) - assert len(out) > 10 - - -def test_polyfill_null_island(): - geo = { - "type": "Polygon", - "coordinates": [ - [ - [-3.218994140625, -3.0856655287215378], - [-3.218994140625, 3.6888551431470478], - [3.5815429687499996, 3.6888551431470478], - [3.5815429687499996, -3.0856655287215378], - [-3.218994140625, -3.0856655287215378], - ] - ] - } - - out = h3.polyfill(geo, 4, True) - assert len(out) > 10 - - -def test_h3_set_to_multi_polygon_empty(): - out = h3.h3_set_to_multi_polygon([]) - assert out == [] - - -def test_h3_set_to_multi_polygon_single(): - h = '89283082837ffff' - hexes = {h} - - # multi_polygon - mp = h3.h3_set_to_multi_polygon(hexes) - vertices = h3.h3_to_geo_boundary(h) - - # We shift the expected circular list so that it starts from - # multi_polygon[0][0][0], since output starting from any vertex - # would be correct as long as it's in order. - expected_coords = shift_circular_list( - mp[0][0][0], - [ - vertices[2], - vertices[3], - vertices[4], - vertices[5], - vertices[0], - vertices[1], - ] - ) - - expected = [[expected_coords]] - - assert mp == expected - - -def test_h3_set_to_multi_polygon_single_geo_json(): - hexes = ['89283082837ffff'] - mp = h3.h3_set_to_multi_polygon(hexes, True) - vertices = h3.h3_to_geo_boundary(hexes[0], True) - - # We shift the expected circular list so that it starts from - # multi_polygon[0][0][0], since output starting from any vertex - # would be correct as long as it's in order. - expected_coords = shift_circular_list( - mp[0][0][0], - [ - vertices[2], - vertices[3], - vertices[4], - vertices[5], - vertices[0], - vertices[1] - ] - ) - - expected = [[expected_coords]] - - # polygon count matches expected - assert len(mp) == 1 - - # loop count matches expected - assert len(mp[0]) == 1 - - # coord count 7 matches expected according to geojson format - assert len(mp[0][0]) == 7 - - # first coord should be the same as last coord according to geojson format - assert mp[0] == mp[-1] - - # the coord should be (lng, lat) according to geojson format - assert mp[0][0][0][0] == approx(-122.42778275313199) - assert mp[0][0][0][1] == approx(37.77598951883773) - - # Discard last coord for testing below, since last coord is - # the same as the first one - mp[0][0].pop() - assert mp == expected - - -def test_h3_set_to_multi_polygon_contiguous(): - # the second hexagon shares v0 and v1 with the first - hexes = ['89283082837ffff', '89283082833ffff'] - - # multi_polygon - mp = h3.h3_set_to_multi_polygon(hexes) - vertices0 = h3.h3_to_geo_boundary(hexes[0]) - vertices1 = h3.h3_to_geo_boundary(hexes[1]) - - # We shift the expected circular list so that it starts from - # multi_polygon[0][0][0], since output starting from any vertex - # would be correct as long as it's in order. - expected_coords = shift_circular_list( - mp[0][0][0], - [ - vertices1[0], - vertices1[1], - vertices1[2], - vertices0[1], - vertices0[2], - vertices0[3], - vertices0[4], - vertices0[5], - vertices1[4], - vertices1[5], - ] - ) - - expected = [[expected_coords]] - - assert len(mp) == 1 # polygon count matches expected - assert len(mp[0]) == 1 # loop count matches expected - assert len(mp[0][0]) == 10 # coord count matches expected - - assert mp == expected - - -def test_h3_set_to_multi_polygon_non_contiguous(): - # the second hexagon does not touch the first - hexes = {'89283082837ffff', '8928308280fffff'} - # multi_polygon - mp = h3.h3_set_to_multi_polygon(hexes) - - assert len(mp) == 2 # polygon count matches expected - assert len(mp[0]) == 1 # loop count matches expected - assert len(mp[0][0]) == 6 # coord count 1 matches expected - assert len(mp[1][0]) == 6 # coord count 2 matches expected - - -def test_h3_set_to_multi_polygon_hole(): - # Six hexagons in a ring around a hole - hexes = [ - '892830828c7ffff', '892830828d7ffff', '8928308289bffff', - '89283082813ffff', '8928308288fffff', '89283082883ffff', - ] - mp = h3.h3_set_to_multi_polygon(hexes) - - assert len(mp) == 1 # polygon count matches expected - assert len(mp[0]) == 2 # loop count matches expected - assert len(mp[0][0]) == 6 * 3 # outer coord count matches expected - assert len(mp[0][1]) == 6 # inner coord count matches expected - - -def test_h3_set_to_multi_polygon_2k_ring(): - h = '8930062838bffff' - hexes = h3.k_ring(h, 2) - # multi_polygon - mp = h3.h3_set_to_multi_polygon(hexes) - - assert len(mp) == 1 # polygon count matches expected - assert len(mp[0]) == 1 # loop count matches expected - assert len(mp[0][0]) == 6 * (2 * 2 + 1) # coord count matches expected - - hexes2 = { - '89300628393ffff', '89300628383ffff', '89300628397ffff', - '89300628067ffff', '89300628387ffff', '893006283bbffff', - '89300628313ffff', '893006283cfffff', '89300628303ffff', - '89300628317ffff', '8930062839bffff', h, - '8930062806fffff', '8930062838fffff', '893006283d3ffff', - '893006283c3ffff', '8930062831bffff', '893006283d7ffff', - '893006283c7ffff' - } - - mp2 = h3.h3_set_to_multi_polygon(hexes2) - - assert len(mp2) == 1 # polygon count matches expected - assert len(mp2[0]) == 1 # loop count matches expected - assert len(mp2[0][0]) == 6 * (2 * 2 + 1) # coord count matches expected - - hexes3 = list(h3.k_ring(h, 6)) - hexes3.sort() - mp3 = h3.h3_set_to_multi_polygon(hexes3) - - assert len(mp3[0]) == 1 # loop count matches expected - - -def test_hex_ring(): - h = '8928308280fffff' - out = h3.hex_ring(h, 1) - expected = { - '8928308280bffff', - '89283082807ffff', - '89283082877ffff', - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - - assert out == expected - assert out == h3.k_ring(h, 1) - h3.k_ring(h, 0) - - -def test_hex_ring2(): - h = '8928308280fffff' - out = h3.hex_ring(h, 2) - - expected = { - '89283082813ffff', - '89283082817ffff', - '8928308281bffff', - '89283082863ffff', - '89283082823ffff', - '8928308287bffff', - '89283082833ffff', - '8928308282bffff', - '89283082857ffff', - '892830828abffff', - '89283082847ffff', - '89283082867ffff', - } - - assert out == expected - assert out == h3.k_ring(h, 2) - h3.k_ring(h, 1) - - -def test_hex_ring_pentagon(): - h = '821c07fffffffff' - out = h3.hex_ring(h, 1) - - expected = { - '821c17fffffffff', - '821c1ffffffffff', - '821c27fffffffff', - '821c2ffffffffff', - '821c37fffffffff', - } - - assert out == expected - - -def test_compact_and_uncompact(): - geo = { - 'type': 'Polygon', - 'coordinates': [ - [ - [37.813318999983238, -122.4089866999972145], - [37.7866302000007224, -122.3805436999997056], - [37.7198061999978478, -122.3544736999993603], - [37.7076131999975672, -122.5123436999983966], - [37.7835871999971715, -122.5247187000021967], - [37.8151571999998453, -122.4798767000009008], - ] - ] - } - - hexes = h3.polyfill(geo, 9) - - compact_hexes = h3.compact(hexes) - assert len(compact_hexes) == 209 - - uncompact_hexes = h3.uncompact(compact_hexes, 9) - assert len(uncompact_hexes) == 1253 - - -def test_compact_and_uncompact_nothing(): - assert h3.compact([]) == set() - assert h3.uncompact([], 9) == set() - - -def test_uncompact_error(): - hexagons = [h3.geo_to_h3(37, -122, 10)] - - with pytest.raises(Exception): - h3.uncompact(hexagons, 5) - - -def test_compact_malformed_input(): - hexes = ['89283082813ffff'] * 13 - - with pytest.raises(Exception): - h3.compact(hexes) - - -def test_h3_to_parent(): - h = '89283082813ffff' - assert h3.h3_to_parent(h, 8) == '8828308281fffff' - - -def test_h3_to_children(): - h = '8828308281fffff' - children = h3.h3_to_children(h, 9) - - assert len(children) == 7 - - -def test_hex_range(): - h = '8928308280fffff' - out = h3.hex_range(h, 1) - assert len(out) == 1 + 6 - - expected = { - '8928308280bffff', - '89283082807ffff', - h, - '89283082877ffff', - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - - assert out == expected - - -def test_hex_range2(): - h = '8928308280fffff' - out = h3.hex_range(h, 2) - - assert len(out) == 1 + 6 + 12 - - expected = { - '89283082813ffff', - '89283082817ffff', - '8928308281bffff', - '89283082863ffff', - '89283082823ffff', - '89283082873ffff', - '89283082877ffff', - '8928308287bffff', - '89283082833ffff', - '8928308282bffff', - '8928308283bffff', - '89283082857ffff', - '892830828abffff', - '89283082847ffff', - '89283082867ffff', - '89283082803ffff', - h, - '89283082807ffff', - '8928308280bffff', - } - - assert out == expected - - -def test_hex_range_pentagon(): - h = '821c07fffffffff' # a pentagon - - # should consist of `h` and it's 5 neighbors - out = h3.hex_range(h, 1) - - expected = { - h, - '821c17fffffffff', - '821c1ffffffffff', - '821c27fffffffff', - '821c2ffffffffff', - '821c37fffffffff', - } - - assert out == expected - - -def test_hex_range_distances(): - h = '8928308280fffff' - - # should consist of `h` and it's 5 neighbors - out = h3.hex_range_distances(h, 1) - - expected = [ - {h}, - { - '8928308280bffff', - '89283082807ffff', - '89283082877ffff', - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - ] - - assert out == expected - - -def test_hex_range_distances_pentagon(): - - h = '821c07fffffffff' - out = h3.hex_range_distances(h, 1) - - expected = [ - {h}, - { - '821c17fffffffff', - '821c1ffffffffff', - '821c27fffffffff', - '821c2ffffffffff', - '821c37fffffffff', - } - ] - - assert out == expected - - -def test_hex_ranges(): - h = '8928308280fffff' - out = h3.hex_ranges([h], 1) - - assert set(out.keys()) == {h} - - expected = [ - {h}, - { - '8928308280bffff', - '89283082807ffff', - '89283082877ffff', - '89283082803ffff', - '89283082873ffff', - '8928308283bffff', - } - ] - - assert out[h] == expected - - -def test_hex_ranges_pentagon(): - h = '821c07fffffffff' - out = h3.hex_ranges([h], 1) - - expected = { - h: [ - {h}, - { - '821c17fffffffff', - '821c1ffffffffff', - '821c27fffffffff', - '821c2ffffffffff', - '821c37fffffffff' - } - ] - } - - assert out == expected - - -def test_many_hex_ranges(): - hexes = h3.k_ring('8928308280fffff', 2) - out = h3.hex_ranges(hexes, 2) - - assert len(out) == 19 - - hexes = out['8928308280fffff'] - assert [len(x) for x in hexes] == [1, 6, 12] - - -def test_many_hex_ranges2(): - hexes = h3.k_ring('8928308280fffff', 5) - out = h3.hex_ranges(hexes, 5) - assert len(out) == 91 - - hexes = out['8928308280fffff'] - - assert [len(x) for x in hexes] == [1, 6, 12, 18, 24, 30] - - -def test_hex_area(): - for i in range(0, 15): - assert isinstance(h3.hex_area(i), float) - assert isinstance(h3.hex_area(i, 'm^2'), float) - - with pytest.raises(ValueError): - h3.hex_area(5, 'ft^2') - - -def test_edge_length(): - for i in range(0, 15): - assert isinstance(h3.edge_length(i), float) - assert isinstance(h3.edge_length(i, 'm'), float) - - with pytest.raises(ValueError): - h3.edge_length(5, 'ft') - - -def test_num_hexagons(): - h0 = 122 - assert h3.num_hexagons(0) == h0 - - for i in range(0, 15): - n = h3.num_hexagons(i) * 1.0 / h0 - - assert 6**i <= n <= 7**i - - -def test_h3_get_base_cell(): - assert h3.h3_get_base_cell('8928308280fffff') == 20 - - -def test_h3_is_res_class_iiiIII(): - assert h3.h3_is_res_class_iii('8928308280fffff') - assert not h3.h3_is_res_class_iii('8828308280fffff') - assert h3.h3_is_res_class_III('8928308280fffff') - - -def test_h3_is_pentagon(): - assert h3.h3_is_pentagon('821c07fffffffff') - assert not h3.h3_is_pentagon('8928308280fffff') - - -def test_h3_indexes_are_neighbors(): - assert h3.h3_indexes_are_neighbors('8928308280fffff', '8928308280bffff') - assert not h3.h3_indexes_are_neighbors('821c07fffffffff', '8928308280fffff') - - -def test_get_h3_unidirectional_edge(): - out = h3.get_h3_unidirectional_edge('8928308280fffff', '8928308280bffff') - assert h3.h3_unidirectional_edge_is_valid(out) - - with pytest.raises(ValueError): - h3.get_h3_unidirectional_edge('821c07fffffffff', '8928308280fffff') - - -def test_h3_unidirectional_edge_is_valid(): - assert not h3.h3_unidirectional_edge_is_valid('8928308280fffff') - assert h3.h3_unidirectional_edge_is_valid('11928308280fffff') - - -def test_get_origin_h3_index_from_unidirectional_edge(): - out = h3.get_origin_h3_index_from_unidirectional_edge('11928308280fffff') - assert out == '8928308280fffff' - - -def test_get_destination_h3_index_from_unidirectional_edge(): - h = '11928308280fffff' - out = h3.get_destination_h3_index_from_unidirectional_edge(h) - - assert out == '8928308283bffff' - - -def test_get_h3_indexes_from_unidirectional_edge(): - e = h3.get_h3_indexes_from_unidirectional_edge('11928308280fffff') - - assert e == ('8928308280fffff', '8928308283bffff') - - -def test_get_h3_unidirectional_edges_from_hexagon(): - h3_uni_edges = h3.get_h3_unidirectional_edges_from_hexagon( - '8928308280fffff' - ) - assert len(h3_uni_edges) == 6 - - h3_uni_edge_pentagon = h3.get_h3_unidirectional_edges_from_hexagon( - '821c07fffffffff' - ) - assert len(h3_uni_edge_pentagon) == 5 - - -def test_get_h3_unidirectional_edge_boundary(): - e = '11928308280fffff' - boundary = h3.get_h3_unidirectional_edge_boundary(e) - assert len(boundary) == 2 - - boundary_geo_json = h3.get_h3_unidirectional_edge_boundary(e, True) - assert len(boundary_geo_json) == 3 - - -def test_h3_distance(): - h = '89283082993ffff' - - assert 0 == h3.h3_distance(h, h) - assert 1 == h3.h3_distance(h, '8928308299bffff') - assert 5 == h3.h3_distance(h, '89283082827ffff') - - -def test_h3_line(): - h1 = '8a2a84730587fff' - h2 = '8a2a8471414ffff' - - out = h3.h3_line(h1, h2) - - expected = [ - h1, - '8a2a8473059ffff', - '8a2a847304b7fff', - '8a2a84730487fff', - '8a2a8473049ffff', - '8a2a84732b37fff', - '8a2a84732b17fff', - '8a2a84732baffff', - '8a2a84732a37fff', - '8a2a84732a17fff', - '8a2a84732aaffff', - '8a2a84732a8ffff', - '8a2a84732327fff', - '8a2a8473232ffff', - '8a2a8473230ffff', - '8a2a84732227fff', - '8a2a84732207fff', - '8a2a8473221ffff', - '8a2a847322e7fff', - '8a2a847322c7fff', - '8a2a847322dffff', - '8a2a84714977fff', - '8a2a84714957fff', - '8a2a8471495ffff', - '8a2a84714877fff', - '8a2a84714857fff', - '8a2a847148effff', - '8a2a847148cffff', - '8a2a84714b97fff', - '8a2a8471416ffff', - h2, - ] - - assert out == expected - - with pytest.raises(ValueError): - h3.h3_line(h1, '8001fffffffffff') diff --git a/tests/test_lib/__init__.py b/tests/test_lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_lib/polyfill/__init__.py b/tests/test_lib/polyfill/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_lib/polyfill/test_h3.py b/tests/test_lib/polyfill/test_h3.py new file mode 100644 index 0000000..6327cf8 --- /dev/null +++ b/tests/test_lib/polyfill/test_h3.py @@ -0,0 +1,548 @@ +import h3 +import pytest + +from .. import util as u + + +class MockGeoInterface: + def __init__(self, dictionary): + assert isinstance(dictionary, dict) + self.dictionary = dictionary + + @property + def __geo_interface__(self): + return self.dictionary + + +def latlng_open(): + return [ + [37.813, -122.408], + [37.707, -122.512], + [37.815, -122.479], + ] + + +def latlng_closed(): + loop = latlng_open() + return loop + [loop[0]] + + +def swap_latlng(ll1): + ll1 = tuple( + (b, a) for a, b in ll1 + ) + return ll1 + + +def lnglat_open(): + return swap_latlng(latlng_open()) + + +def lnglat_closed(): + return swap_latlng(latlng_closed()) + + +def get_mocked(loop): + geo = MockGeoInterface({ + 'type': 'Polygon', + 'coordinates': [loop] + }) + + return geo + + +sf_7x7 = [ + (37.813319, -122.408987), + (37.786630, -122.380544), + (37.719806, -122.354474), + (37.707613, -122.512344), + (37.783587, -122.524719), + (37.815157, -122.479877), +] + +sf_hole1 = [ + (37.786980, -122.447120), + (37.766410, -122.459078), + (37.771068, -122.413710), +] + +sf_hole2 = [ + (37.747976, -122.490025), + (37.731550, -122.503758), + (37.725440, -122.452603), +] + + +def test_geo_interface(): + poly = h3.LatLngPoly(sf_hole1) + mpoly = h3.LatLngMultiPoly(poly) + + assert poly.__geo_interface__['type'] == 'Polygon' + assert mpoly.__geo_interface__['type'] == 'MultiPolygon' + + assert ( + poly.__geo_interface__['coordinates'] + == + mpoly.__geo_interface__['coordinates'][0] + ) + + +def test_shape_repr(): + poly = h3.LatLngPoly(sf_hole1) + mpoly = h3.LatLngMultiPoly(poly) + + assert ( + '' + == str(mpoly) + == repr(mpoly) + ) + + +def test_polyfill(): + poly = h3.LatLngPoly(sf_7x7) + out = h3.h3shape_to_cells(poly, res=9) + + assert len(out) == 1253 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_polygon_to_cells(): + poly = h3.LatLngPoly(sf_7x7) + # Note that `polygon_to_cells` is an alias for `h3shape_to_cells` + out = h3.polygon_to_cells(poly, res=9) + + assert len(out) == 1253 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_polygon_to_cells_experimental(): + poly = h3.LatLngPoly(sf_7x7) + # Note that `polygon_to_cells_experimental` is an alias for + # `h3shape_to_cells_experimental` + out = h3.polygon_to_cells_experimental(poly, res=9, contain='center') + + assert len(out) == 1253 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_h3shape_to_cells_experimental(): + poly = h3.LatLngPoly(sf_7x7) + + out = h3.h3shape_to_cells_experimental(poly, res=9, contain='center') + + assert len(out) == 1253 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_h3shape_to_cells_experimental_full(): + poly = h3.LatLngPoly(sf_7x7) + + out = h3.h3shape_to_cells_experimental(poly, res=9, contain='full') + + assert len(out) == 1175 + assert '89283082a1bffff' in out + assert '89283080527ffff' not in out + assert '89283095edbffff' in out + + +def test_h3shape_to_cells_experimental_overlapping(): + poly = h3.LatLngPoly(sf_7x7) + + out = h3.h3shape_to_cells_experimental(poly, res=9, contain='overlap') + + assert len(out) == 1334 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_h3shape_to_cells_experimental_overlapping_bbox(): + poly = h3.LatLngPoly(sf_7x7) + out = h3.h3shape_to_cells_experimental(poly, res=9, contain='bbox_overlap') + + assert len(out) == 1416 + assert '89283080527ffff' in out + assert '89283095edbffff' in out + + +def test_h3shape_to_cells_experimental_invalid_mode(): + poly = h3.LatLngPoly(sf_7x7) + with pytest.raises(KeyError): + h3.h3shape_to_cells_experimental( + poly, + res = 9, + contain = 'contain_overlapping_bbox_abc', + ) + + +def test_poly_to_cells_experimental_mpoly(): + mpoly = h3.LatLngMultiPoly( + h3.LatLngPoly(sf_hole1), + h3.LatLngPoly(sf_hole2), + ) + + assert ( + set(h3.h3shape_to_cells_experimental(mpoly, res=9)) + == + set(h3.h3shape_to_cells_experimental(mpoly, res=9, contain='center')) + ) + + assert ( + set(h3.h3shape_to_cells_experimental(mpoly, res=9)) + < + set(h3.h3shape_to_cells_experimental( + mpoly, + res = 9, + contain = 'overlap' + )) + ) + + assert 120 == len(h3.h3shape_to_cells_experimental( + mpoly, + res = 9, + contain = 'overlap' + )) + + +def test_poly_to_cells_experimental_mpoly_no_duplicates(): + # cells that overlap both polygons should only be returned once + a = h3.LatLngPoly([(37.70, -122.50), (37.70, -122.45), (37.75, -122.45)]) + b = h3.LatLngPoly([(37.70, -122.449), (37.70, -122.40), (37.75, -122.40)]) + mpoly = h3.LatLngMultiPoly(a, b) + + out = h3.h3shape_to_cells_experimental(mpoly, res=7, contain='overlap') + + expected = set(h3.h3shape_to_cells_experimental(a, res=7, contain='overlap')) + expected |= set(h3.h3shape_to_cells_experimental(b, res=7, contain='overlap')) + assert len(out) == len(expected) + assert set(out) == expected + + +def test_polyfill_with_hole(): + poly = h3.LatLngPoly(sf_7x7, sf_hole1) + + out = h3.h3shape_to_cells(poly, res=9) + assert len(out) == 1214 + + foo = lambda x: set(h3.h3shape_to_cells(h3.LatLngPoly(x), 9)) + + assert u.same_set( + out, + foo(sf_7x7) - foo(sf_hole1) + ) + + +def test_polyfill_with_two_holes(): + + poly = h3.LatLngPoly(sf_7x7, sf_hole1, sf_hole2) + out = h3.h3shape_to_cells(poly, 9) + assert len(out) == 1172 + + foo = lambda x: set(h3.h3shape_to_cells(h3.LatLngPoly(x), 9)) + assert u.same_set( + out, + foo(sf_7x7) - (foo(sf_hole1) | foo(sf_hole2)) + ) + + +def test_polyfill_geo_json_compliant(): + geo = get_mocked(lnglat_open()).__geo_interface__ + out = h3.geo_to_cells(geo, 9) + assert len(out) > 300 + + +def test_polyfill_geo_interface_compliant(): + geo = get_mocked(lnglat_open()) + out = h3.geo_to_cells(geo, 9) + assert len(out) > 300 + + +def test_poly_opens_loop(): + loop = lnglat_closed() + poly = h3.LatLngPoly(loop) + + assert loop[0] == loop[-1] + assert len(poly.outer) == len(loop) - 1 + + +def test_geo_to_h3shape(): + shapes = [ + h3.geo_to_h3shape(get_mocked(lnglat_open())), + h3.geo_to_h3shape(get_mocked(lnglat_closed())), + h3.LatLngPoly(latlng_open()), + h3.LatLngPoly(latlng_closed()), + ] + + for s in shapes: + assert len(h3.h3shape_to_cells(s, 8)) == 48 + + expected = { + 'type': 'Polygon', + 'coordinates': (( + (-122.408, 37.813), + (-122.512, 37.707), + (-122.479, 37.815), + (-122.408, 37.813), + ),) + } + + for shape in shapes: + assert shape.__geo_interface__ == expected + + mpolys = map(h3.LatLngMultiPoly, shapes) + + multi_expected = { + 'type': 'MultiPolygon', + 'coordinates': ((( + (-122.408, 37.813), + (-122.512, 37.707), + (-122.479, 37.815), + (-122.408, 37.813), + ),),) + } + + for mp in mpolys: + assert mp.__geo_interface__ == multi_expected + + +def test_geo_to_h3shape_passthrough(): + poly = h3.LatLngPoly(latlng_open()) + mpoly = h3.LatLngMultiPoly(poly) + + for shape in [poly, mpoly]: + assert h3.geo_to_h3shape(shape) is shape + + +def test_geo_to_h3shape_rejects_non_dict(): + with pytest.raises(ValueError, match='dict or implement __geo_interface__'): + h3.geo_to_h3shape('not a geo object') + + +def test_geo_to_h3shape_empty_polygon(): + # e.g., shapely.Polygon().__geo_interface__ + geo = MockGeoInterface({'type': 'Polygon', 'coordinates': ()}) + + shape = h3.geo_to_h3shape(geo) + assert isinstance(shape, h3.LatLngPoly) + assert shape.outer == () + assert shape.holes == () + + assert h3.geo_to_cells(geo, 9) == [] + + +def test_polyfill_down_under(): + sydney = [ + (-33.8556, 151.1979), + (-33.8520, 151.2075), + (-33.8580, 151.2247), + (-33.8582, 151.2255), + (-33.8564, 151.2353), + (-33.8594, 151.2348), + (-33.8641, 151.2335), + (-33.8716, 151.2332), + (-33.8877, 151.2240), + (-33.8874, 151.2194), + (-33.8870, 151.2189), + (-33.8863, 151.2181), + (-33.8851, 151.2158), + (-33.8852, 151.2157), + (-33.8851, 151.2141), + (-33.8847, 151.2116), + (-33.8835, 151.2083), + (-33.8828, 151.2080), + (-33.8816, 151.2059), + (-33.8828, 151.2044), + (-33.8839, 151.2028), + (-33.8839, 151.2023), + (-33.8842, 151.2011), + (-33.8843, 151.1986), + (-33.8842, 151.1986), + (-33.8773, 151.1948), + (-33.8741, 151.1923), + (-33.8697, 151.1851), + (-33.8625, 151.1903), + (-33.8613, 151.1987), + (-33.8556, 151.1979), + ] + + poly = h3.LatLngPoly(sydney) + out = h3.h3shape_to_cells(poly, 9) + assert len(out) == 92 + assert '89be0e34207ffff' in out + assert '89be0e35ddbffff' in out + + +def test_polyfill_far_east(): + geo = [ + (41.925781, 142.864838), + (42.299659, 142.864838), + (42.299659, 143.415527), + (41.925781, 143.415527), + (41.925781, 142.864838), + ] + + poly = h3.LatLngPoly(geo) + out = h3.h3shape_to_cells(poly, 9) + assert len(out) == 18507 + assert '892e18d16c3ffff' in out + assert '892e1ebb5a7ffff' in out + + +def test_polyfill_southern_tip(): + geo = [ + (-55.416544, -67.642822), + (-54.354956, -67.642822), + (-54.354956, -64.742432), + (-55.416544, -64.742432), + (-55.416544, -67.642822), + ] + + poly = h3.LatLngPoly(geo) + out = h3.h3shape_to_cells(poly, 9) + assert len(out) == 223247 + assert '89df4000003ffff' in out + assert '89df4636b27ffff' in out + + +def test_polyfill_null_island(): + geo = [ + (-3, -3), + (+3, -3), + (+3, +3), + (-3, +3), + (-3, -3), + ] + + poly = h3.LatLngPoly(geo) + out = h3.h3shape_to_cells(poly, 4) + assert len(out) == 345 + assert '847421bffffffff' in out + assert '84825ddffffffff' in out + + +def test_cells_to_h3shape_empty(): + mpoly = h3.cells_to_h3shape([]) + assert list(mpoly) == [] + + +def test_cells_to_h3shape_single(): + h = '89283082837ffff' + cells = {h} + + mpoly = h3.cells_to_h3shape(cells, tight=False) + assert len(mpoly) == 1 + poly = mpoly[0] + + vertices = h3.cell_to_boundary(h) + expected_poly = h3.LatLngPoly(vertices) + + assert set(poly.outer) == set(expected_poly.outer) + assert poly.holes == expected_poly.holes == () + + +def test_cells_to_h3shape_contiguous(): + a = '89283082837ffff' + b = '89283082833ffff' + assert h3.are_neighbor_cells(a, b) + + mpoly = h3.cells_to_h3shape([a, b], tight=False) + assert len(mpoly) == 1 + poly = mpoly[0] + + assert len(poly.outer) == 10 + assert poly.holes == () + + verts_a = h3.cell_to_boundary(a) + verts_b = h3.cell_to_boundary(b) + assert set(poly.outer) == set(verts_a) | set(verts_b) + + +def test_cells_to_h3shape_non_contiguous(): + a = '89283082837ffff' + b = '8928308280fffff' + assert not h3.are_neighbor_cells(a, b) + + mpoly = h3.cells_to_h3shape([a, b]) + assert len(mpoly) == 2 + + assert all(poly.holes == () for poly in mpoly) + assert all(len(poly.outer) == 6 for poly in mpoly) + + verts_a = h3.cell_to_boundary(a) + verts_b = h3.cell_to_boundary(b) + + verts_both = set.union(*[set(poly.outer) for poly in mpoly]) + assert verts_both == set(verts_a) | set(verts_b) + + +def test_cells_to_h3shape_hole(): + # Six hexagons in a ring around a hole + cells = [ + '892830828c7ffff', '892830828d7ffff', '8928308289bffff', + '89283082813ffff', '8928308288fffff', '89283082883ffff', + ] + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 1 + poly = mpoly[0] + + assert len(poly.holes) == 1 + assert len(poly.holes[0]) == 6 + assert len(poly.outer) == 6 * 3 + + +def test_cells_to_h3shape_2grid_disk(): + h = '8930062838bffff' + cells = h3.grid_disk(h, 2) + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 1 + poly = mpoly[0] + + assert len(poly.holes) == 0 + assert len(poly.outer) == 6 * (2 * 2 + 1) + + +def test_multipoly_checks(): + + with pytest.raises(ValueError): + h3.LatLngMultiPoly('foo') + + with pytest.raises(ValueError): + h3.LatLngMultiPoly(1) + + with pytest.raises(ValueError): + h3.LatLngMultiPoly([[(1, 2), (3, 4)]]) + + +def test_3d_geo(): + loop = lnglat_open() + + loop2d = [(lng, lat) for lng, lat in loop] + loop3d = [(lng, lat, 0.0) for lng, lat in loop] + + geo2d = get_mocked(loop2d) + geo3d = get_mocked(loop3d) + + shape2 = h3.geo_to_h3shape(geo2d) + shape3 = h3.geo_to_h3shape(geo3d) + + out2 = h3.h3shape_to_cells(shape2, 9) + out3 = h3.h3shape_to_cells(shape3, 9) + + assert len(out2) == 344 + assert set(out2) == set(out3) + + +def test_against_3d_polygons(): + # LatLngPoly still expects just a lat/lng. it won't handle 3d coords + loop3d = [ + (lat, lng, 0.0) + for lat, lng in latlng_open() + ] + + with pytest.raises(ValueError): + h3.LatLngPoly(loop3d) diff --git a/tests/test_lib/polyfill/test_polyfill.py b/tests/test_lib/polyfill/test_polyfill.py new file mode 100644 index 0000000..f70c639 --- /dev/null +++ b/tests/test_lib/polyfill/test_polyfill.py @@ -0,0 +1,171 @@ +import h3 +import pytest + +from h3 import H3ResDomainError + +from .. import util as u + + +def get_us_box_coords(): + + # big center chunk of the US in lat/lng order + outer = [ + [42.68, -110.61], + [32.17, -109.02], + [31.57, -94.26], + [42.94, -89.38], + [42.68, -110.61] + ] + + hole1 = [ + [39.77, -105.07], + [34.81, -104.72], + [34.77, -98.39], + [40.14, -96.72], + [39.77, -105.07] + ] + + hole2 = [ + [41.37, -98.61], + [40.04, -91.80], + [42.32, -91.80], + [41.37, -98.61] + ] + + return outer, hole1, hole2 + + +def test_h3shape_to_cells(): + + # approximate lat/lngs for State of Maine + maine = [ + (45.137, -67.137), + (44.810, -66.965), + (44.325, -68.033), + (43.980, -69.060), + (43.684, -70.116), + (43.090, -70.646), + (43.080, -70.751), + (43.220, -70.798), + (43.368, -70.982), + (43.466, -70.944), + (45.305, -71.085), + (45.460, -70.660), + (45.915, -70.305), + (46.693, -70.000), + (47.448, -69.237), + (47.185, -68.905), + (47.355, -68.234), + (47.066, -67.790), + (45.703, -67.791), + (45.137, -67.137), + ] + + # a very rough hexagonal approximation to the State of Maine + expected = { + '832b13fffffffff', + '832b18fffffffff', + '832b1afffffffff', + '832b1efffffffff', + '832ba9fffffffff', + '832badfffffffff' + } + + poly = h3.LatLngPoly(maine) + out = h3.h3shape_to_cells(poly, 3) + + assert u.same_set(out, expected) + + +def test_h3shape_to_cells2(): + lnglat, _, _ = get_us_box_coords() + + poly = h3.LatLngPoly(lnglat) + out = h3.h3shape_to_cells(poly, 5) + + assert len(out) == 7063 + + +# todo: we can generate segfaults with malformed input data to polyfill +# need to test for this and avoid segfault +# def test_polyfill_segfault(): +# pass + + +def test_h3shape_to_cells_holes(): + + outer, hole1, hole2 = get_us_box_coords() + + assert 7063 == len( + h3.h3shape_to_cells(h3.LatLngPoly(outer), 5) + ) + + for res in 1, 2, 3, 4, 5: + cells_all = h3.h3shape_to_cells(h3.LatLngPoly(outer), res) + poly = h3.LatLngPoly(outer, hole1, hole2) + cells_holes = set(h3.h3shape_to_cells(poly, res=res)) + + cells_1 = set(h3.h3shape_to_cells(h3.LatLngPoly(hole1), res)) + cells_2 = set(h3.h3shape_to_cells(h3.LatLngPoly(hole2), res)) + + assert len(cells_all) == len(cells_holes) + len(cells_1) + len(cells_2) + assert u.same_set( + cells_all, + set.union(cells_holes, cells_1, cells_2) + ) + + +def test_resolution(): + poly = h3.LatLngPoly([]) + + assert h3.h3shape_to_cells(poly, 0) == [] + assert h3.h3shape_to_cells(poly, 15) == [] + + with pytest.raises(H3ResDomainError): + h3.h3shape_to_cells(poly, -1) + + with pytest.raises(H3ResDomainError): + h3.h3shape_to_cells(poly, 16) + + +def test_invalid_polygon(): + """ + We were previously seeing segfaults on data like + this because we weren't raising errors inside + some `cdef` functions. + """ + with pytest.raises(TypeError): + h3.LatLngPoly([1, 2, 3]) + + with pytest.raises(ValueError): + h3.LatLngPoly([[1, 2, 3]]) + + +def test_bad_geo_input(): + with pytest.raises(ValueError): + h3.h3shape_to_cells('not a shape', 9) + + with pytest.raises(ValueError): + h3.h3shape_to_cells_experimental('not a shape', res=9) + + with pytest.raises(ValueError): + h3.geo_to_cells({'type': 'not a shape', 'coordinates': None}, 9) + + with pytest.raises(ValueError): + h3.geo_to_cells('not a shape', 9) + + +def test_cells_to_geo(): + h = '89754e64993ffff' + res = h3.get_resolution(h) + + geo = h3.cells_to_geo([h], tight=False) + coord = geo['coordinates'] + + assert geo['type'] == 'MultiPolygon' # todo: TBD + assert len(coord) == 1 + coord = coord[0] + assert len(coord[0]) == 7 + assert coord[0][0] == coord[0][-1] + + assert h3.geo_to_cells(geo, res) == [h] diff --git a/tests/test_lib/polyfill/test_polyfill_ordering.py b/tests/test_lib/polyfill/test_polyfill_ordering.py new file mode 100644 index 0000000..e0e43d8 --- /dev/null +++ b/tests/test_lib/polyfill/test_polyfill_ordering.py @@ -0,0 +1,96 @@ +""" Test that `h3shape_to_cells` can take in polygon inputs +where the LinearRings may or may not follow the right hand rule, +and they may or may not be closed loops (where the last element +is equal to the first). + +Test all permutations of these rules on polygons with +0, 1, and 2 holes. Ensure that for any polygon, each LinearRing +may follow a different subset of rules. +""" + +import h3 +import itertools + + +def reverse(loop): + return list(reversed(loop)) + + +def drop_last(loop): + return loop[:-1] + + +def toggle_map(func, poly): + """ Return all permutations of `func` being applied or not + to each element of `poly` + + returns iterable of length 2**len(poly) + """ + mapped = (list(func(loop)) for loop in poly) + + return itertools.product(*zip(poly, mapped)) + + +def chain_toggle_map(func, seq): + seq = (toggle_map(func, p) for p in seq) + seq = itertools.chain(*seq) + + return seq + + +def input_permutations(geo, res=5): + g = [geo] + g = chain_toggle_map(drop_last, g) + g = chain_toggle_map(reverse, g) + + for p in g: + poly = h3.LatLngPoly(*p) + cells = h3.h3shape_to_cells(poly, res=res) + yield cells + + +def get_us_box_coords(): + + # big center chunk of the US in lat/lng order + outer = [ + [42.68, -110.61], + [32.17, -109.02], + [31.57, -94.26], + [42.94, -89.38], + [42.68, -110.61] + ] + + hole1 = [ + [39.77, -105.07], + [34.81, -104.72], + [34.77, -98.39], + [40.14, -96.72], + [39.77, -105.07] + ] + + hole2 = [ + [41.37, -98.61], + [40.04, -91.80], + [42.32, -91.80], + [41.37, -98.61] + ] + + return outer, hole1, hole2 + + +def test_input_format(): + geo = get_us_box_coords() + + assert len(geo) == 3 + + # two holes + for cells in input_permutations(geo[:3]): + assert len(cells) == 5437 + + # one hole + for cells in input_permutations(geo[:2]): + assert len(cells) == 5726 + + # zero holes + for cells in input_permutations(geo[:1]): + assert len(cells) == 7063 diff --git a/tests/test_lib/polyfill/test_polygon_class.py b/tests/test_lib/polyfill/test_polygon_class.py new file mode 100644 index 0000000..a3639b6 --- /dev/null +++ b/tests/test_lib/polyfill/test_polygon_class.py @@ -0,0 +1,65 @@ +import h3 +import pytest + + +def test_repr(): + a = '8928308280fffff' + b = h3.grid_ring(a, 5).pop() + + cells1 = h3.grid_ring(b, 2) + [a] + cells2 = cells1 + [b] + + mpoly1 = h3.cells_to_h3shape(cells1) + mpoly2 = h3.cells_to_h3shape(cells2) + + # unfortunately output order is nondeterministic + mpoly1 = sorted(map(str, mpoly1)) + mpoly2 = sorted(map(str, mpoly2)) + + assert mpoly1 == [ + '', + '', + ] + + assert mpoly2 == [ + '', + '', + '', + ] + + +def test_LatLngPoly_len(): + cells = {'8928308280fffff'} + + poly = h3.cells_to_h3shape(cells, tight=True) + + with pytest.raises(NotImplementedError): + len(poly) + + +def test_bad_subclass(): + class H3Shoop(h3.H3Shape): + def __geo_interface__(self): + return 'foo' + + shoop = H3Shoop() + shoop.__geo_interface__() + + with pytest.raises(ValueError): + h3.h3shape_to_cells(shoop, res=9) + + with pytest.raises(ValueError): + h3.h3shape_to_cells_experimental(shoop, res=9) + + +def test_closed_loop_with_too_few_points(): + # a closed loop of 3 points only has 2 distinct points once the + # repeated closing point is removed + a, b = (37.68, -122.54), (37.82, -122.34) + outer = [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34)] + + with pytest.raises(ValueError, match='at least 3 points'): + h3.LatLngPoly([a, b, a]) + + with pytest.raises(ValueError, match='at least 3 points'): + h3.LatLngPoly(outer, [a, b, a]) diff --git a/tests/test_lib/polyfill/test_to_multipoly.py b/tests/test_lib/polyfill/test_to_multipoly.py new file mode 100644 index 0000000..80c5a75 --- /dev/null +++ b/tests/test_lib/polyfill/test_to_multipoly.py @@ -0,0 +1,360 @@ +import pytest + +import h3 +from h3._cy.error_system import H3DuplicateInputError, H3ResMismatchError, H3FailedError + +from .. import util as u + + +def assert_cells_roundtrip(cells): + """Convert cells to multi-polygon and back, checking we recover the original set.""" + res = h3.get_resolution(cells[0]) + mpoly = h3.cells_to_h3shape(cells, tight=False) + + recovered = h3.h3shape_to_cells(mpoly, res) + + assert u.same_set(recovered, cells) + + +def test_cells_to_h3shape(): + h = '8928308280fffff' + cells = h3.grid_disk(h, 1) + + mpoly = h3.cells_to_h3shape(cells, tight=False) + poly = mpoly[0] + + poly2 = h3.LatLngPoly(poly.outer, *poly.holes) + out = h3.h3shape_to_cells(poly2, 9) + + assert u.same_set(out, cells) + + +def test_cells_to_h3shape_tight(): + h = '8928308280fffff' + cells = h3.grid_disk(h, 1) + + poly = h3.cells_to_h3shape(cells, tight=True) + poly2 = h3.LatLngPoly(poly.outer, *poly.holes) + out = h3.h3shape_to_cells(poly2, 9) + + assert u.same_set(out, cells) + + +def test_2_polys(): + h = '8928308280fffff' + cells = h3.grid_ring(h, 2) + cells = cells + [h] + # cells should be a center hex, and the 2-ring around it + # (with the 1-ring being absent) + + mpoly = h3.cells_to_h3shape(cells) + + out = [ + set(h3.h3shape_to_cells(poly, 9)) + for poly in mpoly + ] + + assert u.same_set( + set.union(*out), + cells + ) + assert set(map(len, out)) == {1, 12} + + +def test_empty(): + mpoly = h3.cells_to_h3shape([], tight=False) + assert isinstance(mpoly, h3.LatLngMultiPoly) + assert len(mpoly) == 0 + + mpoly = h3.cells_to_h3shape([], tight=True) + assert isinstance(mpoly, h3.LatLngMultiPoly) + assert len(mpoly) == 0 + + +def test_all_res0_cells(): + cells = h3.get_res0_cells() + mpoly = h3.cells_to_h3shape(cells, tight=False) + + # We should get an "entire globe" multipolygon back + # The current implementation returns 8 triangles + assert len(mpoly) == 8 + for poly in mpoly: + assert len(poly.outer) == 3 + assert len(poly.holes) == 0 + + # Roundtrip fails: h3shape_to_cells recovers only 69/122 cells. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + cells2 = h3.h3shape_to_cells(mpoly, 0) + assert len(cells2) == 69 + + +def test_pentagons(): + for res in range(16): + cells = h3.get_pentagons(res) + mpoly = h3.cells_to_h3shape(cells, tight=False) + + if res % 2 == 0: + expected_verts = 5 + else: + # pentagons have distortion vertices at odd resolutions + expected_verts = 10 + + assert len(mpoly) == 12 + for poly in mpoly: + assert len(poly.holes) == 0 + assert len(poly.outer) == expected_verts + + assert_cells_roundtrip(cells) + + +def test_duplicate_cells_error(): + cell = '8928308280fffff' + with pytest.raises(H3DuplicateInputError): + h3.cells_to_h3shape([cell, cell]) + + +def test_mixed_resolution_error(): + with pytest.raises(H3ResMismatchError): + h3.cells_to_h3shape(['8027fffffffffff', '81efbffffffffff']) + + +def test_three_polygons(): + cells = [ + '8027fffffffffff', '802bfffffffffff', '804dfffffffffff', + '8067fffffffffff', '806dfffffffffff', '8049fffffffffff', + '805ffffffffffff', '8057fffffffffff', '807dfffffffffff', + '80a5fffffffffff', '80a9fffffffffff', '808bfffffffffff', + '801bfffffffffff', '8035fffffffffff', '803ffffffffffff', + '8053fffffffffff', '8043fffffffffff', '8021fffffffffff', + '8011fffffffffff', '801ffffffffffff', '8097fffffffffff', + ] + + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 3 + hole_counts = [len(p.holes) for p in mpoly] + + # Polygons are ordered by size, and we know the hole counts of each + assert hole_counts == [3, 1, 0] + + assert_cells_roundtrip(cells) + + +def test_issue_1049(): + cells = [ + '827487fffffffff', '82748ffffffffff', '827497fffffffff', + '82749ffffffffff', '8274affffffffff', '8274c7fffffffff', + '8274cffffffffff', '8274d7fffffffff', '8274e7fffffffff', + '8274effffffffff', '8274f7fffffffff', '82754ffffffffff', + '827c07fffffffff', '827c27fffffffff', '827c2ffffffffff', + '827c37fffffffff', '827d87fffffffff', '827d8ffffffffff', + '827d97fffffffff', '827d9ffffffffff', '827da7fffffffff', + '827daffffffffff', '82801ffffffffff', '8280a7fffffffff', + '8280affffffffff', '8280b7fffffffff', '828197fffffffff', + '82819ffffffffff', '8281a7fffffffff', '8281b7fffffffff', + '828207fffffffff', '82820ffffffffff', '828227fffffffff', + '82822ffffffffff', '8282e7fffffffff', '828307fffffffff', + '82830ffffffffff', '82831ffffffffff', '82832ffffffffff', + '828347fffffffff', '82834ffffffffff', '828357fffffffff', + '82835ffffffffff', '828367fffffffff', '828377fffffffff', + '82a447fffffffff', '82a457fffffffff', '82a45ffffffffff', + '82a467fffffffff', '82a46ffffffffff', '82a477fffffffff', + '82a4c7fffffffff', '82a4cffffffffff', '82a4d7fffffffff', + '82a4e7fffffffff', '82a4effffffffff', '82a4f7fffffffff', + '82a547fffffffff', '82a54ffffffffff', '82a557fffffffff', + '82a55ffffffffff', '82a567fffffffff', '82a577fffffffff', + '82a837fffffffff', '82a897fffffffff', '82a8a7fffffffff', + '82a8b7fffffffff', '82a917fffffffff', '82a927fffffffff', + '82a937fffffffff', '82a987fffffffff', '82a98ffffffffff', + '82a997fffffffff', '82a99ffffffffff', '82a9a7fffffffff', + '82a9affffffffff', '82ac47fffffffff', '82ac57fffffffff', + '82ac5ffffffffff', '82ac67fffffffff', '82ac6ffffffffff', + '82ac77fffffffff', '82ad47fffffffff', '82ad4ffffffffff', + '82ad57fffffffff', '82ad5ffffffffff', '82ad67fffffffff', + '82ad77fffffffff', '82c207fffffffff', '82c217fffffffff', + '82c227fffffffff', '82c237fffffffff', '82c287fffffffff', + '82c28ffffffffff', '82c29ffffffffff', '82c2a7fffffffff', + '82c2affffffffff', '82c2b7fffffffff', '82c307fffffffff', + '82c317fffffffff', '82c31ffffffffff', '82c337fffffffff', + '82cfb7fffffffff', '82d0c7fffffffff', '82d0d7fffffffff', + '82d0dffffffffff', '82d0e7fffffffff', '82d0f7fffffffff', + '82d147fffffffff', '82d157fffffffff', '82d15ffffffffff', + '82d167fffffffff', '82d177fffffffff', '82d187fffffffff', + '82d18ffffffffff', '82d197fffffffff', '82d19ffffffffff', + '82d1a7fffffffff', '82d1affffffffff', '82dc47fffffffff', + '82dc57fffffffff', '82dc5ffffffffff', '82dc67fffffffff', + '82dc6ffffffffff', '82dc77fffffffff', '82dcc7fffffffff', + '82dccffffffffff', '82dcd7fffffffff', '82dce7fffffffff', + '82dceffffffffff', '82dcf7fffffffff', '82dd1ffffffffff', + '82dd47fffffffff', '82dd4ffffffffff', '82dd57fffffffff', + '82dd5ffffffffff', '82dd6ffffffffff', '82dd87fffffffff', + '82dd8ffffffffff', '82dd97fffffffff', '82dd9ffffffffff', + '82ddaffffffffff', '82ddb7fffffffff', '82dec7fffffffff', + '82decffffffffff', '82ded7fffffffff', '82dee7fffffffff', + '82deeffffffffff', '82def7fffffffff', '82df0ffffffffff', + '82df1ffffffffff', '82df47fffffffff', '82df4ffffffffff', + '82df57fffffffff', '82df5ffffffffff', '82df77fffffffff', + '82df8ffffffffff', '82df9ffffffffff', '82e6c7fffffffff', + '82e6cffffffffff', '82e6d7fffffffff', '82e6dffffffffff', + '82e6effffffffff', '82e6f7fffffffff', + ] + + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 12 + for poly in mpoly: + assert len(poly.holes) == 0 + + assert_cells_roundtrip(cells) + + +def test_equator_cells(): + """Continuous band of cells overlapping the equator. + """ + cells = [ + '81807ffffffffff', '817efffffffffff', '81723ffffffffff', + '817ebffffffffff', '817c3ffffffffff', '817e3ffffffffff', + '817a3ffffffffff', '8166fffffffffff', '8172bffffffffff', + '816afffffffffff', '81933ffffffffff', '8168fffffffffff', + '8188fffffffffff', '81853ffffffffff', '817f7ffffffffff', + '8180bffffffffff', '81783ffffffffff', '81743ffffffffff', + '8170bffffffffff', '8173bffffffffff', '8179bffffffffff', + '817cbffffffffff', '8188bffffffffff', '81857ffffffffff', + '816f7ffffffffff', '8177bffffffffff', '81617ffffffffff', + '816f3ffffffffff', '8174bffffffffff', '8180fffffffffff', + '817a7ffffffffff', '81767ffffffffff', '81757ffffffffff', + '81957ffffffffff', '81787ffffffffff', '81847ffffffffff', + '81653ffffffffff', '817bbffffffffff', '816cfffffffffff', + '816abffffffffff', '815f3ffffffffff', '817c7ffffffffff', + '8168bffffffffff', '818cbffffffffff', '818cfffffffffff', + '818afffffffffff', '8174fffffffffff', '8172fffffffffff', + '8170fffffffffff', '816fbffffffffff', '81657ffffffffff', + '816c7ffffffffff', '8186bffffffffff', '81763ffffffffff', + '818a7ffffffffff', '8186fffffffffff', '81707ffffffffff', + '8182bffffffffff', '818f3ffffffffff', '8182fffffffffff', + ] + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 1 + poly = mpoly[0] + assert len(poly.holes) == 1 + + # Roundtrip fails: h3shape_to_cells recovers only 18/60 cells. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + cells2 = h3.h3shape_to_cells(mpoly, 1) + assert len(cells2) == 18 + + +def test_prime_meridian(): + """Continuous band of cells overlapping the prime meridian. + """ + cells = [ + '81efbffffffffff', '81c07ffffffffff', '81d1bffffffffff', + '81097ffffffffff', '8109bffffffffff', '81d0bffffffffff', + '81987ffffffffff', '81017ffffffffff', '81e67ffffffffff', + '81ddbffffffffff', '81ac7ffffffffff', '8158bffffffffff', + '81397ffffffffff', '81593ffffffffff', '81c17ffffffffff', + '81827ffffffffff', '81197ffffffffff', '81eebffffffffff', + '81383ffffffffff', '81dcbffffffffff', '81757ffffffffff', + '81093ffffffffff', '81073ffffffffff', '8159bffffffffff', + '81f17ffffffffff', '81187ffffffffff', '81007ffffffffff', + '81997ffffffffff', '81753ffffffffff', '81033ffffffffff', + '81f2bffffffffff', '8138bffffffffff', + ] + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 1 + poly = mpoly[0] + assert len(poly.holes) == 0 + assert len(poly.outer) == 128 + + # Roundtrip fails: h3shape_to_cells raises on this global polygon. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + with pytest.raises(H3FailedError): + h3.h3shape_to_cells(mpoly, 1) + + +def test_anti_meridian(): + """Continuous band of cells overlapping the anti-meridian.""" + cells = [ + '817ebffffffffff', '8133bffffffffff', '81047ffffffffff', + '81f3bffffffffff', '81dbbffffffffff', '8132bffffffffff', + '810cbffffffffff', '81bb3ffffffffff', '81db3ffffffffff', + '81bafffffffffff', '81177ffffffffff', '817fbffffffffff', + '81ba3ffffffffff', '815abffffffffff', '815bbffffffffff', + '81eafffffffffff', '81ed7ffffffffff', '81057ffffffffff', + '819a7ffffffffff', '81eabffffffffff', '819b7ffffffffff', + '81167ffffffffff', '81227ffffffffff', '8171bffffffffff', + '81237ffffffffff', '810dbffffffffff', '81033ffffffffff', + '81f2bffffffffff', '8147bffffffffff', '81f33ffffffffff', + ] + mpoly = h3.cells_to_h3shape(cells, tight=False) + + assert len(mpoly) == 1 + poly = mpoly[0] + assert len(poly.holes) == 0 + assert len(poly.outer) == 117 + + # Roundtrip fails: h3shape_to_cells raises on this global polygon. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + with pytest.raises(H3FailedError): + h3.h3shape_to_cells(mpoly, 1) + + +def test_issue_482_with_antimeridian(): + """From https://github.com/uber/h3-py/issues/482 + + Test three versions: the full set, removal of antimeridian overlaps, and removal + of one cell by the north pole also causing roundtrip issues. + + Roundtrip works after removal of all troublesome cells. + """ + cells0 = { + '8001fffffffffff', '8005fffffffffff', '8009fffffffffff', '800bfffffffffff', + '8011fffffffffff', '8015fffffffffff', '8017fffffffffff', '801ffffffffffff', + '8021fffffffffff', '8025fffffffffff', '802dfffffffffff', '802ffffffffffff', + '8031fffffffffff', '8033fffffffffff', '803dfffffffffff', '803ffffffffffff', + '8041fffffffffff', '8043fffffffffff', '804bfffffffffff', '804ffffffffffff', + '8053fffffffffff', '8059fffffffffff', '8061fffffffffff', '8063fffffffffff', + '8065fffffffffff', '8069fffffffffff', '806bfffffffffff', '8073fffffffffff', + '8077fffffffffff', + } + + # remove cells that overlap the antimeridian + cells1 = cells0 - {'8005fffffffffff', '8017fffffffffff', '8033fffffffffff'} + + # remove cell that is very close to north pole (maybe touches) + cells2 = cells1 - {'8001fffffffffff'} + + # --- cells0: all 29 cells --- + mpoly = h3.cells_to_h3shape(cells0, tight=False) + assert len(mpoly) == 1 + assert len(mpoly[0].holes) == 0 + assert len(mpoly[0].outer) == 37 + + # Roundtrip fails: recovers ~23/29, and not even a subset of the original. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + cells_out = h3.h3shape_to_cells(mpoly, 0) + assert len(cells_out) < len(cells0) # exact count differs by OS + assert not (set(cells_out) <= cells0) + + # --- cells1: remove antimeridian-crossing cells (26 remaining) --- + mpoly = h3.cells_to_h3shape(cells1, tight=False) + assert len(mpoly) == 1 + assert len(mpoly[0].holes) == 0 + assert len(mpoly[0].outer) == 37 + + # Roundtrip fails: recovers 18/26, and not even a subset of the original. + # TODO: assert_cells_roundtrip when h3shape_to_cells handles global polygons. + cells_out = h3.h3shape_to_cells(mpoly, 0) + assert len(cells_out) == 18 + assert not (set(cells_out) <= cells1) + + # --- cells2: also remove near-pole cell (25 remaining) --- + mpoly = h3.cells_to_h3shape(cells2, tight=False) + assert len(mpoly) == 1 + assert len(mpoly[0].holes) == 0 + assert len(mpoly[0].outer) == 37 + + # Roundtrip succeeds. + assert_cells_roundtrip(list(cells2)) diff --git a/tests/test_lib/test_apis/__init__.py b/tests/test_lib/test_apis/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_lib/test_apis/test_api_bindings_match.py b/tests/test_lib/test_apis/test_api_bindings_match.py new file mode 100644 index 0000000..ccc2a9c --- /dev/null +++ b/tests/test_lib/test_apis/test_api_bindings_match.py @@ -0,0 +1,15 @@ +import inspect + + +def test_api_copy_match(): + import h3 + + apis = [ + h3.api.basic_int, + h3.api.basic_str, + h3.api.memview_int, + h3.api.numpy_int, + ] + + api_set = {inspect.getsource(api) for api in apis} + assert len(api_set) == 1 diff --git a/tests/test_lib/test_apis/test_basic_int.py b/tests/test_lib/test_apis/test_basic_int.py new file mode 100644 index 0000000..3f3b14c --- /dev/null +++ b/tests/test_lib/test_apis/test_basic_int.py @@ -0,0 +1,56 @@ +import h3.api.basic_int as h3 + + +from .. import util as u + + +def test_int_output(): + lat = 37.7752702151959 + lng = -122.418307270836 + + assert h3.latlng_to_cell(lat, lng, 9) == 617700169958293503 + assert h3.latlng_to_cell(lat, lng, 9) == 0x8928308280fffff + + +def test_grid_disk(): + expected = [ + 617700169957507071, + 617700169957769215, + 617700169958031359, + 617700169958293503, + 617700169961177087, + 617700169964847103, + 617700169965109247, + ] + + out = h3.grid_disk(617700169958293503, 1) + assert u.same_set(out, expected) + + +def test_compact_cells(): + h = 617700169958293503 + cells = h3.cell_to_children(h) + + assert h3.compact_cells(cells) == [h] + + +def test_identity_scalar_bindings(): + """ + Ensure scalar functions in int APIs are bound directly to _cy implementations + to eliminate wrapper and identity call overhead (Issue #501). + """ + from h3 import _cy + + assert h3.latlng_to_cell is _cy.latlng_to_cell + assert h3.cell_to_parent is _cy.cell_to_parent + assert h3.cell_to_center_child is _cy.cell_to_center_child + assert h3.cells_to_directed_edge is _cy.cells_to_directed_edge + assert h3.get_directed_edge_origin is _cy.get_directed_edge_origin + assert h3.get_directed_edge_destination is _cy.get_directed_edge_destination + assert h3.directed_edge_to_cells is _cy.directed_edge_to_cells + assert h3.local_ij_to_cell is _cy.local_ij_to_cell + assert h3.cell_to_vertex is _cy.cell_to_vertex + + # Ensure docstrings and signatures are intact + assert h3.latlng_to_cell.__doc__ is not None + assert 'latlng_to_cell' in h3.latlng_to_cell.__name__ diff --git a/tests/test_lib/test_apis/test_basic_str.py b/tests/test_lib/test_apis/test_basic_str.py new file mode 100644 index 0000000..fccc164 --- /dev/null +++ b/tests/test_lib/test_apis/test_basic_str.py @@ -0,0 +1,43 @@ +import h3.api.basic_str as h3 + + +from .. import util as u + + +def test1(): + lat, lng = 37.7752702151959, -122.418307270836 + assert h3.latlng_to_cell(lat, lng, 9) == '8928308280fffff' + + +def test5(): + expected = [ + '89283082873ffff', + '89283082877ffff', + '8928308283bffff', + '89283082807ffff', + '8928308280bffff', + '8928308280fffff', + '89283082803ffff' + ] + + out = h3.grid_disk('8928308280fffff', 1) + assert u.same_set(out, expected) + + +def test_string_subtypes(): + + class my_str(str): + pass + + expected = [ + '89283082873ffff', + '89283082877ffff', + '8928308283bffff', + '89283082807ffff', + '8928308280bffff', + '8928308280fffff', + '89283082803ffff' + ] + + out = h3.grid_disk(my_str('8928308280fffff'), 1) + assert u.same_set(out, expected) diff --git a/tests/test_collection_inputs.py b/tests/test_lib/test_apis/test_collection_inputs.py similarity index 72% rename from tests/test_collection_inputs.py rename to tests/test_lib/test_apis/test_collection_inputs.py index aa09c4f..5f826a1 100644 --- a/tests/test_collection_inputs.py +++ b/tests/test_lib/test_apis/test_collection_inputs.py @@ -22,15 +22,15 @@ def test_set(): h = 614553222213795839 - assert basic_int.compact(ints) == {h} + assert basic_int.compact_cells(ints) == [h] with pytest.raises(TypeError): # numpy can't convert from a set - numpy_int.compact(ints) + numpy_int.compact_cells(ints) with pytest.raises(TypeError): # set isn't a memoryview - memview_int.compact(ints) + memview_int.compact_cells(ints) def test_list(): @@ -46,19 +46,19 @@ def test_list(): h = 614553222213795839 - assert basic_int.compact(ints) == {h} + assert basic_int.compact_cells(ints) == [h] # numpy can convert from a list OK # (numpy knows to convert it to uint64) - assert numpy_int.compact(ints) == np.array([h], dtype='uint64') + assert numpy_int.compact_cells(ints) == np.array([h], dtype='uint64') # little weird that numpy comparisons don't consider dtype - assert numpy_int.compact(ints) == np.array([h]) - assert not numpy_int.compact(ints).dtype == np.array([h]).dtype + assert numpy_int.compact_cells(ints) == np.array([h]) + assert not numpy_int.compact_cells(ints).dtype == np.array([h]).dtype with pytest.raises(TypeError): # list isn't a memoryview - memview_int.compact(ints) + memview_int.compact_cells(ints) def test_np_array(): @@ -74,12 +74,12 @@ def test_np_array(): h = 614553222213795839 - assert basic_int.compact(ints) == {h} + assert basic_int.compact_cells(ints) == [h] - assert numpy_int.compact(ints) == np.array([h], dtype='uint64') - assert numpy_int.compact(ints).dtype == np.dtype('uint64') + assert numpy_int.compact_cells(ints) == np.array([h], dtype='uint64') + assert numpy_int.compact_cells(ints).dtype == np.dtype('uint64') - out = memview_int.compact(ints) + out = memview_int.compact_cells(ints) assert len(out) == 1 assert out[0] == h @@ -99,15 +99,15 @@ def test_list_to_array(): h = 614553222213795839 - assert basic_int.compact(ints) == {h} - assert numpy_int.compact(ints) == np.array([h], dtype='uint64') + assert basic_int.compact_cells(ints) == [h] + assert numpy_int.compact_cells(ints) == np.array([h], dtype='uint64') with pytest.raises(ValueError): # Without the explicit dtype given above, the array # assumes it has *signed* integers # The `memview_int` interface requires a dtype match # with uint64. - memview_int.compact(ints) + memview_int.compact_cells(ints) def test_iterator(): @@ -128,14 +128,14 @@ def test_iterator(): h = 614553222213795839 ints = foo() - assert basic_int.compact(ints) == {h} + assert basic_int.compact_cells(ints) == [h] ints = foo() with pytest.raises(TypeError): # numpy can't create an array from an iterator - numpy_int.compact(ints) + numpy_int.compact_cells(ints) ints = foo() with pytest.raises(TypeError): # requires a bytes-like input - memview_int.compact(ints) + memview_int.compact_cells(ints) diff --git a/tests/test_lib/test_apis/test_ico_faces.py b/tests/test_lib/test_apis/test_ico_faces.py new file mode 100644 index 0000000..6466ab0 --- /dev/null +++ b/tests/test_lib/test_apis/test_ico_faces.py @@ -0,0 +1,30 @@ +import h3 + + +def test_icosahedron_faces(): + """ + get_icosahedron_faces is kind of a special case, because it always returns + a list of integers no matter the API + """ + answers = { + '804dfffffffffff': [2, 3, 7, 8, 12], + '80c1fffffffffff': [13], + '80bbfffffffffff': [15, 16], + } + + interfaces = [ + (h3.api.basic_str, lambda x: x), + (h3.api.basic_int, h3.str_to_int), + (h3.api.memview_int, h3.str_to_int), + (h3.api.numpy_int, h3.str_to_int), + ] + + for api, conv in interfaces: + for h in answers: + expected = answers[h] + + h = conv(h) # convert to int or str, depending on API + out = api.get_icosahedron_faces(h) + + assert isinstance(out, list) + assert set(out) == set(expected) diff --git a/tests/test_lib/test_apis/test_memview_int.py b/tests/test_lib/test_apis/test_memview_int.py new file mode 100644 index 0000000..f608f54 --- /dev/null +++ b/tests/test_lib/test_apis/test_memview_int.py @@ -0,0 +1,39 @@ +import h3.api.memview_int as h3 + + +def test1(): + lat, lng = 37.7752702151959, -122.418307270836 + assert h3.latlng_to_cell(lat, lng, 9) == 617700169958293503 + + +def test_line(): + h1 = '8928308280fffff' + h2 = '8928308287bffff' + h1, h2 = h3.str_to_int(h1), h3.str_to_int(h2) + + out = h3.grid_path_cells(h1, h2) + + # todo: are we outputting `memoryviewslice`? should we just output a memoryview? + assert 'memoryview' in str(type(out)) + + expected = [ + 617700169958293503, + 617700169964847103, + 617700169965371391, + ] + + assert list(out) == expected + + +def test_identity_scalar_bindings(): + from h3 import _cy + + assert h3.latlng_to_cell is _cy.latlng_to_cell + assert h3.cell_to_parent is _cy.cell_to_parent + assert h3.cell_to_center_child is _cy.cell_to_center_child + assert h3.cells_to_directed_edge is _cy.cells_to_directed_edge + assert h3.get_directed_edge_origin is _cy.get_directed_edge_origin + assert h3.get_directed_edge_destination is _cy.get_directed_edge_destination + assert h3.directed_edge_to_cells is _cy.directed_edge_to_cells + assert h3.local_ij_to_cell is _cy.local_ij_to_cell + assert h3.cell_to_vertex is _cy.cell_to_vertex diff --git a/tests/test_lib/test_apis/test_numpy_int.py b/tests/test_lib/test_apis/test_numpy_int.py new file mode 100644 index 0000000..6bcd0b6 --- /dev/null +++ b/tests/test_lib/test_apis/test_numpy_int.py @@ -0,0 +1,66 @@ +import h3.api.numpy_int as h3 +import numpy as np # only run this test suite if numpy is installed + +from .. import util as u + + +def test1(): + lat, lng = ( + 37.7752702151959, + -122.418307270836, + ) + assert h3.latlng_to_cell(lat, lng, 9) == 617700169958293503 + + +def test5(): + expected = { + 617700169957507071, + 617700169957769215, + 617700169958031359, + 617700169958293503, + 617700169961177087, + 617700169964847103, + 617700169965109247, + } + + out = h3.grid_disk(617700169958293503, 1) + assert isinstance(out, np.ndarray) + assert u.same_set(out, expected) + + +def test_compact_cells(): + h = 617700169958293503 + cells = h3.cell_to_children(h) + assert isinstance(cells, np.ndarray) + + assert h3.compact_cells(cells) == [h] + + +def test_numpy_str(): + expected = [ + 617700169957507071, + 617700169957769215, + 617700169958031359, + 617700169958293503, + 617700169961177087, + 617700169964847103, + 617700169965109247, + ] + cells = np.array([h3.int_to_str(h) for h in expected]) + got = [h3.str_to_int(c) for c in cells] + + assert expected == got + + +def test_identity_scalar_bindings(): + from h3 import _cy + + assert h3.latlng_to_cell is _cy.latlng_to_cell + assert h3.cell_to_parent is _cy.cell_to_parent + assert h3.cell_to_center_child is _cy.cell_to_center_child + assert h3.cells_to_directed_edge is _cy.cells_to_directed_edge + assert h3.get_directed_edge_origin is _cy.get_directed_edge_origin + assert h3.get_directed_edge_destination is _cy.get_directed_edge_destination + assert h3.directed_edge_to_cells is _cy.directed_edge_to_cells + assert h3.local_ij_to_cell is _cy.local_ij_to_cell + assert h3.cell_to_vertex is _cy.cell_to_vertex diff --git a/tests/test_lib/test_cells_and_edges.py b/tests/test_lib/test_cells_and_edges.py new file mode 100644 index 0000000..65d9d13 --- /dev/null +++ b/tests/test_lib/test_cells_and_edges.py @@ -0,0 +1,773 @@ +import h3 +import pytest + +from h3 import ( + H3FailedError, + H3ResDomainError, + H3DomainError, + H3ResMismatchError, + H3CellInvalidError, + H3NotNeighborsError, + H3DigitDomainError, + H3BaseCellDomainError, + H3DeletedDigitError, + H3IndexInvalidError, +) + + +from . import util as u + + +def test1(): + lat, lng = 37.7752702151959, -122.418307270836 + assert h3.latlng_to_cell(lat, lng, 9) == '8928308280fffff' + + +def test2(): + h = '8928308280fffff' + expected = (37.77670234943567, -122.41845932318311) + + assert h3.cell_to_latlng(h) == pytest.approx(expected) + + +def test3(): + expected = ( + (37.775197782893386, -122.41719971841658), + (37.77688044840226, -122.41612835779264), + (37.778385004930925, -122.4173879761762), + (37.77820687262238, -122.41971895414807), + (37.77652420699321, -122.42079024541877), + (37.775019673792606, -122.4195306280734), + ) + + out = h3.cell_to_boundary('8928308280fffff') + assert u.approx2(out, expected) + + +def test_grid_disk_distance(): + with pytest.raises(H3DomainError): + h3.grid_disk('8928308280fffff', -10) + + +def test_grid_ring_distance(): + with pytest.raises(H3DomainError): + h3.grid_ring('8928308280fffff', -10) + + +def test5(): + expected = [ + '89283082873ffff', + '89283082877ffff', + '8928308283bffff', + '89283082807ffff', + '8928308280bffff', + '8928308280fffff', + '89283082803ffff' + ] + + out = h3.grid_disk('8928308280fffff', 1) + assert u.same_set(out, expected) + + +def test6(): + expected = ['8928308280fffff'] + out = h3.grid_ring('8928308280fffff', 0) + assert u.same_set(out, expected) + + +def test7(): + expected = [ + '89283082803ffff', + '89283082807ffff', + '8928308280bffff', + '8928308283bffff', + '89283082873ffff', + '89283082877ffff' + ] + + out = h3.grid_ring('8928308280fffff', 1) + assert u.same_set(out, expected) + + +def test8(): + assert h3.is_valid_cell('89283082803ffff') + assert not h3.is_valid_cell('abc') + + # looks like it might be valid, but it isn't! + h_bad = '8a28308280fffff' + assert not h3.is_valid_cell(h_bad) + + # other methods should validate and raise exception if bad input + with pytest.raises(H3CellInvalidError): + h3.get_resolution(h_bad) + + +def test9(): + assert h3.get_resolution('8928308280fffff') == 9 + assert h3.get_resolution('8a28308280f7fff') == 10 + + +def test_parent(): + h = '8928308280fffff' + + assert h3.cell_to_parent(h, 7) == '872830828ffffff' + assert h3.cell_to_parent(h, 8) == '8828308281fffff' + assert h3.cell_to_parent(h, 9) == h + + with pytest.raises(H3ResMismatchError): + h3.cell_to_parent(h, 10) + + +def test_parent_err(): + # Test 1 + h = '8075fffffffffff' # latlng_to_cell(0,0,0) + + with pytest.raises(H3ResDomainError): + h3.cell_to_parent(h) + + # Test 2 + try: + h3.cell_to_parent(h) + except Exception as e: + msg = str(e) + + expected = f'Invalid parent resolution -1 for cell 0x{h}.' + + assert msg == expected + + +def test_children(): + h = '8928308280fffff' + + with pytest.raises(H3ResDomainError): + h3.cell_to_children(h, 8) + + # same resolution is set of just cell itself + out = h3.cell_to_children(h, 9) + assert out == [h] + + # one below should give children + expected = [ + '8a28308280c7fff', + '8a28308280cffff', + '8a28308280d7fff', + '8a28308280dffff', + '8a28308280e7fff', + '8a28308280effff', + '8a28308280f7fff' + ] + out = h3.cell_to_children(h, 10) + assert u.same_set(out, expected) + + # finest resolution cell should return error for children + h = '8f04ccb2c45e225' + with pytest.raises(H3ResDomainError): + h3.cell_to_children(h) + + +def test_center_child(): + h = '8928308280fffff' + + # one above should raise an exception + with pytest.raises(H3ResDomainError): + h3.cell_to_center_child(h, 8) + + # same resolution should be same cell + assert h3.cell_to_center_child(h, 9) == h + + # one below should give direct child + expected = '8a28308280c7fff' + assert h3.cell_to_center_child(h, 10) == expected + + # finest resolution hex should return error for child + h = '8f04ccb2c45e225' + with pytest.raises(H3ResDomainError): + h3.cell_to_center_child(h) + + +def test_distance(): + h = '8a28308280c7fff' + assert h3.grid_distance(h, h) == 0 + + n = h3.grid_ring(h, 1).pop() + assert h3.grid_distance(h, n) == 1 + + n = h3.grid_ring(h, 2).pop() + assert h3.grid_distance(h, n) == 2 + + +def test_distance_error(): + """ Two valid cells, but they are too far apart compute the distance + + todo: make sure this raises a E_TOO_FAR error (when we add it in the future) + """ + h1 = '8353b0fffffffff' + h2 = '835804fffffffff' + + with pytest.raises(H3FailedError): + h3.grid_distance(h1, h2) + + +def get_maine_cells(): + # lat/lngs for State of Maine + poly = h3.LatLngPoly([ + (45.137451890638886, -67.13734351262877), + (44.8097, -66.96466), + (44.3252, -68.03252), + (43.98, -69.06), + (43.68405, -70.11617), + (43.090083319667144, -70.64573401557249), + (43.08003225358635, -70.75102474636725), + (43.21973948828747, -70.79761105007827), + (43.36789581966826, -70.98176001655037), + (43.46633942318431, -70.94416541205806), + (45.3052400000002, -71.08482), + (45.46022288673396, -70.6600225491012), + (45.914794623389355, -70.30495378282376), + (46.69317088478567, -70.00014034695016), + (47.44777598732787, -69.23708614772835), + (47.184794623394396, -68.90478084987546), + (47.35462921812177, -68.23430497910454), + (47.066248887716995, -67.79035274928509), + (45.702585354182816, -67.79141211614706), + (45.137451890638886, -67.13734351262877) + ]) + + res = 5 + cells_uncomp = h3.h3shape_to_cells(poly, res=res) + + # the expected result from h3.compact_cells(cells_uncomp) + cells_comp = ['852b114ffffffff', '852b189bfffffff', '852b1163fffffff', '842ba9bffffffff', '842bad3ffffffff', '852ba9cffffffff', '842badbffffffff', '852b1e8bfffffff', '852a346ffffffff', '842b1e3ffffffff', '852b116ffffffff', '842b185ffffffff', '852b1bdbfffffff', '852bad47fffffff', '852ba9c3fffffff', '852b106bfffffff', '852a30d3fffffff', '842b1edffffffff', '852b12a7fffffff', '852b1027fffffff', '842baddffffffff', '852a349bfffffff', '852b1227fffffff', '852a3473fffffff', '852b117bfffffff', '842ba99ffffffff', '852a341bfffffff', '852ba9d3fffffff', '852b1067fffffff', '852a3463fffffff', '852baca7fffffff', '852b116bfffffff', '852b1c6bfffffff', '852a3493fffffff', '852ba9dbfffffff', '852b180bfffffff', '842bad7ffffffff', '852b1063fffffff', '842ba93ffffffff', '852a3693fffffff', '852ba977fffffff', '852b1e9bfffffff', '852bad53fffffff', '852b100ffffffff', '852b102bfffffff', '852a3413fffffff', '852ba8b7fffffff', '852bad43fffffff', '852b1c6ffffffff', '852a340bfffffff', '852b103bfffffff', '852b1813fffffff', '852b12affffffff', '842a34dffffffff', '852b1873fffffff', '852b106ffffffff', '852b115bfffffff', '852baca3fffffff', '852b114bfffffff', '852b1143fffffff', '852a348bfffffff', '852a30d7fffffff', '852b181bfffffff', '842a345ffffffff', '852b1e8ffffffff', '852b1883fffffff', '852b1147fffffff', '852a3483fffffff', '852b12a3fffffff', '852a346bfffffff', '852ba9d7fffffff', '842b18dffffffff', '852b188bfffffff', '852a36a7fffffff', '852bacb3fffffff', '852b187bfffffff', '852bacb7fffffff', '842b1ebffffffff', '842b1e5ffffffff', '852ba8a7fffffff', '842bad9ffffffff', '852a36b7fffffff', '852a347bfffffff', '832b13fffffffff', '852ba9c7fffffff', '832b1afffffffff', '842ba91ffffffff', '852bad57fffffff', '852ba8affffffff', '852b1803fffffff', '842b1e7ffffffff', '852bad4ffffffff', '852b102ffffffff', '852b1077fffffff', '852b1237fffffff', '852b1153fffffff', '852a3697fffffff', '852a36b3fffffff', '842bad1ffffffff', '842b1e1ffffffff', '852b186bfffffff', '852b1023fffffff'] # noqa + + return cells_uncomp, cells_comp, res + + +def test_compact_cells(): + cells_uncomp, cells_comp, _ = get_maine_cells() + out = h3.compact_cells(cells_uncomp) + + assert u.same_set(out, cells_comp) + + +def test_uncompact_cells(): + cells_uncomp, cells_comp, res = get_maine_cells() + out = h3.uncompact_cells(cells_comp, res) + assert u.same_set(out, cells_uncomp) + + +def test_get_num_cells(): + expected = { + 0: 122, + 1: 842, + 2: 5882, + 9: 4842432842, + 15: 569707381193162, + } + + out = { + k: h3.get_num_cells(k) + for k in expected + } + + assert expected == out + + +def test_average_hexagon_area(): + expected_in_km2 = { + 0: 4357449.416078381, + 1: 609788.441794133, + 2: 86801.780398997, + 9: 0.105332513, + 15: 8.95311e-07, + } + + out = { + k: h3.average_hexagon_area(k, unit='km^2') + for k in expected_in_km2 + } + + assert out == pytest.approx(expected_in_km2) + + +def test_average_hexagon_edge_length(): + expected_in_km = { + 0: 1281.256011, + 1: 483.0568391, + 2: 182.5129565, + 9: 0.200786148, + 15: 0.000584169, + } + + out = { + res: h3.average_hexagon_edge_length(res, unit='km') + for res in expected_in_km + } + + assert out == pytest.approx(expected_in_km) + + +def test_edge(): + h1 = '8928308280fffff' + h2 = '89283082873ffff' + + assert not h3.are_neighbor_cells(h1, h1) + assert h3.are_neighbor_cells(h1, h2) + + e = h3.cells_to_directed_edge(h1, h2) + + assert e == '12928308280fffff' + assert h3.is_valid_directed_edge(e) + assert not h3.is_valid_cell(e) + + assert h3.get_directed_edge_origin(e) == h1 + assert h3.get_directed_edge_destination(e) == h2 + + assert h3.directed_edge_to_cells(e) == (h1, h2) + + +def test_origin_to_directed_edges(): + h = '8928308280fffff' + edges = h3.origin_to_directed_edges(h) + destinations = { + h3.get_directed_edge_destination(e) + for e in edges + } + neighbors = h3.grid_ring(h, 1) + + assert u.same_set(neighbors, destinations) + + +def test_edge_boundary(): + h1 = '8928308280fffff' + h2 = '89283082873ffff' + e = h3.cells_to_directed_edge(h1, h2) + + expected = ( + (37.77688044840226, -122.41612835779266), + (37.778385004930925, -122.41738797617619) + ) + + out = h3.directed_edge_to_boundary(e) + + assert out[0] == pytest.approx(expected[0]) + assert out[1] == pytest.approx(expected[1]) + + +def test_validation(): + h = '8a28308280fffff' # invalid cell + + with pytest.raises(H3CellInvalidError): + h3.get_base_cell_number(h) + + with pytest.raises(H3CellInvalidError): + h3.get_resolution(h) + + with pytest.raises(H3CellInvalidError): + h3.cell_to_parent(h, 9) + + with pytest.raises(H3CellInvalidError): + h3.grid_distance(h, h) + + with pytest.raises(H3CellInvalidError): + h3.grid_disk(h, 1) + + with pytest.raises(H3CellInvalidError): + h3.grid_ring(h, 1) + + with pytest.raises(H3CellInvalidError): + h3.cell_to_children(h, 11) + + with pytest.raises(H3CellInvalidError): + h3.compact_cells({h}) + + with pytest.raises(H3CellInvalidError): + h3.uncompact_cells({h}, 10) + + +def test_validation2(): + h = '8928308280fffff' + + with pytest.raises(H3ResDomainError): + h3.cell_to_children(h, 17) + + assert not h3.are_neighbor_cells(h, h) + + +def test_validation_geo(): + h = '8a28308280fffff' # invalid cell + + with pytest.raises(H3CellInvalidError): + h3.cell_to_latlng(h) + + with pytest.raises(H3ResDomainError): + h3.latlng_to_cell(0, 0, 17) + + with pytest.raises(H3CellInvalidError): + h3.cell_to_boundary(h) + + # note: this won't raise an exception on bad input, but it does + # *correctly* say that two invalid indexes are not neighbors + assert not h3.are_neighbor_cells(h, h) + + +def test_edges(): + h = '8928308280fffff' + + with pytest.raises(H3NotNeighborsError): + h3.cells_to_directed_edge(h, h) + + h2 = h3.grid_ring(h, 2).pop() + with pytest.raises(H3NotNeighborsError): + h3.cells_to_directed_edge(h, h2) + + e_bad = '14928308280ffff1' + assert not h3.is_valid_directed_edge(e_bad) + + # note: won't raise an error on bad input + h3.get_directed_edge_origin(e_bad) + h3.get_directed_edge_destination(e_bad) + h3.directed_edge_to_cells(e_bad) + + +def test_line(): + h1 = '8928308280fffff' + h2 = '8928308287bffff' + + out = h3.grid_path_cells(h1, h2) + + expected = [ + '8928308280fffff', + '89283082873ffff', + '8928308287bffff' + ] + + assert out == expected + + +def test_versions(): + from packaging.version import Version + + v = h3.versions() + + assert v['python'] == h3.__version__ + + v_c = Version(v['c']) + v_p = Version(v['python']) + + # For all releases (including pre-release), major version must match + assert v_c.release[0] == v_p.release[0] + + if not v_p.is_prerelease: # pragma: no cover + # of X.Y.Z, X and Y must match + assert v_c.release[:2] == v_p.release[:2] + + +def test_str_int_convert(): + s = '8928308280fffff' + i = h3.str_to_int(s) + + assert h3.int_to_str(i) == s + + +def test_str_to_int_fail(): + h_invalid = {} + + assert not h3.is_valid_cell(h_invalid) + + +def test_edge_is_valid_fail(): + e_invalid = {} + assert not h3.is_valid_directed_edge(e_invalid) + + +def test_is_valid_out_of_uint64_range(): + for h in ['10000000000000000', '-1']: + assert not h3.is_valid_index(h) + assert not h3.is_valid_cell(h) + assert not h3.is_valid_directed_edge(h) + assert not h3.is_valid_vertex(h) + + +def test_get_pentagons(): + out = h3.get_pentagons(0) + + expected = [ + '8009fffffffffff', + '801dfffffffffff', + '8031fffffffffff', + '804dfffffffffff', + '8063fffffffffff', + '8075fffffffffff', + '807ffffffffffff', + '8091fffffffffff', + '80a7fffffffffff', + '80c3fffffffffff', + '80d7fffffffffff', + '80ebfffffffffff', + ] + + assert u.same_set(out, expected) + + out = h3.get_pentagons(5) + + expected = [ + '85080003fffffff', + '851c0003fffffff', + '85300003fffffff', + '854c0003fffffff', + '85620003fffffff', + '85740003fffffff', + '857e0003fffffff', + '85900003fffffff', + '85a60003fffffff', + '85c20003fffffff', + '85d60003fffffff', + '85ea0003fffffff', + ] + + assert u.same_set(out, expected) + + for i in range(16): + assert len(h3.get_pentagons(i)) == 12 + + +def test_uncompact_cell_input(): + # `uncompact_cells` takes in a collection of cells, not a single cell. + # Since a python string is seen as a Iterable collection, + # inputting a single cell string can raise weird errors. + + # Ensure we get a reasonably helpful answer + with pytest.raises(H3CellInvalidError): + h3.uncompact_cells('8001fffffffffff', 1) + + +def test_get_res0_cells(): + out = h3.get_res0_cells() + + assert len(out) == 122 + + # subset + pentagons = h3.get_pentagons(0) + assert set(pentagons) < set(out) + + # all valid + assert all(map(h3.is_valid_cell, out)) + + # resolution + assert all(map( + lambda h: h3.get_resolution(h) == 0, + out + )) + + # verify a few concrete cells + sub = { + '8001fffffffffff', + '8003fffffffffff', + '8005fffffffffff', + } + assert sub < set(out) + + +def test_to_local_ij_error(): + h = h3.latlng_to_cell(0, 0, 0) + + # error if we cross a face + nb = h3.grid_ring(h, k=2) + + # todo: should this be the E_TOO_FAR guy? + with pytest.raises(H3FailedError): + [h3.cell_to_local_ij(h, p) for p in nb] + + # should be fine if we do not cross a face + nb = h3.grid_ring(h, k=1) + out = {h3.cell_to_local_ij(h, p) for p in nb} + expected = {(-1, 0), (0, -1), (0, 1), (1, 0), (1, 1)} + + assert out == expected + + +def test_from_local_ij_error(): + h = h3.latlng_to_cell(0, 0, 0) + + baddies = [(1, -1), (-1, 1), (-1, -1)] + for i, j in baddies: + with pytest.raises(H3FailedError): + h3.local_ij_to_cell(h, i, j) + + # inverting output should give good data + nb = h3.grid_ring(h, k=1) + goodies = {h3.cell_to_local_ij(h, p) for p in nb} + + out = { + h3.local_ij_to_cell(h, i, j) + for i, j in goodies + } + + assert u.same_set(out, nb) + + +def test_to_local_ij_self(): + h = h3.latlng_to_cell(0, 0, 9) + out = h3.cell_to_local_ij(h, h) + + assert out == (-858, -2766) + + +def test_is_valid_index(): + assert h3.is_valid_index('8001fffffffffff') + assert not h3.is_valid_index('8a28308280fffff') + assert not h3.is_valid_index(123) + assert not h3.is_valid_index('abcd') + + +def test_is_valid_index_2(): + import h3.api.basic_int as h3 + + h = h3.latlng_to_cell(0,0,9) + assert h3.is_valid_index(h) + assert not h3.is_valid_index(h + 1) + assert not h3.is_valid_directed_edge(h) + assert not h3.is_valid_vertex(h) + + e = h3.origin_to_directed_edges(h)[0] + assert h3.is_valid_index(e) + assert not h3.is_valid_index(e + 1) + assert not h3.is_valid_cell(e) + assert not h3.is_valid_vertex(e) + + v = h3.cell_to_vertex(h, 0) + assert h3.is_valid_index(v) + assert not h3.is_valid_index(v + 1) + assert not h3.is_valid_cell(v) + assert not h3.is_valid_directed_edge(v) + + +def test_get_index_digit(): + assert h3.get_index_digit('822377fffffffff', 1) == 5 + assert h3.get_index_digit('822377fffffffff', 2) == 6 + assert h3.get_index_digit('822377fffffffff', 3) == 7 + assert h3.get_index_digit('822377fffffffff', 15) == 7 + + with pytest.raises(H3ResDomainError): + h3.get_index_digit('822377fffffffff', 16) + + with pytest.raises(H3ResDomainError): + h3.get_index_digit('822377fffffffff', 0) + + with pytest.raises(H3ResDomainError): + h3.get_index_digit('822377fffffffff',-1) + + +def test_get_index_digit_non_cells(): + h = h3.construct_cell(111, 3, 6, 4) + assert h == '83def4fffffffff' + + e = h3.origin_to_directed_edges(h)[0] + assert e == '113def4fffffffff' + assert h3.is_valid_directed_edge(e) + assert h3.get_index_digit(e, 1) == 3 + assert h3.get_index_digit(e, 2) == 6 + assert h3.get_index_digit(e, 3) == 4 + + e = h3.int_to_str(1 + h3.str_to_int(e)) + assert not h3.is_valid_directed_edge(e) + assert not h3.is_valid_index(e) + with pytest.raises(H3IndexInvalidError): + h3.get_index_digit(e, 1) + + v = h3.cell_to_vertexes(h)[0] + assert v == '223de1afffffffff' + assert h3.is_valid_vertex(v) + assert h3.get_index_digit(v, 1) == 0 + assert h3.get_index_digit(v, 2) == 3 + assert h3.get_index_digit(v, 3) == 2 + + v = h3.int_to_str(1 + h3.str_to_int(v)) + assert not h3.is_valid_vertex(v) + assert not h3.is_valid_index(v) + with pytest.raises(H3IndexInvalidError): + h3.get_index_digit(v, 1) + + +def test_construct_cell(): + bc = 17 + assert h3.construct_cell(bc, 5, 6) == '822377fffffffff' + assert h3.construct_cell(bc) == '8023fffffffffff' + + digits = [0] * 15 + assert h3.construct_cell(bc, *digits) == '8f2200000000000' + + with pytest.raises(H3ResDomainError): + digits = [0] * 16 + h3.construct_cell(bc, *digits) + + with pytest.raises(ValueError): + digits = [1,2,3,4] + h3.construct_cell(bc, *digits, res=2) + + with pytest.raises(H3DigitDomainError): + h3.construct_cell(121, 1, 7) # 7 is not a valid digit + + with pytest.raises(H3DigitDomainError): + h3.construct_cell(121, 45) # 45 is not a valid digit + + with pytest.raises(H3DigitDomainError): + h3.construct_cell(121, -1) # -1 is not a valid digit + + with pytest.raises(H3BaseCellDomainError): + h3.construct_cell(122) # one past last base cell number + + with pytest.raises(H3DeletedDigitError): + # 4 is a pentagon base cell. first nonzero digit can't be a 1 + h3.construct_cell(4, 1) + + with pytest.raises(H3DeletedDigitError): + # 4 is a pentagon base cell. first nonzero digit can't be a 1 + h3.construct_cell(4, 0,0,0, 0, 1) + + +def test_deconstruct_cell(): + h = '822377fffffffff' + assert h3.deconstruct_cell(h) == [17, 5, 6] + + +def test_construct_cell_inverses(): + # demonstrate functions are inverses of each other + + h = '8ff3ac688d63446' + components = [121, 6, 5, 4, 3, 2, 1, 0, 6, 5, 4, 3, 2, 1, 0, 6] + + assert h3.construct_cell(*components) == h + assert h3.deconstruct_cell(h) == components + + assert h3.construct_cell(*h3.deconstruct_cell(h)) == h + assert h3.deconstruct_cell(h3.construct_cell(*components)) == components + + +def test_construct_cell_inverses_int_api(): + # same inverse test as above, but in int api + import h3.api.basic_int as h3 + + h = 0x8ff3ac688d63446 + components = [121, 6, 5, 4, 3, 2, 1, 0, 6, 5, 4, 3, 2, 1, 0, 6] + + assert h3.construct_cell(*components) == h + assert h3.deconstruct_cell(h) == components + + assert h3.construct_cell(*h3.deconstruct_cell(h)) == h + assert h3.deconstruct_cell(h3.construct_cell(*components)) == components + + +def test_center_child_with_deconstruct(): + for h in h3.get_res0_cells(): + h3.construct_cell(*h3.deconstruct_cell(h), 0) == h3.cell_to_center_child(h) + + +def test_uncompact_cells_invalid_resolution(): + # Create a valid cell at resolution 5 + h_res5 = h3.latlng_to_cell(0, 0, 5) + + # Attempting to uncompact to a coarser resolution (4) + # should raise an H3ResMismatchError + with pytest.raises(H3ResMismatchError): + h3.uncompact_cells({h_res5}, 4) diff --git a/tests/test_lib/test_error_codes.py b/tests/test_lib/test_error_codes.py new file mode 100644 index 0000000..4ae1d37 --- /dev/null +++ b/tests/test_lib/test_error_codes.py @@ -0,0 +1,77 @@ +import pytest + +import h3 +from h3._cy import ( + error_code_to_exception, + get_H3_ERROR_END, +) + +# todo: maybe check the `check_for_error` function behavior directly? + + +h3_exceptions = { + # h3.UnknownH3ErrorCode + h3.H3BaseException: None, + + h3.H3GridNavigationError: None, + h3.H3MemoryError: None, + h3.H3ValueError: None, +} + +for e in range(1, get_H3_ERROR_END()): + ex = error_code_to_exception(e) + h3_exceptions[ex] = e + + +def test_num_error_codes(): + assert get_H3_ERROR_END() >= 20 + assert error_code_to_exception(19) == h3.H3DeletedDigitError + + # H3_ERROR_END (and beyond) shouldn't be a valid error code + code = get_H3_ERROR_END() + assert isinstance( + error_code_to_exception(code), + h3.UnknownH3ErrorCode + ) + + code = get_H3_ERROR_END() + 1 + assert isinstance( + error_code_to_exception(code), + h3.UnknownH3ErrorCode + ) + + +def test_error_codes_match(): + """ + Should match the error codes given in `h3api.h.in` in the core C lib. + """ + + for err, code in h3_exceptions.items(): + assert err.h3_error_code == code + + +def test_unknown(): + weird_code = 1234 + + with pytest.raises(h3.UnknownH3ErrorCode) as excinfo: + raise h3.UnknownH3ErrorCode(weird_code) + err = excinfo.value + + assert isinstance(err, h3.UnknownH3ErrorCode) + assert err.args == (weird_code,) + + +def test_attributes(): + # errors always have an `h3_error_code` attribute + for err in h3_exceptions: + x = err.h3_error_code + assert (x is None) or (x > 0) + + # UnknownH3ErrorCode is a bit of a special case + weird_code = 1234 + with pytest.raises(h3.UnknownH3ErrorCode) as excinfo: + raise h3.UnknownH3ErrorCode(weird_code) + err = excinfo.value + + assert err.h3_error_code is None + assert err.args == (weird_code,) diff --git a/tests/test_lib/test_geojson_containers.py b/tests/test_lib/test_geojson_containers.py new file mode 100644 index 0000000..a890c27 --- /dev/null +++ b/tests/test_lib/test_geojson_containers.py @@ -0,0 +1,62 @@ +import pytest +from h3._h3shape import LatLngPoly, h3shape_to_geo, LatLngMultiPoly + + +def test_h3shape_to_geo_containers(): + # Create a basic dummy polygon for testing + poly = LatLngPoly( + [(37.68, -122.54), (37.68, -122.34), (37.82, -122.34), (37.82, -122.54)] + ) + + # Test 'auto' (Default behavior should return a Polygon) + auto_geo = h3shape_to_geo(poly, container='auto') + assert auto_geo['type'] == 'Polygon' + + # Test MultiPolygon wrapper + mp_geo = h3shape_to_geo(poly, container='MultiPolygon') + assert mp_geo['type'] == 'MultiPolygon' + assert len(mp_geo['coordinates']) == 1 + + # Test Feature wrapper + feat_geo = h3shape_to_geo(poly, container='Feature') + assert feat_geo['type'] == 'Feature' + assert feat_geo['geometry']['type'] == 'Polygon' + + # Test FeatureCollection wrapper + fc_geo = h3shape_to_geo(poly, container='FeatureCollection') + assert fc_geo['type'] == 'FeatureCollection' + assert len(fc_geo['features']) == 1 + assert fc_geo['features'][0]['type'] == 'Feature' + assert fc_geo['features'][0]['geometry']['type'] == 'Polygon' + + # Test GeometryCollection wrapper + gc_geo = h3shape_to_geo(poly, container='GeometryCollection') + assert gc_geo['type'] == 'GeometryCollection' + assert len(gc_geo['geometries']) == 1 + assert gc_geo['geometries'][0]['type'] == 'Polygon' + + +def test_h3shape_to_geo_invalid_containers(): + # 1. Test an unknown container string + poly = LatLngPoly([(37.68, -122.54), (37.68, -122.34), (37.82, -122.34)]) + with pytest.raises(ValueError, match='invalid or insufficient'): + h3shape_to_geo(poly, container='InvalidString') + + # 2. Test an insufficient container (MultiPolygon data into a Polygon container) + mpoly = LatLngMultiPoly( + LatLngPoly([(37.68, -122.54), (37.68, -122.34), (37.82, -122.34)]) + ) + with pytest.raises(ValueError, match='invalid or insufficient'): + h3shape_to_geo(mpoly, container='Polygon') + + +def test_h3shape_to_geo_exact_match(): + # Test that requesting a MultiPolygon for MultiPolygon data succeeds + mpoly = LatLngMultiPoly( + LatLngPoly([(37.68, -122.54), (37.68, -122.34), (37.82, -122.34)]) + ) + + mp_geo = h3shape_to_geo(mpoly, container='MultiPolygon') + + assert mp_geo['type'] == 'MultiPolygon' + assert len(mp_geo['coordinates']) == 1 diff --git a/tests/test_lib/test_h3.py b/tests/test_lib/test_h3.py new file mode 100644 index 0000000..760c3fa --- /dev/null +++ b/tests/test_lib/test_h3.py @@ -0,0 +1,511 @@ +import pytest +from pytest import approx + +import h3 + +from . import util as u + + +def test_approx_helper(): + assert not u.approx2('abc', 'abdc') + + +def test_is_valid_cell(): + assert h3.is_valid_cell('85283473fffffff') + assert h3.is_valid_cell('850dab63fffffff') + assert not h3.is_valid_cell('lolwut') + + # H3 0.x Addresses are not considered valid + assert not h3.is_valid_cell('5004295803a88') + + for res in range(16): + assert h3.is_valid_cell(h3.latlng_to_cell(37, -122, res)) + + +def test_latlng_to_cell(): + assert h3.latlng_to_cell(37.3615593, -122.0553238, 5) == '85283473fffffff' + + +def test_get_resolution(): + for res in range(16): + h = h3.latlng_to_cell(37.3615593, -122.0553238, res) + assert h3.get_resolution(h) == res + + +def test_silly_latlng_to_cell(): + lat, lng = 37.3615593, -122.0553238 + + expected0 = '85283473fffffff' + out0 = h3.latlng_to_cell(lat, lng, 5) + assert out0 == expected0 + + out1 = h3.latlng_to_cell(lat + 180.0, lng + 360.0, 5) + expected1 = '85ca2d53fffffff' + assert out1 == expected1 + + +def test_cell_to_latlng(): + latlng = h3.cell_to_latlng('85283473fffffff') + assert latlng == approx((37.34579337536848, -121.97637597255124)) + + +def test_cell_to_boundary(): + out = h3.cell_to_boundary('85283473fffffff') + + expected = [ + [37.271355866731895, -121.91508032705622], + [37.353926450852256, -121.86222328902491], + [37.42834118609435, -121.9235499963016], + [37.42012867767778, -122.0377349642703], + [37.33755608435298, -122.09042892904395], + [37.26319797461824, -122.02910130919], + ] + + assert len(out) == len(expected) + + for o, e in zip(out, expected): + assert o == approx(e) + + +def test_grid_disk(): + h = '8928308280fffff' + out = h3.grid_disk(h, 1) + + assert len(out) == 1 + 6 + + expected = { + '8928308280bffff', + '89283082807ffff', + '89283082877ffff', + h, + '89283082803ffff', + '89283082873ffff', + '8928308283bffff', + } + + assert u.same_set(out, expected) + + +def test_grid_disk2(): + h = '8928308280fffff' + out = h3.grid_disk(h, 2) + + assert len(out) == 1 + 6 + 12 + + expected = { + '89283082813ffff', + '89283082817ffff', + '8928308281bffff', + '89283082863ffff', + '89283082823ffff', + '89283082873ffff', + '89283082877ffff', + h, + '8928308287bffff', + '89283082833ffff', + '8928308282bffff', + '8928308283bffff', + '89283082857ffff', + '892830828abffff', + '89283082847ffff', + '89283082867ffff', + '89283082803ffff', + '89283082807ffff', + '8928308280bffff', + } + + assert u.same_set(out, expected) + + +def test_grid_disk_pentagon(): + h = '821c07fffffffff' # a pentagon cell + out = h3.grid_disk(h, 1) + + assert len(out) == 1 + 5 + + expected = { + '821c2ffffffffff', + '821c27fffffffff', + h, + '821c17fffffffff', + '821c1ffffffffff', + '821c37fffffffff', + } + + assert u.same_set(out, expected) + + +def test_grid_ring(): + h = '8928308280fffff' + out = h3.grid_ring(h, 1) + expected = { + '8928308280bffff', + '89283082807ffff', + '89283082877ffff', + '89283082803ffff', + '89283082873ffff', + '8928308283bffff', + } + + assert u.same_set(out, expected) + assert u.same_set( + out, + set(h3.grid_disk(h, 1)) - set(h3.grid_disk(h, 0)) + ) + + +def test_grid_ring2(): + h = '8928308280fffff' + out = h3.grid_ring(h, 2) + + expected = { + '89283082813ffff', + '89283082817ffff', + '8928308281bffff', + '89283082863ffff', + '89283082823ffff', + '8928308287bffff', + '89283082833ffff', + '8928308282bffff', + '89283082857ffff', + '892830828abffff', + '89283082847ffff', + '89283082867ffff', + } + + assert u.same_set(out, expected) + assert u.same_set( + out, + set(h3.grid_disk(h, 2)) - set(h3.grid_disk(h, 1)) + ) + + +def test_grid_ring_pentagon(): + h = '821c07fffffffff' + out = h3.grid_ring(h, 1) + + expected = { + '821c17fffffffff', + '821c1ffffffffff', + '821c27fffffffff', + '821c2ffffffffff', + '821c37fffffffff', + } + + assert u.same_set(out, expected) + + +def test_compact_and_uncompact_cells(): + sf_7x7 = [ + (37.813318999983238, -122.4089866999972145), + (37.7866302000007224, -122.3805436999997056), + (37.7198061999978478, -122.3544736999993603), + (37.7076131999975672, -122.5123436999983966), + (37.7835871999971715, -122.5247187000021967), + (37.8151571999998453, -122.4798767000009008), + ] + + poly = h3.LatLngPoly(sf_7x7) + cells = h3.h3shape_to_cells(poly, 9) + + compact_cells = h3.compact_cells(cells) + assert len(compact_cells) == 209 + + uncompact_cells = h3.uncompact_cells(compact_cells, 9) + assert len(uncompact_cells) == 1253 + + assert u.same_set(uncompact_cells, cells) + + +def test_compact_cells_and_uncompact_cells_nothing(): + assert h3.compact_cells([]) == [] + assert h3.uncompact_cells([], 9) == [] + + +def test_uncompact_cells_error(): + hexagons = [h3.latlng_to_cell(37, -122, 10)] + + with pytest.raises(Exception): + h3.uncompact_cells(hexagons, 5) + + +def test_compact_cells_malformed_input(): + cells = ['89283082813ffff'] * 13 + + with pytest.raises(Exception): + h3.compact_cells(cells) + + +def test_cell_to_parent(): + h = '89283082813ffff' + assert h3.cell_to_parent(h, 8) == '8828308281fffff' + + +def test_cell_to_children(): + h = '8828308281fffff' + children = h3.cell_to_children(h, 9) + + assert len(children) == 7 + + +def test_average_hexagon_area(): + for i in range(0, 15): + assert isinstance(h3.average_hexagon_area(i), float) + assert isinstance(h3.average_hexagon_area(i, 'm^2'), float) + + with pytest.raises(ValueError): + h3.average_hexagon_area(5, 'ft^2') + + +def test_average_hexagon_edge_length(): + for i in range(0, 15): + assert isinstance(h3.average_hexagon_edge_length(i), float) + assert isinstance(h3.average_hexagon_edge_length(i, 'm'), float) + + with pytest.raises(ValueError): + h3.average_hexagon_edge_length(5, 'ft') + + +def test_get_num_cells(): + h0 = 122 + assert h3.get_num_cells(0) == h0 + + for i in range(0, 15): + n = h3.get_num_cells(i) * 1.0 / h0 + + assert 6**i <= n <= 7**i + + +def test_get_base_cell_number(): + assert h3.get_base_cell_number('8928308280fffff') == 20 + + +def test_is_res_class_III(): + assert h3.is_res_class_III('8928308280fffff') + assert not h3.is_res_class_III('8828308280fffff') + + +def test_is_pentagon(): + assert h3.is_pentagon('821c07fffffffff') + assert not h3.is_pentagon('8928308280fffff') + + +def test_are_neighbor_cells(): + assert h3.are_neighbor_cells('8928308280fffff', '8928308280bffff') + + assert not h3.are_neighbor_cells('821c07fffffffff', '8928308280fffff') + + +def test_cells_to_directed_edge(): + out = h3.cells_to_directed_edge('8928308280fffff', '8928308280bffff') + assert h3.is_valid_directed_edge(out) + + with pytest.raises(h3.H3NotNeighborsError): + h3.cells_to_directed_edge('821c07fffffffff', '8928308280fffff') + + +def test_is_valid_directed_edge(): + assert not h3.is_valid_directed_edge('8928308280fffff') + assert h3.is_valid_directed_edge('11928308280fffff') + + +def test_get_directed_edge_origin(): + out = h3.get_directed_edge_origin('11928308280fffff') + assert out == '8928308280fffff' + + +def test_get_directed_edge_destination(): + h = '11928308280fffff' + out = h3.get_directed_edge_destination(h) + + assert out == '8928308283bffff' + + +def test_directed_edge_to_cells(): + e = h3.directed_edge_to_cells('11928308280fffff') + + assert e == ('8928308280fffff', '8928308283bffff') + + +def test_origin_to_directed_edges(): + h3_uni_edges = h3.origin_to_directed_edges( + '8928308280fffff' + ) + assert len(h3_uni_edges) == 6 + + h3_uni_edge_pentagon = h3.origin_to_directed_edges( + '821c07fffffffff' + ) + assert len(h3_uni_edge_pentagon) == 5 + + +def test_grid_distance(): + h = '89283082993ffff' + + assert 0 == h3.grid_distance(h, h) + assert 1 == h3.grid_distance(h, '8928308299bffff') + assert 5 == h3.grid_distance(h, '89283082827ffff') + + +def test_grid_path_cells(): + h1 = '8a2a84730587fff' + h2 = '8a2a8471414ffff' + + out = h3.grid_path_cells(h1, h2) + + expected = [ + h1, + '8a2a8473059ffff', + '8a2a847304b7fff', + '8a2a84730487fff', + '8a2a8473049ffff', + '8a2a84732b37fff', + '8a2a84732b17fff', + '8a2a84732baffff', + '8a2a84732a37fff', + '8a2a84732a17fff', + '8a2a84732aaffff', + '8a2a84732a8ffff', + '8a2a84732327fff', + '8a2a8473232ffff', + '8a2a8473230ffff', + '8a2a84732227fff', + '8a2a84732207fff', + '8a2a8473221ffff', + '8a2a847322e7fff', + '8a2a847322c7fff', + '8a2a847322dffff', + '8a2a84714977fff', + '8a2a84714957fff', + '8a2a8471495ffff', + '8a2a84714877fff', + '8a2a84714857fff', + '8a2a847148effff', + '8a2a847148cffff', + '8a2a84714b97fff', + '8a2a8471416ffff', + h2, + ] + + assert out == expected + + with pytest.raises(h3.H3ResMismatchError): + h3.grid_path_cells(h1, '8001fffffffffff') + + +def test_cell_to_vertex(): + # pentagon + assert h3.cell_to_vertex('814c3ffffffffff', 0) == '2014c3ffffffffff' + assert h3.cell_to_vertex('814c3ffffffffff', 1) == '2114c3ffffffffff' + assert h3.cell_to_vertex('814c3ffffffffff', 2) == '2214c3ffffffffff' + assert h3.cell_to_vertex('814c3ffffffffff', 3) == '2314c3ffffffffff' + assert h3.cell_to_vertex('814c3ffffffffff', 4) == '2414c3ffffffffff' + + with pytest.raises(h3.H3DomainError): + h3.cell_to_vertex('814c3ffffffffff', 5) + + # hexagon + assert h3.cell_to_vertex('814d7ffffffffff', 0) == '2014d7ffffffffff' + assert h3.cell_to_vertex('814d7ffffffffff', 1) == '2213abffffffffff' + assert h3.cell_to_vertex('814d7ffffffffff', 2) == '2113abffffffffff' + assert h3.cell_to_vertex('814d7ffffffffff', 3) == '2414c3ffffffffff' + assert h3.cell_to_vertex('814d7ffffffffff', 4) == '2314c3ffffffffff' + assert h3.cell_to_vertex('814d7ffffffffff', 5) == '2414cfffffffffff' + + +def test_cell_to_vertexes(): + # pentagon + assert h3.cell_to_vertexes('814c3ffffffffff') == [ + '2014c3ffffffffff', + '2114c3ffffffffff', + '2214c3ffffffffff', + '2314c3ffffffffff', + '2414c3ffffffffff', + ] + + # hexagon + assert h3.cell_to_vertexes('814d7ffffffffff') == [ + '2014d7ffffffffff', + '2213abffffffffff', + '2113abffffffffff', + '2414c3ffffffffff', + '2314c3ffffffffff', + '2414cfffffffffff', + ] + + +def test_vertex_to_latlng(): + latlng = h3.vertex_to_latlng('2114c3ffffffffff') + assert latlng == approx((24.945215618732814, -70.33904370008679)) + + +def test_is_valid_vertex(): + assert h3.is_valid_vertex('2114c3ffffffffff') + assert not h3.is_valid_vertex(2455495337847029759) + assert not h3.is_valid_vertex('foobar') + + +def test_child_pos(): + h = '88283080ddfffff' + + assert h3.cell_to_child_pos(h, 8) == 0 + assert h3.cell_to_child_pos(h, 7) == 6 + assert h3.cell_to_child_pos(h, 6) == 41 + + with pytest.raises(h3.H3BaseException): + h3.cell_to_child_pos(h, 9) + + with pytest.raises(h3.H3BaseException): + h3.child_pos_to_cell(h, 9, -1) + + with pytest.raises(h3.H3BaseException): + h3.child_pos_to_cell(h, 9, 10000) + + +def test_child_pos2(): + h = '88283080ddfffff' + assert h == h3.child_pos_to_cell(h, 8, 0) + assert h == h3.child_pos_to_cell(h3.cell_to_parent(h, 7), 8, 6) + assert h == h3.child_pos_to_cell(h3.cell_to_parent(h, 6), 8, 41) + + +def test_cell_to_children_size(): + h = '8053fffffffffff' # hexagon + for r in range(16): + assert h3.cell_to_children_size(h, r) == 7**r + + +def test_cell_to_children_size2(): + cells = h3.get_res0_cells() + + for r in range(16): + total_cells = 120 * (7**r) + 2 + + assert total_cells == sum( + h3.cell_to_children_size(h, r) + for h in cells + ) + + +def test_child_pos3(): + def cells_at_res(res): + cells = h3.get_res0_cells() + for parent in cells: + yield from h3.cell_to_children(parent, res) + + def roundtrip(child, res_parent): + res_child = h3.get_resolution(child) + parent = h3.cell_to_parent(child, res_parent) + pos = h3.cell_to_child_pos(child, res_parent) + return h3.child_pos_to_cell(parent, res_child, pos) + + res_pairs = [ + (res_parent, res_child) + for res_parent in [0, 1] + for res_child in [0, 1, 2, 3] + if res_parent <= res_child + ] + + for res_parent, res_child in res_pairs: + for child in cells_at_res(res_child): + assert child == roundtrip(child, res_parent) diff --git a/tests/test_length_area.py b/tests/test_lib/test_length_area.py similarity index 54% rename from tests/test_length_area.py rename to tests/test_lib/test_length_area.py index 8236199..ca38257 100644 --- a/tests/test_length_area.py +++ b/tests/test_lib/test_length_area.py @@ -1,24 +1,14 @@ import h3 import pytest -from h3 import H3ValueError - - -def approx2(a, b): - if len(a) != len(b): - return False - - return all( - x == pytest.approx(y) - for x, y in zip(a, b) - ) +from . import util as u def cell_perimiter1(h, unit='km'): - edges = h3.get_h3_unidirectional_edges_from_hexagon(h) + edges = h3.origin_to_directed_edges(h) dists = [ - h3.exact_edge_length(e, unit=unit) + h3.edge_length(e, unit=unit) for e in edges ] @@ -28,12 +18,12 @@ def cell_perimiter1(h, unit='km'): def cell_perimiter2(h, unit='km'): - verts = h3.h3_to_geo_boundary(h) + verts = h3.cell_to_boundary(h) N = len(verts) verts += (verts[0],) dists = [ - h3.point_dist(verts[i], verts[i + 1], unit=unit) + h3.great_circle_distance(verts[i], verts[i + 1], unit=unit) for i in range(N) ] @@ -63,11 +53,11 @@ def test_areas_at_00(): ] out = [ - h3.cell_area(h3.geo_to_h3(0, 0, r), unit='km^2') + h3.cell_area(h3.latlng_to_cell(0, 0, r), unit='km^2') for r in range(16) ] - assert approx2(out, areas_km2) + assert u.approx2(out, areas_km2) areas_rads2 = [ 6.312389871006786335e-02, @@ -89,52 +79,77 @@ def test_areas_at_00(): ] out = [ - h3.cell_area(h3.geo_to_h3(0, 0, r), unit='rads^2') + h3.cell_area(h3.latlng_to_cell(0, 0, r), unit='rads^2') for r in range(16) ] - assert approx2(out, areas_rads2) + assert u.approx2(out, areas_rads2) + + +def test_average_hexagon_area_rads(): + # the ratio between km^2 and rads^2 should match the one used by cell_area + h = '89754e64993ffff' + ratio = h3.cell_area(h, unit='km^2') / h3.cell_area(h, unit='rads^2') + + for res in range(16): + km2 = h3.average_hexagon_area(res, unit='km^2') + rads2 = h3.average_hexagon_area(res, unit='rads^2') + + assert km2 / rads2 == pytest.approx(ratio) + + +def test_average_hexagon_edge_length_rads(): + # the ratio between km and rads should match the one used by edge_length + e = '139754e64993ffff' + ratio = h3.edge_length(e, unit='km') / h3.edge_length(e, unit='rads') + + for res in range(16): + km = h3.average_hexagon_edge_length(res, unit='km') + rads = h3.average_hexagon_edge_length(res, unit='rads') + + assert km / rads == pytest.approx(ratio) def test_bad_units(): h = '89754e64993ffff' e = '139754e64993ffff' - assert h3.h3_is_valid(h) - assert h3.h3_unidirectional_edge_is_valid(e) + assert h3.is_valid_cell(h) + assert h3.is_valid_directed_edge(e) - with pytest.raises(H3ValueError): + with pytest.raises(ValueError): h3.cell_area(h, unit='foot-pounds') - with pytest.raises(H3ValueError): - h3.exact_edge_length(h, unit='foot-pounds') + with pytest.raises(ValueError): + h3.edge_length(e, unit='foot-pounds') - with pytest.raises(H3ValueError): - h3.point_dist((0, 0), (0, 0), unit='foot-pounds') + with pytest.raises(ValueError): + h3.great_circle_distance((0, 0), (0, 0), unit='foot-pounds') -def test_point_dist(): +def test_great_circle_distance(): lyon = (45.7597, 4.8422) # (lat, lon) paris = (48.8567, 2.3508) - d = h3.point_dist(lyon, paris, unit='rads') + d = h3.great_circle_distance(lyon, paris, unit='rads') assert d == pytest.approx(0.0615628186794217) - d = h3.point_dist(lyon, paris, unit='m') + d = h3.great_circle_distance(lyon, paris, unit='m') assert d == pytest.approx(392217.1598841777) - d = h3.point_dist(lyon, paris, unit='km') + d = h3.great_circle_distance(lyon, paris, unit='km') assert d == pytest.approx(392.21715988417765) # test that 'km' is the default unit - assert h3.point_dist(lyon, paris, unit='km') == h3.point_dist(lyon, paris) + dist = h3.great_circle_distance + assert dist(lyon, paris, unit='km') == dist(lyon, paris) def test_cell_perimiter_calculations(): resolutions = [0, 1] for r in resolutions: - cells = h3.uncompact(h3.get_res0_indexes(), r) + cells = h3.uncompact_cells(h3.get_res0_cells(), r) for h in cells: for unit in ['rads', 'm', 'km']: v1 = cell_perimiter1(h, unit) diff --git a/tests/test_lib/util.py b/tests/test_lib/util.py new file mode 100644 index 0000000..f6d3177 --- /dev/null +++ b/tests/test_lib/util.py @@ -0,0 +1,21 @@ +import pytest + + +def same_set(a, b): + """Test if two collections are the same if taken as sets""" + set_a = set(a) + set_b = set(b) + + assert len(a) == len(b) == len(set_a) == len(set_b) + + return set_a == set_b + + +def approx2(a, b): + if len(a) != len(b): + return False + + return all( + x == pytest.approx(y) + for x, y in zip(a, b) + ) diff --git a/tests/test_memview_int.py b/tests/test_memview_int.py deleted file mode 100644 index 9923b75..0000000 --- a/tests/test_memview_int.py +++ /dev/null @@ -1,41 +0,0 @@ -import h3.api.memview_int as h3 - - -def test1(): - assert h3.geo_to_h3(37.7752702151959, -122.418307270836, 9) == 617700169958293503 - - -def test_line(): - h1 = '8928308280fffff' - h2 = '8928308287bffff' - h1, h2 = h3.string_to_h3(h1), h3.string_to_h3(h2) - - out = h3.h3_line(h1, h2) - - # todo: are we outputting `memoryviewslice`? should we just output a memoryview? - assert 'memoryview' in str(type(out)) - - expected = [ - 617700169958293503, - 617700169964847103, - 617700169965371391, - ] - - assert list(out) == expected - - -def test_get_faces(): - h = 577832942814887935 - expected = {2, 3, 7, 8, 12} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579873636396040191 - expected = {13} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579768083279773695 - expected = {16, 15} - out = h3.h3_get_faces(h) - assert out == expected diff --git a/tests/test_numpy_int.py b/tests/test_numpy_int.py deleted file mode 100644 index 8169772..0000000 --- a/tests/test_numpy_int.py +++ /dev/null @@ -1,47 +0,0 @@ -import h3.api.numpy_int as h3 -import numpy as np # only run this test suite if numpy is installed - - -def test1(): - assert h3.geo_to_h3(37.7752702151959, -122.418307270836, 9) == 617700169958293503 - - -def test5(): - expected = { - 617700169957507071, - 617700169957769215, - 617700169958031359, - 617700169958293503, - 617700169961177087, - 617700169964847103, - 617700169965109247, - } - - out = h3.k_ring(617700169958293503, 1) - assert isinstance(out, np.ndarray) - assert set(out) == expected - - -def test_compact(): - h = 617700169958293503 - hexes = h3.h3_to_children(h) - assert isinstance(hexes, np.ndarray) - - assert set(h3.compact(hexes)) == {h} - - -def test_get_faces(): - h = 577832942814887935 - expected = {2, 3, 7, 8, 12} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579873636396040191 - expected = {13} - out = h3.h3_get_faces(h) - assert out == expected - - h = 579768083279773695 - expected = {16, 15} - out = h3.h3_get_faces(h) - assert out == expected diff --git a/tests/test_polyfill.py b/tests/test_polyfill.py deleted file mode 100644 index 4739009..0000000 --- a/tests/test_polyfill.py +++ /dev/null @@ -1,248 +0,0 @@ -import h3 -import itertools -import pytest - - -def reverse(loop): - return list(reversed(loop)) - - -def drop_last(loop): - return loop[:-1] - - -def toggle_map(func, poly): - """ Return all permuations of `func` being applied or not - to each element of `poly` - - returns iterable of length 2**len(poly) - """ - mapped = (list(func(loop)) for loop in poly) - - return itertools.product(*zip(poly, mapped)) - - -def chain_toggle_map(func, seq): - seq = (toggle_map(func, p) for p in seq) - seq = itertools.chain(*seq) - - return seq - - -def input_permutations(poly, res=5): - g = [poly] - g = chain_toggle_map(drop_last, g) - g = chain_toggle_map(reverse, g) - - for p in g: - hexes = h3.polyfill_polygon(p[0], res=res, holes=p[1:]) - yield hexes - - -def swap_element_order(seq): - return [e[::-1] for e in seq] - - -def get_us_box_coords(order='latlng'): - - # big center chunk of the US in lat/lng order - outer = [ - [42.68, -110.61], - [32.17, -109.02], - [31.57, -94.26], - [42.94, -89.38], - [42.68, -110.61] - ] - - hole1 = [ - [39.77, -105.07], - [34.81, -104.72], - [34.77, -98.39], - [40.14, -96.72], - [39.77, -105.07] - ] - - hole2 = [ - [41.37, -98.61], - [40.04, -91.80], - [42.32, -91.80], - [41.37, -98.61] - ] - - if order == 'lnglat': - outer, hole1, hole2 = map(swap_element_order, [outer, hole1, hole2]) - - return outer, hole1, hole2 - - -def test_polyfill_polygon(): - - # lat/lngs for State of Maine - maine = [ - (45.137451890638886, -67.13734351262877), - (44.8097, -66.96466), - (44.3252, -68.03252), - (43.98, -69.06), - (43.68405, -70.11617), - (43.090083319667144, -70.64573401557249), - (43.08003225358635, -70.75102474636725), - (43.21973948828747, -70.79761105007827), - (43.36789581966826, -70.98176001655037), - (43.46633942318431, -70.94416541205806), - (45.3052400000002, -71.08482), - (45.46022288673396, -70.6600225491012), - (45.914794623389355, -70.30495378282376), - (46.69317088478567, -70.00014034695016), - (47.44777598732787, -69.23708614772835), - (47.184794623394396, -68.90478084987546), - (47.35462921812177, -68.23430497910454), - (47.066248887716995, -67.79035274928509), - (45.702585354182816, -67.79141211614706), - (45.137451890638886, -67.13734351262877) - ] - - # a very rough hexagonal approximation to the State of Maine - expected = { - '832b13fffffffff', - '832b18fffffffff', - '832b1afffffffff', - '832b1efffffffff', - '832ba9fffffffff', - '832badfffffffff' - } - - out = h3.polyfill_polygon(maine, 3) - - assert out == expected - - -def test_polyfill_polygon_order(): - lnglat, _, _ = get_us_box_coords(order='lnglat') - - out = h3.polyfill_polygon(lnglat, 5, lnglat_order=True) - - assert len(out) == 7063 - - -# # todo: we can generate segfaults with malformed input data to polyfill -# # need to test for this and avoid segfault -# # def test_polyfill_segfault(): -# # pass - - -def test_polyfill_polygon_holes(): - - outer, hole1, hole2 = get_us_box_coords() - - assert 7063 == len( - h3.polyfill_polygon(outer, 5) - ) - - for res in 1, 2, 3, 4, 5: - hexes_all = h3.polyfill_polygon(outer, res) - hexes_holes = h3.polyfill_polygon(outer, res, [hole1, hole2]) - - hexes_1 = h3.polyfill_polygon(hole1, res) - hexes_2 = h3.polyfill_polygon(hole2, res) - - assert len(hexes_all) == len(hexes_holes) + len(hexes_1) + len(hexes_2) - assert hexes_all == set.union(hexes_holes, hexes_1, hexes_2) - - -def test_polyfill_geojson(): - outer, hole1, hole2 = get_us_box_coords(order='lnglat') - - d = { - 'type': 'Polygon', - 'coordinates': [outer], - } - - out = h3.polyfill_geojson(d, 5) - - assert len(out) == 7063 - - -def test_polyfill(): - outer, hole1, hole2 = get_us_box_coords(order='lnglat') - - d = { - 'type': 'Polygon', - 'coordinates': [outer], - } - - out = h3.polyfill(d, 5, geo_json_conformant=True) - - assert len(out) == 7063 - - -def test_input_format(): - """ Test that `polyfill_polygon` can take in polygon inputs - where the LinearRings may or may not follow the right hand rule, - and they may or may not be closed loops (where the last element - is equal to the first). - - Test all permutations of these rules on polygons with - 0, 1, and 2 holes. Ensure that for any polygon, each LinearRing - may follow a different subset of rules. - """ - - poly = get_us_box_coords(order='latlng') - - assert len(poly) == 3 - - # two holes - for hexes in input_permutations(poly[:3]): - assert len(hexes) == 5437 - - # one hole - for hexes in input_permutations(poly[:2]): - assert len(hexes) == 5726 - - # zero holes - for hexes in input_permutations(poly[:1]): - assert len(hexes) == 7063 - - -def test_resolution(): - d = { - 'type': 'Polygon', - 'coordinates': [[]], - } - - with pytest.raises(h3.H3ResolutionError): - h3.polyfill(d, -1) - - with pytest.raises(h3.H3ResolutionError): - h3.polyfill(d, 16) - - -def test_invalid_polygon(): - """ - We were previously seeing segfaults on data like - this because we weren't raising errors inside - some `cdef` functions. - """ - - # one - d = { - 'type': 'Polygon', - 'coordinates': [1, 2, 3], - } - with pytest.raises(TypeError): - h3.polyfill(d, 4) - - # two - d = { - 'type': 'Polygon', - 'coordinates': [[1, 2, 3]], - } - with pytest.raises(TypeError): - h3.polyfill(d, 4) - - # three - d = { - 'type': 'Polygon', - 'coordinates': [(1, 2), (2, 2), (2, 1), (1, 2)], - } - with pytest.raises(TypeError): - h3.polyfill(d, 4) diff --git a/tests/test_to_multipoly.py b/tests/test_to_multipoly.py deleted file mode 100644 index 0b899b9..0000000 --- a/tests/test_to_multipoly.py +++ /dev/null @@ -1,61 +0,0 @@ -import h3 - - -def test_h3_set_to_multi_polygon(): - h = '8928308280fffff' - hexes = h3.k_ring(h, 1) - - mpoly = h3.h3_set_to_multi_polygon(hexes) - - out = h3.polyfill_polygon(mpoly[0][0], 9, holes=None, lnglat_order=False) - - assert out == hexes - - -def test_2_polys(): - h = '8928308280fffff' - hexes = h3.hex_ring(h, 2) - hexes = hexes | {h} - # hexes should be a center hex, and the 2-ring around it - # (with the 1-ring being absent) - - out = [ - h3.polyfill_polygon(poly[0], 9, holes=poly[1:], lnglat_order=False) - for poly in h3.h3_set_to_multi_polygon(hexes, geo_json=False) - ] - - assert set.union(*out) == hexes - - -def test_2_polys_json(): - h = '8928308280fffff' - hexes = h3.hex_ring(h, 2) - hexes = hexes | {h} - # hexes should be a center hex, and the 2-ring around it - # (with the 1-ring being absent) - - # not deterministic which poly is first.. - poly1, poly2 = h3.h3_set_to_multi_polygon(hexes, geo_json=True) - - assert {len(poly1), len(poly2)} == {1, 2} - - for poly in poly1, poly2: - for loop in poly: - assert loop[0] == loop[-1] - - -def test_2_polys_not_json(): - h = '8928308280fffff' - hexes = h3.hex_ring(h, 2) - hexes = hexes | {h} - # hexes should be a center hex, and the 2-ring around it - # (with the 1-ring being absent) - - # not deterministic which poly is first.. - poly1, poly2 = h3.h3_set_to_multi_polygon(hexes, geo_json=False) - - assert {len(poly1), len(poly2)} == {1, 2} - - for poly in poly1, poly2: - for loop in poly: - assert loop[0] != loop[-1] diff --git a/tests/test_unstable_vect.py b/tests/test_unstable_vect.py deleted file mode 100644 index a556aae..0000000 --- a/tests/test_unstable_vect.py +++ /dev/null @@ -1,69 +0,0 @@ -import h3.api.numpy_int as h3 -import numpy as np # only run this test suite if numpy is installed -import pytest - -with pytest.warns( - UserWarning, - match = 'Modules under `h3.unstable` are experimental', -): - import h3.unstable.vect as h3_vect - - -def test_h3_to_parent(): - # At res 9 - h = np.array([617700169958555647, 617700169958555647], np.uint64) - - # Default to res - 1 - arr1 = h3_vect.h3_to_parent(h) - arr2 = h3_vect.h3_to_parent(h, 8) - assert np.array_equal(arr1, arr2) - - # Same as other h3 bindings - arr1 = h3_vect.h3_to_parent(h) - arr2 = np.array(list(map(h3.h3_to_parent, h)), dtype=np.uint64) - assert np.array_equal(arr1, arr2) - - # Test with a number passed to res - arr1 = h3_vect.h3_to_parent(h, 7) - arr2 = np.array([h3.h3_to_parent(c, 7) for c in h], dtype=np.uint64) - assert np.array_equal(arr1, arr2) - - # Test with an array passed to res - arr1 = h3_vect.h3_to_parent(h, np.array([7, 5], np.intc)) - arr2 = h3_vect.h3_to_parent(h, [7, 5]) - - arr3 = [] - for c, res in zip(h, [7, 5]): - arr3.append(h3.h3_to_parent(c, res)) - - assert np.array_equal(arr1, arr2) - assert np.array_equal(arr1, np.array(arr3, dtype=np.uint64)) - - # Test with array-like (but not np.array) cell input - arr1 = h3_vect.h3_to_parent(list(h)) - arr2 = np.array(list(map(h3.h3_to_parent, h)), dtype=np.uint64) - assert np.array_equal(arr1, arr2) - - -def test_h3_to_parent_multiple_res(): - h = np.array([617700169958555647, 613196570331971583], np.uint64) - - # Cells at res 9, 8 - assert list(h3_vect.h3_get_resolution(h)) == [9, 8] - - # Same as other h3 bindings - arr1 = h3_vect.h3_to_parent(h) - arr2 = np.array(list(map(h3.h3_to_parent, h)), dtype=np.uint64) - assert np.array_equal(arr1, arr2) - - # Parent cells are 8, 7 - parents = h3_vect.h3_to_parent(h) - assert list(h3_vect.h3_get_resolution(parents)) == [8, 7] - - -def test_h3_get_resolution(): - h = np.array([617700169958555647], np.uint64) - - arr1 = h3_vect.h3_get_resolution(h) - arr2 = np.array(list(map(h3.h3_get_resolution, h)), dtype=np.intc) - assert np.array_equal(arr1, arr2)