io

Functions for fetching and converting graphs and network structures.

nx_epsg_conversion

nx_epsg_conversion
(
nx_multigraph : networkx.classes.multigraph.MultiGraph
from_crs_code : int | str
to_crs_code : int | str
)->[ MultiGraph ]

Convert a graph from the from_crs_code EPSG CRS to the to_crs_code EPSG CRS. The to_crs_code must be for a projected CRS. If edge geom attributes are found, the associated LineString geometries will also be converted.

Parameters

nx_multigraph
nx.MultiGraph

A networkX MultiGraph with x and y node attributes in the from_crs_code coordinate system. Optional geom edge attributes containing LineString geoms to be converted.

from_crs_code
int | str

An integer representing a valid EPSG code specifying the CRS from which the graph must be converted. For example, 4326 if converting data from an OpenStreetMap response.

to_crs_code
int | str

An integer representing a valid EPSG code specifying the CRS into which the graph must be projected. For example, 27700 if converting to British National Grid.

Returns

nx.MultiGraph

A networkX MultiGraph with x and y node attributes converted to the specified to_crs_code coordinate system. Edge geom attributes will also be converted if found.

nx_wgs_to_utm

nx_wgs_to_utm
(
nx_multigraph : networkx.classes.multigraph.MultiGraph
)->[ MultiGraph ]

Convert a graph from WGS84 geographic coordinates to UTM projected coordinates. Converts x and y node attributes from WGS84 lng, lat geographic coordinates to the local UTM projected coordinate system. If edge geom attributes are found, the associated LineString geometries will also be converted. The UTM zone derived from the first processed node will be used for the conversion of all other nodes and geometries contained in the graph. This ensures consistent behaviour in cases where a graph spans a UTM boundary.

Parameters

nx_multigraph
nx.MultiGraph

A networkX MultiGraph with x and y node attributes in the WGS84 coordinate system. Optional geom edge attributes containing LineString geoms to be converted.

Returns

nx.MultiGraph

A networkX MultiGraph with x and y node attributes converted to the local UTM coordinate system. If edge geom attributes are present, these will also be converted.

buffered_point_poly

buffered_point_poly
(
lng : float
lat : float
buffer : int
projected : bool = False
)->[ Polygon int ]

Buffer a point and return a shapely Polygon. This function can be used to prepare a buffered point Polygon for passing to osm_graph_from_poly(). Expects WGS 84 / EPSG 4326 input coordinates. If projected is True then a UTM converted polygon will be returned. Otherwise returned as WGS 84 polygon in geographic coords.

Parameters

lng
float

The longitudinal WGS coordinate in degrees.

lat
float

The latitudinal WGS coordinate in degrees.

buffer
int

The buffer distance in metres.

projected
bool

Whether to project the returned polygon to a local UTM projected coordinate reference system.

Returns

geometry.Polygon

A shapely Polygon in WGS coordinates.

int

The UTM EPSG code.

fetch_osm_network

fetch_osm_network
(
osm_request : str
timeout : int = 300
max_tries : int = 3
)->[ Response | None ]

Fetches an OSM response.

This function requires a valid OSM request. If you prepare a polygonal extents then it may be easier to use osm_graph_from_poly(), which would call this method on your behalf and then builds a graph automatically.

Parameters

osm_request
str

A valid OSM request as a string. Use OSM Overpass for testing custom queries.

timeout
int

Timeout duration for API call in seconds.

max_tries
int

The number of attempts to fetch a response before raising.

Returns

requests.Response

An OSM API response.

osm_graph_from_poly

osm_graph_from_poly
(
poly_geom : shapely.geometry.polygon.Polygon
poly_crs_code : int | str = 4326
to_crs_code : int | str | None = None
custom_request : str | None = None
simplify : bool = True
final_clean_distances : tuple[int, ...] = (5, 10)
remove_disconnected : int = 100
cycleways : bool = True
busways : bool = False
green_footways : bool = False
green_service_roads : bool = False
timeout : int = 300
max_tries : int = 3
)->[ MultiGraph ]

