aequilibrae.traffic#

Classes

VDF(name, function, spec[, derivative])

Volume-Delay function that describes the total travel time across a link for a based on its free flow travel time and capacity for a given volume of traffic.

AssignmentResults()

Public results for one traffic class, backed by compact output owners.

TrafficAssignment(*, network, classes, ...)

Traffic assignment class.

TrafficClass(*, mode, cost, demand, name, ...)

Define a traffic class independently of a network or prepared graph.

class aequilibrae.traffic.AssignmentResults[source]#

Public results for one traffic class, backed by compact output owners.

Skims and selected OD demand are the routing output objects. Full-network link loads are reporting snapshots, not a second mutable assignment state. Every load and turn total is in the original demand units, without PCE.

static get_heaps()[source]#
bind(state, class_names)[source]#

Attach the accepted or latest AoN state at the start of execution.

get_load_results()[source]#

Return directional link loads in external network link order.

get_sl_results()[source]#

Return directional link loads for each selection and demand column.

reset()[source]#
set_cores(cores, threading_threshold=None, elementwise_cores=None)#

Set thread counts without reallocating or clearing existing results.

set_heap(heap)[source]#

Read-only snapshot of loads in supernetwork order.

property output#
property skims#
property state#
property total_turn_penalty#
property unassigned_demand#
class aequilibrae.traffic.TrafficAssignment(*, network: Network, classes: list[TrafficClass], time_field: str, capacity_field: str, vdf: VDF, algorithm: str, name_mapping=None, preload=None, project=None)[source]#

Traffic assignment class.

The constructor retains a supplied standalone Network, then checks compatibility. Do not mutate that Network during use. execute() prepares each class’s routing graph and returns link results. Classes share the network reporting mapping, but build their own graph mappings. Each class owns its costs, demand, skims, and output buffers.

For a comprehensive example on use, see the Use examples page.

>>> from aequilibrae.traffic import TrafficAssignment, TrafficClass
>>> from aequilibrae.traffic.vdf import bpr
>>> project = create_example(project_path)
>>> network = project.road.build_network()
>>> proj_matrices = project.matrices

# We will only assign one user class stored as 'matrix' inside the OMX file
>>> demand = proj_matrices.get_matrix("demand.omx", subset=["matrix"])

# Creates the assignment class
>>> assigclass = TrafficClass(
...     name="car", mode="c", cost="free_flow_time", demand=demand,
...     skimming=['free_flow_time', 'distance'], graph_options={'block_centroid_flows': False},
... )
>>> assig = TrafficAssignment(
...     network=network, project=project, classes=[assigclass], time_field='free_flow_time',
...     capacity_field='capacity', vdf=bpr,
...     name_mapping={"alpha": "b", "beta": "power"}, algorithm='bfw',
... )
>>> results_df = assig.execute(max_iterations=10, rgap=0.00001)

# If you want, it is possible to access the convergence report
>>> convergence_report = pd.DataFrame(assig.assignment.convergence_report)

# Assignment results can be viewed as a Pandas DataFrame
>>> results_df = assig.results()

# Information on the assignment setup can be recovered with
>>> info = assig.info()

# Or save it directly to the results database
>>> results = assig.save_results(table_name='base_year_assignment')

# skims are here
>>> avg_skims = assig.class_results['car'].skims # blended ones

>>> project.close()
algorithms_available() → list#

Returns all algorithms available for use

Returns:

list: Available algorithm names

execute(*, max_iterations=None, rgap=None, cores=None, threading_threshold=None, elementwise_cores=None, bfw_conjugacy='approximate', steps_below_needed_to_terminate=1, log_specification=True) → DataFrame[source]#

Prepare graphs, run assignment, and return link results.

Execution options apply to this run. Source data comes from the network retained by the constructor. Each run owns fresh routing contexts and outputs.

bfw_conjugacy chooses how BFW solves for its direction coefficients. Ignored by every other algorithm.

  • "approximate" (default) - appendix A of Mitradjieva & Lindberg, which assumes the two previous directions are already conjugate with respect to the current Hessian. They were made conjugate with respect to the previous one, so the assumption holds only in the limit; the paper notes BFW is therefore “correct only in the limit”.

  • "exact" - solve both conjugacy conditions jointly as a 2x2 system, keeping the cross term the appendix drops. Costs two extra Hessian contractions per iteration, which is negligible next to the shortest-path build. The system is singular when the two previous directions are H-parallel, in which case the iteration restarts from Frank-Wolfe.

