GOSTnets package

Contents

GOSTnets package#

Submodules#

GOSTnets.calculate_od_raw module#

GOSTnets.calculate_od_raw.calculateOD_csv(G, originCSV, destinationCSV='', oLat='Lat', oLon='Lon', dLat='Lat', dLon='Lon', crs='epsg:4326', fail_value=-1, weight='time', calculate_snap=False)#

Calculate OD matrix from csv files of points

Parameters
  • G – describes the road network. Often extracted using OSMNX

  • origins (str) – path to csv file with locations for calculating access

  • destinations (str) – path to csv with destination locations for calculating access

  • oLat (str) – Origin latitude field

  • oLon (str) – Origin longitude field

  • dLat (str) – Destination latitude field

  • dLon (str) – Destination longitude field

  • crs (str) – crs of input origins and destinations, defaults to ‘epsg:4326’

  • fail-value (int) – value to put in OD matrix if no route found, defaults to -1

  • weight (str) – variable in G used to define edge impedance, defaults to ‘time’

  • calculate_snap (bool) – variable to add snapping distance to travel time, default is false

Returns

2d OD matrix with columns as index of origins and rows as index of destinations

Return type

numpy array

GOSTnets.calculate_od_raw.calculateOD_gdf(G, origins, destinations, fail_value=-1, weight='time', calculate_snap=False, wgs84='epsg:4326')#

Calculate Origin destination matrix from GeoDataframes

Parameters
  • G (networkx graph) – describes the road network. Often extracted using OSMNX

  • origins (geopandas dataframe) – source locations for calculating access

  • destinations (geopandas dataframe) – destination locations for calculating access

  • calculate_snap (boolean, optional) – variable to add snapping distance to travel time, default is false

  • wgs84 (CRS dictionary, optional) – CRS of road network to which the GDFs are projected

Returns

2d OD matrix with columns as index of origins and rows as index of destinations

Return type

numpy array

GOSTnets.calculate_od_raw.calculate_gravity(od, oWeight=[], dWeight=[], decayVals=[0.01, 0.005, 0.001, 0.0007701635, 0.0003850818, 0.0001925409, 9.62704e-05, 3.85082e-05, 1e-05])#

Calculate gravity model values for origin-destination (OD) matrix.

Parameters
  • od (numpy.ndarray) – Origin-destination matrix.

  • oWeight (list, optional) – List of weights for each origin. Defaults to an empty list.

  • dWeight (list, optional) – List of weights for each destination. Defaults to an empty list.

  • decayVals (list, optional) – List of decay values for market access. Defaults to a predefined list.

Returns

DataFrame containing gravity model values for each origin-destination pair.

Return type

pandas.DataFrame

GOSTnets.conversion_utils module#

GOSTnets.conversion_utils.rasterize_od_results(inD, outFile, field, template=None)#

Convert gridded point data frame to raster of commensurate size and resolution

Parameters
  • inD (geopandas data frame) – OD matrix as point data frame

  • outFile (string) – path to save output raster

  • field (string) – field to rasterize

  • template (string, optional) – path to raster template file, by default None

Return type

None

GOSTnets.core module#

GOSTnets.core.add_intersection_delay(G, intersection_delay=7, time_col='time', highway_col='highway', filter=['projected_footway', 'motorway'])#

Find node intersections. For all intersection nodes, if directed edge is going into the intersection then add delay to the edge. If the highest rank road at an intersection intersects a lower rank road, then the highest rank road does not get delayed. This assumes the highest rank road has the right-of-way.

Parameters
  • G (nx.MultiDiGraph) – a base network object (nx.MultiDiGraph)

  • intersection_delay (int) – The number of seconds to delay travel time at intersections

  • filter (list) – The filter is a list of highway values where the type of highway does not get an intersection delay.

Returns

a base network object (nx.MultiDiGraph)

Return type

nx.MultiDiGraph

GOSTnets.core.add_missing_reflected_edges(G, one_way_tag=None, verbose=False)#

function for adding any missing reflected edges - makes all edges bidirectional. This is essential for routing with simplified graphs

Parameters
  • G (nx.Graph) – a graph object

  • one_way_tag (str) – if exists, then values that are True are one-way and will not be reflected

  • verbose (bool) – Set to true to monitor progress of queries and notify if any queries failed, defaults to False

Returns

a modified graph with the edited ‘time’ attribute

Return type

nx.Graph

GOSTnets.core.advanced_snap(G, pois, u_tag='stnode', v_tag='endnode', node_key_col='osmid', edge_key_col='osmid', poi_key_col=None, road_col='highway', oneway_tag='oneway', path=None, threshold=500, knn=5, measure_crs='epsg:3857', factor=1, verbose=False)#

Connect and integrate a set of POIs into an existing road network.

Given a road network in the form of two GeoDataFrames: nodes and edges, link each POI to the nearest edge (road segment) based on its projection point (PP) and generate a new integrated road network including the POIs, the projected points, and the connection edge.

Credit for original code: Yuwen Chang, 2020-08-16

  1. Make sure all three input GeoDataFrames have defined crs attribute. Try something like gdf.crs or gdf.crs = ‘epsg:4326’. They will then be converted into epsg:3857 or specified measure_crs for processing.

Parameters
  • pois (GeoDataFrame) – a gdf of POI (geom: Point)

  • nodes (GeoDataFrame) – a gdf of road network nodes (geom: Point)

  • edges (GeoDataFrame) – a gdf of road network edges (geom: LineString)

  • node_key_col (str) – The node tag id in the returned graph

  • edge_key_col (str) – The edge tag id in the returned graph

  • poi_key_col (str) – a unique key column of pois should be provided, e.g., ‘index’, ‘osmid’, ‘poi_number’, etc. Currently, this will be renamed into ‘osmid’ in the output. [NOTE] For use in pandana, you may want to ensure this column is numeric-only to avoid processing errors. Preferably use unique integers (int or str) only, and be aware not to intersect with the node key, ‘osmid’ if you use OSM data, in the nodes gdf.

  • poi_key_col – The tag to be used for oneway edges

  • path (str) – directory path to use for saving optional shapefiles (nodes and edges). Outputs will NOT be saved if this arg is not specified.

  • threshold (int) – the max length of a POI connection edge, POIs withconnection edge beyond this length will be removed. The unit is in meters as crs epsg is set to 3857 by default during processing.

  • knn (int) – k nearest neighbors to query for the nearest edge. Consider increasing this number up to 10 if the connection output is slightly unreasonable. But higher knn number will slow down the process.

  • measure_crs (int) – preferred EPSG in meter units. Suggested to use the correct UTM projection.

  • factor (int) – allows you to scale up / down unit of returned new_footway_edges if other than meters. Set to 1000 if length in km.

Returns

