or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-operations.mdcell-hierarchy.mdcore-cell-operations.mddirected-edges.mdgrid-navigation.mdindex.mdmeasurements.mdpolygon-operations.md
tile.json

tessl/pypi-h3

Python bindings for H3, a hierarchical hexagonal geospatial indexing system

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/h3@4.3.x

To install, run

npx @tessl/cli install tessl/pypi-h3@4.3.0

index.mddocs/

H3

Python bindings for H3, a hierarchical hexagonal geospatial indexing system. H3 partitions the world into hexagonal cells at multiple resolution levels, enabling efficient spatial indexing and analysis for location-based applications.

Package Information

  • Package Name: h3
  • Language: Python
  • Installation: pip install h3

Core Imports

import h3

Alternative APIs with different data formats:

import h3.api.basic_int as h3    # Integer H3 indices
import h3.api.numpy_int as h3    # NumPy optimization
import h3.api.memview_int as h3   # Memory view operations

For polygon operations:

from h3 import LatLngPoly, LatLngMultiPoly

Basic Usage

import h3

# Convert coordinates to H3 cell
cell = h3.latlng_to_cell(37.7749, -122.4194, resolution=9)
print(cell)  # '89283082e73ffff'

# Get cell center and boundary
lat, lng = h3.cell_to_latlng(cell)
boundary = h3.cell_to_boundary(cell)

# Find neighboring cells
neighbors = h3.grid_disk(cell, k=1)
print(f"Cell and neighbors: {len(neighbors)} cells")

# Polygon to cells conversion
from h3 import LatLngPoly
polygon = LatLngPoly([
    (37.68, -122.54), (37.68, -122.34), 
    (37.82, -122.34), (37.82, -122.54)
])
cells = h3.h3shape_to_cells(polygon, resolution=6)

Architecture

H3 organizes the world into hexagonal cells across 16 resolution levels (0-15):

  • Resolution 0: ~4,250 km edge length (122 base cells)
  • Resolution 15: ~0.5 m edge length (finest detail)
  • Hierarchy: Each cell contains ~7 children at the next finer resolution
  • APIs: Multiple interfaces (basic_str, basic_int, numpy_int, memview_int) with identical functions

Capabilities

Core Cell Operations

Essential cell creation, validation, and format conversion functions.

def latlng_to_cell(lat: float, lng: float, res: int) -> str:
    """Convert lat/lng to H3 cell at specified resolution."""

def is_valid_cell(h: str) -> bool:
    """Check if H3 cell identifier is valid."""

def cell_to_latlng(h: str) -> tuple[float, float]:
    """Get center coordinates of H3 cell."""

def cell_to_boundary(h: str) -> tuple[tuple[float, float], ...]:
    """Get boundary vertices of H3 cell."""

def get_resolution(h: str) -> int:
    """Get resolution of H3 cell."""

def str_to_int(h: str) -> int:
    """Convert hex string to 64-bit integer."""

def int_to_str(x: int) -> str:
    """Convert 64-bit integer to hex string."""

def get_num_cells(res: int) -> int:
    """Get total number of cells at resolution."""

def versions() -> dict[str, str]:
    """Get Python and C library versions."""

def is_pentagon(h: str) -> bool:
    """Check if cell is pentagon."""

def get_base_cell_number(h: str) -> int:
    """Get base cell number (0-121)."""

def is_res_class_III(h: str) -> bool:
    """Check if cell has Class III orientation."""

Core Cell Operations

Grid Navigation

Functions for navigating the hexagonal grid and finding neighboring cells.

def grid_distance(h1: str, h2: str) -> int:
    """Calculate grid distance between cells."""

def grid_disk(h: str, k: int = 1) -> list[str]:
    """Get cells within distance k (filled disk)."""

def grid_ring(h: str, k: int = 1) -> list[str]:
    """Get cells at exactly distance k (hollow ring)."""

def grid_path_cells(start: str, end: str) -> list[str]:
    """Find path between cells."""

def are_neighbor_cells(h1: str, h2: str) -> bool:
    """Check if cells are neighbors."""

Grid Navigation

Cell Hierarchy

Operations for working with H3's multi-resolution hierarchy.

def cell_to_parent(h: str, res: int = None) -> str:
    """Get parent cell at coarser resolution."""

def cell_to_children(h: str, res: int = None) -> list[str]:
    """Get child cells at finer resolution."""

def cell_to_children_size(h: str, res: int = None) -> int:
    """Get count of child cells."""

def cell_to_child_pos(child: str, res_parent: int) -> int:
    """Get child position index."""

def child_pos_to_cell(parent: str, res_child: int, child_pos: int) -> str:
    """Get child from position index."""

def cell_to_center_child(h: str, res: int = None) -> str:
    """Get center child at finer resolution."""

def compact_cells(cells: list[str]) -> list[str]:
    """Compact cells by combining children into parents."""

def uncompact_cells(cells: list[str], res: int) -> list[str]:
    """Expand cells to uniform resolution."""

Cell Hierarchy

Polygon Operations

Convert between H3 cells and geographic polygons.

def h3shape_to_cells(h3shape: H3Shape, res: int) -> list[str]:
    """Convert shape to H3 cells."""

def polygon_to_cells(h3shape: H3Shape, res: int) -> list[str]:
    """Alias for h3shape_to_cells."""

def h3shape_to_cells_experimental(h3shape: H3Shape, res: int, contain: str = 'center') -> list[str]:
    """Experimental shape to cells with containment modes."""

def polygon_to_cells_experimental(h3shape: H3Shape, res: int, contain: str = 'center') -> list[str]:
    """Experimental alias for h3shape_to_cells_experimental."""

