aequilibrae.paths#

class aequilibrae.paths.AssignmentPaths(table_name: str, project=None)[source]#

Class for accessing path files optionally generated during assignment.

static get_path_for_destination_from_files(path_o: DataFrame, path_o_index: DataFrame, destination: int)[source]#

for a given path file and path index file, and a given destination, return the path links in o-d order

get_path_for_destination(origin: int, destination: int, iteration: int, traffic_class_id: str)[source]#

Return all link ids, i.e. the full path, for a given destination

read_path_file(origin: int, iteration: int, traffic_class_id: str) -> (<class 'pandas.DataFrame'>, <class 'pandas.DataFrame'>)[source]#
class aequilibrae.paths.AssignmentResults[source]#

Assignment result holder for a single TrafficClass with multiple user classes

get_graph_to_network_mapping()[source]#
get_load_results() DataFrame[source]#

Translates the assignment results from the graph format into the network format

Returns:

dataset (pd.DataFrame): Pandas DataFrame data with the traffic class assignment results

get_sl_results() DataFrame[source]#
prepare(graph: Graph, matrix: AequilibraeMatrix) None[source]#

Prepares the object with dimensions corresponding to the assignment matrix and graph objects

Arguments:

graph (Graph): Needs to have been set with number of centroids and list of skims (if any)

matrix (AequilibraeMatrix): Matrix properly set for computation with matrix.computational_view(:obj:`list`)

reset() None[source]#

Resets object to prepared and pre-computation state

set_cores(cores: int) None#

Sets number of cores (threads) to be used in computation

Value of zero sets number of threads to all available in the system, while negative values indicate the number of threads to be left out of the computational effort.

Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the inputs result in values outside those limits

Arguments:

cores (int): Number of cores to be used in computation

total_flows() None[source]#

Totals all link flows for this class into a single link load

Results are placed into total_link_loads class member

class aequilibrae.paths.ConnectivityAnalysis(graph, origins=None, project=None)[source]#
>>> from aequilibrae.paths.connectivity_analysis import ConnectivityAnalysis

>>> project = create_example(project_path)

>>> network = project.network
>>> network.build_graphs()

>>> graph = network.graphs['c']
>>> graph.set_graph(cost_field="distance")
>>> graph.set_blocked_centroid_flows(False)

>>> conn_test = ConnectivityAnalysis(graph)
>>> conn_test.execute()

# The connectivity tester report as a Pandas DataFrame
>>> disconnected = conn_test.disconnected_pairs

>>> project.close()
doWork()[source]#
execute()[source]#

Runs the skimming process as specified in the graph

set_cores(cores: int) None[source]#

Sets number of cores (threads) to be used in computation

Value of zero sets number of threads to all available in the system, while negative values indicate the number of threads to be left out of the computational effort.

Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the inputs result in values outside those limits

Arguments:

cores (int): Number of cores to be used in computation

connectivity = <aequilibrae.utils.python_signal.PythonSignal object>#
class aequilibrae.paths.Graph(*args, **kwargs)[source]#
available_skims() List[str]#

Returns graph fields that are available to be set as skims.

Returns:

list (str): Skimmeable field names

compute_path(origin: int, destination: int, early_exit: bool = False, a_star: bool = False, heuristic: str | None = None)#

Returns the results from path computation result holder.

Arguments:

origin (int): origin for the path

destination (int): destination for the path

early_exit (bool): stop constructing the shortest path tree once the destination is found. Doing so may cause subsequent calls to ‘update_trace’ to recompute the tree. Default is False.

a_star (bool): whether or not to use A* over Dijkstra’s algorithm. When True, ‘early_exit’ is always True. Default is False.

heuristic (str): heuristic to use if a_star is enabled. Default is None.

compute_skims(cores: int | None = None)#

Returns the results from network skimming result holder.

Arguments:

cores (Union[int, None]): number of cores (threads) to be used in computation

Create three arrays providing a mapping of compressed ID to link ID.

Uses sparse compression. Index ‘idx’ by the by compressed ID and compressed ID + 1, the network IDs are then in the range idx[id]:idx[id + 1].

Links not in the compressed graph are not contained within the ‘data’ array.

‘node_mapping’ provides an easy way to check if a node index is present within the compressed graph. If the value is -1 then the node has been removed, either by compression of dead end link removal. If the value is greater than or equal to 0, then that value is the compressed node index.

>>> project = create_example(project_path)

>>> project.network.build_graphs()

>>> graph = project.network.graphs['c']
>>> graph.prepare_graph(np.arange(1,25))

>>> idx, data, node_mapping = graph.create_compressed_link_network_mapping()

>>> project.close()
Returns:

idx (np.array): index array for data

data (np.array): array of link ids

node_mapping: (np.array): array of node_mapping ids

default_types(tp: str)#

Returns the default integer and float types used for computation

Arguments:

tp (str): data type. ‘int’ or ‘float’

Excludes a list of links from a graph by setting their B node equal to their A node

