Skip to content

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.Transformer so that length_m and 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's add_points_to_graph did previously but computed vectorized instead of via the WKT-string edge-splitting code in the old graph_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 node_id, lon, lat columns (EPSG:4326), as produced by :func:UrbanAccessAnalyzer.osm_io.load_pbf.

required
edges DataFrame

Edge table with a geometry_wkb column in EPSG:4326.

required
crs Optional[str]

Target CRS (e.g. "EPSG:32633"). If None, the UTM zone covering the nodes' centroid is used.

None

Returns:

Type Description
DataFrame

Tuple (nodes, edges, crs) where nodes gains x, y columns

DataFrame

and edges' geometry_wkb/length_m are recomputed in the

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 (node_id + coordinate columns).

required
edges DataFrame

Edge table with u, v, geometry_wkb (CRS must match aoi or be already-projected consistently with it).

required
aoi GeoDataFrame | GeoSeries

AOI geometry.

required

Returns:

Type Description
DataFrame

Tuple (nodes, edges) filtered to the AOI: edges intersecting it,

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 node_id column.

required
edges DataFrame

Edge table with u, v columns (values must be node_ids present in nodes).

required

Returns:

Type Description
DataFrame

nodes with an added _component column (int, arbitrary

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
  1. Crop nodes/edges to the polygon (crop_by_aoi).
  2. Label connected components (connected_component_labels). If there's only one, this polygon's graph is already fine.
  3. Otherwise, if a wider-profile graph is available (all_nodes/ all_edges, e.g. built with network_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.
  4. 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. "walk", profile), node_id + coordinate columns.

required
edges DataFrame

Edge table (same profile), u, v, geometry_wkb (CRS consistent with aoi).

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. network_type="all") covering at least the same extent as nodes, used only as a source of bridging edges/nodes.

None
all_edges Optional[DataFrame]

Optional wider-profile edge table, paired with all_nodes.

None

Returns:

Type Description
DataFrame

Tuple (nodes, edges), each polygon's contribution unioned

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 id_col, x_col, y_col (projected, meters).

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 id_col and _cluster (a label, not

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):

  1. Clustering: nodes are grid-clustered (:func:grid_cluster_labels, cell_size=cluster_distance) -- every cluster's extent is bounded to roughly cluster_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.
  2. 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 (node_id, x, y, projected CRS).

required
edges DataFrame

Directed edge table (u, v, length_m, geometry_wkb, edge_uid, plus any extra attribute columns), as produced by :func:UrbanAccessAnalyzer.osm_io.load_pbf + :func:project. edge_uid must be shared between the forward/backward rows of the same original two-way segment so they're kept or dropped together.

required
cluster_distance float

Grid cell size used to cluster nodes (meters) -- see :func:grid_cluster_labels.

required
protected_node_ids Optional[list[int]]

Node ids to keep as their own singleton cluster.

None

Returns:

Type Description
DataFrame

Tuple (nodes, edges): one row per cluster in nodes, and the

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 (node_id, x, y at minimum, projected CRS matching edges).

required
edges DataFrame

Directed edge table (u, v, length_m, geometry_wkb, plus extra attribute columns).

required
point_geoms ndarray

Array of shapely Point geometries, in the same CRS as nodes/edges.

required
max_dist Optional[float]

Maximum snap distance; points farther than this from every edge are not snapped (returned as None).

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 (nodes, edges, point_node_ids): updated node/edge tables

DataFrame

with new nodes/edges inserted at each split, and a list the same

list[Optional[int]]

length as point_geoms giving the node id each point was snapped

tuple[DataFrame, DataFrame, list[Optional[int]]]

to (None where no edge was within max_dist).

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 (node_id, x, y), projected CRS.

required
point_geoms ndarray

Array of shapely Point geometries in the same CRS.

required
max_dist Optional[float]

Maximum search distance; points with no node within this distance return None.

None

Returns:

Type Description
list[Optional[int]]

List (same length as point_geoms) of nearest node_id or

list[Optional[int]]

None.