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.

References

See also

Several functions, methods, classes and modules are used in this example:

  • aequilibrae.routing.graph()

  • aequilibrae.route_choice.route_choice()

  • aequilibrae.route_choice.sub_area()

  • aequilibrae.matrix.aequilibrae_matrix()

# 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
# We create the example project inside our temp folder
fldr = join(gettempdir(), uuid4().hex)

project = create_example(fldr, "coquimbo")
# We'll also apply a basic logging configuration.

basic_config()
<AequilibraETQDMStreamHandler (NOTSET)>

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 \(distance * theta\), and the path overlap factor (PSL) is equal to \(beta\).

theta = 0.011  # Distance factor

beta = 1.1  # PSL parameter

Let’s build all graphs

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.

We grab the graph for cars

network.modes
('b', 'c', 't', 'w')

Let’s say that utility is just a function of distance. So we build our utility field as the \(distance * theta\).

network.links["utility"] = network.links.distance * theta

Prepare a compact graph for the project centroids.

graph = network.build_graph(mode="c", cost="utility", compact=True)

Mock demand matrix#

We’ll create a mock demand matrix with demand 10 for every zone and prepare it for computation.

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)

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.

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()
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...


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.

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.

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
0/17689 ODs processed                             :   0%|          | 0/17689 [00:00<?, ?it/s]
0/17689 ODs processed                             :   2%|▏         | 366/17689 [00:00<00:23, 748.93it/s]
366/17689 ODs processed                           :   2%|▏         | 366/17689 [00:00<00:23, 748.93it/s]
366/17689 ODs processed                           :   4%|▍         | 763/17689 [00:00<00:21, 775.25it/s]
763/17689 ODs processed                           :   4%|▍         | 763/17689 [00:00<00:21, 775.25it/s]
763/17689 ODs processed                           :   7%|▋         | 1176/17689 [00:01<00:20, 798.19it/s]
1176/17689 ODs processed                          :   7%|▋         | 1176/17689 [00:01<00:20, 798.19it/s]
1176/17689 ODs processed                          :   9%|▊         | 1512/17689 [00:01<00:21, 747.96it/s]
1512/17689 ODs processed                          :   9%|▊         | 1512/17689 [00:01<00:21, 747.96it/s]
1512/17689 ODs processed                          :  11%|█         | 1858/17689 [00:02<00:21, 727.49it/s]
1858/17689 ODs processed                          :  11%|█         | 1858/17689 [00:02<00:21, 727.49it/s]
1858/17689 ODs processed                          :  13%|█▎        | 2236/17689 [00:02<00:20, 736.93it/s]
2236/17689 ODs processed                          :  13%|█▎        | 2236/17689 [00:02<00:20, 736.93it/s]
2236/17689 ODs processed                          :  15%|█▍        | 2586/17689 [00:03<00:20, 724.59it/s]
2586/17689 ODs processed                          :  15%|█▍        | 2586/17689 [00:03<00:20, 724.59it/s]
2586/17689 ODs processed                          :  17%|█▋        | 3015/17689 [00:03<00:19, 766.79it/s]
3015/17689 ODs processed                          :  17%|█▋        | 3015/17689 [00:03<00:19, 766.79it/s]
3015/17689 ODs processed                          :  19%|█▉        | 3444/17689 [00:04<00:17, 795.03it/s]
3444/17689 ODs processed                          :  19%|█▉        | 3444/17689 [00:04<00:17, 795.03it/s]
3444/17689 ODs processed                          :  22%|██▏       | 3918/17689 [00:04<00:16, 841.93it/s]
3918/17689 ODs processed                          :  22%|██▏       | 3918/17689 [00:04<00:16, 841.93it/s]
3918/17689 ODs processed                          :  25%|██▍       | 4376/17689 [00:05<00:15, 864.28it/s]
4376/17689 ODs processed                          :  25%|██▍       | 4376/17689 [00:05<00:15, 864.28it/s]
4376/17689 ODs processed                          :  27%|██▋       | 4849/17689 [00:05<00:14, 888.89it/s]
4849/17689 ODs processed                          :  27%|██▋       | 4849/17689 [00:05<00:14, 888.89it/s]
4849/17689 ODs processed                          :  30%|██▉       | 5303/17689 [00:06<00:13, 894.41it/s]
5303/17689 ODs processed                          :  30%|██▉       | 5303/17689 [00:06<00:13, 894.41it/s]
5303/17689 ODs processed                          :  32%|███▏      | 5650/17689 [00:06<00:14, 833.69it/s]
5650/17689 ODs processed                          :  32%|███▏      | 5650/17689 [00:06<00:14, 833.69it/s]
5650/17689 ODs processed                          :  35%|███▍      | 6107/17689 [00:07<00:13, 857.62it/s]
6107/17689 ODs processed                          :  35%|███▍      | 6107/17689 [00:07<00:13, 857.62it/s]
6107/17689 ODs processed                          :  37%|███▋      | 6519/17689 [00:07<00:13, 847.30it/s]
6519/17689 ODs processed                          :  37%|███▋      | 6519/17689 [00:07<00:13, 847.30it/s]
6519/17689 ODs processed                          :  40%|███▉      | 6989/17689 [00:08<00:12, 874.92it/s]
6989/17689 ODs processed                          :  40%|███▉      | 6989/17689 [00:08<00:12, 874.92it/s]
6989/17689 ODs processed                          :  42%|████▏     | 7443/17689 [00:08<00:11, 884.63it/s]
7443/17689 ODs processed                          :  42%|████▏     | 7443/17689 [00:08<00:11, 884.63it/s]
7443/17689 ODs processed                          :  45%|████▍     | 7931/17689 [00:09<00:10, 911.83it/s]
7931/17689 ODs processed                          :  45%|████▍     | 7931/17689 [00:09<00:10, 911.83it/s]
7931/17689 ODs processed                          :  47%|████▋     | 8302/17689 [00:09<00:10, 860.63it/s]
8302/17689 ODs processed                          :  47%|████▋     | 8302/17689 [00:09<00:10, 860.63it/s]
8302/17689 ODs processed                          :  50%|████▉     | 8837/17689 [00:10<00:09, 921.02it/s]
8837/17689 ODs processed                          :  50%|████▉     | 8837/17689 [00:10<00:09, 921.02it/s]
8837/17689 ODs processed                          :  52%|█████▏    | 9209/17689 [00:11<00:09, 867.79it/s]
9209/17689 ODs processed                          :  52%|█████▏    | 9209/17689 [00:11<00:09, 867.79it/s]
9209/17689 ODs processed                          :  54%|█████▍    | 9566/17689 [00:11<00:09, 821.52it/s]
9566/17689 ODs processed                          :  54%|█████▍    | 9566/17689 [00:11<00:09, 821.52it/s]
9566/17689 ODs processed                          :  56%|█████▌    | 9919/17689 [00:12<00:09, 786.71it/s]
9919/17689 ODs processed                          :  56%|█████▌    | 9919/17689 [00:12<00:09, 786.71it/s]
9919/17689 ODs processed                          :  58%|█████▊    | 10270/17689 [00:12<00:09, 761.15it/s]
10270/17689 ODs processed                         :  58%|█████▊    | 10270/17689 [00:12<00:09, 761.15it/s]
10270/17689 ODs processed                         :  60%|██████    | 10662/17689 [00:13<00:09, 767.80it/s]
10662/17689 ODs processed                         :  60%|██████    | 10662/17689 [00:13<00:09, 767.80it/s]
10662/17689 ODs processed                         :  62%|██████▏   | 11044/17689 [00:13<00:08, 766.43it/s]
11044/17689 ODs processed                         :  62%|██████▏   | 11044/17689 [00:13<00:08, 766.43it/s]
11044/17689 ODs processed                         :  64%|██████▍   | 11400/17689 [00:14<00:08, 749.87it/s]
11400/17689 ODs processed                         :  64%|██████▍   | 11400/17689 [00:14<00:08, 749.87it/s]
11400/17689 ODs processed                         :  67%|██████▋   | 11819/17689 [00:14<00:07, 776.06it/s]
11819/17689 ODs processed                         :  67%|██████▋   | 11819/17689 [00:14<00:07, 776.06it/s]
11819/17689 ODs processed                         :  69%|██████▉   | 12162/17689 [00:15<00:07, 748.87it/s]
12162/17689 ODs processed                         :  69%|██████▉   | 12162/17689 [00:15<00:07, 748.87it/s]
12162/17689 ODs processed                         :  71%|███████   | 12505/17689 [00:15<00:07, 729.80it/s]
12505/17689 ODs processed                         :  71%|███████   | 12505/17689 [00:15<00:07, 729.80it/s]
12505/17689 ODs processed                         :  73%|███████▎  | 12881/17689 [00:16<00:06, 736.22it/s]
12881/17689 ODs processed                         :  73%|███████▎  | 12881/17689 [00:16<00:06, 736.22it/s]
12881/17689 ODs processed                         :  75%|███████▌  | 13294/17689 [00:16<00:05, 762.88it/s]
13294/17689 ODs processed                         :  75%|███████▌  | 13294/17689 [00:16<00:05, 762.88it/s]
13294/17689 ODs processed                         :  78%|███████▊  | 13720/17689 [00:17<00:05, 789.34it/s]
13720/17689 ODs processed                         :  78%|███████▊  | 13720/17689 [00:17<00:05, 789.34it/s]
13720/17689 ODs processed                         :  80%|███████▉  | 14068/17689 [00:17<00:04, 761.14it/s]
14068/17689 ODs processed                         :  80%|███████▉  | 14068/17689 [00:17<00:04, 761.14it/s]
14068/17689 ODs processed                         :  82%|████████▏ | 14434/17689 [00:18<00:04, 752.21it/s]
14434/17689 ODs processed                         :  82%|████████▏ | 14434/17689 [00:18<00:04, 752.21it/s]
14434/17689 ODs processed                         :  84%|████████▍ | 14848/17689 [00:18<00:03, 774.73it/s]
14848/17689 ODs processed                         :  84%|████████▍ | 14848/17689 [00:18<00:03, 774.73it/s]
14848/17689 ODs processed                         :  86%|████████▌ | 15230/17689 [00:19<00:03, 771.32it/s]
15230/17689 ODs processed                         :  86%|████████▌ | 15230/17689 [00:19<00:03, 771.32it/s]
15230/17689 ODs processed                         :  88%|████████▊ | 15632/17689 [00:19<00:02, 780.91it/s]
15632/17689 ODs processed                         :  88%|████████▊ | 15632/17689 [00:19<00:02, 780.91it/s]
15632/17689 ODs processed                         :  91%|█████████ | 16124/17689 [00:20<00:01, 841.57it/s]
16124/17689 ODs processed                         :  91%|█████████ | 16124/17689 [00:20<00:01, 841.57it/s]
16124/17689 ODs processed                         :  93%|█████████▎| 16528/17689 [00:20<00:01, 831.29it/s]
16528/17689 ODs processed                         :  93%|█████████▎| 16528/17689 [00:20<00:01, 831.29it/s]
16528/17689 ODs processed                         :  96%|█████████▌| 17005/17689 [00:21<00:00, 867.87it/s]
17005/17689 ODs processed                         :  96%|█████████▌| 17005/17689 [00:21<00:00, 867.87it/s]
17005/17689 ODs processed                         :  99%|█████████▉| 17475/17689 [00:21<00:00, 889.28it/s]
17475/17689 ODs processed                         :  99%|█████████▉| 17475/17689 [00:21<00:00, 889.28it/s]
17475/17689 ODs processed                         : 100%|██████████| 17689/17689 [00:22<00:00, 750.81it/s]
17689/17689 ODs processed                         : 100%|██████████| 17689/17689 [00:22<00:00, 750.81it/s]
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



