diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..3f950dd --- /dev/null +++ b/.flake8 @@ -0,0 +1,18 @@ +# 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, + # E731 do not assign a lambda expression, use a def + E731, + # https://stackoverflow.com/questions/67942075/w504-line-break-after-binary-operator + W503,W504 diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml deleted file mode 100644 index 9cc00a2..0000000 --- a/.github/workflows/build_docs.yml +++ /dev/null @@ -1,41 +0,0 @@ -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 new file mode 100644 index 0000000..878239a --- /dev/null +++ b/.github/workflows/coverage-lint.yml @@ -0,0 +1,56 @@ +name: coverage-lint + +on: + push: + branches: [master] + pull_request: + branches: ['*'] + +jobs: + tests: + name: Coverage and Lint + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + with: + submodules: recursive + + - uses: actions/setup-python@v4.5.0 + with: + python-version: 3.11 + + - 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 new file mode 100644 index 0000000..c3a4c3e --- /dev/null +++ b/.github/workflows/deploy_docs.yml @@ -0,0 +1,48 @@ +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-20.04 + + steps: + - uses: actions/checkout@v3 + with: + submodules: recursive + + - uses: actions/setup-python@v4.5.0 + with: + python-version: 3.11 + + - 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 + # turn off warningiserror just for https://github.com/uber/h3-py/pull/283 + # jupyter-book build docs/ --warningiserror --keep-going --all + run: | + jupyter-book build docs/ --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 deleted file mode 100644 index 8ec1ef1..0000000 --- a/.github/workflows/lint_and_coverage.yml +++ /dev/null @@ -1,38 +0,0 @@ -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 f7a9854..a5b4fec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,22 +13,20 @@ jobs: strategy: matrix: - 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'] + os: [macos-latest, windows-latest, ubuntu-20.04] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', '3.11'] steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v3 with: submodules: recursive - - uses: astral-sh/setup-uv@v7 + - uses: actions/setup-python@v4.5.0 with: python-version: '${{ matrix.python-version }}' - - uses: extractions/setup-just@v2 - ## Start Windows stuff - - uses: ilammy/msvc-dev-cmd@v1.13.0 + - uses: ilammy/msvc-dev-cmd@v1.12.0 if: startsWith(matrix.os, 'windows') - name: Set Windows Compiler @@ -38,11 +36,13 @@ jobs: echo "CXX=cl.exe" >> $GITHUB_ENV ## End Windows stuff - - name: Install - run: uv sync + - name: Install from source + run: | + pip install --upgrade pip setuptools wheel + pip install .[all] - name: Tests - run: just ci-test - - - name: Cython Tests - run: just ci-test-cython + run: | + pip install Cython + cythonize -i tests/cython_example.pyx + pytest tests --cov=h3 --full-trace diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 1de5a80..5d4bc60 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -19,149 +19,90 @@ on: jobs: make_sdist: + name: 'SDist: ${{ matrix.os }}' if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} - runs-on: ubuntu-22.04 + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-20.04] steps: - - uses: actions/checkout@v6.0.2 + - uses: actions/checkout@v3 with: submodules: recursive - - uses: astral-sh/setup-uv@v7 - with: - python-version: '3.11' - + - name: Setup Python + uses: actions/setup-python@v4.5.0 - name: Make sdist - run: uv build --sdist + run: | + python --version + pipx --version + pipx run 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: | - uv venv + pip install --upgrade pip setuptools wheel + pip install pytest cp dist/h3-*.tar.gz h3.tar.gz - uv pip install h3.tar.gz[numpy] pytest pytest-cov + pip install h3.tar.gz[all] - name: Test sdist - # run pytest directly from the venv to avoid `uv run` syncing from the local checkout - run: .venv/bin/pytest + run: pytest --cov=h3 --full-trace - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v6.0.0 + uses: actions/upload-artifact@v3 with: - name: temp_result_sdist path: ./dist - make_wheels: - name: 'cibw: ${{ matrix.name }}' + make_cibw_v2_wheels: + name: 'cibuildwheel v2: ${{ matrix.name }}' if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ${{ matrix.os }} strategy: matrix: include: - - os: macos-15 - build: 'cp*-macosx_arm64' - name: macOS15 - + - os: macos-latest + build: 'cp*-macosx*' + name: macOS - os: windows-latest build: 'cp3*-win_amd64' name: Windows 64-bit - - - 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 + - os: ubuntu-20.04 build: 'cp*-manylinux_x86_64' name: Linux Intel glibc 64-bit - - - 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 + - os: ubuntu-20.04 + build: 'cp*-musllinux_x86_64' + name: Linux Intel musl 64-bit + - os: ubuntu-20.04 + build: 'cp36-manylinux_aarch64' + name: Linux Aarch64 3.6 + - os: ubuntu-20.04 + build: 'cp37-manylinux_aarch64' + name: Linux Aarch64 3.7 + - os: ubuntu-20.04 + build: 'cp38-manylinux_aarch64' + name: Linux Aarch64 3.8 + - os: ubuntu-20.04 + build: 'cp39-manylinux_aarch64' + name: Linux Aarch64 3.9 + - os: ubuntu-20.04 build: 'cp310-manylinux_aarch64' name: Linux Aarch64 3.10 - - os: ubuntu-22.04 + - os: ubuntu-20.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@v6.0.2 + - uses: actions/checkout@v3 with: submodules: recursive - - uses: astral-sh/setup-uv@v7 + ## Setup Env - - 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 + - uses: ilammy/msvc-dev-cmd@v1.12.0 + if: runner.os == 'Windows' - name: Set Windows variables if: runner.os == 'Windows' @@ -172,69 +113,41 @@ jobs: - name: Set up QEMU if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v3.7.0 + uses: docker/setup-qemu-action@v2.1.0 with: platforms: aarch64 - - uses: pypa/cibuildwheel@v4.2.1 + ## Build + + - uses: pypa/cibuildwheel@v2.16.2 env: - CIBW_BUILD_FRONTEND: 'build[uv]' - CIBW_TEST_REQUIRES: pytest pytest-cov numpy + CIBW_TEST_REQUIRES: pytest 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: uvx twine check wheelhouse/* + run: | + pipx run twine check wheelhouse/* - name: Upload artifacts to GitHub - uses: actions/upload-artifact@v6.0.0 + uses: actions/upload-artifact@v3 with: - name: temp_result_${{ matrix.os }}-${{ strategy.job-index }} path: wheelhouse/*.whl - merge: - needs: [make_sdist, make_wheels] - runs-on: ubuntu-latest - steps: - - name: Merge Artifacts - uses: actions/upload-artifact/merge@v6 - with: - 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 - - - name: Check all wheels and sdist with Twine - run: uvx twine check dist/* - - to_pypi: - needs: [check_merged] + upload_all: + needs: [make_sdist, make_cibw_v2_wheels] + runs-on: ubuntu-20.04 if: github.event_name == 'release' && github.event.action == 'published' - runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v7.0.0 + - uses: actions/download-artifact@v3 with: - name: wheels_and_sdist + name: artifact path: dist - - uses: pypa/gh-action-pypi-publish@v1.13.0 + - uses: pypa/gh-action-pypi-publish@v1.5.1 with: password: ${{ secrets.pypi_password }} diff --git a/.gitignore b/.gitignore index 1141de9..5bd718f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,57 +1,72 @@ -# Byte-compiled / optimized +h3c/ *.py[cod] -__pycache__/ +.cache/ +h3/out/ + +# Generated C code from Cython test +tests/*.c +# Cython HTML annotations +*.html # C extensions *.so -# Generated C code from Cython test -tests/**/*.c -# Cython HTML annotations -*.html - -# Build artifacts -build/ -dist/ +# Packages +*.egg *.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg -# Coverage +# Installer logs +pip-log.txt + +# Unit test / coverage reports .coverage coverage.xml -coverage.lcov +.tox +nosetests.xml +.noseids +.pytest_cache + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject + +*.csv +build/ +env/ +env_docs/ +docs/_build/ htmlcov/ -# Test -.pytest_cache/ - -# Tools -.ruff_cache/ -.cache/ - -# Docs -_build/ -docs/_build/ - -# Environment -.venv/ -uv.lock - -# OS -.DS_Store - -# Editor backup files +# vim/emacs backup files *~ \#*\# .\#* .*.sw* -# IDE +#DB snapshots +db_snapshots/ + +#OSX +.DS_Store + +node_modules/ +bower_components/ +.sass-cache/ .idea/ +.unison.* -# IPython / Jupyter .ipynb_checkpoints/ - -# Legacy build dirs _skbuild/ -h3c/ -h3/out/ + +# might want to remove this later when distributing +MANIFEST diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b6ee3a..7fb30c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,4 @@ -# CHANGELOG - -## Versioning +# 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 @@ -15,134 +13,8 @@ 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) -## [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) +- None ## [4.0.0b2] - 2022-11-23 @@ -166,7 +38,7 @@ Beta release; feedback welcome! - 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 52a76f1..85ea71c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,27 +1,11 @@ -cmake_minimum_required(VERSION 3.15...3.26) +cmake_minimum_required(VERSION 3.7.2) -# --- 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) +project(h3) 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 # See all options with `cmake -LA` in an `h3/build` directory, # or at https://h3geo.org/docs/next/core-library/compilation-options/ @@ -53,4 +37,4 @@ install( FILES "${CMAKE_CURRENT_BINARY_DIR}/src/h3lib/src/h3lib/include/h3api.h" DESTINATION - ${SKBUILD_PROJECT_NAME}/_cy) + src/h3/_cy) diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..6ccde1f --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,24 @@ +# 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/cmake +graft src/h3lib/src/h3lib +exclude MANIFEST.in diff --git a/dev_notes.md b/dev_notes.md index 65b4f62..f1b3d53 100644 --- a/dev_notes.md +++ b/dev_notes.md @@ -2,21 +2,11 @@ ## Install for development -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` +- `git clone git@github.com:uber/h3-py.git` - `cd h3-py` -- `just lint` -- `just test` -- `just test-cython` - -To build and view docs: - -- `just docs` -- `just view` +- `make init` +- `make test` +- `make lint` ## Docstrings @@ -58,8 +48,7 @@ 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 `pyproject.toml` -- if updating the C `h3lib` version, update the version badge on the readme +- update the `h3-py` version in `src/h3/_version.py` - 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 37ee18c..1a4a8c8 100644 --- a/docs/_config.yml +++ b/docs/_config.yml @@ -1,6 +1,11 @@ +####################################################################################### +# 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: "2024" +copyright: "2021" logo: logo.svg html: diff --git a/docs/_toc.yml b/docs/_toc.yml index 1238199..9d53f89 100644 --- a/docs/_toc.yml +++ b/docs/_toc.yml @@ -1,16 +1,34 @@ +# Table of contents # Learn more at https://jupyterbook.org/customize/toc.html format: jb-book + root: intro parts: -- caption: h3-py +- caption: Getting started chapters: - - file: api_quick - - file: api_verbose - - file: polygon_tutorial - file: api_comparison + - file: api_reference -- caption: Sundries +- caption: Contributing chapters: - - file: _changelog - file: contributing - - file: project_links + # - 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 diff --git a/docs/api_comparison.md b/docs/api_comparison.md index bcf9991..e3ce64b 100644 --- a/docs/api_comparison.md +++ b/docs/api_comparison.md @@ -1,4 +1,4 @@ -# Comparison of APIs +# API comparison The `h3-py` library provides several APIs which share the same functions, but differ in their input and output types: diff --git a/docs/api_quick.md b/docs/api_quick.md deleted file mode 100644 index 6694ed4..0000000 --- a/docs/api_quick.md +++ /dev/null @@ -1,200 +0,0 @@ -# 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 new file mode 100644 index 0000000..526c85b --- /dev/null +++ b/docs/api_reference.md @@ -0,0 +1,122 @@ +# 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:: + is_valid_cell + is_pentagon + is_res_class_III + is_valid_directed_edge + versions +``` + +### Cells + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + latlng_to_cell + cell_to_latlng + int_to_str + str_to_int + get_res0_cells + get_pentagons + get_num_cells + get_resolution + compact_cells + uncompact_cells +``` + +### Geographic coordinates + +Functions relating H3 objects to geographic (lat/lng) coordinates. + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + great_circle_distance + average_hexagon_area + cell_area + edge_length + average_hexagon_edge_length + cell_to_boundary + directed_edge_to_boundary + polygon_to_cells + cells_to_polygons +``` + +### Hierarchical relationships + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + cell_to_parent + cell_to_children + cell_to_center_child +``` + +### 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 + get_directed_edge_destination + directed_edge_to_cells + origin_to_directed_edges + get_directed_edge_origin +``` + +### IJ-indexing + +```{eval-rst} +.. currentmodule:: h3 + +.. autosummary:: + get_base_cell_number + get_icosahedron_faces + cell_to_local_ij + local_ij_to_cell +``` + + +## Definitions + +```{eval-rst} +.. automodule:: h3 + :members: + :imported-members: +``` diff --git a/docs/api_verbose.md b/docs/api_verbose.md deleted file mode 100644 index 83e5219..0000000 --- a/docs/api_verbose.md +++ /dev/null @@ -1,10 +0,0 @@ -# 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 a76bfb5..b6bfcde 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,12 +1,33 @@ # Contributing -Contributions from the community are welcome! +```{attention} +This page still a work in progress. +``` -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 +## 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 diff --git a/docs/polygon_tutorial.ipynb b/docs/polygon_tutorial.ipynb deleted file mode 100644 index e8df06a..0000000 --- a/docs/polygon_tutorial.ipynb +++ /dev/null @@ -1,933 +0,0 @@ -{ - "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 deleted file mode 100644 index d9f9d63..0000000 --- a/docs/project_links.md +++ /dev/null @@ -1,19 +0,0 @@ -# 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 deleted file mode 100644 index d8e44fb..0000000 --- a/justfile +++ /dev/null @@ -1,61 +0,0 @@ -# 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 new file mode 100644 index 0000000..a2f59da --- /dev/null +++ b/makefile @@ -0,0 +1,49 @@ +.PHONY: init clear rebuild purge test lint lab ipython + +PYTHON=$(shell command -v python || command -v python3) + + +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 + -@find ./tests -type f -name '*.c' | 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 -r requirements-dev.txt + ./env/bin/jupyter lab diff --git a/poly/tutorial.ipynb b/poly/tutorial.ipynb new file mode 100644 index 0000000..745eb9c --- /dev/null +++ b/poly/tutorial.ipynb @@ -0,0 +1,781 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 39, + "id": "48e7d5ca-d782-4d0f-8df3-0f862e5b2082", + "metadata": {}, + "outputs": [], + "source": [ + "#todo reorganize\n", + "# do basics first, then API summary, then do geopandas integration" + ] + }, + { + "cell_type": "markdown", + "id": "29ff917d-82f6-4f70-9263-6abc9a596021", + "metadata": {}, + "source": [ + "# Using `h3-py` to convert between polygons and H3 cells\n", + "\n", + "We can use `h3-py` to convert GeoJSON-like Polygons and MultiPolygons to sets of H3 cells and vice versa.\n", + "\n", + "First we'll import relevant libraries, and define a plotting helper function to visualize the shapes we're dealing with." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "595a3eea-392d-44e1-a657-1a2771b08947", + "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", + "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", + " fig, 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", + "def plot_shape(shape, ax=None):\n", + " df = geopandas.GeoDataFrame({'geometry': [shape]}, crs='EPSG:4326')\n", + " plot_df(df, ax=ax)\n", + "\n", + "def plot_cells(cells, ax=None):\n", + " shape = h3.cells_to_h3shape(cells)\n", + " plot_shape(shape, ax=ax)" + ] + }, + { + "cell_type": "markdown", + "id": "06330c3d-ad4b-494d-a760-98aedeafd65b", + "metadata": {}, + "source": [ + "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 the `__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", + "**Note**: 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": "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 a collection of 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": [ + "We can use `h3.geo_to_cells()` to get the associated set of H3 cells at resolution 6." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1a12743-b5e2-4cd1-a7fd-848e920fa928", + "metadata": {}, + "outputs": [], + "source": [ + "cells = h3.geo_to_cells(geo, res=6)\n", + "cells" + ] + }, + { + "cell_type": "markdown", + "id": "d568b20e-88cb-4269-99ce-dc96a73d93d1", + "metadata": {}, + "source": [ + "# Visualizing H3 cells\n", + "\n", + "To visualize these cells, we can convert the set back to a Polygon or MultiPolygon using `h3.cells_to_shape()`.\n", + "Note that the returned object will be either `H3Poly` or `H3MulitPoly`, each of which implement `__geo_interface__`.\n", + "Because they impelement this interface, these objects will be compatible with Python libraries like GeoPandas." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "652576b9-98e5-439c-be95-a25ae8d86087", + "metadata": {}, + "outputs": [], + "source": [ + "h3shape = h3.cells_to_h3shape(cells)\n", + "h3shape" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f10939f-a520-4417-9c47-b6bdbc3ed09c", + "metadata": {}, + "outputs": [], + "source": [ + "h3shape.__geo_interface__" + ] + }, + { + "cell_type": "markdown", + "id": "fc49cfd6-2c9d-46c1-8901-e277d2cc3617", + "metadata": {}, + "source": [ + "To demonstrate, we'll convert all of the boroughs and plot the results." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45c98d61-ac9f-4832-bad6-57dfca40e4c1", + "metadata": {}, + "outputs": [], + "source": [ + "res = 8\n", + "\n", + "s = df.geometry.apply(lambda x: h3.geo_to_cells(x, res))\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "04ff8c9c-3e7c-4346-b890-9ddf2911baa4", + "metadata": {}, + "outputs": [], + "source": [ + "s = s.apply(h3.cells_to_h3shape)\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb871b94-beb5-4eb4-83ec-3251d13ef3fc", + "metadata": {}, + "outputs": [], + "source": [ + "s[1]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14890fba-fe1c-4343-8820-4db1c3c165ba", + "metadata": {}, + "outputs": [], + "source": [ + "df.geometry = s\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7506a042-c8d7-4475-b7a1-c43ec80c2e26", + "metadata": {}, + "outputs": [], + "source": [ + "# TODO: note that geopandas automaticallyc converst the H3Shape objects to Shapely objects via `__geo_interface__`\n", + "type(df.geometry[1])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8655f681-b929-41e6-ae45-dbbff5da90e0", + "metadata": {}, + "outputs": [], + "source": [ + "plot_df(df, column='BoroName')" + ] + }, + { + "cell_type": "markdown", + "id": "54de7696-5934-4257-847e-08384f68d78d", + "metadata": {}, + "source": [ + "# H3Poly and H3MultiPoly details\n", + "\n", + "As demonstrated above, we expect `h3.geo_to_cells()` and `h3.cells_to_geo()` to cover most common use cases.\n", + "For more control, the API provides some additional objects and functions.\n", + "\n", + "The following classes describe GeoJSON-like Polygons and MultiPolygons:\n", + "\n", + "- `H3Shape`: abstract base class; parent of the two below\n", + "- `H3Poly`: similar to a Shapely `Polygon`\n", + "- `H3MultiPoly`: similar to a Shapely `MultiPolyon`\n", + "\n", + "\n", + "The following functions convert between `H3Shape` objects and cells:\n", + "\n", + "- `h3shape_to_cells`\n", + "- `cells_to_h3shape`\n", + "\n", + "\n", + "The following functions convert between \"geo\" objects and `H3Shape` objects.\n", + "\n", + "- `geo_to_h3shape`\n", + "- `h3shape_to_geo`\n", + "\n", + "Here, a \"geo\" object is either:\n", + "\n", + "- anything that implements `__geo_interface__`\n", + "- a dictionary like what is output by `__geo_interface__`\n", + "\n", + "Note that if an object `a` is an `H3Shape` (either `H3Poly` or `H3MultiPoly`)\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`: `geo_to_h3shape(a) == a`.\n", + "\n", + "\n", + "Summarizing, `H3Shape` objects are the intermediate representation used to translate from\n", + "external objects that implement `__geo_interface__` (like you'd have from using GeoPandas).\n", + "\n", + "```\n", + "\"Geo\" object <-> H3Shape <-> H3 cells\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cac95253-5960-42ad-9c36-7e55f60a3d55", + "metadata": {}, + "outputs": [], + "source": [ + "h3.H3Poly?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5850a20c-b09a-4b7f-8522-aa408b896e02", + "metadata": {}, + "outputs": [], + "source": [ + "# TODO\n", + "h3.H3MultiPoly?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8fb43747-680b-43ca-91c2-53fc2055245c", + "metadata": {}, + "outputs": [], + "source": [ + "# can iterate through multipolygons\n", + "# can get len\n", + "# how to read the description\n", + "# h3 polygons don't close. order doesn't matter. not differences when converting to geojson\n", + "\n", + "# plot shape helper" + ] + }, + { + "cell_type": "markdown", + "id": "c5a41e2b-0c9e-45f5-8005-51af2ef8af32", + "metadata": {}, + "source": [ + "# H3Poly and H3MultiPoly\n", + "\n", + "We can create a simple `H3Poly` object by providing a list of the **latitude/longitude pairs** that describe its exterior." + ] + }, + { + "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", + "hole1 = [\n", + " (37.782, -122.449),\n", + " (37.779, -122.465),\n", + " (37.788, -122.454),\n", + "]\n", + "\n", + "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.H3Poly(outer)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "markdown", + "id": "5b49dc26-12a2-4ca6-aa26-e3548461024e", + "metadata": {}, + "source": [ + "Holes can be added to the polygon by appending additional lat/lng lists." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6872b341-afc9-4405-b27a-b5f2b8a19847", + "metadata": {}, + "outputs": [], + "source": [ + "poly = h3.H3Poly(outer, hole1)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2d7ae0fb-fa96-46fe-8d06-7778575642dd", + "metadata": {}, + "outputs": [], + "source": [ + "poly = h3.H3Poly(outer, hole1, hole2)\n", + "print(poly)\n", + "plot_shape(poly)" + ] + }, + { + "cell_type": "markdown", + "id": "62317cfd-8a0e-4c8a-b899-131acdec4305", + "metadata": {}, + "source": [ + "The `H3Poly` 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", + "- `H3Poly.outer` gives the list of lat/lng points making up the outer loop of the polygon.\n", + "- `H3Poly.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.H3Poly(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": [ + "`H3Poly.__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**, and the last vertex repeats the first." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fb79c742-27aa-481c-971b-28c100109efe", + "metadata": {}, + "outputs": [], + "source": [ + "poly.__geo_interface__" + ] + }, + { + "cell_type": "markdown", + "id": "8f567fae-9f4e-472f-afcd-bd6f7bb32cba", + "metadata": {}, + "source": [ + "Note that we can create an `H3Poly` object from a GeoJSON-like dictionary using `h3.geo_to_h3shape()`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42d7d580-2bba-4cd3-8d13-2434323e4081", + "metadata": {}, + "outputs": [], + "source": [ + "h3.geo_to_h3shape(poly.__geo_interface__)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b6196ad-113d-4371-bf67-d82bcb84e4a2", + "metadata": {}, + "outputs": [], + "source": [ + "h3.geo_to_h3shape(poly.__geo_interface__).__geo_interface__" + ] + }, + { + "cell_type": "markdown", + "id": "faa6a726-2adc-40cc-9e1e-5d4ee66a08ea", + "metadata": {}, + "source": [ + "## H3 Polygons don't need to follow the right-hand rule\n", + "\n", + "`H3Poly` 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 do the correct thing when, 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", + "This is only a concern when creating `H3Poly` objects from external input; `H3Poly` or `H3MultiPoly`\n", + "objects created through `h3.cells_to_shape()` **will respect the right-hand rule**.\n", + "\n", + "For example, if we reverse the order of one of the holes in our example polygon,\n", + "the hole won't be rendered correctly, but the conversion to cells will still be correct." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "143c911d-e8df-496b-8b08-cb3587f68450", + "metadata": {}, + "outputs": [], + "source": [ + "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": "code", + "execution_count": null, + "id": "34ef8624-c852-419d-9e98-e9ec70ec6bc0", + "metadata": {}, + "outputs": [], + "source": [ + "# Respects right-hand rule\n", + "poly = h3.H3Poly(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.H3Poly(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.H3Poly(outer[::-1], hole1[::-1], hole2)\n", + "plot_shape_and_cells(poly, res=10)" + ] + }, + { + "cell_type": "markdown", + "id": "b0b13d4a-a376-4a8f-b314-898d9cf94c59", + "metadata": {}, + "source": [ + "## H3MultiPoly\n", + "\n", + "An `H3MultiPoly` can be created from `H3Poly` objects. The string representation of the `H3MultiPoly`\n", + "gives the number of vertices in the outer loop of each `H3Poly`, along with the number of vertices\n", + "in each hole (if there are any)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16b0b4b2-2cfb-461d-bd69-511c87e208a3", + "metadata": {}, + "outputs": [], + "source": [ + "poly1 = h3.H3Poly([(37.804, -122.412), (37.778, -122.507), (37.733, -122.501)])\n", + "poly2 = h3.H3Poly(\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.H3MultiPoly(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": [ + "`h3.h3shape_to_cells()` works on both `H3MultiPoly` and `H3Poly` objects." + ] + }, + { + "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": "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": "0ae6d480-4807-4ca1-ac20-4095a20ded31", + "metadata": {}, + "source": [ + "# Summary\n", + "\n", + "geo <> shape <> cells\n", + "\n", + "Most users can use\n", + "\n", + "- `geo_to_cells`\n", + "- `cells_to_geo`\n", + "\n", + "\n", + "For an alternative interface, consider the classes\n", + "\n", + "- `H3Shape`\n", + "- `H3Poly`\n", + "- `H3MultiPoly`\n", + "\n", + "\n", + "We have a few functions for dealing with polygons in H3:\n", + "\n", + "- `h3shape_to_cells`\n", + "- `cells_to_h3shape`\n", + "\n", + "do i need:\n", + "\n", + "- `geo_to_h3shape`\n", + "- `h3shape_to_geo`\n", + "\n", + "Define `geo`:\n", + "\n", + "- anything that implements `__geo_interface__`\n", + "- a dictionary like `__geo_interface__`" + ] + }, + { + "cell_type": "markdown", + "id": "5838f6c8-aacb-4813-be7c-756c87945476", + "metadata": {}, + "source": [ + "# Interfacing with GeoPandas and other libraries\n", + "\n", + "TODO" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cd012d79-a653-4d5d-bb30-408031301015", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyproject.toml b/pyproject.toml index 4430799..ce6867f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,143 +1,6 @@ [build-system] -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 +requires = [ + 'scikit-build', + 'cython', + 'cmake', ] diff --git a/readme.md b/readme.md index 8cb052b..eab09ad 100644 --- a/readme.md +++ b/readme.md @@ -1,16 +1,30 @@ -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-v4.5.0-blue.svg)](https://github.com/uber/h3/releases/tag/v4.5.0) +[![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/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) -[![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) +[![codecov](https://codecov.io/gh/uber/h3-py/branch/master/graph/badge.svg)](https://codecov.io/gh/uber/h3-py) +---- +### ANNOUNCEMENT: v4.0.0 beta released! +Install the latest beta version with `pip install h3 --pre` +or with +`pip install 'h3==4.0.0b2'`.
+Feedback is welcome via +[Issues](https://github.com/uber/h3-py/issues/new), +[Discussions](https://github.com/uber/h3/discussions), +and +[Slack](https://join.slack.com/t/h3-core/shared_invite/zt-g6u5r1hf-W_~uVJmfeiWtMQuBGc1NNg). + +---- Python bindings for the [H3 core library](https://h3geo.org/). @@ -47,12 +61,12 @@ conda install h3-py ## APIs [api_comparison]: https://uber.github.io/h3-py/api_comparison -[api_quick]: https://uber.github.io/h3-py/api_quick +[api_reference]: https://uber.github.io/h3-py/api_reference We provide [multiple APIs][api_comparison] in `h3-py`. - All APIs have the same set of functions; - see the [API reference][api_quick]. + see the [API reference][api_reference]. - The APIs differ only in their input/output formats; see the [API comparison page][api_comparison]. @@ -91,5 +105,5 @@ Use `h3.versions()` to see the version numbers for both ```python >>> import h3 >>> h3.versions() -{'c': '4.1.0', 'python': '4.1.1'} +{'c': '3.6.3', 'python': '3.6.1'} ``` diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..c6ffe77 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,8 @@ +jupyterlab +jupyterlab-geojson +geopandas +geodatasets +matplotlib +contextily +cartopy +geoviews diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000..6412c77 --- /dev/null +++ b/requirements.in @@ -0,0 +1,14 @@ +# 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 new file mode 100644 index 0000000..23353b1 --- /dev/null +++ b/setup.py @@ -0,0 +1,44 @@ +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 1e4f4b8..4f7cb32 100644 --- a/src/h3/__init__.py +++ b/src/h3/__init__.py @@ -26,8 +26,4 @@ from ._cy import ( H3MemoryAllocError, H3MemoryBoundsError, H3OptionInvalidError, - H3IndexInvalidError, - H3BaseCellDomainError, - H3DigitDomainError, - H3DeletedDigitError, ) diff --git a/src/h3/_cy/CMakeLists.txt b/src/h3/_cy/CMakeLists.txt index 2cb2b6f..5d392d2 100644 --- a/src/h3/_cy/CMakeLists.txt +++ b/src/h3/_cy/CMakeLists.txt @@ -1,35 +1,30 @@ -list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +find_package(Cython MODULE REQUIRED) +find_package(PythonExtensions MODULE REQUIRED) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +# Build Cython annotations +set(CYTHON_ANNOTATE TRUE) + macro(add_cython_file 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) - + add_cython_target(${filename} C PY3) + add_library(${filename} MODULE ${filename} ${LIB_SOURCE_FILES} ${CONFIGURED_API_HEADER}) + python_extension_module(${filename}) set_property(TARGET ${filename} PROPERTY C_STANDARD 99) - target_link_libraries(${filename} PRIVATE h3) - install(TARGETS ${filename} LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}/_cy) + target_link_libraries(${filename} h3) + install(TARGETS ${filename} LIBRARY DESTINATION src/h3/_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(latlng) 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(util) +add_cython_file(error_system) +add_cython_file(memory) + # Include pyx and pxd files in distribution for use by Cython API install( @@ -38,16 +33,14 @@ install( cells.pyx edges.pxd edges.pyx - error_system.pyx - h3lib.pxd latlng.pxd latlng.pyx - memory.pxd - memory.pyx + h3lib.pxd util.pxd util.pyx - vertex.pxd - vertex.pyx + error_system.pyx + memory.pxd + memory.pyx DESTINATION - ${SKBUILD_PROJECT_NAME}/_cy + src/h3/_cy ) diff --git a/src/h3/_cy/__init__.py b/src/h3/_cy/__init__.py index 70fa087..c208711 100644 --- a/src/h3/_cy/__init__.py +++ b/src/h3/_cy/__init__.py @@ -14,21 +14,15 @@ function interface and input conversion (string to int, for instance). """ from .cells import ( - is_valid_index, is_valid_cell, is_pentagon, 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, @@ -61,20 +55,11 @@ from .latlng import ( 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 ( cells_to_multi_polygon ) @@ -112,11 +97,4 @@ from .error_system import ( 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 1bc31b8..b6a36d1 100644 --- a/src/h3/_cy/cells.pxd +++ b/src/h3/_cy/cells.pxd @@ -1,21 +1,15 @@ from .h3lib cimport bool, int64_t, H3int -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_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 diff --git a/src/h3/_cy/cells.pyx b/src/h3/_cy/cells.pyx index f0667e5..6a21576 100644 --- a/src/h3/_cy/cells.pyx +++ b/src/h3/_cy/cells.pyx @@ -1,17 +1,13 @@ -# cython: freethreading_compatible=True cimport h3lib from .h3lib cimport bool, int64_t, H3int, H3ErrorCodes from .util cimport ( check_cell, - check_index, + check_res, check_distance, ) -from .util import EARTH_RADIUS_KM - from .error_system cimport ( - H3Error, check_for_error, check_for_error_msg, ) @@ -23,14 +19,6 @@ from .memory cimport ( # 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_valid_cell(H3int h): @@ -61,33 +49,6 @@ cpdef int get_resolution(H3int h) except -1: 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 grid_distance(H3int h1, H3int h2) except -1: """ Compute the grid distance between two cells @@ -126,6 +87,41 @@ cpdef H3int[:] grid_disk(H3int h, int k): 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 algorithm runs into a pentagon. + """ + cdef: + int64_t n + int[:] distances ## todo: weird, this needs to be specified to avoid errors. cython bug? + + check_cell(h) + check_distance(k) + + check_for_error( + h3lib.maxGridDiskSize(k, &n) + ) + hmm = H3MemoryManager(n) + + # parallel array of cell distances from `h`. + # idea: instead of a memoryview object, have a my_mv object that can return a ptr, but does the correct logic when it has length 0 + # then can always just return the pointer, instead of the weird &mv[0] syntax + distances = int_mv(n) + check_for_error( + h3lib.gridDiskDistances(h, k, hmm.ptr, &distances[0]) + ) + + for i,v in enumerate(distances): + if v != k: + hmm.ptr[i] = 0 + + mv = hmm.to_mv() + + return mv + cpdef H3int[:] grid_ring(H3int h, int k): """ Return cells at grid distance `== k` from `h`. Collection is "hollow" for k >= 1. @@ -135,19 +131,20 @@ cpdef H3int[:] grid_ring(H3int h, int k): n = 6*k if k > 0 else 1 hmm = H3MemoryManager(n) - check_for_error( - h3lib.gridRing(h, k, hmm.ptr) - ) - mv = hmm.to_mv() + err = h3lib.gridRingUnsafe(h, k, hmm.ptr) + if err: + mv = _ring_fallback(h, k) + else: + mv = hmm.to_mv() return mv - cpdef H3int cell_to_parent(H3int h, res=None) except 0: cdef: H3int parent - check_cell(h) + check_cell(h) # todo: do we want to check for validity here? or leave correctness to the user? + if res is None: res = get_resolution(h) - 1 @@ -160,11 +157,12 @@ cpdef H3int cell_to_parent(H3int h, res=None) except 0: return parent -cpdef int64_t cell_to_children_size(H3int h, res=None) except -1: +cpdef H3int[:] cell_to_children(H3int h, res=None): cdef: int64_t n check_cell(h) + if res is None: res = get_resolution(h) + 1 @@ -174,16 +172,6 @@ cpdef int64_t cell_to_children_size(H3int h, res=None) except -1: msg = msg.format(res, hex(h)) check_for_error_msg(err, msg) - return 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) @@ -193,12 +181,12 @@ cpdef H3int[:] cell_to_children(H3int h, res=None): return mv - cpdef H3int cell_to_center_child(H3int h, res=None) except 0: cdef: H3int child check_cell(h) + if res is None: res = get_resolution(h) + 1 @@ -211,33 +199,6 @@ cpdef H3int cell_to_center_child(H3int h, res=None) except 0: return child -cpdef int64_t cell_to_child_pos(H3int child, int parent_res) except -1: - cdef: - int64_t child_pos - - 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? @@ -324,8 +285,7 @@ cpdef double average_hexagon_area(int resolution, unit='km^2') except -1: # todo: multiple units convert = { 'km^2': 1.0, - 'm^2': 1000*1000.0, - 'rads^2': 1.0/(EARTH_RADIUS_KM*EARTH_RADIUS_KM), + 'm^2': 1000*1000.0 } try: @@ -426,7 +386,7 @@ cpdef get_icosahedron_faces(H3int h): # 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] + out = {f for f in faces if f >= 0} return out diff --git a/src/h3/_cy/edges.pyx b/src/h3/_cy/edges.pyx index 7364bd5..bd0aa7c 100644 --- a/src/h3/_cy/edges.pyx +++ b/src/h3/_cy/edges.pyx @@ -1,11 +1,8 @@ -# cython: freethreading_compatible=True cimport h3lib from .h3lib cimport bool, H3int from .error_system cimport check_for_error -from .util import EARTH_RADIUS_KM - from .memory cimport H3MemoryManager # todo: make bint @@ -88,8 +85,7 @@ cpdef double average_hexagon_edge_length(int resolution, unit='km') except -1: # todo: multiple units convert = { 'km': 1.0, - 'm': 1000.0, - 'rads': 1.0/EARTH_RADIUS_KM, + 'm': 1000.0 } try: diff --git a/src/h3/_cy/error_system.pxd b/src/h3/_cy/error_system.pxd index 4a1e3b4..af8c709 100644 --- a/src/h3/_cy/error_system.pxd +++ b/src/h3/_cy/error_system.pxd @@ -1,6 +1,3 @@ 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 index 5fe5cd9..fbdd918 100644 --- a/src/h3/_cy/error_system.pyx +++ b/src/h3/_cy/error_system.pyx @@ -1,4 +1,3 @@ -# cython: freethreading_compatible=True """ Exceptions from the h3-py library have three possible sources: @@ -61,10 +60,6 @@ Summarizing, all exceptions originating from the C library inherit from - H3MemoryAllocError - H3MemoryBoundsError - H3OptionInvalidError -- H3IndexInvalidError -- H3BaseCellDomainError -- H3DigitDomainError -- H3DeletedDigitError # TODO: add tests verifying that concrete exception classes have the right error codes associated with them @@ -92,11 +87,6 @@ from .h3lib cimport ( 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 @@ -179,10 +169,6 @@ with _the_error(H3ValueError) as e: class H3NotNeighborsError(e): ... class H3ResMismatchError(e): ... class H3OptionInvalidError(e): ... - class H3IndexInvalidError(e): ... - class H3BaseCellDomainError(e): ... - class H3DigitDomainError(e): ... - class H3DeletedDigitError(e): ... """ @@ -206,10 +192,6 @@ error_mapping = { 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 @@ -225,37 +207,25 @@ for code, ex in error_mapping.items(): # 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. - """ +cdef code_to_exception(H3Error err): if err == E_SUCCESS: return None elif err in error_mapping: return error_mapping[err] else: - return UnknownH3ErrorCode(err) + raise UnknownH3ErrorCode(err) cdef check_for_error(H3Error err): - ex = error_code_to_exception(err) + ex = 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) + ex = code_to_exception(err) if ex: raise ex(msg) diff --git a/src/h3/_cy/h3lib.pxd b/src/h3/_cy/h3lib.pxd index 6ee3b41..00fff60 100644 --- a/src/h3/_cy/h3lib.pxd +++ b/src/h3/_cy/h3lib.pxd @@ -1,8 +1,7 @@ -# cython: c_string_type=unicode, c_string_encoding=utf8 from cpython cimport bool from libc.stdint cimport uint32_t, uint64_t, int64_t -ctypedef object H3str +ctypedef basestring H3str cdef extern from 'h3api.h': cdef int H3_VERSION_MAJOR @@ -29,11 +28,6 @@ cdef extern from 'h3api.h': 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 @@ -47,6 +41,21 @@ cdef extern from 'h3api.h': int i int j + ctypedef struct LinkedLatLng: + LatLng data 'vertex' + LinkedLatLng *next + + # renaming these for clarity + ctypedef struct LinkedGeoLoop: + LinkedLatLng *data 'first' + LinkedLatLng *_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 GeoLoop: int numVerts LatLng *verts @@ -60,32 +69,22 @@ cdef extern from 'h3api.h': 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 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 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 - H3Error cellToVertex(H3int cell, int vertexNum, H3int *out) nogil - H3Error cellToVertexes(H3int cell, H3int *vertexes) nogil - H3Error vertexToLatLng(H3int vertex, LatLng *coord) nogil - H3Error maxGridDiskSize(int k, int64_t *out) nogil # num/out/N? H3Error gridDisk(H3int h, int k, H3int *out) nogil 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 H3Error cellToChildrenSize(H3int h, int childRes, int64_t *num) nogil # num/out/N? H3Error cellToChildren( H3int h, int childRes, H3int *children) nogil @@ -132,7 +131,6 @@ cdef extern from 'h3api.h': H3Error localIjToCell(H3int origin, const CoordIJ *ij, uint32_t mode, H3int *out) nogil 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 H3Error areNeighborCells(H3int origin, H3int destination, int *out) nogil @@ -156,15 +154,15 @@ cdef extern from 'h3api.h': double greatCircleDistanceKm(const LatLng *a, const LatLng *b) nogil double greatCircleDistanceM(const LatLng *a, const LatLng *b) nogil + H3Error cellsToLinkedMultiPolygon(const H3int *h3Set, const int numCells, LinkedGeoPolygon *out) + void destroyLinkedMultiPolygon(LinkedGeoPolygon *polygon) + 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) - 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) - - ctypedef struct GeoMultiPolygon: - int numPolygons - GeoPolygon *polygons + # ctypedef struct GeoMultiPolygon: + # int numPolygons + # GeoPolygon *polygons # int hexRange(H3int origin, int k, H3int *out) @@ -181,11 +179,3 @@ cdef extern from 'h3api.h': # void h3ToString(H3int h, char *str, size_t sz) # void getH3intesFromUnidirectionalEdge(H3int edge, H3int *originDestination) - - -# 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.pyx b/src/h3/_cy/latlng.pyx index 630d3ad..520b950 100644 --- a/src/h3/_cy/latlng.pyx +++ b/src/h3/_cy/latlng.pyx @@ -1,4 +1,3 @@ -# cython: freethreading_compatible=True from libc.stdint cimport uint64_t cimport h3lib @@ -9,7 +8,7 @@ from .util cimport ( check_edge, check_res, deg2coord, - coord2deg + coord2deg, ) from .error_system cimport check_for_error @@ -158,10 +157,6 @@ def polygon_to_cells(outer, int res, holes=None): uint64_t n check_res(res) - - if not outer: - return H3MemoryManager(0).to_mv() - gp = GeoPolygon(outer, holes=holes) check_for_error( @@ -197,84 +192,6 @@ def polygons_to_cells(polygons, int res): 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: diff --git a/src/h3/_cy/memory.pyx b/src/h3/_cy/memory.pyx index 963b00d..0852105 100644 --- a/src/h3/_cy/memory.pyx +++ b/src/h3/_cy/memory.pyx @@ -1,4 +1,3 @@ -# cython: freethreading_compatible=True from cython.view cimport array from .h3lib cimport H3int diff --git a/src/h3/_cy/to_multipoly.pyx b/src/h3/_cy/to_multipoly.pyx index cb5e5e2..db29baa 100644 --- a/src/h3/_cy/to_multipoly.pyx +++ b/src/h3/_cy/to_multipoly.pyx @@ -1,46 +1,60 @@ -# cython: freethreading_compatible=True cimport h3lib from h3lib cimport H3int from .util cimport check_cell, coord2deg -from .error_system cimport check_for_error -cdef _loop_to_list(const h3lib.GeoLoop *loop): - return [coord2deg(loop.verts[v]) for v in range(loop.numVerts)] +# 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 _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_loops(const h3lib.LinkedGeoLoop* L): + out = [] + while L: + out += [walk_coords(L.data)] + L = L.next + + return out +cdef walk_coords(const h3lib.LinkedLatLng* L): + out = [] + while L: + out += [coord2deg(L.data)] + L = L.next + + return out + +# todo: tuples instead of lists? def _to_multi_polygon(const H3int[:] cells): cdef: - h3lib.GeoMultiPolygon mpoly - H3int cell + h3lib.LinkedGeoPolygon polygon - for cell in cells: - check_cell(cell) + for h in cells: + check_cell(h) - check_for_error( - h3lib.cellsToMultiPolygon(&cells[0], len(cells), &mpoly) - ) + h3lib.cellsToLinkedMultiPolygon(&cells[0], len(cells), &polygon) - try: - out = [ - _poly_to_lists(&mpoly.polygons[p]) - for p in range(mpoly.numPolygons) - ] - finally: - h3lib.destroyGeoMultiPolygon(&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.destroyLinkedMultiPolygon(&polygon) return out def cells_to_multi_polygon(const H3int[:] cells): + # todo: gotta be a more elegant way to handle these... if len(cells) == 0: return [] - return _to_multi_polygon(cells) + multipoly = _to_multi_polygon(cells) + + return multipoly diff --git a/src/h3/_cy/util.pxd b/src/h3/_cy/util.pxd index b584d3a..15e97ad 100644 --- a/src/h3/_cy/util.pxd +++ b/src/h3/_cy/util.pxd @@ -8,7 +8,5 @@ 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) diff --git a/src/h3/_cy/util.pyx b/src/h3/_cy/util.pyx index 74e8f80..8bc061d 100644 --- a/src/h3/_cy/util.pyx +++ b/src/h3/_cy/util.pyx @@ -1,12 +1,4 @@ -# cython: freethreading_compatible=True -from .h3lib cimport ( - H3int, - H3str, - isValidCell, - isValidDirectedEdge, - isValidVertex, - isValidIndex, -) +from .h3lib cimport H3int, H3str, isValidCell, isValidDirectedEdge cimport h3lib @@ -15,14 +7,8 @@ from .error_system import ( H3DomainError, H3DirEdgeInvalidError, H3CellInvalidError, - H3VertexInvalidError, - H3IndexInvalidError, ) -# 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.LatLng c @@ -87,14 +73,6 @@ cdef check_edge(H3int 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 H3ResDomainError(res) diff --git a/src/h3/_cy/vertex.pxd b/src/h3/_cy/vertex.pxd deleted file mode 100644 index 98d890c..0000000 --- a/src/h3/_cy/vertex.pxd +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 99cc5ef..0000000 --- a/src/h3/_cy/vertex.pyx +++ /dev/null @@ -1,55 +0,0 @@ -# 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 index 68d18c2..4607ca8 100644 --- a/src/h3/_h3shape.py +++ b/src/h3/_h3shape.py @@ -2,18 +2,15 @@ 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): +class H3Poly(H3Shape): """ - Container for loops of lat/lng points describing a polygon, possibly with holes. + Container for loops of lat/lng points describing a polygon. Attributes ---------- @@ -28,39 +25,36 @@ class LatLngPoly(H3Shape): A polygon with a single outer ring consisting of 4 points, having no holes: - >>> LatLngPoly( + >>> H3Poly( ... [(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( + >>> H3Poly( ... [(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( + >>> H3Poly( ... [(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.') + if len(loop) in (1, 2): + self.outer = [] + self.holes = [] + raise ValueError('Non-empty H3Poly loops need at least 3 points.') self.outer = tuple(_open_ring(outer)) self.holes = tuple( @@ -69,23 +63,23 @@ class LatLngPoly(H3Shape): ) def __repr__(self): - return ''.format(self.loopcode) + 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.') + raise NotImplementedError('No clear definition of length for H3Poly.') @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, + 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. + Example: `[15]` indicates an outer loop of 15 points and no holes. """ outer = len(self.outer) holes = tuple(map(len, self.holes)) @@ -107,26 +101,18 @@ class LatLngPoly(H3Shape): 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 - """ +class H3MultiPoly(H3Shape): 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 + if not isinstance(p, H3Poly): + raise ValueError('H3MultiPoly requires each input to be an H3Poly object, instead got: ' + str(p)) # noqa def __repr__(self): out = [p.loopcode for p in self.polys] out = ', '.join(out) - out = ''.format(out) + out = ''.format(out) return out def __iter__(self): @@ -140,25 +126,24 @@ class LatLngMultiPoly(H3Shape): 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. + I'd prefer the one that states `H3MultiPoly`. 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 , , ) - 1 (, , , , , , <... + 0 (, , ) + 1 (, , , , , , <... """ return len(self.polys) @@ -184,6 +169,13 @@ 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) + + +## TODO + +- Allow user to specify "container" in `cells_to_geojson`. + - That is, they may want a MultiPolygon even if the output fits in a Polygon + - 'auto', Polygon, MultiPolygon, FeatureCollection, GeometryCollection, ... """ @@ -202,13 +194,13 @@ def _LL3_to_mpoly(ll3): for ll2 in ll3 ] - mpoly = LatLngMultiPoly(*polys) + mpoly = H3MultiPoly(*polys) return mpoly -def _polygon_to_LL2(poly): - ll2 = [poly.outer] + list(poly.holes) +def _polygon_to_LL2(h3poly): + ll2 = [h3poly.outer] + list(h3poly.holes) ll2 = tuple( _close_ring(_swap_latlng(ll1)) for ll1 in ll2 @@ -217,26 +209,12 @@ def _polygon_to_LL2(poly): 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) + h3poly = H3Poly(*ll2) return h3poly @@ -288,16 +266,16 @@ def _open_ring(ll1): def geo_to_h3shape(geo): """ - Translate from ``__geo_interface__`` to H3Shape. + Translate from __geo_interface__ to H3Shape. - ``geo`` either implements ``__geo_interface__`` or is a dict matching the format + `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 + # geo can be dict, a __geo_interface__, a string, H3Poly or H3MultiPoly if isinstance(geo, H3Shape): return geo @@ -305,84 +283,31 @@ def geo_to_h3shape(geo): # 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)) - ) + assert isinstance(geo, dict) # todo: remove t = geo['type'] coord = geo['coordinates'] if t == 'Polygon': ll2 = coord - shape = _LL2_to_polygon(ll2) + h3shape = _LL2_to_polygon(ll2) elif t == 'MultiPolygon': ll3 = coord - shape = _LL3_to_mpoly(ll3) + h3shape = _LL3_to_mpoly(ll3) else: raise ValueError('Unrecognized type: ' + str(t)) - return shape + return h3shape -def h3shape_to_geo(h3shape, container='auto'): +def h3shape_to_geo(h3shape): """ - Translate from an ``H3Shape`` to a ``__geo_interface__`` dict. + Translate from 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). + `h3shape` should be either H3Poly or H3MultiPoly 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']}'." - ) + return h3shape.__geo_interface__ diff --git a/src/h3/_version.py b/src/h3/_version.py index 712565a..56fe687 100644 --- a/src/h3/_version.py +++ b/src/h3/_version.py @@ -1,3 +1,26 @@ -from importlib import metadata - -__version__ = metadata.version(__package__ or __name__) +__version__ = '4.0.0b2' +__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', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: POSIX :: Linux', + 'Operating System :: Microsoft :: Windows', + 'Topic :: Scientific/Engineering :: GIS', +] diff --git a/src/h3/api/__init__.py b/src/h3/api/__init__.py index 435b13a..9bc858a 100644 --- a/src/h3/api/__init__.py +++ b/src/h3/api/__init__.py @@ -3,4 +3,3 @@ 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 new file mode 100644 index 0000000..58c725d --- /dev/null +++ b/src/h3/api/_api_template.py @@ -0,0 +1,944 @@ +""" +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 +from .._h3shape import ( + H3Poly, + H3MultiPoly, + geo_to_h3shape, + h3shape_to_geo, +) + + +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 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) + + @staticmethod + 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) + + @staticmethod + 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) + + @staticmethod + def average_hexagon_area(res, unit='km^2'): + """ + Return the average area of an H3 *hexagon* + for the given resolution. + + This average *excludes* pentagons. + + Returns + ------- + float + """ + return _cy.average_hexagon_area(res, unit) + + @staticmethod + def average_hexagon_edge_length(res, unit='km'): + """ + Return the average *hexagon* edge length + for the given resolution. + + This average *excludes* pentagons. + + Returns + ------- + float + """ + return _cy.average_hexagon_edge_length(res, unit) + + def is_valid_cell(self, h): + """ + Validates an H3 cell (hexagon or pentagon). + + Returns + ------- + bool + """ + try: + h = self._in_scalar(h) + return _cy.is_valid_cell(h) + except (ValueError, TypeError): + return False + + def is_valid_directed_edge(self, edge): + """ + Validates an H3 unidirectional edge. + + Returns + ------- + bool + """ + try: + e = self._in_scalar(edge) + return _cy.is_valid_directed_edge(e) + except (ValueError, TypeError): + return False + + def latlng_to_cell(self, lat, lng, res): + """ + Return the cell containing the (lat, lng) point + for a given resolution. + + Returns + ------- + H3Cell + + """ + return self._out_scalar(_cy.latlng_to_cell(lat, lng, res)) + + def cell_to_latlng(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.cell_to_latlng(self._in_scalar(h)) + + def get_resolution(self, h): + """ + Return the resolution of an H3 cell. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + int + """ + # todo: could also work for edges + return _cy.get_resolution(self._in_scalar(h)) + + def cell_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.cell_to_parent(h, res) + p = self._out_scalar(p) + + return p + + def grid_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 raise an exception 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.grid_distance(h1, h2) + + return d + + def cell_to_boundary(self, h): + """ + Return tuple of lat/lng pairs describing the cell boundary. + + Parameters + ---------- + h : H3Cell + + Returns + ------- + tuple of (lat, lng) tuples + """ + return _cy.cell_to_boundary(self._in_scalar(h)) + + def grid_disk(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.grid_disk(self._in_scalar(h), k) + + return self._out_unordered(mv) + + def grid_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.grid_ring(self._in_scalar(h), k) + + return self._out_unordered(mv) + + def cell_to_children(self, h, res=None): + """ + Children of a cell. + + 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.cell_to_children(self._in_scalar(h), res) + + return self._out_unordered(mv) + + # todo: nogil for expensive C operation? + def compact_cells(self, 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 + """ + # todo: does compact_cells work on mixed-resolution collections? + hu = self._in_collection(cells) + hc = _cy.compact_cells(hu) + + return self._out_unordered(hc) + + def uncompact_cells(self, 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 + + Raises + ------ + todo: add test to make sure an error is returned when input + contains cell smaller than output res. + https://github.com/uber/h3/blob/master/src/h3lib/lib/h3Index.c#L425 + """ + hc = self._in_collection(cells) + hu = _cy.uncompact_cells(hc, res) + + return self._out_unordered(hu) + + def h3shape_to_cells(self, h3shape, res): + """ + Return the set of H3 cells at a given resolution whose center points + are contained within an `H3Poly` or `H3MultiPoly`. + + Parameters + ---------- + h3shape : H3shape + res : int + Resolution of the output cells + + Returns + ------- + unordered collection of H3Cell + + Examples + -------- + + >>> poly = H3Poly( + ... [(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'} + """ + + # todo: not sure if i want this dispatch logic here. maybe in the objects? + if isinstance(h3shape, H3Poly): + poly = h3shape + mv = _cy.polygon_to_cells(poly.outer, res, holes=poly.holes) + elif isinstance(h3shape, H3MultiPoly): + mpoly = h3shape + mv = _cy.polygons_to_cells(mpoly.polys, res) + else: + raise ValueError('Unrecognized type: ' + str(h3shape)) + + return self._out_unordered(mv) + + def cells_to_h3shape(self, cells, tight=True): + """ + Return a H3MultiPoly describing the area covered by a set of H3 cells. + + Parameters + ---------- + cells : iterable of H3 cells + tight : bool + If True, return H3Poly if possible. If False, always return H3MultiPoly + + Returns + ------- + H3MultiPoly + + Examples + -------- + + >>> cells = ['8428309ffffffff', '842830dffffffff'] + >>> h3.cells_to_h3shape(cells, tight=True) + + >>> h3.cells_to_h3shape(cells, tight=False) + + """ + cells = self._in_collection(cells) + mpoly = _cy.cells_to_multi_polygon(cells) + + polys = [H3Poly(*poly) for poly in mpoly] + out = H3MultiPoly(*polys) + + if tight and len(out) == 1: + out = out[0] + + return out + + def geo_to_cells(self, geo, res): + """ Convert from __geo_interface__ to cells. + Parameters + ---------- + geo : an object implementing `__geo_interface__` or a dictionary in that format. + Both H3Poly and H3MultiPoly implement the interface. + res : int + Resolution of desired output cells. + """ + h3shape = geo_to_h3shape(geo) + return self.h3shape_to_cells(h3shape, res) + + def cells_to_geo(self, cells, tight=True): + """ + Parameters + ---------- + cells : iterable of H3 Cells + + Returns + ------- + dict + in `__geo_interface__` format + """ + h3shape = self.cells_to_h3shape(cells, tight=tight) + return h3shape_to_geo(h3shape) + + def 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 ``is_valid_cell()``. + Will return ``False`` for valid H3Edge. + """ + return _cy.is_pentagon(self._in_scalar(h)) + + def get_base_cell_number(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_number(self._in_scalar(h)) + + def are_neighbor_cells(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_neighbor_cells(h1, h2) + + def cells_to_directed_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.cells_to_directed_edge(o, d) + e = self._out_scalar(e) + + return e + + def get_directed_edge_origin(self, e): + """ + Origin cell from an H3 directed edge. + + Parameters + ---------- + e : H3Edge + + Returns + ------- + H3Cell + """ + e = self._in_scalar(e) + o = _cy.get_directed_edge_origin(e) + o = self._out_scalar(o) + + return o + + def get_directed_edge_destination(self, e): + """ + Destination cell from an H3 directed edge. + + Parameters + ---------- + e : H3Edge + + Returns + ------- + H3Cell + """ + e = self._in_scalar(e) + d = _cy.get_directed_edge_destination(e) + d = self._out_scalar(d) + + return d + + def directed_edge_to_cells(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.directed_edge_to_cells(e) + o, d = self._out_scalar(o), self._out_scalar(d) + + return o, d + + def origin_to_directed_edges(self, origin): + """ + Return all directed edges starting from ``origin`` cell. + + Parameters + ---------- + origin : H3Cell + + Returns + ------- + unordered collection of H3Edge + """ + mv = _cy.origin_to_directed_edges(self._in_scalar(origin)) + + return self._out_unordered(mv) + + def directed_edge_to_boundary(self, edge): + return _cy.directed_edge_to_boundary(self._in_scalar(edge)) + + def grid_path_cells(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.grid_path_cells(self._in_scalar(start), self._in_scalar(end)) + + return self._out_ordered(mv) + + def 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 get_pentagons(self, 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 self._out_unordered(mv) + + def get_res0_cells(self): + """ + Return all cells at resolution 0. + + Parameters + ---------- + None + + Returns + ------- + unordered collection of H3Cell + """ + mv = _cy.get_res0_cells() + + return self._out_unordered(mv) + + def cell_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.cell_to_center_child(h, res) + p = self._out_scalar(p) + + return p + + def get_icosahedron_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_icosahedron_faces(h) + + return faces + + def cell_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.cell_to_local_ij(origin, h) + + return i, j + + def local_ij_to_cell(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.local_ij_to_cell(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 + `great_circle_distance`. + """ + h = self._in_scalar(h) + + return _cy.cell_area(h, unit=unit) + + def 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 + `great_circle_distance`. + """ + e = self._in_scalar(e) + + return _cy.edge_length(e, unit=unit) + + @staticmethod + 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 + ) diff --git a/src/h3/api/basic_int/__init__.py b/src/h3/api/basic_int/__init__.py index 8eac4b1..a297461 100644 --- a/src/h3/api/basic_int/__init__.py +++ b/src/h3/api/basic_int/__init__.py @@ -1,1392 +1,9 @@ -# 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 +# flake8: noqa +from ._public_api import * from ..._h3shape import ( - H3Shape, - LatLngPoly, - LatLngMultiPoly, - geo_to_h3shape, - h3shape_to_geo, + H3MultiPoly, + H3Poly, + H3Shape, + 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 new file mode 100644 index 0000000..28002dd --- /dev/null +++ b/src/h3/api/basic_int/_binding.py @@ -0,0 +1,36 @@ +""" +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(cells): + it = list(cells) + + return _cy.iter_to_mv(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 deleted file mode 100644 index 51f4728..0000000 --- a/src/h3/api/basic_int/_convert.py +++ /dev/null @@ -1,17 +0,0 @@ -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 new file mode 100644 index 0000000..8e87df1 --- /dev/null +++ b/src/h3/api/basic_int/_public_api.py @@ -0,0 +1,63 @@ +"""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 as _b + + +is_valid_cell = _b.is_valid_cell +is_pentagon = _b.is_pentagon +is_valid_directed_edge = _b.is_valid_directed_edge +is_res_class_III = _b.is_res_class_III + +int_to_str = _b.int_to_str +str_to_int = _b.str_to_int + +cell_area = _b.cell_area +edge_length = _b.edge_length +great_circle_distance = _b.great_circle_distance +average_hexagon_area = _b.average_hexagon_area +average_hexagon_edge_length = _b.average_hexagon_edge_length + +latlng_to_cell = _b.latlng_to_cell +cell_to_latlng = _b.cell_to_latlng +cell_to_boundary = _b.cell_to_boundary +cell_to_local_ij = _b.cell_to_local_ij +local_ij_to_cell = _b.local_ij_to_cell + +grid_ring = _b.grid_ring +grid_disk = _b.grid_disk +grid_distance = _b.grid_distance +grid_path_cells = _b.grid_path_cells + +get_num_cells = _b.get_num_cells +get_pentagons = _b.get_pentagons +get_res0_cells = _b.get_res0_cells +get_resolution = _b.get_resolution +get_base_cell_number = _b.get_base_cell_number +get_icosahedron_faces = _b.get_icosahedron_faces + +cell_to_parent = _b.cell_to_parent +cell_to_children = _b.cell_to_children +cell_to_center_child = _b.cell_to_center_child +compact_cells = _b.compact_cells +uncompact_cells = _b.uncompact_cells + +h3shape_to_cells = _b.h3shape_to_cells +cells_to_h3shape = _b.cells_to_h3shape +cells_to_geo = _b.cells_to_geo +geo_to_cells = _b.geo_to_cells + +are_neighbor_cells = _b.are_neighbor_cells +cells_to_directed_edge = _b.cells_to_directed_edge +directed_edge_to_cells = _b.directed_edge_to_cells +origin_to_directed_edges = _b.origin_to_directed_edges +get_directed_edge_origin = _b.get_directed_edge_origin +get_directed_edge_destination = _b.get_directed_edge_destination +directed_edge_to_boundary = _b.directed_edge_to_boundary + +versions = _b.versions diff --git a/src/h3/api/basic_str/__init__.py b/src/h3/api/basic_str/__init__.py deleted file mode 120000 index 92056a2..0000000 --- a/src/h3/api/basic_str/__init__.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/__init__.py \ No newline at end of file diff --git a/src/h3/api/basic_str/__init__.py b/src/h3/api/basic_str/__init__.py new file mode 100644 index 0000000..a297461 --- /dev/null +++ b/src/h3/api/basic_str/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa +from ._public_api import * +from ..._h3shape import ( + H3MultiPoly, + H3Poly, + H3Shape, + geo_to_h3shape, + h3shape_to_geo, +) diff --git a/src/h3/api/basic_str/_binding.py b/src/h3/api/basic_str/_binding.py new file mode 100644 index 0000000..4ebd5fb --- /dev/null +++ b/src/h3/api/basic_str/_binding.py @@ -0,0 +1,43 @@ +""" +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(cells): + it = [_cy.str_to_int(h) for h in cells] + + return _cy.iter_to_mv(it) + + +def _out_unordered(mv): + # todo: should this be an (immutable) frozenset? + return set(_cy.int_to_str(h) for h in mv) + + +def _out_ordered(mv): + # todo: should this be an (immutable) tuple? + return list(_cy.int_to_str(h) for h in mv) + + +_binding = _API_FUNCTIONS( + _in_scalar = _cy.str_to_int, + _out_scalar = _cy.int_to_str, + _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 deleted file mode 100644 index a6c0ba0..0000000 --- a/src/h3/api/basic_str/_convert.py +++ /dev/null @@ -1,14 +0,0 @@ -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 new file mode 120000 index 0000000..c4a6ebd --- /dev/null +++ b/src/h3/api/basic_str/_public_api.py @@ -0,0 +1 @@ +../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 120000 index 92056a2..0000000 --- a/src/h3/api/memview_int/__init__.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/__init__.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 new file mode 100644 index 0000000..a297461 --- /dev/null +++ b/src/h3/api/memview_int/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa +from ._public_api import * +from ..._h3shape import ( + H3MultiPoly, + H3Poly, + H3Shape, + geo_to_h3shape, + h3shape_to_geo, +) diff --git a/src/h3/api/memview_int/_binding.py b/src/h3/api/memview_int/_binding.py new file mode 100644 index 0000000..96efb77 --- /dev/null +++ b/src/h3/api/memview_int/_binding.py @@ -0,0 +1,31 @@ +""" +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 deleted file mode 100644 index 2f054fd..0000000 --- a/src/h3/api/memview_int/_convert.py +++ /dev/null @@ -1,8 +0,0 @@ -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 new file mode 120000 index 0000000..c4a6ebd --- /dev/null +++ b/src/h3/api/memview_int/_public_api.py @@ -0,0 +1 @@ +../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 120000 index 92056a2..0000000 --- a/src/h3/api/numpy_int/__init__.py +++ /dev/null @@ -1 +0,0 @@ -../basic_int/__init__.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 new file mode 100644 index 0000000..a297461 --- /dev/null +++ b/src/h3/api/numpy_int/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa +from ._public_api import * +from ..._h3shape import ( + H3MultiPoly, + H3Poly, + H3Shape, + geo_to_h3shape, + h3shape_to_geo, +) diff --git a/src/h3/api/numpy_int/_binding.py b/src/h3/api/numpy_int/_binding.py new file mode 100644 index 0000000..c00275e --- /dev/null +++ b/src/h3/api/numpy_int/_binding.py @@ -0,0 +1,43 @@ +""" +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 deleted file mode 100644 index 6b293cc..0000000 --- a/src/h3/api/numpy_int/_convert.py +++ /dev/null @@ -1,15 +0,0 @@ -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 new file mode 120000 index 0000000..c4a6ebd --- /dev/null +++ b/src/h3/api/numpy_int/_public_api.py @@ -0,0 +1 @@ +../basic_int/_public_api.py \ No newline at end of file diff --git a/src/h3lib b/src/h3lib index 1b536c3..46a581c 160000 --- a/src/h3lib +++ b/src/h3lib @@ -1 +1 @@ -Subproject commit 1b536c34225191ba24a75a840f634d4a48c3b206 +Subproject commit 46a581c905b2747c861aa1683125276501f68a3b diff --git a/tests/test_cython/__init__.py b/tests/__init__.py similarity index 100% rename from tests/test_cython/__init__.py rename to tests/__init__.py diff --git a/tests/test_cython/cython_example.pyx b/tests/cython_example.pyx similarity index 100% rename from tests/test_cython/cython_example.pyx rename to tests/cython_example.pyx diff --git a/tests/test_lib/polyfill/test_h3.py b/tests/polyfill/test_h3.py similarity index 57% rename from tests/test_lib/polyfill/test_h3.py rename to tests/polyfill/test_h3.py index 6327cf8..c38ff5f 100644 --- a/tests/test_lib/polyfill/test_h3.py +++ b/tests/polyfill/test_h3.py @@ -1,8 +1,6 @@ import h3 import pytest -from .. import util as u - class MockGeoInterface: def __init__(self, dictionary): @@ -74,8 +72,8 @@ sf_hole2 = [ def test_geo_interface(): - poly = h3.LatLngPoly(sf_hole1) - mpoly = h3.LatLngMultiPoly(poly) + poly = h3.H3Poly(sf_hole1) + mpoly = h3.H3MultiPoly(poly) assert poly.__geo_interface__['type'] == 'Polygon' assert mpoly.__geo_interface__['type'] == 'MultiPolygon' @@ -88,18 +86,18 @@ def test_geo_interface(): def test_shape_repr(): - poly = h3.LatLngPoly(sf_hole1) - mpoly = h3.LatLngMultiPoly(poly) + poly = h3.H3Poly(sf_hole1) + mpoly = h3.H3MultiPoly(poly) assert ( - '' + '' == str(mpoly) == repr(mpoly) ) def test_polyfill(): - poly = h3.LatLngPoly(sf_7x7) + poly = h3.H3Poly(sf_7x7) out = h3.h3shape_to_cells(poly, res=9) assert len(out) == 1253 @@ -107,145 +105,25 @@ def test_polyfill(): 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) + poly = h3.H3Poly(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) - ) + foo = lambda x: h3.h3shape_to_cells(h3.H3Poly(x), 9) + # todo: foo = lambda x: h3.H3Poly(x).to_cells(9) + assert out == foo(sf_7x7) - foo(sf_hole1) def test_polyfill_with_two_holes(): - poly = h3.LatLngPoly(sf_7x7, sf_hole1, sf_hole2) + poly = h3.H3Poly(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)) - ) + foo = lambda x: h3.h3shape_to_cells(h3.H3Poly(x), 9) + assert out == foo(sf_7x7) - (foo(sf_hole1) | foo(sf_hole2)) def test_polyfill_geo_json_compliant(): @@ -262,21 +140,21 @@ def test_polyfill_geo_interface_compliant(): def test_poly_opens_loop(): loop = lnglat_closed() - poly = h3.LatLngPoly(loop) + poly = h3.H3Poly(loop) assert loop[0] == loop[-1] assert len(poly.outer) == len(loop) - 1 def test_geo_to_h3shape(): - shapes = [ + h3shapes = [ h3.geo_to_h3shape(get_mocked(lnglat_open())), h3.geo_to_h3shape(get_mocked(lnglat_closed())), - h3.LatLngPoly(latlng_open()), - h3.LatLngPoly(latlng_closed()), + h3.H3Poly(latlng_open()), + h3.H3Poly(latlng_closed()), ] - for s in shapes: + for s in h3shapes: assert len(h3.h3shape_to_cells(s, 8)) == 48 expected = { @@ -289,10 +167,10 @@ def test_geo_to_h3shape(): ),) } - for shape in shapes: + for shape in h3shapes: assert shape.__geo_interface__ == expected - mpolys = map(h3.LatLngMultiPoly, shapes) + mpolys = map(h3.H3MultiPoly, h3shapes) multi_expected = { 'type': 'MultiPolygon', @@ -309,30 +187,13 @@ def test_geo_to_h3shape(): def test_geo_to_h3shape_passthrough(): - poly = h3.LatLngPoly(latlng_open()) - mpoly = h3.LatLngMultiPoly(poly) + poly = h3.H3Poly(latlng_open()) + mpoly = h3.H3MultiPoly(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), @@ -368,7 +229,7 @@ def test_polyfill_down_under(): (-33.8556, 151.1979), ] - poly = h3.LatLngPoly(sydney) + poly = h3.H3Poly(sydney) out = h3.h3shape_to_cells(poly, 9) assert len(out) == 92 assert '89be0e34207ffff' in out @@ -384,7 +245,7 @@ def test_polyfill_far_east(): (41.925781, 142.864838), ] - poly = h3.LatLngPoly(geo) + poly = h3.H3Poly(geo) out = h3.h3shape_to_cells(poly, 9) assert len(out) == 18507 assert '892e18d16c3ffff' in out @@ -400,7 +261,7 @@ def test_polyfill_southern_tip(): (-55.416544, -67.642822), ] - poly = h3.LatLngPoly(geo) + poly = h3.H3Poly(geo) out = h3.h3shape_to_cells(poly, 9) assert len(out) == 223247 assert '89df4000003ffff' in out @@ -416,7 +277,7 @@ def test_polyfill_null_island(): (-3, -3), ] - poly = h3.LatLngPoly(geo) + poly = h3.H3Poly(geo) out = h3.h3shape_to_cells(poly, 4) assert len(out) == 345 assert '847421bffffffff' in out @@ -437,7 +298,7 @@ def test_cells_to_h3shape_single(): poly = mpoly[0] vertices = h3.cell_to_boundary(h) - expected_poly = h3.LatLngPoly(vertices) + expected_poly = h3.H3Poly(vertices) assert set(poly.outer) == set(expected_poly.outer) assert poly.holes == expected_poly.holes == () @@ -509,40 +370,10 @@ def test_cells_to_h3shape_2grid_disk(): def test_multipoly_checks(): with pytest.raises(ValueError): - h3.LatLngMultiPoly('foo') + h3.H3MultiPoly('foo') with pytest.raises(ValueError): - h3.LatLngMultiPoly(1) + h3.H3MultiPoly(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) + h3.H3MultiPoly([[(1, 2), (3, 4)]]) diff --git a/tests/test_lib/polyfill/test_polyfill.py b/tests/polyfill/test_polyfill.py similarity index 74% rename from tests/test_lib/polyfill/test_polyfill.py rename to tests/polyfill/test_polyfill.py index f70c639..7b059eb 100644 --- a/tests/test_lib/polyfill/test_polyfill.py +++ b/tests/polyfill/test_polyfill.py @@ -3,8 +3,6 @@ import pytest from h3 import H3ResDomainError -from .. import util as u - def get_us_box_coords(): @@ -71,16 +69,16 @@ def test_h3shape_to_cells(): '832badfffffffff' } - poly = h3.LatLngPoly(maine) + poly = h3.H3Poly(maine) out = h3.h3shape_to_cells(poly, 3) - assert u.same_set(out, expected) + assert out == expected def test_h3shape_to_cells2(): lnglat, _, _ = get_us_box_coords() - poly = h3.LatLngPoly(lnglat) + poly = h3.H3Poly(lnglat) out = h3.h3shape_to_cells(poly, 5) assert len(out) == 7063 @@ -97,29 +95,25 @@ def test_h3shape_to_cells_holes(): outer, hole1, hole2 = get_us_box_coords() assert 7063 == len( - h3.h3shape_to_cells(h3.LatLngPoly(outer), 5) + h3.h3shape_to_cells(h3.H3Poly(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_all = h3.h3shape_to_cells(h3.H3Poly(outer), res) + cells_holes = h3.h3shape_to_cells(h3.H3Poly(outer, hole1, hole2), res=res) - cells_1 = set(h3.h3shape_to_cells(h3.LatLngPoly(hole1), res)) - cells_2 = set(h3.h3shape_to_cells(h3.LatLngPoly(hole2), res)) + cells_1 = h3.h3shape_to_cells(h3.H3Poly(hole1), res) + cells_2 = h3.h3shape_to_cells(h3.H3Poly(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) - ) + assert cells_all == set.union(cells_holes, cells_1, cells_2) def test_resolution(): - poly = h3.LatLngPoly([]) + poly = h3.H3Poly([]) - assert h3.h3shape_to_cells(poly, 0) == [] - assert h3.h3shape_to_cells(poly, 15) == [] + assert h3.h3shape_to_cells(poly, 0) == set() + assert h3.h3shape_to_cells(poly, 15) == set() with pytest.raises(H3ResDomainError): h3.h3shape_to_cells(poly, -1) @@ -135,25 +129,21 @@ def test_invalid_polygon(): some `cdef` functions. """ with pytest.raises(TypeError): - h3.LatLngPoly([1, 2, 3]) + poly = h3.H3Poly([1, 2, 3]) + h3.h3shape_to_cells(poly, 4) with pytest.raises(ValueError): - h3.LatLngPoly([[1, 2, 3]]) + poly = h3.H3Poly([[1, 2, 3]]) + h3.h3shape_to_cells(poly, 4) 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' @@ -168,4 +158,4 @@ def test_cells_to_geo(): assert len(coord[0]) == 7 assert coord[0][0] == coord[0][-1] - assert h3.geo_to_cells(geo, res) == [h] + assert h3.geo_to_cells(geo, res) == {h} diff --git a/tests/test_lib/polyfill/test_polyfill_ordering.py b/tests/polyfill/test_polyfill_ordering.py similarity index 98% rename from tests/test_lib/polyfill/test_polyfill_ordering.py rename to tests/polyfill/test_polyfill_ordering.py index e0e43d8..0206138 100644 --- a/tests/test_lib/polyfill/test_polyfill_ordering.py +++ b/tests/polyfill/test_polyfill_ordering.py @@ -44,7 +44,7 @@ def input_permutations(geo, res=5): g = chain_toggle_map(reverse, g) for p in g: - poly = h3.LatLngPoly(*p) + poly = h3.H3Poly(*p) cells = h3.h3shape_to_cells(poly, res=res) yield cells diff --git a/tests/polyfill/test_polygon_class.py b/tests/polyfill/test_polygon_class.py new file mode 100644 index 0000000..721eb75 --- /dev/null +++ b/tests/polyfill/test_polygon_class.py @@ -0,0 +1,37 @@ +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_h3poly_len(): + cells = {'8928308280fffff'} + + poly = h3.cells_to_h3shape(cells, tight=True) + + with pytest.raises(NotImplementedError): + len(poly) diff --git a/tests/polyfill/test_to_multipoly.py b/tests/polyfill/test_to_multipoly.py new file mode 100644 index 0000000..e613d4d --- /dev/null +++ b/tests/polyfill/test_to_multipoly.py @@ -0,0 +1,43 @@ +import h3 + + +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.H3Poly(poly.outer, *poly.holes) + out = h3.h3shape_to_cells(poly2, 9) + + assert 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.H3Poly(poly.outer, *poly.holes) + out = h3.h3shape_to_cells(poly2, 9) + + assert 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 = [ + h3.h3shape_to_cells(poly, 9) + for poly in mpoly + ] + + assert set.union(*out) == cells + assert set(map(len, out)) == {1, 12} diff --git a/tests/readme.md b/tests/readme.md deleted file mode 100644 index 0aba346..0000000 --- a/tests/readme.md +++ /dev/null @@ -1,18 +0,0 @@ -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 new file mode 100644 index 0000000..9bcb60b --- /dev/null +++ b/tests/test_api_bindings_match.py @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000..99452fe --- /dev/null +++ b/tests/test_basic_int.py @@ -0,0 +1,48 @@ +import h3.api.basic_int as h3 + + +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 out == expected + + +def test_compact_cells(): + h = 617700169958293503 + cells = h3.cell_to_children(h) + + assert h3.compact_cells(cells) == {h} + + +def test_get_icosahedron_faces(): + h = 577832942814887935 + expected = {2, 3, 7, 8, 12} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579873636396040191 + expected = {13} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579768083279773695 + expected = {16, 15} + out = h3.get_icosahedron_faces(h) + assert out == expected diff --git a/tests/test_basic_str.py b/tests/test_basic_str.py new file mode 100644 index 0000000..eaae35b --- /dev/null +++ b/tests/test_basic_str.py @@ -0,0 +1,21 @@ +import h3.api.basic_str as h3 + + +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 out == expected diff --git a/tests/test_lib/test_cells_and_edges.py b/tests/test_cells_and_edges.py similarity index 69% rename from tests/test_lib/test_cells_and_edges.py rename to tests/test_cells_and_edges.py index 65d9d13..c82c6ab 100644 --- a/tests/test_lib/test_cells_and_edges.py +++ b/tests/test_cells_and_edges.py @@ -8,14 +8,17 @@ from h3 import ( H3ResMismatchError, H3CellInvalidError, H3NotNeighborsError, - H3DigitDomainError, - H3BaseCellDomainError, - H3DeletedDigitError, - H3IndexInvalidError, ) -from . import util as u +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(): @@ -41,7 +44,7 @@ def test3(): ) out = h3.cell_to_boundary('8928308280fffff') - assert u.approx2(out, expected) + assert approx2(out, expected) def test_grid_disk_distance(): @@ -55,7 +58,7 @@ def test_grid_ring_distance(): def test5(): - expected = [ + expected = { '89283082873ffff', '89283082877ffff', '8928308283bffff', @@ -63,30 +66,30 @@ def test5(): '8928308280bffff', '8928308280fffff', '89283082803ffff' - ] + } out = h3.grid_disk('8928308280fffff', 1) - assert u.same_set(out, expected) + assert out == expected def test6(): - expected = ['8928308280fffff'] + expected = {'8928308280fffff'} out = h3.grid_ring('8928308280fffff', 0) - assert u.same_set(out, expected) + assert out == expected def test7(): - expected = [ + expected = { '89283082803ffff', '89283082807ffff', '8928308280bffff', '8928308283bffff', '89283082873ffff', '89283082877ffff' - ] + } out = h3.grid_ring('8928308280fffff', 1) - assert u.same_set(out, expected) + assert out == expected def test8(): @@ -131,7 +134,9 @@ def test_parent_err(): except Exception as e: msg = str(e) - expected = f'Invalid parent resolution -1 for cell 0x{h}.' + # todo: revist this weird formatting stuff + expected = 'Invalid parent resolution -1 for cell {}.' + expected = expected.format(hex(h3.str_to_int(h))) assert msg == expected @@ -144,10 +149,10 @@ def test_children(): # same resolution is set of just cell itself out = h3.cell_to_children(h, 9) - assert out == [h] + assert out == {h} # one below should give children - expected = [ + expected = { '8a28308280c7fff', '8a28308280cffff', '8a28308280d7fff', @@ -155,9 +160,9 @@ def test_children(): '8a28308280e7fff', '8a28308280effff', '8a28308280f7fff' - ] + } out = h3.cell_to_children(h, 10) - assert u.same_set(out, expected) + assert out == expected # finest resolution cell should return error for children h = '8f04ccb2c45e225' @@ -210,7 +215,7 @@ def test_distance_error(): def get_maine_cells(): # lat/lngs for State of Maine - poly = h3.LatLngPoly([ + poly = h3.H3Poly([ (45.137451890638886, -67.13734351262877), (44.8097, -66.96466), (44.3252, -68.03252), @@ -237,7 +242,7 @@ def get_maine_cells(): 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 + 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 @@ -246,13 +251,13 @@ def test_compact_cells(): cells_uncomp, cells_comp, _ = get_maine_cells() out = h3.compact_cells(cells_uncomp) - assert u.same_set(out, cells_comp) + assert 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) + assert out == cells_uncomp def test_get_num_cells(): @@ -291,11 +296,11 @@ def test_average_hexagon_area(): def test_average_hexagon_edge_length(): expected_in_km = { - 0: 1281.256011, - 1: 483.0568391, - 2: 182.5129565, - 9: 0.200786148, - 15: 0.000584169, + 0: 1107.712591000, + 1: 418.676005500, + 2: 158.244655800, + 9: 0.174375668, + 15: 0.000509713, } out = { @@ -334,7 +339,7 @@ def test_origin_to_directed_edges(): } neighbors = h3.grid_ring(h, 1) - assert u.same_set(neighbors, destinations) + assert neighbors == destinations def test_edge_boundary(): @@ -454,12 +459,8 @@ def test_versions(): 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] + # of X.Y.Z, X and Y must match + assert v_c.release[:2] == v_p.release[:2] def test_str_int_convert(): @@ -480,18 +481,10 @@ def test_edge_is_valid_fail(): 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 = [ + expected = { '8009fffffffffff', '801dfffffffffff', '8031fffffffffff', @@ -504,13 +497,13 @@ def test_get_pentagons(): '80c3fffffffffff', '80d7fffffffffff', '80ebfffffffffff', - ] + } - assert u.same_set(out, expected) + assert out == expected out = h3.get_pentagons(5) - expected = [ + expected = { '85080003fffffff', '851c0003fffffff', '85300003fffffff', @@ -523,9 +516,9 @@ def test_get_pentagons(): '85c20003fffffff', '85d60003fffffff', '85ea0003fffffff', - ] + } - assert u.same_set(out, expected) + assert out == expected for i in range(16): assert len(h3.get_pentagons(i)) == 12 @@ -548,7 +541,7 @@ def test_get_res0_cells(): # subset pentagons = h3.get_pentagons(0) - assert set(pentagons) < set(out) + assert pentagons < out # all valid assert all(map(h3.is_valid_cell, out)) @@ -565,7 +558,24 @@ def test_get_res0_cells(): '8003fffffffffff', '8005fffffffffff', } - assert sub < set(out) + assert sub < out + + +def test_get_icosahedron_faces(): + h = '804dfffffffffff' + expected = {2, 3, 7, 8, 12} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = '80c1fffffffffff' + expected = {13} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = '80bbfffffffffff' + expected = {16, 15} + out = h3.get_icosahedron_faces(h) + assert out == expected def test_to_local_ij_error(): @@ -603,7 +613,7 @@ def test_from_local_ij_error(): for i, j in goodies } - assert u.same_set(out, nb) + assert out == nb def test_to_local_ij_self(): @@ -611,163 +621,3 @@ def test_to_local_ij_self(): 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_apis/test_collection_inputs.py b/tests/test_collection_inputs.py similarity index 93% rename from tests/test_lib/test_apis/test_collection_inputs.py rename to tests/test_collection_inputs.py index 5f826a1..92a8ba5 100644 --- a/tests/test_lib/test_apis/test_collection_inputs.py +++ b/tests/test_collection_inputs.py @@ -22,7 +22,7 @@ def test_set(): h = 614553222213795839 - assert basic_int.compact_cells(ints) == [h] + assert basic_int.compact_cells(ints) == {h} with pytest.raises(TypeError): # numpy can't convert from a set @@ -46,7 +46,7 @@ def test_list(): h = 614553222213795839 - assert basic_int.compact_cells(ints) == [h] + assert basic_int.compact_cells(ints) == {h} # numpy can convert from a list OK # (numpy knows to convert it to uint64) @@ -74,7 +74,7 @@ def test_np_array(): h = 614553222213795839 - assert basic_int.compact_cells(ints) == [h] + assert basic_int.compact_cells(ints) == {h} assert numpy_int.compact_cells(ints) == np.array([h], dtype='uint64') assert numpy_int.compact_cells(ints).dtype == np.dtype('uint64') @@ -99,7 +99,7 @@ def test_list_to_array(): h = 614553222213795839 - assert basic_int.compact_cells(ints) == [h] + assert basic_int.compact_cells(ints) == {h} assert numpy_int.compact_cells(ints) == np.array([h], dtype='uint64') with pytest.raises(ValueError): @@ -128,7 +128,7 @@ def test_iterator(): h = 614553222213795839 ints = foo() - assert basic_int.compact_cells(ints) == [h] + assert basic_int.compact_cells(ints) == {h} ints = foo() with pytest.raises(TypeError): diff --git a/tests/test_cython/test_cython.py b/tests/test_cython.py similarity index 83% rename from tests/test_cython/test_cython.py rename to tests/test_cython.py index 1833de3..89aa064 100644 --- a/tests/test_cython/test_cython.py +++ b/tests/test_cython.py @@ -12,7 +12,7 @@ np.random.seed(0) def test_cython_api(): if latlng_to_cell_vect is None: - print('Not running Cython test because cython example was not compiled') + 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') + out = np.zeros(len(lats), dtype="uint64") latlng_to_cell_vect(lats, lngs, res, out) assert out[0] == 617284541015654399 diff --git a/tests/test_lib/test_error_codes.py b/tests/test_error_codes.py similarity index 65% rename from tests/test_lib/test_error_codes.py rename to tests/test_error_codes.py index 4ae1d37..9961178 100644 --- a/tests/test_lib/test_error_codes.py +++ b/tests/test_error_codes.py @@ -1,10 +1,6 @@ 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? @@ -16,30 +12,24 @@ h3_exceptions = { h3.H3GridNavigationError: None, h3.H3MemoryError: None, h3.H3ValueError: None, + + h3.H3FailedError: 1, + h3.H3DomainError: 2, + h3.H3LatLngDomainError: 3, + h3.H3ResDomainError: 4, + h3.H3CellInvalidError: 5, + h3.H3DirEdgeInvalidError: 6, + h3.H3UndirEdgeInvalidError: 7, + h3.H3VertexInvalidError: 8, + h3.H3PentagonError: 9, + h3.H3DuplicateInputError: 10, + h3.H3NotNeighborsError: 11, + h3.H3ResMismatchError: 12, + h3.H3MemoryAllocError: 13, + h3.H3MemoryBoundsError: 14, + h3.H3OptionInvalidError: 15, } -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(): """ diff --git a/tests/test_lib/test_h3.py b/tests/test_h3.py similarity index 67% rename from tests/test_lib/test_h3.py rename to tests/test_h3.py index 760c3fa..94a9a94 100644 --- a/tests/test_lib/test_h3.py +++ b/tests/test_h3.py @@ -3,12 +3,6 @@ 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') @@ -83,7 +77,7 @@ def test_grid_disk(): '8928308283bffff', } - assert u.same_set(out, expected) + assert out == expected def test_grid_disk2(): @@ -114,7 +108,7 @@ def test_grid_disk2(): '8928308280bffff', } - assert u.same_set(out, expected) + assert out == expected def test_grid_disk_pentagon(): @@ -132,7 +126,7 @@ def test_grid_disk_pentagon(): '821c37fffffffff', } - assert u.same_set(out, expected) + assert out == expected def test_grid_ring(): @@ -147,11 +141,8 @@ def test_grid_ring(): '8928308283bffff', } - assert u.same_set(out, expected) - assert u.same_set( - out, - set(h3.grid_disk(h, 1)) - set(h3.grid_disk(h, 0)) - ) + assert out == expected + assert out == h3.grid_disk(h, 1) - h3.grid_disk(h, 0) def test_grid_ring2(): @@ -173,11 +164,8 @@ def test_grid_ring2(): '89283082867ffff', } - assert u.same_set(out, expected) - assert u.same_set( - out, - set(h3.grid_disk(h, 2)) - set(h3.grid_disk(h, 1)) - ) + assert out == expected + assert out == h3.grid_disk(h, 2) - h3.grid_disk(h, 1) def test_grid_ring_pentagon(): @@ -192,7 +180,7 @@ def test_grid_ring_pentagon(): '821c37fffffffff', } - assert u.same_set(out, expected) + assert out == expected def test_compact_and_uncompact_cells(): @@ -205,7 +193,7 @@ def test_compact_and_uncompact_cells(): (37.8151571999998453, -122.4798767000009008), ] - poly = h3.LatLngPoly(sf_7x7) + poly = h3.H3Poly(sf_7x7) cells = h3.h3shape_to_cells(poly, 9) compact_cells = h3.compact_cells(cells) @@ -214,12 +202,12 @@ def test_compact_and_uncompact_cells(): uncompact_cells = h3.uncompact_cells(compact_cells, 9) assert len(uncompact_cells) == 1253 - assert u.same_set(uncompact_cells, cells) + assert uncompact_cells == cells def test_compact_cells_and_uncompact_cells_nothing(): - assert h3.compact_cells([]) == [] - assert h3.uncompact_cells([], 9) == [] + assert h3.compact_cells([]) == set() + assert h3.uncompact_cells([], 9) == set() def test_uncompact_cells_error(): @@ -391,121 +379,3 @@ def test_grid_path_cells(): 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_lib/test_length_area.py b/tests/test_length_area.py similarity index 77% rename from tests/test_lib/test_length_area.py rename to tests/test_length_area.py index ca38257..8851a4b 100644 --- a/tests/test_lib/test_length_area.py +++ b/tests/test_length_area.py @@ -1,7 +1,15 @@ import h3 import pytest -from . import util as u + +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 cell_perimiter1(h, unit='km'): @@ -57,7 +65,7 @@ def test_areas_at_00(): for r in range(16) ] - assert u.approx2(out, areas_km2) + assert approx2(out, areas_km2) areas_rads2 = [ 6.312389871006786335e-02, @@ -83,31 +91,7 @@ def test_areas_at_00(): for r in range(16) ] - 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) + assert approx2(out, areas_rads2) def test_bad_units(): diff --git a/tests/test_lib/__init__.py b/tests/test_lib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_lib/polyfill/__init__.py b/tests/test_lib/polyfill/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_lib/polyfill/test_polygon_class.py b/tests/test_lib/polyfill/test_polygon_class.py deleted file mode 100644 index a3639b6..0000000 --- a/tests/test_lib/polyfill/test_polygon_class.py +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index 80c5a75..0000000 --- a/tests/test_lib/polyfill/test_to_multipoly.py +++ /dev/null @@ -1,360 +0,0 @@ -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 deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_lib/test_apis/test_api_bindings_match.py b/tests/test_lib/test_apis/test_api_bindings_match.py deleted file mode 100644 index ccc2a9c..0000000 --- a/tests/test_lib/test_apis/test_api_bindings_match.py +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 3f3b14c..0000000 --- a/tests/test_lib/test_apis/test_basic_int.py +++ /dev/null @@ -1,56 +0,0 @@ -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 deleted file mode 100644 index fccc164..0000000 --- a/tests/test_lib/test_apis/test_basic_str.py +++ /dev/null @@ -1,43 +0,0 @@ -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_lib/test_apis/test_ico_faces.py b/tests/test_lib/test_apis/test_ico_faces.py deleted file mode 100644 index 6466ab0..0000000 --- a/tests/test_lib/test_apis/test_ico_faces.py +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index f608f54..0000000 --- a/tests/test_lib/test_apis/test_memview_int.py +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 6bcd0b6..0000000 --- a/tests/test_lib/test_apis/test_numpy_int.py +++ /dev/null @@ -1,66 +0,0 @@ -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_geojson_containers.py b/tests/test_lib/test_geojson_containers.py deleted file mode 100644 index a890c27..0000000 --- a/tests/test_lib/test_geojson_containers.py +++ /dev/null @@ -1,62 +0,0 @@ -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/util.py b/tests/test_lib/util.py deleted file mode 100644 index f6d3177..0000000 --- a/tests/test_lib/util.py +++ /dev/null @@ -1,21 +0,0 @@ -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 new file mode 100644 index 0000000..0e7e56e --- /dev/null +++ b/tests/test_memview_int.py @@ -0,0 +1,42 @@ +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_get_icosahedron_faces(): + h = 577832942814887935 + expected = {2, 3, 7, 8, 12} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579873636396040191 + expected = {13} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579768083279773695 + expected = {16, 15} + out = h3.get_icosahedron_faces(h) + assert out == expected diff --git a/tests/test_numpy_int.py b/tests/test_numpy_int.py new file mode 100644 index 0000000..c565518 --- /dev/null +++ b/tests/test_numpy_int.py @@ -0,0 +1,48 @@ +import h3.api.numpy_int as h3 +import numpy as np # only run this test suite if numpy is installed + + +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 set(out) == expected + + +def test_compact_cells(): + h = 617700169958293503 + cells = h3.cell_to_children(h) + assert isinstance(cells, np.ndarray) + + assert set(h3.compact_cells(cells)) == {h} + + +def test_get_icosahedron_faces(): + h = 577832942814887935 + expected = {2, 3, 7, 8, 12} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579873636396040191 + expected = {13} + out = h3.get_icosahedron_faces(h) + assert out == expected + + h = 579768083279773695 + expected = {16, 15} + out = h3.get_icosahedron_faces(h) + assert out == expected