the original gdf with POIs and PPs appended and with connection edges appended and existing edges updated (if PPs are present)pois_meter (GeoDataFrame): gdf of the POIs along with extra columns, such as the associated nearest lines and PPs new_footway_edges (GeoDataFrame): gdf of the new footway edges that connect the POIs to the original graph

Return type

graph

GOSTnets.core.assign_traffic_times(G, mb_token, accepted_road_types=['trunk', 'trunk_link', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link', 'motorway', 'motorway_link'], verbose=False, road_col='infra_type', id_col='id')#

Function for querying travel times from the Mapbox “driving traffic” API. Queries are only made for the specified road types.

Parameters
  • G (nx.Graph) – a graph object of the road network

  • mb_token (str) – Mapbox token (retrieve from Mapbox account, starts with “pk:”)

  • road_types (list) – a list of OSM road types for which to query traffic-aware travel time, defaults to main roads

  • verbose (bool) – Set to true to monitor progress of queries and notify if any queries failed, defaults to False

  • road_col (str) – key for the road type in the edge data dictionary, defaults to ‘infra_type’

  • id_col (str) – key for the id in the edge data dictionary, defaults to ‘id’

Returns

The original graph with two new data properties for the edges: ‘mapbox_api’ (a boolean set to True if the edge successfully received a traffic time value) and ‘time_traffic’ (travel time in seconds)

Return type

nx.Graph

GOSTnets.core.build_path(G, node, endpoints, path)#

Recursively build a path of nodes until you hit an endpoint node.

Parameters
  • G (networkx multidigraph) – networkx multidigraph

  • node (int) – the current node to start from

  • endpoints (set) – the set of all nodes in the graph that are endpoints

  • path (list) – the list of nodes in order in the path so far

Returns

paths_to_simplify

Return type

list

GOSTnets.core.calculate_OD(G, origins, destinations, fail_value, weight='time', weighted_origins=False, one_way_roads_exist=False, verbose=False)#

Function for generating an origin: destination matrix

Parameters
  • G (nx.Graph) – a graph containing one or more nodes

  • fail_value (int) – the value to return if the trip cannot be completed (implies some sort of disruption / disconnected nodes)

  • origins (list) – a list of the node IDs to treat as origins points

  • destinations (list) – a list of the node IDs to treat as destinations

  • weight (str) – use edge weight of ‘time’ unless otherwise specified

  • weighted_origins (bool) – equals ‘true’ if the origins have weights. If so, the input to ‘origins’ must be dictionary instead of a list, where the keys are the origin IDs and the values are the weighted demands.

  • one_way_roads_exist (bool) – If the value is ‘True’, then even if there are more origins than destinations, it will not do a flip during processing.

  • verbose (bool) – Set to true to monitor progress of queries and notify if any queries failed, defaults to False

Returns

a numpy matrix of format OD[o][d] = shortest time possible

Return type

numpy matrix

GOSTnets.core.chck(x, poly)#

Check if a point is within a polygon

Parameters
  • x (shapely.geometry.Point) – a point object

  • poly (shapely.geometry.Polygon) – a polygon object

Returns

1 if the point is within the polygon, 0 if not

Return type

int

GOSTnets.core.check(x, chck_set)#

Check if a value is in a set

Parameters
  • x (any) – the value to be checked

  • chck_set (set) – the set to be checked against

Returns

1 if the value is in the set, 0 if not

Return type

int

GOSTnets.core.clip(G, bound, source_crs='epsg:4326', target_crs='epsg:4326', geom_col='geometry', largest_G=True)#

Removes any edges that fall beyond a polygon, and shortens any other edges that do so

Parameters
  • G (nx.MultiDiGraph) – a graph object.

  • bound (shapely Polygon or MultiPolygon) – a shapely polygon object

  • source_crs (str) – crs object in format ‘epsg:4326’

  • target_crs (str) – crs object in format ‘epsg:4326’

  • geom_col (str) – label name for geometry object

  • largest_G (bool) – if True, takes largest remaining subgraph of G as G

Returns

returns a new graph object that is the clipped version of the input graph

Return type

nx.MultiDiGraph

GOSTnets.core.combo_csv_to_graph(fpath, u_tag='u', v_tag='v', geometry_tag='Wkt', largest_G=False)#

Function for generating a G object from a saved combo .csv

Parameters
  • fpath (str) – path to a .csv containing edges (WARNING: COMBO CSV only)

  • u_tag (str) – specify column containing u node ID if not labelled ‘u’

  • v_tag (str) – specify column containing v node ID if not labelled ‘v’

  • geometry_tag (str) – specify column containing geometry if not “Wkt”

  • largest_G (bool, optional) – Boolean that if True, returns only the largest sub-graph, default is False

Return type

nx.MultiDiGraph

GOSTnets.core.convert(x, u_tag, v_tag, geometry_tag, attr_list)#

Convert a row of a pandas dataframe to a tuple of (u, v, data) for use in a networkx graph

Parameters
  • x (pandas.Series) – a row of a pandas dataframe

  • u_tag (str) – the column name for the u node

  • v_tag (str) – the column name for the v node

  • geometry_tag (str) – the column name for the geometry

  • attr_list (list) – a list of the columns to be included in the data dictionary

Returns

a tuple of (u, v, data) for use in a networkx graph

Return type

tuple

GOSTnets.core.convert_network_to_time(G, distance_tag, graph_type='drive', road_col='highway', output_time_col='time', speed_dict=None, walk_speed=4.5, factor=1, default=20)#

Function for adding a time value to graph edges. Ensure any graphs are in the same projection before using function, or pass a crs.

DEFAULT SPEEDS:

speed_dict = { ‘residential’: 20, # kmph ‘primary’: 40, # kmph ‘primary_link’:35, ‘motorway’:50, ‘motorway_link’: 45, ‘trunk’: 40, ‘trunk_link’:35, ‘secondary’: 30, ‘secondary_link’:25, ‘tertiary’:30, ‘tertiary_link’: 25, ‘unclassified’:20, ‘projected_footway’:3.5 }

Parameters
  • G – a graph containing one or more nodes

  • distance_tag – the key in the dictionary for the field currently containing a distance in meters

  • road_col – key for the road type in the edge data dictionary

  • road_col – key for the time value in the output graph

  • graph_type – set to either ‘drive’ or ‘walk’. IF walk - will set time = walking time across all segments, using the supplied walk_speed. IF drive - will use a speed dictionary for each road type, or defaults as per the note below.

  • speed_dict – speed dictionary to use. If not supplied, reverts to defaults

  • walk_speed – specify a walkspeed in km/h

  • factor – allows you to scale up / down distances if saved in a unit other than meters. Set to 1000 if length in km.

  • default – if highway type not in the speed_dict, use this speed as the default. If default is None, then the conversion will be skipped

Returns

The original graph with a new data property for the edges called ‘time’

GOSTnets.core.convert_to_MultiDiGraph(G)#

takes any graph object, loads it into a MultiDiGraph type Networkx object

Parameters

G (nx.Graph) – a graph object

Returns

a MultiDiGraph object

Return type

nx.MultiDiGraph

GOSTnets.core.custom_simplify(G, strict=True)#

Simplify a graph’s topology by removing all nodes that are not intersections or dead-ends. Create an edge directly between the end points that encapsulate them, but retain the geometry of the original edges, saved as attribute in new edge.

Parameters
  • G (networkx multidigraph) – networkx multidigraph

  • strict (bool) – if False, allow nodes to be end points even if they fail all other rules but have edges with different OSM IDs

Returns

simplified networkx multidigraph

Return type

networkx multidigraph

GOSTnets.core.cut(line, distance)#

Cuts a line in two at a distance from its starting point

Parameters
  • line (LineString) – a shapely LineString object

  • distance (float) – distance from start of line to cut

Returns

list of two LineString objects

Return type

list

GOSTnets.core.disrupt_network(G, property, thresh, fail_value)#

Function for disrupting a graph given a threshold value against a node’s value. Any edges which bind to broken nodes have their ‘time’ property set to fail_value

Parameters
  • G (nx.Graph) – REQUIRED a graph containing one or more nodes and one or more edges

  • property (str) – the element in the data dictionary for the edges to test

  • thresh (int) – values of data[property] above this value are disrupted

  • fail_value (int) – The data[‘time’] property is set to this value to simulate the removal of the edge

Returns

a modified graph with the edited ‘time’ attribute

Return type

nx.Graph

GOSTnets.core.edge_gdf_from_graph(G, crs='EPSG:4326', attr_list=None, geometry_tag='geometry', xCol='x', yCol='y', oneway_tag='oneway', single_edge=False)#

Function for generating a GeoDataFrame from a networkx Graph object

Parameters
  • G (nx.Graph) – (required) a graph object G

  • crs (str) – (optional) projection of format ‘epsg:4326’. Defaults to WGS84. Note: here we are defining the crs of the input geometry -we do NOT reproject to this crs. To reproject, consider using geopandas’ to_crs method on the returned gdf.

  • attr_list (list) – (optional) list of the keys which you want to be moved over to the GeoDataFrame.

  • geometry_tag (str) – (optional) the key in the data dictionary for each edge which contains the geometry info.

  • xCol (str) – (optional) if no geometry is present in the edge data dictionary, the function will try to construct a straight line between the start and end nodes, if geometry information is present in their data dictionaries. Pass the Longitude info as ‘xCol’.

  • yCol (str) – (optional) likewise, determining the Latitude tag for the node’s data dictionary allows us to make a straight line geometry where an actual geometry is missing.

  • single_edge (bool) – If True then one edge/row in the returned GeoDataFrame will represent a bi-directional edge. An extra ‘oneway’ column will be added

Returns

a GeoDataFrame object of the edges in the graph

Return type

gpd.GeoDataFrame

GOSTnets.core.edges_and_nodes_csv_to_graph(fpath_nodes, fpath_edges, u_tag='stnode', v_tag='endnode', geometry_tag='Wkt', largest_G=False)#

Function for generating a G object from a saved .csv of edges

Parameters
  • fpath_nodes (str) – path to a .csv containing nodes

  • fpath_edges (str) – path to a .csv containing edges

  • u_tag (str) – optional. specify column containing u node ID if not labelled ‘stnode’

  • v_tag (str) – specify column containing v node ID if not labelled ‘endnode’

  • geometry_tag (str) – specify column containing geometry if not labelled ‘Wkt’

Return type

nx.MultiDiGraph

GOSTnets.core.edges_and_nodes_gdf_to_graph(nodes_df, edges_df, node_tag='node_ID', u_tag='stnode', v_tag='endnode', geometry_tag='Wkt', largest_G=False, discard_node_col=[], checks=False, add_missing_reflected_edges=False, oneway_tag=None)#

Function for generating a G object from dataframse of nodes and one of edges

Parameters
  • nodes_df (str) – Pandas DataFrame with node information

  • edges_df (str) – Pandas DataFrame with edges information

  • u_tag (str) – optional. specify column containing the node ID. This is used to only include entries that have a value.

  • u_tag – optional. specify column containing u node ID if not labelled ‘stnode’

  • v_tag (str) – specify column containing v node ID if not labelled ‘endnode’

  • geometry_tag (str) – specify column containing geometry if not labelled ‘Wkt’

  • largest_G (bool) – If largest_G is true, then only the largest graph will be returned

  • discard_node_col (list) – default is empty, all columns in the nodes_df will be copied to the nodes in the graph. If a list is filled, all the columns specified will be dropped.

  • checks (bool) – if True, will perform a validation checks and return the nodes_df with a ‘node_in_edge_df’ column

  • add_missing_reflected_edges (bool) – if contains a tag, then the oneway column is used to see whether reverse edges need to be added. This is much faster than using the add_missing_reflected_edges after a graph is already created.

  • oneway_tag (str) – if oneway_tag exists, then missing reflected edges won’t be added where an edge’s oneway_tag equals True

Return type

nx.MultiDiGraph

GOSTnets.core.euclidean_distance(lat1, lon1, lat2, lon2)#

Calculate the great circle distance between two points on the earth (specified in decimal degrees)

Parameters
  • lat1 (float) – lat1

  • lon1 (float) – lon1

  • lat2 (float) – lat2

  • lon2 (float) – lon2

Returns

returns the distance between two points in km

Return type

float

GOSTnets.core.example_edge(G, n=1)#

Prints out an example edge

Parameters
  • G (nx.Graph) – a graph object

  • n (int) – n - number of edges to print

Returns

Prints out the edge data

Return type

None

GOSTnets.core.example_node(G, n=1)#

Prints out an example node

Parameters
  • G (nx.Graph) – a graph object

  • n (int) – number of nodes to print

Returns

Prints out the node data

Return type

None

GOSTnets.core.find_graph_avg_speed(G, distance_tag, time_tag)#

Function for finding the average speed per km for the graph. It will sum up the total meters in the graph and the total time (in sec). Then it will convert m/sec to km/hr. This function needs the ‘convert_network_to_time’ function to have run previously.

Parameters
  • G (nx.Graph) – a graph containing one or more nodes

  • distance_tag (str) – the key in the dictionary for the field currently containing a distance in meters

  • time_tag (str) – time to traverse the edge in seconds

Returns

The average speed for the whole graph in km per hr

Return type

float

GOSTnets.core.find_hwy_distances_by_class(G, distance_tag='length')#

Function for finding out the different highway classes in the graph and their respective lengths

Parameters
  • G (nx.Graph) – a graph object

  • distance_tag (str) – specifies which edge attribute represents length

Returns

a dictionary that has each class and the total distance per class

Return type

dict

GOSTnets.core.find_kne(point, lines, near_idx)#

Find the nearest edge (kne) to a given point from a set of lines.

Parameters
  • point (Point) – The point for which to find the nearest edge.

  • lines (GeoDataFrame) – The set of lines representing edges.

  • near_idx (array-like) – The array-like object containing the indices of the nearest edges.

Returns

  • kne_idx (int) – The index of the nearest edge.

  • kne (Series) – The geometry of the nearest edge.

GOSTnets.core.first_val(x)#

Get the first value of a list, or the value itself if it is not a list

Parameters

x (list or str) – a list or string

Returns

the first value of the list, or the string itself if it is not a list

Return type

str

GOSTnets.core.flatten(line)#

Flattens a nested list into a single list.

Parameters

line (list) – The nested list to be flattened.

Returns

The flattened list.

Return type

list

GOSTnets.core.generate_isochrones(G, origins, thresh, weight=None, stacking=False)#

Function for generating isochrones from one or more graph nodes. Ensure any GeoDataFrames / graphs are in the same projection before using function, or pass a crs

Parameters
  • G (nx.Graph) – a graph containing one or more nodes

  • origins (list) – a list of node IDs that the isochrones are to be generated from

  • thresh (str) – The time threshold for the calculation of the isochrone

  • weight (str) – Name of edge weighting for calculating ‘distances’. For isochrones, should be time expressed in seconds. Defaults to time expressed in seconds.

  • stacking (bool) – If True, returns number of origins that can be reached from that node. If false, max = 1

Returns

The original graph with a new data property for the nodes and edges included in the isochrone

Return type

nx.Graph

GOSTnets.core.get_paths_to_simplify(G, strict=True)#

Create a list of all the paths to be simplified between endpoint nodes.

The path is ordered from the first endpoint, through the interstitial nodes, to the second endpoint. If your street network is in a rural area with many interstitial nodes between true edge endpoints, you may want to increase your system’s recursion limit to avoid recursion errors.

Parameters
  • G (networkx multidigraph) – networkx multidigraph

  • strict (bool) – if False, allow nodes to be end points even if they fail all other rules but have edges with different OSM IDs

Returns

paths to be simplified

Return type

list

GOSTnets.core.get_pp(point, line)#

Get the projected point (pp) of ‘point’ on ‘line’.

Parameters
  • point (Point) – The point to be projected.

  • line (LineString) – The line on which the point is projected.

Returns

The projected point on the line.

Return type

Point

GOSTnets.core.gn_project_graph(G, to_crs=None)#

Taken from OSMNX. Project graph from its current CRS to another. If to_crs is None, project the graph to the UTM CRS for the UTM zone in which the graph’s centroid lies. Otherwise, project the graph to the CRS defined by to_crs.

Parameters
  • G (networkx.MultiDiGraph) – networkx.MultiDiGraph the graph to be projected

  • to_crs (str) – string or pyproj.CRS if None, project graph to UTM zone in which graph centroid lies, otherwise project graph to this CRS

Returns

the projected graph

Return type

networkx.MultiDiGraph

GOSTnets.core.graph_edges_intersecting_polygon(G, polygons, mode, crs=None, fast=True)#

Function for identifying edges of a graph that intersect polygon(s). Ensure any GeoDataFrames are in the same projection before using function, or pass a crs.

Parameters
  • G (nx.Graph) – a Graph object

  • polygons (gpd.GeoDataFrame) – a GeoDataFrame containing one or more polygons

  • mode (str) – a string, either ‘contains’ or ‘intersecting’

  • crs (dict) – If passed, will reproject both polygons and graph edge gdf to this projection.

  • fast (bool) – (default: True): we can cheaply test whether an edge intersects a polygon gdf by checking whether either the start or end nodes are within a polygon. If both are, then we return ‘contained’; if at least one is, we can return ‘intersects’. If we set fast to False, then we iterate through each geometry one at a time, and check to see whether the geometry object literally intersects the polygon geodataframe, one at a time. May be computationally intensive!

Returns

a GeoDataFrame containing the edges intersecting the polygons

Return type

geopandas.GeoDataFrame

GOSTnets.core.graph_nodes_intersecting_polygon(G, polygons, crs=None)#

Function for identifying nodes of a graph that intersect polygon(s). Ensure any GeoDataFrames are in the same projection before using function, or pass a crs.

Parameters
  • G (nx.Graph or gpd.GeoDataFrame) – a Graph object OR node geodataframe

  • polygons (gpd.GeoDataFrame) – a GeoDataFrame containing one or more polygons

  • crs (str) – a crs object of form ‘epsg:XXXX’. If passed, matches both inputs to this crs.

Returns

a list of the nodes intersecting the polygons

Return type

list

GOSTnets.core.gravity_demand(G, origins, destinations, weight, maxtrips=100, dist_decay=1, fail_value=99999999999)#

Function for generating a gravity-model based demand matrix. Note: 1 trip will always be returned between an origin and a destination, even if weighting would otherwise be 0.

Parameters
  • origins (list) – a list of node IDs. Must be in G.

  • destinations (list) – a list of node IDs Must be in G.

  • weight (str) – the gravity weighting of the nodes in the model, e.g. population

  • fail_value (int) – the data[‘time’] property is set to this value to simulate the removal of the edge

  • maxtrips (int) – normalize the number of trips in the resultant function to this number of trip_times

  • dist_decay (int) – parameter controlling the aggresion of discounting based on distance

Returns

a numpy array describing the demand between o and d in terms of number of trips

Return type

numpy array

GOSTnets.core.is_endpoint(G, node, strict=True)#

Return True if the node is a “real” endpoint of an edge in the network, otherwise False. OSM data includes lots of nodes that exist only as points to help streets bend around curves. An end point is a node that either: 1) is its own neighbor, ie, it self-loops. 2) or, has no incoming edges or no outgoing edges, ie, all its incident edges point inward or all its incident edges point outward. 3) or, it does not have exactly two neighbors and degree of 2 or 4. 4) or, if strict mode is false, if its edges have different OSM IDs. :param G: the input graph :type G: networkx multidigraph :param node: the node to examine :type node: int :param strict: if False, allow nodes to be end points even if they fail all other rules but have edges with different OSM IDs :type strict: bool

