.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "_auto_examples/route_choice/plot_subarea_analysis.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr__auto_examples_route_choice_plot_subarea_analysis.py: .. _example_usage_sub_area_analysis: Route Choice with sub-area analysis =================================== In this example, we show how to perform sub-area analysis using route choice assignment, for a city in La Serena Metropolitan Area in Chile. .. admonition:: References * :doc:`../../route_choice` .. seealso:: Several functions, methods, classes and modules are used in this example: * :func:`aequilibrae.routing.graph` * :func:`aequilibrae.route_choice.route_choice` * :func:`aequilibrae.route_choice.sub_area` * :func:`aequilibrae.matrix.aequilibrae_matrix` .. GENERATED FROM PYTHON SOURCE LINES 24-39 .. code-block:: Python # Imports import itertools from os.path import join from tempfile import gettempdir from uuid import uuid4 import folium import numpy as np import pandas as pd from aequilibrae.examples import create_example from aequilibrae.utils import basic_config .. GENERATED FROM PYTHON SOURCE LINES 41-47 .. code-block:: Python # We create the example project inside our temp folder fldr = join(gettempdir(), uuid4().hex) project = create_example(fldr, "coquimbo") .. GENERATED FROM PYTHON SOURCE LINES 48-53 .. code-block:: Python # We'll also apply a basic logging configuration. basic_config() .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 54-59 Model parameters ---------------- We'll set the parameters for our route choice model. These are the parameters that will be used to calculate the utility of each path. In our example, the utility is equal to :math:`distance * theta`, and the path overlap factor (PSL) is equal to :math:`beta`. .. GENERATED FROM PYTHON SOURCE LINES 59-64 .. code-block:: Python theta = 0.011 # Distance factor beta = 1.1 # PSL parameter .. GENERATED FROM PYTHON SOURCE LINES 65-66 Let's build all graphs .. GENERATED FROM PYTHON SOURCE LINES 66-70 .. code-block:: Python network = project.road.build_network() # We get warnings that several fields in the project are filled with NaNs. # This is true, but we won't use those fields. .. GENERATED FROM PYTHON SOURCE LINES 71-72 We grab the graph for cars .. GENERATED FROM PYTHON SOURCE LINES 72-73 .. code-block:: Python network.modes .. rst-class:: sphx-glr-script-out .. code-block:: none ('b', 'c', 't', 'w') .. GENERATED FROM PYTHON SOURCE LINES 74-76 Let's say that utility is just a function of distance. So we build our *utility* field as the :math:`distance * theta`. .. GENERATED FROM PYTHON SOURCE LINES 76-78 .. code-block:: Python network.links["utility"] = network.links.distance * theta .. GENERATED FROM PYTHON SOURCE LINES 79-80 Prepare a compact graph for the project centroids. .. GENERATED FROM PYTHON SOURCE LINES 80-82 .. code-block:: Python graph = network.build_graph(mode="c", cost="utility", compact=True) .. GENERATED FROM PYTHON SOURCE LINES 83-87 Mock demand matrix ------------------ We'll create a mock demand matrix with demand `10` for every zone and prepare it for computation. .. GENERATED FROM PYTHON SOURCE LINES 87-92 .. code-block:: Python from aequilibrae.matrix import AequilibraeMatrix, from_df mat = AequilibraeMatrix(index=graph.centroids, index_name="zones") mat["demand"] = np.full((graph.num_zones, graph.num_zones), 10.0) .. GENERATED FROM PYTHON SOURCE LINES 93-100 Sub-area preparation -------------------- We need to define some polygon for out sub-area analysis, here we'll use a section of zones and create out polygon as the union of their geometry. It's best to choose a polygon that avoids any unnecessary intersections with links as the resource requirements of this approach grow quadratically with the number of links cut. .. GENERATED FROM PYTHON SOURCE LINES 100-106 .. code-block:: Python zones_of_interest = [29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 49, 50, 51, 52, 57, 58, 59, 60] zones = project.tables.zones.data.set_index("zone_id") zones = zones.loc[zones_of_interest] zones.head() .. raw:: html
area name population employment geometry
zone_id
29 None None 4665.233898 None MULTIPOLYGON (((-71.32613 -29.97973, -71.32665...
30 None None 4190.454424 None MULTIPOLYGON (((-71.33702 -29.98829, -71.33754...
31 None None 4107.854460 None MULTIPOLYGON (((-71.3308 -29.98206, -71.33131 ...
32 None None 4815.264246 None MULTIPOLYGON (((-71.34687 -29.99529, -71.34791...
33 None None 4556.225468 None MULTIPOLYGON (((-71.33909 -29.97428, -71.33857...


.. GENERATED FROM PYTHON SOURCE LINES 107-114 Sub-area analysis ----------------- From here there are two main paths to conduct a sub-area analysis, manual or automated. AequilibraE ships with a small class that handle most of the details regarding the implementation and extract of the relevant data. It also exposes all the tools necessary to conduct this analysis yourself if you need fine grained control. .. GENERATED FROM PYTHON SOURCE LINES 116-125 Automated sub-area analysis ~~~~~~~~~~~~~~~~~~~~~~~~~~~ We first construct out ``SubAreaAnalysis`` object from the graph, zones, and matrix we previously constructed, then configure the route choice assignment and execute it. From there the ``post_process`` method is able to use the route choice assignment results to construct the desired demand matrix as a DataFrame. If we were interested in the original origin and destination IDs for each entry we could use `subarea.post_process(keep_original_ods=True)` instead. This will attach the true ODs from the select link OD matrix as part of the index. However, this will create a significantly larger, but more flexible matrix. .. GENERATED FROM PYTHON SOURCE LINES 125-133 .. code-block:: Python from aequilibrae.route_choice import SubAreaAnalysis subarea = SubAreaAnalysis(graph, zones, mat, project=project) subarea.rc.set_choice_set_generation("lp", max_routes=3, penalty=1.02, store_results=False) subarea.rc.execute(perform_assignment=True) demand = subarea.post_process() demand .. rst-class:: sphx-glr-script-out .. code-block:: none 0/17689 ODs processed : 0%| | 0/17689 [00:00
demand
origin id destination id
29 29 10.000000
30 10.000000
31 10.000000
32 10.000000
33 10.000000
... ... ...
79892 60 446.582196
67891 44.468296
72092 2750.593321
72161 477.979044
73381 44.468296

543 rows × 1 columns



.. GENERATED FROM PYTHON SOURCE LINES 134-135 We'll re-prepare our graph but with our new "external" ODs. .. GENERATED FROM PYTHON SOURCE LINES 135-139 .. code-block:: Python new_centroids = np.unique(demand.reset_index()[["origin id", "destination id"]].to_numpy().reshape(-1)) graph = network.build_graph(mode="c", cost="utility", centroids=new_centroids, compact=True) new_centroids .. rst-class:: sphx-glr-script-out .. code-block:: none array([ 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 49, 50, 51, 52, 57, 58, 59, 60, 61044, 67891, 68671, 72092, 72096, 72161, 73381, 73432, 73506, 73541, 73589, 75548, 77287, 79297, 79892], dtype=uint64) .. GENERATED FROM PYTHON SOURCE LINES 140-141 We can then perform an assignment using our new demand matrix on the limited graph .. GENERATED FROM PYTHON SOURCE LINES 141-158 .. code-block:: Python from aequilibrae.route_choice import RouteChoice demand_matrix = from_df( demand.reset_index(), row="origin id", col="destination id", subset=list(demand.columns), index=new_centroids, index_name="zones", sparse=True, ) rc = RouteChoice(graph) rc.set_demand(demand_matrix) rc.set_choice_set_generation("lp", max_routes=3, penalty=1.02, store_results=False, seed=123) rc.execute(perform_assignment=True) .. rst-class:: sphx-glr-script-out .. code-block:: none 0/543 ODs processed : 0%| | 0/543 [00:00 .. GENERATED FROM PYTHON SOURCE LINES 164-165 And prepare the sub-area to plot. .. GENERATED FROM PYTHON SOURCE LINES 165-174 .. code-block:: Python subarea_zone = folium.Polygon( locations=[(x[1], x[0]) for x in poly.boundary.coords], fill_color="blue", fill_opacity=0.1, fill=True, weight=1, ) .. GENERATED FROM PYTHON SOURCE LINES 175-176 We create a function to plot out link loads data more easily .. GENERATED FROM PYTHON SOURCE LINES 176-193 .. code-block:: Python def plot_results(link_loads): link_loads = link_loads[link_loads["demand_tot"] > 0] max_load = link_loads[["demand_tot"]].max() links = project.tables.links.data loaded_links = links.merge(link_loads, on="link_id", how="inner") factor = 10 / max_load return loaded_links.explore( color="red", style_kwds={ "style_function": lambda x: { "weight": x["properties"]["demand_tot"] * factor, } }, ) .. GENERATED FROM PYTHON SOURCE LINES 194-195 And plot our data! .. GENERATED FROM PYTHON SOURCE LINES 195-199 .. code-block:: Python map = plot_results(rc.get_load_results()) subarea_zone.add_to(map) map .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 200-204 Sub-area further preparation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's useful later on to know which links from the network cross our polygon. .. GENERATED FROM PYTHON SOURCE LINES 204-208 .. code-block:: Python links = project.tables.links.data inner_links = links[links.crosses(poly.boundary)].sort_index() inner_links.head() .. raw:: html
link_id a_node b_node direction distance modes link_type name speed_ab speed_ba travel_time_ab travel_time_ba capacity_ab capacity_ba geometry osm_id lanes_ab lanes_ba fixed_cost_ab fixed_cost_ba other_attributes
560 734 75548 75321 1 118.672175 ct primary Avenida Costanera 50.0 NaN None None NaN NaN LINESTRING (-71.31995 -29.96046, -71.32004 -29... 1.087246e+09 1.0 NaN None None None
599 777 68671 77289 1 98.456777 ct trunk NaN NaN NaN None None NaN NaN LINESTRING (-71.31844 -29.96439, -71.31855 -29... 1.087084e+09 1.0 NaN None None None
1821 3799 73589 72898 1 38.022984 ct residential Las Violetas NaN NaN None None NaN NaN LINESTRING (-71.3339 -29.98877, -71.33423 -29.... 7.925576e+08 NaN NaN None None None
9462 20823 66687 73506 1 36.529160 ct residential Las Orquídeas NaN NaN None None NaN NaN LINESTRING (-71.33567 -29.98926, -71.33536 -29... 2.322910e+08 NaN NaN None None None
10112 21724 77269 77266 0 105.722347 ct residential Suiza NaN NaN None None NaN NaN LINESTRING (-71.31896 -29.96747, -71.31838 -29... 2.253009e+08 NaN NaN None None None


.. GENERATED FROM PYTHON SOURCE LINES 209-210 As well as which nodes are interior. .. GENERATED FROM PYTHON SOURCE LINES 210-214 .. code-block:: Python nodes = project.tables.nodes.data.set_index("node_id") inside_nodes = nodes.sjoin(zones, how="inner").sort_index() inside_nodes.head() .. raw:: html
is_centroid modes link_types geometry osm_id other_attributes zone_id area name population employment
node_id
29 1 ct z POINT (-71.3234 -29.97278) NaN None 29 None None 4665.233898 None
30 1 ct z POINT (-71.33567 -29.98311) NaN None 30 None None 4190.454424 None
31 1 ct z POINT (-71.33088 -29.97783) NaN None 31 None None 4107.854460 None
32 1 ct z POINT (-71.34347 -29.98923) NaN None 32 None None 4815.264246 None
33 1 ct z POINT (-71.33627 -29.96964) NaN None 33 None None 4556.225468 None


.. GENERATED FROM PYTHON SOURCE LINES 215-217 Let's filter those network links to links retained by the graph, including links inside contracted chains, and create a `link_id`, `direction` multi-index. .. GENERATED FROM PYTHON SOURCE LINES 217-231 .. code-block:: Python mapping = graph.mapping source = mapping.network retained = mapping.network_link_to_graph >= 0 g = pd.DataFrame( { "link_id": source.link_ids[retained], "direction": source.directions[retained], "a_node": source.node_ids[source.link_tails[retained]], "b_node": source.node_ids[source.link_heads[retained]], } ) g = g.loc[g.link_id.isin(inner_links.link_id)].set_index(["link_id", "direction"]) g.head() .. raw:: html
a_node b_node
link_id direction
734 1 75548 75321
777 1 68671 77289
3799 1 73589 72898
20823 1 66687 73506
21724 1 77269 77266


.. GENERATED FROM PYTHON SOURCE LINES 232-234 Here we'll quickly visualise what our sub-area is looking like. We'll plot the polygon from our zoning system and the links that it cuts. .. GENERATED FROM PYTHON SOURCE LINES 234-238 .. code-block:: Python map = inner_links.explore(color="red", style_kwds={"weight": 4}) subarea_zone.add_to(map) map .. raw:: html
Make this Notebook Trusted to load map: File -> Trust Notebook


.. GENERATED FROM PYTHON SOURCE LINES 239-247 Manual sub-area analysis ~~~~~~~~~~~~~~~~~~~~~~~~ Here we'll construct and use the Route Choice class to generate our route sets, In order to perform out analysis we need to know what OD pairs have flow that enters and/or exists our polygon. To do so we perform a select link analysis on all links and pairs of links that cross the boundary. We create them as tuples of tuples to make represent the select link AND sets. .. GENERATED FROM PYTHON SOURCE LINES 247-253 .. code-block:: Python entering = g.loc[~g.a_node.isin(inside_nodes.index) & g.b_node.isin(inside_nodes.index)].index exiting = g.loc[g.a_node.isin(inside_nodes.index) & ~g.b_node.isin(inside_nodes.index)].index edge_pairs = {pair: (pair,) for pair in itertools.product(entering, exiting)} single_edges = {x: ((x,),) for x in g.index} f"Created: {len(edge_pairs)} edge pairs from {len(single_edges)} edges" .. rst-class:: sphx-glr-script-out .. code-block:: none 'Created: 256 edge pairs from 34 edges' .. GENERATED FROM PYTHON SOURCE LINES 254-255 Let's prepare our graph once again .. GENERATED FROM PYTHON SOURCE LINES 255-257 .. code-block:: Python graph = network.build_graph(mode="c", cost="utility", compact=True, block_centroid_flows=False) .. GENERATED FROM PYTHON SOURCE LINES 258-262 Graph construction has already prepared the compressed-link to network-link mapping. We need to supply a Graph and an AequilibraeMatrix or AequilibraeSparseMatrix via the ``set_demand`` method, if demand is not provided link loading cannot be performed. .. GENERATED FROM PYTHON SOURCE LINES 262-265 .. code-block:: Python rc = RouteChoice(graph) rc.set_demand(mat) .. GENERATED FROM PYTHON SOURCE LINES 266-267 Here we add the union of edges as select link sets. .. GENERATED FROM PYTHON SOURCE LINES 267-269 .. code-block:: Python rc.set_select_links(single_edges | edge_pairs) .. GENERATED FROM PYTHON SOURCE LINES 270-272 For the sake of demonstration we limit out demand matrix to a few OD pairs. .. GENERATED FROM PYTHON SOURCE LINES 272-293 .. code-block:: Python ods_pairs_of_interest = [ (4, 39), (92, 37), (31, 58), (4, 19), (39, 34), ] ods_pairs_of_interest = ods_pairs_of_interest + [(x[1], x[0]) for x in ods_pairs_of_interest] # Construct a sparse Aeq matrix for our sub-selection demand = pd.DataFrame( {name: [mat.mat[name, o, d] for o, d in ods_pairs_of_interest] for name in mat}, index=pd.MultiIndex.from_tuples(ods_pairs_of_interest, names=["origin id", "destination id"]), ).sort_index() demand_matrix = from_df(demand.reset_index(), "origin id", "destination id", index=mat.index, sparse=True) rc = RouteChoice(graph) rc.set_demand(demand_matrix) rc.set_select_links(single_edges | edge_pairs) rc.demand .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 294-295 Perform the assignment .. GENERATED FROM PYTHON SOURCE LINES 295-298 .. code-block:: Python rc.set_choice_set_generation("lp", max_routes=3, penalty=1.02, store_results=False, seed=123) rc.execute(perform_assignment=True) .. rst-class:: sphx-glr-script-out .. code-block:: none 0/10 ODs processed : 0%| | 0/10 [00:00 .. GENERATED FROM PYTHON SOURCE LINES 305-307 We'll pull out just OD matrix results as well we need it for the post-processing, we'll also use the returned SciPy CSR arrays directly. .. GENERATED FROM PYTHON SOURCE LINES 307-312 .. code-block:: Python sl_od = rc.get_select_link_od_matrix_results() od_index = demand_matrix.index edge_totals = {k: sl_od[k]["demand"] for k in single_edges} edge_pair_values = {k: sl_od[k]["demand"] for k in edge_pairs} .. GENERATED FROM PYTHON SOURCE LINES 313-317 For the post processing, we are interested in the demand of OD pairs that enter or exit the sub-area, or do both. For the single enters and exists we can extract that information from the single link select link results. We also need to map the links that cross the boundary to the origin/destination node and the node that appears on the outside of the sub-area. .. GENERATED FROM PYTHON SOURCE LINES 317-337 .. code-block:: Python from collections import defaultdict entered = defaultdict(float) exited = defaultdict(float) for (link_id, dir), v in edge_totals.items(): link = g.loc[link_id, dir] for (o, d), load in v.todok().items(): o = od_index[o] d = od_index[d] o_inside = o in inside_nodes.index d_inside = d in inside_nodes.index if o_inside and not d_inside: exited[o, link.b_node] += load elif not o_inside and d_inside: entered[link.a_node, d] += load elif not o_inside and not d_inside: pass .. GENERATED FROM PYTHON SOURCE LINES 338-339 Here he have the load that entered the sub-area .. GENERATED FROM PYTHON SOURCE LINES 339-341 .. code-block:: Python entered .. rst-class:: sphx-glr-script-out .. code-block:: none defaultdict(, {(np.uint64(75548), np.uint64(37)): np.float64(10.0), (np.uint64(67891), np.uint64(39)): np.float64(10.0)}) .. GENERATED FROM PYTHON SOURCE LINES 342-343 and the load that exited the sub-area .. GENERATED FROM PYTHON SOURCE LINES 343-345 .. code-block:: Python exited .. rst-class:: sphx-glr-script-out .. code-block:: none defaultdict(, {(np.uint64(39), np.uint64(67891)): np.float64(10.0), (np.uint64(37), np.uint64(61044)): np.float64(10.0)}) .. GENERATED FROM PYTHON SOURCE LINES 346-347 To find the load that both entered and exited we can look at the edge pair select link results. .. GENERATED FROM PYTHON SOURCE LINES 347-363 .. code-block:: Python through = defaultdict(float) for (l1, l2), v in edge_pair_values.items(): link1 = g.loc[l1] link2 = g.loc[l2] for (o, d), load in v.todok().items(): o = od_index[o] d = od_index[d] o_inside = o in inside_nodes.index d_inside = d in inside_nodes.index if not o_inside and not d_inside: through[link1.a_node, link2.b_node] += load through .. rst-class:: sphx-glr-script-out .. code-block:: none defaultdict(, {(np.uint64(68671), np.uint64(72092)): np.float64(3.5468434501979447), (np.uint64(72092), np.uint64(77287)): np.float64(6.613396221491072), (np.uint64(72092), np.uint64(79297)): np.float64(3.386603778508928), (np.uint64(79892), np.uint64(72092)): np.float64(6.453156549802056)}) .. GENERATED FROM PYTHON SOURCE LINES 364-366 With these results we can construct a new demand matrix. Usually this would be now transplanted onto another network, however for demonstration purposes we'll reuse the same network. .. GENERATED FROM PYTHON SOURCE LINES 366-378 .. code-block:: Python manual_od_pairs = list(entered.keys()) + list(exited.keys()) + list(through.keys()) manual_od_pairs = np.asarray(manual_od_pairs, dtype=np.uint64) demand = pd.DataFrame( list(entered.values()) + list(exited.values()) + list(through.values()), index=pd.MultiIndex.from_arrays( [manual_od_pairs[:, 0], manual_od_pairs[:, 1]], names=["origin id", "destination id"] ), columns=["demand"], ).sort_index() demand.index = demand.index.set_levels([level.astype(np.int64) for level in demand.index.levels]) demand.head() .. raw:: html
demand
origin id destination id
37 61044 10.000000
39 67891 10.000000
67891 39 10.000000
68671 72092 3.546843
72092 77287 6.613396


.. GENERATED FROM PYTHON SOURCE LINES 379-380 We'll re-prepare our graph but with our new "external" ODs. .. GENERATED FROM PYTHON SOURCE LINES 380-384 .. code-block:: Python new_centroids = np.unique(demand.reset_index()[["origin id", "destination id"]].to_numpy(dtype=np.int64).reshape(-1)) graph = network.build_graph(mode="c", cost="utility", centroids=new_centroids, compact=True) new_centroids .. rst-class:: sphx-glr-script-out .. code-block:: none array([ 37, 39, 61044, 67891, 68671, 72092, 75548, 77287, 79297, 79892]) .. GENERATED FROM PYTHON SOURCE LINES 385-386 Re-perform our assignment .. GENERATED FROM PYTHON SOURCE LINES 386-391 .. code-block:: Python rc = RouteChoice(graph) rc.set_demand(from_df(demand.reset_index(), "origin id", "destination id", index=new_centroids, sparse=True)) rc.set_choice_set_generation("lp", max_routes=3, penalty=1.02, store_results=False, seed=123) rc.execute(perform_assignment=True) .. rst-class:: sphx-glr-script-out .. code-block:: none 0/8 ODs processed : 0%| | 0/8 [00:00 .. GENERATED FROM PYTHON SOURCE LINES 398-399 .. code-block:: Python project.close() .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 28.687 seconds) .. _sphx_glr_download__auto_examples_route_choice_plot_subarea_analysis.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_subarea_analysis.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_subarea_analysis.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_subarea_analysis.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_