Python API Docs#

class nrel.routee.compass.compass_app.CompassApp(app: CompassAppWrapper, config: Config)[source]#

The CompassApp holds everything needed to run a route query.

classmethod from_config_file(config_file: str | Path, parallelism: int | None = None) CompassApp[source]#

Build a CompassApp from a config file

Parameters:
  • config_file -- Path to the config file

  • parallelism -- optional number of threads to use for parallel query execution. Overrides the value in the config file.

Returns:

A CompassApp object

Return type:

app

Example

>>> from nrel.routee.compass import CompassApp
>>> app = CompassApp.from_config_file("config.toml")
classmethod from_dict(config: TOMLDocument, working_dir: Path | None = None, parallelism: int | None = None) CompassApp[source]#

Build a CompassApp from a configuration object

Parameters:
  • config -- Configuration dictionary

  • working_dir -- optional path to working directory

  • parallelism -- optional number of threads to use for parallel query execution. Overrides the value in the config.

Returns:

a CompassApp object

Return type:

app

Example

>>> from nrel.routee.compass import CompassApp
>>> conf = { "parallelism": 2 }
>>> app = CompassApp.from_config(conf)
classmethod from_graph(graph: nx.MultiDiGraph, config_file: str | None = None, cache_dir: str | Path | None = None, hwy_speeds: dict[str, Any] | None = None, fallback: float | None = None, agg: Callable[[Any], Any] | None = None, phases: List[GeneratePipelinePhase] = [GeneratePipelinePhase.GRAPH, GeneratePipelinePhase.CONFIG, GeneratePipelinePhase.POWERTRAIN], raster_resolution_arc_seconds: str | int = 1, vehicle_models: List[str] | None = None, parallelism: int | None = None, overwrite: bool = False) CompassApp[source]#

Build a CompassApp from a networkx graph.

Parameters:
  • graph -- the networkx graph to build the CompassApp from. This is assumed to be the direct output of an osmnx download.

  • config_file -- optional name of the config file to load from the generated dataset. If not set, it will default to 'osm_default_energy.toml' if the powertrain phase is included, otherwise 'osm_default_speed.toml'.

  • cache_dir -- optional path to save necessary files to build the CompassApp. If not set, TemporaryDirectory will be used instead. Defaults to None.

  • hwy_speeds -- OSM highway types and values = typical speeds (km per hour) to assign to edges of that highway type for any edges missing speed data. Any edges with highway type not in hwy_speeds will be assigned the mean preexisting speed value of all edges of that highway type. Defaults to None.

  • fallback -- Default speed value (km per hour) to assign to edges whose highway type did not appear in hwy_speeds and had no preexisting speed values on any edge. Defaults to None.

  • agg -- Aggregation function to impute missing values from observed values. The default is numpy.mean, but you might also consider for example numpy.median, numpy.nanmedian, or your own custom function. Defaults to numpy.mean.

  • phases (List[GeneratePipelinePhase]) -- of the overall generate pipeline, which phases of the pipeline to run. Defaults to all (["graph", "grade", "config", "powertrain"])

  • raster_resolution_arc_seconds -- If grade is added, the resolution (in arc-seconds) of the tiles to download (either 1 or 1/3). Defaults to 1.

  • vehicle_models -- If provided, only download and configure the listed vehicle models (by name, e.g. ["2017_CHEVROLET_Bolt", "2016_TOYOTA_Camry_4cyl_2WD"]). Use list_available_vehicle_models() to see valid names. When None (the default) all available models are included.

  • parallelism -- optional number of threads to use for parallel query execution. Overrides the value in the config file.

  • overwrite -- if True, will overwrite any existing files in the cache_dir. Defaults to False.

Returns:

a CompassApp object

Return type:

CompassApp

classmethod from_place(query: OSMNXQuery, network_type: str = 'drive', parallelism: int | None = None, cache_dir: str | Path | None = None, overwrite: bool = False, **kwargs: Any) CompassApp[source]#

Build a CompassApp from a place

Parameters:
  • query -- the query or queries to geocode to get place boundary polygon(s)

  • network_type -- what type of street network. Default to drive List of options: ["all", "all_public", "bike", "drive", "drive_service", "walk"]

  • parallelism -- optional number of threads to use for parallel query execution. Overrides the value in the config file.

  • cache_dir -- optional path to save necessary files to build the CompassApp. If not set, TemporaryDirectory will be used instead. Defaults to None.

  • overwrite -- if True, will overwrite any existing files in the cache_dir. Defaults to False.

  • **kwargs -- additional arguments to pass to from_graph and generate_compass_dataset

Returns:

a CompassApp object

Return type:

CompassApp

Example