Returns

whether the node is a real endpoint

Return type

bool

GOSTnets.core.join_networks(base_net, new_net, measure_crs, thresh=500)#

joins two networks together within a binding threshold

Parameters
  • base_net (nx.MultiDiGraph) – a base network object (nx.MultiDiGraph)

  • new_net (nx.MultiDiGraph) – the network to add on to the base (nx.MultiDiGraph)

  • measure_crs (int) – the crs number of the measurement (epsg code)

  • thresh (int) – binding threshold - unit of the crs - default 500m

Returns

returns a new network object that is the combination of the two input networks

Return type

nx.MultiDiGraph

GOSTnets.core.make_iso_polys(G, origins, trip_times, edge_buff=10, node_buff=25, infill=False, weight='time', measure_crs='epsg:4326', edge_filters=None)#

Function for adding a time value to edge dictionaries

Parameters
  • G (nx.Graph) – a graph object

  • origins (list) – a list object of node IDs from which to generate an isochrone poly object

  • trip_times (list) – a list object containing the isochrone values

  • edge_buff (int) – the thickness with witch to buffer included edges

  • node_buff (int) – the thickness with witch to buffer included nodes

  • infill (bool) – If True, will remove any holes in isochrones

  • weight (str) – The edge weight to use when appraising travel times.

  • measure_crs (str) – measurement crs, object of form ‘epsg:XXXX’

  • edge_filters (dict) – you can optionally add a dictionary with key values, where the key is the attribute and the value you want to ignore from creating isochrones. An example might be an underground subway line.

