Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Behavior and Advanced Mobility Big Access Model (BAMBAM)

by Rob Fitzgerald and the BAMBAM contributors

BAMBAM is a scalable mobility access modeling platform built on RouteE Compass. It evaluates how easily people across a region can reach destinations—such as jobs, healthcare, food, retail, services, and entertainment—within given travel-time budgets across multiple transportation modes.

BAMBAM is designed for both smaller-scale studies in interactive notebooks and large-scale deployments on high-performance computing (HPC) systems. It was developed at the National Laboratory of the Rockies (formerly NREL) to scale the Mobility Energy Productivity (MEP) metric across the continental United States.

🌏 Explore the MEP metric interactively at mep.stratus.nlr.gov.

How This Book Is Organized

This guide walks through running BAMBAM—from a basic three-mode study to advanced multimodal scenarios:

What happens in an access study?

At a high level, BAMBAM takes a multimodal transportation network and a study region, divides the study region into a spatial grid of origins, simulates travel outward from each grid cell across any configured set of unimodal and multimodal trip types, and measures the reachable destinations across travel-time, distance, or energy thresholds.

1. Grid Generation & Population Weighting

Rather than evaluating access from arbitrary points, BAMBAM tessellates the study area into a regular spatial grid—by default, H3 resolution 8 hexagonal cells (each covering approximately \(0.74\text{ km}^2\)). Population data from the U.S. Census American Community Survey (ACS) is spatially apportioned to each grid cell based on areal overlap, allowing accessibility metrics to be weighted by the population they serve (see Grid and Population Input Plugin).

2. Mode & Trip-Chain Expansion

From the centroid of each grid cell, BAMBAM expands the query across all configured travel modes and multimodal trip chains. While our introductory quickstarts begin with a baseline walk, bike, and drive network, BAMBAM models each mode as a dedicated edge list sharing a common vertex set—allowing you to evaluate both single-mode trips and multi-leg trip chains (see Multimodal Routing Constraints):

  • Active Modes (walk, bike): Travel on links accessible to pedestrians or cyclists, optionally filtered or weighted by infrastructure comfort such as Walk Comfort Index (WCI) and Level of Traffic Stress (LTS) (see Modal Comfort Metrics).
  • Driving (drive): Travels on the drivable road network (using posted speeds or time-of-day congested operating speeds), optionally beginning with a short first-leg walk to reach a parked vehicle.
  • Public Transit & Shared Mobility (transit, gbfs, gtfs-flex): Combines walking, cycling, or driving legs with scheduled transit (GTFS), shared micromobility (GBFS), and on-demand microtransit (GTFS-Flex)—enforcing realistic mode-transition sequences, transfer limits, and per-leg or per-mode time and distance budgets (such as walk-to-transit, micromobility-to-transit, or kiss-and-ride).

3. Map Matching

Grid cell centroids rarely fall directly on a roadway centerline. Before routing begins, BAMBAM snaps each origin to the nearest network link permitted for the trip’s starting mode within a spatial tolerance (about \(0.53\text{ km}\) by default, matching the characteristic edge length of an H3 resolution 8 hexagon).

For each origin and configured trip mode, BAMBAM searches outward across the multimodal network to build a minimum-cost search tree up to the configured trip budgets (by default, a maximum travel time \(T_{\max} = 40\text{ minutes}\)).

  • Link costs and state variables are updated dynamically across modes—combining fixed or grade-adjusted active speeds, roadway speed limits or congested speeds, timetable-scheduled transit departures, and micromobility or microtransit boarding and dwell rules.
  • Any branch of the search terminates once it violates a multimodal transition rule or exceeds its cumulative travel-time, distance, or leg budget.

Note on Network Buffering: Because a 40-minute highway drive or regional rail trip can cover up to 40 miles, the underlying transportation network should extend well beyond the boundary of the study grid so trips originating near the edge of the study area are not artificially cut off.

5. Destination Filtering & Binning

Rather than reporting only a single total at \(T_{\max}\), BAMBAM filters reached tree branches for valid trip-ending states (for example, ensuring a traveler is not mid-ride inside a no-parking micromobility zone), deduplicates vertices reached via multiple mode sequences, and partitions destinations into cumulative intervals (see Binning and Destination Filtering). By default, destinations are binned by travel time at \(10, 20, 30,\text{ and }40\text{ minutes}\), though bins can also be defined by travel distance, energy consumption, or customized per mode. For a time bin \(b \in \{10, 20, 30, 40\}\), the reachable set includes all valid destinations reachable from origin \(i\) by mode \(m\) in travel time \(t_{ij}^m \le b\).

6. Isochrones

For each bin, BAMBAM constructs an isochrone—a polygon representing the geographic travel shed reachable within that threshold (e.g., \(10, 20, 30,\text{ or }40\text{ minutes}\)). Points are sampled along reached network geometries, and a concave hull is fit around them to capture the shape of the reachable watershed (see Isochrone Generation).

7. Opportunities & Composite Metrics

Finally, BAMBAM measures cumulative opportunity access within each bin (see Opportunity Sources and Opportunity Models). Employment and point-of-interest locations—such as U.S. Census LODES workplace employment records, Overture Maps places and buildings, or custom tabular datasets categorized into jobs, retail, healthcare, food, services, and entertainment—are spatially attached to the network. For each origin \(i\), mode \(m\), activity type \(k\), and threshold \(b\), BAMBAM sums the reachable opportunities:

\[A_{i,m,k}(b) = \sum_{j : t_{ij}^m \le b} O_{j,k}\]

where \(O_{j,k}\) is the number of opportunities of type \(k\) at destination \(j\). Optionally, BAMBAM can evaluate mathematical expressions directly on these binned counts in memory to produce composite indices such as the Mobility Energy Productivity (MEP) score (see Post-Processing Opportunities with the Eval Plugin).


Try It Out

To get started hands-on, the next two chapters walk through building a baseline walk / bike / drive network and running your first access study before layering on additional modes and features:

Running a Simple Access Study in the Command Line

This guide walks through a quick example of building a default walk / bike / drive road network for the Denver region and running an access study from the command line.

Prerequisites

Compile the Rust binaries and set your U.S. Census API key:

cargo build --release --manifest-path rust/Cargo.toml
export CENSUS_API_TOKEN="<your-census-api-key>"

1. Build the Network

Use script/bambam_build_open_data.sh with --to-stage network to download Overture Maps road data for the buffered Denver region (query/denver_470_buffer.txt) and write the network files to denver_buf/:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --to-stage network

This downloads the road network, separates it into walk/, bike/, and drive/ edge lists, and writes a ready-to-run denver_buf/bambam.toml configuration file.

2. Run BAMBAM

Now run bambam using the generated denver_buf/bambam.toml configuration and a query file describing our interior study grid (query/denver_extent.json, which sits well inside the buffered network extent):

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

Here, query/denver_extent.json simply specifies the study area polygon in Well-Known Text (WKT):

{
    "extent": "POLYGON ((-105.026035 39.728445, -104.958401 39.728445, -104.958401 39.77002, -105.026035 39.77002, -105.026035 39.728445))"
}

When finished, BAMBAM writes result.csv and result.json inside denver_buf/, containing the 10-, 20-, 30-, and 40-minute isochrones and reachable opportunity counts for every H3 grid cell and mode (walk, bike, and drive).

Running a Simple Access Study from Python

This guide shows how to build the default walk / bike / drive road network and run the same access study from Python.

Note for Python Users: At present, all data import steps and model configuration updates (covered in the subsequent chapters of this book) are performed via the command-line tools or by editing the bambam.toml configuration file directly, after which BambamRunner.from_config_file(...) is used to load and run the configured model in Python. In a future release, we plan to roll these import and configuration operations into a unified Python builder API.

Prerequisites

Compile the Rust binaries, install the Python package, and set your U.S. Census API key:

cargo build --release --manifest-path rust/Cargo.toml
uv sync
uv pip install -e ".[all]"
export CENSUS_API_TOKEN="<your-census-api-key>"

1. Build the Network

Run script/bambam_build_open_data.sh with --to-stage network to download the road network for query/denver_470_buffer.txt into denver_buf/:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --to-stage network

This creates the walk/, bike/, and drive/ network files and generates denver_buf/bambam.toml.

2. Run BAMBAM in Python

Load denver_buf/bambam.toml with BambamRunner and pass the study grid extent from query/denver_extent.json:

import json
from nlr.bambam import BambamRunner

# Load the generated configuration
app = BambamRunner.from_config_file("denver_buf/bambam.toml")

# Load the grid extent query
with open("query/denver_extent.json") as f:
    query = json.load(f)

# Run the access study
app.run(query)

When app.run(query) completes, the results are written to result.csv and result.json with 10-, 20-, 30-, and 40-minute isochrones and opportunity counts for each grid cell and travel mode:

import pandas as pd

df = pd.read_csv("result.csv")
print(df[["grid_id", "mode", "opps_jobs_10", "opps_jobs_20", "opps_jobs_30", "opps_jobs_40"]].head())

Overture Maps Import

1. Overview

The Overture Maps Foundation (OMF) publishes globally standardized, cloud-native geospatial datasets hosted as GeoParquet files on Amazon S3. Its Transportation theme represents road networks using an explicit connector-and-segment linear-referencing model:

  • Connectors: Point locations representing intersections or physical junctions where travel paths can branch or merge.
  • Segments: Continuous roadway, path, or track geometries (LineString) carrying linear-referenced attributes—including road class (motorway, primary, residential, footway, cycleway, etc.), directional access restrictions, and speed limits (mph or kph) that can vary along fractions of a segment’s length.
  • Infrastructure: Point and polygon features representing traffic signals, stop signs, yield (give_way) signs, and pedestrian crossings.

BAMBAM’s Overture Maps importer (bambam-omf, invoked by stage 1 of script/bambam_build_open_data.sh) queries Overture’s cloud GeoParquet releases directly over S3 for any study extent—eliminating the need to manually download and slice multi-gigabyte regional files. It then splits segments at interior connectors, attaches intersection infrastructure, filters links into modal networks (walk, bike, drive), removes disconnected network islands, and writes a ready-to-run RouteE Compass dataset.


2. Setup

1. Import via the Build Script (bambam_build_open_data.sh)

To download and build an Overture Maps road network using the pipeline script, run the network stage with your buffered WKT extent file:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --to-stage network