Arguments:

links (list): List of link IDs to be excluded from the graph

load_from_disk(filename: str) None#

Loads graph from disk

Arguments:

filename (str): Path to file

prepare_graph(centroids: ndarray | None = None, remove_dead_ends: bool = True) None#

Prepares the graph for a computation for a certain set of centroids.

Under the hood, if sets all centroids to have IDs from 1 through n, which should correspond to the index of the matrix being assigned.

This is what enables having any node IDs as centroids, and it relies on the inference that all links connected to these nodes are centroid connectors.

Arguments:

centroids (np.ndarray or None, optional): Array with centroid IDs. Mandatory type Int64, unique and positive.

remove_dead_ends (bool, optional): Whether or not to remove dead ends from the graph. Defaults to True.

reverse()#
save_compressed_correspondence(path, mode_name, mode_id)#

Save graph and nodes_to_indices to disk

save_to_disk(filename: str) None#

Saves graph to disk

Arguments:

filename (str): Path to file. Usual file extension is aeg.

set_blocked_centroid_flows(block_centroid_flows) None#

Chooses whether we want to block paths to go through centroids or not. Default value is True.

Arguments:

block_centroid_flows (bool): Blocking or not paths to go through centroids.

set_graph(cost_field) None#

Sets the field to be used for path computation

Arguments:

cost_field (str): Field name. Must be numeric

set_skimming(skim_fields: list) None#

Sets the list of skims to be computed

Skimming with A* may produce results that differ from traditional Dijkstra’s due to its use a heuristic.

Arguments:

skim_fields (list): Fields must be numeric

class aequilibrae.paths.HyperpathGenerating(edges, tail='tail', head='head', trav_time='trav_time', freq='freq', check_edges=False, skim_cols=None, *, o_vert_ids=array([], dtype=int64), d_vert_ids=array([], dtype=int64), nodes_to_indices)#

A class for hyperpath generation.

Arguments:

edges (pandas.DataFrame): The edges of the graph.

tail (str, optional): The column name for the tail of the edge. Default is “tail”.

head (str, optional): The column name for the head of the edge. Default is “head”.

trav_time (str, optional): The column name for the travel time of the edge. Default is “trav_time”.

freq (str, optional): The column name for the frequency of the edge. Default is “freq”.

check_edges (bool, optional): If True, check the validity of the edges. Default is False.

assign(origin_column, destination_column, demand_column, check_demand=False, threads=None)#

Assigns demand to the edges of the graph.

Assumes the *_column arguments are provided as numpy arrays that form a COO sprase matrix.

Arguments:

origin_column (np.ndarray, optional): The column for the origin vertices. Default is “orig_vert_idx”.

destination_column (np.ndarray, optional): The column or the destination vertices. Default is “dest_vert_idx”.

demand_column (np.ndarray, optional): The column for the demand values. Default is “demand”.

check_demand (bool, optional): If True, check the validity of the demand data. Default is False.

threads (int, optional): The number of threads to use for computation. Default is 0 (using all available threads).

check_skim_cols(skim_cols: Union(list[str], tuple[str], set(str)))#
compute_skim_cols(skim_cols, edges: DataFrame, trav_time: str)#
info() dict#
run(origin, destination, volume)#
save_results(table_name: str, keep_zero_flows=True, project=None) None#

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 active project

class aequilibrae.paths.MultiThreadedAoN[source]#
prepare(graph, results)[source]#
class aequilibrae.paths.MultiThreadedNetworkSkimming[source]#
prepare(graph, cores, nodes, num_skims)[source]#
prepare_(graph, cores, nodes)#
class aequilibrae.paths.NetworkSkimming(graph, origins=None, project=None)[source]#
>>> from aequilibrae.paths.network_skimming import NetworkSkimming

>>> project = create_example(project_path)
>>> project.network.build_graphs(modes=["c"])

>>> graph = project.network.graphs['c']
>>> graph.set_graph("distance")
>>> graph.set_skimming("distance")

>>> skm = NetworkSkimming(graph)
>>> skm.execute()

# The skim report (if any error generated) is available here
>>> skm.report
[]

# To access the skim matrix directly from its temporary file
>>> matrix = skm.results.skims

# Or you can save the results to disk
>>> skm.save_to_project('skimming_result_omx', 'omx')

>>> project.close()
doWork()[source]#
execute()[source]#

Runs the skimming process as specified in the graph

save_to_project(name: str, format='omx', project=None) None[source]#

Saves skim results to the project folder and creates record in the database

Arguments:

name (str): Name of the matrix. Same value for matrix record name and file (plus extension)

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

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

set_cores(cores: int) None[source]#

Sets number of cores (threads) to be used in computation

Value of zero sets number of threads to all available in the system, while negative values indicate the number of threads to be left out of the computational effort.

Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the inputs result in values outside those limits

Arguments:

cores (int): Number of cores to be used in computation