Returns

a GeoDataFrame object of the isochrone polygons

Return type

gpd.GeoDataFrame

GOSTnets.core.make_iso_polys_original(G, origins, trip_times, edge_buff=10, node_buff=25, infill=False, weight='time', measure_crs='epsg:4326')#

Function for adding a time value to edge dictionaries

Parameters
  • G (nx.Graph) – a graph object

  • origins (list) – a list object of node IDs from which to generate an isochrone poly object

  • trip_times (list) – a list object containing the isochrone values

  • edge_buff (int) – the thickness with witch to buffer included edges

  • node_buff (int) – the thickness with witch to buffer included nodes

  • infill (bool) – If True, will remove any holes in isochrones

  • weight (str) – The edge weight to use when appraising travel times.

  • measure_crs (str) – measurement crs, object of form ‘epsg:XXXX’

Returns

GeoDataFrame object of the isochrone polygons

Return type

gpd.GeoDataFrame

GOSTnets.core.nearest_edge(row, Rtree, knn, edges_meter)#

Finds the nearest edge(s) to a given point.

Parameters

row (pandas.Series) – A row containing the point geometry.

Returns

A tuple containing the indices of the nearest edges and their corresponding geometries.

Return type

tuple

GOSTnets.core.new_edge_generator(passed_geom, infra_type, iterator, existing_legitimate_point_geometries, geom_col, project_WGS_UTM)#

