Skip to content

geohierarchy.raster_resample

Generic, exact, mass-conserving raster -> polygon-tiling area-weighted resampling.

This module implements raster_to_polygons: given a raster (a 2D array of values + an affine transform + a CRS) and an arbitrary set of target polygons (H3 cells, administrative boundaries, or anything else), it splits each pixel's value across every polygon the pixel geometrically intersects, in proportion to the intersection area, and returns one row per polygon that is touched by at least one non-null pixel.

Guarantees (see tests in geohierarchy/tests/test_raster_resample.py):

  1. Area-weighted split -- a pixel straddling several polygons splits its value across them in exact proportion to the overlap area.
  2. Full coverage -- every polygon touching a non-null pixel appears in the output with a non-null value; none are silently dropped.
  3. Exact mass conservation -- sum(output value) equals sum(pixel value) over the raster window, up to floating point precision (no approximation, no residual rounding error).
  4. Density bound -- for every output polygon, value / polygon_area lies between the min and max of pixel_value / pixel_area over the pixels that polygon touches, since a polygon's value is by construction an area-weighted average of exactly those pixels' densities.

Algorithm

Exact polygon/pixel intersection (via shapely), but not naively computed for every pixel: pixels are square and axis-aligned in the raster's own CRS, so most of them (anywhere the target tiling's cells are larger than a pixel, e.g. WorldPop's ~100m pixels vs. an H3 res-9/10 cell) fall entirely inside a single target polygon. This is detected cheaply with a shapely.STRtree bounding-box query per pixel against the target polygons: pixels with exactly one candidate whose bounds contain the pixel's bounds skip geometric clipping entirely and hand their whole value to that one polygon (the fast path, and the common case). Only pixels whose bounding box touches more than one candidate polygon -- i.e. pixels that plausibly straddle a boundary -- pay for an actual shapely.intersection call, and even then only against their few real candidates, never the full pixel x polygon cross product.

A closed-form periodicity/offset lookup (precomputing exact intersection fractions once for "a pixel at relative offset X from the hex lattice" and reusing it everywhere) was investigated and is documented as a follow-up in the module docstring below, but was not implemented: correctness (exact conservation, full coverage, density bound, all hard requirements here) was prioritized over that extra optimization within the time available. The boundary-only-exact-clip approach above already reduces the number of real geometric intersections to a small minority of total pixels in the realistic pixel-smaller-or-comparable-to-cell regime this is used for (WorldPop pixels vs. H3 res 9-11), and benchmarks fast enough in practice (see the module's benchmark script / test suite for real numbers).

Future optimization note (periodicity lookup): H3's hex tiling at a fixed resolution is a regular lattice everywhere except at the 12 icosahedral pentagon base cells (which would need to fall back to this module's exact path as a documented edge case). For the regular hexagonal regions, a pixel's split fractions across its (up to 3) covering hexagons are a function only of the pixel's offset modulo the hex lattice's repeating unit cell -- in principle, precomputing that function on a fine grid of offsets (or deriving it analytically from the hexagon edge equations) and looking it up per pixel would avoid the shapely intersection call even for boundary-crossing pixels. That was judged a materially larger, riskier undertaking (deriving/validating the closed-form offset -> area-fraction map against the actual H3 projection, which is not a perfectly flat lattice in lon/lat) than the time available supported to get right and verified; the boundary-only-exact-clip approach here is exact by construction and fast enough in practice.

raster_to_polygons(raster_array, transform, raster_crs, polygons, id_col, nodata=None)

Area-weighted, mass-conserving resample of a raster onto a polygon tiling.

Parameters:

Name Type Description Default
raster_array ndarray

2D array of pixel values (e.g. one band read from a GeoTIFF). NaN and nodata pixels are treated as missing and excluded.

required
transform Affine

Affine transform mapping pixel (col, row) -> raster CRS coordinates (as returned by rasterio).

required
raster_crs

CRS of raster_array/transform.

required
polygons GeoDataFrame

Target polygon tiling (e.g. H3 cells from :func:~geohierarchy.utils.h3_cells, or any other polygon GeoDataFrame). Reprojected internally to raster_crs so pixel and polygon geometries share a common, metric-if-possible plane; pass an already-projected raster_crs/polygons pair (not EPSG:4326) for exact, non-degree area weighting.

required
id_col str

Name of the unique identifier column in polygons.

required
nodata Optional[float]

Sentinel value in raster_array treated as missing, in addition to NaN.

None

Returns:

Type Description
DataFrame

Polars DataFrame with columns id_col and value: one row per

DataFrame

polygon touched by at least one valid pixel, with a value equal to

DataFrame

the area-weighted sum of that pixel's contributions. Guarantees (1)

DataFrame

every touching polygon appears, (2) sum(value) exactly equals

DataFrame

sum(raster_array) over valid pixels within the polygons'

