Skip to content

UrbanAccessAnalyzer.h3_ops

H3-specific utilities: point/polygon rasterization, raster ingest, and cell resampling, in Polars.

Consolidates the previous h3_utils.py (pandas/geopandas, mature but slow) and h3_polars.py (an incomplete polars port whose cells_in_geometry was pandas code with only the type hint changed, and which was never imported anywhere else in the package) into one correct implementation.

Edge-to-any-polygon aggregation (the street-edges-to-H3 path previously covered by :func:from_df from :class:AccessibilityAnalyzer) now lives in the optional geohierarchy dependency, wired in through :mod:UrbanAccessAnalyzer.geometry_levels and :meth:UrbanAccessAnalyzer.api.AccessibilityAnalyzer.to_level/to_h3 -- that path works against any polygon layer, not just H3 grids. This module keeps the remaining H3-specific pieces that have no geohierarchy equivalent: rasterizing points/polygons/rasters directly into H3 cells (:func:cells_in_geometry, :func:from_df, :func:from_raster, used e.g. by :class:UrbanAccessAnalyzer.api.PointsOfInterest), re-aggregating H3 data onto a coarser resolution's parent cells (:func:resample), and building H3 hexagon boundary geometries (:func:to_gdf).

Methodology / sources:

  • H3 is Uber's hexagonal hierarchical spatial index: https://h3geo.org/docs. Cell ids are opaque 64-bit strings; each resolution (0-15) subdivides the previous one into ~7 children.
  • Polygon-to-cell rasterization (:func:cells_in_geometry) uses h3.h3shape_to_cells (stable "center-of-cell-inside-polygon" containment) and h3.h3shape_to_cells_experimental (H3's newer, still-experimental API: https://h3geo.org/docs/library/experimental) for the full, overlap, bbox_overlap and center_overlap containment strategies, since H3 itself has no stable API for those. H3 has no bulk/vectorized polyfill entry point, so this step is a Python loop over input geometries -- fine here because POI/polygon counts are orders of magnitude smaller than the street-graph edge counts the rest of the package optimizes for.
  • :func:aggregate is fully vectorized Polars (explode + group_by/agg expression chains): supports first/last/min/max/mean/sum and two spatial-specific reducers, density (value normalized by cell area in m^2, via h3.cell_area) and distribute (a value split evenly across every cell a source geometry overlaps).

cells_in_geometry(df, resolution, geometry_col='geometry', buffer=0.0, contain='center_overlap')

Rasterize WKB geometries into lists of H3 cell ids.

Parameters:

Name Type Description Default
df DataFrame

Polars DataFrame with a WKB geometry column (projected CRS if buffer > 0, EPSG:4326 otherwise -- H3 always operates in lon/lat).

required
resolution int

H3 resolution (0-15); higher is smaller/finer cells.

required
geometry_col str

Name of the WKB geometry column.

'geometry'
buffer float

Buffer distance (CRS units) applied before rasterization; required for line/point geometries to acquire any area.

0.0
contain ContainMode

Containment rule -- "center" (cell center inside geometry, stable API), "full"/"overlap"/"bbox_overlap" (experimental API), "centroid" (rasterize each geometry's centroid point instead of its shape), or "center_overlap" (try "center", fall back to "overlap" for geometries that match no cell, e.g. slivers smaller than one hexagon).

'center_overlap'

Returns:

Type Description
DataFrame

df with an added h3_cells (list[str]) column.

aggregate(h3_df, columns=None, value_order=None, method='max', h3_column='h3_cell')

Explode list-valued H3 cell columns and aggregate values per cell.

Parameters:

Name Type Description Default
h3_df DataFrame

DataFrame with an h3_column holding either a single cell id per row or a list[str] of cell ids (e.g. from :func:cells_in_geometry's h3_cells).

required
columns Optional[List[str]]

Columns to aggregate; defaults to every column except h3_column.

None
value_order Optional[Union[List, Dict[str, List]]]

Explicit category ordering for first/last/etc. on non-numeric columns, either one list shared by all columns or a {column: order} dict.

None
method Union[str, Dict[str, str]]

Aggregation method per column, one of first, last, min, max, mean, sum, density (requires an area column in m², normalizes by H3 cell area), or distribute (splits a value evenly across every cell a row's source geometry maps to).

'max'
h3_column str

Name of the cell-id column (renamed to h3_cell internally if different).

'h3_cell'

Returns:

Type Description
DataFrame

Polars DataFrame with one row per distinct H3 cell (h3_cell

DataFrame

column) and one aggregated column per entry in columns.

from_df(df, resolution, geometry_col='geometry', columns=None, value_order=None, buffer=0.0, contain='center_overlap', method='max')

Rasterize a Polars DataFrame with WKB geometry directly into aggregated H3 cells.

Combines :func:cells_in_geometry and :func:aggregate.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with a WKB geometry_col column and attribute columns.

required
resolution int

H3 resolution.

required
geometry_col str

Name of the WKB geometry column.

'geometry'
columns Optional[List[str]]

Attribute columns to aggregate.

None
value_order Optional[Union[List, Dict[str, List]]]

See :func:aggregate.

None
buffer float

Buffer distance applied before rasterization.

0.0
contain ContainMode

Containment rule, see :func:cells_in_geometry.

'center_overlap'
method Union[str, Dict[str, str]]

Aggregation method(s), see :func:aggregate. If "density" is used for any column, per-row geometry area (m²) is computed automatically.

'max'

Returns:

Type Description
DataFrame

Polars DataFrame aggregated per H3 cell (see :func:aggregate).

from_raster(raster, aoi=None, resolution=10, contain='center_overlap', method='distribute', value_order=None, transform=None, crs=None, nodata=None)

Rasterize a raster dataset into aggregated H3 cells.

Parameters:

Name Type Description Default
raster Union[ndarray, str]

Either a file path (read via :func:UrbanAccessAnalyzer.raster_ops.read_raster) or an in-memory NumPy array (requires transform/crs).

required
aoi

AOI to crop to when raster is a file path.

None
resolution int

H3 resolution.

10
contain ContainMode

Containment rule, see :func:cells_in_geometry.

'center_overlap'
method Union[str, Dict[str, str]]

Aggregation method, see :func:aggregate.

'distribute'
value_order Optional[List]

Explicit ordering for categorical raster values.

None
transform

Affine transform (required for array input).

None
crs

CRS (required for array input).

None
nodata

Nodata value to exclude.

None

Returns:

Type Description
DataFrame

Polars DataFrame aggregated per H3 cell, from the value column.

from_raster_centroid(raster_path, aoi=None, resolution=10, agg='sum', row_chunk=500)

Map each raster pixel's center straight to its H3 cell, in bounded-size row-bands.

A much cheaper alternative to :func:from_raster for rasters whose pixels are comparable to or larger than the target H3 resolution's cells (e.g. a ~100m WorldPop pixel vs. an H3 resolution-10 cell, ~140m across): :func:from_raster -> :func:UrbanAccessAnalyzer.raster_ops.vectorize turns every pixel into an explicit Shapely polygon before H3- polyfilling it, which scales with total pixel count and can exhaust memory on a large AOI (confirmed via repeated real OOM kills on a full-metro WorldPop crop at resolution 10). This instead computes each pixel's center coordinate via plain affine arithmetic on NumPy arrays (no geometry objects at all) and maps it to an H3 cell with h3ronpy.vector.coordinates_to_cells -- one vectorized, Arrow-native call per row-band.

For a summable agg (the population use case), a pixel is never mapped straight to resolution if that would be coarser than the pixel itself. Centroid-only assignment has a real error mode: a pixel whose center falls in cell A but whose square footprint partially overlaps neighbor cell B contributes 100% of its value to A and 0% to B. That error's absolute size scales with the assignment resolution's cell size, so assigning directly at a coarse target resolution (a big cell) can distort that cell's density by more than a couple percent. Instead, this picks the H3 resolution whose average cell area (:func:h3.average_hexagon_area) is closest to the pixel's own area, assigns pixels there (bounding the mismatch to that much smaller cell size), then aggregates up to resolution via :func:resample (method="sum") -- an exact, purely index-based parent/child rollup with no additional approximation, so every target cell's total is the sum of exactly the fine cells nested under it. sum(value) is therefore identical whether pixels are assigned directly at resolution or via this finer intermediate step; only the per-cell distribution (density) accuracy improves.

Parameters:

Name Type Description Default
raster_path str

Path to a raster file (cropped to aoi internally via :func:UrbanAccessAnalyzer.raster_ops.read_raster, which uses an exact polygon mask, not just a bounding-box crop, and reprojected to a metric CRS so pixel area is measured in true m^2 rather than degrees).

required
aoi

Area of interest to crop the raster to.

None
resolution int

Target H3 resolution.

10
agg Union[str, 'AggregationStrategy']

Aggregation across pixels landing in the same cell -- a :class:~geohierarchy.aggregation.AggregationStrategy (e.g. Sum(), Mean(), Max()) if the optional geohierarchy dependency is installed, or one of the plain string reducers polars' group_by(...).agg understands ("sum", "mean", "max", ...) otherwise. Only a sum (the default) gets the pixel-matched-resolution treatment above -- summing nests exactly across resolutions, but a mean or max computed at a fine resolution is not equivalent to the same reducer computed directly at a coarser one, so non-sum aggregations are assigned directly at resolution.

'sum'
row_chunk int

Number of raster rows processed per batch. Bounds peak memory to one row-band's worth of pixel coordinates/H3 cells regardless of the overall raster size.

500

Returns:

Type Description
DataFrame

Polars DataFrame with h3_cell and value columns, one row

DataFrame

per H3 cell within resolution's grid with at least one

DataFrame

contributing pixel.

resample(df, target_resolution, columns=None, value_order=None, method='max', h3_column='h3_cell')

Re-aggregate H3 cell data onto a coarser resolution's parent cells.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with an h3_column of H3 cell ids.

required
target_resolution int

Target (coarser) H3 resolution.

required
columns Optional[List[str]]

Columns to aggregate; see :func:aggregate.

None
value_order Optional[Dict]

See :func:aggregate.

None
method Union[str, Dict[str, str]]

Aggregation method(s); see :func:aggregate.

'max'
h3_column str

Name of the cell-id column.

'h3_cell'

Returns:

Type Description
DataFrame

Polars DataFrame aggregated at target_resolution.