Generates new edge and node geometries based on a passed geometry. WARNING: This is a child process of clip(), and shouldn’t be run on its own

Parameters
  • passed_geom (shapely LineString) – a shapely Linestring object

  • infra_type (str) – the road / highway class of the passed geometry

  • iterator (int) – helps count the new node IDs to keep unique nodes

  • existing_legitimate_point_geometries (dict) – a dictionary of points already created / valid in [u:geom] format

  • project_WGS_UTM (object) – projection object to transform passed geometries

  • geom_col (str) – label name for geometry object

Returns

returns a list of new nodes and edges to be added to the graph

Return type

list

GOSTnets.core.node_gdf_from_graph(G, crs='epsg:4326', attr_list=None, geometry_tag='geometry', xCol='x', yCol='y')#

Function for generating GeoDataFrame from Graph

Parameters
  • G (nx.Graph) – a graph object G

  • crs (str) – projection of format ‘epsg:4326’. Defaults to WGS84. note: here we are defining the crs of the input geometry - we do NOT reproject to this crs. To reproject, consider using geopandas’ to_crs method on the returned gdf.

  • attr_list (list) – list of the keys which you want to be moved over to the GeoDataFrame, if not all. Defaults to None, which will move all.

  • geometry_tag (str) – specify geometry attribute of graph, default ‘geometry’

  • xCol (str) – if no shapely geometry but Longitude present, assign here

  • yCol (str) – if no shapely geometry but Latitude present, assign here

Returns

a geodataframe of the node objects in the graph

Return type

gpd.GeoDataFrame

GOSTnets.core.pandana_snap(G, point_gdf, source_crs='epsg:4326', target_crs='epsg:4326', add_dist_to_node_col=True, time_it=False)#

snaps points to a graph at very high speed

Parameters
  • G (nx.Graph) – a graph object, or the node geodataframe of a graph

  • point_gdf (gpd.GeoDataFrame) – a geodataframe of points, in the same source crs as the geometry of the graph object

  • source_crs (str) – The crs for the input G and input point_gdf in format ‘epsg:32638’

  • target_crs (str) – The measure crs how distances between points are calculated. The returned point GeoDataFrame’s CRS does not get modified. The crs object in format ‘epsg:32638’

  • add_dist_to_node_col (bool) – return distance to nearest node in the units of the target_crs

Returns

returns a GeoDataFrame that is the same as the input point_gdf but adds a column containing the id of the nearest node in the graph, and the distance if add_dist_to_node_col is True

Return type

GeoDataFrame

GOSTnets.core.pandana_snap_c(G, point_gdf, source_crs='epsg:4326', target_crs='epsg:4326', add_dist_to_node_col=True, time_it=False)#

snaps points to a graph at a faster speed than pandana_snap.

Parameters
  • G (nx.Graph) – a graph object, or the node geodataframe of a graph

  • point_gdf (gpd.GeoDataFrame) – a geodataframe of points, in the same source crs as the geometry of the graph object

  • source_crs (str) – The crs for the input G and input point_gdf in format ‘epsg:32638’

  • target_crs (str) – The measure crs how distances between points are calculated. The returned point GeoDataFrame’s CRS does not get modified. The crs object in format ‘epsg:32638’

  • add_dist_to_node_col (bool) – return distance to nearest node in the units of the target_crs

  • time_it (bool) – return time to complete function

Returns

returns a GeoDataFrame that is the same as the input point_gdf but adds a column containing the id of the nearest node in the graph, and the distance if add_dist_to_node_col is True

Return type

GeoDataFrame

GOSTnets.core.pandana_snap_points(source_gdf, target_gdf, source_crs='epsg:4326', target_crs='epsg:4326', add_dist_to_node_col=True)#

snaps points to another GeoDataFrame at very high speed

Parameters
  • source_gdf (gpd.GeoDataFrame) – a geodataframe of points

  • target_gdf (gpd.GeoDataFrame) – a geodataframe of points, in the same source crs as the geometry of the source_gdfsg:32638’

  • source_crs (str, optional) – crs object in format ‘epsg:32638’, by default ‘epsg:4326’

  • target_crs (str, optional) – crs object in format ‘epsg:32638’, by default ‘epsg:4326’

  • add_dist_to_node_col (bool) – return distance in metres to nearest node