We’ll re-prepare our graph but with our new “external” ODs.

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
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)

We can then perform an assignment using our new demand matrix on the limited graph

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)
0/543 ODs processed                               :   0%|          | 0/543 [00:00<?, ?it/s]
0/543 ODs processed                               : 100%|██████████| 543/543 [00:00<00:00, 1088.16it/s]
543/543 ODs processed                             : 100%|██████████| 543/543 [00:00<00:00, 1088.16it/s]

Let’s take the union of the zones GeoDataFrame as a polygon

poly = zones.union_all()
poly
<POLYGON ((-71.348 -29.993, -71.349 -29.993, -71.35 -29.992, -71.349 -29.991...>

And prepare the sub-area to plot.

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,
)

We create a function to plot out link loads data more easily

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,
            }
        },
    )

And plot our data!

map = plot_results(rc.get_load_results())
subarea_zone.add_to(map)
map
<folium.folium.Map object at 0x727c090d7410>

Sub-area further preparation#

It’s useful later on to know which links from the network cross our polygon.

links = project.tables.links.data
inner_links = links[links.crosses(poly.boundary)].sort_index()
inner_links.head()
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


As well as which nodes are interior.

nodes = project.tables.nodes.data.set_index("node_id")
inside_nodes = nodes.sjoin(zones, how="inner").sort_index()
inside_nodes.head()
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


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.

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()
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


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.