signal = <aequilibrae.utils.python_signal.PythonSignal object>#
class aequilibrae.paths.OptimalStrategies(assig_spec)[source]#
execute()[source]#
class aequilibrae.paths.PathResults[source]#

Path computation result holder

>>> from aequilibrae.paths.results import PathResults

>>> project = create_example(project_path)
>>> project.network.build_graphs()

# Mode c is car in this project
>>> car_graph = project.network.graphs['c']

# minimize distance
>>> car_graph.set_graph('distance')

# If you want to compute skims
# It does increase path computation time substantially
>>> car_graph.set_skimming(['distance', 'free_flow_time'])

>>> res = PathResults()
>>> res.prepare(car_graph)
>>> res.compute_path(1, 17)

# Update all the outputs mentioned above for destination 9. Same origin: 1
>>> res.update_trace(9)

# clears all computation results
>>> res.reset()

>>> project.close()
compute_path(origin: int, destination: int, early_exit: bool = False, a_star: bool = False, heuristic: str | None = None) None[source]#

Computes the path between two nodes in the network.

A* heuristics are currently only valid distance cost fields.

Arguments:

origin (int): Origin for the path

destination (int): Destination for the path

early_exit (bool): Stop constructing the shortest path tree once the destination is found. Doing so may cause subsequent calls to update_trace to recompute the tree. Default is False.

a_star (bool): Whether or not to use A* over Dijkstra’s algorithm. When True, early_exit is always True. Default is False.

heuristic (str): Heuristic to use if a_star is enabled. Default is None.

get_heuristics() List[str][source]#

Return the available heuristics.

prepare(graph: Graph) None[source]#

Prepares the object with dimensions corresponding to the graph object

Arguments:

graph (Graph): Needs to have been set with number of centroids and list of skims (if any)

reset() None[source]#

Resets object to prepared and pre-computation state

set_heuristic(heuristic: str) None[source]#

Set the heuristics to be used in A*. Must be one of get_heuristics().

Arguments:

heuristic (str): Heuristic to use in A*.

update_trace(destination: int) None[source]#

Updates the path’s nodes, links, skims and mileposts

If the previously computed path had early_exit enabled, update_trace will check if the destination has already been found, if not the shortest path tree will be recomputed with the early_exit argument passed on.

If the previously computed path had a_star enabled, update_trace always recompute the path.

Arguments:

destination (int): ID of the node we are computing the path too

class aequilibrae.paths.RouteChoice(graph: Graph, project=None)[source]#
add_demand(demand, fill: float = 0.0)[source]#

Add demand DataFrame or matrix for the assignment.

Arguments:

demand (Union[pd.DataFrame, AequilibraeMatrix]): Demand to add to assignment. If the supplied demand is a DataFrame, it should have a 2-level MultiIndex of Origin and Destination node IDs. If an AequilibraE Matrix is supplied node IDs will be inferred from the index. Demand values should be either float32 or float64.

fill (float): Value to fill any NaN with.

execute(perform_assignment: bool = True) None[source]#

Generate route choice sets between the previously supplied nodes, potentially performing an assignment.

To access results see RouteChoice.get_results().

Arguments:

perform_assignment (bool): Whether or not to perform an assignment. Defaults to False.

execute_from_pandas(df: DataFrame, recompute_psl: bool = False) None[source]#

Perform an assignment using route sets from a Pandas DataFrame.

Requires the DataFrame contains the origin id, destination id and route set columns. The route sets must be a list of links IDs stored as integers with the direction encoded as the sign. Additionally, when recompute_psl is False, the probability column must also be present.

When recompute_psl is True, the path-sized logit is recomputed for each route with respect to the graphs current cost field and the beta and cutoff_prob parameters.

All origin and destination IDs within the DataFrame must exist within the demand matrix.

All link IDs and directions must exist within the graph. Links must also be present within the compressed graph.

If recompute_psl is False the table returned from self.get_results() will have all zeros for the cost and path overlap fields, and all True for the mask field. If recompute_psl is True these fields will be recalculated as required.

execute_from_path_files(path_files: Path | str, recompute_psl: bool = False) None[source]#

Perform an assignment from an existing set of path-files.

This method expects the path-files to be written by the self.save_path_files() method, however any parquet hive dataset with the correct structure is accepted. This allows the use of AequilibraE’s path-sized logit, link loading, select link analysis, and assignment while using externally generated routes.

execute_single(origin: int, destination: int, demand: float = 0.0) List[Tuple[int]][source]#

Generate route choice sets between origin and destination, potentially performing an assignment.

Does not require preparation.

Node IDs must be present in the compressed graph. To make a node ID always appear in the compressed graph add it as a centroid.

Arguments:

origin (int): Origin node ID.

destination (int): Destination node ID.

demand (float): If provided an assignment will be performed with this demand.

Returns:

route set (List[Tuple[int]]): A list of routes as tuples of link IDs.

get_load_results() DataFrame[source]#

Translates the link loading results from the graph format into the network format.

Returns:

