h3-py Documentation

repository·master·Indexed 21 days ago

https://github.com/uber/h3-py

Python bindings for Uber's H3 hierarchical hexagonal geospatial indexing system. h3-py enables complex geospatial indexing, grid manipulation, and spatial analysis using hexagonal cells. It provides multiple API variations (basic_str, basic_int, numpy_int, and memview_int) to balance human readability with high-performance bulk computations. Key features include converting latitude/longitude to H3 cells, navigating hierarchical and grid relationships, and a polygon interface for converting geographic shapes to H3 cells.

Tokens
7.1K
Snippets
21
Records
43
Agent score
76%

What's inside h3-py

  1. Choose the right H3 API based on performance and convenience

    master

    The h3-py library provides several APIs that share the same functions but differ in how they represent H3 indices and collections. Choosing the right API allows you to balance Pythonic convenience with computational speed.

    API Comparison Summary

    APIIndex TypeCollection TypeBest For
    h3.api.basic_str (Default)Python str (hexadecimal)list, setHuman readability and standard Python workflows.
    h3.api.basic_intPython intlist, setInteger-based math without string conversion overhead.
    h3.api.numpy_intnumpy.uint64numpy.ndarrayHigh-performance, memory-efficient bulk computations.
    h3.api.memview_intuint64memoryviewHigh performance without requiring a numpy dependency.

    Conversion Pattern

    A common high-performance pattern is to perform heavy computations using h3.api.numpy_int or h3.api.memview_int, and then convert the final results to strings for reporting or inspection using h3.int_to_str().

  2. Understand h3-py API variations

    master
    The h3-py library provides multiple APIs that share the same set of functions. The primary difference between these APIs is the input and output formats they accept (e.g., handling coordinates as tuples vs. individual arguments, or returning hex strings vs. integers). Refer to the API comparison page to determine which API format best suits your data structures.
  3. Use the Polygon interface for geospatial shapes

    master

    The polygon interface allows you to represent (multi)polygons of lat/lng points and convert them to/from H3 cells.

    Critical Coordinate Order Warning:

    • h3-py polygon objects expect coordinates in lat/lng order.
    • This is the reverse of the standard __geo_interface__ protocol (used by GeoPandas), which uses lng/lat order. Ensure you swap coordinates when integrating with other geospatial libraries.

    Polygon Objects

    • LatLngPoly: Represents a single polygon.
    • LatLngMultiPoly: Represents multiple polygons.
    • H3Shape: A generic shape object.

    Conversion Functions

    • geo_to_cells(polygon, res): Converts a geographic polygon to a set of H3 cells.
    • cells_to_geo(cells): Converts H3 cells to a geographic shape.
    • h3shape_to_cells(shape): Converts an H3Shape to cells.
  4. Update the H3 submodule

    master

    The h3-py project relies on an h3lib submodule located in src/h3lib. To update this submodule to the latest master branch or a specific version tag, follow these steps:

    Update to latest master

    cd src/h3lib
    git checkout master
    git pull
    cd ..
    git add h3lib
    git commit ...

    Update to a specific version tag

    cd src/h3lib
    git checkout v3.7.1  # Replace with your desired version tag
    cd ..
    git add h3lib
    git commit ...
    cd src/h3lib
    git checkout v3.7.1
    cd ..
    git add h3lib
    git commit ...
  5. Install h3-py for development

    master

    The h3-py repository uses just to manage common development tasks. To set up a local development environment, clone the repository with submodules included and use the just commands for linting and testing.

    Prerequisites

    Setup Steps

    1. Clone the repository with submodules:
      git clone --recurse-submodules git@github.com:uber/h3-py.git
    2. Navigate to the directory:
      cd h3-py
    3. Run development commands:
      • just lint: Run linters.
      • just test: Run standard tests.
      • just test-cython: Run Cython-specific tests.

    Documentation

    • just docs: Build the documentation.
    • just view: View the built documentation.
    git clone --recurse-submodules git@github.com:uber/h3-py.git
    cd h3-py
    just lint
    just test
    just test-cython
  6. Reset the H3 submodule

    master

    If you are switching between h3-py branches that use different versions of the h3lib submodule, you may need to reset the submodule to ensure the correct files are present.

    Run the following commands from the repository root:

    git submodule deinit -f .
    git submodule update --init
  7. Release a new version of h3-py

    master

    To release a new version of h3-py, follow this workflow:

    1. Update Documentation: Update CHANGELOG.md with changes since the last release.
    2. Update Version: Update the h3-py version in pyproject.toml.
    3. Update C Library (if applicable): If updating the C h3lib version, update the version badge in the README.md.
    4. PR Process: Create a Pull Request, obtain reviews, and merge the changes.
    5. GitHub Release:
      • Go to GitHub Releases and select "Draft a new release".
      • Set the tag version (e.g., v3.7.2). You can also use git tag v3.7.2 && git push origin --tags.
      • Add the updated CHANGELOG.md text to the release notes.
      • Publish the release.
    6. Automated Build: GitHub Actions will trigger on the release event to build and upload wheels to PyPI.
  8. Install h3-py via pip or conda

    master

    You can install the H3 Python bindings using either pip from PyPI or conda from the conda-forge channel.

    # Using pip
    pip install h3
    
    # Using conda
    conda config --add channels conda-forge
    conda install h3-py
  9. How H3Shape, Geo objects, and H3 cells relate

    master

    The h3-py library provides a bridge between standard geospatial Python objects and H3 cells through the H3Shape abstraction.

    • Geo objects: Any Python object implementing __geo_interface__ (e.g., Shapely Polygon, MultiPolygon).
    • H3Shape: The internal h3-py representation (LatLngPoly or LatLngMultiPoly).
    • H3 cells: The discrete hexagonal identifiers.

    Mapping Functions

    TaskFrom Geo ObjectVia H3ShapeTo H3 Cells
    Directh3.geo_to_cells(geo, res)
    Via Shapeh3.geo_to_h3shape(geo)$\rightarrow$ H3Shapeh3.h3shape_to_cells(shape, res)
    Reverseh3.cells_to_geo(cells)$\leftarrow$ h3.cells_to_h3shape(cells)
  10. Understand the LatLngPoly loopcode format

    master

    The loopcode property provides a compact string representation of the polygon's structure, showing the number of points in the outer loop and each hole.

    Format: [outer_count/(hole1_count, hole2_count, ...)]

    Examples:

    • [15]: Outer loop of 15 points, no holes.
    • [382/(18, 6, 6)]: Outer loop of 382 points, with three holes containing 18, 6, and 6 points respectively.
  11. Interfacing with GeoPandas and other Geo-libraries

    master

    The h3-py library is compatible with any Python object that implements the __geo_interface__ protocol (e.g., Shapely geometries used in GeoPandas).

    Conversion Workflow

    1. Geo $\rightarrow$ Cells: Use h3.geo_to_cells(geo, res).
    2. Cells $\rightarrow$ Geo: Use h3.cells_to_h3shape(cells) to get an H3Shape, which can then be assigned to a GeoPandas geometry column. Because H3Shape implements __geo_interface__, GeoPandas will automatically treat it as a valid geometry.

    Critical Requirement: Coordinate Reference Systems (CRS)

    h3-py functions expect coordinates in latitude-longitude (degrees). If your data is in a different CRS (like EPSG:2263/feet), you must convert it to a compatible CRS (like EPSG:4326/WGS84) before calling H3 functions, otherwise results will be incorrect.

    # Correct workflow with GeoPandas
    # 1. Convert to WGS84
    df = df.to_crs(epsg=4326)
    
    # 2. Convert geometries to cells
    cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8))
    
    # 3. Convert cells back to H3Shapes for GeoPandas compatibility
    shape_column = cell_column.apply(h3.cells_to_h3shape)
    
    # 4. Assign back to geometry
    df.geometry = shape_column