map = inner_links.explore(color="red", style_kwds={"weight": 4})
subarea_zone.add_to(map)
map
Make this Notebook Trusted to load map: File -> Trust Notebook


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.

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"
'Created: 256 edge pairs from 34 edges'

Let’s prepare our graph once again

graph = network.build_graph(mode="c", cost="utility", compact=True, block_centroid_flows=False)

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.

Here we add the union of edges as select link sets.

rc.set_select_links(single_edges | edge_pairs)

For the sake of demonstration we limit out demand matrix to a few OD pairs.

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
<aequilibrae.matrix.aequilibrae_matrix.AequilibraeSparseMatrix object at 0x727c0883a110>

Perform the assignment

rc.set_choice_set_generation("lp", max_routes=3, penalty=1.02, store_results=False, seed=123)
rc.execute(perform_assignment=True)
0/10 ODs processed                                :   0%|          | 0/10 [00:00<?, ?it/s]
0/10 ODs processed                                : 100%|██████████| 10/10 [00:00<00:00, 20.03it/s]
10/10 ODs processed                               : 100%|██████████| 10/10 [00:00<00:00, 20.03it/s]

We can visualise the current links loads

map = plot_results(rc.get_load_results())
subarea_zone.add_to(map)
map
<folium.folium.Map object at 0x727c0883aad0>

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.

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}

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.

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