>>> from nrel.routee.compass import CompassApp
>>> app = CompassApp.from_place("Denver, Colorado, USA")
classmethod from_polygon(polygon: 'Polygon' | 'MultiPolygon', network_type: str = 'drive', parallelism: int | None = None, cache_dir: str | Path | None = None, overwrite: bool = False, **kwargs: Any) CompassApp[source]#

Build a CompassApp from a polygon

Parameters:
  • polygon -- the shape to get network data within. coordinates should be in unprojected latitude-longitude degrees

  • network_type -- what type of street network. Default to drive List of options: ["all", "all_public", "bike", "drive", "drive_service", "walk"]

  • parallelism -- optional number of threads to use for parallel query execution. Overrides the value in the config file.

  • cache_dir -- optional path to save necessary files to build the CompassApp. If not set, TemporaryDirectory will be used instead. Defaults to None.

  • overwrite -- if True, will overwrite any existing files in the cache_dir. Defaults to False.

  • **kwargs -- additional arguments to pass to from_graph and generate_compass_dataset

Returns:

a CompassApp object

Return type:

CompassApp

Example

>>> from nrel.routee.compass import CompassApp
>>> from shapely import geometry
>>> p1 = geometry.Point(0,0)
>>> p2 = geometry.Point(1,0)
>>> p3 = geometry.Point(1,1)
>>> p4 = geometry.Point(0,1)
>>> pointList = [p1, p2, p3, p4]
>>> poly = geometry.Polygon(pointList)
>>> app = CompassApp.from_polygon(poly)
classmethod get_constructor() CompassAppWrapper[source]#

Return the underlying constructor for the application. This allows a child class to inherit the CompassApp python class and implement its own rust based app constructor, while still using the original python methods.

graph_edge_destination(edge_id: int) int[source]#

get the destination vertex id for some edge

Parameters:

edge_id -- the id of the edge

Returns:

the vertex id at the destination of the edge

Return type:

vertex_id

graph_edge_distance(edge_id: int, distance_unit: str | None = None) float[source]#

get the distance for some edge

Parameters:
  • edge_id -- the id of the edge

  • distance_unit -- distance unit, by default meters

Returns:

the distance covered by traversing the edge

Return type:

dist

graph_edge_origin(edge_id: int) int[source]#

get the origin vertex id for some edge

Parameters:

edge_id -- the id of the edge

Returns:

the vertex id at the source of the edge

Return type:

vertex_id

graph_get_in_edge_ids(vertex_id: int) List[int][source]#

get the list of edge ids that arrive from some vertex

Parameters:

vertex_id -- the id of the vertex

Returns:

the edge ids of edges arriving at this vertex

Return type:

edges

graph_get_out_edge_ids(vertex_id: int) List[int][source]#

get the list of edge ids that depart from some vertex

Parameters:

vertex_id -- the id of the vertex

Returns:

the edge ids of edges departing from this vertex

Return type:

edges

map_match(query: CompassQuery | List[CompassQuery]) Result | Results[source]#

Run a map matching query (or multiple queries) against the CompassApp

Parameters:

query -- A query or list of queries to run

Returns:

A list of results (or a single result if a single query was passed)

Return type:

results

Example

>>> from nrel.routee.compass import CompassApp
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {
        "trace": [
            {"x": -105.1710052, "y": 39.7402804},
            {"x": -105.1710052, "y": 39.7402804}
        ]
    }
>>> result = app.map_match(query)
run(query: CompassQuery | List[CompassQuery], config: Config | None = None) Result | Results[source]#

Run a query (or multiple queries) against the CompassApp

Parameters:
  • query -- A query or list of queries to run

  • config -- optional configuration

Returns:

A list of results (or a single result if a single query was passed)

Return type:

results

Example

>>> from nrel.routee.compass import CompassApp
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {
        "origin_name": "NREL",
        "destination_name": "Comrade Brewing Company",
        "origin_x": -105.1710052,
        "origin_y": 39.7402804,
        "destination_x": -104.9009913,
        "destination_y": 39.6757025
    }
>>> result = app.run(query)
run_calculate_path(query: CompassQuery | List[CompassQuery], config: Config | None = None) Result | Results[source]#

Run a path evaluation query (or multiple queries) against the CompassApp

Parameters:
  • query -- A query or list of queries to run. Each query must have 'path'.

  • config -- optional configuration

Returns:

A list of results (or a single result if a single query was passed)

Return type:

results

Example

>>> from nrel.routee.compass import CompassApp
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {
        "path": [{"edge_id": 0}, {"edge_id": 2}],
    }
