UrbanAccessAnalyzer.graph_ops¶
Street-graph topology operations on Polars node/edge tables.
Replaces the previous networkx/osmnx-backed graph_processing.py. The
graph is represented purely as two Polars DataFrames:
nodes:node_id (i64), x (f64), y (f64)(projected, meters).edges:u (i64), v (i64), length_m (f64), geometry_wkb (binary), plus whatever extra attribute columns (highway, ...) the caller kept.
Geometry itself has no Polars-native representation, so it is stored as WKB
bytes and manipulated with vectorized shapely
<https://shapely.readthedocs.io/en/stable/manual.html>_ array functions
(shapely.STRtree for nearest-neighbor/nearest-edge queries,
shapely.line_locate_point/shapely.ops.substring for projecting points
onto edges and splitting them). This is real geometric computation, not a
graph library, so it stays even though networkx/geopandas do not.
Methodology:
- Projection: nodes/edges are projected to a local UTM CRS with
pyproj.Transformerso thatlength_mand all distance thresholds are true meters, not degrees. - Chain contraction (simplification): an OSM way is frequently split into
many short edges at every intersection-irrelevant vertex OSM happened to
record. A node of undirected degree exactly 2 that is not "protected" (e.g.
a snapped point of interest) carries no routing information -- it can be
merged into a single edge spanning its two neighbors. This is done
iteratively (each pass contracts one layer of degree-2 chains) with a
Polars self-join, and geometries are merged with
shapely.line_merge. - Point snapping: a query point is assigned to its nearest edge via an
STRtree nearest-neighbor query, then projected onto that edge
(
shapely.line_locate_point) and the edge is split there (shapely.ops.substring) into two new edges plus a new node, exactly like osmnx'sadd_points_to_graphdid previously but computed vectorized instead of via the WKT-string edge-splitting code in the oldgraph_processing.py.
Source for the degree-2 contraction concept: standard graph-simplification
technique used by OSM routing engines (e.g. osmnx's simplify_graph,
https://osmnx.readthedocs.io).
project(nodes, edges, crs=None)
¶
Project lon/lat nodes and WKB edge geometry into a metric CRS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table with |
required |
edges
|
DataFrame
|
Edge table with a |
required |
crs
|
Optional[str]
|
Target CRS (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
DataFrame
|
and |
str
|
target CRS. |
crop_by_aoi(nodes, edges, aoi)
¶
Crop a graph to edges intersecting an AOI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table ( |
required |
edges
|
DataFrame
|
Edge table with |
required |
aoi
|
GeoDataFrame | GeoSeries
|
AOI geometry. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
DataFrame
|
and nodes referenced by at least one kept edge. |
connected_component_labels(nodes, edges)
¶
Label every node with its (undirected) connected-component id.
Uses scipy.sparse.csgraph.connected_components (the same
sparse-matrix graph-algorithm family UrbanAccessAnalyzer.routing
already relies on for Dijkstra, rather than adding a networkx
dependency this package deliberately avoids -- see this module's own
docstring). Cheap: builds one sparse adjacency matrix over len(nodes)
nodes and len(edges) edges, no all-pairs work.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table with a |
required |
edges
|
DataFrame
|
Edge table with |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
labeling -- only equality between two rows' labels is meaningful). |
crop_by_aoi_connected(nodes, edges, aoi, all_nodes=None, all_edges=None)
¶
crop_by_aoi, but guarantees a connected graph for every SIMPLE polygon of aoi.
2026-09-02, explicit user request: "make sure we have a complete
connected graph per unique polygon of the aoi... so no multipolygon,
per simple polygon... include [a non-pedestrian road] if really needed
for connectivity of the graph then... consider the road walkable."
Plain crop_by_aoi only filters by geometric intersection -- a
pedestrian-only (or otherwise road-type-restricted) network can come
out of that crop genuinely fragmented into disconnected islands (e.g.
a residential cluster whose only real link to the rest of the network
is a road type the profile excluded), which silently makes some
origin/destination pairs unroutable even though a real path exists on
the ground.
aoi is exploded into its individual (non-multi) polygons first --
each is cropped and repaired independently, then the results are
concatenated (deduplicated on node_id/(u, v) for nodes shared
across adjacent polygons). Two real AOI polygons are not assumed to be
connected to each other at all (they may be genuinely separate, e.g.
two disjoint districts) -- only connectivity WITHIN each one is
guaranteed.
Repair strategy per polygon
- Crop
nodes/edgesto the polygon (crop_by_aoi). - Label connected components (
connected_component_labels). If there's only one, this polygon's graph is already fine. - Otherwise, if a wider-profile graph is available (
all_nodes/all_edges, e.g. built withnetwork_type="all"), crop THAT to the same polygon. If the wider graph is itself connected (the normal case -- OSM's full road network, unlike its pedestrian subset, is almost always contiguous within a real developed area), it fully replaces this polygon's edges/nodes: every road that was needed for connectivity is now included and is treated as walkable, exactly the "include it and consider it walkable" request, not a penalized/avoided edge. - If still disconnected (no wider graph given, or the wider graph is ALSO fragmented -- e.g. a real island with no bridge), fall back to keeping only the largest connected component -- the standard routing-graph practice of dropping genuinely-isolated islands rather than leaving unroutable dead-end fragments in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table (already the road-type-filtered, e.g. |
required |
edges
|
DataFrame
|
Edge table (same profile), |
required |
aoi
|
GeoDataFrame | GeoSeries
|
AOI geometry -- may be a single polygon, a MultiPolygon, or a GeoDataFrame/GeoSeries with several rows; every constituent simple polygon is handled independently. |
required |
all_nodes
|
Optional[DataFrame]
|
Optional wider-profile node table (e.g.
|
None
|
all_edges
|
Optional[DataFrame]
|
Optional wider-profile edge table, paired with
|
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
DataFrame
|
together, deduplicated. |
grid_cluster_labels(points, cell_size, id_col='node_id', x_col='x', y_col='y', protected_ids=None)
¶
Two-offset-grid clustering: bounds every cluster to ~cell_size, no chaining.
Overlays two square grids of cell_size over the point set, the second
offset by half a cell in both axes, so every point falls into exactly
one cell of each grid -- two candidate clusters. Each point joins
whichever of its two candidate cells has the nearer mean position, then
(since membership just changed) that mean is implicitly recomputed the
next time a caller aggregates by the returned _cluster label (e.g.
points.join(labels).group_by("_cluster").agg(pl.col(x_col).mean(),
...)) -- a single further group-by, not an iterative/converging
k-means. The two-grid overlap (vs. a single hard grid) avoids the
artifact where two points a meter apart, straddling one grid line,
would otherwise never cluster together.
Unlike chaining nearby points transitively (e.g. connected components
over a graph of short edges), a cluster here can never span more than
roughly cell_size regardless of how many points or how long a chain
of short links connects them -- which is what "chain" clustering can
do on a curvy street built from many short segments, collapsing a much
longer real-world span into one point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
DataFrame
|
Table with |
required |
cell_size
|
float
|
Grid cell side length (meters). Every cluster's extent is bounded to roughly this scale. |
required |
id_col
|
str
|
Unique id column name. |
'node_id'
|
x_col
|
str
|
X-coordinate column name. |
'x'
|
y_col
|
str
|
Y-coordinate column name. |
'y'
|
protected_ids
|
Optional[set]
|
Ids that must stay their own singleton cluster (never merged with another point). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
necessarily numeric) -- one row per input point. |
simplify(nodes, edges, cluster_distance, protected_node_ids=None)
¶
Cluster nearby nodes and collapse the graph onto the cluster centroids.
Two-step, fully vectorized simplification designed for very large graphs (no per-edge/per-node Python loop):
- Clustering: nodes are grid-clustered (:func:
grid_cluster_labels,cell_size=cluster_distance) -- every cluster's extent is bounded to roughlycluster_distance, unlike chaining nodes transitively through a sequence of short edges (which has no such bound: a long curvy street built from many short segments could otherwise collapse entirely into one point). Each cluster collapses to a single node at the mean coordinate of its members.protected_node_ids(e.g. nodes a POI was snapped to) never merge into a cluster with another node -- they stay singleton clusters. - Edge reduction: every edge's endpoints are remapped to their
cluster's representative node. Edges whose two endpoints land in the
same cluster are dropped (internal edges). Among edges left connecting
the same two clusters, only the straightest one is kept: the one
minimizing
|real_edge_length - straight_line_distance_between_cluster_centroids|. The kept edge's geometry has its first/last coordinate snapped to the new cluster centroid (interior vertices untouched) so the linestring stays continuous and valid, and its length is recomputed from that adjusted geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table ( |
required |
edges
|
DataFrame
|
Directed edge table ( |
required |
cluster_distance
|
float
|
Grid cell size used to cluster nodes (meters) --
see :func: |
required |
protected_node_ids
|
Optional[list[int]]
|
Node ids to keep as their own singleton cluster. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
DataFrame
|
reduced, geometry-corrected edge table. |
snap_points(nodes, edges, point_geoms, max_dist=None, min_edge_length=1.0)
¶
Snap external points onto the nearest graph edge, splitting it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table ( |
required |
edges
|
DataFrame
|
Directed edge table ( |
required |
point_geoms
|
ndarray
|
Array of shapely |
required |
max_dist
|
Optional[float]
|
Maximum snap distance; points farther than this from every
edge are not snapped (returned as |
None
|
min_edge_length
|
float
|
If the projected point falls within this distance of an existing edge endpoint, it is snapped to that endpoint instead of creating a near-duplicate node. |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
DataFrame
|
with new nodes/edges inserted at each split, and a list the same |
list[Optional[int]]
|
length as |
tuple[DataFrame, DataFrame, list[Optional[int]]]
|
to ( |
nearest_nodes(nodes, point_geoms, max_dist=None)
¶
Find the nearest graph node to each query point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
DataFrame
|
Node table ( |
required |
point_geoms
|
ndarray
|
Array of shapely |
required |
max_dist
|
Optional[float]
|
Maximum search distance; points with no node within this
distance return |
None
|
Returns:
| Type | Description |
|---|---|
list[Optional[int]]
|
List (same length as |
list[Optional[int]]
|
|