If you have already run the import once and want to rebuild the network from the cached raw/ Parquet files without re-downloading from S3, pass --local-omf-dir:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --local-omf-dir denver_buf/raw \
  --to-stage network \
  --force

Alternative: Direct CLI Invocation (bambam-omf or bambam_util import-network)

You can also invoke bambam-omf network (or bambam_util import-network --source omf) directly:

./rust/target/release/bambam-omf network \
  --configuration-file configuration/bambam-network/bambam-network-config.json \
  --extent-file query/denver_470_buffer.txt \
  --output-directory denver_buf

Network Filter Configuration (bambam-network-config.json)

The file configuration/bambam-network/bambam-network-config.json controls which Overture road classes and access modes are included in each modal edge list and sets the minimum connected-component size for island removal:

{
  "edge_lists": [
    {
      "mode": "walk",
      "filter": [
        { "type": "subtype", "subtype": "road" },
        {
          "type": "class",
          "classes": ["secondary", "tertiary", "residential", "living_street", "unclassified", "service", "pedestrian", "footway", "steps", "path", "track", "bridleway", "unknown"],
          "allow_unset": true,
          "behavior": "include"
        },
        { "type": "access_mode", "modes": ["foot"] }
      ]
    },
    {
      "mode": "bike",
      "filter": [
        { "type": "subtype", "subtype": "road" },
        {
          "type": "class",
          "classes": ["primary", "secondary", "tertiary", "residential", "living_street", "unclassified", "service", "pedestrian", "path", "track", "cycleway", "bridleway", "unknown"],
          "allow_unset": true,
          "behavior": "include"
        },
        { "type": "access_mode", "modes": ["bicycle"] }
      ]
    },
    {
      "mode": "drive",
      "filter": [
        { "type": "subtype", "subtype": "road" },
        {
          "type": "class",
          "classes": ["motorway", "trunk", "primary", "secondary", "tertiary", "residential", "living_street", "unclassified"],
          "allow_unset": false,
          "behavior": "include"
        },
        { "type": "access_mode", "modes": ["motor_vehicle", "car", "truck", "motorcycle"] }
      ]
    }
  ],
  "island_algorithm_configuration": {
    "min_distance": 2,
    "distance_unit": "miles"
  }
}

2. Run BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Two-Stage Cloud Spatial Filtering:
    • bambam-omf computes the bounding box of --extent-file and streams matching row groups from the latest Overture Maps release on Amazon S3 (segments, connectors, and infrastructure) using concurrent async readers.
    • Records inside the bounding box are then filtered against the exact WKT polygon geometry.
  2. Raw GeoParquet Caching (raw/):
    • The filtered Overture records are saved locally under denver_buf/raw/ (segments.parquet, connectors.parquet, and infrastructure.parquet), guaranteeing reproducibility and enabling offline re-imports.
  3. Linear-Referenced Segment Splitting & Island Removal:
    • Segments that contain interior connectors are split at each connector’s linear-referenced position \(\text{lr} \in [0, 1]\), producing directed graph edges with exact sub-linestring geometries, bearings, and speed limits.
    • Weakly connected components whose total roadway length is less than min_distance (2 miles by default) are removed so grid origins never snap to isolated parking lots or disconnected paths.
  4. Infrastructure Attachment & Dataset Serialization:
    • Traffic signals, stop signs, yield signs, and crossings are spatially matched within 15 meters to connector vertices (vertices-complete.csv.gz and vertices-*-enumerated.txt.gz).
    • Source-to-Compass ID mappings (vertices-mapping.csv.gz and <mode>/edges-mapping.csv.gz), mode subdirectories (walk/, bike/, drive/), network statistics (summary.toml), and a default bambam.toml are written to denver_buf/.

OpenStreetMap PBF Import

1. Overview

In addition to Overture Maps Foundation (OMF) cloud datasets, BAMBAM can build multimodal road networks directly from local OpenStreetMap (.osm.pbf) extracts (such as regional extracts from Geofabrik).

Both the OMF and OSM import pipelines share the same underlying graph construction engine (bambam-network), ensuring identical output file structures and modeling guarantees:

  • Non-Destructive Topological Splitting: OSM ways are split at intersections and simplified to collapse intermediate degree-2 shape nodes while preserving full WKT LineString geometries.
  • Spatial Infrastructure Attachment: OSM nodes tagged with traffic_signals, stop, give_way, or crossing are spatially matched (within 15 meters) to intersection vertices.
  • Modal Filtering & Island Removal: Ways are filtered by highway class and modal access tags into walk/, bike/, and drive/ edge lists, and disconnected network islands smaller than 2 miles are pruned.
  • Drop-In Compatibility: Produces the exact same bambam.toml, vertices-compass.csv.gz, and <mode>/edges-*.gz layout as Overture Maps imports.

2. Setup

1. Import an .osm.pbf File (bambam-osm or bambam_util import-network)

Suppose you have downloaded a regional OpenStreetMap extract (e.g., colorado-latest.osm.pbf) and want to build a BAMBAM network clipped to query/denver_470_buffer.txt.

You can run bambam-osm network (or the unified bambam_util import-network --source osm command) using the standard network filter configuration configuration/bambam-network/bambam-network-config.json:

./rust/target/release/bambam-osm network \
  --pbf-file /path/to/colorado-latest.osm.pbf \
  --configuration-file configuration/bambam-network/bambam-network-config.json \
  --extent-file query/denver_470_buffer.txt \
  --output-directory denver_osm

(Alternatively, using bambam_util import-network:)

./rust/target/release/bambam_util import-network \
  --source osm \
  --input-path /path/to/colorado-latest.osm.pbf \
  --configuration-file configuration/bambam-network/bambam-network-config.json \
  --extent-file query/denver_470_buffer.txt \
  --output-directory denver_osm

2. Run BAMBAM

Because the OSM importer generates the standard bambam.toml and modal subdirectories inside denver_osm/, running BAMBAM is identical to the Overture Maps workflow:

cd denver_osm

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. PBF Parsing & Polygonal Clipping:
    • bambam-osm streams the .osm.pbf binary file, filtering OSM ways and nodes against the highway classes defined in bambam-network-config.json and clipping them to the polygon in query/denver_470_buffer.txt.
  2. Raw Parquet Caching & ID Mapping:
    • Raw OSM node and way tables are saved to denver_osm/raw/nodes.parquet and denver_osm/raw/ways.parquet (allowing fast re-imports via --local-source denver_osm without re-parsing the PBF).
    • Bidirectional mappings between RouteE Compass IDs and OSM Node/Way IDs are written to vertices-mapping.csv.gz and <mode>/edges-mapping.csv.gz.
  3. Graph Serialization & Execution:
    • denver_osm/ is populated with bambam.toml, summary.toml, vertices-compass.csv.gz, and the walk/, bike/, and drive/ subdirectories, which bambam then loads to execute the grid access study and produce result.csv and result.json.

Scheduled Transit (GTFS)

1. Overview

Public transit operates on fixed routes and published timetables rather than continuous, on-demand roadway speeds. Modeling transit accessibility requires capturing:

  • First- and last-mile access: Walking from an origin to a transit stop, walking between stops to transfer routes, and walking from the alighting stop to the final destination.
  • Schedule-dependent waiting and in-vehicle travel: A traveler arriving at a transit stop at time \(t\) must wait until the next scheduled departure \(t_{\text{dep}} \ge t\) on that route before traversing the stop-to-stop link and arriving at \(t_{\text{arr}}\).

BAMBAM models scheduled public transit using GTFS (General Transit Feed Specification) feeds. It snaps GTFS stops to vertices on the road network, builds a dedicated transit edge list representing stop-to-stop service patterns, compiles active departures within a target date and time window into a high-speed binary timetable (edges-schedules.rkyv), and couples the walk and transit networks into a multimodal graph.


2. Setup

Building the Transit Network (bambam_build_open_data.sh)

In script/bambam_build_open_data.sh, stages 2 through 4 (gtfs-download, gtfs-import, and gtfs-config) download GTFS archives from a Mobility Data Catalog CSV manifest, compile the transit edge list and schedule tables into denver_buf/transit/, and generate denver_buf/bambam_gtfs.toml:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --gtfs-manifest path/to/mobility_catalog_manifest.csv \
  --subdivision-name "Colorado" \
  --from-stage network \
  --to-stage gtfs-config

Under the hood, these stages run:

  1. bambam-transit download: Downloads GTFS .zip feeds matching the country/subdivision filter into denver_buf/gtfs/.
  2. bambam-transit import: Filters feeds to the study extent, maps service calendars to the target date/time window (e.g., 08:00:00 to 09:00:00), snaps stops to vertices-compass.csv.gz, and writes denver_buf/transit/edges-compass.csv.gz and denver_buf/transit/edges-schedules.rkyv.
  3. bambam_util gtfs-config: Reads denver_buf/bambam.toml and writes denver_buf/bambam_gtfs.toml with the transit edge list, transit schedule traversal model, and "transit" multimodal label injected.

Modifying bambam_gtfs.toml