Prepares a networkX MultiGraph from an OSM request for the specified shapely polygon. This function will retrieve the OSM response and will automatically unpack this into a networkX graph. Simplification will be applied by default, but can be disabled.

Parameters

poly_geom
shapely.Polygon

A shapely Polygon representing the extents for which to fetch the OSM network.

poly_crs_code
int | str

An integer representing a valid EPSG code for the provided polygon. For example, 4326 if using WGS lng / lat, or 27700 if using the British National Grid.

to_crs_code
int | str

An optional integer representing a valid EPSG code for the generated network returned from this function. If this parameter is provided, then the network will be converted to the specified EPSG coordinate reference system. If not provided, then the OSM network will be projected into a local UTM coordinate reference system.

buffer_dist
int

A distance to use for buffering and cleaning operations. 15m by default.

custom_request
str

An optional custom OSM request. If provided, this must include a “geom_osm” string formatting key for inserting the geometry passed to the OSM API query. See the discussion below.

simplify
bool

Whether to automatically simplify the OSM graph.

final_clean_distances
tuple[int]

A tuple of distances to use for the final cleaning step. These will be applied incrementally. (6, 12) by default.

remove_disconnected
int

Remove disconnected components containing fewer nodes than specified. 100 nodes by default.

cycleways
bool

Whether to include cycleways. True by default.

busways
bool

Whether to include busways. False by default.

green_footways
bool

Whether to include footways contained by green areas. When True, footways contained by green areas are kept but are labelled as footway_green and can be removed manually if required. False by default.

green_service_roads
bool

Whether to include service roads contained by green areas. When True, service roads contained by green areas are kept but are labelled as service_green and can be removed manually if required. False by default.

timeout
int

Timeout duration for API call in seconds.

max_tries
int

The number of attempts to fetch a response before raising.

Returns

nx.MultiGraph

A networkX MultiGraph with x and y node attributes that have been converted to UTM. The network will be simplified if the simplify parameter is True.

Notes

If you wish to provide your own OSM request, then provide a valid OSM API request to the custom_request parameter. The string must contain a geom_osm f-string formatting key. This allows for the geometry parameter passed to the OSM API to be injected into the request. It is also recommended to not use the skel output option so that cityseer can use street name and highway reference information for cleaning purposes. See OSM Overpass for experimenting with custom queries.

The following is the default query which you can adapt for your purposes. Notice the geom_osm f-string interpolation key (for injecting the geometry) and the use of out qt; instead of out skel qt;.