Return type

return: returns a GeoDataFrame that is the same as the input source_gdf but adds a column containing the id of the nearest node in the target_gdf, and the distance if add_dist_to_node_col is True

GOSTnets.core.pandana_snap_single_point(G, shapely_point, source_crs='epsg:4326', target_crs='epsg:4326')#

snaps a point to a graph at very high speed

Parameters
  • G (nx.Graph) – a graph object

  • shapely_point (shapely Point) – a shapely point (ex. Point(x, y)), in the same source crs as the geometry of the graph object

  • source_crs (str) – crs object in format ‘epsg:32638’

  • target_crs (str) – crs object in format ‘epsg:32638’

  • add_dist_to_node_col (bool) – return distance in metres to nearest node

Returns

returns the id of the nearest node in the graph, could be an integer, float, string, or really any object

Return type

object

GOSTnets.core.pandana_snap_to_many(G, point_gdf, source_crs='epsg:4326', target_crs='epsg:4326', add_dist_to_node_col=True, time_it=False, k_nearest=5, origin_id='index')#

snaps points their k nearest neighbors in the graph.

Parameters
  • G (nx.Graph) – a graph object

  • point_gdf (gpd.GeoDataFrame) – a geodataframe of points, in the same source crs as the geometry of the graph object

  • source_crs (str) – The crs for the input G and input point_gdf in format ‘epsg:32638’

  • target_crs (str) – The desired crs returned point GeoDataFrame. The crs object in format ‘epsg:32638’

  • add_dist_to_node_col (bool) – return distance to nearest node in the units of the target_crs

  • time_it (bool) – return time to complete function

  • k_nearest (int) – k nearest neighbors to query for the nearest node

  • origin_id (str) – key for the id in the points_gdf input, defaults to ‘index’

Returns

returns a dictionary of the k nearest nodes to each origin point

Return type

dict

GOSTnets.core.project_gdf(gdf, to_crs=None, to_latlong=False)#

Taken from OSMNX

Project a GeoDataFrame from its current CRS to another. If to_crs is None, project to the UTM CRS for the UTM zone in which the GeoDataFrame’s centroid lies. Otherwise project to the CRS defined by to_crs. The simple UTM zone calculation in this function works well for most latitudes, but may not work for some extreme northern locations like Svalbard or far northern Norway.

Parameters
  • gdf (geopandas.GeoDataFrame) – geopandas.GeoDataFrame the GeoDataFrame to be projected

  • to_crs (str) – string or pyproj. CRS if None, project to UTM zone in which gdf’s centroid lies, otherwise project to this CRS

  • to_latlong (bool) – bool if True, project to settings.default_crs and ignore to_crs

Returns

the projected GeoDataFrame

Return type

geopandas.GeoDataFrame

GOSTnets.core.randomly_disrupt_network(G, edge_frac, fail_value)#

Function for randomly disurpting a network. NOTE: requires the graph to have an ‘edge_id’ value in the edge data dictionary. This DOES NOT have to be unique.

Parameters
  • G (nx.Graph) – a graph containing one or more nodes and one or more edges

  • edge_frac (int) – the percentage of edges to destroy. Integer rather than decimal, e.g. 5 = 5% of edges

  • fail_value (int) – the data[‘time’] property is set to this value to simulate the removal of the edge

Returns

nx.Graph

a modified graph with the edited ‘time’ attribute the list of edge IDs randomly chosen for destruction

destroy_list

list of the integers corresponding to the edge indices that were ‘destroyed’

Return type

tuple (nx.Graph, destroy_list)

GOSTnets.core.remove_duplicate_edges(G, max_ratio=1.5)#

function for deleting duplicated edges - where there is more than one edge connecting a node pair. USE WITH CAUTION - will change both topological relationships and node maps

Parameters
  • G (nx.Graph) – a graph object

  • max_ratio (float) – most of the time we see duplicate edges that are clones of each other. Sometimes, however, there are valid duplicates. These occur if multiple roads connect two junctions uniquely and without interruption - e.g. two roads running either side of a lake which meet at either end. The idea here is that valid ‘duplicate edges’ will have geometries of materially different length. Hence, we include a ratio - defaulting to 1.5 - beyond which we are sure the duplicates are valid edges, and will not be deleted.

Returns

a modified graph with the edited ‘time’ attribute

Return type

nx.Graph

GOSTnets.core.salt_long_lines(G, source, target, thresh=5000, factor=1, attr_list=None, geometry_tag='Wkt')#

Adds in new nodes to edges greater than a given length

Parameters
  • G (nx.Graph) – a graph object

  • source (str) – crs object in format ‘epsg:4326’

  • target (str) – crs object in format ‘epsg:32638’

  • thresh (int) – distance in metres after which to break edges.

  • factor (int) – edge lengths can be returned in units other than metres by specifying a numerical multiplication factor. Factor behavior divides rather than multiplies.

  • attr_dict (dict) – list of attributes to be saved onto new edges.

Returns

a modified graph with the edited ‘time’ attribute

Return type

nx.Graph

GOSTnets.core.sample_raster(G, tif_path, property_name='RasterValue')#

Function for attaching raster values to corresponding graph nodes.

Ensure any GeoDataFrames / graphs are in the same projection before using function.

Parameters
  • G (nx.Graph) – a graph containing one or more nodes

  • tif_path (str) – a raster or path to a tif

  • property_name (str) – a property name for the value of the raster attached to the node

Returns

The original graph with a new data property for the nodes included in the raster

Return type

nx.Graph

GOSTnets.core.save(G, savename, wpath, pickle=True, edges=True, nodes=True)#

function used to save a graph object in a variety of handy formats

Parameters
  • G (nx.Graph) – a graph object

  • savename (str) – the filename, WITHOUT extension

  • wpath (str) – the write path for where the user wants the files saved

  • pickle (bool) – if set to false, will not save a pickle of the graph

  • edges (bool) – if set to false, will not save an edge gdf

  • nodes (bool) – if set to false, will not save a node gdf

Returns

saves files to the write path

Return type

None

GOSTnets.core.selector(x)#

Selects and returns an integer if the input is an integer, otherwise returns the input as is.

Parameters

x (int or any) – The input value to be selected.

Returns

The selected value.

Return type

int or any

GOSTnets.core.simplify_junctions(G, measure_crs, in_crs='epsg:4326', thresh=25, verbose=False)#

simplifies topology of networks by simplifying node clusters into single nodes.

Parameters
  • G (nx.Graph) – a graph object

  • measure_crs (str) – the crs to make the measurements inself.

  • in_crs (str) – the current crs of the graph’s geometry properties. By default, assumes WGS 84 (epsg 4326)

  • thresh (int) – the threshold distance in which to simplify junctions. By default, assumes 25 meters

Returns

a modified graph with simplified junctions

Return type

nx.Graph

GOSTnets.core.split_line(line, pps)#

Split ‘line’ by all intersecting ‘pps’ (as multipoint).

Parameters
  • line (LineString) – The line to be split.

  • pps (MultiPoint) – The multipoint object containing all the points at which to split the line.

Returns

a list of all line segments after the split

Return type

list

GOSTnets.core.unbundle_geometry(c)#

Function for unbundling complex geometric objects. Note: shapely MultiLineString objects quickly get complicated. They may not show up when you plot them in QGIS. This function aims to make a .csv ‘plottable’

Parameters

c (object) – any object. This helper function is usually applied in lambda format against a pandas / geopandas dataframe. The idea is to try to return more simple versions of complex geometries for LineString and MultiLineString type objects.

Returns

an unbundled geometry value that can be plotted.

Return type

geometry

GOSTnets.core.update_edges(edges, new_lines, replace=True, nodes_meter=None, pois_meter=None)#

Update edge info by adding new_lines; or, replace existing ones with new_lines (n-split segments).

Parameters
  • edges (GeoDataFrame) – The original edges GeoDataFrame.

  • new_lines (list) – The new line segments to be added to the edges.

  • replace (bool) – treat new_lines (flat list) as newly added edges if False, else replace existing edges with new_lines (often a nested list)

  • nodes_meter (GeoDataFrame) – The nodes GeoDataFrame.

  • pois_meter (GeoDataFrame) – The POIs GeoDataFrame.

Returns

  • GeoDataFrame – The updated edges GeoDataFrame.

  • Note – kne_idx refers to ‘fid in Rtree’/’label’/’loc’, not positional iloc

GOSTnets.core.update_nodes(nodes, new_points, ptype, road_col, node_key_col, poi_key_col, node_highway_pp, node_highway_poi, measure_crs='epsg:3857', osmid_prefix=9990000000)#

Update nodes with a list (pp) or a GeoDataFrame (poi) of new_points.

Parameters
  • nodes (GeoDataFrame) – The original nodes GeoDataFrame.

  • new_points (GeoDataFrame or list) – The new points to be added to the nodes.

  • ptype (str) – type of Point list to append, ‘pp’ or ‘poi’

  • measure_crs (str) – the crs of the measure (epsg code)

Returns

The updated nodes GeoDataFrame.

Return type

GeoDataFrame

GOSTnets.core.utm_of_graph(G)#

Calculates the UTM coordinate reference system (CRS) for a given graph.

Parameters

G (networkx.Graph) – The input graph.

Returns

The UTM CRS string.

Return type

str

GOSTnets.fetch_od module#

GOSTnets.fetch_od.CreateODMatrix(infile, infile_2, lat_name='Lat', lon_name='Lon', UID='ID', Pop=None, call_type='OSRM', rescue=0, rescue_num=0, MB_Token='', sleepTime=5, osrmHeader='')#

Create an Origin-Destination matrix from a list of origins and destinations.

make sure lat_name and Lon_names are the same column names in both your infile (origins) and infile_2 (destinations)

Parameters
  • infile (string or geodataframe) – string for folder path containing input data of the origins. This can also be a geodataframe of the data instead.

  • infile_2 (string or geodataframe) – string for folder path containing input data of the destinations. This can also be a geodataframe of the data instead.

  • lat_name (string) – Latitude column name.

  • lon_name (string) – Longitude column name

  • UID (string) – Origin Unique Identifier column name (e.g. District, Name, Object ID…). This is mainly helpful for joining the output back to the input data / a shapefile, and is non-essential in terms of the calculation. It can be text or a number.

  • Pop (string) – Population / weighting column name

  • call_type (string) – Server call type - “OSRM” for OSRM, “MB” for Mapbox, “MBT” for Mapbox traffic, or “Euclid” for Euclidean distances (as the crow flies)

  • rescue (int) – Save - input latest save number to pick up matrix construction process from there.

  • rescue_num (int) – Rescue number parameter - If you have already re-started the download process, denote how many times. First run = 0, restarted once = 1…

  • MB_Token (string) – Mapbox private key if using the “MB” or “MBT” call types

  • sleepTime (int) – When making calls to OSRM, a sleep time is required to avoid DDoS

  • osrmHeader (string) – optional parameter to set OSRM source

Returns

DataFrame containing the OD matrix.

Return type

pandas.DataFrame

GOSTnets.fetch_od.MarketAccess(new, lambder_list=[0.01, 0.005, 0.001, 0.0007701635, 0.0003850818, 0.0001925409, 9.62704e-05, 3.85082e-05, 1e-05])#

Calculate Market Access for a given range of lambdas.

Parameters
  • new (pd.DataFrame) – DataFrame containing the data for market access calculation.

  • lambder_list (list) – List of lambda values to be used for market access calculation.

Returns

DataFrame containing the market access values for each lambda.

Return type

pd.DataFrame

GOSTnets.fetch_od.ReadMe(ffpath)#

GOSTnets.fetch_pois module#

class GOSTnets.fetch_pois.OsmObject(a, poly, tags, path='')#

Bases: object

Represents an object for fetching and processing OpenStreetMap Points of Interest (POIs).

tags#

A dictionary of tags used to filter the POIs.

Type

dict

name#

The name of the amenity.

Type

str

bbox#

The area within which to search for POIs.

Type

shapely Polygon

path#

The output folder where results are saved.

Type

str

RelationtoPoint(string): Converts a relation geometry to a point geometry.
GenerateOSMPOIs(): Generates the OSM POIs within the specified area.
RemoveDupes(buf_width, crs): Removes duplicate POIs within a buffer width.
prepForMA(): Prepares the results data frame for use in OSRM functions.
Save(outFolder): Saves the POIs to a CSV file in the specified output folder.

Examples

>>> education = {'amenity':['school', 'kindergarten','university', 'college']}
>>> health = {'amenity':['clinic', 'pharmacy', 'hospital', 'health']}
>>> crs = 'epsg:4326'
>>> buf_width = 0.0005
>>> for a in amenities:
...     curr_amenity = amenities[a]
...     current = AmenityObject(a, bbox, tags, path)
...     current.GenerateOSMPOIs()
...     current.RemoveDupes(buf_width, crs)
...     current.Save(a)
GenerateOSMPOIs()#

Generates OpenStreetMap Points of Interest (POIs) within a given bounding box.

Returns

A DataFrame containing the generated POIs.

Return type

pandas.DataFrame

RelationtoPoint(string)#

Converts a relation geometry to a point geometry.

Parameters

string (shapely.geometry) – The relation geometry to be converted.

Returns

The centroid of the relation geometry if it is a Polygon, otherwise the centroid of the MultiPolygon formed by the relation geometry’s constituent geometries.

Return type