dataset (Union[Tuple[pd.DataFrame, pd.DataFrame], pd.DataFrame]): A tuple of link loading results as DataFrames. Columns are the matrix name concatenated direction.

get_results() DataFrame[source]#

Returns the results of the route choice procedure

Returns a table of OD pairs to lists of link IDs for each OD pair provided (as columns). Represents paths from origin to destination. When the link id in the route set is positive it represents the ab direction, while negative represents the ba direction.

Returns:

results (pd.DataFrame): Table with the results of the route choice procedure

Get the select link loading results.

Returns:

dataset (Tuple[pd.DataFrame, pd.DataFrame]): Select link loading results as DataFrames. Columns are the matrix name concatenated with the select link set and direction.

Get the select link OD matrix results as a sparse matrix.

Returns:

select link OD matrix results (Dict[str, Dict[str, scipy.sparse.coo_matrix]]): Returns a dict of select link set names to a dict of demand column names to a sparse OD matrix

info() dict[source]#

Returns information for the transit assignment procedure

Dictionary contains keys:

  • Algorithm,

  • Matrix totals

  • Computer name

  • Procedure ID

  • Parameters

  • Select links

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

Returns:

info (dict): Dictionary with summary information

log_specification()[source]#
prepare(nodes: List[int] | List[Tuple[int, int]] | None = None) None[source]#

Prepare OD pairs for batch computation.

Arguments:

nodes (Union[list[int], list[tuple[int, int]]]): List of node IDs to operate on. If a 1D list is provided, OD pairs are taken to be all pair permutations of the list. If a list of pairs is provided OD pairs are taken as is. All node IDs must be present in the compressed graph. To make a node ID always appear in the compressed graph add it as a centroid. Duplicates will be dropped on execution. If None is provided, all OD pairs with non-zero flows will be used.

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

Arguments:

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

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

save_path_files(where: Path | None = None)[source]#

Save path-files to the directory specific.

Files will be saved as a parquet hive dataset partitioned by the origin ID. Existing path-files will not be removed to allow incremental route choice set generation.

Arguments:

where (Optional[pathlib.Path]): Directory to save the dataset to.

Saves the select link link flows for all classes into the results database. Additionally, it exports the OD matrices into OMX format.

Arguments:

table_name (str): Name of the table being inserted to and the name of the OpenMatrix file used for OD matrices.

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

set_choice_set_generation(algorithm: str = None, **kwargs) None[source]#

Chooses the assignment algorithm and set its parameters.

Options for algorithm are ‘bfsle’ for breadth first search with link removal, or ‘link-penalisation’/’link-penalization’. ‘lp’ is also accepted as an alternative to ‘link-penalisation’. If algorithm is None, none will be set, but the parameters will be updated. This is useful when assigning from path-files.

BFSLE implementation based on “Route choice sets for very high-resolution data” by Nadine Rieser-Schüssler, Michael Balmer & Kay W. Axhausen (2013). DOI: 10.1080/18128602.2012.671383.

Setting the parameters for the route choice:

  • seed is a BFSLE specific parameters.

  • Although not required, setting max_depth or max_misses, is strongly recommended to prevent runaway algorithms.

  • max_misses is the maximum amount of duplicate routes found per OD pair. If a set of routes is returned in a case where max_misses is exceeded, the number of routes may be fewer than max_routes. Assumes a default value of 100.

  • When using BFSLE max_depth corresponds to the maximum height of the graph. It’s value is largely dependent on the size of the paths within the network. For very small networks a value of 10 is a recommended starting point. For large networks a good starting value is 5. Increase the value until the number of desired routes is being consistently returned. If a set of routes is returned in a case where max_depth is exceeded, the number of routes may be fewer than max_routes.

  • When using LP, max_depth corresponds to the maximum number of iterations performed. While not enforced, it should be higher than max_routes. It’s value is dependent on the magnitude of the cost field, specifically if it’s related to the log base penalty of the ratio of costs between two alternative routes. If a set of routes is returned in a case where max_depth is exceeded, the number of routes may be fewer than max_routes.

  • Additionally BFSLE has the option to incorporate link penalisation. Every link in all routes found at a depth are penalised with the penalty factor for the next depth. So at a depth of 0 no links are penalised nor removed. At depth 1, all links found at depth 0 are penalised, then the links marked for removal are removed. All links in the routes found at depth 1 are then penalised for the next depth. The penalisation compounds. Set penalty=1.0 to disable.

  • When performing an assignment, cutoff_prob can be provided to exclude routes from the path-sized logit model. The cutoff_prob is used to compute an inverse binary logit and obtain a max difference in utilities. If a paths total cost is greater than the minimum cost path in the route set plus the max difference, the route is excluded from the PSL calculations. The route is still returned, but with a probability of 0.0.

  • The cutoff_prob should be in the range \([0, 1]\). It is then rescaled internally to \([0.5, 1]\) as probabilities below 0.5 produce negative differences in utilities because the choice is between two routes only, one of which is the shortest path. A higher cutoff_prob includes less routes. A value of 1.0 will only include the minimum cost route. A value of 0.0 includes all routes.

