Source code for aequilibrae.project.tools.network_simplifier

import logging
from copy import deepcopy
from math import ceil
from typing import TYPE_CHECKING, List, Literal, Optional

if TYPE_CHECKING:
    from aequilibrae.project.project import Project

import numpy as np
import numpy.typing as npt
import pandas as pd
from shapely.geometry.linestring import LineString
from shapely.ops import linemerge, substring

from aequilibrae.routing.graph import Graph
from aequilibrae.utils.aeq_signal import SIGNAL
from aequilibrae.utils.db_utils import commit_and_close
from aequilibrae.utils.interface.worker_thread import WorkerThread

logger = logging.getLogger(__name__)


[docs] class NetworkSimplifier(WorkerThread): signal = SIGNAL(object) def __init__(self, project: Optional["Project"] = None) -> None: super().__init__(None) if project is None: raise ValueError("An explicit project is required") self.project: Project = project self.tables = self.project.tables self.link_layer = self.tables.links.data logger.warning("This will alter your database in place. Make sure you have a backup.")
[docs] def simplify(self, graph: Graph, max_speed_ratio: float = 1.1): """ Simplifies the network by merging links that are shorter than a given threshold :Arguments: **graph** (:obj:`Graph`): AequilibraE graph. Prepared graphs must use compact topology. **max_speed_ratio** (:obj:`float`, *Optional*): Maximum ratio between the fastest and slowest speed for a link to be considered for simplification. """ self.graph = graph # Creates the sequence of compressed link IDs so we don't have to rebuild through path computation if not isinstance(graph, Graph): raise TypeError("graph must be a Graph built by Network.build_graph()") if not graph.compact: raise ValueError("Network simplification requires a compact graph") mapping = graph.mapping compressed_idx, compressed_link_data = mapping.expansion_offsets, mapping.expansion_links correspondence = pd.DataFrame( { "link_id": mapping.network.link_ids, "__compressed_id__": mapping.network_link_to_graph, } ) # Links removed from the graph no longer have a compressed ID correspondence = correspondence[correspondence.__compressed_id__ >= 0] link_set_df = self.link_layer.merge(correspondence, on="link_id") graph_link_ids = mapping.network.link_ids centroid_connectors = graph_link_ids[~np.isin(graph_link_ids, self.link_layer.link_id)] # compressed_ids that appear for more than one link relevant_compressed_ids = pd.DataFrame(link_set_df.value_counts("__compressed_id__")).query("count>1").index link_set_df = link_set_df[link_set_df.__compressed_id__.isin(relevant_compressed_ids)] # Makes sure we always get the compressed Id for the same (arbitrary) direction link_set_df = link_set_df.sort_values("__compressed_id__").drop_duplicates(subset="link_id", keep="first") # We only need one link ID per "super link" link_set_df = link_set_df.drop_duplicates(subset="__compressed_id__") links_to_delete, new_links = [], [] max_link_id = self.link_layer.link_id.max() + 1 self.signal.emit(["start", link_set_df.shape[0], "Simplifying links"]) counter = 0 for _, rec in link_set_df.iterrows(): counter += 1 self.signal.emit(["update", counter, "Simplifying links"]) compressed_id = rec.__compressed_id__ link_sequence = compressed_link_data[compressed_idx[compressed_id] : compressed_idx[compressed_id + 1]] if len(link_sequence) < 2: continue # Resolve the directed network indices in the expansion mapping to link IDs link_directions = mapping.network.directions[link_sequence] link_sequence = graph_link_ids[link_sequence] retained_links = ~np.isin(link_sequence, centroid_connectors) self.link_sequence = link_sequence[retained_links] link_directions = link_directions[retained_links] self.candidates = self.link_layer.query("link_id in @link_sequence").set_index("link_id") if self.candidates.shape[0] <= 1: continue # To merge, all links have to have the same number of lanes and link type breaker = self.candidates["link_type"].nunique() > 1 if breaker: continue # We build the geometry sequence, speeds, and capacities candidates, geos, long_dir, long_lnk = self.__process_link_fields( self.candidates, self.link_sequence, link_directions, max_speed_ratio ) if candidates.empty: continue new_geo = linemerge(geos) if not isinstance(new_geo, LineString): logger.warning("Failed to merge geometry for superlink around link %s", rec.link_id) continue break_into = ceil(new_geo.length) # Now we build the template for the links we will build main_data = long_lnk.to_dict() if long_lnk is not None else {} # The merged geometry follows traversal, any one-way link makes the whole chain one-way main_data["direction"] = int((candidates["direction"] != 0).any()) # Some values we will bring from the direction-aligned weighted average ordered_candidates = candidates.loc[self.link_sequence] for field in ["speed_ab", "speed_ba", "capacity_ab", "capacity_ba"]: reverse_field = field.replace("ab", "ba") if "ab" in field else field.replace("ba", "ab") values = np.where(link_directions == 1, ordered_candidates[field], ordered_candidates[reverse_field]) main_data[field] = (values * ordered_candidates["distance"]).sum() / candidates["distance"].sum() # If that link is in the opposite direction, we need to swap lanes, # as we would have swapped the geometry as well if long_dir == -1: main_data["lanes_ab"], main_data["lanes_ba"] = main_data["lanes_ba"], main_data["lanes_ab"] for i in range(break_into): data = deepcopy(main_data) data["link_id"] = max_link_id sub_geo = substring(new_geo, i / break_into, (i + 1.0) / break_into, normalized=True) if sub_geo.length < 0.000001: raise ValueError("Link with zero length") data["geo"] = sub_geo.wkb max_link_id += 1 new_links.append(data) links_to_delete.extend(candidates.index.tolist()) self.signal.emit(["finished"]) logger.info(f"{len(links_to_delete):,} links will be removed") logger.info(f"{len(new_links):,} links will be added") if new_links: self.__execute_link_deletion_and_addition(new_links, links_to_delete) logger.warning("Network has been rebuilt. You should run this tool's rebuild network method")
def __process_link_fields( self, candidates: pd.DataFrame, link_sequence: npt.NDArray[np.integer], link_directions: npt.NDArray[np.int8], max_speed_ratio: float = 1.1, ) -> tuple[ pd.DataFrame, list | None, Literal[1, -1] | None, pd.Series | None, ]: longest_link_id = candidates.sort_values("distance", ascending=False).index[0] speed_ab, speed_ba, geos, lanes_ab, lanes_ba = [], [], [], [], [] longest_link, longest_direction = None, None for link_id, link_direction in zip(link_sequence, link_directions, strict=True): link = candidates.loc[link_id] direction = "AB" if link_direction == 1 else "BA" geos.append(link.geometry if direction == "AB" else link.geometry.reverse()) speed_ab.append(link.speed_ab if direction == "AB" else link.speed_ba) speed_ba.append(link.speed_ba if direction == "AB" else link.speed_ab) lanes_ab.append(link.lanes_ab if direction == "AB" else link.lanes_ba) lanes_ba.append(link.lanes_ba if direction == "AB" else link.lanes_ab) if link_id == longest_link_id: # We use the longest link as a template longest_direction = 1 if direction == "AB" else -1 longest_link = link constraints_broken = int(np.unique(lanes_ab).shape[0] > 1) constraints_broken += np.unique(lanes_ba).shape[0] > 1 # Speeds cannot diverge by more than 10% constraints_broken += max(speed_ab) / max(min(speed_ab), 0.00001) > max_speed_ratio constraints_broken += max(speed_ba) / max(min(speed_ba), 0.00001) > max_speed_ratio if constraints_broken > 0: return pd.DataFrame([]), None, None, None return candidates, geos, longest_direction, longest_link def __execute_link_deletion_and_addition(self, new_links: list[dict], links_to_delete: pd.DataFrame | list): df = pd.DataFrame(new_links) df = df.drop(columns=["a_node", "b_node", "geometry"]).rename({"geo": "geometry"}, axis=1) cols = list(df.columns) df = df[cols] data = df.assign(srid=self.link_layer.crs.to_epsg()).to_records(index=False) sql = ( f"INSERT INTO links({','.join(df.columns)}) " f"VALUES ({','.join(['?'] * (len(df.columns) - 1))},GeomFromWKB(?, ?))" ) with commit_and_close(self.project.path_to_file, spatial=True) as conn: conn.executemany(sql, data) conn.executemany("DELETE FROM links WHERE link_id=?", [[x] for x in links_to_delete]) conn.commit() # Validate that we kept distances the same distance_crs = self.link_layer.estimate_utm_crs() old_dist = self.link_layer.geometry.to_crs(distance_crs).length.sum() self.link_layer = self.tables.links.data new_dist = self.link_layer.geometry.to_crs(distance_crs).length.sum() logger.warning("Old distance: %s, new distance: %s. Difference: %s", old_dist, new_dist, old_dist - new_dist)