Graph operations¶
Overview¶
The editing functions inspect, cut, join and transform UrbanGraph objects, and attach objects such as
buildings or stops to them. They return new graphs and leave the source unchanged; the matching
UrbanGraph methods change the graph itself with inplace=True.
Task |
Functions |
|---|---|
Connectivity |
|
Cutting and joining |
|
Topology |
|
Objects |
|
Scenario edits |
|
Storage and checks |
Connectivity¶
A route exists only inside one connected component. connected_components() finds the components of an
undirected graph; on a directed graph, weakly_connected_components() ignores the direction and
strongly_connected_components() keeps it, so every node of a strong component reaches every other. The
number_* functions count the components and the largest_* functions return the node ids of the largest
one. keep_largest_connected_component() returns the graph cut to it, strong components on directed graphs.
The builders do the same with keep_largest_subgraph=True. Components are computed in the Rust core.
Cutting and joining¶
subgraph_by_nodes() keeps the given nodes and the edges between them. clip_urban_graph() keeps the part
of a graph inside a polygon; a bare shapely polygon is read in EPSG:4326, as territory in the graph builders,
and a GeoSeries or GeoDataFrame in its own CRS. join_urban_graphs() concatenates the tables of compatible
graphs, and relabel_urban_graph() renumbers the nodes 0 .. n-1.
With by="coordinates", relabel_urban_graph() packs the latitude and longitude of every node, in units
of 1e-7 degree (the precision of OpenStreetMap), into one int64 id. A street node then keeps its id when the graph
is built again from newer data, and the graphs of two neighbouring territories share the ids of their common
nodes. Two nodes closer than 1e-7 degree (about 1 cm) would get one id, and the function raises instead. Public
transport graphs have such nodes, for example the stops of several routes at one platform; with
on_duplicate="hash" each of them gets a negative id hashed from the coordinate id, its attributes and its rank
among equal nodes, which stays the same when the graph is built again in the same way.
coordinate_node_ids() computes the ids of any points, for example new nodes of a service.
Topology¶
to_directed() returns a directed graph whose direction comes from a boolean column, oneway by default;
edges without a value get default_direction_value (False: both directions). to_undirected() drops the
direction. simplify_multiedges() keeps one of the parallel edges between two nodes, the cheapest by
weight with rule="min" (the default).
consolidate_intersections() merges the nodes OSM draws for one junction, for example where two dual
carriageways cross. Nodes closer than tolerance form clusters (single linkage), and a cluster is split into the
parts that edges inside it connect, so a bridge above a road stays apart. Each part becomes one node at the mean
position of its members, and the edges keep their geometry with moved end points. Parts wider than max_span
(four times the tolerance by default) stay unmerged. The function serves network statistics and centralities;
it changes routing, because turns and one-way links inside a junction disappear.
simplify_graph() merges chains of edges through nodes of degree two into single edges, in any graph. Two edges
are merged at a node when they are the only edges there, the values of keys (by default every column except the
costs and the geometry) are equal, and their directions agree: two-way edges always, one-way edges only head to
tail. An edge drawn against the chain is turned, so the merged geometry runs from u to v; length_meter
and the time_* columns are summed. keep_nodes keeps the nodes other tables refer to; the nodes a walk graph
joins public transport at (platforms, subway entrances and exits) always stay. The merging runs in the
Rust core, about one second for a million edges.
unique_segments() returns the straight pieces of the edge geometries with every physical segment once, also
where two edges of a two-way street or a there-and-back pair share their points. Its total length is the network
length on the ground, which graph_stats() uses.
Objects¶
nearest_nodes() returns the nearest graph node of every object, and nearest_edges() the nearest edge
with the distance to it and the position along it. Objects are matched by their representative point, a point
inside the geometry. Routing and analysis functions take objects with a graph_node_id column as they are and
match the others to their nearest nodes themselves.
project_objects2urban_graph() inserts objects into the graph. The nearest edge of every object within
max_dist is split at the projection point, and with add_link_edge=True (the default) a new node for the
object and a link edge at speed_m_per_min join it to that point. The function returns the changes,
an UrbanGraphChanges with the nodes and edges to add and the edges to delete, and the node of every
object. apply_urban_graph_changes() applies them; UrbanGraph.project_objects() does both in one call.
Keeping the changes apart lets a service store them in its own tables.
Each piece gets a share of the original edge’s length_meter and time_min proportional to its geometric length
in the CRS used for splitting. The pieces preserve the original totals up to floating-point error. A link edge uses
its geometric length rounded to three decimal places and that length divided by speed_m_per_min, with the time
rounded to two decimal places.
Scenario edits¶
A planning scenario closes streets, changes speeds or adds new links. Ids of nodes and edges change when the graph
is built again from newer OSM data, and a simplified edge has no OSM way id, so a stored scenario keeps its edits
as lines. GraphEdits holds three tables: add with the lines of new edges and their attributes,
remove with anchor lines of the network to remove and update with anchor lines and the new values of the
edges along them. resolve_graph_edits() binds them to the current graph and returns an
UrbanGraphChanges and a report of the edits it could not bind.
An anchor selects the edges that run along it within tolerance; a street that only crosses the anchor is not
selected. An edge covered in part is split at the ends of the anchor, so only the covered part changes, even when
the rebuilt graph has its junctions elsewhere. In a directed graph direction="along" limits an edit to the
direction the anchor is drawn in, and a two-way edge becomes two one-way edges. speed_kmh in update sets
time_min from the edge length. Each end of an added line is attached to a node within tolerance, or splits
the nearest edge there, or becomes a new node. edge_types keeps the edits on one layer, for example the
walking edges of an intermodal graph, whose transit edges often run along the same streets.
An anchor that the graph covers by less than min_coverage of its length, or an added line that would join a
node to itself, is skipped and reported. UrbanGraphChanges also sets new values on edges by key with
edges_to_update; apply_urban_graph_changes() deletes edges first, then updates, then adds.
edits = GraphEdits(
remove=closed_streets, # lines in any CRS
update=slow_zone.assign(speed_kmh=20),
add=new_paths.assign(highway="footway"),
)
changes, report = resolve_graph_edits(walk, edits, tolerance=5, speed_kmh=5)
scenario = apply_urban_graph_changes(walk, changes)
graph, home_nodes = walk.project_objects(homes, 5 * 1000 / 60, max_dist=200)
homes["graph_node_id"] = home_nodes # used by od_matrix, aggregate_objects, ...
Storage and checks¶
write_urban_graph() and read_urban_graph() store and read .urbangraph archives, and
validate_graph() checks the tables after your own edits (see The UrbanGraph model).
Functions¶
Return connected components of an undirected |
|
Return weakly connected components. |
|
Return strongly connected components. |
|
Return the number of connected components in an undirected graph. |
|
Return the number of weakly connected components. |
|
Return the number of strongly connected components. |
|
Return the largest connected component of an undirected graph. |
|
Return the largest weakly connected component. |
|
Return the largest strongly connected component. |
|
Return the largest component according to the selected connectivity mode. |
|
Keep only the largest component of an |
|
Return an induced |
|
Clip graph nodes by geometry and keep only edges with retained endpoints. |
|
Join two compatible |
|
Relabel node ids and update edge endpoints. |
|
Stable int64 node ids packed from the coordinates of points. |
|
Return a directed copy of |
|
Return an undirected copy of |
|
Collapse a multigraph |
|
Merge chains of edges through nodes of degree two into single edges. |
|
Merge groups of nearby nodes, such as the several nodes of one junction of dual carriageways, into one. |
|
Return the straight segments the edge geometries are made of, each physical segment once. |
|
Return the nearest graph node id for each input geometry. |
|
Return the nearest graph edge for each input geometry, with the distance and the position along it. |
|
Prepare graph changes that connect objects to their nearest edges. |
|
Apply prepared changes to an |
|
Set of table changes that can be applied to an |
|
Edits of a graph given by lines in any CRS, resolved by |
|
Bind geometric edits to the current graph. |
|
Read an |
|
Write an |
|
Validate all node, edge, topology and CRS contracts of an |
NetworkX is not installed with IduEdu. Install it separately (pip install networkx) to use the helpers below;
without it they raise ImportError when called.
Convert an |
|
Convert a NetworkX graph to an |
|
Convert a NetworkX graph to GeoDataFrames for nodes and/or edges. |
|
Convert a GeoDataFrame of LineStrings into a directed graph (nx.DiGraph). |
|
Keep only the largest connected component of a NetworkX graph. |
|
Clip a NetworkX graph by a polygon and return the induced subgraph. |
|
Read a GML file into a NetworkX graph and cast edge geometry from WKT strings to shapely. |
|
Write a NetworkX graph to GML, coercing node coordinates to plain floats. |
|
Reproject node coordinates (x, y) and edge geometries to a new CRS (in place). |
Figures¶
Vasilyevsky Island. Left and middle: junctions of the drive graph before and after
consolidate_intersections(drive, 15), which reduces the district from 900 to 678 nodes; carriageways more
than 15 m apart stay separate. Right: buildings joined to the nearest walkable edge by
UrbanGraph.project_objects(); orange lines are the new link edges.¶
Limitations¶
consolidate_intersections()works with distances only and can join nodes that are close but belong to different junctions; check the result on a map and settoleranceto the width of the junctions.project_objects2urban_graph()attaches every object to one edge; an object far from any edge (beyondmax_dist) stays unattached.resolve_graph_edits()finds edges by distance: two streets closer thantoleranceand running side by side are both selected by an anchor along one of them. Settolerancebelow the distance between parallel carriageways, or limit the edits withedge_types.
Example notebook¶
Graph operations, Connectivity diagnostics, Objects, nearest nodes, and graph projection