>>> result = app.run_calculate_path(query)
class nrel.routee.compass.io.generate_dataset.GeneratePipelinePhase(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
nrel.routee.compass.io.generate_dataset.generate_compass_dataset(g: networkx.MultiDiGraph, output_directory: str | Path, hwy_speeds: HIGHWAY_SPEED_MAP | None = None, fallback: float | None = None, agg: AggFunc | None = None, phases: List[GeneratePipelinePhase] = [GeneratePipelinePhase.GRAPH, GeneratePipelinePhase.CONFIG, GeneratePipelinePhase.POWERTRAIN], raster_resolution_arc_seconds: str | int = 1, default_config: bool = True, requests_kwds: Dict[Any, Any] | None = None, afdc_api_key: str = 'DEMO_KEY', vehicle_models: List[str] | None = None) None[source]#

Processes a graph downloaded via OSMNx, generating the set of input files required for running RouteE Compass.

The input graph is assumed to be the direct output of an osmnx download.

Parameters:
  • g -- OSMNx graph used to generate input files

  • output_directory -- Directory path to use for writing new Compass files.

  • hwy_speeds -- OSM highway types and values = typical speeds (km per hour) to assign to edges of that highway type for any edges missing speed data. Any edges with highway type not in hwy_speeds will be assigned the mean preexisting speed value of all edges of that highway type.

  • fallback -- Default speed value (km per hour) to assign to edges whose highway type did not appear in hwy_speeds and had no preexisting speed values on any edge.

  • agg -- Aggregation function to impute missing values from observed values. The default is numpy.mean, but you might also consider for example numpy.median, numpy.nanmedian, or your own custom function. Defaults to numpy.mean.

  • phases (List[GeneratePipelinePhase]) -- of the overall generate pipeline, which phases of the pipeline to run. Defaults to all (["graph", "grade", "config", "powertrain"])

  • raster_resolution_arc_seconds (str, optional) -- If grade is added, the resolution (in arc-seconds) of the tiles to download (either 1 or 1/3). Defaults to 1.

  • default_config (bool, optional) -- If true, copy default configuration files into the output directory. Defaults to True.

  • requests_kwds (Optional[Dict], optional) -- Keyword arguments to pass to the requests Python library for HTTP configuration. Defaults to None.

  • afdc_api_key (str, optional) -- API key for the AFDC API to download EV charging stations. Defaults to "DEMO_KEY". See https://developer.nrel.gov/docs/transportation/alt-fuel-stations-v1/all/ for more information.

  • vehicle_models (Optional[List[str]]) -- If provided, only download and configure the listed vehicle models (by name, e.g. ["2017_CHEVROLET_Bolt", "2016_TOYOTA_Camry_4cyl_2WD"]). Use list_available_vehicle_models() to see valid names. When None (the default) all available models are included.

Example

>>> import osmnx as ox
>>> g = ox.graph_from_place("Denver, Colorado, USA")
>>> generate_compass_dataset(g, Path("denver_co"))
nrel.routee.compass.io.generate_dataset.list_available_vehicle_models() List[str][source]#

Return the list of all available vehicle model names that can be used with the vehicle_models parameter of generate_compass_dataset() and CompassApp.from_graph().

Each name corresponds to a vehicle configuration JSON shipped with the package (filename stem, e.g. "2017_CHEVROLET_Bolt").

Returns:

sorted list of available vehicle model name strings

Return type:

names

Example

>>> from nrel.routee.compass import list_available_vehicle_models
>>> models = list_available_vehicle_models()
>>> print(models[:3])
class nrel.routee.compass.io.utils.TileResolution(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
nrel.routee.compass.io.utils.add_grade_to_graph(g: networkx.MultiDiGraph, output_dir: Path = PosixPath('cache'), resolution_arc_seconds: str | int = 1, api_key: str | None = None) networkx.MultiDiGraph[source]#

Adds grade information to the edges of a graph. If using an api_key will try and download the grades from Google API, otherwise this will download the necessary elevation data from USGS as raster tiles and cache them in the output_dir. The resolution of the tiles can be specified with the resolution parameter. USGS has elevation data in increasing resolutions of: 1 arc-second and 1/3 arc-second Average tile file sizes for each resolution are about:

  • 1 arc-second: 50 MB

  • 1/3 arc-second: 350 MB

Parameters:
  • g (nx.MultiDiGraph) -- The networkx graph to add grades to.

  • output_dir (Path, optional) -- The directory to cache the downloaded tiles in. Defaults to Path("cache").

  • resolution_arc_seconds (str, optional) -- The resolution (in arc-seconds) of the tiles to download (either 1 or 1/3). Defaults to 1.

  • api_key -- The google API key to pull down grade information. If None will use USGS raster elevation tiles

Returns:

The graph with grade information added to the edges.

Return type:

g

Example

>>> import osmnx as ox
>>> g = ox.graph_from_place("Denver, Colorado, USA")
>>> g = add_grade_to_graph(g)
>>> g2 = ox.graph_from_place("Denver, Colorado, USA")
>>> g2 = add_grade_to_graph(g2, api_key=<api_key>)
nrel.routee.compass.plot.plot_folium.matched_path_to_coords(matched_path: dict[str, Any]) Sequence[Tuple[float, float]][source]#

Converts the matched path from a map matching query to coords to be sent to the folium map.

Parameters:

matched_path (Dict[str, Any]) -- A matched path from a map matching query (GeoJSON FeatureCollection)

Returns:

A sequence of latitude and longitude tuples.

Return type:

Sequence[(float, float)]

nrel.routee.compass.plot.plot_folium.plot_coords_folium(coords: Sequence[Tuple[float, float]], line_kwargs: dict[str, Any] | None = None, folium_map: Map | None = None) Map[source]#

Plots a sequence of pairs of latitude and longitude on a folium map as a route.

Parameters:
  • coords (Sequence[Tuple[float, float]]) -- A sequence of pairs of latitude and longitude

  • line_kwargs (Optional[Dict[str, Any]], optional) -- A dictionary of keyword arguments to pass to the folium Polyline

  • folium_map (folium.Map, optional) -- A existing folium map to plot the route on. Defaults to None.

Returns:

A folium map with the route plotted on it

Return type:

folium.Map

Example

>>> from nrel.routee.compass import CompassApp
>>> from nrel.routee.compass.plot import plot_route_folium
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {origin_x: -105.1710052, origin_y: 39.7402804, destination_x: -104.9009913, destination_y: 39.6757025}
>>> result = app.run(query)
>>> coords = result_dict_to_coords(result[0])
>>> m = plot_coords_folium(coords)
nrel.routee.compass.plot.plot_folium.plot_matched_path_folium(result_dict: dict[str, Any], line_kwargs: dict[str, Any] | None = None, folium_map: Map | None = None) Map[source]#

Plots the matched path from a map matching query on a folium map.

Parameters:
  • result_dict -- A result dictionary from a CompassApp map_match query

  • line_kwargs -- A dictionary of keyword arguments to pass to the folium Polyline

  • folium_map -- A existing folium map to plot the route on.

Returns:

A folium map with the route plotted on it

Return type:

folium_map

nrel.routee.compass.plot.plot_folium.plot_route_folium(result_dict: dict[str, Any], line_kwargs: dict[str, Any] | None = None, folium_map: Map | None = None) Map[source]#

Plots a single route from a compass query on a folium map.

Parameters:
  • result_dict -- A result dictionary from a CompassApp query

  • line_kwargs -- A dictionary of keyword arguments to pass to the folium Polyline

  • folium_map -- A existing folium map to plot the route on.

Returns:

A folium map with the route plotted on it

Return type:

folium_map

Example

>>> from nrel.routee.compass import CompassApp
>>> from nrel.routee.compass.plot import plot_route_folium
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {origin_x: -105.1710052, origin_y: 39.7402804, destination_x: -104.9009913, destination_y: 39.6757025}
>>> result = app.run(query)
>>> m = plot_route_folium(result)
nrel.routee.compass.plot.plot_folium.plot_routes_folium(results: dict[str, ~typing.Any] | list[dict[str, ~typing.Any]], value_fn: ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any] = <function <lambda>>, color_map: str = 'viridis', folium_map: ~folium.folium.Map | None = None) Map[source]#

Plot multiple routes from a CompassApp query on a folium map

Parameters:
  • results -- A result dictionary or list of result dictionaries from a CompassApp query

  • value_fn -- A function that takes a result dictionary and returns a value to use for coloring the routes. Defaults to lambda r: r["request"].get("name").

  • color_map (str, optional) -- The name of the matplotlib colormap to use for coloring the routes. Defaults to "viridis".

  • folium_map (folium.Map, optional) -- A existing folium map to plot the routes on. Defaults to None.

Returns:

A folium map with the routes plotted on it

Return type:

folium_map

Example

>>> from nrel.routee.compass import CompassApp
>>> from nrel.routee.compass.plot import plot_results_folium
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {origin_x: -105.1710052, origin_y: 39.7402804, destination_x: -104.9009913, destination_y: 39.6757025}
>>> result = app.run(query)
>>> m = plot_results_folium(result)
nrel.routee.compass.plot.plot_folium.result_dict_to_coords(result_dict: dict[str, Any]) Sequence[Tuple[float, float]][source]#

Converts the CompassApp results to coords to be sent to the folium map.

Parameters:

result_dict (Dict[str, Any]) -- A result dictionary from a CompassApp query

Returns:

A sequence of latitude and longitude tuples.

Return type:

Sequence[(float, float)]

Example

>>> from nrel.routee.compass import CompassApp
>>> from nrel.routee.compass.plot import result_dict_to_coords
>>> app = CompassApp.from_config_file("config.toml")
>>> query = {origin_x: -105.1710052, origin_y: 39.7402804, destination_x: -104.9009913, destination_y: 39.6757025}
>>> result = app.run(query)
>>> coords = result_dict_to_coords(result)