Arguments:

algorithm (str): Algorithm to be used

kwargs (dict): Dictionary with all parameters for the algorithm

set_cores(cores: int) None[source]#

Allows one to set the number of cores to be used

Inherited from AssignmentResultsBase

Arguments:

cores (int): Number of CPU cores to use

set_save_routes(where: str | None = None) None[source]#

Set save path for route choice results. Provide None to disable.

Arguments:

save_it (bool): Boolean to indicate whether routes should be saved

Set the selected links. Checks if the links and directions are valid. Supports OR and AND sets of links.

Dictionary values should be a list of either a single (link_id, direction) tuple or a list of (link_id, dirirection).

The elements of the first list represent the AND sets, together they are OR’ed. If any of these sets is satisfied the link are loaded as appropriate.

The AND sets are comprised of either a single (link_id, direction) tuple or a list of (link_id, direction). The single tuple represents an AND set with a single element.

All links and directions in an AND set must appear in any order within a route for it to be considered satisfied.

Supply links=None to disable select link analysis.

Arguments:

links (Union[None, Dict[Hashable, List[Union[Tuple[int, int], List[Tuple[int, int]]]]]]): Name of link set and link IDs and directions to be used in select link analysis.

link_loading (bool): Enable select link loading. If disabled only OD matrix results are available.

all_algorithms = ['bfsle', 'lp', 'link-penalisation', 'link-penalization']#
default_parameters = {'bfsle': {'penalty': 1.0}, 'generic': {'beta': 1.0, 'cutoff_prob': 0.0, 'max_depth': 0, 'max_misses': 100, 'max_routes': 0, 'penalty': 1.01, 'seed': 0, 'store_results': True}, 'link-penalisation': {}}#
demand_index_names = ['origin id', 'destination id']#
class aequilibrae.paths.SkimResults[source]#

Network skimming result holder.

>>> from aequilibrae.paths.results import SkimResults

>>> project = create_example(project_path)
>>> project.network.build_graphs()

# Mode c is car in this project
>>> car_graph = project.network.graphs['c']

# minimize travel time
>>> car_graph.set_graph('free_flow_time')

# Skims travel time and distance
>>> car_graph.set_skimming(['free_flow_time', 'distance'])

>>> res = SkimResults()
>>> res.prepare(car_graph)

>>> res.skims.export(project_path / "skim_matrices.omx")

>>> project.close()
prepare(graph: Graph)[source]#

Prepares the object with dimensions corresponding to the graph objects

Arguments:

graph (Graph): Needs to have been set with number of centroids and list of skims (if any)

class aequilibrae.paths.SubAreaAnalysis(graph: Graph, subarea: GeoDataFrame, demand: DataFrame | AequilibraeMatrix, project=None)[source]#
post_process(demand_cols=None, keep_original_ods: bool = False)[source]#

Apply the necessary post processing to the route choice assignment select link results.

Arguments:

demand_cols ([list[str]], optional): If provided, only construct the sub-area matrix for these demand matrices.

keep_original_ods (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 (pd.DataFrame): A DataFrame representing the sub-area demand matrix.

class aequilibrae.paths.TrafficAssignment(project=None)[source]#

Traffic assignment class.

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

>>> from aequilibrae.paths import TrafficAssignment, TrafficClass

>>> project = create_example(project_path)
>>> project.network.build_graphs()

>>> graph = project.network.graphs['c'] # we grab the graph for cars
>>> graph.set_graph('free_flow_time') # let's say we want to minimize time
>>> graph.set_skimming(['free_flow_time', 'distance']) # And will skim time and distance
>>> graph.set_blocked_centroid_flows(True)

>>> proj_matrices = project.matrices

>>> demand = proj_matrices.get_matrix("demand_omx")

# We will only assign one user class stored as 'matrix' inside the OMX file
>>> demand.computational_view(['matrix'])

# Creates the assignment class
>>> assigclass = TrafficClass("car", graph, demand)

>>> assig = TrafficAssignment()

# The first thing to do is to add at list of traffic classes to be assigned
>>> assig.set_classes([assigclass])

# Then we set the volume delay function
>>> assig.set_vdf("BPR")  # This is not case-sensitive

# And its parameters
>>> assig.set_vdf_parameters({"alpha": "b", "beta": "power"})

# The capacity and free flow travel times as they exist in the graph
>>> assig.set_capacity_field("capacity")
>>> assig.set_time_field("free_flow_time")

# And the algorithm we want to use to assign
>>> assig.set_algorithm('bfw')

>>> assig.max_iter = 10
>>> assig.rgap_target = 0.00001

>>> assig.execute() # we then execute the assignment

# 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 = assigclass.results.skims # blended ones
>>> last_skims = assigclass._aon_results.skims # those for the last iteration

>>> project.close()
add_class(traffic_class: TrafficClass) None[source]#

Adds a traffic class to the assignment

Arguments:

traffic_class (TrafficClass): Traffic class

add_preload(preload: DataFrame, name: str = None) None[source]#

Given a dataframe of ‘link_id’, ‘direction’ and ‘preload’, merge into current preloads dataframe.

Arguments:

preload (pd.DataFrame): dataframe mapping ‘link_id’ & ‘direction’ to ‘preload’ name (str): Name for particular preload (optional - default name will be chosen if not specified)

algorithms_available() list#

Returns all algorithms available for use

Returns:

list: List of string values to be used with set_algorithm

execute(log_specification=True) None#

Processes assignment

get_skim_results() list#

Prepares the assignment skim results for all classes

Returns:

skim list (list): Lists of all skims with the results for each class

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

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 active 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 active 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 active 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) None[source]#

