import itertools
import logging
from collections import defaultdict
from typing import Union
import geopandas as gpd
import numpy as np
import pandas as pd
from scipy.sparse import coo_array, issparse
from aequilibrae.matrix.aequilibrae_matrix import AequilibraeMatrix, AequilibraeSparseMatrix
from aequilibrae.route_choice.route_choice import RouteChoice
from aequilibrae.routing.graph import Graph
logger = logging.getLogger(__name__)
[docs]
class SubAreaAnalysis:
def __init__(
self,
graph: Graph,
subarea: gpd.GeoDataFrame,
demand: Union[AequilibraeMatrix, AequilibraeSparseMatrix],
project=None,
):
"""
Construct a sub-area matrix from a provided sub-area GeoDataFrame using route choice.
This class aims to provide a semi-automated method for constructing the sub-area matrix.
The user should provide a graph, demand matrix, and a GeoDataFrame whose geometry
union represents the desired sub-area. Perform a route choice assignment, then call the
``post_process`` method to obtain a sub-area matrix.
Check how to run sub-area analysis :ref:`here <example_usage_sub_area_analysis>`.
:param project: Required project supplying the source network links and nodes and owning route choice results.
:raises ValueError: If no project is supplied.
:Arguments:
**graph** (:obj:`Graph`): Graph object.
**subarea** (:obj:`gpd.GeoDataFrame`): A GeoPandas GeoDataFrame whose geometry union
represents the sub-area.
**demand** (:obj:`Union[AequilibraeMatrix, AequilibraeSparseMatrix]`): The demand matrix to
provide to the route choice assignment.
"""
if project is None:
raise ValueError("An explicit project is required")
if not isinstance(graph, Graph):
raise TypeError("graph must be a Graph built by Network.build_graph()")
self.graph = graph
self.sub_area_demand = None
links = gpd.GeoDataFrame(project.tables.links.data)
nodes = gpd.GeoDataFrame(project.tables.nodes.data).set_index("node_id")
if subarea.crs != links.crs or nodes.crs != links.crs:
raise ValueError("Sub-area, project links and project nodes must use the same CRS")
self.interior_links = links[links.crosses(subarea.union_all().boundary)].sort_index()
self.interior_nodes = nodes.sjoin(subarea, how="inner").sort_index()
mapping = graph.mapping
network = mapping.network
retained = mapping.network_link_to_graph >= 0
# Boundary endpoints belong to source links, including those inside contracted chains.
edges = pd.DataFrame(
{
"link_id": network.link_ids[retained],
"direction": network.directions[retained],
"a_node": network.node_ids[network.link_tails[retained]],
"b_node": network.node_ids[network.link_heads[retained]],
}
)
self.interior_graph = edges.loc[edges.link_id.isin(self.interior_links.link_id)].set_index(
["link_id", "direction"]
)
entering = [
edge
for edge, link in self.interior_graph.iterrows()
if link.a_node not in self.interior_nodes.index and link.b_node in self.interior_nodes.index
]
exiting = [
edge
for edge, link in self.interior_graph.iterrows()
if link.a_node in self.interior_nodes.index and link.b_node not in self.interior_nodes.index
]
self.edge_pairs = {pair: (pair,) for pair in itertools.product(entering, exiting)}
self.single_edges = {x: ((x,),) for x in self.interior_graph.index}
logger.info(f"Created: {len(self.edge_pairs)} edge pairs from {len(self.single_edges)} edges")
self.rc = RouteChoice(self.graph, project=project)
self.rc.set_demand(demand)
self.rc.set_select_links(self.single_edges | self.edge_pairs, link_loading=False)
[docs]
def post_process(self, demand_cols=None, keep_original_ods: bool = False):
"""
Apply the necessary post processing to the route choice assignment select link results.
:Arguments:
**demand_cols** (:obj:`[list[str]]`, optional): If provided, only construct the
sub-area matrix for these demand matrices.
**keep_original_ods** (:obj:`bool`, optional): If provided, the original origin and destination IDs for
the demand will be kept. This will create a significantly larger demand matrix but is more flexible.
:Returns:
**sub_area_demand** (:obj:`pd.DataFrame`): A DataFrame representing the sub-area demand matrix.
"""
assert self.rc.demand is not None
if demand_cols is None:
demand_cols = tuple(self.rc.demand)
sl_od = self.rc.get_select_link_od_matrix_results()
index = self.rc.demand.index
sub_area_demand = []
for col in demand_cols:
edge_totals = {k: sl_od[k][col] for k in self.single_edges}
edge_pair_values = {k: sl_od[k][col] for k in self.edge_pairs}
entered = defaultdict(float)
exited = defaultdict(float)
for (link_id, dir), v in edge_totals.items():
link = self.interior_graph.loc[link_id, dir]
for (o, d), load in v.todok().items():
o = index[o]
d = index[d]
o_inside = o in self.interior_nodes.index
d_inside = d in self.interior_nodes.index
original_ods = (o, d) if keep_original_ods else ()
if o_inside and not d_inside:
exited[(o, link.b_node) + original_ods] += load
elif not o_inside and d_inside:
entered[(link.a_node, d) + original_ods] += load
elif not o_inside and not d_inside:
pass
through = defaultdict(float)
for (l1, l2), v in edge_pair_values.items():
link1 = self.interior_graph.loc[l1]
link2 = self.interior_graph.loc[l2]
for (o, d), load in v.todok().items():
o = index[o]
d = index[d]
o_inside = o in self.interior_nodes.index
d_inside = d in self.interior_nodes.index
original_ods = (o, d) if keep_original_ods else ()
if not o_inside and not d_inside:
through[(link1.a_node, link2.b_node) + original_ods] += load
subarea_od_keys = list(entered) + list(exited) + list(through)
subarea_od_values = list(entered.values()) + list(exited.values()) + list(through.values())
subarea_od_ids = np.asarray(subarea_od_keys, dtype=np.uint64).reshape(-1, 4 if keep_original_ods else 2)
id_columns = list(subarea_od_ids.T)
id_names = ["origin id", "destination id"]
if keep_original_ods:
id_names += ["original origin id", "original destination id"]
sub_area_demand.append(
pd.DataFrame(
subarea_od_values,
index=pd.MultiIndex.from_arrays(id_columns, names=id_names),
columns=[col],
dtype=np.float64,
)
)
interior = []
inside = np.flatnonzero(np.isin(self.rc.demand.index, self.interior_nodes.index))
inside_ids = self.rc.demand.index[inside]
for col in demand_cols:
values = self.rc.demand[col]
values = values.tocsr()[inside][:, inside] if issparse(values) else values[np.ix_(inside, inside)]
records = coo_array(values)
nonzero = records.data != 0
interior.append(
pd.Series(
records.data[nonzero],
name=col,
index=pd.MultiIndex.from_arrays(
[
inside_ids[records.row[nonzero]].astype(np.uint64, copy=False),
inside_ids[records.col[nonzero]].astype(np.uint64, copy=False),
],
names=["origin id", "destination id"],
),
)
)
self.sub_area_demand = pd.concat(sub_area_demand, axis=1).fillna(0.0)
interior = pd.concat(interior, axis=1).fillna(0.0)
if keep_original_ods:
# We need to duplicate the interior ODs if we're "keeping the originals"
interior.index = pd.MultiIndex.from_arrays(
[np.asarray(interior.index.get_level_values(level % 2), dtype=np.uint64) for level in range(4)],
names=self.sub_area_demand.index.names,
)
self.sub_area_demand = pd.concat([self.sub_area_demand, interior]).sort_index()
# Boundary nodes and demand centroids can have different integer dtypes.
self.sub_area_demand.index = pd.MultiIndex.from_arrays(
[
self.sub_area_demand.index.get_level_values(name).to_numpy(dtype="uint64")
for name in self.sub_area_demand.index.names
],
names=self.sub_area_demand.index.names,
)
return self.sub_area_demand