iduedu.UrbanGraph¶
- class iduedu.UrbanGraph(nodes_gdf, edges_gdf, is_multigraph, is_directed, *, edge_direction_column=None, adjacency_weight='time_min', crs=None, graph_type=None, routes=None)[source]¶
Tabular representation of an urban transport graph.
UrbanGraphstores nodes and edges as pandas-compatible tables and builds SciPy CSR adjacency matrices for shortest-path and OD-matrix calculations. Spatial graphs useGeoDataFrametables: nodes are points, edges are lines, and both tables share the graph CRS.- Parameters:
nodes_gdf (
GeoDataFrame|DataFrame) – Node table. Its index is the node id and must be unique. Spatial graphs should use point geometries.edges_gdf (
GeoDataFrame|DataFrame) – Edge table. Required columns areu,v,geometry,length_meterandtime_min. Multigraphs also requirek. Edge endpoint columns referencenodes_gdf.index.is_multigraph (
bool) – Whether multiple edges may exist between the same node pair. If true,(u, v, k)uniquely identifies an edge.is_directed (
bool) – Whether edge direction is respected by adjacency-based algorithms.edge_direction_column (
str|None) – Optional boolean edge column.Truemeans movement is allowed only fromutov;Falsemeans both directions are allowed.adjacency_weight (
str) – Default edge column used when building weighted adjacency matrices.crs (
Any|None) – Optional graph CRS. If omitted, it is inferred from GeoDataFrames when possible.graph_type (
str|None) – Optional semantic graph type such as"drive","walk"or"intermodal".routes (
DataFrame|None) – Optional table of public-transport routes, one row per route variant, indexed byroute_key(seeiduedu.graph.routes). Edges refer to it by theirroute_keycolumn; rows no edge refers to are dropped, so clipping or cutting a graph drops the routes it loses. Street graphs have none (None).
- Raises:
TypeError – If node or edge tables use unsupported types.
ValueError – If graph table contracts are violated.
Methods
Return a copy of the graph with node heights and edge grades.
Count objects and sum their values within a travel cost of every origin.
Return up to k distinct routes by the penalty method.
Return a copy of the graph with travel times that depend on the grade.
Centralities of the nodes within travel-cost thresholds.
Clip the graph by geometry and keep only nodes inside it.
Return connected components for an undirected graph.
Merge groups of nearby nodes, such as the nodes of one junction, into one node.
Return an independent copy of the graph and cached adjacency state.
Run independent source searches.
Diversity of object categories within a travel cost of every origin.
Betweenness of the edges within travel-cost thresholds.
Edge counts, lengths and speeds for every value of an edge column.
Create an empty graph with the requested topology metadata.
Create an
UrbanGraphfrom a NetworkX graph.Measures of size, density, shape and connectivity of the street network.
Yield OD origin-row blocks.
Join this graph with another compatible
UrbanGraph.Return up to k shortest loopless paths.
Keep only the largest graph component.
Return the largest component according to the selected mode.
Network measures around every node, within a travel cost along the network.
Search from the nearest source.
Find the nearest source node and distance for each reachable graph node.
Return the nearest graph edge for each object, with the distance and the position along it.
Return nearest graph node ids for object geometries.
Find the
knearest objects of every origin along the network.Calculate an OD matrix of shortest paths on this graph.
Convert an ordered node path to ordered graph edges.
Project objects onto nearest graph edges and add them to the graph.
Read an
UrbanGraphfrom an.urbangrapharchive.Relabel graph nodes to a dense
RangeIndex.Ratio of network to straight distance between origins and destinations.
Travel edges of one route in the order of travel.
Stop nodes of one route in calling order.
Routes with an edge or a stop in an area.
Return the cost and node route of one shortest path.
Collapse a multigraph to a simple graph.
Search once for distances and/or routes.
Return one shortest path as an ordered list of graph node ids.
Number of streets that meet at every node.
Return strongly connected components.
Return the node-induced subgraph for
nodes.Build a CSR adjacency matrix without changing graph state.
Return a directed version of the graph with an edge direction column.
Convert this graph to a NetworkX graph.
Return an undirected version of the graph.
Stops, routes and stop spacing of every public-transport mode.
Return the straight segments of the edge geometries, each physical segment once.
Rebuild and store the graph adjacency matrix.
Validate node, edge, topology and CRS contracts of the graph.
Return weakly connected components, ignoring edge direction.
Write the graph to an
.urbangrapharchive.- classmethod empty(*, crs=None, is_multigraph=True, is_directed=False, edge_direction_column=None, adjacency_weight='time_min', graph_type=None, routes=None)[source]¶
Create an empty graph with the requested topology metadata.
- validate()[source]¶
Validate node, edge, topology and CRS contracts of the graph.
- Raises:
TypeError – If graph tables use unsupported types.
ValueError – If graph table contracts are violated.
- Return type:
- classmethod read(path, *, validate=True)[source]¶
Read an
UrbanGraphfrom an.urbangrapharchive.- Parameters:
- Return type:
- Returns:
Restored graph instance.
- update_adjacency_matrix(*, nodelist=None, weight=None, multigraph_rule='min')[source]¶
Rebuild and store the graph adjacency matrix.
- Parameters:
- Return type:
csr_matrix- Returns:
Built SciPy CSR adjacency matrix.
- Raises:
KeyError – If
weightis not present inedges_gdf.ValueError – If edge weights are invalid.
- to_csr(*, nodelist=None, weight=None, multigraph_rule='min')[source]¶
Build a CSR adjacency matrix without changing graph state.
- Parameters:
- Return type:
csr_matrix- Returns:
Built SciPy CSR adjacency matrix.
- largest_component(*, mode='auto')[source]¶
Return the largest component according to the selected mode.
- subgraph_by_nodes(nodes)[source]¶
Return the node-induced subgraph for
nodes.- Return type:
- Parameters:
- route_edges(route_key)[source]¶
Travel edges of one route in the order of travel. See
iduedu.route_edges().- Return type:
- Parameters:
route_key (str)
- route_stops(route_key)[source]¶
Stop nodes of one route in calling order. See
iduedu.route_stops().- Return type:
- Parameters:
route_key (str)
- routes_in_area(area)[source]¶
Routes with an edge or a stop in an area. See
iduedu.routes_in_area().- Return type:
- keep_largest_connected_component(*, mode='auto', inplace=False)[source]¶
Keep only the largest graph component.
- Return type:
- Parameters:
- single_source_dijkstra(source_node, *, target_nodes=None, weight='time_min', cutoff=None, reverse=False, output='both', path_storage='eager', dtype=<class 'numpy.float32'>, distance_format='frame')[source]¶
Search once for distances and/or routes. See
iduedu.single_source_dijkstra().- Return type:
- Parameters:
- multi_source_dijkstra(*, source_nodes=None, gdf_sources=None, graph_node_column='graph_node_id', target_nodes=None, weight='time_min', cutoff=None, reverse=False, output='both', path_storage='eager', dtype=<class 'numpy.float32'>, distance_format='frame')[source]¶
Search from the nearest source. See
iduedu.multi_source_dijkstra().- Return type:
- Parameters:
- dijkstra_parallel(*, source_nodes=None, gdf_sources=None, graph_node_column='graph_node_id', target_nodes=None, weight='time_min', cutoff=None, reverse=False, output='both', path_storage='eager', dtype=<class 'numpy.float32'>, max_workers=None, batch_size=None, distance_format='frame')[source]¶
Run independent source searches. See
iduedu.dijkstra_parallel().- Return type:
DataFrame|ShortestPathResult|ndarray|csr_array- Parameters:
gdf_sources (DataFrame | None)
graph_node_column (str)
weight (Literal['length_meter', 'time_min'])
cutoff (float | None)
reverse (bool)
output (Literal['distances', 'paths', 'both'])
path_storage (Literal['eager', 'lazy'])
dtype (dtype)
max_workers (int | None)
batch_size (int | None)
distance_format (Literal['frame', 'dense', 'sparse'])
- single_source_dijkstra_path(source_node, target_node, *, weight='time_min', cutoff=None, reverse=False)[source]¶
Return one shortest path as an ordered list of graph node ids.
- shortest_path(source_node, target_node, *, weight='time_min', cutoff=None, method='bidirectional')[source]¶
Return the cost and node route of one shortest path. See
iduedu.shortest_path().
- k_shortest_paths(source_node, target_node, k, *, weight='time_min', cutoff=None, max_workers=None)[source]¶
Return up to k shortest loopless paths. See
iduedu.k_shortest_paths().
- alternative_paths(source_node, target_node, k=3, *, weight='time_min', penalty=1.5, max_overlap=0.7, max_cost_ratio=1.4, cutoff=None)[source]¶
Return up to k distinct routes by the penalty method. See
iduedu.alternative_paths().
- multi_source_dijkstra_nearest_source(*, source_nodes=None, gdf_sources=None, graph_node_column='graph_node_id', weight='time_min', cutoff=None, reverse=False, dtype=<class 'numpy.float32'>)[source]¶
Find the nearest source node and distance for each reachable graph node.
- od_matrix(*, gdf_origins=None, gdf_destinations=None, origins_nodes=None, destination_nodes=None, graph_node_column='graph_node_id', weight='time_min', dtype=<class 'numpy.float32'>, threshold=None, max_workers=None, cutoff=None, output='distances', path_storage='eager', mode='all_to_all', batch_size=None, method='auto', distance_format='frame')[source]¶
Calculate an OD matrix of shortest paths on this graph.
- Return type:
DataFrame|ShortestPathResult|ndarray|csr_array- Parameters:
gdf_origins (DataFrame | None)
gdf_destinations (DataFrame | None)
graph_node_column (str)
weight (Literal['length_meter', 'time_min'])
dtype (dtype)
threshold (float | None)
max_workers (int | None)
cutoff (float | None)
output (Literal['distances', 'paths', 'both'])
path_storage (Literal['eager', 'lazy'])
mode (Literal['all_to_all', 'pairwise'])
batch_size (int | None)
method (Literal['auto', 'bidirectional', 'astar', 'dijkstra'])
distance_format (Literal['frame', 'dense', 'sparse'])
- iter_od_matrix(*, gdf_origins=None, gdf_destinations=None, origins_nodes=None, destination_nodes=None, graph_node_column='graph_node_id', weight='time_min', dtype=<class 'numpy.float32'>, threshold=None, max_workers=None, cutoff=None, output='distances', path_storage='eager', mode='all_to_all', batch_size=256, method='auto', distance_format='frame')[source]¶
Yield OD origin-row blocks. See
iduedu.iter_od_matrix().- Return type:
Iterator[DataFrame|ShortestPathResult|ndarray|csr_array]- Parameters:
gdf_origins (DataFrame | None)
gdf_destinations (DataFrame | None)
graph_node_column (str)
weight (Literal['length_meter', 'time_min'])
dtype (dtype)
threshold (float | None)
max_workers (int | None)
cutoff (float | None)
output (Literal['distances', 'paths', 'both'])
path_storage (Literal['eager', 'lazy'])
mode (Literal['all_to_all', 'pairwise'])
batch_size (int)
method (Literal['auto', 'bidirectional', 'astar', 'dijkstra'])
distance_format (Literal['frame', 'dense', 'sparse'])
- path_to_edges(path, *, weight='time_min')[source]¶
Convert an ordered node path to ordered graph edges.
- Return type:
- Parameters:
- classmethod from_nx_graph(nx_graph, restore_edge_geom=False, *, check_oneway=True, oneway_column='oneway')[source]¶
Create an
UrbanGraphfrom a NetworkX graph.This constructor is useful for graphs received from external libraries when they already contain node coordinates, CRS metadata and edge attributes such as
length_meterandtime_min. The conversion itself is performed byiduedu.nx_graph2urban_graph().- Parameters:
nx_graph – NetworkX graph, directed graph, multigraph or multidigraph.
restore_edge_geom (
bool) – IfTrue, empty edge geometries are restored as straight segments between endpoint nodes.check_oneway (
bool) – IfTrueandoneway_columnexists on edges, that column is used as the edge direction column.oneway_column (
str) – Boolean edge attribute that marks one-way movement.
- Return type:
- Returns:
Converted
UrbanGraphinstance.
- to_nx_graph()[source]¶
Convert this graph to a NetworkX graph.
The method delegates to
iduedu.urban_graph2nx_graph()and preserves node and edge attributes where possible.- Returns:
NetworkX graph type matching this graph topology.
- simplify_multiedges(*, weight='time_min', rule='min', inplace=False)[source]¶
Collapse a multigraph to a simple graph.
For each node pair, one edge is selected by the
weightcolumn.rule="min"keeps the smallest weight andrule="max"keeps the largest weight. Functional equivalent:iduedu.simplify_multiedges().- Parameters:
- Return type:
- Returns:
Simplified
UrbanGraph.
- relabel(*, inplace=False)[source]¶
Relabel graph nodes to a dense
RangeIndex.Functional equivalent:
iduedu.relabel_urban_graph().- Parameters:
inplace (
bool) – IfTrue, replace this object with the relabeled graph.- Return type:
- Returns:
UrbanGraphwith updated node indexes and edge endpoints.
- clip(polygon, *, inplace=False)[source]¶
Clip the graph by geometry and keep only nodes inside it.
Edges are retained only when both endpoints remain in the graph. Node ids are preserved; call
relabel()if dense labels are needed. Functional equivalent:iduedu.clip_urban_graph().- Parameters:
polygon – Shapely geometry in EPSG:4326 (as
territoryof the graph builders), or a GeoSeries / GeoDataFrame in any CRS.inplace (
bool) – IfTrue, replace this object with the clipped graph.
- Return type:
- Returns:
Clipped
UrbanGraph.
- join(other, *, graph_type=None, node_conflict='left', inplace=False)[source]¶
Join this graph with another compatible
UrbanGraph.Shared node indexes are allowed and resolved with
node_conflict. Duplicate edge keys are treated as conflicts.- Parameters:
other (
UrbanGraph) – Graph to append.graph_type (
str|None) – Optional graph type for the result. IfNone, keep this graph type.node_conflict (
str) – Which side wins when node indexes overlap:"left"or"right".inplace (
bool) – IfTrue, replace this object with the joined graph.
- Return type:
- Returns:
Joined
UrbanGraph.
- to_directed(*, edge_direction_column='oneway', default_direction_value=False, inplace=False)[source]¶
Return a directed version of the graph with an edge direction column.
Functional equivalent:
iduedu.to_directed().- Parameters:
- Return type:
- Returns:
Directed
UrbanGraph.
- to_undirected(*, inplace=False)[source]¶
Return an undirected version of the graph.
Functional equivalent:
iduedu.to_undirected().- Parameters:
inplace (
bool) – IfTrue, replace this object with the undirected graph.- Return type:
- Returns:
Undirected
UrbanGraph.
- nearest_nodes(objects_gdf, *, graph_node_column='graph_node_id')[source]¶
Return nearest graph node ids for object geometries.
Functional equivalent:
iduedu.nearest_nodes().- Parameters:
objects_gdf (
GeoDataFrame) – GeoDataFrame with geometries to match to graph nodes.graph_node_column (
str) – Name assigned to the returnedSeries.
- Return type:
- Returns:
Series indexed like
objects_gdfwith nearest node ids as values.
- nearest_edges(objects_gdf, *, max_dist=None)[source]¶
Return the nearest graph edge for each object, with the distance and the position along it.
Functional equivalent:
iduedu.nearest_edges().- Return type:
- Parameters:
objects_gdf (GeoDataFrame)
max_dist (float | None)
- unique_segments(*, precision=0.01)[source]¶
Return the straight segments of the edge geometries, each physical segment once.
Functional equivalent:
iduedu.unique_segments().- Return type:
- Parameters:
precision (float)
- consolidate_intersections(tolerance=10.0, *, max_span=None, return_mapping=False)[source]¶
Merge groups of nearby nodes, such as the nodes of one junction, into one node.
Functional equivalent:
iduedu.consolidate_intersections().
- project_objects(objects_gdf, speed_m_per_min, *, max_dist=None, add_link_edge=True, inplace=False)[source]¶
Project objects onto nearest graph edges and add them to the graph.
The method creates graph nodes for objects, projects their representative points onto nearest edges, splits those edges when needed and adds connector edges. It is convenient for in-memory preparation of buildings, services or other objects before OD-matrix calculations. For backend workflows where graph changes should be persisted separately, use
iduedu.project_objects2urban_graph().- Parameters:
objects_gdf (
GeoDataFrame) – Objects with a unique index and geometry. The index becomes theobject2node_mapindex.speed_m_per_min (
float) – Movement speed on connector edges, in meters per minute. For 5 km/h use5 * 1000 / 60.max_dist (
float|None) – Optional maximum distance to the nearest edge. IfNone, no distance limit is applied.add_link_edge (
bool) – IfTrue, create a dedicated object node and connector edge. IfFalse, map objects to projection nodes on the graph.inplace (
bool) – IfTrue, apply changes to this graph.
- Return type:
- Returns:
Pair
(graph, object2node_map).object2node_mapis indexed by the original object index and contains graph node ids.
- graph_stats(*, area=None, zones=None, edge_types=None, boundary_buffer=1.0, precision=0.01)[source]¶
Measures of size, density, shape and connectivity of the street network.
Functional equivalent:
iduedu.graph_stats().- Return type:
- Parameters:
area (BaseGeometry | GeoSeries | GeoDataFrame | None)
zones (GeoSeries | GeoDataFrame | None)
boundary_buffer (float | None)
precision (float)
- edge_stats(by='type', *, area=None, precision=0.01)[source]¶
Edge counts, lengths and speeds for every value of an edge column.
Functional equivalent:
iduedu.edge_stats().- Return type:
- Parameters:
by (str)
area (BaseGeometry | GeoSeries | GeoDataFrame | None)
precision (float)
- transport_stats(*, modes=None)[source]¶
Stops, routes and stop spacing of every public-transport mode.
Functional equivalent:
iduedu.transport_stats().
- local_stats(radius, *, weight='length_meter', nodes=None, edge_types=None, max_workers=None)[source]¶
Network measures around every node, within a travel cost along the network.
Functional equivalent:
iduedu.local_stats().
- streets_per_node(*, edge_types=None)[source]¶
Number of streets that meet at every node.
Functional equivalent:
iduedu.streets_per_node().
- route_directness(*, origins_nodes=None, destination_nodes=None, gdf_origins=None, gdf_destinations=None, graph_node_column='graph_node_id', sample=200, seed=0, max_workers=None)[source]¶
Ratio of network to straight distance between origins and destinations.
Functional equivalent:
iduedu.route_directness().
- nearest_objects(*, gdf_origins=None, gdf_objects=None, origins_nodes=None, object_nodes=None, k=1, cutoff=None, weight='time_min', direction='from', graph_node_column='graph_node_id', max_workers=None)[source]¶
Find the
knearest objects of every origin along the network.Functional equivalent:
iduedu.nearest_objects().- Return type:
- Parameters:
- aggregate_objects(cutoff, *, gdf_origins=None, gdf_objects=None, origins_nodes=None, object_nodes=None, columns=None, weight='time_min', decay=None, beta=None, direction='from', graph_node_column='graph_node_id', max_workers=None)[source]¶
Count objects and sum their values within a travel cost of every origin.
Functional equivalent:
iduedu.aggregate_objects().
- diversity(cutoff, category, *, gdf_objects, gdf_origins=None, origins_nodes=None, values=None, hill_order=2.0, weight='time_min', decay=None, beta=None, direction='from', graph_node_column='graph_node_id', max_workers=None)[source]¶
Diversity of object categories within a travel cost of every origin.
Functional equivalent:
iduedu.diversity().- Return type:
- Parameters:
- centrality(measures=('reach', 'harmonic', 'gravity'), *, cutoffs=None, weight='length_meter', beta=None, node_weights=None, direction='from', area=None, sample=None, seed=0, max_workers=None)[source]¶
Centralities of the nodes within travel-cost thresholds.
Functional equivalent:
iduedu.centrality().
- edge_betweenness(*, cutoffs=None, weight='length_meter', node_weights=None, sample=None, seed=0, max_workers=None)[source]¶
Betweenness of the edges within travel-cost thresholds.
Functional equivalent:
iduedu.edge_betweenness().
- add_elevation(elevation, *, column='elevation', method='linear', sample_distance=20.0, structure_columns=('bridge', 'tunnel'), band=1)[source]¶
Return a copy of the graph with node heights and edge grades.
Functional equivalent:
iduedu.add_elevation().
- apply_grade_speed(model='tobler', *, edge_types=None)[source]¶
Return a copy of the graph with travel times that depend on the grade.
Functional equivalent:
iduedu.apply_grade_speed().- Return type:
- Parameters: