Skip to main content

Highly optimized and aggregated network functions

Project description

Network Functions

A group of network-related functions used for geospatial analysis.

Modules

functions (also accessed as pure network_functions)

inject_crossing

inject_crossing(Graph: nx.MultiDiGraph, G: nx.MultiDiGraph, alternatives: gpd.GeoDataFrame, 
                crossing, typedict={'normal': 1.0, 'bridge': 1.25, 'tunnel': 1.15}) -> list

Inject the new alternative into the graph

Inputs:

  • Graph (nx.MultiDiGraph): The parent graph, which should not be modified
  • G (nx.MultiDiGraph): The child graph, which will be modified to produce the new graph
  • alternatives (gpd.GeoDataFrame): Shapefiles of alternative crossings
  • crossing (str): The name of the crossing, extracted from alternatives['name']
  • typedict (dict): Dictionary of scaling factor for elevated or submerged segments

Outputs:

  • endpoint_ids (list): The list of the node ids of the two new endpoints of the injected segment

path_dijkstra

path_dijkstra(origins: int | list | np.ndarray, destinations: int | list, G: nx.MultiDiGraph = None,
            nodes: gpd.GeoDataFrame = None, edges: gpd.GeoDataFrame = None, *, dist_param: str = 'length',
            origins_in_nodes: bool = False, destinations_in_nodes: bool = False, pairs: bool = False,
            verbose: bool = True) -> tuple[dict[tuple:float], dict[tuple:list]]
An data-structure optimized algorithm for computing shortest paths between sets of points. Utilizes
compressed sparse row (CSR) matricies for efficient adjacent-node searching across the graph. 
Can compute between one origin and one destination, many origins and one destination, one origin
and many destinations, or many origins and many destinations, which will compute pairwise if `pairs`
is specified, and every possible combination otherwise. Note that unreachable paths will have a distance
of 'inf' and a path list of length 1 (the origin node only).

Parameters:

    origins: int | list | np.ndarray
    - The origin points to be used. Can be a point, list of points, or array of points (like pd.Series). 
      If `origins_in_nodes` is `True`, this must be a node or list/array of nodes in `G` (by OSMID)

    destinations: int | list
    - The destination points to be used. Can be a point, list of points, or array of points (like pd.Series). 
      If `destinations_in_nodes` is `True`, this must be a node or list/array of nodes in `G` (by OSMID)

    G: nx.MultiDiGraph = None
    - The graph to be used in the calculation. If left as None, both a `nodes` GeoDataFrame and an 
      `edges` GeoDataFrame must be passed in. The function expects that G is well-connected; if
      not, it will not find paths and throw an error. This can be fixed beforehand with
      `nx.connected_components()`. 

    nodes: gpd.GeoDataFrame = None
    - If a graph is not passed, the nodes to be used in the construction of the graph. The call 
      relies on `ox.graph_from_gdfs`, so it must be indexed by `osmid`.

    edges: gpd.GeoDataFrame = None
    - If a graph is not passed, the edges to be used in the construction of the graph. The call 
      relies on `ox.graph_from_gdfs`, so it must be indexed by `u`, `v`, and `key`.

    dist_param: str = 'length'
    - The distance parameter to be used for computing distance. Defaults to `length` (natively
      in OSM). Useful if passing uniquely weighted edges. Must be one of the edge attributes.

    origins_in_nodes: bool = False
    - Whether or not the origins list is in `G.nodes()`. If True, the origins list must be a list
      of `osmid`'s in `G`. Otherwise, the origins list needs to be a list of geometries.

    destinations_in_nodes: bool = False
    - Whether or not the destinations list is in `G.nodes()`. If True, the destinations list must 
      be a list of `osmid`'s in `G`. Otherwise, the destinations list needs to be list of 
      geometries.

    pairs: bool = False
    - Whether the origins and destinations should be interpreted as OD pairs. Will perform single 
      routings between each pair

    verbose: bool = True
    - If passing multiorigin/multidestination, will add a `tqdm` wrapper and verbosity to the calculations,
      so the user can get a sense of how long it will take to run.

Outputs:
    - A Dictionary of points and the distances to or from them (in the multiple -> multiple case, 
      every combination of Origin/Destination)

    - A list of nodes forming the paths between each (o, d) pair being analyzed.

geomerge

geomerge(df: gpd.GeoDataFrame, field: str, base_osm: gpd.GeoDataFrame,
    *, name: str = None, categories: list = None, road_id: str = None,
    area: gpd.GeoDataFrame | gpd.GeoSeries = None, type_join: str = 'range',
    buffer_ft: float = 10, n_samples: int = 10, threshold: float = 0.85,
    crs_ft: str = "EPSG:2236", verbose: bool = False,
    ) -> gpd.GeoDataFrame

Approximate the n%-overlap of df with base_osm via interpolated point-sampling along each OSM segment. $n$ is set by threshold. Note that n_samples does not include the two endpoints, so $n$% is mathematically $\lceil t\times\text{n samples} \rceil / (\text{n samples} + 2)$. Any values computed as NaN will be imputed as -1, for convenience. Parameters - df: gpd.GeoDataFrame Vendor GeoDataFrame containing the attribute field. This will be merged onto base_osm. - field: str column in df with the raw attribute values to be merged onto base_osm. - base_osm: gpd.GeoDataFrame OSM road GeoDataFrame. Output will have the same geometry and attributes. - name: str name of the new categorical column to add. If not passed, will be inferred from the field parameter. - categories: list list of thresholds (for "range") or exact values (for "exact"). If categories is not passed, it will be inferred as a linspace or a logspace (if mean >= 3x median). - road_id: str column in base_osm GeoFrames that uniquely identifies roads. If not passed, will default to a new column set as the index of base_osm. - area: gpd.GeoDataFrame | gpd.GeoSeries polygon boundary of the study area. If not passed, defaults to a the minimum bounding rectangle of df. - type_join: str "range" ⇒ bin by intervals; "exact" ⇒ only keep exact matches. Defaults to range - buffer_ft: float distance to buffer each line/point by to find its match. Defaults to 10 of CRS unit - n_samples: int number of points to interpolate along each segment. Defaults to 10 (meaning 12 total) - threshold: float percentage threshold used to "match" segments. Defaults to 0.85 (85%) - crs_ft: str projected CRS in feet for geometry ops. Defaults to EPSG:2236 (Florida) - verbose: bool Whether to show print statements and progress bars. Default is False Returns - GeoDataFrame in the CRS of base_osm with the extra column name.

compute_area_access

compute_area_access(G: nx.MultiDiGraph, endpoints: LineString | Point, *, 
                    return_nodes: bool = False, return_edges: bool = False,
                    return_graph: bool = False, step: int | float = 1609, 
                    n_steps: int = 4, dist_param: str = 'length',
                    etwork_type: str = 'all', edge_exclusions: dict = None) 
                    -> gpd.GeoDataFrame | nx.MultiDiGraph

A function to compute consecutive ego graphs. It computes n ego graphs at each step to create a GeoDataFrame of edges in the access area with a new dist calculation classifying each edge into a 'distance band'. Useful for visualizations and is less complicated than path_dijkstra.

Parameters: G: nx.MultiDiGraph The graph to be used for computation. endpoints: LineString, MultiLineString, Point, MultiPoint The points to be used for centering the ego graphs. return_nodes: bool Whether the function should return a nodes GeoDataFrame. Default is False. return_edges: bool Whether the function should return an edges GeoDataFrame. Default is False. return_graph: bool Whether the function should return a graph. Default is False. Exactly one of the returns must be true. step: int, float The size of the distance steps the output will contain, in meters. Default is set at 1 mile (1609 meters). n_steps: int The number of distance steps the function will check. dist_param: str The attribute in the graph's edges that will be used to compute distance. The function will raise a ValueError if it is not a valid attribute. network_type: str - {"all", "all_public", "bike", "drive", "drive_service", "walk"} The network type to compute the distances on. Passing an invalid type will default to "all". edge_exclusions: dict A dictionary of the form {field: str | list}; exclude edge values in field attribute Outputs: output: geopandas.GeoDataFrame, nx.MultiDiGraph Either the resulting graph, the nodes of the resulting graph, or the edges of the resulting graph, based on the user's inputs

classifiers

fill_holes_and_dissolve

fill_holes_and_dissolve(geom)

Remove every interior ring, then dissolve overlaps. • Polygon → Polygon without holes • MultiPolygon → each part without holes, then unioned into a single valid geometry (islands kept)

classify_node

classify_node(G, n)

Return number of edges in and out of each node.

find_bridges

find_bridges(G, max_len_ft=100)

Find bridges between two sides of a dual carriageway, topologically

find_res_links (DEPRECATED)

find_res_links(G, max_len_ft=300)

Currently in use to find misclassified slip lanes, but needs future modification. Avoid usage.

collapse_one_in_one_out

collapse_one_in_one_out(G)

Collapses nodes with only one edge in and one edge out. Similar to ox.simplify_graph, but less greedy.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

network_functions-0.1.3.tar.gz (22.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

network_functions-0.1.3-py3-none-any.whl (19.6 kB view details)

Uploaded Python 3

File details

Details for the file network_functions-0.1.3.tar.gz.

File metadata

  • Download URL: network_functions-0.1.3.tar.gz
  • Upload date:
  • Size: 22.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for network_functions-0.1.3.tar.gz
Algorithm Hash digest
SHA256 541ba080d6a276a9f01005b68b7ac6eca78a6ef92f27b13c0fbafefd5a1c4abe
MD5 9fbbb53269efb21247ee5c40da83f189
BLAKE2b-256 0064d22c750f17c818dbce2521d7228fb7cf7ff5e0dde938be0ad5df5a856c25

See more details on using hashes here.

File details

Details for the file network_functions-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for network_functions-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 741c22b735aa23eff4b3c88f68bf91c5e197daf24499a78d23462e2be2b2bec0
MD5 0474e80d48a3bdc6899286270acc2a0a
BLAKE2b-256 401a3786a65c3b98610eb1669b4c03103f79a71521957cb597b81bd5c02a3392

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page