Saves the skims (if any) to the skim folder and registers in the matrix list

Arguments:

name (str): Name of the matrix record to hold this matrix (same name used for file name)

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 (‘aem’ or ‘omx’). Default is ‘omx’

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

Defaults to the active project

Returns a dataframe of the select link flows for each class

set_algorithm(algorithm: str)[source]#

Chooses the assignment algorithm. e.g. ‘frank-wolfe’, ‘bfw’, ‘msa’

‘fw’ is also accepted as an alternative to ‘frank-wolfe’

Arguments:

algorithm (str): Algorithm to be used

set_capacity_field(capacity_field: str) None[source]#

Sets the graph field that contains link capacity for the assignment period -> e.g. ‘capacity1h’

Arguments:

capacity_field (str): Field name

set_classes(classes: List[TrafficClass]) None[source]#

Sets Traffic classes to be assigned

Arguments:

classes (List[TrafficClass]): List of Traffic classes for assignment

set_cores(cores: int) None[source]#

Allows one to set the number of cores to be used AFTER traffic classes have been added

Inherited from AssignmentResultsBase

Arguments:

cores (int): Number of CPU cores to use

set_path_file_format(file_format: str) None[source]#

Specify path saving format. Either parquet or feather.

Arguments:

file_format (str): Name of file format to use for path files

set_save_path_files(save_it: bool) None[source]#

Turn path saving on or off.

Arguments:

save_it (bool): Boolean to indicate whether paths should be saved

set_time_field(time_field: str) None[source]#

Sets the graph field that contains free flow travel time -> e.g. ‘fftime’

Arguments:

time_field (str): Field name

set_vdf(vdf_function: str) None[source]#

Sets the Volume-delay function to be used

Arguments:

vdf_function (str): Name of the VDF to be used

set_vdf_parameters(par: dict) None[source]#

Sets the parameters for the Volume-delay function.

Parameter values can be scalars (same values for the entire network) or network field names (link-specific values) - Examples: {‘alpha’: 0.15, ‘beta’: 4.0} or {‘alpha’: ‘alpha’, ‘beta’: ‘beta’}

The Akcelik VDF parameter ‘tau’ value has typical 8 factor absorbed into it. Users should supply 8 * tau to match other common usages. Additionally the standard 0.25 factor can be overridden by supplying the ‘alpha’ parameter.

Arguments:

par (dict): Dictionary with all parameters for the chosen VDF

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.

algorithm: str#
all_algorithms = ['all-or-nothing', 'msa', 'frank-wolfe', 'fw', 'cfw', 'bfw']#
assignment: LinearApproximation | OptimalStrategies#
bpr_parameters = ['alpha', 'beta']#
capacity: ndarray#
capacity_field: str#
classes: List[TrafficClass]#
congested_time: ndarray#
cores: int#
description: str#
free_flow_tt: ndarray#
preloads: DataFrame#
save_path_files: bool#
time_field: str#
total_flow: ndarray#
vdf_parameters: list#
class aequilibrae.paths.TrafficClass(name: str, graph: Graph, matrix: AequilibraeMatrix)[source]#

Traffic class for equilibrium traffic assignment

>>> from aequilibrae.paths import TrafficClass

>>> project = create_example(project_path)
>>> project.network.build_graphs()

>>> graph = project.network.graphs['c'] # we grab the graph for cars
>>> graph.set_graph('free_flow_time') # let's say we want to minimize time
>>> graph.set_skimming(['free_flow_time', 'distance']) # And will skim time and distance
>>> graph.set_blocked_centroid_flows(False)

>>> proj_matrices = project.matrices

>>> demand = proj_matrices.get_matrix("demand_omx")
>>> demand.computational_view()

>>> tc = TrafficClass("car", graph, demand)
>>> tc.set_pce(1.3)

>>> project.close()
set_fixed_cost(field_name: str, multiplier=1)[source]#

Sets value of time

Arguments:

field_name (str): Name of the graph field with fixed costs for this class

multiplier (Union[float, int]): Multiplier for the fixed cost. Defaults to 1 if not set

set_pce(pce: float | int) None[source]#

Sets Passenger Car equivalent

Arguments:

