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) usesh3.h3shape_to_cells(stable "center-of-cell-inside-polygon" containment) andh3.h3shape_to_cells_experimental(H3's newer, still-experimental API: https://h3geo.org/docs/library/experimental) for thefull,overlap,bbox_overlapandcenter_overlapcontainment 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:
aggregateis fully vectorized Polars (explode + group_by/agg expression chains): supportsfirst/last/min/max/mean/sumand two spatial-specific reducers,density(value normalized by cell area in m^2, viah3.cell_area) anddistribute(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
|
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_overlap'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
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 |
required |
columns
|
Optional[List[str]]
|
Columns to aggregate; defaults to every column except
|
None
|
value_order
|
Optional[Union[List, Dict[str, List]]]
|
Explicit category ordering for |
None
|
method
|
Union[str, Dict[str, str]]
|
Aggregation method per column, one of |
'max'
|
h3_column
|
str
|
Name of the cell-id column (renamed to |
'h3_cell'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with one row per distinct H3 cell ( |
DataFrame
|
column) and one aggregated column per entry in |
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 |
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: |
None
|
buffer
|
float
|
Buffer distance applied before rasterization. |
0.0
|
contain
|
ContainMode
|
Containment rule, see :func: |
'center_overlap'
|
method
|
Union[str, Dict[str, str]]
|
Aggregation method(s), see :func: |
'max'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame aggregated per H3 cell (see :func: |
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: |
required |
aoi
|
AOI to crop to when |
None
|
|
resolution
|
int
|
H3 resolution. |
10
|
contain
|
ContainMode
|
Containment rule, see :func: |
'center_overlap'
|
method
|
Union[str, Dict[str, str]]
|
Aggregation method, see :func: |
'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 |
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 |
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: |
'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 |
DataFrame
|
per H3 cell within |
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 |
required |
target_resolution
|
int
|
Target (coarser) H3 resolution. |
required |
columns
|
Optional[List[str]]
|
Columns to aggregate; see :func: |
None
|
value_order
|
Optional[Dict]
|
See :func: |
None
|
method
|
Union[str, Dict[str, str]]
|
Aggregation method(s); see :func: |
'max'
|
h3_column
|
str
|
Name of the cell-id column. |
'h3_cell'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame aggregated at |