shapely.geometry.Point

RemoveDupes(buf_width, crs='epsg:4326')#

Remove duplicate geometries from the GeoDataFrame.

Parameters
  • buf_width (float) – The buffer width used for checking intersection.

  • crs (str, optional) – The coordinate reference system. Defaults to “epsg:4326”.

Returns

The GeoDataFrame with duplicate geometries removed.

Return type

pandas.DataFrame

Save(outFolder)#

Save the dataframe as a CSV file in the specified output folder.

Parameters

outFolder (str) – The name of the output folder.

Return type

None

prepForMA()#

Prepare results data frame for use in the OSRM functions in OD.

Steps: 1. Add ‘Lat’ and ‘Lon’ fields based on the x and y coordinates of the geometry. 2. Add a unique identifier ‘mID’ to each row. 3. Remove the ‘geometry’ and ‘buffer’ fields from the data frame.

Returns

The modified data frame with added fields and removed geometry fields.

Return type

pandas.DataFrame

GOSTnets.load_osm module#

GOSTnets.network_clean module#

GOSTnets.network_clean.clean_network(G, wpath='', output_file_name='', UTM='epsg:3857', WGS='epsg:4326', junctdist=50, verbose=False)#

Topologically simplifies an input graph object by collapsing junctions and removing interstital nodes

Parameters
  • G (networkx.graph object) – a graph object containing nodes and edges. Edges should have a property called ‘Wkt’ containing geometry objects describing the roads.

  • wpath (str) – the write path - a drive directory for inputs and output

  • output_file_name (str) – This will be the output file name with ‘_processed’ appended

  • UTM (dict) – The epsg code of the projection, in metres, to apply the junctdist

  • WGS (dict) – the current crs of the graph’s geometry properties. By default, assumes WGS 84 (epsg 4326)

  • junctdist (int, float) – distance within which to collapse neighboring nodes. simplifies junctions. Set to 0.1 if not simplification desired. 50m good for national (primary / secondary) networks

  • verbose (boolean) – if True, saves down intermediate stages for dissection

Returns

A simplified graph object

Return type

nx.MultiDiGraph

GOSTnets.optimization module#

GOSTnets.osm_parser module#

source: https://gist.github.com/Tofull/49fbb9f3661e376d2fe08c2e9d64320e

class GOSTnets.osm_parser.Node(id, lon, lat)#

Bases: object

Represents a node in the OpenStreetMap data.

id#

The unique identifier of the node.

Type

int

lon#

The longitude coordinate of the node.

Type

float

lat#

The latitude coordinate of the node.

Type

float

tags#

A dictionary containing additional tags associated with the node.

Type

dict

class GOSTnets.osm_parser.OSM(filename_or_stream)#

Bases: object

Represents an OpenStreetMap (OSM) data structure.

Parameters

filename_or_stream (str or file object) – The OSM data file name or stream.

nodes#

A dictionary of OSM nodes, where the key is the node ID and the value is the Node object.

Type

dict

ways#

A dictionary of OSM ways, where the key is the way ID and the value is the Way object.

Type

dict

class GOSTnets.osm_parser.Way(id, osm)#

Bases: object

Represents a way in the OpenStreetMap data.

id#

The unique identifier of the way.

Type

str

osm#

The OpenStreetMap object that the way belongs to.

Type

object

nds#

The list of node references that make up the way.

Type

list

tags#

The dictionary of tags associated with the way.

Type

dict

split(dividers)#

Splits the way into multiple smaller ways based on the given dividers.

Parameters

dividers (dict) – A dictionary containing the number of occurrences of each node reference.

Returns

A list of new Way objects, each representing a slice of the original way.

Return type

list

GOSTnets.osm_parser.download_osm(left, bottom, right, top, proxy=False, proxyHost='10.0.4.2', proxyPort='3128', cache=False, cacheTempDir='/tmp/tmpOSM/', verbose=True)#

Downloads OpenStreetMap data for a given bounding box.

Parameters
  • left (float) – The left longitude of the bounding box.

  • bottom (float) – The bottom latitude of the bounding box.

  • right (float) – The right longitude of the bounding box.

  • top (float) – The top latitude of the bounding box.

  • proxy (bool, optional) – Whether to use a proxy for the request. Defaults to False.

  • proxyHost (str, optional) – The proxy host address. Defaults to “10.0.4.2”.

  • proxyPort (str, optional) – The proxy port number. Defaults to “3128”.

  • cache (bool, optional) – Whether to cache the downloaded tile. Defaults to False.

  • cacheTempDir (str, optional) – The directory to store the cached tile. Defaults to “/tmp/tmpOSM/”.

  • verbose (bool, optional) – Whether to print progress messages. Defaults to True.

Returns

The downloaded OpenStreetMap tile.

Return type

file-like object

GOSTnets.osm_parser.fetch_roads_OSM(osm_path, acceptedRoads=['motorway', 'motorway_link', 'trunk', 'trunk_link', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link'])#

Returns a GeoDataFrame of OSM roads from an OSM file

Parameters
  • osm_path (str) – path to OSM file

  • acceptedRoads (list) – list of OSM road types

Returns

A GeoDataFrame of OSM roads

Return type

gpd.GeoDataFrame

GOSTnets.osm_parser.haversine(lon1, lat1, lon2, lat2, unit_m=True)#

Calculate the great circle distance between two points on the earth (specified in decimal degrees) default unit : m

Parameters
  • lon1 (float) – longitude of the first point

  • lat1 (float) – latitude of the first point

  • lon2 (float) – longitude of the second point

  • lat2 (float) – latitude of the second point

  • unit_m (bool) – if True, return the distance in meters (default) if False, return the distance in kilometers

Returns

distance between the two points

Return type

float

GOSTnets.osm_parser.line_length(line, ellipsoid='WGS-84')#

Returns length of a line in kilometers, given in geographic coordinates. Adapted from https://gis.stackexchange.com/questions/4022/looking-for-a-pythonic-way-to-calculate-the-length-of-a-wkt-linestring#answer-115285

Parameters
Returns

Length of line in kilometers

Return type

float

GOSTnets.osm_parser.read_osm(filename_or_stream, only_roads=True)#

Read graph in OSM format from file specified by name or by stream object.

Parameters
  • filename_or_stream (string or file) – The filename or stream to read. File can be either a filename or stream/file object.

  • only_roads (bool, optional) – Whether to only read roads. Defaults to True.

Returns

The graph from the OSM file.

Return type

networkx multidigraph

Examples

>>> G=nx.read_osm(nx.download_osm(-122.33,47.60,-122.31,47.61))
>>> import matplotlib.pyplot as plt
>>> plt.plot([G.node[n]['lat']for n in G], [G.node[n]['lon'] for n in G], 'o', color='k')
>>> plt.show()

Module contents#