Skip to content

geohierarchy.utils

Spatial utilities for geohierarchy mapping and raster processing.

geodesic_area(geom, geod=Geod(ellps='WGS84'))

Area of a polygon or multipolygon on the ellipsoid, in m2 (0 for other geometry types or an empty geometry).

Parameters:

Name Type Description Default
geom

Shapely geometry in EPSG:4326.

required
geod

The ellipsoid (pyproj Geod).

Geod(ellps='WGS84')

Returns:

Type Description
float

Area in square metres.

geodesic_perimeter(geom, geod=Geod(ellps='WGS84'))

Perimeter of a polygon or multipolygon on the ellipsoid, in m (0 for other geometry types).

Parameters:

Name Type Description Default
geom

Shapely geometry in EPSG:4326.

required
geod

The ellipsoid (pyproj Geod).

Geod(ellps='WGS84')

Returns:

Type Description
float

Perimeter in metres.

geodesic_length(geom, geod=Geod(ellps='WGS84'))

Length of a line or multiline on the ellipsoid, in m; for polygons, their perimeter.

Parameters:

Name Type Description Default
geom

Shapely geometry in EPSG:4326.

required
geod

The ellipsoid (pyproj Geod).

Geod(ellps='WGS84')

Returns:

Type Description
float

Length in metres.

is_utm_reasonable(gdf, max_width_m=750000, max_height_m=2000000, ellps=None)

Check if a GeoDataFrame is reasonable for a single UTM projection. Uses the CRS ellipsoid directly.

Parameters:

Name Type Description Default
gdf GeoDataFrame | GeoSeries

Data in a geographic CRS (degrees).

required
max_width_m float

Largest east-west extent that one UTM zone handles well.

750000
max_height_m float

Largest north-south extent that one UTM zone handles well.

2000000
ellps

Ellipsoid name; None = the CRS's own.

None

Returns:

Type Description
bool

True if the data's extent fits one UTM projection.

Raises:

Type Description
ValueError

If the data have no geographic CRS.

area(gdf, max_width_m=750000, max_height_m=2000000, ellps=None, geod=Geod(ellps='WGS84'), line_area=0, point_area=0)

Compute per-geometry area in square meters, CRS-aware.

Uses the CRS's own units directly if already projected; otherwise reprojects to a local UTM zone when the data fits within one, and falls back to geodesic area computation on the ellipsoid otherwise.

Parameters:

Name Type Description Default
gdf GeoDataFrame | GeoSeries

Geometries to measure.

required
max_width_m float

Maximum east-west extent (meters) considered safe for a single UTM projection.

750000
max_height_m float

Maximum north-south extent (meters) considered safe for a single UTM projection.

2000000
ellps

Ellipsoid name passed to :class:pyproj.Geod for the geodesic fallback. Derived from gdf's CRS if None.

None
geod

:class:pyproj.Geod instance used for geodesic area computation.

Geod(ellps='WGS84')
line_area

Area value assigned to line geometries, if not 0.

0
point_area

Area value assigned to point geometries, if not 0.

0

Returns:

Type Description

A pandas Series of areas aligned with gdf.

length(gdf, max_width_m=750000, max_height_m=2000000, ellps=None, geod=Geod(ellps='WGS84'), point_length=0)

Compute per-geometry length in meters, CRS-aware.

Same reprojection/fallback strategy as :func:area, applied to line/polygon-boundary length instead of area.

Parameters:

Name Type Description Default
gdf GeoDataFrame | GeoSeries

Geometries to measure.

required
max_width_m float

Maximum east-west extent (meters) considered safe for a single UTM projection.

750000
max_height_m float

Maximum north-south extent (meters) considered safe for a single UTM projection.

2000000
ellps

Ellipsoid name passed to :class:pyproj.Geod for the geodesic fallback. Derived from gdf's CRS if None.

None
geod

:class:pyproj.Geod instance used for geodesic length computation.

Geod(ellps='WGS84')
point_length

Length value assigned to point geometries, if not 0.

0

Returns:

Type Description

A pandas Series of lengths aligned with gdf.

get_geometry_types(gdf)

The base geometry types present (Multi* counted as its single type), e.g. {"Polygon", "Point"}.

Parameters:

Name Type Description Default
gdf

A non-empty GeoDataFrame.

required

Returns:

Type Description

Set of base geometry type names.

Raises:

Type Description
ValueError

If the GeoDataFrame is empty or None.

vectorize_raster_polars(raster_array, transform)

Efficiently converts a raster array into a Polars DataFrame of pixel centroids.

Parameters:

Name Type Description Default
raster_array ndarray

2D array of raster values.

required
transform Affine

Affine transform of the raster.

required

Returns:

Type Description
DataFrame

pl.DataFrame: DataFrame with columns [value, x, y, minx, miny, maxx, maxy].

get_id_mapping(src_gdf, dst_gdf, src_id, dst_id, geoweighted=False, how=None, intersection_mode=None)

Creates a mapping table between two geometry levels.

Parameters:

Name Type Description Default
src_gdf GeoDataFrame

Source geometry (finer).

required
dst_gdf GeoDataFrame

Destination geometry (coarser).

required
src_id str

ID column in source layer.

required
dst_id str

ID column in destination layer.

required
geoweighted bool

Legacy flag, kept for backward compatibility. Ignored whenever intersection_mode is given explicitly; otherwise True behaves like intersection_mode="exact" and False like intersection_mode="centroid".

False
how Optional[Literal['area', 'length']]

"area" or "length", forwarded to the "exact" path.

None
intersection_mode Optional[Literal['centroid', 'touches', 'exact', 'intersects']]