DataFrame

combined extent, and (3) each polygon's implied density

DataFrame

(value / polygon area) never exceeds the max, nor falls below

DataFrame

the min, of the densities of the pixels it touches. See the module

DataFrame

docstring for the algorithm and why those hold by construction.

raster_to_h3(raster_array, transform, raster_crs, resolution, value_col='value', h3_col='h3_cell', nodata=None)

Convenience wrapper: area-weighted, mass-conserving raster -> H3 grid resample.

Builds an H3 cell grid covering the raster's own extent at resolution (via :func:~geohierarchy.utils.h3_cells) and delegates to :func:raster_to_polygons. This is the generic primitive pycensus's WorldPop loader applies with WorldPop-specific knowledge (nodata handling, AOI cropping, CRS choice) layered on top -- see pycensus.census.worldwide.worldpop.loader.

Parameters:

Name Type Description Default
raster_array ndarray

2D array of pixel values.

required
transform Affine

Affine transform for raster_array.

required
raster_crs

CRS of raster_array.

required
resolution int

H3 resolution for the output grid.

required
value_col str

Name to give the output value column.

'value'
h3_col str

Name to give the output H3 cell-id column.

'h3_cell'
nodata Optional[float]

Sentinel value in raster_array treated as missing, in addition to NaN.

None

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col -- one row per

DataFrame

H3 cell touched by at least one valid pixel.

raster_to_h3_tiled(tif_path, resolution, value_col='value', h3_col='h3_cell', nodata=None, tile_resolution=5, max_workers=None)

Memory-bounded, optionally-parallel version of :func:raster_to_h3.

raster_to_h3 reads the entire raster into one array and builds one shapely.STRtree over the entire target H3 grid before doing any work -- fine for a small city, but for a large one (millions of H3 cells, tens of millions of raster pixels) that single-shot approach can hold everything -- the full pixel arrays, the full set of H3 polygons, the STRtree's internal index, every intermediate shapely/numpy array -- in memory simultaneously (a real, live OOM failure: Boston and Beersheba's run.py were both killed past a 20GB cgroup cap during exactly this step, 2026-08-30).