To evaluate transit trips during your target departure window, ensure bambam_gtfs.toml includes:

  1. A start_datetime input plugin so schedule lookups know when the trip begins:
    [[plugin.input_plugins]]
    type = "inject"
    format = "key_value"
    write_mode = "overwrite"
    key = "start_datetime"
    value = "2025-09-01 08:00:00"
    
  2. A transit mode entry under the trip_modes input plugin defining the multimodal leg rules (such as a maximum of 4 legs, up to 10 minutes of walking, and at least 3 minutes on transit):
    [plugin.input_plugins.modes.transit]
    multimodal_label = true
    max_trip_legs = 4
    constraints = [
        { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
        { type = "mode_leg_time_limit", mode = "transit", min = 3.0, unit = "minutes" },
        { type = "allowed_modes", values = ["walk", "transit"] },
    ]
    

Running BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam_gtfs.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Multimodal Graph Construction:
    • BAMBAM loads the walk, bike, drive, and transit edge lists over the shared vertex set (vertices-compass.csv.gz). Because GTFS stops were snapped to road network vertices during gtfs-import, travelers can seamlessly transition between walk edges and transit edges at any transit stop vertex.
  2. Schedule-Aware Tree Search:
    • For each grid cell’s transit query, the search starts at start_datetime (e.g., 8:00 AM) on the walk network.
    • When the search reaches a vertex with outgoing transit edges, it transitions from walk to transit (incrementing the trip leg counter).
    • The transit traversal model consults transit/edges-schedules.rkyv to find the earliest departure at or after the traveler’s current arrival time at that stop. The link travel time is computed as: \[\Delta t = (t_{\text{departure}} - t_{\text{arrival}}) + (t_{\text{next\_stop}} - t_{\text{departure}})\] capturing both schedule wait/transfer time and in-vehicle travel time.
    • At downstream stops, the traveler can either stay aboard the transit vehicle, transfer to another transit route, or alight back onto the walk network to reach final destinations, subject to the 10-minute total walk limit and 40-minute total trip time limit.
  3. Output Aggregation:
    • Reached destinations and opportunities along the multimodal walk+transit tree are binned into 10-, 20-, 30-, and 40-minute intervals and written to result.csv and result.json with mode = "transit".

Shared Micromobility (GBFS)

1. Overview

Shared micromobility systems—such as docked and dockless bikeshare and e-scooter fleets—publish operational data using the GBFS (General Bikeshare Feed Specification) standard. In an access study, shared micromobility acts as a first-mile, last-mile, or point-to-point mode governed by spatial geofencing rules:

  • Service and Boarding Zones: Where a traveler is allowed to pick up a vehicle and start a ride (ride_start_allowed).
  • Ride-Through Zones: Where a boarded rider is permitted to travel (ride_through_allowed) and whether localized speed caps apply (maximum_speed_kph).
  • Drop-Off Zones: Where a rider is permitted to end a trip and park the vehicle (ride_end_allowed).

BAMBAM’s bambam-gbfs tool downloads GBFS feeds (supporting v2.2, v2.3, and v3.0), extracts geofencing zones and operational rules, and compiles them into spatial lookup tables that constrain and price micromobility legs during multimodal routing.


2. Setup

1. Download and Process GBFS Feeds (bambam-gbfs)

First, compile the workspace binaries (including bambam-gbfs) and download either a single GBFS endpoint or a batch of feeds from a MobilityData systems.csv catalog into denver_buf/gbfs/:

# Download a single GBFS feed endpoint
./rust/target/release/bambam-gbfs download \
  --gbfs-url "https://example-operator.com/gbfs/3.0/gbfs.json" \
  --version v3.0 \
  --output-directory denver_buf/gbfs \
  --overwrite

# Or batch-download from a systems.csv catalog
./rust/target/release/bambam-gbfs batch-download \
  --csv-file systems.csv \
  --csv-column "Auto-Discovery URL" \
  --entry-point gbfs \
  --output-directory denver_buf/gbfs \
  --parallelism 8 \
  --overwrite

This creates three files in denver_buf/gbfs/:

  • edges-gbfs-geofences-enumerated.txt.gz: WKT polygon geometries for each geofence zone.
  • edges-gbfs-records.csv.gz: Zone attributes (system_id, ride_start_allowed, ride_through_allowed, ride_end_allowed, maximum_speed_kph, and time windows).
  • edges-system-ids.txt.gz: Enumerated operator system_id list.

2. Configure bambam.toml for GBFS

To add a gbfs mode that rides over the bikeable road network (bike/edges-compass.csv.gz), update denver_buf/bambam.toml:

  1. Add "gbfs" to [label]:

    [label]
    type = "multimodal"
    max_trip_legs = 3
    modes = ["walk", "bike", "drive", "gbfs"]
    

    (Also add "gbfs" to available_modes in each [[search]] block’s multimodal traversal and constraint models.)

  2. Append the gbfs edge list to [graph] and [mapping] (reusing the bike network topology and geometries):

    [graph]
    edge_list = [
        { input_file = "walk/edges-compass.csv.gz" },
        { input_file = "bike/edges-compass.csv.gz" },
        { input_file = "drive/edges-compass.csv.gz" },
        { input_file = "bike/edges-compass.csv.gz" },
    ]
    vertex_list_input_file = "vertices-compass.csv.gz"
    
    [mapping]
    type = "edge"
    geometry = [
        { type = "from_linestrings", geometry_input_file = "walk/edges-geometries-enumerated.txt.gz" },
        { type = "from_linestrings", geometry_input_file = "bike/edges-geometries-enumerated.txt.gz" },
        { type = "from_linestrings", geometry_input_file = "drive/edges-geometries-enumerated.txt.gz" },
        { type = "from_linestrings", geometry_input_file = "bike/edges-geometries-enumerated.txt.gz" },
    ]
    
  3. Add a [[search]] block for the gbfs edge list:

    [[search]]
    traversal.type = "combined"
    traversal.models = [
        { type = "distance", distance_unit = "miles" },
        { type = "gbfs", zone_record_input_file = "gbfs/edges-gbfs-records.csv.gz", zone_geometry_input_file = "gbfs/edges-gbfs-geofences-enumerated.txt.gz", system_ids_input_file = "gbfs/edges-system-ids.txt.gz", default_speed = { speed = 16.0, speed_unit = "kph" } },
        { type = "time", time_unit = "minutes" },
        { type = "multimodal", this_mode = "gbfs", available_modes = ["walk", "bike", "drive", "gbfs"] },
    ]
    
    constraint.type = "combined"
    constraint.models = [
        { type = "gbfs", zone_record_input_file = "gbfs/edges-gbfs-records.csv.gz", zone_geometry_input_file = "gbfs/edges-gbfs-geofences-enumerated.txt.gz", system_ids_input_file = "gbfs/edges-system-ids.txt.gz" },
        { type = "multimodal", this_mode = "gbfs", available_modes = ["walk", "bike", "drive", "gbfs"] },
    ]
    
  4. Inject start_time and add gbfs to trip_modes:

    [[plugin.input_plugins]]
    type = "inject"
    format = "key_value"
    write_mode = "overwrite"
    key = "start_time"
    value = "2025-09-01T08:00:00Z"
    
    [plugin.input_plugins.modes.gbfs]
    multimodal_label = true
    max_trip_legs = 3
    constraints = [
        { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
        { type = "allowed_modes", values = ["walk", "gbfs"] },
    ]
    

3. Run BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Spatial Geofence Indexing:
    • On startup, BAMBAM builds a polygonal R-tree over gbfs/edges-gbfs-geofences-enumerated.txt.gz linked to the operator rules in gbfs/edges-gbfs-records.csv.gz.
  2. Boarding and Geofence Enforcement (gbfs Constraint & Traversal):
    • A traveler can begin a trip by walking (walk) and transition onto the gbfs network only at a vertex that lies inside an active GBFS zone where ride_start_allowed = true and ride_through_allowed = true.
    • Upon boarding, BAMBAM records the operator’s system_id in the search state so the rider stays on that operator’s fleet for the duration of the micromobility leg.
    • As the rider traverses links on the gbfs network, the gbfs constraint model verifies that each vertex remains inside a valid ride_through_allowed zone for that operator.
    • The gbfs traversal model sets the link travel speed to default_speed (e.g., \(16\text{ km/h}\)), capping it at maximum_speed_kph whenever the rider passes through a slow-speed geofence zone.
    • If a zone has ride_end_allowed = false (a no-parking zone), the rider can pass through it, but BAMBAM marks those vertices as invalid destinations for ending the micromobility leg.
  3. Output Aggregation:
    • Valid destinations reached via walk + gbfs within 10, 20, 30, and 40 minutes are aggregated into isochrones and opportunity counts in result.csv and result.json.

On-Demand Transit (GTFS-Flex)

1. Overview

Many transit agencies operate demand-responsive or microtransit services—such as dial-a-ride, curb-to-curb shuttles, or deviated fixed routes—modeled using the GTFS-Flex specification. Instead of fixed stop-to-stop timetables, GTFS-Flex defines polygonal service zones (locations.geojson), booking rules, operating time windows (start_pickup_drop_off_window / end_pickup_drop_off_window), and zone-to-zone travel rules (stop_times.txt).

In BAMBAM, a GTFS-Flex trip allows a traveler to walk to a pickup location within an active flex zone, board an on-demand vehicle that routes over the drivable road network within permitted pickup/drop-off zone pairs, and alight to walk to their final destination.


2. Setup

1. Import GTFS-Flex Feeds (bambam-gtfs-flex)

After building your road network (e.g., denver_buf/), run bambam-gtfs-flex import on a directory containing GTFS-Flex .zip archives for a specific service date (YYYYMMDD):

./rust/target/release/bambam-gtfs-flex import \
  denver_buf/gtfs \
  denver_buf/flex \
  20250901

This extracts all GTFS-Flex zones, operating windows, and zone-pair relations active on 20250901 and writes them to denver_buf/flex/:

  • gtfs-flex-zones.csv.gz
  • gtfs-flex-geometries.txt.gz
  • gtfs-flex-relations.csv.gz
  • gtfs-flex-metadata.json

2. Inject GTFS-Flex into bambam.toml (bambam_util gtfs-flex-config-app)

Use bambam_util gtfs-flex-config-app to automatically augment denver_buf/bambam.toml with the gtfs-flex mode and write denver_buf/bambam-gtfs-flex.toml:

./rust/target/release/bambam_util gtfs-flex-config-app \
  --base-file denver_buf/bambam.toml \
  --out-file denver_buf/bambam-gtfs-flex.toml \
  --flex-directory denver_buf/flex \
  --start-time "2025-09-01T08:00:00" \
  --graph-edge-list 2 \
  --map-edge-list 2 \
  --gtfs-flex-edge-list 2 \
  --overwrite

Here, --graph-edge-list 2, --map-edge-list 2, and --gtfs-flex-edge-list 2 instruct BAMBAM to attach the gtfs-flex service to edge list index 2 (the drive road network, since on-demand microtransit vehicles travel on drivable streets).

3. Run BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam-gtfs-flex.toml \
  --query-file ../query/denver_extent.json

(See script/bambam_gtfs_flex_test.sh for a complete self-contained example script.)


3. What Happens

  1. Automated Configuration Injection (gtfs-flex-config-app):
    • Appends a fourth edge list (gtfs-flex) to [graph] and [mapping] backed by the drive network topology and geometries.
    • Adds "gtfs-flex" to the [label] modes and updates all multimodal traversal and constraint models.
    • Adds a [[search]] block for gtfs-flex combining the drive speed/time traversal models with the gtfs-flex zone traversal and departure-frontier constraint models.
    • Injects the trip start_time (2025-09-01T08:00:00) and adds the gtfs-flex mode constraints (allowing walk + gtfs-flex with a 0.5-mile walk limit on first/last legs and a 40-minute total time budget).
  2. Zone-Constrained On-Demand Routing:
    • During the search, a traveler can transition onto the gtfs-flex edge list at vertices inside a flex zone whose pickup window is active at start_time.
    • Once boarded in a pickup zone, the gtfs-flex traversal and constraint models track the active zone pair (gtfs-flex-relations.csv.gz), applying any boarding wait times (prior_notice_duration_min / zone delays) and restricting vehicle movement and alighting to valid drop-off zones within the service’s operating rules.
  3. Output Aggregation:
    • Destinations reachable within 10, 20, 30, and 40 minutes via gtfs-flex are written alongside walk, bike, and drive in result.csv and result.json.

Modal Comfort Metrics (WCI and LTS)

1. Overview

In active transportation planning, shortest-distance or fixed-speed routing over all legally permissible streets often overestimates real-world walking and cycling accessibility. Many streets that are technically open to pedestrians or cyclists lack sidewalks or bike lanes and carry high-speed vehicle traffic.

BAMBAM computes and applies two roadway comfort metrics:

  • Walking Comfort Index (WCI): An integer score in the range \([-6, 9]\) (where higher scores indicate greater pedestrian comfort) computed for every edge in the walk network. WCI combines:
    • Walkability: Presence of dedicated sidewalks or footways vs. shared roadway shoulders.
    • Traffic Speed Comfort: Posted or adjacent vehicle operating speeds.
    • Cycleway Buffer Comfort: Presence of adjacent bike lanes or buffers separating pedestrians from motor vehicles.
    • Intersection Control Comfort: Presence of traffic signals or stop signs at the upstream vertex. In BAMBAM, WCI is used as a route constraint: edges with a WCI below a user-specified comfort threshold are excluded from walking trips.
  • Level of Traffic Stress (LTS): A classification from LTS 1 (lowest stress, suitable for all ages and abilities, such as separated paths or buffered bike lanes) to LTS 4 (highest stress, high-speed multi-lane traffic) computed for every edge in the bike network based on cycling facility protection, street one-way status, and vehicle speeds. In BAMBAM, LTS is used as a traversal speed modifier: high-stress links apply a percentage speed penalty (or impedance) to reflect cyclist route preferences and delays.

2. Setup

1. Compute WCI and LTS (bambam_build_open_data.sh)

Stage 10 (modal-metrics) of script/bambam_build_open_data.sh computes walk/wci.csv.gz and bike/lts.csv.gz from the imported network’s complete edge and vertex tables:

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --from-stage modal-metrics \
  --to-stage modal-metrics

(If denver_buf has not been built yet, omit --from-stage modal-metrics and run --to-stage network first, or invoke bambam_util modal_metric directly:)

./rust/target/release/bambam_util modal_metric \
  --modal-metric WCI \
  --network-dir denver_buf \
  --mode walk \
  --output-file denver_buf/walk/wci.csv.gz

./rust/target/release/bambam_util modal_metric \
  --modal-metric LTS \
  --network-dir denver_buf \
  --mode bike \
  --output-file denver_buf/bike/lts.csv.gz

2. Configure WCI and LTS in bambam.toml

Update denver_buf/bambam.toml to attach the wci constraint model to the walk topology and the lts traversal model to the bike topology:

  1. Add the wci constraint model to the walk [[search]] section:

    ###
    ### WALK TOPOLOGY
    ###
    [[search]]
    traversal.type = "combined"
    traversal.models = [
        { type = "distance", distance_unit = "miles" },
        { type = "fixed_speed", name = "walk", speed = 5.0, speed_unit = "kph" },
        { type = "time", time_unit = "minutes" },
        { type = "multimodal", this_mode = "walk", available_modes = ["walk", "bike", "drive"] }
    ]
    
    constraint.type = "combined"
    constraint.models = [
        { type = "wci", wci_input_file = "walk/wci.csv.gz" },
        { type = "multimodal", this_mode = "walk", available_modes = ["walk", "bike", "drive"] }
    ]
    
  2. Add the lts traversal model to the bike [[search]] section (placed after fixed_speed and before time so time uses the LTS-adjusted edge_speed):

    ###
    ### BIKE TOPOLOGY
    ###
    [[search]]
    traversal.type = "combined"
    traversal.models = [
        { type = "distance", distance_unit = "miles" },
        { type = "fixed_speed", name = "bike", speed = 16.0, speed_unit = "kph" },
        { type = "lts", lts_input_file = "bike/lts.csv.gz", speed_unit = "kph", mapping = { "1" = { type = "percent_penalty", percent = 100.0 }, "2" = { type = "percent_penalty", percent = 90.0 }, "3" = { type = "percent_penalty", percent = 70.0 }, "4" = { type = "percent_penalty", percent = 40.0 } } },
        { type = "time", time_unit = "minutes" },
        { type = "multimodal", this_mode = "bike", available_modes = ["walk", "bike", "drive"] }
    ]
    
  3. Inject wci_threshold for queries (e.g., requiring a minimum WCI score of 0):

    [[plugin.input_plugins]]
    type = "inject"
    format = "key_value"
    write_mode = "overwrite"
    key = "wci_threshold"
    value = 0
    

3. Run BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Spatial Context Calculation (modal-metrics stage):
    • When computing WCI and LTS, bambam_util modal_metric loads not only the target mode’s edges (walk/edges-complete.csv.gz or bike/edges-complete.csv.gz) and intersection controls (vertices-complete.csv.gz), but also indexes sibling modal edge lists in a spatial R-tree so sidewalks and cycleways inherit speed and buffer context from adjacent roadways.
  2. WCI Filtering on Walk Searches:
    • During walk tree expansion, the wci constraint model checks each candidate edge’s score in walk/wci.csv.gz. Any link with \(\text{WCI} < \text{wci\_threshold}\) is rejected, restricting pedestrian travel sheds to comfortable walking infrastructure.
  3. LTS Speed Scaling on Bike Searches:
    • During bike tree expansion, the fixed_speed model first sets the base cycling speed (\(16\text{ km/h}\)), and the lts traversal model scales that speed by the configured percentage for the link’s LTS rating (e.g., \(100\%\) of base speed on LTS 1 paths, down to \(40\%\) on high-stress LTS 4 arterials) before link travel time is calculated.

Congestion Imputation

1. Overview

Default open road networks (from Overture Maps or OpenStreetMap) provide posted speed limits or functional road-class default speeds. However, real-world driving accessibility varies significantly by time of day due to traffic congestion—a 30-minute morning peak commute (wd-am) covers a much smaller travel shed than a 30-minute Sunday afternoon drive (we-af).

When empirical probe speed data (such as a commercial reference network) is available for a calibration region, BAMBAM’s congestion imputation pipeline transfers those observed congestion patterns onto the open road network across six standard time-of-day bins:

  • Weekday (Wednesday): Morning Peak (wd-am, 08:00–09:00), Midday (wd-af, 10:00–11:00), Evening Peak (wd-pm, 17:00–18:00)
  • Weekend (Sunday): Morning (we-am, 08:00–09:00), Afternoon (we-af, 10:00–11:00), Evening (we-pm, 17:00–18:00)

The pipeline conflates reference network links onto the open road network, computes surrounding land-use, demographic, and network topology features (such as intersection control density, POI activity density, and census population/employment density within a 0.5-mile radius), trains gradient-boosted tree (XGBoost) models, and imputes time-period-specific operating speeds for every drivable link in the open network.


2. Setup

1. Run the Congestion Pipeline Stages (bambam_build_open_data.sh)

In script/bambam_build_open_data.sh, stages 5 through 9 (census, opportunities, calibrate, train, and impute) execute the full congestion workflow. You must provide --ref-network-dir pointing to the reference speed dataset (and optionally --ref-speeds-dir if speed files are stored separately):

export CENSUS_API_TOKEN="<your-census-api-key>"

./script/bambam_build_open_data.sh \
  --extent-file query/denver_470_buffer.txt \
  --output-dir denver_buf \
  --ref-network-dir /path/to/reference_network \
  --from-stage census \
  --to-stage impute

(Ensure network stage has already been run for denver_buf/, or set --from-stage network --to-stage impute to run both network import and congestion imputation together.)

This produces six enumerated speed tables inside denver_buf/drive/:

  • drive/edges-speeds-wd-am-mph-enumerated.txt.gz
  • drive/edges-speeds-wd-af-mph-enumerated.txt.gz
  • drive/edges-speeds-wd-pm-mph-enumerated.txt.gz
  • drive/edges-speeds-we-am-mph-enumerated.txt.gz
  • drive/edges-speeds-we-af-mph-enumerated.txt.gz
  • drive/edges-speeds-we-pm-mph-enumerated.txt.gz

2. Point bambam.toml to a Congested Speed Table

In denver_buf/bambam.toml, update speed_table_input_file under the Drive Topology [[search]] block to reference the desired time bin (for example, weekday morning peak wd-am):

###
### DRIVE TOPOLOGY
###
[[search]]
traversal.type = "combined"
traversal.models = [
    { type = "distance", distance_unit = "miles" },
    { type = "speed", speed_unit = "mph", speed_table_input_file = "drive/edges-speeds-wd-am-mph-enumerated.txt.gz" },
    { type = "time", time_unit = "minutes" },
    { type = "multimodal", this_mode = "drive", available_modes = ["walk", "bike", "drive"] }
]

3. Run BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Feature Extraction (census & opportunities stages):
    • bambam-congestion export-census downloads Census tract geometries, population, and employment into denver_buf/census_tracts_bamcensus.csv.gz.
    • bambam-congestion export-opportunities downloads Overture Maps POIs and buildings into denver_buf/opportunities_omf.csv.gz.
  2. Conflation & Calibration (calibrate stage):
    • bambam-congestion calibrate spatially matches reference road segments to denver_buf/drive/edges-complete.csv.gz (using a 5-meter buffer and \(45^\circ\) maximum heading difference), attaches 0.5-mile geodesic spatial density features and vertex traffic-control attributes, and writes training tables to denver_buf/congestion_calibration/.
  3. Model Training (train stage):
    • train_congestion_models.py trains two XGBoost models (xgboost_model_with_speedlimit.json for links with known posted speed limits, and xgboost_model_without_speedlimit.json for links without posted speed limits) and saves them to denver_buf/congestion_models/.
  4. Network Speed Imputation & Routing (impute stage + bambam):
    • bambam-congestion impute evaluates the trained XGBoost models across every link in denver_buf/drive/ for all six time bins and writes the enumerated .txt.gz speed tables.
    • When bambam runs with edges-speeds-wd-am-mph-enumerated.txt.gz, drive tree searches use the imputed weekday AM peak operating speeds on every roadway link, reflecting realistic peak-hour travel times and contracted peak-hour isochrones.

Multimodal Routing Constraints

Real-world trips often combine multiple modes of transportation—such as walking a few blocks to a bus stop, riding shared micromobility to a rail station, being dropped off at a transit hub (kiss-and-ride), or taking an on-demand microtransit shuttle to connect with regional transit.

BAMBAM represents each transportation mode (walk, bike, drive, transit, gbfs, gtfs-flex) as a separate edge list sharing a common set of network vertices. Travelers can switch modes at any vertex that connects edges from two different mode networks. To ensure simulated trips reflect realistic traveler behavior—and to keep the multimodal search space tractable—BAMBAM pairs a multimodal traversal model with a multimodal constraint model (and a multimodal label model).


1. How Multimodal Traversal and Constraint Models Work

Every mode’s [[search]] block in bambam.toml includes a multimodal entry in both traversal.models and constraint.models:

[[search]]
traversal.type = "combined"
traversal.models = [
    { type = "distance", distance_unit = "miles" },
    { type = "fixed_speed", name = "walk", speed = 5.0, speed_unit = "kph" },
    { type = "time", time_unit = "minutes" },
    { type = "multimodal", this_mode = "walk", available_modes = ["walk", "bike", "drive", "transit", "gbfs", "gtfs-flex"] },
]

constraint.type = "combined"
constraint.models = [
    { type = "multimodal", this_mode = "walk", available_modes = ["walk", "bike", "drive", "transit", "gbfs", "gtfs-flex"] },
]

As a search expands across an edge belonging to this_mode, the multimodal traversal model performs link-level accounting on the search state:

  1. Mode Transition Detection: Compares this_mode (and, for scheduled transit, the edge’s route_id) against the mode of the current active trip leg (active_leg). Whenever the traveler switches modes—or transfers between two different transit routes—the model increments active_leg and records the new mode in leg_<idx>_mode.
  2. Leg-Level Accumulators: Adds the link’s edge_distance and edge_time to the active leg’s accumulators (leg_<idx>_distance and leg_<idx>_time).
  3. Mode-Level Accumulators: Adds the link’s edge_distance and edge_time to the cumulative totals for that mode across the entire trip (mode_<mode>_distance and mode_<mode>_time), even if that mode is used across multiple non-contiguous legs (e.g., walking on both the first and last legs of a transit trip).

The Multimodal Constraint Model: Rules on Mode Transitions & Budgets

Before the search is allowed to traverse a candidate edge, the multimodal constraint model inspects the accumulated state variables and enforces two categories of rules:

  1. Mode Transition Rules: Determines whether transitioning into this_mode is legal given the sequence of modes used so far, the maximum number of trip legs (max_trip_legs), and whether any minimum time/distance requirement on the outgoing leg has been satisfied before switching modes.
  2. Resource Budget Rules: Verifies that adding the candidate link will not push the trip’s total, per-mode, or per-leg distance or travel time past its configured maximum limit.

Multimodal Labels (multimodal_label)

In a single-mode search, only the fastest path to each vertex needs to be retained (multimodal_label = false). In complex multimodal trips, however, a traveler who reaches a vertex quickly by driving may no longer be allowed to board transit, whereas a traveler who walked to that same vertex can. Setting multimodal_label = true on a mode in trip_modes instructs BAMBAM’s [label] model to include the sequence of leg modes ([walk], [walk, transit], etc.) in the search label so valid mode sequences are not pruned prematurely.


2. Multimodal Constraint Configurations

Constraints are declared per travel mode inside the trip_modes input plugin ([[plugin.input_plugins]] with type = "trip_modes"). Shared constraints placed under [plugin.input_plugins.defaults] are automatically prepended to every mode’s constraint list.

Below are all available constraint types and their TOML syntax.

Mode & Sequence Constraints

Constraint typePurposeExample
allowed_modesRestricts the trip to a set of permitted modes in any order (up to max_trip_legs).{ type = "allowed_modes", values = ["walk", "transit"] }
exact_sequencesRequires the trip’s leg sequence to match one of the listed mode sequences (or a prefix thereof). Automatically infers max_trip_legs if omitted.{ type = "exact_sequences", values = [["drive"], ["walk", "drive"]] }
mode_countsCaps how many distinct legs can use each mode during a trip.{ type = "mode_counts", values = { walk = 2, transit = 1 } }

Whole-Trip Resource Limits

Whole-trip limits constrain total trip_time or trip_distance summed across all legs. Each accepts min and/or max bounds (plus optional min_exclusive = true / max_exclusive = true) and a unit:

constraints = [
    { type = "time_limit", max = 40.0, unit = "minutes" },
    { type = "distance_limit", max = 25.0, unit = "miles" },
]

Cumulative Per-Mode Limits (mode_time_limit & mode_distance_limit)

Cumulative mode limits cap (or set a floor on) the total time or distance spent in a specific mode summed across all legs of the trip. You can write them using either inline single-mode syntax (mode = "...") or multi-mode values map syntax:

constraints = [
    # Inline syntax: spend no more than 10 minutes walking across the entire trip
    { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },

    # Map syntax: cap total walking distance at 1.0 mile and total biking distance at 5.0 miles
    { type = "mode_distance_limit", values = { walk = { max = 1.0, unit = "miles" }, bike = { max = 5.0, unit = "miles" } } },
]

Per-Leg Mode Limits (mode_leg_time_limit & mode_leg_distance_limit)

Per-leg limits constrain the time or distance spent in a mode on a specific trip leg. The leg selector supports:

  • "first": The departing leg of the trip (leg index 0).
  • "last": The final leg of the trip (max_trip_legs - 1).
  • "any" (default if leg is omitted): Applies independently to every leg that uses that mode.
  • An integer index (0, 1, 2, …) or { type = "leg_index", index = 1 }: Targets a specific 0-based leg number.

How min bounds work on legs: A min bound on a leg (such as requiring at least 3 minutes on a transit leg) is evaluated when switching out of that leg—preventing trivial 1-stop hops while allowing the leg to build up from 0 minutes as it starts.

constraints = [
    # Walk at most 0.5 km on the first leg
    { type = "mode_leg_distance_limit", mode = "walk", leg = "first", max = 0.5, unit = "kilometers" },

    # Every transit leg must be at least 3 minutes long
    { type = "mode_leg_time_limit", mode = "transit", leg = "any", min = 3.0, unit = "minutes" },
]

3. Combining Constraints for Multimodal Travel Behaviors

Using the trip_modes input plugin, you can evaluate unimodal and complex multimodal behaviors side-by-side in a single BAMBAM run.

[[plugin.input_plugins]]
type = "trip_modes"

[plugin.input_plugins.defaults]
multimodal_label = false
constraints = [
    { type = "time_limit", max = 40.0, unit = "minutes" },
]

Standard Unimodal & Park-Access Modes (walk, bike, drive)

[plugin.input_plugins.modes.walk]
constraints = [
    { type = "allowed_modes", values = ["walk"] },
]

[plugin.input_plugins.modes.bike]
constraints = [
    { type = "allowed_modes", values = ["bike"] },
]

# Drive: allow up to 0.5 km of walking on the first leg to reach a parked vehicle
[plugin.input_plugins.modes.drive]
constraints = [
    { type = "mode_leg_distance_limit", mode = "walk", leg = "first", max = 0.5, unit = "kilometers" },
    { type = "exact_sequences", values = [["drive"], ["walk", "drive"]] },
]

Scheduled Transit with Walk Access/Egress (transit)

Allows up to 4 legs (e.g., walk -> transit -> transit -> walk or walk -> transit -> walk), caps total walking across the trip at 10 minutes, and requires each transit ride to last at least 3 minutes:

[plugin.input_plugins.modes.transit]
multimodal_label = true
max_trip_legs = 4
constraints = [
    { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
    { type = "mode_leg_time_limit", mode = "transit", min = 3.0, unit = "minutes" },
    { type = "allowed_modes", values = ["walk", "transit"] },
]

First- and Last-Mile Transit + Shared Micromobility (transit_gbfs)

Shared bikes and e-scooters (gbfs) can dramatically expand the catchment area of high-frequency transit stations compared to walking alone. Here, a traveler can walk or ride micromobility to reach transit, transfer, and use micromobility or walk at the destination end:

[plugin.input_plugins.modes.transit_gbfs]
multimodal_label = true
max_trip_legs = 5
constraints = [
    # Allowed modes across the trip
    { type = "allowed_modes", values = ["walk", "gbfs", "transit"] },
    # Cap total walking at 10 minutes and total micromobility riding at 15 minutes
    { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
    { type = "mode_time_limit", mode = "gbfs", max = 15.0, unit = "minutes" },
    # Require each transit ride to be at least 3 minutes
    { type = "mode_leg_time_limit", mode = "transit", min = 3.0, unit = "minutes" },
]

Kiss-and-Ride / Park-and-Ride (kiss_and_ride)

In a kiss-and-ride (or park-and-ride) trip, a traveler uses a private automobile for the first-mile access leg to reach a transit station (drive -> transit -> walk, or walk -> drive -> transit -> walk), then completes the trip on transit and foot without driving at the destination end. Using exact_sequences and per-leg limits prevents the model from driving all the way to the destination or using a car after alighting from transit:

[plugin.input_plugins.modes.kiss_and_ride]
multimodal_label = true
max_trip_legs = 4
constraints = [
    # Only allow driving on the access side before boarding transit
    { type = "exact_sequences", values = [
        ["drive", "transit", "walk"],
        ["drive", "transit", "transit", "walk"],
        ["walk", "drive", "transit", "walk"],
    ] },
    # Cap the first-mile drive access leg at 10 minutes (or 5 miles)
    { type = "mode_leg_time_limit", mode = "drive", max = 10.0, unit = "minutes" },
    { type = "mode_leg_distance_limit", mode = "drive", max = 5.0, unit = "miles" },
    # Cap total walking at 10 minutes and require at least 5 minutes on transit
    { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
    { type = "mode_leg_time_limit", mode = "transit", min = 5.0, unit = "minutes" },
]

On-Demand Microtransit + Fixed-Route Transit (flex_transit)

Many transit agencies deploy GTFS-Flex microtransit zones in lower-density suburbs to feed riders into trunk bus or rail corridors (transit). Combining walk, gtfs-flex, and transit models both direct on-demand trips and first-/last-mile feeder trips into the scheduled transit network:

[plugin.input_plugins.modes.flex_transit]
multimodal_label = true
max_trip_legs = 4
constraints = [
    # Allow walking, on-demand microtransit, and fixed-route transit
    { type = "allowed_modes", values = ["walk", "gtfs-flex", "transit"] },
    # Limit on-demand microtransit to a single feeder leg of at most 15 minutes
    { type = "mode_counts", values = { "gtfs-flex" = 1, transit = 2, walk = 2 } },
    { type = "mode_leg_time_limit", mode = "gtfs-flex", max = 15.0, unit = "minutes" },
    # Limit walking to 10 minutes total
    { type = "mode_time_limit", mode = "walk", max = 10.0, unit = "minutes" },
]

Grid and Population Input Plugin

1. Overview

Regional accessibility studies evaluate how the transportation network serves an entire metropolitan area or state rather than a single origin-destination pair. To do this systematically, BAMBAM uses the grid input plugin to convert a single study-area boundary polygon (extent) into a uniform spatial grid of origin cells and attach resident population counts to each cell.

  • Hexagonal Spatial Tessellation (H3): BAMBAM uses the H3 hierarchical hexagonal spatial index (by default, resolution 8, where each hexagon covers approximately \(0.74\text{ km}^2\) with an average edge length of \(0.53\text{ km}\)). Hexagons minimize orientation bias and have uniform adjacency distances to all six neighbors.
  • Areal-Weighted Population Disaggregation: To evaluate population-weighted regional access, BAMBAM fetches U.S. Census American Community Survey (ACS) population counts (paired with TIGER/Line census geometries) and apportions them onto the H3 grid cells. When an H3 hexagon \(i\) intersects a set of census polygons \(c \in C\), the grid cell’s population \(P_i\) is computed assuming uniform spatial distribution within each census unit: \[P_i = \sum_{c \in C} P_c \cdot \frac{\text{Area}(i \cap c)}{\text{Area}(c)}\]

2. Setup

Configuring the grid Input Plugin in bambam.toml

In bambam.toml, the grid input plugin is placed at the start of [[plugin.input_plugins]] (before trip_modes):

[[plugin.input_plugins]]
type = "grid"
extent_format = "wkt"
grid = { type = "h3", resolution = 8 }

[plugin.input_plugins.population_source]
type = "acs"
acs_type = "five_year"
acs_year = 2022
acs_resolution = "census_tract"
acs_categories = ["B01001_001E"]

Key configuration parameters:

  • extent_format: Format of the "extent" polygon in the input query JSON ("wkt" for POLYGON ((...)) or MULTIPOLYGON (((...)))).
  • grid: Grid tessellation system and resolution (type = "h3", resolution = 0..15). Common resolutions for regional studies are 7 (\(5.16\text{ km}^2\)), 8 (\(0.74\text{ km}^2\)), and 9 (~\(0.11\text{ km}^2\)).
  • population_source (optional):
    • type = "acs": Downloads U.S. Census ACS tables via bamcensus (requires CENSUS_API_TOKEN in the environment).
    • acs_type: "five_year" (5-year ACS estimates, covering all tracts/block groups) or "one_year" (1-year ACS estimates).
    • acs_year: Survey year (e.g., 2022 or 2024).
    • acs_resolution: Census geographic granularity ("census_tract", "block_group", "county", or "state").
    • acs_categories: List of ACS variable codes to sum (e.g., ["B01001_001E"] for total population).

Optional: Pre-Processing the Grid Offline (bambam_util preprocess_grid)

For very large multi-state studies or HPC runs where compute nodes lack internet access, you can pre-generate the H3 grid and ACS population dataset ahead of time using bambam_util preprocess_grid:

export CENSUS_API_TOKEN="<your-census-api-key>"

./rust/target/release/bambam_util preprocess_grid \
  --acs-type five-year \
  --acs-year 2022 \
  --acs-resolution census-tract \
  --acs-categories "B01001_001E" \
  --extent-format wkt \
  --grid-resolution 8 \
  --extent-file query/denver_470_extent.txt \
  --output-file denver_buf/preprocessed_grid.jsonl

This writes a newline-delimited JSON query file where each line already contains grid_id, origin_x, origin_y, geometry, and population. When passing a pre-processed query file to bambam (with --newline-delimited), the grid input plugin detects that origin_x and origin_y are already present and passes the rows straight through without re-querying the Census API.

Running BAMBAM

To run with on-the-fly grid generation from an extent query JSON (query/denver_extent.json):

export CENSUS_API_TOKEN="<your-census-api-key>"
cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Query Validation & Template Extraction:
    • The grid plugin inspects the incoming query JSON. If the query contains "origin_x" and "origin_y" (a point query), the plugin is a no-op. If the query contains "extent", the plugin parses the WKT POLYGON or MULTIPOLYGON and preserves any additional user keys on the JSON object as a template.
  2. H3 Polyfill & Centroid Extraction:
    • BAMBAM fills the polygon extent with H3 cells at the configured resolution.
    • For each H3 cell, it creates a query object populated with:
      • grid_id: The hexadecimal H3 index string (e.g., "88268cda01fffff").
      • origin_x and origin_y: The longitude and latitude of the hexagon’s centroid.
      • geometry: The WKT boundary polygon of the H3 hexagon.
  3. Census ACS Download & Spatial Intersection:
    • When population_source is configured, BAMBAM identifies which U.S. states intersect the study extent, downloads the requested ACS table (B01001_001E) and TIGER/Line census tract polygons, and indexes them in a polygonal R-tree.
    • Across all CPU threads in parallel, each H3 hexagon’s boundary geometry is intersected with the census tract R-tree to compute the area-proportioned population field, which is attached to the grid row and carried through to result.csv and result.json.

Binning and Destination Filtering

1. Overview

After BAMBAM builds a shortest-path search tree outward from a grid cell origin, raw tree branches must be translated into meaningful transportation accessibility metrics. The bambam output plugin (type = "bambam") governs how reached network locations are filtered, deduplicated, and binned before downstream plugins compute isochrones and opportunity counts.

Aggregate vs. Disaggregate Output Formats

  • format = "aggregate" (standard): Partitions reached destinations into cumulative intervals (bins) along a chosen state variable—most commonly travel time (trip_time at 10, 20, 30, and 40 minutes), travel distance (trip_distance), energy consumption, or a custom state variable.
  • format = "disaggregate": Skips binning and outputs reachable opportunities across the entire unbinned search tree.

Global vs. Modal Configuration (GlobalOrModal)

In the bambam output plugin, binning, destination_filter, isochrone_point_model, and isochrone_algorithm can each be specified as either:

  • type = "global": Applies the same setting to all travel modes (value = { ... }).
  • type = "modal": Applies different settings per travel mode (values = { walk = ..., drive = ... }, with an optional fallback). For example, you might bin walking trips at [5, 10, 15, 20] minutes while binning driving and transit trips at [10, 20, 30, 40] minutes, or use distance bins for walking and time bins for driving.

Destination Filtering (destination_filter)

Not every link or vertex traversed during a multimodal trip is a valid place to end the trip. For example, in a shared micromobility (gbfs) trip, a rider may be allowed to ride through a geofenced zone (ride_through_allowed = true) where parking is prohibited (ride_end_allowed = false). Similarly, custom traversal models may set a boolean state variable indicating whether the traveler is currently in a valid alighting state. Configuring a destination_filter ensures that only search tree branches satisfying those boolean predicates are counted as reachable destinations.


2. Setup

Configuring bambam Binning and Filtering in bambam.toml

In bambam.toml, the bambam output plugin must appear before the isochrone and opportunity output plugins so it can scaffold the bin ranges and destination filters on each result row:

[[plugin.output_plugins]]
type = "bambam"
format = "aggregate"
isochrone_format = "wkb"
opportunity_orientation = "destination_vertex_oriented"

# Global time binning: 10, 20, 30, and 40 minutes
binning.type = "global"
binning.value = { type = "time", feature = "trip_time", values = [10, 20, 30, 40], unit = "minutes" }

isochrone_point_model.type = "global"
isochrone_point_model.value = { type = "linestring_stride", stride = 100.0, distance_unit = "meters" }

isochrone_algorithm.type = "global"
isochrone_algorithm.value = { type = "concave_hull", concavity = 1.2, length_threshold = 0.0025, simplify_epsilon_latlon = 0.0003 }

Alternative Binning Configurations

  1. Distance Binning (type = "distance"): Group reached destinations by network travel distance (e.g., 1, 2, 5, and 10 miles):

    [plugin.output_plugins.binning]
    type = "global"
    value = { type = "distance", feature = "trip_distance", values = [1, 2, 5, 10], unit = "miles" }
    
  2. Energy Binning (type = "energy"): When paired with a RouteE Compass powertrain traversal model, bin by energy expended (trip_energy):

    [plugin.output_plugins.binning]
    type = "global"
    value = { type = "energy", feature = "trip_energy", values = [1, 2, 3, 5], unit = "kilowatt_hours" }
    
  3. Modal Binning (type = "modal"): Use finer time or distance bins for active modes and wider bins for motorized modes:

    [plugin.output_plugins.binning]
    type = "modal"
    values.walk = { type = "time", feature = "trip_time", values = [5, 10, 15, 20], unit = "minutes" }
    values.bike = { type = "time", feature = "trip_time", values = [10, 20, 30, 40], unit = "minutes" }
    values.drive = { type = "time", feature = "trip_time", values = [10, 20, 30, 40], unit = "minutes" }
    fallback = { type = "time", feature = "trip_time", values = [10, 20, 30, 40], unit = "minutes" }
    

Adding a Destination Filter (destination_filter)

To restrict destination collection to branches where a boolean state feature is true (or false when negate = true):

[plugin.output_plugins.destination_filter]
type = "global"
value = [
    { type = "boolean", feature = "valid_destination", negate = false }
]

Running BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Row Scaffolding (bambam Output Plugin):
    • For each completed search row, the bambam output plugin inspects request.trip_mode, resolves the active binning, destination_filter, and isochrone settings for that mode, and writes them to the row’s info metadata for downstream plugins (isochrone and opportunity).
  2. Destination Filtering & Multimodal Vertex Deduplication:
    • When collecting destinations from the search tree, BAMBAM first discards the origin root node and any tree branch that fails a destination_filter predicate.
    • In a multimodal search (multimodal_label = true), a single network vertex \(v\) may be reached by multiple mode sequences (for example, ["walk"] arriving at 14 minutes and ["walk", "bike"] arriving at 8 minutes). BAMBAM deduplicates destinations by vertex ID, keeping only the branch with the lowest accumulated total_cost at each vertex so opportunities at vertex \(v\) are never double-counted.
  3. Cumulative Bin Assignment:
    • From the configured bin upper bounds (e.g., values = [10, 20, 30, 40]), BAMBAM constructs cumulative intervals starting from zero: \([0, 10)\), \([0, 20)\), \([0, 30)\), and \([0, 40)\).
    • Each deduplicated destination branch is placed into every bin whose upper bound exceeds its state value (trip_time, trip_distance, etc.), and stored under aggregate_opportunities.<bin_key> (e.g., aggregate_opportunities.10, aggregate_opportunities.20, etc.).

Isochrone Generation

1. Overview

An isochrone (or travel shed) is a polygon delineating the geographic area reachable from an origin within a given travel time, distance, or energy threshold. In BAMBAM, isochrones provide both visual insight into how road network topology, barriers (rivers, highways), and modal speeds shape mobility, and geometric polygons for spatial overlay analysis.

Generating an accurate isochrone from a shortest-path tree involves three configuration choices in the bambam output plugin, which are then executed by the isochrone output plugin:

  1. Point Sampling Model (isochrone_point_model): How BAMBAM extracts 2D coordinate points from the reached branches of the search tree:
    • destination_point: Uses only the endpoint coordinate of each reached link. Fast, but can miss intermediate curvature along long rural or highway links.
    • linestring_coordinates: Includes all shape vertices along each reached link’s LineString geometry.
    • linestring_stride (default): Interpolates points at a regular distance interval (stride, e.g., every 100.0 meters) along each reached link’s LineString geometry, ensuring uniform point density along both short urban blocks and long highway segments.
    • buffered_linestring / buffered_destination_point: Generates a circular buffer of points (buffer_radius) around each reached link or destination vertex.
  2. Hull Construction Algorithm (isochrone_algorithm): How BAMBAM wraps the sampled point cloud into a polygon:
    • concave_hull (default): Fits a concave hull around the point cloud controlled by concavity (smaller values hug the road network more tightly), length_threshold (minimum edge length in lat/lon degrees for inward subdivision), and optional Ramer-Douglas-Peucker smoothing (simplify_epsilon_latlon).
    • k_nearest_concave_hull: Constructs a concave hull using the \(k\)-nearest neighbors algorithm with a fixed k (must be \(\ge 3\)).
    • k_nearest_log_scaled / k_nearest_sqrt_scaled: Dynamically scales \(k = c \cdot \log_b(n)\) or \(k = \sqrt{n}\) based on the number of reached points \(n\).
  3. Serialization Format (isochrone_format): How the resulting polygon is encoded in result.csv and result.json:
    • wkb (default): Hex-encoded Well-Known Binary—compact and fast to parse in GeoPandas (geopandas.GeoSeries.from_wkb) or PostGIS.
    • wkt: Human-readable Well-Known Text (POLYGON ((...))).
    • geo_json: GeoJSON Feature string.

2. Setup

Configuring Isochrones in bambam.toml

Isochrone parameters are declared inside the bambam output plugin block, followed by the isochrone output plugin:

[[plugin.output_plugins]]
type = "bambam"
format = "aggregate"
isochrone_format = "wkb"

binning.type = "global"
binning.value = { type = "time", feature = "trip_time", values = [10, 20, 30, 40], unit = "minutes" }

isochrone_point_model.type = "global"
isochrone_point_model.value = { type = "linestring_stride", stride = 100.0, distance_unit = "meters" }

isochrone_algorithm.type = "global"
isochrone_algorithm.value = { type = "concave_hull", concavity = 1.2, length_threshold = 0.0025, simplify_epsilon_latlon = 0.0003 }

[[plugin.output_plugins]]
type = "isochrone"

Because walking trees cover dense, short blocks while driving trees span long highway corridors, you can vary the sampling density by mode using type = "modal":

[plugin.output_plugins.isochrone_point_model]
type = "modal"
values.walk = { type = "linestring_stride", stride = 20.0, distance_unit = "meters" }
values.bike = { type = "linestring_stride", stride = 50.0, distance_unit = "meters" }
values.transit = { type = "linestring_stride", stride = 50.0, distance_unit = "meters" }
values.drive = { type = "linestring_stride", stride = 150.0, distance_unit = "meters" }

Reference for concave_hull Degree Thresholds

Both length_threshold and simplify_epsilon_latlon on concave_hull are specified in decimal degrees (latitude/longitude):

Approximate Ground DistanceDegrees (lat/lon)
~15 meters0.000135
~30 meters0.0003
~100 meters0.0009
~250 meters0.00225–0.0025
~500 meters0.0045

Running BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Binned Branch Collection:
    • For each completed search tree, the isochrone output plugin retrieves the binned, deduplicated destination branches prepared by the bambam configuration (e.g., for the 10-, 20-, 30-, and 40-minute bins).
  2. Geometry Point Cloud Generation (isochrone_point_model):
    • For each bin, BAMBAM looks up the reached edge geometries in the RouteE Compass MapModel (<mode>/edges-geometries-enumerated.txt.gz) and extracts a MultiPoint cloud according to isochrone_point_model (e.g., interpolating points every 100 meters along each reached roadway LineString).
  3. Concave Hull & Simplification (isochrone_algorithm):
    • If a bin contains fewer than 3 points, BAMBAM emits an empty POLYGON EMPTY geometry.
    • Otherwise, BAMBAM runs the configured hull algorithm (such as concave_hull with concavity = 1.2 and length_threshold = 0.0025) and optionally simplifies the exterior ring using Ramer-Douglas-Peucker (simplify_epsilon_latlon = 0.0003) to keep output file sizes small.
  4. Serialization to Output Columns:
    • For each bin key (10, 20, 30, 40), the plugin records both the number of reached destination vertices (aggregate_opportunities.<bin>.n_destinations, mapped to opps_count_<bin>) and the serialized polygon (aggregate_opportunities.<bin>.isochrone, mapped to isochrone_<bin> in result.csv).

Opportunity Sources and Opportunity Models

1. Overview

In transportation accessibility modeling, travel time alone only tells half the story—the value of a transportation network lies in the opportunities (activities, jobs, goods, and services) it connects people to.

BAMBAM separates opportunity modeling into two concepts:

  • Opportunity Source: Where raw land-use and employment data come from and how domain-specific categories are mapped to study activity types (such as jobs, retail, healthcare, food, services, and entertainment). BAMBAM provides built-in connectors for:
    • U.S. Census LEHD LODES: Workplace Area Characteristics (WAC) employment counts by NAICS industry sector (CNS01–CNS20), joined with Census TIGER/Line block or tract polygons.
    • Overture Maps Foundation (OMF): Point-of-interest places and buildings footprints downloaded from cloud object storage and categorized by land-use taxonomy.
    • Custom Tabular Data: Point or polygon CSV datasets in wide or long format.
  • Opportunity Model: How those opportunities are attached to the routing graph and looked up during a study:
    • api Model: Downloads and spatially disaggregates opportunities onto network vertices on the fly when BAMBAM starts.
    • file Model: Loads pre-tabulated opportunity counts already indexed to network vertices (or edges), avoiding repeated API downloads across multiple runs.
    • combined Model: Merges multiple opportunity models together—for example, combining Overture Maps POIs (food, retail, healthcare, services, entertainment) with Census LODES employment (jobs).

2. Setup

Pre-Computing Opportunities to Disk (bambam_util import-opportunities)

While the default bambam.toml uses an api model to fetch LODES data at runtime, large studies typically pre-import both Overture Maps POIs and LODES employment into vertex-indexed file tables so subsequent runs start immediately.

First, define an Overture Maps opportunity source config (e.g., denver_buf/opps-omf/opps-import.toml):

[plugin.output_plugins.model.opportunity_source]
type = "overture"
release_version = "Latest"
extent = { type = "wkt_file", path = "query/denver_470_buffer.txt" }
collector_config = { "obj_store_type" = "s3" }

[plugin.output_plugins.model.opportunity_source.places_activity_mapping]
food = ["restaurant", "bar"]
healthcare = ["health_care"]
entertainment = ["sports_and_recreation", "arts_and_entertainment"]
retail = ["shopping"]
services = ["education", "financial_service", "animal_or_pet_service", "home_service"]

[plugin.output_plugins.model.opportunity_source.buildings_activity_mapping]
food = []
healthcare = ["medical"]
entertainment = ["entertainment", "civic"]
retail = ["commercial"]
services = ["education", "religion"]

And a LODES opportunity source config for jobs (e.g., denver_buf/opps-lodes/run-opps.toml):

type = "lodes"
study_region = { type = "national" }
data_granularity = "census_tract"
edition = "LODES8"
job_type = "JT00"
segment = "S000"
year = 2024
fallback = { TryPreviousYears = 5 }

[activity_mapping]
C000 = ["jobs"]

Run bambam_util import-opportunities for each source to spatially attach opportunities to denver_buf/vertices-compass.csv.gz:

# 1. Import Overture Maps Places & Buildings
./rust/target/release/bambam_util import-opportunities \
  --source-config denver_buf/opps-omf/opps-import.toml \
  --impute-graph \
  --vertices-file denver_buf/vertices-compass.csv.gz \
  --output-directory denver_buf/opps-omf \
  --namespace output-plugins

# 2. Import LODES Employment
./rust/target/release/bambam_util import-opportunities \
  --source-config denver_buf/opps-lodes/run-opps.toml \
  --impute-graph \
  --vertices-file denver_buf/vertices-compass.csv.gz \
  --output-directory denver_buf/opps-lodes \
  --namespace output-plugins

(Note: For custom CSV datasets, you can also use ./rust/target/release/bambam_util opps-long or opps-wide to snap point or WKT rows to vertices-compass.csv.gz.)

Modifying bambam.toml

Each import-opportunities run writes opportunities.csv.gz and an opportunity.toml snippet containing the pre-computed opportunity_totals and file model block. Replace the [[plugin.output_plugins]] type = "opportunity" section in denver_buf/bambam.toml with a combined model referencing both files:

[[plugin.output_plugins]]
type = "opportunity"

[plugin.output_plugins.opportunity_totals]
entertainment = 8625.0
food = 6884.0
healthcare = 9446.0
retail = 19279.0
services = 21608.0
jobs = 152629402.0

[plugin.output_plugins.model]
type = "combined"

[[plugin.output_plugins.model.models]]
type = "file"
opportunity_input_file = "opps-omf/opportunities.csv.gz"
activity_column_names = ["entertainment", "food", "healthcare", "retail", "services"]
table_orientation = "destination_vertex_oriented"

[[plugin.output_plugins.model.models]]
type = "file"
opportunity_input_file = "opps-lodes/opportunities.csv.gz"
activity_column_names = ["jobs"]
table_orientation = "destination_vertex_oriented"

Running BAMBAM

cd denver_buf

../rust/target/release/bambam \
  --config-file bambam.toml \
  --query-file ../query/denver_extent.json

3. What Happens

  1. Spatial Disaggregation & Vertex Assignment (import-opportunities):
    • Point opportunities (such as Overture Places) are snapped to the nearest road network vertex within a proximity tolerance (200 meters by default).
    • Polygonal opportunities (such as Census LODES tracts/blocks or Overture Building footprints) are apportioned evenly across all road network vertices that fall inside the polygon (or snapped to the nearest vertex to the polygon centroid if no vertices lie strictly inside).
    • The resulting opportunities.csv.gz table has one row per vertex ID in vertices-compass.csv.gz, storing the exact count of each activity category at that vertex (destination_vertex_oriented).
  2. Fast Tabular Lookup During BAMBAM Execution:
    • When bambam starts, the combined opportunity output plugin loads both opps-omf/opportunities.csv.gz and opps-lodes/opportunities.csv.gz into memory and merges their activity columns.
    • As each grid cell’s shortest-path tree completes, BAMBAM groups reached destination vertices into the 10-, 20-, 30-, and 40-minute travel-time bins and sums the vertex opportunity vectors in \(O(1)\) lookup time per reached vertex.
    • Study-wide opportunity_totals are written alongside the bin-level counts (opps_<activity>_10..40) in result.csv and result.json.

Post-Processing Opportunities with the Eval Plugin

1. Overview

Raw cumulative opportunity counts (e.g., “12,400 retail opportunities within 20 minutes by bike”) are useful on their own, but many transportation planning workflows combine those raw counts into composite accessibility indices—such as the Mobility Energy Productivity (MEP) metric.

Rather than requiring external post-processing scripts to compute derived metrics on massive output files, BAMBAM can use RouteE Compass’s eval output plugin (type = "eval") to perform custom mathematical expressions directly on each output row in memory before writing result.csv and result.json.

For example, in a MEP calculation, raw cumulative opportunity counts \(O_{i,j,k,t}\) (at origin \(i\), activity type \(j\), mode \(k\), and travel-time bin \(t \in \{10, 20, 30, 40\}\) minutes) are:

  1. Normalized and weighted by regional activity totals \(N_j\), a reference scale \(N_{\ast}\), and relative trip-purpose frequencies \(f_j / \sum f\): \[\tilde{O}_{i,j,k,t} = O_{i,j,k,t} \cdot \frac{N_{\ast}}{N_j} \cdot \frac{f_j}{\sum_a f_a}\]
  2. Weighted by modal impedance (decaying with travel time \(t\), modal energy intensity \(e_k\), and modal monetary cost \(c_k\) using negative parameters \(\alpha, \beta, \sigma\)): \[M_{k,t} = \exp(\alpha e_k + \beta t + \sigma c_k)\]
  3. Summed across incremental travel-time shells to produce per-activity and overall accessibility scores: \[\text{Score}_{i,k} = \tilde{O}_{i,k,10} M_{k,10} + (\tilde{O}_{i,k,20} - \tilde{O}_{i,k,10}) M_{k,20} + (\tilde{O}_{i,k,30} - \tilde{O}_{i,k,20}) M_{k,30} + (\tilde{O}_{i,k,40} - \tilde{O}_{i,k,30}) M_{k,40}\]

All of this arithmetic can be expressed declaratively in bambam.toml using the eval output plugin.


2. Setup

1. Inject Model Parameters (input_plugins)

In your BAMBAM configuration file (see denver_buf/bambam_mep.toml for a full working example), inject any constants needed by your equations—such as activity frequencies (mep_activity_frequency), modal decay weights (mep_modal_weight), and per-mode energy/cost intensities (intensity inside trip_modes):

[[plugin.input_plugins]]
type = "inject"
key = "mep_activity_frequency"
format = "key_value"
write_mode = "overwrite"
[plugin.input_plugins.value]
retail = 1.5
jobs = 16.6
food = 6.7
entertainment = 19.5
healthcare = 3.1
services = 8.4

[[plugin.input_plugins]]
type = "inject"
key = "mep_modal_weight"
format = "key_value"
write_mode = "overwrite"
[plugin.input_plugins.value]
alpha = -0.5
beta = -0.08
sigma = -0.5

And attach intensity = { energy = ..., cost = ... } to each mode under [[plugin.input_plugins]] (type = "trip_modes"):

[plugin.input_plugins.modes.walk]
intensity = { energy = 0.0, cost = 0.0 }
constraints = [{ type = "allowed_modes", values = ["walk"] }]

[plugin.input_plugins.modes.drive]
intensity = { energy = 0.9, cost = 0.48 }
constraints = [
    { type = "mode_leg_distance_limit", mode = "walk", leg = "first", max = 0.5, unit = "kilometers" },
    { type = "exact_sequences", values = [["drive"], ["walk", "drive"]] },
]

2. Add the eval Output Plugin After opportunity

Place [[plugin.output_plugins]] with type = "eval" after the opportunity output plugin. Each [[plugin.output_plugins.expressions]] entry binds variables from the JSON result row using JSONPath selectors ($.request..., $.opportunity_totals..., $.aggregate_opportunities['10']...), evaluates an algebraic expr, and writes the result to an output JSONPath:

[[plugin.output_plugins]]
type = "eval"
on_failure = { type = "record", path = "eval_error" }

# Sum of activity frequencies
[[plugin.output_plugins.expressions]]
inputs.F_f = "$.request.mep_activity_frequency.food"
inputs.F_e = "$.request.mep_activity_frequency.entertainment"
inputs.F_h = "$.request.mep_activity_frequency.healthcare"
inputs.F_j = "$.request.mep_activity_frequency.jobs"
inputs.F_r = "$.request.mep_activity_frequency.retail"
inputs.F_s = "$.request.mep_activity_frequency.services"
expr = "F_f + F_e + F_h + F_j + F_r + F_s"
output = "$.mep.activity_frequency_sum"

# Modal impedance factor at t = 10 minutes
[[plugin.output_plugins.expressions]]
inputs.alpha = "$.request.mep_modal_weight.alpha"
inputs.beta = "$.request.mep_modal_weight.beta"
inputs.sigma = "$.request.mep_modal_weight.sigma"
inputs.e_k = "$.request.intensity.energy"
inputs.c_k = "$.request.intensity.cost"
expr = "exp((alpha * e_k) + (beta * 10.0) + (sigma * c_k))"
output = "$.mep.mikt.exp_mi10"

# Weighted food opportunities at t = 10 minutes
[[plugin.output_plugins.expressions]]
inputs.n_star = "$.opportunity_totals.food"
inputs.n_j = "$.opportunity_totals.food"
inputs.f_j = "$.request.mep_activity_frequency.food"
inputs.f_sum = "$.mep.activity_frequency_sum"
inputs.o_ijkt = "$.aggregate_opportunities['10'].opportunities.food"
expr = "o_ijkt * (n_star / n_j) * (f_j / f_sum)"
output = "$.mep.o_ijkt.food.o_ijk10"

Subsequent expressions blocks can reference outputs written by earlier expressions (such as $.mep.o_ijkt.food.o_ijk10 and $.mep.mikt.exp_mi10) to compute the final composite scores:

[[plugin.output_plugins.expressions]]
inputs.o_ik10 = "$.mep.o_ikt.o_ik10"
inputs.o_ik20 = "$.mep.o_ikt.o_ik20"
inputs.o_ik30 = "$.mep.o_ikt.o_ik30"
inputs.o_ik40 = "$.mep.o_ikt.o_ik40"
inputs.exp_mi10 = "$.mep.mikt.exp_mi10"
inputs.exp_mi20 = "$.mep.mikt.exp_mi20"
inputs.exp_mi30 = "$.mep.mikt.exp_mi30"
inputs.exp_mi40 = "$.mep.mikt.exp_mi40"
expr = "(o_ik10 * exp_mi10) + ((o_ik20 - o_ik10) * exp_mi20) + ((o_ik30 - o_ik20) * exp_mi30) + ((o_ik40 - o_ik30) * exp_mi40)"
output = "$.mep.score.overall"

Finally, map the computed fields into result.csv under [system.response_output_policy.policies.format.mapping]:

[system.response_output_policy.policies.format.mapping]
grid_id = "request.grid_id"
mode = "request.trip_mode"
mep = "mep.score.overall"
mep_food = "mep.score.food"
mep_jobs = "mep.score.jobs"
mep_retail = "mep.score.retail"
mep_healthcare = "mep.score.healthcare"
mep_entertainment = "mep.score.entertainment"
mep_services = "mep.score.services"

3. Run BAMBAM

Run BAMBAM using the MEP-enabled configuration file (e.g., denver_buf/bambam_mep.toml):

./rust/target/release/bambam \
  --config-file denver_buf/bambam_mep.toml \
  --query-file query/denver_extent.json

3. What Happens

  1. Sequential Expression Pipeline:
    • After the bambam, isochrone, and opportunity output plugins populate $.opportunity_totals and $.aggregate_opportunities on a completed search row, the eval output plugin executes its list of expressions in order.
    • Each expression extracts numeric values from the JSON row via its inputs JSONPath queries, evaluates the mathematical formula in expr, and writes the scalar result back into the row at output (under $.mep.*).
  2. Error Handling:
    • With on_failure = { type = "record", path = "eval_error" }, any division-by-zero or missing-input error is recorded on the row under eval_error without aborting the batch study.
  3. Direct CSV Export:
    • When the output policy serializes the row, the newly computed mep and per-activity mep_<activity> scores are written directly as columns in result.csv alongside the raw opportunity counts and isochrones.