How src rows are paired with dst rows:

  • "centroid": a source polygon belongs to whichever destination polygon contains its centroid (this is the original, cheap geoweighted=False behavior). Every matched row gets _geoweight = 1.0.
  • "touches": a source geometry belongs to every destination polygon that contains it (full containment, not just border-touching). If a source row is contained by N destination rows, its _geoweight is 1/N -- downstream additive aggregations (e.g. :class:~geohierarchy.aggregation.Sum) split its value across those N claims, while averaging aggregations (e.g. :class:~geohierarchy.aggregation.Mean) naturally average instead of divide, since the weights are equal.
  • "exact": like "touches", but _geoweight is the real intersection area (or length) fraction between each matched pair, not a plain 1/N split (this is the original geoweighted=True behavior).
  • "intersects": a source geometry belongs to every destination polygon it geometrically touches at all -- real predicate="intersects" on the original geometry, no centroid substitution -- with every match getting _geoweight = 1.0 (no 1/N split, no area-fraction overlay). 2026-09-01 fix: this is what "centroid" was always meant to approximate for a caller aggregating an attribute like transit-access level_of_service onto census polygons ("population weighted average of every hexagon cell touching this polygon") -- a hexagon whose true footprint overlaps a small/oddly-shaped polygon but whose centroid happens to fall just outside it (common for census blocks comparable in size to a single hexagon) was silently dropped from that polygon's aggregate, which could paint a real transit-served block with a wrong 0 despite every hexagon actually covering it showing real access. Costs the same index-based gpd.sjoin as "centroid" (no expensive gpd.overlay), so it is not the slow path "exact" is.

If None (default), falls back to the legacy geoweighted bool for backward compatibility.

None

Returns:

Type Description
DataFrame

pl.DataFrame: Mapping table with [src_id, dst_id, geoweight].

get_knn_mapping(src_gdf, dst_gdf, src_id, dst_id, k=6, power=2.0)

Build an inverse-distance-weighted k-nearest-neighbor mapping, for smoothed downscaling.

Unlike :func:get_id_mapping (which only pairs geometries that physically overlap, reproducing the source geometry's boundaries exactly), this pairs every src_gdf centroid with its k nearest dst_gdf centroids, weighted by inverse distance and normalized to sum to 1 within each src_id group. Used by :class:~geohierarchy.aggregation.SmoothMean so a downscaled value blends across several source cells instead of copying whichever one happens to contain (or nearly contain) a given destination cell, smoothing out the source geometry's hard boundaries.

Also computes each row's polygon area (reusing an existing "area" column if either GeoDataFrame already has one -- e.g. the "area" column :class:~geohierarchy.core.GeoHierarchy stores on every level's geometry table -- rather than recomputing it) and carries it along as "_query_area" (area of the src_gdf row each mapping row is computed for) and "_neighbor_area" (area of the paired dst_gdf neighbor). :class:~geohierarchy.aggregation.SmoothMean uses these to convert an additive count to a density (dividing by whichever side the value's own row is on) before blending, and back to a count sized for the row being computed afterward. Meaningless (and unused) for non-polygon geometries.

Parameters:

Name Type Description Default
src_gdf GeoDataFrame

Rows to compute neighbor weights for (the finer, "destination-of-propagation" geometries in a downscale).

required
dst_gdf GeoDataFrame

Candidate neighbor geometries (the coarser, "source-of-propagation" geometries in a downscale).

required
src_id str

Id column in src_gdf.

required
dst_id str

Id column in dst_gdf.

required
k int

Number of nearest dst_gdf neighbors to blend per src_gdf row.

6
power float

Inverse-distance weighting exponent; higher values concentrate more weight on the nearest neighbor(s).

2.0

Returns:

Type Description
DataFrame

Polars DataFrame with ``[src_id, dst_id, "_geoweight", "_query_area",

DataFrame

"_neighbor_area"];"_geoweight"sums to 1 within eachsrc_id`` group.

h3_cells(geometry, resolution)

Build an H3 cell grid covering a geometry, as polygon cells.

Useful for building an H3 hierarchy level with :meth:GeoHierarchy.add_level -- H3 cells are plain polygons once vectorized, so they work as a core layer exactly like any other polygon geometry (they can also be used with :meth:GeoHierarchy.add_vector_data / :meth:GeoHierarchy.add_raster_data as non-layer source data).

Parameters:

Name Type Description Default
geometry GeoDataFrame | GeoSeries

Geometries whose combined extent the H3 grid should cover. Reprojected to EPSG:4326 first, since H3 operates on geographic coordinates.

required
resolution int

H3 resolution (0 = coarsest, ~15 = finest). See the H3 documentation for the approximate cell size at each level.

required

Returns:

Type Description
GeoDataFrame

A GeoDataFrame in EPSG:4326 with an "h3" column (the cell

GeoDataFrame

index as a hex string) and one polygon per covering cell.

h3_cells_from_ids(cell_ids)

Build polygons for an explicit, already-known list of H3 cell ids.

Unlike :func:h3_cells (which discovers the cells covering a geometry via containment), this just vectorizes cells you already have ids for -- the tiled/chunked raster resamplers use it to materialize only one H3-resolution-5 tile's worth of child cells at a time (e.g. via h3.cell_to_children), instead of building geometry for an entire city's fine-resolution grid in one shot.

Parameters:

Name Type Description Default
cell_ids

Iterable of H3 cell id hex strings.

required

Returns:

Type Description
GeoDataFrame

A GeoDataFrame in EPSG:4326 with an "h3" column and one polygon

GeoDataFrame

per cell, same shape/columns as :func:h3_cells.