pce (Union[float, int]): PCE. Defaults to 1 if not set

Set the selected links. Checks if the links and directions are valid. Translates link_id and direction into unique link id used in compact graph. Supply links=None to disable select link analysis.

Arguments:

links (Union[None, Dict[str, List[Tuple[int, int]]]]): name of link set and Link IDs and directions to be used in select link analysis

set_vot(value_of_time: float) None[source]#

Sets value of time

Arguments:

value_of_time (Union[float, int]): Value of time. Defaults to 1 if not set

skim_congested(skim_fields=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.

Arguments:

skim_fields (Union[None, str]): Name of the skims to use. If None, uses default only

property info: dict#
class aequilibrae.paths.TransitAssignment(*args, project=None, **kwargs)[source]#
add_class(transport_class: TransportClassBase) None#

Adds a Transport class to the assignment

Arguments:

transport_class (TransportClassBase): Transport class

algorithms_available() list#

Returns all algorithms available for use

Returns:

list: List of string values to be used with set_algorithm

execute(log_specification=True) None#

Processes assignment

get_skim_results() list#

Prepares the assignment skim results for all classes

Returns:

skim list (list): Lists of all skims with the results for each class

info() dict[source]#

Returns information for the transit assignment procedure

Dictionary contains keys ‘Algorithm’, ‘Classes’, ‘Computer name’, ‘Procedure ID’.

The classes key is also a dictionary with all the user classes per transit 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

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 active project

set_algorithm(algorithm: str)[source]#

Chooses the assignment algorithm. Currently only ‘optimal-strategies’ is available.

‘os’ is also accepted as an alternative to ‘optimal-strategies’

Arguments:

algorithm (str): Algorithm to be used

set_classes(classes: List[TransportClassBase]) None#

Sets Transport classes to be assigned

Arguments:

classes (List[TransportClassBase]): List of TransportClass’s for assignment

set_cores(cores: int) None[source]#

Allows one to set the number of cores to be used AFTER transit classes have been added

Inherited from AssignmentResultsBase

Arguments:

cores (int): Number of CPU cores to use

set_frequency_field(frequency_field: str) None[source]#

Sets the graph field that contains the frequency -> e.g. ‘freq’

Arguments:

frequency_field (str): Field name

set_skimming_fields(skimming_fields: list[str] = None) None[source]#

Sets the skimming fields for the transit assignment.

Also accepts predefined skimming fields:
  • discrete: ‘boardings’, ‘alightings’, ‘inner_transfers’, ‘outer_transfers’, and ‘transfers’.

  • continuous: ‘trav_time’, ‘on_board_trav_time’, ‘dwelling_time’, ‘egress_trav_time’, ‘access_trav_time’, ‘walking_trav_time’, ‘transfer_time’, ‘in_vehicle_trav_time’, and ‘waiting_time’.

Provide no argument to disable.

Arguments:

skimming_fields (list[str]): Optional list of field names, or predefined skimming type.

set_time_field(time_field: str) None[source]#

Sets the graph field that contains free flow travel time -> e.g. ‘trav_time’

Arguments:

time_field (str): Field name

algorithm: str#
all_algorithms = ['optimal-strategies', 'os']#
assignment: LinearApproximation | OptimalStrategies#
classes: List[TrafficClass]#
cores: int#
description: str#
free_flow_tt: ndarray#
time_field: str#
total_flow: ndarray#
class aequilibrae.paths.TransitAssignmentResults[source]#

Assignment result holder for a single Transit

get_load_results() DataFrame[source]#

Translates the assignment results from the graph format into the network format

Returns:

dataset (pd.DataFrame): DataFrame data with the transit class assignment results

prepare(graph: TransitGraph, matrix: AequilibraeMatrix) None[source]#

Prepares the object with dimensions corresponding to the assignment matrix and graph objects

Arguments:

graph (TransitGraph): Needs to have been set with number of centroids

matrix (AequilibraeMatrix): Matrix properly set for computation with matrix.computational_view(:obj:`list`)

reset() None[source]#

Resets object to prepared and pre-computation state

set_cores(cores: int) None#

Sets number of cores (threads) to be used in computation

Value of zero sets number of threads to all available in the system, while negative values indicate the number of threads to be left out of the computational effort.

Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the inputs result in values outside those limits

Arguments:

cores (int): Number of cores to be used in computation

class aequilibrae.paths.TransitClass(name: str, graph: TransitGraph, matrix: AequilibraeMatrix)[source]#
set_demand_matrix_core(core: str)[source]#

Set the matrix core to use for demand.

Arguments:

core (str):

property info: dict#
class aequilibrae.paths.TransitGraph(config: dict = None, od_node_mapping: DataFrame = None, *args, **kwargs)[source]#
available_skims() List[str]#

Returns graph fields that are available to be set as skims.

Returns:

list (str): Skimmeable field names

compute_path(origin: int, destination: int, early_exit: bool = False, a_star: bool = False, heuristic: str | None = None)#

Returns the results from path computation result holder.

Arguments:

origin (int): origin for the path

destination (int): destination for the path

early_exit (bool): stop constructing the shortest path tree once the destination is found. Doing so may cause subsequent calls to ‘update_trace’ to recompute the tree. Default is False.

a_star (bool): whether or not to use A* over Dijkstra’s algorithm. When True, ‘early_exit’ is always True. Default is False.

heuristic (str): heuristic to use if a_star is enabled. Default is None.

compute_skims(cores: int | None = None)#

Returns the results from network skimming result holder.

Arguments:

cores (Union[int, None]): number of cores (threads) to be used in computation

Create three arrays providing a mapping of compressed ID to link ID.

Uses sparse compression. Index ‘idx’ by the by compressed ID and compressed ID + 1, the network IDs are then in the range idx[id]:idx[id + 1].

Links not in the compressed graph are not contained within the ‘data’ array.

‘node_mapping’ provides an easy way to check if a node index is present within the compressed graph. If the value is -1 then the node has been removed, either by compression of dead end link removal. If the value is greater than or equal to 0, then that value is the compressed node index.

>>> project = create_example(project_path)

>>> project.network.build_graphs()

>>> graph = project.network.graphs['c']
>>> graph.prepare_graph(np.arange(1,25))

>>> idx, data, node_mapping = graph.create_compressed_link_network_mapping()

>>> project.close()
Returns:

idx (np.array): index array for data

data (np.array): array of link ids

node_mapping: (np.array): array of node_mapping ids

default_types(tp: str)#

Returns the default integer and float types used for computation

Arguments:

tp (str): data type. ‘int’ or ‘float’

Excludes a list of links from a graph by setting their B node equal to their A node

Arguments:

links (list): List of link IDs to be excluded from the graph

load_from_disk(filename: str) None#

Loads graph from disk

Arguments:

filename (str): Path to file

prepare_graph(centroids: ndarray | None = None, remove_dead_ends: bool = True) None#

Prepares the graph for a computation for a certain set of centroids.

Under the hood, if sets all centroids to have IDs from 1 through n, which should correspond to the index of the matrix being assigned.

This is what enables having any node IDs as centroids, and it relies on the inference that all links connected to these nodes are centroid connectors.

Arguments:

centroids (np.ndarray or None, optional): Array with centroid IDs. Mandatory type Int64, unique and positive.

remove_dead_ends (bool, optional): Whether or not to remove dead ends from the graph. Defaults to True.

reverse()#
save_compressed_correspondence(path, mode_name, mode_id)#

Save graph and nodes_to_indices to disk

save_to_disk(filename: str) None#

Saves graph to disk

Arguments:

filename (str): Path to file. Usual file extension is aeg.

set_blocked_centroid_flows(block_centroid_flows) None#

Chooses whether we want to block paths to go through centroids or not. Default value is True.

Arguments:

block_centroid_flows (bool): Blocking or not paths to go through centroids.

set_graph(cost_field) None#

Sets the field to be used for path computation

Arguments:

cost_field (str): Field name. Must be numeric

set_skimming(skim_fields: list) None#

Sets the list of skims to be computed

Skimming with A* may produce results that differ from traditional Dijkstra’s due to its use a heuristic.

Arguments:

skim_fields (list): Fields must be numeric

property config#
class aequilibrae.paths.VDF[source]#

Volume-Delay function

>>> from aequilibrae.paths import VDF

>>> vdf = VDF()
>>> vdf.functions_available()
['bpr', 'bpr2', 'conical', 'inrets', 'akcelik']
functions_available() list[source]#

returns a list of all functions available

class aequilibrae.paths.allOrNothing(class_name: str, matrix: AequilibraeMatrix, graph: Graph, results: AssignmentResults)[source]#
doWork()[source]#
execute()[source]#
func_assig_thread(origin, all_threads)[source]#
signal = <aequilibrae.utils.python_signal.PythonSignal object>#
aequilibrae.paths.one_to_all(origin, matrix, graph, result, aux_result, curr_thread)#
aequilibrae.paths.path_computation(origin, destination, graph, results)#
Parameters:
  • graph – AequilibraE graph. Needs to have been set with number of centroids and list of skims (if any)

  • results – AequilibraE Matrix properly set for computation using matrix.computational_view([matrix list])

  • skimming – if we will skim for all nodes or not

aequilibrae.paths.skimming_single_origin(origin, graph, result, aux_result, curr_thread)#
Parameters:
  • origin

  • graph

  • results

Returns:

aequilibrae.paths.update_path_trace(results, destination, graph)#

If results.early_exit is True, early exit will be enabled if the path is to be recomputed. If results.a_star is True, A* will be used if the path is to be recomputed.

Parameters:
  • graph – AequilibraE graph. Needs to have been set with number of centroids and list of skims (if any)

  • results – AequilibraE Matrix properly set for computation using matrix.computational_view([matrix list])

  • destination – New destination for path computation

Modules