This instead partitions the work by H3's own parent/child hierarchy: every resolution-level cell has a unique, well-defined ancestor at tile_resolution (coarser, e.g. H3 res 5's ~252 km^2 average cell), so grouping by that ancestor is an exact, non-overlapping, non-duplicating partition of the whole grid -- no cell is ever split across two tiles, and no cell is ever double-counted. Each tile then only needs its own (small, bounded) set of child-cell polygons and its own windowed slice of the raster (read fresh from disk in that tile's own worker, never the whole file), so peak memory is bounded by one tile's size, not the whole city's, regardless of how many tiles there are.

Mass conservation across tile boundaries needs one extra piece beyond the exact partition itself, which an earlier version of this function got wrong (caught live by test_raster_to_h3_tiled_matches_single_shot, 2026-08-30, ~8% mass inflation): a pixel that straddles the true geometric boundary between a cell owned by tile A and a cell owned by tile B needs to see BOTH real candidate cells at once to split correctly. If each tile's worker only ever sees its OWN cells as candidates, that shared pixel looks like a single-candidate pixel to BOTH tiles independently, and each one wrongly hands it 100% of the pixel's value -- doubling it. The fix is a "halo": every tile also gets a thin ring of its true H3 neighbors' cells as extra (non-owned) candidates, purely so raster_to_polygons can see the full local picture and split correctly; each tile then keeps only the rows for cells it actually owns and discards the halo rows (see _raster_to_h3_tile_worker) -- the neighboring tile that DOES own those halo cells computes the identical split independently and keeps its own share. Net effect: every cell is produced by exactly one tile, with the same value :func:raster_to_h3 would have given it.

Parameters:

Name Type Description Default
tif_path str

Path to the source GeoTIFF (read once for its header here, then re-opened independently -- windowed -- by each tile's worker).

required
resolution int

Target (fine) H3 resolution.

required
value_col str

Name to give the output value column.

'value'
h3_col str

Name to give the output H3 cell-id column.

'h3_cell'
nodata Optional[float]

Sentinel value treated as missing, in addition to NaN. Defaults to the GeoTIFF's own declared nodata value if not given.

None
tile_resolution int

Coarser H3 resolution whose cells define the partition (default 5, resolution must be > this). Larger cities/finer resolution benefit from a coarser (smaller number, more cells skipped) tile_resolution -- lower peak memory per tile, more tiles, each cheap.

5
max_workers Optional[int]

Worker process count for ProcessPoolExecutor (default: os.cpu_count()). Pass 1 to run tiles serially in this same process (useful for debugging / tiny AOIs where process-pool overhead would dominate).

None

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col, one row per H3 cell

DataFrame

touched by at least one valid pixel -- identical contract (and, up

DataFrame

to row order, identical values) to :func:raster_to_h3.

pixel_area_density_bounds(raster_array, transform)

Min/max pixel density (value / pixel area) over the raster's valid pixels.

Convenience helper for verification: compare an output polygon's value / polygon_area against these bounds restricted to the pixels that polygon actually touches (see the test suite for the full, per-cell version of this check -- this module-level helper gives the raster-wide bound only).

Parameters:

Name Type Description Default
raster_array ndarray

Raster values (NaN or nodata already masked).

required
transform Affine

The raster's affine transform (pixel size from it).

required

Returns:

Type Description
Tuple[float, float]

(min density, max density) over the valid pixels.

resample_points_to_h3(lat, lng, value, resolution, is_count=True, point_area_m2=None, h3_col='h3_cell', value_col='value')

Fast, approximate-but-mass-conserving point/pixel -> H3 resample.

2026-09-04, explicit user request/spec: a much cheaper alternative to :func:raster_to_polygons's exact area-weighted overlay, for the common case of a dense point/pixel cloud (raster pixel centers, or a real gridded census source like Germany's Zensus 100m grid) being resampled onto H3 cells noticeably LARGER than the source spacing -- exact overlay is real work this doesn't need to pay for at that scale. Pure polars + h3ronpy vector ops, no per-point geometry/STRtree at all:

  1. (is_count=True only) convert each point's value to a density by dividing by point_area_m2 -- skip this for a source that's already a mean/rate/density/relative quantity (is_count=False, e.g. a pop_density-shaped raster), which starts directly at step 2 on the raw value array.
  2. assign each point to its containing H3 cell at resolution (h3ronpy.vector.coordinates_to_cells -- for a hexagonal grid, "the cell whose lattice point is nearest" and "the cell containing this coordinate" are the same cell by construction, so this needs no separate nearest-neighbor search against a target grid), then take the MEAN density of every point assigned to the same cell.
  3. (is_count=True only) multiply each cell's mean density by that cell's own real geodesic area (h3ronpy.cells_area_m2) to recover a count.
  4. (is_count=True only) rescale every cell's count by a single global factor so sum(output value) exactly equals sum(value) over every point that got assigned a cell (in practice every valid point, since H3 tiles the whole globe -- there is no "too far" case at the point-assignment step itself; the rescale still exists because step 2's per-cell MEAN-of-densities is only an approximation of the true within-cell distribution, unlike :func:raster_to_polygons's exact overlay, so a global correction is needed to keep the total exactly right even though individual cells are only approximately right).

For is_count=False, the output is simply each cell's mean of value over its assigned points -- no area multiply, no rescale (a global sum of a rate/density column isn't a meaningful conserved quantity to correct against).

Parameters:

Name Type Description Default
lat ndarray

Point latitudes (degrees, EPSG:4326).

required
lng ndarray

Point longitudes (degrees, EPSG:4326).

required
value ndarray

Point values -- a count (is_count=True) or an already-relative quantity (is_count=False).

required
resolution int

Target H3 resolution.

required
is_count bool

Whether value is an absolute count needing the density-conversion + area-recovery + conservation-rescale treatment (True, default) or is already a mean/rate/density (False, in which case point_area_m2 is not needed).

True
point_area_m2 Optional[ndarray]

Each point's own represented area in m^2 (e.g. a raster pixel's real geodesic footprint, or a gridded census cell's known cell size). Required when is_count=True.

None
h3_col str