def cells_to_h3shape(cells: list[str], tight: bool = True) -> H3Shape:
    """Convert cells to shape."""

def geo_to_cells(geo: dict, res: int) -> list[str]:
    """Convert GeoJSON to cells."""

def cells_to_geo(cells: list[str], tight: bool = True) -> dict:
    """Convert cells to GeoJSON."""

Polygon Operations

Directed Edges

Operations for working with edges between adjacent cells.

def cells_to_directed_edge(origin: str, destination: str) -> str:
    """Create directed edge between cells."""

def is_valid_directed_edge(edge: str) -> bool:
    """Check if edge identifier is valid."""

def directed_edge_to_cells(e: str) -> tuple[str, str]:
    """Get origin and destination from edge."""

def get_directed_edge_origin(e: str) -> str:
    """Get origin cell from edge."""

def get_directed_edge_destination(e: str) -> str:
    """Get destination cell from edge."""

def origin_to_directed_edges(origin: str) -> list[str]:
    """Get all edges from origin cell."""

def directed_edge_to_boundary(edge: str) -> tuple[tuple[float, float], ...]:
    """Get boundary points of edge."""

Directed Edges

Measurements

Calculate areas, lengths, and distances with multiple unit support.

def cell_area(h: str, unit: str = 'km^2') -> float:
    """Calculate area of specific cell."""

def edge_length(e: str, unit: str = 'km') -> float:
    """Calculate length of specific edge."""

def great_circle_distance(latlng1: tuple[float, float], latlng2: tuple[float, float], unit: str = 'km') -> float:
    """Calculate spherical distance between points."""

def average_hexagon_area(res: int, unit: str = 'km^2') -> float:
    """Get average hexagon area at resolution."""

def average_hexagon_edge_length(res: int, unit: str = 'km') -> float:
    """Get average hexagon edge length at resolution."""

Measurements

Advanced Operations

Specialized functions including local coordinates, vertices, and system introspection.

def cell_to_local_ij(origin: str, h: str) -> tuple[int, int]:
    """Convert cell to local (i,j) coordinates."""

def local_ij_to_cell(origin: str, i: int, j: int) -> str:
    """Convert local coordinates to cell."""

def cell_to_vertex(h: str, vertex_num: int) -> str:
    """Get specific vertex of cell."""

def cell_to_vertexes(h: str) -> list[str]:
    """Get all vertices of cell."""

def vertex_to_latlng(v: str) -> tuple[float, float]:
    """Get coordinates of vertex."""

def is_valid_vertex(v: str) -> bool:
    """Check if vertex identifier is valid."""

def get_pentagons(res: int) -> list[str]:
    """Get all pentagon cells at resolution."""

def get_res0_cells() -> list[str]:
    """Get all base cells (resolution 0)."""

def get_icosahedron_faces(h: str) -> set[int]:
    """Get icosahedron faces intersecting cell."""

Advanced Operations

H3Shape Classes

class H3Shape:
    """Abstract base class for geographic shapes."""

class LatLngPoly(H3Shape):
    """Polygon with optional holes."""
    def __init__(self, outer: list[tuple[float, float]], *holes: list[tuple[float, float]]):
        """Create polygon from outer boundary and optional holes."""
    
    @property
    def outer(self) -> tuple[tuple[float, float], ...]
    
    @property  
    def holes(self) -> tuple[tuple[tuple[float, float], ...], ...]

class LatLngMultiPoly(H3Shape):
    """Collection of multiple polygons."""
    def __init__(self, *polys: LatLngPoly):
        """Create multipolygon from LatLngPoly objects."""
    
    @property
    def polys(self) -> tuple[LatLngPoly, ...]

Shape Utilities

def geo_to_h3shape(geo: dict) -> H3Shape:
    """Convert GeoJSON to H3Shape."""

def h3shape_to_geo(h3shape: H3Shape) -> dict:
    """Convert H3Shape to GeoJSON."""

Error Handling

class H3BaseException(Exception):
    """Base class for all H3 exceptions."""

class H3ValueError(H3BaseException):
    """Invalid input values."""

class H3DomainError(H3BaseException):
    """Input outside valid domain."""

class H3LatLngDomainError(H3DomainError):
    """Latitude/longitude outside valid range."""

class H3ResDomainError(H3DomainError):
    """Resolution outside valid range (0-15)."""

class H3CellInvalidError(H3BaseException):
    """Invalid H3 cell identifier."""

class H3DirEdgeInvalidError(H3BaseException):
    """Invalid H3 directed edge identifier."""

class H3UndirEdgeInvalidError(H3BaseException):
    """Invalid H3 undirected edge identifier."""

class H3VertexInvalidError(H3BaseException):
    """Invalid H3 vertex identifier."""

class H3PentagonError(H3BaseException):
    """Pentagon-related errors."""

class H3DuplicateInputError(H3BaseException):
    """Duplicate input error."""

class H3NotNeighborsError(H3BaseException):
    """Cells are not neighbors when required."""

class H3ResMismatchError(H3BaseException):
    """Resolution mismatch between cells."""

class H3GridNavigationError(H3BaseException):
    """Grid navigation operation failed."""

class H3MemoryError(H3BaseException):
    """Memory-related errors."""

class H3MemoryAllocError(H3MemoryError):
    """Memory allocation error."""

class H3MemoryBoundsError(H3MemoryError):
    """Memory bounds error."""

class H3OptionInvalidError(H3BaseException):
    """Invalid option error."""

class H3FailedError(H3BaseException):
    """General operation failure."""

class UnknownH3ErrorCode(H3BaseException):
    """Unknown H3 error code."""