Here he have the load that entered the sub-area

entered
defaultdict(<class 'float'>, {(np.uint64(75548), np.uint64(37)): np.float64(10.0), (np.uint64(67891), np.uint64(39)): np.float64(10.0)})

and the load that exited the sub-area

exited
defaultdict(<class 'float'>, {(np.uint64(39), np.uint64(67891)): np.float64(10.0), (np.uint64(37), np.uint64(61044)): np.float64(10.0)})

To find the load that both entered and exited we can look at the edge pair select link results.

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
defaultdict(<class 'float'>, {(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)})

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.

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()
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


We’ll re-prepare our graph but with our new “external” ODs.

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
array([   37,    39, 61044, 67891, 68671, 72092, 75548, 77287, 79297,
       79892])

Re-perform our assignment

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)
0/8 ODs processed                                 :   0%|          | 0/8 [00:00<?, ?it/s]
0/8 ODs processed                                 : 100%|██████████| 8/8 [00:00<00:00, 16.02it/s]
8/8 ODs processed                                 : 100%|██████████| 8/8 [00:00<00:00, 16.02it/s]

And plot the link loads for easy viewing

map = plot_results(rc.get_load_results())
subarea_zone.add_to(map)
map
<folium.folium.Map object at 0x727c08b11390>

Total running time of the script: (0 minutes 25.422 seconds)

Gallery generated by Sphinx-Gallery