/* https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL */
[out:json];
(way["highway"]
    ["highway"!~"bus_guideway|busway|escape|raceway|proposed|planned|abandoned|platform|
        emergency_bay|rest_area|disused|corridor|ladder|bus_stop|elevator|services"]
    ["area"!="yes"]
    ["footway"!="sidewalk"]
    ["amenity"!~"charging_station|parking|fuel|motorcycle_parking|parking_entrance|parking_space"]
    ["indoor"!="yes"]
    ["level"!="-2"]
    ["level"!="-3"]
    ["level"!="-4"]
    ["level"!="-5"](poly:"{geom_osm}");
);
out body;
>;
out qt;

nx_from_osm

nx_from_osm
(
osm_json : str
)->[ MultiGraph ]

Generate a NetworkX MultiGraph from Open Street Map data.

Parameters

osm_json
str

A json string response from the OSM overpass API, consisting of nodes and ways.

Returns

nx.MultiGraph

A NetworkX MultiGraph with x and y attributes in WGS84 lng, lat geographic coordinates.

nx_from_osm_nx

nx_from_osm_nx
(
nx_multidigraph
node_attributes : list[str] | None = None
edge_attributes : list[str] | None = None
tolerance : float = 0.001
)->[ MultiGraph ]

Copy an OSMnx directed MultiDiGraph to an undirected cityseer MultiGraph. See the OSMnx section of the guide for a more general discussion (and example) on workflows combining OSMnx with cityseer.

x and y node attributes will be copied directly and geometry edge attributes will be copied to a geom edge attribute. The conversion process will snap the shapely LineString endpoints to the corresponding start and end node coordinates.

Note that OSMnx geometry attributes only exist for simplified edges: if a geometry edge attribute is not found, then a simple (straight) shapely LineString geometry will be inferred from the respective start and end nodes.

Other attributes will be ignored to avoid potential downstream misinterpretations of the attributes as a consequence of subsequent steps of graph manipulation, i.e. to avoid situations where attributes may fall out of lock-step with the state of the graph. If particular attributes need to be copied across, and assuming cognisance of downstream implications, then these can be manually specified by providing a list of node attributes keys per the node_attributes parameter or edge attribute keys per the edge_attributes parameter.

Parameters

nx_multidigraph
MultiDiGraph

A OSMnx derived networkX MultiDiGraph containing x and y node attributes, with optional geometry edge attributes containing LineString geoms (for simplified edges).

node_attributes
tuple[str]

Optional node attributes to copy to the new MultiGraph. (In addition to the default x and y attributes.)

edge_attributes
tuple[str]

Optional edge attributes to copy to the new MultiGraph. (In addition to the optional geometry attribute.)

tolerance
float

Tolerance at which to raise errors for mismatched geometry end-points vis-a-vis corresponding node coordinates. Prior to conversion, this method will check edge geometry end-points for alignment with the corresponding end-point nodes. Where these don’t align within the given tolerance an exception will be raised. Otherwise, if within the tolerance, the conversion function will snap the geometry end-points to the corresponding node coordinates so that downstream exceptions are not subsequently raised. It is preferable to minimise graph manipulation prior to conversion to a cityseer compatible MultiGraph otherwise particularly large tolerances may be required, and this may lead to some unexpected or undesirable effects due to aggressive snapping.

Returns

nx.MultiGraph

A cityseer compatible networkX graph with x and y node attributes and geom edge attributes.

nx_from_open_roads

nx_from_open_roads
(
open_roads_path : str | pathlib._local.Path
road_node_layer_key : str = 'road_node'
road_link_layer_key : str = 'road_link'
target_bbox : tuple[int, int, int, int] | tuple[float, float, float, float] | None = None
)->[ MultiGraph ]

Generates a networkX MultiGraph from an OS Open Roads dataset.

Parameters

open_roads_path
str | Path

A valid relative filepath from which to load the OS Open Roads dataset.

target_bbox
tuple[int]

A tuple of integers or floats representing the [s, w, n, e] bounding box extents for which to load the dataset. Set to None for no bounding box.

road_node_layer_key
str

The GPKG layer key for the OS Open Roads road nodes layer. This may change from time to time.

road_link_layer_key
str

The GPKG layer key for the OS Open Roads road links layer. This may change from time to time.

Returns

nx.MultiGraph

A cityseer compatible networkX graph with x and y node attributes and geom edge attributes.

network_structure_from_nx

network_structure_from_nx
(
nx_multigraph : networkx.classes.multigraph.MultiGraph
crs : str | int
)->[ GeoDataFrame GeoDataFrame NetworkStructure ]

Transpose a networkX MultiGraph into a gpd.GeoDataFrame and NetworkStructure for use by cityseer. Calculates length and angle attributes, as well as in and out bearings, and stores this information in the returned data maps.

Parameters

nx_multigraph
nx.MultiGraph

A networkX MultiGraph in a projected coordinate system, containing x and y node attributes, and geom edge attributes containing LineString geoms.

crs
str | int

CRS for initialising the returned structures. This is used for initialising the GeoPandas GeoDataFrame.

Returns

gpd.GeoDataFrame

A gpd.GeoDataFrame with live, weight, and geometry attributes. The original networkX graph’s node keys will be used for the GeoDataFrame index. If nx_multigraph is a dual graph prepared with graphs.nx_to_dual then the corresponding primal edge LineString geometry will be set as the GeoPandas geometry for visualisation purposes using primal_edge for the column name. The dual node Point geometry will be saved in WKT format to the dual_node column.

gpd.GeoDataFrame

A gpd.GeoDataFrame with ns_edge_idx, start_ns_node_idx, end_ns_node_idx, edge_idx, nx_start_node_key ,nx_end_node_key, length, angle_sum, imp_factor, in_bearing, out_bearing, total_bearing, geom attributes.

rustalgos.NetworkStructure

network_structure_from_gpd

network_structure_from_gpd
(
nodes_gdf : geopandas.geodataframe.GeoDataFrame
edges_gdf : geopandas.geodataframe.GeoDataFrame
)->[ NetworkStructure ]

Reassembles a NetworkStructure from cityseer nodes and edges GeoDataFrames. This method is intended for use with “circular” workflows, where a cityseer NetworkX graph has been converted into cityseer nodes and edges GeoDataFrames using network_structure_from_nx. If the resultant GeoDataFrames are saved to disk and reloaded, then this method can be used to recreate the associated NetworkStructure which is required for optimised (rust) functions.

Parameters

nodes_gdf
gpd.GeoDataFrame

A cityseer created nodes gpd.GeoDataFrame where the originating networkX graph’s node keys have been saved as the DataFrame index, and where the columns contain x, y, live, and weight attributes.

edges_gdf
gpd.GeoDataFrame

A cityseer created edges gpd.GeoDataFrame with start_ns_node_idx, end_ns_node_idx, edge_idx, nx_start_node_key, nx_end_node_key, length, angle_sum, imp_factor, in_bearing, out_bearing attributes.

Returns

rustalgos.NetworkStructure

nx_from_cityseer_geopandas

nx_from_cityseer_geopandas
(
nodes_gdf : geopandas.geodataframe.GeoDataFrame
edges_gdf : geopandas.geodataframe.GeoDataFrame
)->[ MultiGraph ]

Write cityseer nodes and edges GeoDataFrames to a networkX MultiGraph. This method is intended for use with “circular” workflows, where a cityseer NetworkX graph has been converted into cityseer nodes and edges GeoDataFrames using network_structure_from_nx. Once metrics have been computed then this method can be used to convert the nodes and edges GeoDataFrames back into a cityseer compatible networkX graph with the computed metrics intact. This is useful when intending to visualise or export the metrics as a networkX graph.

If importing a generic gpd.GeoDataFrame LineString dataset, then use the nx_from_generic_geopandas instead.

Parameters

nodes_gdf
gpd.GeoDataFrame

A gpd.GeoDataFrame with live, weight, and Point geometry attributes. The index will be used for the returned networkX graph’s node keys.

edges_gdf
gpd.GeoDataFrame

An edges gpd.GeoDataFrame as derived from network_structure_from_nx.

Returns

nx.MultiGraph

A networkX graph with geometries and attributes as copied from the input GeoDataFrames.

geopandas_from_nx

geopandas_from_nx
(
nx_multigraph : networkx.classes.multigraph.MultiGraph
crs : str | int
)->[ GeoDataFrame ]

Transpose a cityseer networkX MultiGraph into a gpd.GeoDataFrame representing the network edges. Converts the geom attribute attached to each edge into a GeoPandas GeoDataFrame. This is useful when inspecting or cleaning the network in QGIS. It can then be reimported with nx_from_generic_geopandas

Parameters

nx_multigraph
nx.MultiGraph

A networkX MultiGraph in a projected coordinate system, containing x and y node attributes, and geom edge attributes containing LineString geoms.

crs
str | int

CRS for initialising the returned structures. This is used for initialising the GeoPandas GeoDataFrame.

Returns

gpd.GeoDataFrame

A gpd.GeoDataFrame with edge_idx and geom attributes.

nx_from_generic_geopandas

nx_from_generic_geopandas
(
gdf_network : geopandas.geodataframe.GeoDataFrame
drop_self_loops_dist : int = 50
)->[ MultiGraph ]

Converts a generic LineString gpd.GeoDataFrame to a cityseer compatible networkX MultiGraph. The gpd.GeoDataFrame should be provided in the “primal” form, where edges represent LineString geometries.

Parameters

gdf_network
gpd.GeoDataFrame

A LineString gpd.GeoDataFrame.

drop_self_loops_dist
int

Drop looping street segments shorter than specified distance. 20m by default.

Returns

nx.MultiGraph

A cityseer compatible networkX graph with x and y node attributes and geom edge attributes.