Either way, negative coefficients are clamped to zero to keep the weights on the simplex, and that clamping breaks strict biconjugacy whenever it triggers.

When the algorithm is BFW the convergence report gains conjugacy_prev, conjugacy_prev2 and hessian_drift columns to compare the two variants; see LinearApproximation.

Arguments:

cores (int): Number of CPU cores to use

threading_threshold (int, Optional): Minimum number of array elements for elementwise operations to be threaded. Negative values disable threading for those operations.

elementwise_cores (int, Optional): Number of CPU cores for elementwise (parallel_numpy/VDF) operations. When not provided, it is resolved from the AEQ_ELEMENTWISE_CPUS environment variable or parameters.yml, defaulting to at most 8 threads

get_skim_results()[source]#

Return assignment skims by class name.

info() → dict[source]#

Returns information for the traffic assignment procedure

Dictionary contains keys ‘Algorithm’, ‘Classes’, ‘Computer name’, ‘Procedure ID’, ‘Maximum iterations’ and ‘Target RGap’.

The classes key is also a dictionary with all the user classes per traffic class and their respective matrix totals

Returns:

info (dict): Dictionary with summary information

log_specification()[source]#
report() → DataFrame#

Returns the assignment convergence report

Returns:

DataFrame (pd.DataFrame): Convergence report

results() → DataFrame[source]#

Prepares the assignment results as a Pandas DataFrame

Class load columns use demand matrix names without a traffic-class prefix. Names must be unique across classes and shared network metrics.

Returns:

DataFrame (pd.DataFrame): Pandas DataFrame with all the assignment results indexed on link_id

save_results(table_name: str, keep_zero_flows=True, project=None) → None[source]#

Saves the assignment results to results_database.sqlite

Method fails if table exists

Arguments:

table_name (str): Name of the table to hold this assignment result

keep_zero_flows (bool): Whether we should keep records for zero flows. Defaults to True

project (Project, Optional): Project we want to save the results to. Defaults to the explicitly supplied constructor project

Saves the select link link flows for all classes into the results database.

Arguments:

table_name (str): Name of the table being inserted to. Note the traffic class

project (Project, Optional): Project we want to save the results to. Defaults to the explicitly supplied constructor project

Saves the Select Link matrices for each TrafficClass in the current TrafficAssignment class into OMX format.

Arguments:

name (str): name of the matrices

project (Project, Optional): Project we want to save the results to. Defaults to the explicitly supplied constructor project

Saves both the Select Link matrices and flow results at the same time, using the same name.

Arguments:

name (str): name of the matrices

save_skims(matrix_name: str, which_ones='final', format='omx', project=None) → list[str][source]#

Saves the skims (if any) to the project’s matrix folder

Arguments:

matrix_name (str): Base file name for the matrices, suffixed with each traffic class ID

which_ones (str, Optional): ‘final’: Results of the final iteration,

‘blended’: Averaged results for all iterations, ‘all’: Saves skims for both the final iteration and the blended ones. Default is ‘final’

format (str, Optional): File format (‘omx’). Default is ‘omx’

project (Project, Optional): Project we want to save the results to.

Defaults to the explicitly supplied constructor project

Returns:

file_names (list): OMX file names saved for classes with skims to save.

Returns a dataframe of the select link flows for each class

skim_congested(skim_fields=None, return_matrices=False) → dict | None[source]#

Skims the congested network. The user can add a list of skims to be computed, which will be added to the congested time and the assignment cost from the last iteration of the assignment.

The matrices are always stored internally in the AequilibraE objects to be saved to the project if needed. If return_matrices is set to True, the matrices are also returned.

Arguments:

skim_fields (Union[None, str]): Name of the skims to use. If None, uses default only return_matrices (Bool): Returns a dictionary with skims. Defaults to False.

all_algorithms = ['all-or-nothing', 'msa', 'frank-wolfe', 'fw', 'cfw', 'bfw']#
all_bfw_conjugacies = ['approximate', 'exact']#
property class_results#

Return results by traffic class name after execution.

