aequilibrae.route_choice#

Classes

RouteChoice(graph[, project, coordinates])

SubAreaAnalysis(graph, subarea, demand[, ...])

class aequilibrae.route_choice.RouteChoice(graph: Graph, project=None, *, coordinates: DataFrame | None = None)[source]#
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 lists of unsigned link IDs, with matching +1/-1 arrays in route directions. 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 graph’s cost field and the beta, disutility_cutoff_constant and disutility_cutoff_coefficient parameters. With PSL recomputation, the supplied mask is combined with the cost-cutoff mask. Otherwise, supplied costs and masks are kept. Invalid routes wil raise ValueError, including masked routes, regardless of PSL recomputation. This includes empty paths, incomplete graph-link expansions, wrong OD endpoints, disconnected links, prohibited turns, disallowed U-turns, blocked centroid flow and infinite costs. Masked routes are not loaded regardless of supplied probabilities. Without recomputation, unmasked probabilities are not changed. Links absent from the graph or compact graph raise an error.

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.

The table returned from self.get_results() includes recalculated costs and a combined mask when PSL is recomputed. Otherwise, missing costs and path overlap default to zero and masked probabilities are zero.

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. With recompute_psl=True, costs (including turn penalties), probabilities and overlap are recomputed. Otherwise, supplied results are used. Invalid routes always raise ValueError, including masked routes.

execute_single(origin: int, destination: int, demand: float = 0.0) → list[tuple[ndarray, ndarray]][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. Non-zero demand requires centroid endpoints.

Returns:

route set (list[tuple[np.ndarray, np.ndarray]]): A list of routes as ID/direction array pairs.

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. Matching route directions arrays contain +1 for the ab direction and -1 for 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 (:obj:`Dict[str,

AequilibraeSparseMatrix]`): Returns a dict of select link set names to labelled sparse OD matrices.

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.

recompute_psl(df: DataFrame) → DataFrame[source]#

Validate and recost routes, then return their PSL results by OD.

Invalid routes raise ValueError, including masked routes.

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 explicitly supplied constructor project

save_path_files(where: Path | None = None, **to_parquet_kwargs)[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. to_parquet_kwargs (dict): Keyword arguments to supply to the underlying to_parquet call.

Save both select link flows and OD matrices using the same name.

Saves the select link link flows 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 explicitly supplied constructor project

Save the select link OD matrices to a new OMX file in the project matrices folder.

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. For both algorithms, penalty must be finite and at least 1.

  • Set a_star=True to use A* instead of Dijkstra. heuristic accepts euclidean (default) or haversine. Euclidean distance uses the constructor’s coordinates; Haversine uses the constructor’s lon and lat coordinates in degrees.

  • A* requires an finite, nonnegative heuristic_scale to convert distance to cost units. Use estimate_heuristic_scale to calculate a conservative value. A scale above a consistent bound can give non-shortest paths and change the generated route sets. A consistent bound remains valid as links are removed or penalised.

  • When performing an assignment, disutility_cutoff_constant and disutility_cutoff_coefficient can be provided to exclude routes from the path-sized logit model. Any route with a cost higher when applied to this function disutility_cutoff_coefficient * cost + disutility_cutoff_constant within the route set is masked out.

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_demand(demand: AequilibraeMatrix | AequilibraeSparseMatrix | None) → None[source]#

Set the demand matrix for the assignment.

Arguments:
demand (AequilibraeMatrix or

AequilibraeSparseMatrix, Optional): Demand for assignment. Node IDs are inferred from the index and must be graph centroids. Use aequilibrae.matrix.from_df() to convert a DataFrame.

set_save_routes(where: str | None = None, to_parquet_kwargs: dict[str, Any] | None = None) → None[source]#

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

Arguments:

where (Optional[pathlib.Path]): Directory to save the dataset to. to_parquet_kwargs (dict): Keyword arguments to supply to the underlying to_parquet call.

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

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': {'a_star': False, 'beta': 1.0, 'disutility_cutoff_coefficient': inf, 'disutility_cutoff_constant': inf, 'heuristic': 'euclidean', 'heuristic_scale': None, 'max_depth': 0, 'max_misses': 100, 'max_routes': 0, 'penalty': 1.01, 'seed': 0, 'store_results': True}, 'link-penalisation': {}}#
class aequilibrae.route_choice.SubAreaAnalysis(graph: Graph, subarea: GeoDataFrame, demand: AequilibraeMatrix | AequilibraeSparseMatrix, 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.