Skip to content

UrbanAccessAnalyzer.geometry_ops

General vector-geometry utilities: file I/O, area, spatial joins, aggregation.

File I/O (:func:read_geofile) and the spatial-predicate join (:func:source_ids_to_dst_geometry) stay on geopandas/pyogrio/shapely: file format support (shapefile, GeoPackage, KML, ...) and spatial-predicate joins are exactly what those libraries are for, and this module is the package's sanctioned geometry I/O boundary (see module docstrings of :mod:UrbanAccessAnalyzer.osm_io and :mod:UrbanAccessAnalyzer.graph_ops for the same boundary on the OSM/graph side).

:func:aggregate is the one piece of this module that used to be duplicated almost verbatim between the old geometry_utils.py (pandas, keyed by an arbitrary id column) and h3_utils.py/h3_polars.py (keyed by H3 cell). It is now a single generic Polars implementation keyed by any id column (scalar or list-valued, for one-to-many source-to-destination assignments); :func:UrbanAccessAnalyzer.h3_ops.aggregate is a thin wrapper around it.

Methodology:

  • Geodesic area (:func:geodesic_area): for AOIs too large for a single UTM zone to stay accurate (:func:is_utm_reasonable checks width/height against configurable thresholds), area is computed on the ellipsoid directly via pyproj.Geod.geometry_area_perimeter rather than a projected approximation.
  • Containment/join modes shared across :func:source_ids_to_dst_geometry and :mod:UrbanAccessAnalyzer.h3_ops (center, full, overlap, bbox_overlap, centroid, center_overlap) follow the same semantics everywhere in the package: center_overlap tries strict centroid-in-polygon first and falls back to any-overlap only for sources that matched nothing (e.g. a destination cell smaller than a source feature's centroid-exclusion sliver).

read_geofile(path, bounds=None)

Load a vector geo file, auto-detecting format and pushing down a bbox filter.

Tries GeoParquet first (fastest, with true bbox pushdown via geopandas.read_parquet(bbox=...)), then falls back through FlatGeobuf/GeoPackage/Shapefile/GeoJSON/... via pyogrio.

Parameters:

Name Type Description Default
path

File path, with or without extension. If given without an extension, every file sharing that base name is considered, fastest format first.

required
bounds

Optional bbox filter: a shapely geometry, a [xmin, ymin, xmax, ymax] list/tuple (assumed EPSG:4326), or a GeoDataFrame/GeoSeries.

None

Returns:

Type Description
GeoDataFrame

The loaded GeoDataFrame, spatially filtered to bounds if given.

Raises:

Type Description
FileNotFoundError

If no candidate file could be read.

intersects_all_with_all(G, g)

Fully vectorized pairwise intersection matrix between two geometry collections.

Parameters:

Name Type Description Default
G Union[GeoDataFrame, GeoSeries]

Target geometries (one output row each).

required
g Union[GeoDataFrame, GeoSeries]

Source geometries (one output column each); reprojected to G's CRS.

required

Returns:

Type Description
ndarray

Boolean array of shape (len(G), len(g)).

intersects_xy_all_with_all(G, x, y=None)

Vectorized intersection test between geometries and many point coordinates.

Parameters:

Name Type Description Default
G Union[GeoDataFrame, GeoSeries]

Target geometries.

required
x

Iterable of x-coordinates, iterable of (x, y) pairs, or a GeoDataFrame/GeoSeries (whose centroids are used).

required
y

Y-coordinates, required unless x already carries both.

None

Returns:

Type Description
ndarray

Boolean array of shape (len(G), n_points).

source_ids_to_dst_geometry(source_gdf, dst_gdf, buffer_source=0.0, buffer_dst=0.0, contain='center_overlap', id_column=None, simplify_tol=None, clip_to_dst_bbox=True)

Assign the list of intersecting source-feature ids to each destination geometry.

Parameters:

Name Type Description Default
source_gdf Union[GeoDataFrame, GeoSeries]

Source features to assign.

required
dst_gdf Union[GeoDataFrame, GeoSeries]

Destination geometries to receive assigned ids.

required
buffer_source float

Buffer applied to source geometries before the join.

0.0
buffer_dst float

Buffer applied to destination geometries before the join.

0.0
contain ContainMode

Spatial relationship rule; see :mod:h3_ops for the shared containment-mode semantics used across the package.

'center_overlap'
id_column Optional[str]

Column in source_gdf to collect; defaults to its index.

None
simplify_tol Optional[float]

Optional geometry simplification tolerance applied to source_gdf before the join (speeds up complex polygons).

None
clip_to_dst_bbox bool

Pre-filter source_gdf to dst_gdf's bounding box before the (potentially expensive) join.

True

Returns:

Type Description
GeoDataFrame

dst_gdf with an added id_column list column of matched

GeoDataFrame

source ids (empty list where nothing matched).

Raises:

Type Description
NotImplementedError

For an unrecognized contain mode.

aggregate(df, id_column, columns=None, value_order=None, method='max')

Explode a list-valued (or scalar) id column and aggregate values per id.

Generic Polars group-by-and-reduce used by both plain geometry-to-geometry resampling (:func:resample_gdf) and H3 rasterization (:func:UrbanAccessAnalyzer.h3_ops.aggregate, a thin wrapper around this function).

Parameters:

Name Type Description Default
df DataFrame

DataFrame with an id_column (scalar or list[...]) plus attribute columns to aggregate.

required
id_column str

Column to group by (exploded first if list-valued).

required
columns Optional[List[str]]

Columns to aggregate; defaults to every other column.

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

Explicit category ordering for non-numeric columns (needed for first/last/min/max to be meaningful), either one list shared by all columns or a {column: order} dict.

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

Aggregation method per column: first, last, min, max, mean, sum, density (requires an area column in m², total-preserving), or distribute (splits a value evenly across every id a row maps to, total-preserving).

'max'

Returns:

Type Description
DataFrame

Polars DataFrame with one row per distinct id_column value.

resample_gdf(source_gdf, dst_gdf, columns=None, value_order=None, buffer_source=0.0, buffer_dst=0.0, contain='center_overlap', method='max', id_column=None)

Spatially resample attributes from a source layer onto a destination geometry layer.

Combines :func:source_ids_to_dst_geometry (spatial join) with :func:aggregate (Polars reduction), then rejoins the result to dst_gdf's geometry.

Parameters:

Name Type Description Default
source_gdf GeoDataFrame

Source geometries and attributes.

required
dst_gdf Union[GeoDataFrame, GeoSeries]

Destination geometries to receive resampled attributes.

required
columns Optional[List[str]]

Columns from source_gdf to aggregate.

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

See :func:aggregate.

None
buffer_source float

Buffer applied to source geometries before the join.

0.0
buffer_dst float

Buffer applied to destination geometries before the join.

0.0
contain ContainMode

Spatial relationship rule.

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

Aggregation method(s); see :func:aggregate. "density" automatically computes source-feature area in m².

'max'
id_column Optional[str]

Identifier column on dst_gdf (defaults to its index).

None

Returns:

Type Description
GeoDataFrame

GeoDataFrame with dst_gdf's geometry and the aggregated columns.