Output H3 cell-id column name (hex string, matching this codebase's h3_cell convention).

'h3_cell'
value_col str

Output value column name.

'value'

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col -- one row per

DataFrame

H3 cell touched by at least one input point.

raster_to_h3_nearest(tif_path, resolution, value_col='value', h3_col='h3_cell', nodata=None, is_count=True, row_chunk=4096)

Fast raster -> H3 resample via :func:resample_points_to_h3 (pixel centers, not exact overlay).

Reads the raster in horizontal row-block windows (bounded by row_chunk, default 4096 rows) so peak memory scales with one chunk's pixel count, not the whole raster -- each chunk's valid (non-nodata) pixel centers/values/areas are extracted and accumulated; the actual H3 assignment + mean + rescale happens once, over the full accumulated point set, in :func:resample_points_to_h3.

Pixel area (needed for is_count=True's density conversion): for a geographic (degree) CRS -- WorldPop's real shipping CRS -- uses the standard equirectangular approximation (R = 6,371,000m, pixel width scaled by cos(latitude)), accurate to well under 0.1% at typical WorldPop pixel sizes (~100m) and normal (non-polar) latitudes. For a projected (metric) CRS, pixel area is simply abs(transform.a * transform.e) (already in real m^2), and pixel centers are reprojected to EPSG:4326 for the H3 assignment step (via pyproj) since coordinates_to_cells needs real lat/lng.

Parameters:

Name Type Description Default
tif_path str

Path to a single-band GeoTIFF.

required
resolution int

Target H3 resolution.

required
value_col str

Output value column name.

'value'
h3_col str

Output H3 cell-id column name.

'h3_cell'
nodata Optional[float]

Nodata sentinel to exclude (default: read from the file itself).

None
is_count bool

See :func:resample_points_to_h3.

True
row_chunk int

Rows per read window.

4096

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col.

raster_to_h3_by_centroid(tif_path, resolution, value_col='value', h3_col='h3_cell', nodata=None, is_count=True)

Raster -> H3 resample by sampling the raster AT each H3 cell's own centroid.

The inverse direction of :func:raster_to_h3_nearest -- for use when the target H3 resolution is FINER than the raster's own pixel spacing (see :func:raster_to_h3_auto's docstring for when this applies). Aggregating sparse pixel centers into a denser H3 grid (as raster_to_h3_nearest/resample_points_to_h3 do) leaves most cells with zero assigned pixels in that regime -- most H3 cells simply don't contain any pixel center. Sampling the raster's own value at each H3 cell's centroid instead guarantees a value for every cell whose centroid falls within the raster's valid-data extent, at the cost of point-sampling noise (a cell's density is exactly its centroid's pixel value, not a true area-weighted average over the cell) -- corrected for in aggregate by the same global conservation rescale step 4 uses.

Steps (matching :func:resample_points_to_h3's spec, applied in the other direction): 1. Generate every H3 cell at resolution whose centroid falls within the raster's bounding-box footprint (h3ronpy.vector.geometry_to_cells). 2. Sample the raster's value at each cell's own centroid (nearest pixel, rasterio.DatasetReader.sample). 3. (is_count=True) convert each sampled value to a density (divide by that pixel's own real area), multiply by the H3 CELL's own area to recover a count. 4. (is_count=True) rescale every cell's count by a single global factor so sum(output value) matches the TRUE sum of every valid pixel in the raster (not just the sampled ones) -- this is what corrects for the point-sampling approximation in aggregate, exactly as resample_points_to_h3's own rescale corrects for its mean-of-densities approximation.

Parameters:

Name Type Description Default
tif_path str

Path to a single-band GeoTIFF.

required
resolution int

Target H3 resolution.

required
value_col str

Output value column name.

'value'
h3_col str

Output H3 cell-id column name.

'h3_cell'
nodata Optional[float]

Nodata sentinel to exclude (default: read from the file).

None
is_count bool

See :func:resample_points_to_h3.

True

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col -- one row per H3

DataFrame

cell whose centroid sampled a valid (non-nodata) pixel.

raster_to_h3_auto(tif_path, resolution, value_col='value', h3_col='h3_cell', nodata=None, is_count=True, row_chunk=4096)

Fast raster -> H3 resample, auto-picking the right direction for the resolution.

2026-09-04, explicit user spec: "if the issue is that h3 cells are too small then better assign to each h3 cell the value of the raster at the h3 cell centroid and use the other method if the h3 res is higher than the raster size (use h3 cell diameter and pixel side)." Compares each H3 cell's real diameter at resolution (h3.average_hexagon_edge_length * 2) against the raster's own pixel side length (in real meters, geodesic-approximated for a degree CRS):

  • H3 cell diameter >= pixel side (the common case for a coarse-ish H3 resolution over a fine raster, e.g. WorldPop 100m pixels onto H3 res 9 or coarser, ~252 km^2+ per cell): :func:raster_to_h3_nearest (aggregate pixel centers per cell, mean density) -- every cell gets many pixels, a real local average.
  • H3 cell diameter < pixel side (H3 finer than the raster, e.g. WorldPop's 100m pixels onto this study's native H3 res 11, ~29m edge/58m diameter cells): :func:raster_to_h3_by_centroid (sample the raster directly at each cell's centroid) -- aggregation would leave most cells with zero assigned pixels in this regime (verified live: WorldPop res-11 aggregation covered only ~22% of the cells the exact area-weighted method covers), while centroid-sampling gives every cell within the raster's extent a value.

Both branches are mass-conserving via the same global rescale (see each function's own docstring) -- sum(output value) matches the raster's real total either way when is_count=True.

Parameters:

Name Type Description Default
tif_path str

Path to a single-band GeoTIFF.

required
resolution int

Target H3 resolution.

required
value_col str

Output value column name.

'value'
h3_col str

Output H3 cell-id column name.

'h3_cell'
nodata Optional[float]

Nodata sentinel to exclude (default: read from the file).

None
is_count bool

See :func:resample_points_to_h3.

True
row_chunk int

Rows per read window, only used by the aggregation branch.

4096

Returns:

Type Description
DataFrame

Polars DataFrame with h3_col and value_col.