class aequilibrae.traffic.TrafficClass(*, mode: str, cost: str, demand: AequilibraeMatrix | AequilibraeSparseMatrix, name: str | None = None, pce: float = 1.0, vot: float = 1.0, skimming: tuple[str, ...]=(), fixed_cost_field: str | None = None, fixed_cost_multiplier: float = 1.0, select_link_sets: Mapping[str, tuple]=<factory>, select_link_od: bool = True, graph_options: Mapping[str, bool]=<factory>, heap: str = '4ary')[source]#

Define a traffic class independently of a network or prepared graph.

cost is the free-flow generalised cost in time units. Congestion adds the change in travel time. Fixed costs are multiplied by fixed_cost_multiplier and divided by vot.

Demand matrices must contain float64 values. name defaults to the mode. Classes with the same mode need distinct names. graph_options accepts compact, remove_dead_ends, block_centroid_flows and allow_uturns. Omitted U-turn policy inherits the network setting.

>>> from aequilibrae.traffic import TrafficClass

>>> project = create_example(project_path)
>>> proj_matrices = project.matrices

>>> demand = proj_matrices.get_matrix("demand.omx", subset=["matrix"])

>>> tc = TrafficClass(
...     name="car", mode="c", cost='free_flow_time', demand=demand, pce=1.3,
...     skimming=['free_flow_time', 'distance'], graph_options={'block_centroid_flows': False},
... )

>>> project.close()
cost: str#
demand: AequilibraeMatrix | AequilibraeSparseMatrix#
fixed_cost_field: str | None = None#
fixed_cost_multiplier: float = 1.0#
graph_options: Mapping[str, bool]#
heap: str = '4ary'#
property info#
mode: str#
name: str | None = None#
pce: float = 1.0#
skimming: tuple[str, ...] = ()#
vot: float = 1.0#
class aequilibrae.traffic.VDF(name: str, function: Callable | str, spec: dict, derivative: Callable | str | None = None)[source]#

Volume-Delay function that describes the total travel time across a link for a based on its free flow travel time and capacity for a given volume of traffic. Supports multiplicative and additive delays, and returns the absolute congested time rather than a delay or factor***

>>> from aequilibrae.traffic import VDF
static convert_str_function_into_function(function_def: str) → Callable[source]#
apply_derivative(*, delta, link_flows, fftime, capacity, cores: int, **link_attributes)[source]#
apply_vdf(*, congested_time, link_flows, fftime, capacity, cores: int, **link_attributes)[source]#
check_valid(num_points, link_attributes: dict[str, Any], from_voc: float = 0.0, to_voc: float = 3.0)[source]#

Implements checks for VDF requirements described by Spiess (1990) in “Technical Note—Conical Volume-Delay Functions” (Transportation Science, 24(2): 153-158).

The VDF is evaluated at num_points values of volume/capacity in the range between from_voc to to_voc. Then, these values are used in the following checks:

It is strictly increasing, found by comparing neighbouring function values and checking that the derivative is positive. It is convex from above, found by checking that the derivative only increases between evaluated points For zero volume on the road, the VDF returns the free flow travel time

Any violations found are printed, listing the offending volume/capacity values.

Arguments:

num_points (int): the number of volume/capacity values at which to evaluate the VDF and its derivative between from_voc and to_voc.

link_attributes (dict[str, Any]): mapping of link attribute names to values used to evaluate the VDF and its derivative, for example secondary capacity or the parameters for the VDF.

from_voc (float, Optional): the lower bound of the volume/capacity range to evaluate. Defaults to 0.0.

to_voc (float, Optional): the upper bound of the volume/capacity range to evaluate. Defaults to 3.0.

Returns:

vdf_valid_0_value (bool): True if the VDF evaluates to 1 (the free flow travel time) at zero volume/capacity, within a small tolerance.

vdf_increasing_f_vals (bool): True if the VDF’s values are non-decreasing across the evaluated volume/capacity range.

vdf_nonnegative_derivative (bool): True if the VDF’s derivative is non-negative across the evaluated volume/capacity range.

vdf_convex (bool): True if the VDF’s derivative is non-decreasing across the evaluated volume/capacity range (i.e. the VDF is convex from above).

make_finite_difference_derivative(eps: float = 0.0001) → Callable[source]#
plot_vdf(num_points: int, link_attributes: dict[str, Any])[source]#

Creates a plot of the vdf using num_points for velocity/capacity in the range [0,3]. Link attributes are directly passed self.apply_vdf() and self.apply_derivative, so they may need to be a numpy array the size of num_points.