Simulation + Code
Download everything as one zip (0.8 MB).
Live mini-simulation of our corridor
A simplified version of our SUMO model that runs right here in your browser: the same four lights, real County traffic counts and turn shares, the same timing plans.
Explain this simulator
A simplified version of our SUMO model, written for this page. Same four lights, real County counts and turn shares, same timing plans and signal programs as SUMO.
Cars: drive at the speed limit, keep a safe gap (SUMO's default rule), stop at red.
Use: pick a plan, press Play. Left: whole corridor (red = stopped). Right: one intersection up close. "Custom timing" sets your own cycle and Big Bend green share. "Run the full hour instantly" simulates 5–6 PM in ~1 s and compares with SUMO.
Limits: no lane-changing tactics or vehicle types, so delays are lower than SUMO's. It ranks plans similarly (table below).
| Plan | Simulated time | ||
|---|---|---|---|
| Cars on the road | Cars waiting to enter | ||
| Delay so far (veh-h per hour) | Cars through per hour |
Full-hour runs (3 seeds each)
| plan | cycle (s) | mini-sim delay | SUMO delay |
|---|
What the real SUMO looks like
Screenshots of SUMO's own viewer running our simulated corridor at rush hour (County's current timing). Click to enlarge.





Mini-simulation vs SUMO
Every plan run through both, full rush hour (5 runs each for the mini-simulation, 10 for SUMO). Delay in vehicle-hours per hour; rank 1 = least delay.
| plan | mini-sim delay | mini-sim rank | SUMO delay | SUMO rank |
|---|---|---|---|---|
| Optimized in SUMO (Study 1) | 119 ± 3 | 2 | 170 | 1 |
| Math model's best (stand-in) | 118 ± 1 | 1 | 179 | 2 |
| SUMO's built-in tool | 139 ± 3 | 4 | 203 | 3 |
| Webster (common cycle) | 161 ± 1 | 5 | 230 | 4 |
| County's current timing (real) | 127 ± 1 | 3 | 251 | 5 |
| Equal split | 175 ± 1 | 6 | 310 | 6 |
Rank agreement (Spearman): 0.77 (1 = identical order). Both put the optimized plans first and equal split last; the mini-simulation is kinder to the County's timing and its delays are lower overall, because it leaves out lane-changing friction.
Original source files (exactly as received)
Before any processing: the County's emailed documents and the raw downloads from public websites. Everything else on this page is built from these.
From St. Louis County Transportation & Public Works (Traffic Operations), by email, November 17, 2026
The four documents exactly as received: signal timing sheets plus turning-movement counts. Byte-for-byte the email attachments.
| file (opens / downloads) | what it is | size | where it came from |
|---|---|---|---|
Big Bend Blvd & Forest Park Pkwy.pdf | Signal #051: timing sheet (Oct 21, 2026) + counts (Feb 5 / Jun 30, 2021, scanned) | 2.7 MB | email attachment |
Big Bend Blvd & Forsyth Blvd.pdf | Signal #040: timing sheet (Dec 10, 2024) + counts (Mar 3, 2017, scanned) | 2.9 MB | email attachment |
Big Bend Blvd & Wydown Blvd.pdf | Signal #063: timing sheet (Dec 10, 2024) + counts (Sep 26, 2025) | 238 KB | email attachment |
Big Bend Blvd & Clayton Rd.pdf | Signal #034: timing sheet (May 12, 2026) + counts (Jun 24-25, 2026) | 217 KB | email attachment |
Downloaded from public online sources, November 17, 2026
Exactly as saved from each service (JSON / XML as returned), with the address it came from.
| file (opens / downloads) | what it is | size | where it came from |
|---|---|---|---|
county-signals-raw.json | St. Louis County signal inventory near the corridor (Signals layer), raw JSON | 43 KB | source address |
county-count-locations-raw.json | St. Louis County traffic count stations near the corridor (latest counts), raw JSON | 39 KB | source address |
county-count-history-raw.json | St. Louis County count history for the corridor stations, raw JSON | 16 KB | source address |
stlco_traffic_counts_corridor.csv | Same County count stations, wider area, saved as CSV (converted from the service's JSON) | 7 KB | source address |
modot_aadt_2025_corridor.csv | MoDOT 2025 traffic segments near the corridor (daily traffic, lanes, speed), saved as CSV from the service | 8 KB | source address |
bigbend.osm | OpenStreetMap data for the corridor (roads, lanes, signals), raw XML (© OpenStreetMap contributors, ODbL) | 7.4 MB | source address |
t1.osm | OpenStreetMap, wider area for the map (tile 1 of 5), raw XML | 2.6 MB | source address |
t2.osm | OpenStreetMap, wider area (tile 2 of 5) | 6.6 MB | source address |
t3.osm | OpenStreetMap, wider area (tile 3 of 5) | 3.4 MB | source address |
t4.osm | OpenStreetMap, wider area (tile 4 of 5) | 7.8 MB | source address |
t5.osm | OpenStreetMap, wider area (tile 5 of 5) | 3.3 MB | source address |
Live source pages
- St. Louis County: Traffic Studies and Maps (counts map)
- St. Louis County: Traffic Signal Network
- St. Louis County public GIS data (signals, count stations)
- MoDOT traffic volume map service
- OpenStreetMap
Run everything
How the whole workflow is started, and what it needs.
run_all.shThe one command: runs every step below in order and rebuilds all results.
#!/usr/bin/env bash# Rebuild everything from config/ + data/ (the README rerun). Usage: ./run_all.sh [seeds] (default 10)# Each step only reads what earlier steps wrote; build/ is regenerated, never hand-edited.set -euo pipefailcd "$(dirname "$0")"PY=.venv/bin/pythonSEEDS="${1:-10}"if [ ! -x "$PY" ]; then python3 -m venv .venv && .venv/bin/pip install -q -r requirements.txtfiecho "== 1. measured County data: parse + verify"; $PY src/parse_county_counts.py && $PY src/parse_county_timing.py && $PY src/verify_counts.pyecho "== 2. corridor dataset"; $PY src/derive.pyecho "== 3. optimizer input"; $PY src/to_optimizer.pyecho "== 4. SUMO network"; $PY src/build_network.pyecho "== 5. SUMO demand"; $PY src/build_demand.py 2>&1 | grep -v "Reading up to"echo "== 6. timing plans"; $PY src/plans.pyecho "== 7. SUMO runs ($SEEDS seeds per plan)"; rm -rf build/runs; $PY src/run_sumo.py --seeds "$SEEDS"echo "== 8. validation"; $PY src/validate.py county-currentecho "== 9. report tables + figures"; $PY src/report_tables.py$PY src/review_page.py$PY src/sim_export.py && node sim/validate.js 5 && $PY src/site_page.py && $PY src/code_page.pyecho "done: open REVIEW.html · publish: npx wrangler@4 pages deploy build/site --project-name bigbend-signal-study --branch main"README.mdInstructions: how to rerun, how the pieces fit, how to change things.
# Big Bend corridor: data + simulation pipeline (CSE 5403 traffic-signal project)Gabriel + Diego's part: real corridor data, the SUMO simulation, plan → SUMO, Study 1, report tables.Corridor: **Big Bend Blvd, St. Louis County MO: Forest Park Pkwy (#051) → Forsyth (#040) → Wydown (#063) → Clayton Rd (#034)**,PM weekday peak (5:00–6:00 PM).## Rerun everything (one command)```./run_all.sh # 10 seeds per plan; ./run_all.sh 4 for a quick run.venv/bin/python src/study1.py --n-random 30 --budget 120 # Study 1 (≈15-20 min)```First run creates `.venv` from `requirements.txt` (SUMO 1.28 comes from the `eclipse-sumo` pip package, no separate install).Outputs: `build/results_summary.json`, `build/validation.json`, `build/report/*.md|png`, `build/study1/`.## Pipeline| step | script | reads | writes ||---|---|---|---|| 1 | `parse_county_counts.py`, `parse_county_timing.py`, `verify_counts.py` | County PDFs in `data/measured/county-timing/` | `data/measured/county-counts/*.csv`, `county_timing.json`; checks every count against the sheet's printed totals || 2 | `derive.py` | config + raw + measured | `build/corridor.json`: the canonical dataset, every number tagged measured / derived / assumed with evidence || 3 | `to_optimizer.py` | corridor.json | `build/optimizer_input.json/.csv` (Michael + Noah's input) || 4 | `build_network.py` (`build_network_gen.py`) | corridor.json | `build/sumo/net.net.xml` || 5 | `build_demand.py` | corridor.json | flows, turn ratios, routes, mid-block balancing flows || 6 | `plans.py` | corridor.json | `plans/*.json`: baselines + County current + formula optimum || 7 | `run_sumo.py` | plans | `build/runs/`, `build/results_summary.json` || 8 | `validate.py` | runs | `build/validation.json` (GEH vs counts) || 9 | `report_tables.py` | all of build/ | `build/report/` || - | `study1.py` | corridor, plans | `build/study1/`, `plans/study1-sumo-loop.json` |## How to change things (built to be updated)- **New measurement** (field count, newer County sheet): drop the PDF in `data/measured/county-timing/` (named `<id>-<name>.pdf`) or a CSV in `data/measured/county-counts/` (same columns + a `.totals.csv` for verification), rerun. Measured always wins.- **Different lights / hour / timing pattern**: `config/corridor.toml` (`order`, `[counts] design_hour`, `[timing] pattern`).- **Any assumption** (bay length, turn shares, sat flow, model parameters): `config/assumptions.toml` / `config/corridor.toml`, each with its evidence.- **Michael + Noah's formats**: input → `src/to_optimizer.py::write_theirs`; their plan files → `src/plans.py::from_their_format`. Nothing else knows their format.- **Plan format** (`plans/*.json`): `C`, per light `g_main` (Big Bend green, s) and `offset_s` (start of the Big Bend block relative to Forest Park Pkwy); side green = C − L − g_main.## Data sources (see `build/report/provenance.md` for every number)- **Measured:** St. Louis County timing sheets for all 4 signals (PM pattern 37: 120 s cycle, splits, offsets, yellow/all-red, phase sequence) and County turning-movement counts (Forsyth 3/3/2017, Forest Park Pkwy 6/30/2021, Wydown 9/26/2025, Clayton 6/24/2026). Scanned count pages (Forsyth, FPP) were transcribed by hand and verified against printed totals. MoDOT 2025 lanes/speeds; County signal inventory; OpenStreetMap approach lanes and geometry.- **Derived:** link lengths (County coordinates), effective saturation flows along the real phase sequence, lost time along the phase sequence, mid-block balancing flows (counted volume into a light minus volume propagated from the previous light).- **Assumed (sensitivity-test):** 1,800 veh/h/lane, platoon share p = 0.8, g_min, cycle range, x_max = 0.9, 90 m left bays.## Modelling choices (state these in the report)1. **Generated network** (`[network] source = "generated"`): 4 signals at real spacing, real approach lanes + left bays, posted speeds. The raw OpenStreetMap network (`source = "osm"`, still supported) jams on unsignalized merges/slip lanes outside the model's scope.2. **SUMO runs the County's real phase sequence** (`[sumo] signal_program = "nema"`), scaled to each plan: the plan sets cycle, Big Bend vs cross-street block, offsets; inside a block the protected-left and through phases keep the County's proportions, left arrows sized to measured left-turn demand (what the actuated controller does). `two_phase` reproduces the model literally.3. **Model inputs consistent with that sequence** (`[model] lost_time_basis`, `capacity_basis` = `signal_sequence`): L and s are computed along the real phase sequence. Set both to the 2-phase values to reproduce the model's original inputs.4. Right turn on red allowed (Missouri default). Mid-block balancing flows enter/leave by right turns only.5. Delay = time lost on corridor edges + time waiting to enter, during the measured hour after a 15-min warm-up.## Status- `formula-optimum-standin` is OUR implementation of the Nov 10 model (`src/formula.py`) until Michael + Noah's `signal_opt.py` is plugged in. Their results replace it.## Browser mini-simulator (Simulation + Code page)`sim/core.js` is a small simulator we wrote (Krauss car-following, County phase sequence ported from `src/nema.py`, same data andplans as SUMO); `sim/ui.js` draws it. `src/sim_export.py` writes its input (`build/site/sim/data.json`); `node sim/validate.js 5`compares every plan with SUMO (rank agreement, Spearman ≈ 0.77). SUMO screenshots: `data/screenshots/` (taken in SUMO's viewer).The page is `build/site/code.html`, generated by `src/code_page.py`; publish with the wrangler command printed by run_all.sh.requirements.txtSoftware the pipeline needs (SUMO, Python libraries), with exact versions.
eclipse-sumo==1.28.0matplotlib==3.11.2numpy==2.5.5pandas==3.1.1pillow==13.0.0pymupdf==2.1pyproj==3.8.0scipy==1.18.1sumolib==1.28.0traci==1.28.0Settings
Every choice in plain files: which lights, which hour, every assumption with its evidence.
config/corridor.tomlWhich four lights, which count stations feed each approach, lanes, design hour, timing pattern, simulation options.
# Corridor definition: WHICH lights and WHERE each input comes from.# Edit this file to change the corridor; everything in build/ regenerates from it.# Directions: Big Bend is the main road (NB = northbound, SB = southbound);# the cross street is the side road (EB, WB). Approach = traffic driving INTO the light from that direction,# e.g. NB approach = cars on the Big Bend leg SOUTH of the light, heading north.[corridor]name = "Big Bend Blvd, Forest Park Pkwy to Clayton Rd (St. Louis County, MO)"main_road = "Big Bend Boulevard"peak = "PM"order = ["051", "040", "063", "034"] # north -> south, County signal numbers# Count sources for each approach.# county:<Location_ID> = St. Louis County count station (two-way volume on that leg; peak hour volume)# modot:<road> = MoDOT 2025 directional AADT for that road (converted to peak hour in derive.py)[lights.051]name = "Forest Park Pkwy"cross_street = "Forest Park Parkway"side_class = "major"NB = "county:132" # Big Bend @ Forest Park Pkwy S (2026)SB = "county:1063" # Big Bend @ Forest Park Pkwy N (2026)EB = "county:388" # Forest Park Pkwy @ Big Bend W (2024)WB = "county:387" # Forest Park Pkwy @ Big Bend E (2026)# Lanes AT the light (approach lanes incl. turn bays), from OpenStreetMap turn:lanes tags. Overrides MoDOT segment lanes.lanes = { EB = 3, WB = 3 } # OSM: one approach left|through|through|right, the other left|(2 lanes); conservative 3 each[lights.040]name = "Forsyth"cross_street = "Forsyth Boulevard"side_class = "minor"NB = "county:1064" # Big Bend @ Forsyth S (2018)SB = "county:123" # Big Bend @ Forsyth N (2018)EB = "modot:FORSYTH BLVD"WB = "modot:FORSYTH BLVD"lanes = { EB = 3, WB = 3 } # OSM: Forsyth widens to 4 lanes near Big Bend (lanes:backward=2) -> 2 through/right + left bay at the light; MoDOT mid-block 1[lights.063]name = "Wydown"cross_street = "Wydown Boulevard"side_class = "minor"NB = "county:1062" # Big Bend @ Wydown S (2026)SB = "county:1064" # Big Bend between Forsyth and Wydown (= Forsyth S station, 2018)EB = "modot:WYDOWN BLVD"WB = "modot:WYDOWN BLVD"lanes = { EB = 2, WB = 2 } # OSM: Wydown is a divided boulevard, 2-3 lanes on approach carriageways[lights.034]name = "Clayton Rd"cross_street = "Clayton Road"side_class = "major"NB = "county:118" # Big Bend @ Clayton Rd S (2026)SB = "county:117" # Big Bend @ Clayton Rd N (2026)EB = "county:247" # Clayton Rd @ Big Bend W (2017)WB = "county:246" # Clayton Rd @ Big Bend E (2017)lanes = { EB = 4, WB = 4 } # OSM: Clayton Rd carriageways are 4 lanes at the light (left + 2 through + right); MoDOT mid-block 2-3# Stations used to measure this corridor's own peak-hour factor (peak hour / average weekday).[peak_factor]stations = [132, 1063, 123, 1064, 1062, 117, 118, 388, 387, 247, 246]# Network clean-up applied on top of OpenStreetMap (each one a known OSM gap; checked against MoDOT / street view).[network]source = "generated" # "generated" = clean corridor from corridor.json (default); "osm" = full OpenStreetMap networkbay_m = 90.0 # ASSUMED left-turn bay length (generated network); typical urban 75-100 m, not measuredrbl_speed_threshold = 0 # no "yield to the right" junctions: OSM gives unsigned residential corners equal priority[network.lanes_by_name] # streets with no OSM lane tags"North Big Bend Boulevard" = 2 # MoDOT 2025: 2 lanes per direction north of Forsyth[network.lanes_by_edge] # individual OSM splitting artifacts"103632499#0" = 4 # Clayton Rd WB stop-line stub drawn as 2 lanes after a 4-lane approach# Measured County data (data/measured/): which count hour and which timing pattern are the design case.[counts]design_hour = "17:00" # 5:00-6:00 PM: peak hour at Forsyth, Clayton Rd and Forest Park Pkwy counts; inside the PM plan window[timing]pattern = "37" # County PM weekday pattern (3:00-6:30 PM M-F) at all four lights[sumo]right_on_red = true # Missouri allows right turn on red unless signed; SUMO state "s" (stop, then go if clear)signal_program = "nema" # "nema" = County's real phase sequence scaled to each plan (needs timing sheets); "two_phase" = model's 2-phaseconfig/assumptions.tomlEvery value not measured (turn shares fallback, saturation flow, model defaults) with the reason for it.
# Every number we did NOT measure lives here, with its evidence.# tag: "derived" = computed from real data by a stated rule; "assumed" = standard/engineering value, sensitivity-tested.# A file in data/measured/ always overrides these (see derive.py).[direction_split]# Share of a two-way peak-hour count going in each direction.# Rule: use MoDOT 2025 directional AADT ratio for that road (derived); peak skew on top is assumed 0 by default.rule = "modot_directional_ratio"peak_skew = 0.0 # +0.05 would push 55/45 toward the heavier direction; sensitivity-testtag = "derived"evidence = "MoDOT 2025 directional AADT (data/raw/modot); peak-hour skew unknown, set to 0 and varied in sensitivity tests"[peak_hour_factor]# Peak-hour volume as a share of daily volume, for roads with only daily (AADT) data (Forsyth, Wydown).rule = "median of County stations on this corridor (PkHrVol / AWT)"tag = "derived"evidence = "County count stations listed in corridor.toml [peak_factor]"[peak_hour_note]text = "County 'peak hour' is the busiest hour of the count day; at a few stations that is AM (8:00). Used as the PM design hour."tag = "assumed"[turn_shares]# Share of each approach turning Left / going Through / turning Right. No turning counts exist (field session will measure).main = { L = 0.10, T = 0.80, R = 0.10 } # Big Bendside_minor = { L = 0.30, T = 0.40, R = 0.30 } # small cross streets (Forsyth, Wydown)side_major = { L = 0.12, T = 0.76, R = 0.12 } # major cross roads (Forest Park Pkwy, Clayton Rd)tag = "assumed"evidence = "Typical arterial/cross-street shares; replaced by field counts when available; sensitivity-tested"[signal]lost_time_per_phase_s = 4.0 # yellow + all-red per phaseyellow_s = 3.5all_red_s = 0.5tag_lost_time = "derived"evidence_lost_time = "ITE yellow-change formula at 30-35 mph gives ~3.5-4 s, plus all-red; 2 phases -> L = 8 s"sat_flow_per_lane_vph = 1800tag_sat_flow = "assumed"evidence_sat_flow = "Textbook value (HCM base 1900 pc/h/ln with typical urban adjustments)"lanes_main = 2 # through lanes per direction on Big Bend (MoDOT 2025 + OSM)lanes_side_default = 1 # per direction on cross streets unless MoDOT says otherwisetag_lanes = "measured"evidence_lanes = "MoDOT 2025 segment lanes field + OpenStreetMap lane tags"[model]# Michael + Noah's model parameters (notes/meeting-prep-2026-11-10.txt). Theirs to change.# lost_time_basis: "signal_sequence" = L per light is the total yellow+all-red along the County's real phase sequence# (critical ring, both blocks; ~25 s), consistent with how SUMO runs the plans; "two_phase" = one clearance per block (~12 s).lost_time_basis = "signal_sequence"# capacity_basis: "signal_sequence" = each approach's saturation flow s handed to the model is an EFFECTIVE value# q / Y_block, where Y_block is the critical flow ratio of that block along the real phase sequence (left arrow + opposing# through, worst ring; lefts on a 1-lane bay, through+right on the through lanes). "lanes" = lanes x sat flow per lane.capacity_basis = "signal_sequence"p_platoon = 0.8g_min_s = 10.0C_min_s = 60.0C_max_s = 150.0x_max = 0.9tag = "assumed"evidence = "Model defaults from the Nov 10 meeting prep"[speeds]# Posted speed limits (MoDOT 2025): 30 mph north of Forsyth, 35 mph south.north_of_forsyth_mph = 30south_of_forsyth_mph = 35tag = "measured"evidence = "MoDOT 2025 speed_limit field"[current_timing]# No public data. Placeholder for the "current timing" baseline until stopwatch/County numbers arrive.C_s = 120.0main_share = 0.65 # share of (C - L) given to Big Bendoffsets = "zero" # unknowntag = "assumed"evidence = "Placeholder only: typical suburban arterial cycle. Replace with field stopwatch or County timing sheets."Step 1 · Read and check the County data
Turns the County documents into data tables and checks every number.
src/parse_county_counts.pyReads the hourly turning counts from the County count sheets (text-based sheets).
"""Parse the text-based County turning-movement count pages (hourly summary page) into data/measured/county-counts/.Source sheets (text layer): Clayton Rd (034, page 8) and Wydown (063, page 8): rows of HH:MM AM|PM then 4 approaches (From North, East, South, West) x [Right, Thru, Left, Peds, App.Total] then Int.Totalfollowed by a 'Grand Total' row. Writes <id>-<name>-<date>.csv plus .totals.csv (printed totals) for verify_counts.py.Scanned sheets (Forsyth, Forest Park Pkwy) are transcribed by hand into the same format."""import re, pathlib, datetimeimport pymupdfROOT = pathlib.Path(__file__).resolve().parents[1]SRC, OUT = ROOT/"data/measured/county-timing", ROOT/"data/measured/county-counts"SHEETS = [("034-clayton-rd.pdf", 8, "034-clayton-rd"), ("063-wydown.pdf", 8, "063-wydown")]APPROACH = ["SB", "WB", "NB", "EB"] # From North, From East, From South, From Westdef parse(pdf, page): text = pymupdf.open(SRC/pdf)[page-1].get_text() date = re.search(r"Start Date\s*:\s*(\d+/\d+/\d+)", text).group(1) tok = text.split() i = tok.index("Int.") + 2 rows, totals = [], None while i < len(tok): if re.fullmatch(r"\d\d:\d\d", tok[i]) and tok[i+1] in ("AM", "PM"): h, m = map(int, tok[i].split(":")); h = h % 12 + (12 if tok[i+1] == "PM" else 0) nums = list(map(int, tok[i+2:i+23])); rows.append((f"{h:02d}:{m:02d}", nums)); i += 23 elif tok[i] == "Grand" and tok[i+1] == "Total": totals = list(map(int, tok[i+2:i+23])); break else: i += 1 return date, rows, totalsdef main(): OUT.mkdir(parents=True, exist_ok=True) for pdf, page, stem in SHEETS: date, rows, totals = parse(pdf, page) iso = datetime.datetime.strptime(date, "%m/%d/%Y").date().isoformat() f = OUT/f"{stem}-{iso}.csv" with open(f, "w") as o: o.write(f"# St. Louis County turning-movement count, {date}, hourly. Parsed from the text layer of {pdf} page {page} " f"by parse_county_counts.py.\n# approach: SB = Big Bend from North, WB = from East, NB = Big Bend from South, EB = from West\n") o.write("hour,approach,L,T,R,peds,app_total\n") for k, a in enumerate(APPROACH): for hour, n in rows: R, T, L, P, A = n[5*k:5*k+5] o.write(f"{hour},{a},{L},{T},{R},{P},{A}\n") with open(f.with_name(f.stem+".totals.csv"), "w") as o: o.write("# printed Grand Total row and hourly intersection totals\nkind,key,L,T,R,peds,app_total\n") for k, a in enumerate(APPROACH): R, T, L, P, A = totals[5*k:5*k+5] o.write(f"grand,{a},{L},{T},{R},{P},{A}\n") for hour, n in rows: o.write(f"int,{hour},,,,,{n[20]}\n") o.write(f"int,grand,,,,,{totals[20]}\n") print(f"{f.name}: {len(rows)} hours")if __name__ == "__main__": main()src/parse_county_timing.pyReads the timing sheets: phases, yellow/all-red, cycle, splits, offsets for every pattern.
"""Parse the County signal timing sheets -> data/measured/county_timing.json.From each sheet (text layer of data/measured/county-timing/<id>-*.pdf): - per phase 1..8: movement description, yellow, all-red (page 1-2) - schedule lines ("Pattern N on ...") and every coordination pattern: cycle, 16 split times, offset (pages 3-4)The design pattern is chosen in config/corridor.toml [timing] (PM weekday = Pattern 37 at all four lights)."""import re, json, pathlibimport pymupdfROOT = pathlib.Path(__file__).resolve().parents[1]SRC = ROOT/"data/measured/county-timing"def parse(pdf): doc = pymupdf.open(pdf) text = "\n".join(p.get_text() for p in doc) flat = " ".join(text.split()) date = re.search(r"#\d{3}\s+([A-Z][a-z]+ \d+, \d{4})", flat).group(1) phases = {} for m in re.finditer(r"PHASE (\d) \(([^)]*)\)(.*?)(?=PHASE \d \(|----|Emergency|First Phases|$)", flat): n, rec, body = int(m.group(1)), m.group(2), m.group(3) y = re.search(r"Yellow ([\d.]+)", body); ar = re.search(r"All Red ([\d.]+)", body) mn = re.search(r"Minimum ([\d.]+)", body); mx = re.search(r"Max I ([\d.]+)", body) desc = re.sub(r"\s*(SECONDS|Minimum.*)$", "", body.strip()).strip() if n not in phases and y: phases[n] = dict(movement=desc, recall=rec, yellow=float(y.group(1)), all_red=float(ar.group(1)) if ar else None, min_green=float(mn.group(1)) if mn else None, max_green=float(mx.group(1)) if mx else None) schedule = re.findall(r"(Pattern \d+ on [^P]*?\((?:M-F|Everyday|Sat & Sun)\))", flat) coord = re.search(r"First Phases Green: Phases (\d) & (\d)", flat) patterns = {} for m in re.finditer(r"Cycle Length\.+: (\d+) \[PATTERN (\d+)\].*?Time \.: ((?:\d+ ){16}).*?R4L ((?:\d+ ){11})", flat): C, pid, times, tail = int(m.group(1)), m.group(2), list(map(int, m.group(3).split())), list(map(int, m.group(4).split())) patterns[pid] = dict(cycle=C, splits={i+1: t for i, t in enumerate(times) if t}, offset=tail[6]) return dict(date=date, phases=phases, schedule=schedule, patterns=patterns, coordinated_phases=[int(coord.group(1)), int(coord.group(2))] if coord else None)def main(): out = {} for f in sorted(SRC.glob("*.pdf")): lid = f.name[:3] out[lid] = dict(file=f.name, **parse(f)) p = out[lid] print(f"{lid} ({p['date']}): phases {sorted(p['phases'])}, coord {p['coordinated_phases']}, patterns " + ", ".join(f"{k}: C={v['cycle']} off={v['offset']}" for k, v in p["patterns"].items())) json.dump(out, open(ROOT/"data/measured/county_timing.json", "w"), indent=1)if __name__ == "__main__": main()src/verify_counts.pyRe-adds every count row and column and compares with the totals printed on the sheets.
"""Check every count file in data/measured/county-counts/ against the totals printed on the County sheet.For each <name>.csv with a matching <name>.totals.csv: - each row: L + T + R + peds == app_total - each approach: column sums == printed grand totals - each hour: sum of app_totals == printed intersection total; and the grand intersection totalAny mismatch = a transcription error to fix before the data is used. Exit code 1 if anything fails."""import csv, pathlib, sys, collectionsDIR = pathlib.Path(__file__).resolve().parents[1]/"data/measured/county-counts"def rows(p): return [r for r in csv.DictReader(l for l in open(p) if not l.startswith("#"))]def main(): bad = 0 for f in sorted(DIR.glob("*.csv")): if f.name.endswith(".totals.csv"): continue tf = f.with_name(f.stem+".totals.csv") R = rows(f); errs = [] for r in R: s = sum(int(r[k]) for k in ("L", "T", "R", "peds")) if s != int(r["app_total"]): errs.append(f"row {r['hour']} {r['approach']}: L+T+R+peds={s} != {r['app_total']}") if tf.exists(): T = rows(tf); col = collections.defaultdict(lambda: collections.Counter()); hr = collections.Counter() for r in R: for k in ("L", "T", "R", "peds", "app_total"): col[r["approach"]][k] += int(r[k]) hr[r["hour"]] += int(r["app_total"]) for t in T: if t["kind"] == "grand": for k in ("L", "T", "R", "peds", "app_total"): if col[t["key"]][k] != int(t[k]): errs.append(f"grand {t['key']} {k}: sum {col[t['key']][k]} != printed {t[k]}") elif t["kind"] == "int": got = sum(hr.values()) if t["key"] == "grand" else hr[t["key"]] if got != int(t["app_total"]): errs.append(f"intersection total {t['key']}: sum {got} != printed {t['app_total']}") status = "OK" if not errs else f"{len(errs)} ERRORS" print(f"{f.name}: {len(R)} rows, {status}") for e in errs: print(" ", e) bad += len(errs) sys.exit(1 if bad else 0)if __name__ == "__main__": main()Step 2 · Build the master data file
One file with every number, each labelled measured / derived / assumed.
src/derive.pyCombines County counts and timing, MoDOT and map data into corridor.json; computes lost time and capacity.
"""raw data + config + measured overrides -> build/corridor.json (the canonical corridor dataset).Every number carries: source (measured | derived | assumed), evidence (why), ref (where from).Measured files in data/measured/ always win over derived/assumed values.Measured override files (all optional, CSV with header): data/measured/approach_volumes.csv : light_id,approach,q_vph,L,T,R,note (L/T/R shares optional)"""import csv, json, math, statistics, tomllib, datetime, pathlib, sysROOT = pathlib.Path(__file__).resolve().parents[1]RAW, MEAS, BUILD, CFG = ROOT/"data/raw", ROOT/"data/measured", ROOT/"build", ROOT/"config"DIRS = ["NB", "SB", "EB", "WB"]SHIFT = {"NB": (-0.0012, 0), "SB": (0.0012, 0), "EB": (0, -0.0015), "WB": (0, 0.0015)} # point on the approach legdef load_toml(name): with open(CFG/name, "rb") as f: return tomllib.load(f)def haversine(a, b): R = 6371000.0 la1, lo1, la2, lo2 = map(math.radians, (a[0], a[1], b[0], b[1])) return 2*R*math.asin(math.sqrt(math.sin((la2-la1)/2)**2 + math.cos(la1)*math.cos(la2)*math.sin((lo2-lo1)/2)**2))def county_stations(): feats = json.load(open(RAW/"county/county-count-locations-raw.json"))["features"] hist = json.load(open(RAW/"county/county-count-history-raw.json"))["features"] st = {} for f in feats: a = f["attributes"] st[int(a["Location_ID"])] = dict(id=int(a["Location_ID"]), on=a["On_Street"], at=a["At_Street"], side=a["Direction_From"], year=a["Most_Recent_Year"], awt=a["Most_Recent_AWT"], pk=a["PkHrVol"], pk_time=f'{a["PkHrTime"]} {a["PkHrAMPM"]}', lat=f["geometry"]["y"], lon=f["geometry"]["x"]) return stdef modot_rows(): return list(csv.DictReader(open(RAW/"modot/modot_aadt_2025_corridor.csv")))def modot_dir_ratio(rows, road, pt, d): """Share of daily traffic going in direction d (NB/SB/EB/WB) on `road` near point pt, from MoDOT directional AADT.""" inv = {"NB": "E", "SB": "W", "EB": "E", "WB": "W"}[d] other = {"E": "W", "W": "E"}[inv] def nearest(dirn): cand = [r for r in rows if road in r["road"] and r["inv_dir"] == dirn] def dist(r): mid = ((float(r["start_lat"])+float(r["end_lat"]))/2, (float(r["start_lon"])+float(r["end_lon"]))/2) return haversine(pt, mid) return min(cand, key=dist) a, b = nearest(inv), nearest(other) return float(a["dir_aadt"])/(float(a["dir_aadt"])+float(b["dir_aadt"])), a, bdef county_counts(lid, hour): """Measured County turning-movement count for one light, summed over [hour, hour+1h). None if no file.""" files = sorted((MEAS/"county-counts").glob(f"{lid}-*.csv")) files = [f for f in files if not f.name.endswith(".totals.csv")] if not files: return None f = files[-1]; h0 = int(hour[:2])*60+int(hour[3:]) agg = {} for r in csv.DictReader(l for l in open(f) if not l.startswith("#")): hh, mm = map(int, r["hour"].split(":")); t = hh*60+mm if h0 <= t < h0+60: a = agg.setdefault(r["approach"], dict(L=0, T=0, R=0)) for k in ("L", "T", "R"): a[k] += int(r[k]) return dict(file=f.name, date=f.stem.split("-", 3)[-1] if f.stem.count("-") >= 3 else "", approaches=agg)def county_timing(lid, pattern, basis="signal_sequence"): """Measured County timing for one light, reduced to the model's two-phase form. None if no sheet.""" jf = MEAS/"county_timing.json" if not jf.exists(): return None T = json.load(open(jf)).get(lid) if not T or pattern not in T["patterns"]: return None P = T["patterns"][pattern]; ph = {int(k): v for k, v in T["phases"].items()}; sp = {int(k): v for k, v in P["splits"].items()} main = [n for n in sp if "Big Bend" in ph.get(n, {}).get("movement", "")] side = [n for n in sp if n not in main] ring = lambda ns, r: [n for n in ns if (n <= 4) == (r == 1)] block = lambda ns: max(sum(sp[n] for n in ring(ns, 1)), sum(sp[n] for n in ring(ns, 2))) thru = lambda ns: [n for n in ns if "LT" not in ph[n]["movement"]] or ns m_t, s_t = thru(main), thru(side) ya = lambda n: ph[n]["yellow"] + (ph[n]["all_red"] or 0) nm, ns = max(m_t, key=ya), max(s_t, key=ya) if basis == "signal_sequence": # every phase in the block clears; critical ring = the larger total Lm = max(sum(ya(n) for n in ring(main, r)) for r in (1, 2)) Ls = max(sum(ya(n) for n in ring(side, r)) for r in (1, 2)) else: Lm, Ls = ya(nm), ya(ns) lead_left = sum(sp[n] for n in main if "LT" in ph[n]["movement"]) / max(1, len({n <= 4 for n in main if "LT" in ph[n]["movement"]})) return dict(source="measured", sheet=T["file"], sheet_date=T["date"], pattern=pattern, C_s=P["cycle"], offset_county_s=P["offset"], splits=sp, main_phases=main, side_phases=side, main_block_s=block(main), side_block_s=block(side), clearance_main_s=Lm, clearance_side_s=Ls, L_s=round(Lm+Ls, 2), yellow_main_s=ph[nm]["yellow"], all_red_main_s=ph[nm]["all_red"] or 0.0, yellow_side_s=ph[ns]["yellow"], all_red_side_s=ph[ns]["all_red"] or 0.0, g_main_s=round(block(main)-Lm, 2), lead_left_s=round(lead_left, 2), main_start_s=round((P["offset"]-lead_left) % P["cycle"], 2), lost_time_basis=basis, note=f"2-phase reduction ({basis}): main green = Big Bend block minus its clearances; " "main start = County offset (start of Big Bend through green) minus the leading protected-left split")def main(): cor, asm = load_toml("corridor.toml"), load_toml("assumptions.toml") st, mrows = county_stations(), modot_rows() sig = {r["signal_id"]: r for r in csv.DictReader(open(RAW/"county/county-signals.csv"))} # corridor's own peak-hour factor ks = [st[i]["pk"]/st[i]["awt"] for i in cor["peak_factor"]["stations"] if st.get(i) and st[i]["awt"]] K = statistics.median(ks) measured = {} mfile = MEAS/"approach_volumes.csv" if mfile.exists(): for r in csv.DictReader(open(mfile)): measured[(r["light_id"], r["approach"])] = r sa, ts = asm["signal"], asm["turn_shares"] hour = cor.get("counts", {}).get("design_hour", "17:00"); pattern = cor.get("timing", {}).get("pattern", "37") counts_by_light = {lid: county_counts(lid, hour) for lid in cor["corridor"]["order"]} lights = [] for lid in cor["corridor"]["order"]: c = cor["lights"][lid] s = sig[lid] pos = (float(s["lat"]), float(s["lon"])) apps = {} for d in DIRS: pt = (pos[0]+SHIFT[d][0], pos[1]+SHIFT[d][1]) spec = c[d] main = d in ("NB", "SB") road = "BIG BEND" if main else c["cross_street"].upper().replace("BOULEVARD", "BLVD").replace("PARKWAY", "PKWY").replace("ROAD", "RD") ratio, ra, rb = modot_dir_ratio(mrows, road, pt, d) ratio = min(max(ratio + asm["direction_split"]["peak_skew"], 0.0), 1.0) if spec.startswith("county:"): sid = int(spec.split(":")[1]); x = st[sid] q = x["pk"]*ratio q_src, q_ev = "derived", (f'County station {sid} ({x["on"]} @ {x["at"]} {x["side"]}, {x["year"]}): peak hour {x["pk"]} veh/h two-way ' f'at {x["pk_time"]} x MoDOT direction share {ratio:.3f}') q_ref = f"county:{sid}" else: q = float(ra["dir_aadt"])*K q_src, q_ev = "derived", (f'MoDOT 2025 {ra["road"]} dir AADT {ra["dir_aadt"]} ({ra["seg_desc"]}) x corridor peak-hour factor {K:.3f}') q_ref = f'modot:{ra["road"]}:{ra["seg_desc"]}:{ra["inv_dir"]}' # lanes per direction from the MoDOT segment for this approach (measured); config default if blank lanes = int(float(ra["lanes"])) if ra.get("lanes") else (sa["lanes_main"] if main else sa["lanes_side_default"]) lanes_src = "measured (MoDOT segment lanes)" if d in c.get("lanes", {}): lanes, lanes_src = int(c["lanes"][d]), "measured (OpenStreetMap approach lanes, config override)" shares = dict(ts["main"] if main else ts["side_" + c.get("side_class", "minor")]); sh_src, sh_ev = "assumed", asm["turn_shares"]["evidence"] cc = counts_by_light.get(lid) if cc and d in cc["approaches"]: mv = cc["approaches"][d]; tot = mv["L"]+mv["T"]+mv["R"] q, q_src, q_ref = float(tot), "measured", f"county-counts/{cc['file']}" q_ev = f"St. Louis County turning-movement count {cc['file']}, {hour}-{int(hour[:2])+1:02d}:{hour[3:]} (L {mv['L']}, T {mv['T']}, R {mv['R']})" if tot: shares = {k: round(mv[k]/tot, 4) for k in ("L", "T", "R")}; sh_src, sh_ev = "measured", q_ev m = measured.get((lid, d)) if m: q, q_src, q_ev, q_ref = float(m["q_vph"]), "measured", m.get("note", "field count"), str(mfile.name) if m.get("L"): shares = {k: float(m[k]) for k in ("L", "T", "R")}; sh_src, sh_ev = "measured", m.get("note", "field count") apps[d] = dict(q_vph=round(q, 1), q_source=q_src, q_evidence=q_ev, q_ref=q_ref, lanes=lanes, lanes_source=lanes_src, s_vph=lanes*sa["sat_flow_per_lane_vph"], s_source=sa["tag_sat_flow"], turn_share=shares, turn_source=sh_src, turn_evidence=sh_ev) lights.append(dict(id=lid, name=c["name"], cross_street=c["cross_street"], lat=pos[0], lon=pos[1], approaches=apps, timing=county_timing(lid, pattern, asm["model"].get("lost_time_basis", "two_phase")))) sp = asm["speeds"]; links = [] for a, b in zip(lights, lights[1:]): L = haversine((a["lat"], a["lon"]), (b["lat"], b["lon"])) north = a["id"] in ("051",) # FPP->Forsyth link is north of Forsyth (30 mph); others 35 mph mph = sp["north_of_forsyth_mph"] if north else sp["south_of_forsyth_mph"] v = mph*0.44704 links.append(dict(**{"from": a["id"], "to": b["id"]}, length_m=round(L, 1), length_source="derived", length_evidence="straight-line distance between County signal coordinates", speed_mps=round(v, 2), speed_source=sp["tag"], tau_s=round(L/v, 2))) mo = asm["model"] Lmeas = [l["timing"]["L_s"] for l in lights if l["timing"]] L_global = round(sum(Lmeas)/len(Lmeas), 2) if len(Lmeas) == len(lights) else 2*sa["lost_time_per_phase_s"] L_src = "measured" if len(Lmeas) == len(lights) else sa["tag_lost_time"] L_ev = ("mean of per-light yellow+all-red (main + side) from County timing sheets; per-light values in lights[].timing.L_s" if L_src == "measured" else sa["evidence_lost_time"]) params = dict(L_s=L_global, L_source=L_src, L_evidence=L_ev, p=mo["p_platoon"], g_min_s=mo["g_min_s"], C_min_s=mo["C_min_s"], C_max_s=mo["C_max_s"], x_max=mo["x_max"], model_source=mo["tag"], yellow_s=sa["yellow_s"], all_red_s=sa["all_red_s"], sat_flow_per_lane_vph=sa["sat_flow_per_lane_vph"]) counts = {"measured": 0, "derived": 0, "assumed": 0} for l in lights: for a in l["approaches"].values(): counts[a["q_source"]] += 1 out = dict(meta=dict(name=cor["corridor"]["name"], peak=cor["corridor"]["peak"], built=datetime.datetime.now().isoformat(timespec="seconds"), version=("v2" if (measured or any(counts_by_light.values()) or Lmeas) else "v1"), peak_hour_factor=round(K, 4), peak_hour_factor_evidence=f"median of {len(ks)} County stations (PkHrVol/AWT)", approach_volume_sources=counts, design_hour=hour, timing_pattern=pattern, lights_with_measured_timing=[l["id"] for l in lights if l["timing"]]), lights=lights, links=links, params=params) print(f"corridor.json {out['meta']['version']}: {len(lights)} lights, K={K:.3f}, volumes {counts}") for l in lights: print(f" {l['id']} {l['name']:16s} " + " ".join(f"{d}:{l['approaches'][d]['q_vph']:7.1f}" for d in DIRS)) # effective saturation flows along the real phase sequence (see assumptions.toml [model].capacity_basis) if asm["model"].get("capacity_basis") == "signal_sequence": import nema rawt = json.load(open(MEAS/"county_timing.json")) if (MEAS/"county_timing.json").exists() else {} spl = sa["sat_flow_per_lane_vph"] for l in lights: T = l["timing"] if not T or l["id"] not in rawt: continue A = l["approaches"]; ph = {int(k): v for k, v in rawt[l["id"]]["phases"].items()} has_lt = {a for v in ph.values() for a in __import__("re").findall(r"(NB|SB|EB|WB)\s*LT", v["movement"])} nt = lambda a: (2 if a in ("NB", "SB") else max(A[a]["lanes"]-1, 1)) mv = lambda a, k: A[a]["q_vph"]*A[a]["turn_share"][k] def y_phase(n): prot, perm = nema._moves(ph[n]["movement"], has_lt); ys = [0.0] for a, ms in prot.items(): if ms == {"R"}: continue if ms == {"L"}: ys.append(mv(a, "L")/spl) elif "L" in ms: ys.append(A[a]["q_vph"]/(spl*(nt(a)+1))) else: ys.append((mv(a, "T")+mv(a, "R"))/(spl*nt(a))) return max(ys) sp = {int(k): v for k, v in T["splits"].items()} for block, dirs in ((T["main_phases"], ("NB", "SB")), ([n for n in sp if n not in T["main_phases"]], ("EB", "WB"))): Y = max(sum(y_phase(n) for n in block if (n <= 4) == (r == 1)) for r in (1, 2)) for d in dirs: A[d]["s_lanes_vph"] = A[d]["s_vph"] A[d]["s_vph"] = round(A[d]["q_vph"]/Y, 1) if Y > 0 else A[d]["s_vph"] A[d]["s_source"] = "derived" A[d]["s_evidence"] = (f"effective: q / Y_block, Y_block = {Y:.3f} = critical flow ratio of this block along the County " f"phase sequence (measured volumes, lanes; {spl} veh/h/lane)") # two-phase feasibility: sum over phases of max flow ratio y = q/s must leave room for lost time at C_max and x_max Lt, xm, Cmax = params["L_s"], params["x_max"], params["C_max_s"] for l in lights: A = l["approaches"] y_main = max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("NB", "SB")); y_side = max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("EB", "WB")) need = (y_main + y_side)/xm ok = need < 1 - Lt/Cmax print(f" feasibility {l['id']}: y_main={y_main:.2f} y_side={y_side:.2f} need {need:.2f} of cycle (< {1-Lt/Cmax:.2f}) {'OK' if ok else 'OVER CAPACITY'}") for k in links: print(f" link {k['from']}->{k['to']}: {k['length_m']} m, {k['speed_mps']} m/s, tau {k['tau_s']} s") _write(out)def _write(out): BUILD.mkdir(exist_ok=True) json.dump(out, open(BUILD/"corridor.json", "w"), indent=1)if __name__ == "__main__": sys.exit(main())Step 3 · Hand-off to the math team
The data file the optimizer reads.
src/to_optimizer.pyWrites the optimizer input (volumes, capacities, travel times, parameters). Only file that knows their input format.
"""corridor.json -> Michael + Noah's optimizer input.THE ONLY FILE that knows their input format. Their format hasn't arrived, so this writes our proposed template: build/optimizer_input.json : lights (ordered N->S) with q (veh/h) and s (veh/h) per approach, links with tau (s), params build/optimizer_input.csv : same per-approach numbers as a flat table, with a `source` column (measured/derived/assumed)When their format arrives, change `write_theirs()` only."""import sys, json, csv, pathlibsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, corridordef template(cor): return dict( about="Big Bend Blvd corridor, PM peak. Main road = Big Bend (NB/SB); side = cross street (EB/WB). Units: veh/h, s.", dataset_version=cor["meta"]["version"], built=cor["meta"]["built"], lights=[dict(id=l["id"], name=l["name"], q={d: a["q_vph"] for d, a in l["approaches"].items()}, s={d: a["s_vph"] for d, a in l["approaches"].items()}, lanes={d: a["lanes"] for d, a in l["approaches"].items()}) for l in cor["lights"]], links=[dict(frm=k["from"], to=k["to"], length_m=k["length_m"], speed_mps=k["speed_mps"], tau_s=k["tau_s"]) for k in cor["links"]], params={k: cor["params"][k] for k in ("L_s", "p", "g_min_s", "C_min_s", "C_max_s", "x_max")}, platoon_direction="SB platoons run light i -> i+1 (north->south); NB platoons run i+1 -> i", )def write_theirs(cor): """Placeholder: convert to Michael + Noah's format once known.""" return Nonedef main(): cor = corridor() json.dump(template(cor), open(BUILD/"optimizer_input.json", "w"), indent=1) with open(BUILD/"optimizer_input.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["light_id", "light", "approach", "q_vph", "s_vph", "lanes", "q_source", "q_evidence"]) for l in cor["lights"]: for d, a in l["approaches"].items(): w.writerow([l["id"], l["name"], d, a["q_vph"], a["s_vph"], a["lanes"], a["q_source"], a["q_evidence"]]) write_theirs(cor) print("wrote build/optimizer_input.json and build/optimizer_input.csv")if __name__ == "__main__": main()Step 4 · Build the virtual street
The SUMO road network.
src/build_network.pyBuilds the network: the generated corridor (default) or the full OpenStreetMap network.
"""OpenStreetMap extract -> SUMO network (build/sumo/net.net.xml) + map of County signal id -> SUMO traffic-light id.Manual fixes (lanes, turn bays) go in config/net_patches/ as netconvert patch files, so the network rebuilds identically."""import json, subprocess, pathlib, sys, glob, tomllibimport sumolibROOT = pathlib.Path(__file__).resolve().parents[1]BIN = pathlib.Path(sys.executable).parentOUT = ROOT/"build/sumo"def main(): OUT.mkdir(parents=True, exist_ok=True) if tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}).get("source", "osm") == "generated": import build_network_gen return build_network_gen.main() net = OUT/"net.net.xml" cfg = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}) cmd = [str(BIN/"netconvert"), "--osm-files", str(ROOT/"data/raw/osm/bigbend.osm"), "-o", str(net), "--junctions.right-before-left.speed-threshold", str(cfg.get("rbl_speed_threshold", 13.89)), "--keep-edges.by-vclass", "passenger", "--remove-edges.isolated", "--osm.turn-lanes", "--geometry.remove", "--roundabouts.guess", "--ramps.guess", "--junctions.join", "--tls.guess-signals", "--tls.join", "--tls.discard-simple", "--tls.default-type", "static", "--tls.ignore-internal-junction-jam", "--output.street-names", "--no-turnarounds.tls", "--no-warnings", "--log", str(OUT/"netconvert.log")] patches = sorted(glob.glob(str(ROOT/"config/net_patches/*.edg.xml"))) for p in patches: cmd += ["--edge-files", p] subprocess.run(cmd, check=True) # patches from config: lane counts by street name (only edges with fewer lanes) and by edge id n0 = sumolib.net.readNet(str(net)) patch = {} for name, k in cfg.get("lanes_by_name", {}).items(): for e in n0.getEdges(): if e.getName() == name and e.getLaneNumber() < k: patch[e.getID()] = k patch.update(cfg.get("lanes_by_edge", {})) if patch: pf = OUT/"lane_patch.edg.xml" pf.write_text("<edges>\n" + "".join(f' <edge id="{i}" numLanes="{k}"/>\n' for i, k in patch.items()) + "</edges>\n") subprocess.run([str(BIN/"netconvert"), "-s", str(net), "-e", str(pf), "-o", str(net), "--tls.ignore-internal-junction-jam", "--no-warnings"], check=True) print(f"patched lanes on {len(patch)} edges") cor = json.load(open(ROOT/"build/corridor.json")) n = sumolib.net.readNet(str(net), withPrograms=True) tls_map = {} for l in cor["lights"]: x, y = n.convertLonLat2XY(l["lon"], l["lat"]) best = None for t in n.getTrafficLights(): nodes = {c[0].getEdge().getToNode() for c in t.getConnections()} for nd in nodes: dx, dy = nd.getCoord()[0]-x, nd.getCoord()[1]-y dist = (dx*dx+dy*dy)**0.5 if best is None or dist < best[0]: best = (dist, t.getID()) tls_map[l["id"]] = dict(tls=best[1], dist_m=round(best[0], 1), name=l["name"]) json.dump(tls_map, open(OUT/"tls_map.json", "w"), indent=1) print("network:", net) for k, v in tls_map.items(): print(f" County {k} {v['name']:16s} -> SUMO tls {v['tls']} ({v['dist_m']} m from County coordinate)")if __name__ == "__main__": main()src/build_network_gen.pyGenerates the corridor from the data: 4 signals at real spacing, real lanes, left-turn bays, speeds.
"""Generate a clean SUMO corridor network from build/corridor.json (real distances, lanes, speeds).Why: the raw OpenStreetMap network carries unsignalized merges, split carriageways and slip lanes around Forsyth andClayton Rd that jam the simulation and are outside the model's scope. This network keeps what the model is about:4 signalized intersections at their real spacing, Big Bend with 2 through lanes + a left-turn bay per approach,cross streets with their real approach lanes, posted speeds.Geometry: light positions projected from County coordinates (local metres). Each light gets cross-street legs ofSIDE_LEG_M east and west; Big Bend extends END_LEG_M north of the first light and south of the last."""import json, math, pathlib, subprocess, sysROOT = pathlib.Path(__file__).resolve().parents[1]BIN = pathlib.Path(sys.executable).parentOUT = ROOT/"build/sumo"END_LEG_M, SIDE_LEG_M, BAY_M = 600.0, 400.0, 60.0MAIN = "Big Bend Boulevard"def xy(lat, lon, lat0, lon0): return ((lon-lon0)*111320*math.cos(math.radians(lat0)), (lat-lat0)*110540)def main(): global BAY_M import tomllib BAY_M = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}).get("bay_m", BAY_M) cor = json.load(open(ROOT/"build/corridor.json")) L = cor["lights"]; lat0, lon0 = L[-1]["lat"], L[-1]["lon"] P = {l["id"]: xy(l["lat"], l["lon"], lat0, lon0) for l in L} speed = {} for k in cor["links"]: speed[(k["from"], k["to"])] = speed[(k["to"], k["from"])] = k["speed_mps"] v_end_n, v_end_s = cor["links"][0]["speed_mps"], cor["links"][-1]["speed_mps"] v_side = 13.41 # 30 mph cross streets (MoDOT: Forsyth/Wydown unposted -> 30 mph assumed; FPP 40, Clayton 35 below) side_speed = {"Forest Park Parkway": 17.88, "Clayton Road": 15.65} nodes, edges, cons, mid_cons = [], [], [], [] side_nt = {} def node(i, x, y, t="priority"): nodes.append(f' <node id="{i}" x="{x:.2f}" y="{y:.2f}" type="{t}"/>') def edge(i, a, b, lanes, v, name): edges.append(f' <edge id="{i}" from="{a}" to="{b}" numLanes="{lanes}" speed="{v:.2f}" name="{name}" priority="{3 if name == MAIN else 2}"/>') ids = [l["id"] for l in L] for l in L: x, y = P[l["id"]] node(f"J{l['id']}", x, y, "traffic_light") for d, sx in (("W", -1), ("E", 1)): node(f"{d}{l['id']}", x+sx*SIDE_LEG_M, y) node(f"{d}b{l['id']}", x+sx*BAY_M, y) # left-turn bay start on the cross street for d, sy in (("Nb", 1), ("Sb", -1)): # bay start nodes on Big Bend node(f"{d}{l['id']}", x, y+sy*BAY_M) xn, yn = P[ids[0]]; xs, ys = P[ids[-1]] node("NEND", xn, yn+END_LEG_M); node("SEND", xs, ys-END_LEG_M) mids = set() def bb_chain(a_node, b_light, v, tag): """Big Bend from a_node towards light b: plain 2-lane edge to the bay start, then a 3-lane bay edge (left bay). Between two lights the plain part is split at a mid-block access point (balancing flows, see build_demand).""" come_from_north = tag == "SB" bay = f"Nb{b_light}" if come_from_north else f"Sb{b_light}" if a_node[:2] in ("Sb", "Nb"): a = a_node[2:] north, south = (a, b_light) if come_from_north else (b_light, a) m = f"M{north}_{south}" if m not in mids: mids.add(m) (xa, ya), (xb, yb) = P[north], P[south] mx, my = (xa+xb)/2, ((ya-BAY_M)+(yb+BAY_M))/2 node(m, mx, my); node(f"DW{north}_{south}", mx-80, my); node(f"DE{north}_{south}", mx+80, my) nm = f"Access {north}-{south}" edge(f"WIN_{north}_{south}", f"DW{north}_{south}", m, 1, 8.94, nm) edge(f"WOUT_{north}_{south}", m, f"DW{north}_{south}", 1, 8.94, nm) edge(f"EIN_{north}_{south}", f"DE{north}_{south}", m, 1, 8.94, nm) edge(f"EOUT_{north}_{south}", m, f"DE{north}_{south}", 1, 8.94, nm) edge(f"{tag}_mid_{b_light}", a_node, m, 2, v, MAIN) mid_cons.append((tag, f"{tag}_mid_{b_light}", f"{tag}_to_{b_light}", north, south)) a_node = m edge(f"{tag}_to_{b_light}", a_node, bay, 2, v, MAIN) edge(f"{tag}_bay_{b_light}", bay, f"J{b_light}", 3, v, MAIN) cons.append((f"{tag}_to_{b_light}", f"{tag}_bay_{b_light}", None)) return f"{tag}_bay_{b_light}" out_edges = {} # southbound chain prev = "NEND"; v = v_end_n for i, lid in enumerate(ids): bb_chain(prev if i == 0 else f"Sb{ids[i-1]}", lid, v if i == 0 else speed[(ids[i-1], lid)], "SB") if i+1 < len(ids): edge(f"SB_from_{lid}", f"J{lid}", f"Sb{lid}", 2, speed[(lid, ids[i+1])], MAIN) else: edge(f"SB_from_{lid}", f"J{lid}", "SEND", 2, v_end_s, MAIN) out_edges[(lid, "S")] = f"SB_from_{lid}" # northbound chain rev = ids[::-1] for i, lid in enumerate(rev): bb_chain("SEND" if i == 0 else f"Nb{rev[i-1]}", lid, v_end_s if i == 0 else speed[(rev[i-1], lid)], "NB") if i+1 < len(rev): edge(f"NB_from_{lid}", f"J{lid}", f"Nb{lid}", 2, speed[(lid, rev[i+1])], MAIN) else: edge(f"NB_from_{lid}", f"J{lid}", "NEND", 2, v_end_n, MAIN) out_edges[(lid, "N")] = f"NB_from_{lid}" # cross streets for l in L: lid, name = l["id"], l["cross_street"]; vs = side_speed.get(name, v_side) A = l["approaches"] # approach = through lanes (approach lanes minus the left lane, at least 1) + a left-turn bay at the stop line nt = {d: max(A[d]["lanes"]-1, 1) for d in ("EB", "WB")} edge(f"EB_up_{lid}", f"W{lid}", f"Wb{lid}", nt["EB"], vs, name) edge(f"EB_in_{lid}", f"Wb{lid}", f"J{lid}", nt["EB"]+1, vs, name) edge(f"WB_up_{lid}", f"E{lid}", f"Eb{lid}", nt["WB"], vs, name) edge(f"WB_in_{lid}", f"Eb{lid}", f"J{lid}", nt["WB"]+1, vs, name) edge(f"EB_out_{lid}", f"J{lid}", f"E{lid}", nt["WB"], vs, name) edge(f"WB_out_{lid}", f"J{lid}", f"W{lid}", nt["EB"], vs, name) side_nt[lid] = nt # explicit lane-to-lane connections at each light (lane 0 = rightmost) con_xml = [] def c(fe, te, fl, tl): con_xml.append(f' <connection from="{fe}" to="{te}" fromLane="{fl}" toLane="{tl}"/>') for k, (fe, te, _) in enumerate(cons): # plain -> bay: 2 lanes feed 3 (lane 1 also feeds the bay) c(fe, te, 0, 0); c(fe, te, 1, 1); c(fe, te, 1, 2) for tag, fe, te, north, south in mid_cons: # mid-block access: right turns only (no crossing conflicts) c(fe, te, 0, 0); c(fe, te, 1, 1) if tag == "SB": c(fe, f"WOUT_{north}_{south}", 0, 0); c(f"EIN_{north}_{south}", te, 0, 0) else: c(fe, f"EOUT_{north}_{south}", 0, 0); c(f"WIN_{north}_{south}", te, 0, 0) for l in L: lid = l["id"]; A = l["approaches"] # Big Bend bays: lane0 R+T, lane1 T, lane2 L sb_t, sb_r, sb_l = out_edges[(lid, "S")], f"WB_out_{lid}", f"EB_out_{lid}" nb_t, nb_r, nb_l = out_edges[(lid, "N")], f"EB_out_{lid}", f"WB_out_{lid}" for bay, t, r, lft in ((f"SB_bay_{lid}", sb_t, sb_r, sb_l), (f"NB_bay_{lid}", nb_t, nb_r, nb_l)): c(bay, t, 0, 0); c(bay, t, 1, 1); c(bay, r, 0, 0); c(bay, lft, 2, 0) # cross streets: EB in -> through EB_out, right = SB_from (south), left = NB_from (north) for side, t, r, lft in (("EB", f"EB_out_{lid}", out_edges[(lid, "S")], out_edges[(lid, "N")]), ("WB", f"WB_out_{lid}", out_edges[(lid, "N")], out_edges[(lid, "S")])): nt = side_nt[lid][side]; nout = side_nt[lid]["WB" if side == "EB" else "EB"] up, fe = f"{side}_up_{lid}", f"{side}_in_{lid}" for i in range(nt): c(up, fe, i, i) c(up, fe, nt-1, nt) # leftmost through lane also feeds the left bay c(fe, r, 0, 0) # right turn from the curb lane for i in range(nt): c(fe, t, i, min(i, nout-1)) # through lanes c(fe, lft, nt, 1) # left bay -> inner lane of Big Bend OUT.mkdir(parents=True, exist_ok=True) (OUT/"gen.nod.xml").write_text("<nodes>\n"+"\n".join(nodes)+"\n</nodes>\n") (OUT/"gen.edg.xml").write_text("<edges>\n"+"\n".join(edges)+"\n</edges>\n") (OUT/"gen.con.xml").write_text("<connections>\n"+"\n".join(con_xml)+"\n</connections>\n") net = OUT/"net.net.xml" subprocess.run([str(BIN/"netconvert"), "-n", str(OUT/"gen.nod.xml"), "-e", str(OUT/"gen.edg.xml"), "-x", str(OUT/"gen.con.xml"), "-o", str(net), "--no-turnarounds", "--tls.default-type", "static", "--no-warnings", "--offset.disable-normalization"], check=True) tls_map = {l["id"]: dict(tls=f"J{l['id']}", dist_m=0.0, name=l["name"]) for l in L} json.dump(tls_map, open(OUT/"tls_map.json", "w"), indent=1) print("generated network:", net)_LANES = {}def tout_lanes(edge_id, light): A = light["approaches"] if edge_id.startswith("EB_out"): return max(A["WB"]["lanes"], 1) if A["WB"]["lanes"] < 3 else 2 if edge_id.startswith("WB_out"): return max(A["EB"]["lanes"], 1) if A["EB"]["lanes"] < 3 else 2 return 2if __name__ == "__main__": main()src/common.pyShared helpers: file paths, loading the network, labelling each approach as NB/SB/EB/WB.
"""Shared helpers: paths, network loading, and labelling each signal approach as NB/SB (Big Bend) or EB/WB (cross street)."""import json, math, pathlib, sys, functoolsimport sumolibROOT = pathlib.Path(__file__).resolve().parents[1]BUILD = ROOT/"build"SUMO = BUILD/"sumo"BIN = pathlib.Path(sys.executable).parentdef corridor(): return json.load(open(BUILD/"corridor.json"))def tls_map(): return json.load(open(SUMO/"tls_map.json"))@functools.lru_cache(maxsize=1)def net(): return sumolib.net.readNet(str(SUMO/"net.net.xml"), withPrograms=True, withConnections=True)def same_street_pred(edge): """Upstream edge on the same street (by name), not the reverse direction; None if none.""" name = edge.getName() cands = [p for p in edge.getIncoming() if p.allows("passenger") and p.getFromNode() != edge.getToNode() and (not name or p.getName() == name)] return max(cands, key=lambda p: p.getLength()) if cands else Nonedef heading(edge, span=25.0): """Direction of travel as the edge ENTERS its end node, measured over the last `span` metres (walking back through same-street edges, so tiny OSM stub edges don't give noise). Returns unit (dx, dy).""" end = edge.getShape()[-1]; pts = list(edge.getShape()); run = edge.getLength(); cur = edge while run < span: p = same_street_pred(cur) if p is None: break pts = list(p.getShape()) + pts; run += p.getLength(); cur = p acc, start = 0.0, pts[0] for a, b in zip(reversed(pts[:-1]), reversed(pts[1:])): acc += math.hypot(b[0]-a[0], b[1]-a[1]) if acc >= span: start = a; break dx, dy = end[0]-start[0], end[1]-start[1] d = math.hypot(dx, dy) or 1.0 return dx/d, dy/dMAIN_NAME = "Big Bend"def approach_label(edge): """Main road (Big Bend, by street name) -> NB/SB by heading; any other street -> EB/WB by heading. Unnamed edges fall back to heading alone.""" dx, dy = heading(edge) name = edge.getName() or "" main = (MAIN_NAME in name) if name else abs(dy) >= abs(dx) if main: return "NB" if dy > 0 else "SB" return "EB" if dx > 0 else "WB"def tls_links(tls_id): """[(link_index, incoming_edge, outgoing_edge, approach_label, direction)] for one traffic light. direction: SUMO turn code s/l/r/t/L/R.""" t = net().getTLS(tls_id) out = [] for inl, outl, idx in t.getConnections(): e_in, e_out = inl.getEdge(), outl.getEdge() d = "s" for c in e_in.getConnections(e_out): if c.getFromLane() == inl and c.getToLane() == outl: d = c.getDirection() out.append((idx, e_in, e_out, approach_label(e_in), d)) return outStep 5 · Fill it with traffic
Virtual cars that match the real counts.
src/build_demand.pyEntry flows, measured turn shares at each light, balancing flows between lights, routes.
"""corridor.json -> SUMO demand (flows + turn ratios -> jtrrouter routes) and the set of edges we measure delay on.Entries: Big Bend SB at the northmost light, Big Bend NB at the southmost light, and every cross-street approach.Each entry starts up to ENTRY_RUN_M metres upstream (straight-ahead chain of edges) so queues have room.At each of our lights, turn shares come from corridor.json; on the corridor between lights traffic goes straight.Every edge leaving the corridor is a sink (vehicles leave the simulation there).Timing: warm-up WARMUP_S at peak rate, then MEASURE_S measured. Flows stop at WARMUP_S + MEASURE_S."""import sys, pathlib, json, subprocess, mathsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import SUMO, BIN, corridor, tls_map, net, tls_links, approach_label, heading, same_street_predWARMUP_S, MEASURE_S, ENTRY_RUN_M = 900, 3600, 300.0END_S = WARMUP_S + MEASURE_Sdef straight_successor(edge): """The outgoing edge that continues most straight ahead (passenger-allowed).""" best, hx = None, heading(edge) for e2 in edge.getOutgoing(): if not e2.allows("passenger"): continue shp = e2.getShape(); (x0, y0), (x1, y1) = shp[0], shp[1] d = math.hypot(x1-x0, y1-y0) or 1 dot = hx[0]*(x1-x0)/d + hx[1]*(y1-y0)/d if best is None or dot > best[0]: best = (dot, e2) return best[1] if best and best[0] > 0.7 else Nonedef straight_predecessor(edge): best = None for e0 in edge.getIncoming(): if not e0.allows("passenger"): continue hx = heading(e0); shp = edge.getShape(); (x0, y0), (x1, y1) = shp[0], shp[1] d = math.hypot(x1-x0, y1-y0) or 1 dot = hx[0]*(x1-x0)/d + hx[1]*(y1-y0)/d if best is None or dot > best[0]: best = (dot, e0) return best[1] if best and best[0] > 0.7 else Nonedef main(): cor, tm, n = corridor(), tls_map(), net() ids = [l["id"] for l in cor["lights"]] by_light = {lid: tls_links(tm[lid]["tls"]) for lid in ids} tls_nodes = {lid: {e_in.getToNode().getID() for _, e_in, _, _, _ in by_light[lid]} | {e_in.getFromNode().getID() for _, e_in, _, _, _ in by_light[lid] if e_in.getLength() < 30} for lid in ids} def approach_edges(lid, lab): return sorted({e_in for _, e_in, _, l, _ in by_light[lid] if l == lab}, key=lambda e: -e.getLaneNumber()) rel = {} # (from, to) -> prob measure = set() flows = [] # corridor links between lights: follow straight chain from light i outgoing to light j approach for a, b, lab in [(ids[k], ids[k+1], "SB") for k in range(len(ids)-1)] + [(ids[k+1], ids[k], "NB") for k in range(len(ids)-1)]: targets = set(approach_edges(b, lab)) starts = {e_out for _, e_in, e_out, l, d in by_light[a] if l == lab and d == "s"} for e in starts: chain, cur = [e], e while cur not in targets and len(chain) < 40: nxt = straight_successor(cur) if nxt is None: break rel[(cur.getID(), nxt.getID())] = 1.0; chain.append(nxt); cur = nxt measure.update(x.getID() for x in chain) # turn ratios at our lights + entry flows for l in cor["lights"]: lid = l["id"] for lab, A in l["approaches"].items(): edges = approach_edges(lid, lab) measure.update(e.getID() for e in edges) for e_in in edges: outs = {} for _, ei, eo, lb, d in by_light[lid]: if ei != e_in: continue k = "L" if d in ("l", "L", "t") else ("R" if d in ("r", "R") else "T") outs.setdefault(k, set()).add(eo.getID()) tot = sum(A["turn_share"][k] for k in outs) for k, es in outs.items(): for eo in es: rel[(e_in.getID(), eo)] = A["turn_share"][k]/tot/len(es) entry = (lab in ("EB", "WB")) or (lab == "SB" and lid == ids[0]) or (lab == "NB" and lid == ids[-1]) if not entry or not edges: continue edges_pos = [x for x in edges if x.getLength() > 1.0] or edges e = max(edges_pos, key=lambda x: (x.getLaneNumber(), x.getLength())); run = e.getLength(); chain = [e] while run < ENTRY_RUN_M: p = same_street_pred(chain[0]) or straight_predecessor(chain[0]) own = tls_nodes[lid] other_sig = lambda nd: nd.getType().startswith("traffic_light") and nd.getID() not in own if p is None or other_sig(p.getToNode()) or other_sig(p.getFromNode()): break rel[(p.getID(), chain[0].getID())] = 1.0; chain.insert(0, p); run += p.getLength() measure.update(x.getID() for x in chain) flows.append(dict(id=f"{lid}_{lab}", frm=chain[0].getID(), vph=A["q_vph"])) # balancing flows at the mid-block access point between consecutive lights (unsignalized side streets/driveways). # Propagate each direction analytically: out of light j = through + side-street turns into that direction; # the counted volume into the next light is the target; the difference enters (deficit) or leaves (surplus) mid-block. balancing = [] Ls = cor["lights"] for k in range(len(Ls)-1): north, south = Ls[k], Ls[k+1]; nid, sid = north["id"], south["id"] for tag, frm, to in (("SB", north, south), ("NB", south, north)): A = frm["approaches"]; sh = lambda d, m: A[d]["turn_share"][m] if tag == "SB": # leaving northern light southbound: SB through + EB right + WB left out = A["SB"]["q_vph"]*sh("SB", "T") + A["EB"]["q_vph"]*sh("EB", "R") + A["WB"]["q_vph"]*sh("WB", "L") else: # leaving southern light northbound: NB through + EB left + WB right out = A["NB"]["q_vph"]*sh("NB", "T") + A["EB"]["q_vph"]*sh("EB", "L") + A["WB"]["q_vph"]*sh("WB", "R") target = to["approaches"][tag]["q_vph"] diff = target - out mid, nxt = f"{tag}_mid_{to['id']}", f"{tag}_to_{to['id']}" if diff > 0: # extra traffic joins: right turn in (SB from east side, NB from west side) src = f"{'EIN' if tag == 'SB' else 'WIN'}_{nid}_{sid}" rel[(src, nxt)] = 1.0 flows.append(dict(id=f"bal_{tag}_{nid}_{sid}", frm=src, vph=diff)) else: # traffic leaves: right turn out (SB to west side, NB to east side) snk = f"{'WOUT' if tag == 'SB' else 'EOUT'}_{nid}_{sid}" share = min(-diff/out, 0.9) if out > 0 else 0.0 rel[(mid, nxt)] = 1.0-share; rel[(mid, snk)] = share balancing.append(dict(link=f"{nid}-{sid}", direction=tag, propagated_vph=round(out, 1), target_vph=round(target, 1), balance_vph=round(diff, 1), source="derived", evidence="difference between counted volume into the next light and volume propagated from the previous light")) # sinks: every edge leaving one of our lights that is not a corridor edge sinks = set() for lid in ids: for _, ei, eo, lb, d in by_light[lid]: if eo.getID() not in measure: sinks.add(eo.getID()) sinks.update(e.getID() for e in n.getEdges() if e.getID().startswith(("WOUT_", "EOUT_"))) SUMO.mkdir(parents=True, exist_ok=True) with open(SUMO/"turns.xml", "w") as f: f.write(f'<edgeRelations>\n <interval begin="0" end="{END_S}">\n') for (a, b), p in sorted(rel.items()): f.write(f' <edgeRelation from="{a}" to="{b}" probability="{p:.4f}"/>\n') f.write(" </interval>\n</edgeRelations>\n") with open(SUMO/"flows.xml", "w") as f: f.write('<routes>\n <vType id="car" vClass="passenger" sigma="0.5"/>\n') for fl in flows: f.write(f' <flow id="{fl["id"]}" type="car" begin="0" end="{END_S}" vehsPerHour="{fl["vph"]:.1f}" from="{fl["frm"]}" departLane="best" departSpeed="max"/>\n') f.write("</routes>\n") subprocess.run([str(BIN/"jtrrouter"), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"flows.xml"), "-t", str(SUMO/"turns.xml"), "--sink-edges", ",".join(sorted(sinks)), "-T", "0,100,0", "--max-edges-factor", "3", "--randomize-flows", "--seed", "42", "-o", str(SUMO/"routes.rou.xml"), "--no-warnings", "--ignore-errors"], check=True) json.dump(dict(measure_edges=sorted(measure), sinks=sorted(sinks), flows=flows, balancing=balancing, warmup_s=WARMUP_S, measure_s=MEASURE_S), open(SUMO/"demand.json", "w"), indent=1) print(f"demand: {len(flows)} entry flows, {len(rel)} turn relations, {len(measure)} measured edges, {len(sinks)} sinks") for fl in flows: print(f" {fl['id']:14s} {fl['vph']:7.1f} veh/h from {fl['frm']}") for b in balancing: print(f" balance {b['link']} {b['direction']}: propagated {b['propagated_vph']:7.1f} target {b['target_vph']:7.1f} -> {b['balance_vph']:+7.1f} veh/h")if __name__ == "__main__": main()Step 6 · The timing plans
Every light timing we test.
src/plans.pyPlan format and the baselines: County current, equal split, Webster, SUMO coordination, formula optimum.
"""Canonical timing-plan format + baseline generators + readers for outside formats.Plan JSON (plans/<name>.json):{ "name": str, "source": str, "C": float (common cycle, s), "lights": { "<County id>": { "g_main": float (s), "offset_s": float (s), "C": float (optional per-light cycle) } }, "L_s": float, "notes": str }g_main = Big Bend green; side green = C - L - g_main. offset_s = when Big Bend green starts, relative to the first light.The ONLY place that knows Michael + Noah's output format is `from_their_format()` below."""import json, sys, pathlib, tomllibsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import ROOT, corridorimport formulaPLANS = ROOT/"plans"def save(plan): PLANS.mkdir(exist_ok=True) json.dump(plan, open(PLANS/f"{plan['name']}.json", "w"), indent=1) return plandef load(name): return json.load(open(PLANS/f"{name}.json"))def _ys(cor): out = [] for l in cor["lights"]: A = l["approaches"] out.append((max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("NB", "SB")), max(A[d]["q_vph"]/A[d]["s_vph"] for d in ("EB", "WB")))) return outdef _L(l, cor): return formula.light_L(cor, l)def webster_cycle(L, Y, P): return min(max((1.5*L+5)/(1-Y), P["C_min_s"]), P["C_max_s"])def webster_per_light(cor): """Each light on its own Webster cycle and splits, no coordination (offsets 0).""" P = cor["params"]; L = P["L_s"]; lights = {} for l, (ym, ys) in zip(cor["lights"], _ys(cor)): Li = _L(l, cor); C = webster_cycle(Li, ym+ys, P); g = (C-Li)*ym/(ym+ys) lights[l["id"]] = dict(g_main=round(g, 2), offset_s=0.0, C=round(C, 2)) Cs = [v["C"] for v in lights.values()] return dict(name="webster-per-light", source="baseline: Webster (1958) cycle + splits per light, uncoordinated", C=max(Cs), lights=lights, L_s=L, notes="per-light cycles; offsets 0")def webster_common(cor): """Common cycle = largest Webster cycle; Webster splits; offsets 0 (input to coordination tools).""" P = cor["params"]; L = P["L_s"]; ys = _ys(cor) C = max(webster_cycle(_L(l, cor), ym+yss, P) for l, (ym, yss) in zip(cor["lights"], ys)) lights = {l["id"]: dict(g_main=round((C-_L(l, cor))*ym/(ym+yss), 2), offset_s=0.0) for l, (ym, yss) in zip(cor["lights"], ys)} return dict(name="webster-common", source="baseline: common Webster cycle, Webster splits, offsets 0", C=round(C, 2), lights=lights, L_s=L, notes="")def equal_split(cor): P = cor["params"]; L = P["L_s"]; C = webster_common(cor)["C"] lights = {l["id"]: dict(g_main=round((C-_L(l, cor))/2, 2), offset_s=0.0) for l in cor["lights"]} return dict(name="equal-split", source="baseline: equal green to main and side, common Webster cycle, offsets 0", C=C, lights=lights, L_s=L, notes="")def estimated_current(cor): a = tomllib.load(open(ROOT/"config/assumptions.toml", "rb"))["current_timing"] L = cor["params"]["L_s"]; C = a["C_s"] lights = {l["id"]: dict(g_main=round((C-L)*a["main_share"], 2), offset_s=0.0) for l in cor["lights"]} return dict(name="estimated-current", source=f"ASSUMED placeholder ({a['evidence']})", C=C, lights=lights, L_s=L, notes="replace with stopwatch or County timing sheets")def county_current(cor): """MEASURED current timing: County PM pattern (timing sheets), reduced to the model's two-phase form.""" T = [l["timing"] for l in cor["lights"]] if not all(T): return None C = T[0]["C_s"]; ref = T[0]["main_start_s"] lights = {l["id"]: dict(g_main=t["g_main_s"], offset_s=round((t["main_start_s"]-ref) % C, 2)) for l, t in zip(cor["lights"], T)} return dict(name="county-current", source=f"MEASURED: St. Louis County timing sheets, pattern {T[0]['pattern']} (PM weekday)", C=C, lights=lights, L_s=cor["params"]["L_s"], notes=T[0]["note"] + "; offsets relative to the first light")def formula_optimum(cor, starts=30): r = formula.optimize(cor, starts=starts) lights = {l["id"]: dict(g_main=round(g, 3), offset_s=round(o, 3)) for l, g, o in zip(cor["lights"], r["g_main"], r["offsets"])} return dict(name="formula-optimum-standin", source="stand-in for Michael+Noah: formula model, multistart SLSQP (formula.py)", C=round(r["C"], 3), lights=lights, L_s=cor["params"]["L_s"], notes=f"formula delay {r['total_veh_h']:.2f} veh-h/h; {r['n_success']} successful starts; distinct optima {r['distinct_optima'][:8]}")def sumo_coordinated(cor): """SUMO's built-in tlsCoordinator.py: Webster common-cycle splits + green-wave offsets computed by SUMO from the routes.""" import subprocess, os, xml.etree.ElementTree as ET from common import SUMO, BIN import plan_to_sumo base = webster_common(cor); base["name"] = "_tmp_webster"; plan_to_sumo.write(base) tools = pathlib.Path(sys.executable).parents[1]/"lib" tool = next(tools.glob("python*/site-packages/sumo/tools/tlsCoordinator.py")) out = SUMO/"plans"/"_coord.add.xml" env = dict(os.environ, SUMO_HOME=str(tool.parents[1])) subprocess.run([sys.executable, str(tool), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"routes.rou.xml"), "-a", str(SUMO/"plans"/"_tmp_webster.tls.add.xml"), "-o", str(out)], check=True, env=env, stdout=subprocess.DEVNULL) from common import tls_map rev = {v["tls"]: k for k, v in tls_map().items()} offs = {rev[e.get("id")]: float(e.get("offset")) for e in ET.parse(out).getroot().iter("tlLogic") if e.get("id") in rev} ids = [l["id"] for l in cor["lights"]]; C = base["C"]; o0 = offs[ids[0]] lights = {i: dict(g_main=base["lights"][i]["g_main"], offset_s=round((offs[i]-o0) % C, 2)) for i in ids} return dict(name="sumo-coordinated", source="baseline: SUMO tlsCoordinator.py offsets on the common Webster plan", C=C, lights=lights, L_s=base["L_s"], notes="SUMO built-in green-wave coordination")def from_their_format(path): """Adapter for Michael + Noah's plan files. FORMAT UNKNOWN YET: fill this in when their format arrives. Expected to return a plan dict in the canonical format above.""" raise NotImplementedError("Waiting for Michael + Noah's plan-file format")def formula_delay(cor, plan): """Formula-model delay for a common-cycle plan (None for per-light-cycle plans).""" if any("C" in v for v in plan["lights"].values()): return None ids = [l["id"] for l in cor["lights"]] return formula.evaluate(cor, plan["C"], [plan["lights"][i]["g_main"] for i in ids], [plan["lights"][i]["offset_s"] for i in ids])def main(): cor = corridor() from common import SUMO have_timing = all(l.get("timing") for l in cor["lights"]) makers = [equal_split, webster_per_light, webster_common, county_current if have_timing else estimated_current, formula_optimum] if have_timing and (PLANS/"estimated-current.json").exists(): (PLANS/"estimated-current.json").unlink() # superseded by measured timing if (SUMO/"routes.rou.xml").exists(): makers.append(sumo_coordinated) for mk in makers: p = save(mk(cor)) fd = formula_delay(cor, p) print(f"{p['name']:24s} C={p['C']:6.1f} formula delay={'n/a' if fd is None else f'{fd:.2f} veh-h/h'}")if __name__ == "__main__": main()src/formula.pyThe delay formula (Webster + platoon) and its optimizer: our stand-in for the math team's code.
"""Formula delay model for the corridor (Webster + platoon delay), N lights.STAND-IN for Michael + Noah's signal_opt.py: same formulation as notes/meeting-prep-2026-11-10.txt, generalized frommath-example/model.py. When their code arrives, plans from it are read through plans.py and this file is only usedfor Study 1's "formula prediction" column (or replaced by their evaluator).Conventions: lights ordered north -> south (index 0 = northmost). Main road = Big Bend (NB, SB); side = EB, WB.SB platoons travel light i -> i+1; NB platoons travel light i+1 -> i.A plan gives C (common cycle), per light g_main (s) and offset_s (time main green starts, relative to light 0)."""import numpy as npfrom scipy.optimize import minimizeH = 3600.0def webster_terms(C, g, q_vph, s_vph): q, s = q_vph/H, s_vph/H lam = g/C x = q/(lam*s) if lam > 0 else 9.9 if x >= 0.999 or lam <= 0: return 1e3, 1e3, lam, x return C*(1-lam)**2/(2*(1-lam*x)), x**2/(2*q*(1-x)), lam, xdef _w_int(a, b, C, gd): gd = min(max(gd, 0.0), C) W = lambda u: 0.0 if u <= gd else C*(u-gd)-(u*u-gd*gd)/2 F = lambda t: np.floor(t/C)*W(C)+W(t-np.floor(t/C)*C) return F(b)-F(a)def platoon_delay(phi, C, g_up, g_down): return _w_int(phi, phi+g_up, C, g_down)/g_updef light_L(cor, l): """Lost time for one light: measured (timing sheet) if present, else the corridor parameter.""" return (l.get("timing") or {}).get("L_s", cor["params"]["L_s"])def evaluate(cor, C, g_main, offsets, detail=False): """Total delay in vehicle-hours per hour. g_main, offsets: lists in corridor order.""" P = cor["params"]; p = P["p"] lights, links = cor["lights"], cor["links"] n = len(lights); total = 0.0; rows = [] for i, l in enumerate(lights): L = light_L(cor, l) for a in ("NB", "SB", "EB", "WB"): A = l["approaches"][a]; main = a in ("NB", "SB") g = g_main[i] if main else C-L-g_main[i] t1, t2, lam, x = webster_terms(C, g, A["q_vph"], A["s_vph"]) up = i-1 if a == "SB" else (i+1 if a == "NB" else None) if main and up is not None and 0 <= up < n: tau = links[min(i, up)]["tau_s"] phi = (offsets[up]+tau-offsets[i]) % C dp = platoon_delay(phi, C, g_main[up], g_main[i]) d = (1-p)*t1+p*dp+t2; kind = "platoon" else: d = t1+t2; kind = "webster"; phi = None vh = A["q_vph"]*d/H; total += vh rows.append(dict(light=l["id"], approach=a, g=g, x=x, delay_s=d, veh_h=vh, kind=kind, phi=phi)) return (total, rows) if detail else totaldef constraints(cor, C, g_main): P = cor["params"]; c = [] for i, l in enumerate(cor["lights"]): g = g_main[i]; L = light_L(cor, l) c += [g-P["g_min_s"], C-L-g-P["g_min_s"]] for a in ("NB", "SB", "EB", "WB"): A = l["approaches"][a]; gg = g if a in ("NB", "SB") else C-L-g c.append(P["x_max"]*A["s_vph"]*gg-A["q_vph"]*C) return np.array(c)def optimize(cor, starts=30, seed=0): """Multistart SLSQP over z = [C, g_1..g_n, w_2..w_n] (offsets as fractions of C, light 0 fixed at 0).""" P = cor["params"]; n = len(cor["lights"]); rng = np.random.default_rng(seed) def unpack(z): C = z[0]; g = list(z[1:1+n]); offs = [0.0]+[w*C for w in z[1+n:]] return C, g, offs f = lambda z: evaluate(cor, *unpack(z)) cons = [{"type": "ineq", "fun": lambda z: constraints(cor, z[0], z[1:1+n])}] bounds = [(P["C_min_s"], P["C_max_s"])]+[(P["g_min_s"], None)]*n+[(0, 1)]*(n-1) best, found = None, [] for _ in range(starts): C0 = rng.uniform(P["C_min_s"], P["C_max_s"]) z0 = [C0]+[(C0-light_L(cor, l))*0.55 for l in cor["lights"]]+list(rng.uniform(0, 1, n-1)) r = minimize(f, z0, method="SLSQP", bounds=bounds, constraints=cons, options=dict(maxiter=400, ftol=1e-10)) if r.success and min(constraints(cor, r.x[0], r.x[1:1+n])) > -1e-6: found.append(r.fun) if best is None or r.fun < best[0]: best = (r.fun, r.x) C, g, offs = unpack(best[1]) return dict(total_veh_h=float(best[0]), C=float(C), g_main=g, offsets=offs, n_success=len(found), distinct_optima=sorted(set(float(round(v, 2)) for v in found)))Step 7 · Run the simulations
Each plan, 10 runs, delay measured.
src/run_sumo.pyRuns SUMO for each plan and seed in parallel; measures delay, stops, throughput.
"""Run plans in SUMO over several seeds and measure corridor delay.Metrics (measurement window only, after warm-up): delay_veh_h_per_h : total time lost on corridor edges (edgeData timeLoss) + insertion delay at entries, in vehicle-hours per hour stops_per_veh : average number of stops (tripinfo waitingCount) per completed trip throughput_vph : trips completed in the windowUsage: run_sumo.py [plan names...] [--seeds N]"""import sys, pathlib, json, subprocess, csv, statistics, tempfile, osimport xml.etree.ElementTree as ETfrom concurrent.futures import ThreadPoolExecutorsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import SUMO, BIN, BUILDimport plans as Pimport plan_to_sumoRUNS = BUILD/"runs"def run_one(plan_name, seed, extra_add=None): dem = json.load(open(SUMO/"demand.json")) w0, w1 = dem["warmup_s"], dem["warmup_s"]+dem["measure_s"] tls_add = SUMO/"plans"/f"{plan_name}.tls.add.xml" out = RUNS/plan_name/f"seed{seed}"; out.mkdir(parents=True, exist_ok=True) meas = out/"edgedata.add.xml" meas.write_text(f'<additional><edgeData id="m" file="{out/"edges.xml"}" begin="{w0}" end="{w1}" excludeEmpty="true"/></additional>\n') cmd = [str(BIN/"sumo"), "-n", str(SUMO/"net.net.xml"), "-r", str(SUMO/"routes.rou.xml"), "-a", f"{extra_add or tls_add},{meas}", "--seed", str(seed), "--end", str(w1+1800), "--tripinfo-output", str(out/"trips.xml"), "--no-step-log", "--no-warnings", "--time-to-teleport", "300", "--duration-log.disable"] subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL) measure = set(dem["measure_edges"]) loss = 0.0; entered = {} for iv in ET.parse(out/"edges.xml").getroot().iter("interval"): for e in iv.iter("edge"): if e.get("id") in measure: loss += float(e.get("timeLoss", 0)) entered[e.get("id")] = float(e.get("entered", 0)) ddelay = 0.0; stops = []; done = 0 for t in ET.parse(out/"trips.xml").getroot().iter("tripinfo"): dep = float(t.get("depart")) if w0 <= dep < w1: ddelay += float(t.get("departDelay", 0)); stops.append(int(t.get("waitingCount", 0))); done += 1 hours = (w1-w0)/3600 res = dict(plan=plan_name, seed=seed, delay_veh_h_per_h=(loss+ddelay)/3600/hours, edge_timeloss_veh_h=loss/3600, depart_delay_veh_h=ddelay/3600, stops_per_veh=statistics.mean(stops) if stops else 0, throughput_vph=done/hours) json.dump(dict(res, entered=entered), open(out/"metrics.json", "w")) return resdef run_plans(names, seeds=10, workers=None): for n in names: plan_to_sumo.write(P.load(n)) jobs = [(n, s) for n in names for s in range(1, seeds+1)] with ThreadPoolExecutor(max_workers=workers or max(1, (os.cpu_count() or 4)-1)) as ex: res = list(ex.map(lambda j: run_one(*j), jobs)) RUNS.mkdir(parents=True, exist_ok=True) with open(RUNS/"all_runs.csv", "a", newline="") as f: w = csv.DictWriter(f, fieldnames=list(res[0].keys())) if f.tell() == 0: w.writeheader() w.writerows(res) summary = {} for n in names: r = [x for x in res if x["plan"] == n] d = [x["delay_veh_h_per_h"] for x in r] summary[n] = dict(delay_mean=statistics.mean(d), delay_sd=statistics.stdev(d) if len(d) > 1 else 0.0, stops_mean=statistics.mean(x["stops_per_veh"] for x in r), throughput_mean=statistics.mean(x["throughput_vph"] for x in r), seeds=len(r)) return summaryif __name__ == "__main__": args = sys.argv[1:]; seeds = 10 if "--seeds" in args: i = args.index("--seeds"); seeds = int(args[i+1]); del args[i:i+2] names = args or sorted(p.stem for p in P.PLANS.glob("*.json")) s = run_plans(names, seeds) json.dump(s, open(BUILD/"results_summary.json", "w"), indent=1) for n, v in sorted(s.items(), key=lambda kv: kv[1]["delay_mean"]): print(f"{n:26s} delay {v['delay_mean']:7.2f} ± {v['delay_sd']:5.2f} veh-h/h stops/veh {v['stops_mean']:.2f} " f"throughput {v['throughput_mean']:.0f} veh/h ({v['seeds']} seeds)")src/plan_to_sumo.pyTurns a plan into SUMO signal programs (County phase sequence or simple two-phase).
"""Canonical plan JSON -> SUMO traffic-light programs (build/sumo/plans/<name>.tls.add.xml).Two-phase program per light, matching the model: 1 Big Bend green (through/right 'G', left 'g' = permissive, yields to oncoming) 2 Big Bend yellow 3 all-red 4 cross-street green 5 cross-street yellow 6 all-redLost time per phase = yellow + all-red (from corridor params). SUMO offset == plan offset_s (verified: phase 1 starts at t = offset)."""import sys, pathlib, json, tomllibsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import SUMO, ROOT, corridor, tls_map, tls_linksimport plans as Pimport nemaMOVE = {"s": "T", "r": "R", "R": "R", "l": "L", "L": "L", "t": "L"}def program_nema(tls_id, raw, T, C, g_main, offset, light=None): """County phase sequence scaled to this plan, left arrows sized to measured left-turn demand (see nema.py).""" phases = {int(k): v for k, v in raw["phases"].items()} splits = {int(k): v for k, v in T["splits"].items()} ld = {a: A["q_vph"]*A["turn_share"]["L"] for a, A in light["approaches"].items()} if light else None ivs = nema.build(phases, splits, set(T["main_phases"]), C, g_main+T["clearance_main_s"], left_demand=ld) links = sorted(tls_links(tls_id), key=lambda z: z[0]) merged = [] for d, col in ivs: # fold slivers (< 0.1 s, from ring boundaries a few ms apart) into the previous phase if merged and d < 0.1: merged[-1] = (merged[-1][0]+d, merged[-1][1]) else: merged.append((d, col)) body = [] for d, col in merged: s = "".join(col.get((lab, MOVE.get(dr, "T")), "r") for idx, e_in, e_out, lab, dr in links) body.append(f' <phase duration="{d:.2f}" state="{s}"/>') return f' <tlLogic id="{tls_id}" type="static" programID="plan" offset="{offset % C:.2f}">\n' + "\n".join(body) + "\n </tlLogic>"MAIN = ("NB", "SB")def program(tls_id, C, g_main, offset, yellow, allred, yellow_s=None, allred_s=None): links = sorted(tls_links(tls_id), key=lambda z: z[0]) def state(green_main, color): s = [] for idx, e_in, e_out, lab, d in links: ours = (lab in MAIN) == green_main if not ours: s.append("r") elif color == "G": s.append("g" if d in ("l", "L", "t") else "G") else: s.append(color) return "".join(s) yellow_s = yellow if yellow_s is None else yellow_s; allred_s = allred if allred_s is None else allred_s L = yellow+allred+yellow_s+allred_s g_side = C-L-g_main if g_main <= 0 or g_side <= 0: raise ValueError(f"{tls_id}: infeasible greens main={g_main} side={g_side} C={C}") ph = [(g_main, state(True, "G")), (yellow, state(True, "y")), (allred, state(True, "r")), (g_side, state(False, "G")), (yellow_s, state(False, "y")), (allred_s, state(False, "r"))] body = "\n".join(f' <phase duration="{d:.2f}" state="{s}"/>' for d, s in ph) return f' <tlLogic id="{tls_id}" type="static" programID="plan" offset="{offset % C:.2f}">\n{body}\n </tlLogic>'def apply_rtor(xml_body, tls_id): """Right turn on red: right-turn links that would show red show 's' (stop, then proceed when clear).""" links = sorted(tls_links(tls_id), key=lambda z: z[0]) rights = [i for i, (idx, e_in, e_out, lab, dr) in enumerate(links) if dr in ("r", "R")] def fix(m): s = list(m.group(1)) for i in rights: if s[i] == "r": s[i] = "s" return f'state="{"".join(s)}"' import re return re.sub(r'state="([^"]+)"', fix, xml_body)def write(plan): cor = corridor(); tm = tls_map(); pr = cor["params"] scfg = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("sumo", {}) mode = scfg.get("signal_program", "two_phase") rawf = ROOT/"data/measured/county_timing.json" raw = json.load(open(rawf)) if rawf.exists() else {} out = [] for l in cor["lights"]: v = plan["lights"][l["id"]] C = v.get("C", plan["C"]) T = l.get("timing") if mode == "nema" and T and l["id"] in raw: out.append(program_nema(tm[l["id"]]["tls"], raw[l["id"]], T, C, v["g_main"], v["offset_s"], light=l)) elif T: # measured yellow / all-red for this light out.append(program(tm[l["id"]]["tls"], C, v["g_main"], v["offset_s"], T["yellow_main_s"], T["all_red_main_s"], T["yellow_side_s"], T["all_red_side_s"])) else: out.append(program(tm[l["id"]]["tls"], C, v["g_main"], v["offset_s"], pr["yellow_s"], pr["all_red_s"])) if scfg.get("right_on_red", False): out = [apply_rtor(x, tm[l["id"]]["tls"]) for x, l in zip(out, cor["lights"])] d = SUMO/"plans"; d.mkdir(parents=True, exist_ok=True) f = d/f"{plan['name']}.tls.add.xml" f.write_text("<additional>\n"+"\n".join(out)+"\n</additional>\n") return fif __name__ == "__main__": names = sys.argv[1:] or [p.stem for p in P.PLANS.glob("*.json")] for n in names: print("wrote", write(P.load(n)))src/nema.pyBuilds the County's real phase sequence (incl. left arrows) scaled to a plan's timing.
"""Build a SUMO signal program that follows the County's real dual-ring phase sequence (NEMA), scaled to a plan.A plan fixes, per light: cycle C, the Big Bend block length (g_main + its clearance), the cross-street block (the rest),and the offset (start of the Big Bend block). Inside each block every phase keeps its real yellow + all-red, and theremaining green time is shared in the County's proportions (timing sheet, design pattern).Phase meanings come from the sheet's movement text: "Big Bend Blvd. SB LT" -> SB left, protected "Big Bend Blvd. NB" -> NB through + right; NB left permissive (sheets mark LT phases Protected/Permissive) "Forsyth Blvd. WB & LT" -> WB through + right + left, protected (split phase) "Big Bend Blvd. SB LT ... Clayton Rd. WB RT" -> SB left protected + WB right overlapRing 1 = phases 1-4, ring 2 = phases 5-8; a ring with no phases in a block follows the other ring there."""import reORDER = {None: 0, "r": 0, "y": 1, "g": 2, "G": 3}def _moves(desc, has_lt): prot, perm = {}, set() for m in re.finditer(r"(NB|SB|EB|WB)\s*(& LT|LT|RT)?", desc): a, k = m.group(1), (m.group(2) or "").strip() if k == "LT": prot.setdefault(a, set()).add("L") elif k == "RT": prot.setdefault(a, set()).add("R") elif k == "& LT": prot.setdefault(a, set()).update({"L", "T", "R"}) else: prot.setdefault(a, set()).update({"T", "R"}) perm.add(a) # left turns on gaps during the through phase (protected/permissive or no LT phase) return prot, permdef _max(a, b): return a if ORDER[a] >= ORDER[b] else bdef left_only(desc): """Approach served by a protected-left-only phase (e.g. 'Big Bend Blvd. SB LT'), else None.""" m = re.search(r"(NB|SB|EB|WB)\s*LT", desc) return m.group(1) if m and "& LT" not in desc else Nonedef build(phases, splits, main_phases, C_plan, main_block_plan, left_demand=None, sat_left=1800.0, x_target=0.9): """phases: {n: {movement, yellow, all_red, min_green}}, splits: {n: seconds} (design pattern), main_phases: Big Bend phases. left_demand: {approach: left-turn veh/h}. If given, each protected-left-only phase gets the green its demand needs (q*C/(s*x_target)), clamped to [min green, its County split green]; the time saved goes to the other phases of that ring block (what the actuated controller does when a left arrow gaps out). Returns [(duration_s, {(approach, 'L'|'T'|'R'): 'G'|'g'|'y'})] covering one cycle, starting at the Big Bend block.""" has_lt = {m.group(1) for p in phases.values() for m in re.finditer(r"(NB|SB|EB|WB)\s*LT", p["movement"])} clr = lambda n: phases[n]["yellow"] + (phases[n]["all_red"] or 0.0) rings = {} for r, ids in ((1, [1, 2, 3, 4]), (2, [5, 6, 7, 8])): seq = [n for n in ids if n in splits] t = 0.0; tl = [] for group, block in (([n for n in seq if n in main_phases], main_block_plan), ([n for n in seq if n not in main_phases], C_plan-main_block_plan)): if not group: tl.append((t, t+block, None)); t += block; continue avail = block - sum(clr(n) for n in group) if avail <= 0: raise ValueError(f"block {block:.1f}s shorter than its clearances") share = {n: max(splits[n]-clr(n), 0.1) for n in group} green = {n: avail*share[n]/sum(share.values()) for n in group} if left_demand: fixed = {} for n in group: a = left_only(phases[n]["movement"]) if a is not None and len(group) > 1: need = left_demand.get(a, 0.0)*C_plan/(sat_left*x_target) lo = phases[n].get("min_green") or 4.0 fixed[n] = min(max(need, lo), green[n]) rest = [n for n in group if n not in fixed] if fixed and rest: left = avail - sum(fixed.values()); tot = sum(share[n] for n in rest) green = {**fixed, **{n: left*share[n]/tot for n in rest}} for n in group: d = clr(n) + green[n] tl.append((t, t+d, n)); t += d rings[r] = tl def state_at(r, t): for s, e, n in rings[r]: if s <= t < e: if n is None: return None y, ar = phases[n]["yellow"], phases[n]["all_red"] or 0.0 return n, ("G" if t < e-y-ar else ("y" if t < e-ar else "r")) return None pts = {0.0, C_plan} for tl in rings.values(): for s, e, n in tl: pts |= {s, e} if n is not None: pts |= {e-phases[n]["yellow"]-(phases[n]["all_red"] or 0.0), e-(phases[n]["all_red"] or 0.0)} pts = sorted(p for p in pts if 0 <= p <= C_plan) out = [] for a, b in zip(pts, pts[1:]): if b-a < 1e-3: continue mid = (a+b)/2; col = {} for r in (1, 2): st = state_at(r, mid) or state_at(3-r, mid) if not st or st[1] == "r": continue n, c = st prot, perm = _moves(phases[n]["movement"], has_lt) for appr, mv in prot.items(): for m in mv: col[(appr, m)] = _max(col.get((appr, m)), c) for appr in perm: col[(appr, "L")] = _max(col.get((appr, "L")), "g" if c == "G" else "y") out.append((b-a, col)) return outStep 8 · Check against reality
Simulated vs counted traffic.
src/validate.pyCompares simulated volumes with the counts (GEH score) at every approach.
"""Sanity check: simulated hourly volumes into each light vs the corridor dataset (County / MoDOT derived).GEH = sqrt(2 (M - C)^2 / (M + C)), M = simulated veh/h, C = target veh/h. Standard traffic-model check:GEH < 5 good, 5-10 look at it, > 10 problem. Entry approaches match by construction; the interior Big Bendapproaches are the real test (their volume emerges from upstream turning + side-street inflow).Usage: validate.py [plan] (uses that plan's seed runs; default webster-common)"""import sys, json, math, pathlib, statisticssys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, SUMO, corridor, tls_map, tls_linksdef main(plan="webster-common"): cor = corridor(); tm = tls_map(); dem = json.load(open(SUMO/"demand.json")) hours = dem["measure_s"]/3600 runs = sorted((BUILD/"runs"/plan).glob("seed*/metrics.json")) if not runs: sys.exit(f"no runs for {plan}; run run_sumo.py first") entered = [json.load(open(r))["entered"] for r in runs] entries = {f["id"] for f in dem["flows"]} rows = [] for l in cor["lights"]: lid = l["id"] for lab, A in l["approaches"].items(): edges = {e_in.getID() for _, e_in, _, lb, _ in tls_links(tm[lid]["tls"]) if lb == lab} if f"{lid}_{lab}" in entries: kind = "entry" sim = A["q_vph"] # inserted at this rate by construction (checked via throughput) else: kind = "interior" sim = statistics.mean(sum(en.get(e, 0) for e in edges) for en in entered)/hours tgt = A["q_vph"] geh = math.sqrt(2*(sim-tgt)**2/(sim+tgt)) if sim+tgt > 0 else 0 rows.append(dict(light=lid, name=l["name"], approach=lab, kind=kind, target_vph=round(tgt), sim_vph=round(sim), geh=round(geh, 2), target_source=A["q_source"], target_ref=A["q_ref"])) json.dump(rows, open(BUILD/"validation.json", "w"), indent=1) print(f"validation ({plan}, {len(runs)} seeds): light approach kind target sim GEH") for r in rows: flag = "" if r["geh"] < 5 else (" <- check" if r["geh"] < 10 else " <- PROBLEM") print(f" {r['light']} {r['name']:16s} {r['approach']} {r['kind']:8s} {r['target_vph']:6d} {r['sim_vph']:6d} {r['geh']:5.2f}{flag}") inter = [r["geh"] for r in rows if r["kind"] == "interior"] print(f"interior approaches: {sum(g < 5 for g in inter)}/{len(inter)} with GEH < 5")if __name__ == "__main__": main(*sys.argv[1:])Study 1
Formula model vs optimizing inside the simulation.
src/study1.pyPart A: 30 random plans, formula vs simulation ranking. Part B: Nelder–Mead search using the simulation.
"""Study 1: simulator-in-the-loop vs formula model.Part A (prediction): N random feasible plans; formula delay vs SUMO delay (SEEDS_A seeds each) -> correlation, scatter.Part B (optimization): derivative-free optimizer (Nelder-Mead) whose objective is mean SUMO delay (SEEDS_B seeds, common random numbers), same knobs as the model (C, g_main per light, offsets), warm-started from the formula optimum. Fixed budget of SUMO evaluations. Best plan saved as plans/study1-sumo-loop.json for the main comparison.Outputs: build/study1/{prediction.csv, optimization.csv, summary.json, prediction.png, convergence.png}Usage: study1.py [--n-random 30] [--budget 120]"""import sys, json, csv, time, pathlib, shutil, statisticsimport numpy as npfrom scipy.optimize import minimizefrom concurrent.futures import ThreadPoolExecutorsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, corridorimport plans as P, plan_to_sumo, run_sumo, formulaOUT = BUILD/"study1"SEEDS_A, SEEDS_B = (1, 2), (1, 2)def plan_from(cor, C, g, offs, name, source): ids = [l["id"] for l in cor["lights"]] return dict(name=name, source=source, C=float(C), L_s=cor["params"]["L_s"], lights={i: dict(g_main=float(gi), offset_s=float(o % C)) for i, gi, o in zip(ids, g, offs)}, notes="")def feasible(cor, C, g): return min(formula.constraints(cor, C, g)) >= -1e-6def sumo_delay(plan, seeds): """Mean SUMO delay over seeds; None if the plan can't be built or SUMO fails (logged).""" try: plan_to_sumo.write(plan) with ThreadPoolExecutor(max_workers=len(seeds)) as ex: res = list(ex.map(lambda s: run_sumo.run_one(plan["name"], s), seeds)) except Exception as e: print(f" ! {plan['name']} failed: {str(e)[:120]}") shutil.rmtree(run_sumo.RUNS/plan["name"], ignore_errors=True) return None shutil.rmtree(run_sumo.RUNS/plan["name"], ignore_errors=True) (plan_to_sumo.SUMO/"plans"/f"{plan['name']}.tls.add.xml").unlink(missing_ok=True) return statistics.mean(r["delay_veh_h_per_h"] for r in res)def random_plan(cor, rng): Pm = cor["params"]; n = len(cor["lights"]) for _ in range(5000): C = rng.uniform(Pm["C_min_s"], Pm["C_max_s"]); g = [] for l in cor["lights"]: A = l["approaches"]; L = formula.light_L(cor, l) lo = max(Pm["g_min_s"], max(A[d]["q_vph"]*C/(Pm["x_max"]*A[d]["s_vph"]) for d in ("NB", "SB"))) hi = C-L-max(Pm["g_min_s"], max(A[d]["q_vph"]*C/(Pm["x_max"]*A[d]["s_vph"]) for d in ("EB", "WB"))) if hi <= lo: break g.append(rng.uniform(lo, hi)) if len(g) == n and feasible(cor, C, g): return C, g, [0.0]+list(rng.uniform(0, C, n-1)) raise RuntimeError("no feasible random plan found")def part_a(cor, n): rng = np.random.default_rng(7); rows = [] for k in range(n): C, g, o = random_plan(cor, rng) p = plan_from(cor, C, g, o, f"_s1a_{k}", "study1 random") fd = formula.evaluate(cor, C, g, o) sd = sumo_delay(p, SEEDS_A) if sd is None: continue rows.append(dict(k=k, C=C, formula=fd, sumo=sd)); print(f" A {k+1}/{n}: C={C:5.1f} formula {fd:7.1f} sumo {sd:7.1f}") return rowsdef part_b(cor, budget): ids = [l["id"] for l in cor["lights"]]; n = len(ids); Pm = cor["params"] start = P.load("formula-optimum-standin") z0 = [start["C"]]+[start["lights"][i]["g_main"] for i in ids]+[start["lights"][i]["offset_s"]/start["C"] for i in ids[1:]] hist = []; t0 = time.time() def obj(z): C = float(np.clip(z[0], Pm["C_min_s"], Pm["C_max_s"])); g = list(z[1:1+n]); w = [0.0]+[float(x) % 1 for x in z[1+n:]] if not feasible(cor, C, g): pen = -min(formula.constraints(cor, C, g)) val = 1e4+pen else: val = sumo_delay(plan_from(cor, C, g, [x*C for x in w], f"_s1b_{len(hist)}", "study1 eval"), SEEDS_B) val = 1e4 if val is None else val hist.append(dict(eval=len(hist)+1, value=val, C=C, g=g, w=w, t=time.time()-t0)) best = min(h["value"] for h in hist) print(f" B eval {len(hist):3d}: {val:8.1f} best {best:8.1f}") return val simplex = [np.array(z0, float)] steps = [8.0]+[4.0]*n+[0.08]*(n-1) for k, s in enumerate(steps): v = np.array(z0, float); v[k] += s; simplex.append(v) minimize(obj, z0, method="Nelder-Mead", options=dict(maxfev=budget, initial_simplex=np.array(simplex), xatol=1e-2, fatol=0.5)) b = min(hist, key=lambda h: h["value"]) plan = plan_from(cor, b["C"], b["g"], [x*b["C"] for x in b["w"]], "study1-sumo-loop", f"Study 1: Nelder-Mead on SUMO delay ({len(hist)} evaluations x {len(SEEDS_B)} seeds), warm start = formula optimum") P.save(plan) return hist, plandef figures(rows, hist): import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt if rows: f, ax = plt.subplots(figsize=(5, 4)) ax.scatter([r["formula"] for r in rows], [r["sumo"] for r in rows], s=18) ax.set_xlabel("formula model delay (veh-h/h)"); ax.set_ylabel("SUMO delay (veh-h/h)") ax.set_title("Study 1A: does the formula rank plans like SUMO?"); f.tight_layout(); f.savefig(OUT/"prediction.png", dpi=150) if hist: f, ax = plt.subplots(figsize=(5, 3.5)) vals = [h["value"] for h in hist if h["value"] < 1e4]; best = np.minimum.accumulate([h["value"] for h in hist]) ax.plot(range(1, len(best)+1), best); ax.set_xlabel("SUMO evaluations"); ax.set_ylabel("best delay so far (veh-h/h)") ax.set_title("Study 1B: simulator-in-the-loop optimization"); f.tight_layout(); f.savefig(OUT/"convergence.png", dpi=150)def main(): args = sys.argv[1:] n_random = int(args[args.index("--n-random")+1]) if "--n-random" in args else 30 budget = int(args[args.index("--budget")+1]) if "--budget" in args else 120 OUT.mkdir(parents=True, exist_ok=True); cor = corridor() t = time.time(); rows = part_a(cor, n_random); ta = time.time()-t from scipy.stats import spearmanr, pearsonr fin = [r for r in rows if r["formula"] < 900] rho = spearmanr([r["formula"] for r in fin], [r["sumo"] for r in fin]).statistic if len(fin) > 2 else None r_p = pearsonr([r["formula"] for r in fin], [r["sumo"] for r in fin]).statistic if len(fin) > 2 else None with open(OUT/"prediction.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows) t = time.time(); hist, plan = part_b(cor, budget); tb = time.time()-t with open(OUT/"optimization.csv", "w", newline="") as f: w = csv.writer(f); w.writerow(["eval", "sumo_delay", "C", "seconds"]) for h in hist: w.writerow([h["eval"], round(h["value"], 3), round(h["C"], 2), round(h["t"], 1)]) t = time.time(); r_formula = formula.optimize(cor, starts=30); tf = time.time()-t summary = dict(prediction=dict(n_plans=len(rows), n_finite=len(fin), spearman=rho, pearson=r_p, seconds=round(ta)), sumo_loop=dict(evaluations=len(hist), seeds_per_eval=len(SEEDS_B), best_delay_2seeds=min(h["value"] for h in hist), seconds=round(tb), plan="plans/study1-sumo-loop.json"), formula_optimizer=dict(seconds=round(tf, 1), starts=30, formula_delay=r_formula["total_veh_h"])) json.dump(summary, open(OUT/"summary.json", "w"), indent=1, default=float) figures(rows, hist) print(json.dumps(summary, indent=1, default=float))if __name__ == "__main__": main()Browser mini-simulator
The simplified simulation that runs on this page, and how it is checked against SUMO.
sim/core.jsThe engine: cars follow the Krauss rule (SUMO's default), lights run the County sequence; runs in the browser and in Node.
/* Big Bend mini-simulator: a small, browser-sized traffic simulation of our corridor. Written for this project (not SUMO code). Same ingredients as our SUMO model, simplified: - corridor from data.json: 4 signals at real spacing, measured volumes + turn shares, approach lanes, left-turn bays - cars follow the Krauss car-following rule (SUMO's default model, Krauss 1998), one update per simulated second - signals run the County phase sequence scaled to each plan (port of src/nema.py), right turn on red - delay = time lost below each car's desired speed + time waiting to enter (same definition as our SUMO runs) Works in the browser (window.MiniSim) and in Node (module.exports) for validation against SUMO. */(function (root) { "use strict"; const DIRS = ["NB", "SB", "EB", "WB"]; const OPP = { NB: "SB", SB: "NB", EB: "WB", WB: "EB" }; const HEAD = { NB: { T: "NB", L: "WB", R: "EB" }, SB: { T: "SB", L: "EB", R: "WB" }, EB: { T: "EB", L: "NB", R: "SB" }, WB: { T: "WB", L: "SB", R: "NB" } }; const VLEN = 5.0, MINGAP = 2.5, ACC = 2.6, DEC = 4.5, SIGMA = 0.5, TAU = 1.0, SAT = 1800, XT = 0.9; function rng(seed) { let a = seed >>> 0; return function () { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function poisson(lam, r) { let L = Math.exp(-lam), k = 0, p = 1; do { k++; p *= r(); } while (p > L); return k - 1; } /* ---------- signal programs: port of src/nema.py ---------- */ function moves(desc) { const prot = {}, perm = new Set(); const re = /(NB|SB|EB|WB)\s*(& LT|LT|RT)?/g; let m; while ((m = re.exec(desc))) { const a = m[1], k = (m[2] || "").trim(); prot[a] = prot[a] || new Set(); if (k === "LT") prot[a].add("L"); else if (k === "RT") prot[a].add("R"); else if (k === "& LT") { prot[a].add("L"); prot[a].add("T"); prot[a].add("R"); } else { prot[a].add("T"); prot[a].add("R"); perm.add(a); } } return { prot, perm }; } const RANK = { r: 0, y: 1, g: 2, G: 3 }; const better = (a, b) => (RANK[a || "r"] >= RANK[b] ? a : b); function leftOnly(desc) { const m = /(NB|SB|EB|WB)\s*LT/.exec(desc); return m && desc.indexOf("& LT") < 0 ? m[1] : null; } function buildProgram(T, C, mainBlock, leftDemand) { const ph = T.phases, sp = {}; for (const k in T.splits) sp[+k] = T.splits[k]; const mainSet = new Set(T.main_phases.map(Number)); const clr = (n) => ph[n].yellow + (ph[n].all_red || 0); const rings = {}; for (const [r, ids] of [[1, [1, 2, 3, 4]], [2, [5, 6, 7, 8]]]) { const seq = ids.filter((n) => sp[n] !== undefined); let t = 0; const tl = []; for (const [group, block] of [[seq.filter((n) => mainSet.has(n)), mainBlock], [seq.filter((n) => !mainSet.has(n)), C - mainBlock]]) { if (!group.length) { tl.push([t, t + block, null]); t += block; continue; } const avail = block - group.reduce((s, n) => s + clr(n), 0); if (avail <= 0) throw new Error("block shorter than its clearances"); const share = {}; group.forEach((n) => (share[n] = Math.max(sp[n] - clr(n), 0.1))); const tot = group.reduce((s, n) => s + share[n], 0); let green = {}; group.forEach((n) => (green[n] = (avail * share[n]) / tot)); if (leftDemand && group.length > 1) { const fixed = {}; group.forEach((n) => { const a = leftOnly(ph[n].movement); if (a) { const need = ((leftDemand[a] || 0) * C) / (SAT * XT); fixed[n] = Math.min(Math.max(need, ph[n].min_green || 4), green[n]); } }); const rest = group.filter((n) => fixed[n] === undefined); if (Object.keys(fixed).length && rest.length) { const left = avail - Object.values(fixed).reduce((s, x) => s + x, 0), rt = rest.reduce((s, n) => s + share[n], 0); green = Object.assign({}, fixed); rest.forEach((n) => (green[n] = (left * share[n]) / rt)); } } group.forEach((n) => { const d = clr(n) + green[n]; tl.push([t, t + d, n]); t += d; }); } rings[r] = tl; } const stateAt = (r, t) => { for (const [s, e, n] of rings[r]) if (s <= t && t < e) { if (n === null) return null; const y = ph[n].yellow, ar = ph[n].all_red || 0; return [n, t < e - y - ar ? "G" : t < e - ar ? "y" : "r"]; } return null; }; const pts = new Set([0, C]); for (const r in rings) for (const [s, e, n] of rings[r]) { pts.add(s); pts.add(e); if (n !== null) { pts.add(e - ph[n].yellow - (ph[n].all_red || 0)); pts.add(e - (ph[n].all_red || 0)); } } const P = [...pts].filter((p) => p >= 0 && p <= C).sort((a, b) => a - b); const out = []; for (let i = 0; i + 1 < P.length; i++) { const a = P[i], b = P[i + 1]; if (b - a < 1e-3) continue; const mid = (a + b) / 2, col = {}; for (const r of [1, 2]) { const st = stateAt(r, mid) || stateAt(3 - r, mid); if (!st || st[1] === "r") continue; const { prot, perm } = moves(ph[st[0]].movement); for (const ap in prot) for (const mv of prot[ap]) col[ap + "_" + mv] = better(col[ap + "_" + mv], st[1]); for (const ap of perm) col[ap + "_L"] = better(col[ap + "_L"], st[1] === "G" ? "g" : "y"); } if (out.length && b - a < 0.1) out[out.length - 1].dur += b - a; else out.push({ dur: b - a, col }); } return out; } /* ---------- the simulation ---------- */ function Sim(data, plan, seed) { this.d = data; this.r = rng(seed || 1); this.t = 0; this.links = {}; this.pending = {}; this.programs = {}; this.stats = { loss: 0, waitEnter: 0, trips: 0, stops: 0, inserted: 0, lossWin: [] }; this.lastCross = {}; const G = data.geometry, L = data.lights; L.forEach((l, i) => { for (const d of DIRS) { const A = l.approaches[d]; let len, v; if (d === "SB") { len = i === 0 ? G.end_len : l.s - L[i - 1].s; v = G.link_speed[Math.max(i - 1, 0)]; } else if (d === "NB") { len = i === L.length - 1 ? G.end_len : L[i + 1].s - l.s; v = G.link_speed[Math.min(i, G.link_speed.length - 1)]; } else { len = G.side_len; v = G.side_speed[l.id]; } const entry = d === "EB" || d === "WB" || (d === "SB" && i === 0) || (d === "NB" && i === L.length - 1); this.links[l.id + "_" + d] = { lid: l.id, i, dir: d, len, vmax: v, nt: A.nt, bayStart: len - Math.min(G.bay, len - 20), lanes: Array.from({ length: A.nt + 1 }, () => []), A, entry, balance: 0 }; if (entry) this.pending[l.id + "_" + d] = []; } }); for (const b of data.balancing) { // mid-block flows: into the downstream light's approach const [n, s] = b.link.split("-"); const key = (b.dir === "SB" ? s : n) + "_" + b.dir; if (this.links[key]) this.links[key].balance = b.vph; } this.setPlan(plan); } Sim.prototype.setPlan = function (plan) { this.plan = plan; for (const l of this.d.lights) { const T = this.d.timing[l.id], p = plan.lights[l.id], C = p.C || plan.C; const ld = {}; for (const d of DIRS) ld[d] = l.approaches[d].q * l.approaches[d].L; this.programs[l.id] = { C, off: p.offset, prog: buildProgram(T, C, p.g_main + T.clearance_main, ld) }; } }; Sim.prototype.signal = function (lid, key, t) { const P = this.programs[lid]; let x = (((t - P.off) % P.C) + P.C) % P.C; for (const ph of P.prog) { if (x < ph.dur) return ph.col[key] || "r"; x -= ph.dur; } return "r"; }; Sim.prototype.chooseMove = function (A) { const u = this.r(); return u < A.L ? "L" : u < A.L + A.T ? "T" : "R"; }; Sim.prototype.place = function (link, v, pos) { // put a vehicle on a link at pos (0 = upstream end); false if no room const mv = v.move; let lane; if (mv === "L") lane = link.nt - 1; else { let best = 0, bestGap = -Infinity; for (let k = 0; k < link.nt; k++) { const ln = link.lanes[k]; const last = ln[ln.length - 1]; const gap = last ? last.pos - pos : 1e9; if (gap > bestGap) { bestGap = gap; best = k; } } lane = best; } const ln = link.lanes[lane]; const last = ln.length ? ln[ln.length - 1] : null; if (pos === 0 && last && last.pos - VLEN - MINGAP < 0) return false; if (pos > 0) { for (const o of ln) if (Math.abs(o.pos - pos) < VLEN + MINGAP + 5) return false; } v.pos = pos; v.lane = lane; v.vmax = link.vmax * v.sf; v.v = Math.min(v.v, v.vmax); v.stopT = 0; if (pos === 0 || !last) ln.push(v); else { ln.push(v); ln.sort((a, b) => b.pos - a.pos); } return true; }; Sim.prototype.newVehicle = function (A) { const sf = Math.min(1.2, Math.max(0.8, 1 + 0.1 * (this.r() + this.r() + this.r() - 1.5) * 2)); return { move: this.chooseMove(A), v: 0, sf, moving: true, stopT: 0, id: (this.nid = (this.nid || 0) + 1) }; }; Sim.prototype.canGo = function (link, v) { const key = link.dir + "_" + v.move, st = this.signal(link.lid, key, this.t), dist = link.len - v.pos; if (st === "G") return true; if (st === "y") return (v.v * v.v) / (2 * DEC) > dist - 0.5; if (st === "g") { // permissive left: wait for a gap in oncoming traffic const opp = this.links[link.lid + "_" + OPP[link.dir]]; if (!opp) return true; const ost = this.signal(link.lid, OPP[link.dir] + "_T", this.t); if (ost !== "G" && ost !== "y") return true; if (this.t - (this.lastCross[link.lid + "_" + OPP[link.dir] + "_T"] || -99) < 2) return false; for (let k = 0; k < opp.nt; k++) { const f = opp.lanes[k][0]; if (f && (opp.len - f.pos) < Math.max(f.v * 4, 10)) return false; } return dist < 3; } if (v.move === "R" && this.d.meta.right_on_red && v.stopT >= 2) { // right turn on red: stop, then go if clear const head = HEAD[link.dir].R, conf = this.links[link.lid + "_" + head]; if (conf) { const cst = this.signal(link.lid, head + "_T", this.t); if (cst === "G" || cst === "y") for (let k = 0; k < conf.nt; k++) { const f = conf.lanes[k][0]; if (f && (conf.len - f.pos) < Math.max(f.v * 4, 12)) return false; } } if (this.t - (this.lastCross[link.lid + "_R"] || -99) < 3) return false; this.lastCross[link.lid + "_R"] = this.t; return true; } return false; }; Sim.prototype.target = function (link, mv) { // where a vehicle goes after crossing: next approach link or out const h = HEAD[link.dir][mv], L = this.d.lights, i = link.i; if (h === "SB" && i + 1 < L.length) return this.links[L[i + 1].id + "_SB"]; if (h === "NB" && i - 1 >= 0) return this.links[L[i - 1].id + "_NB"]; return null; }; Sim.prototype.step = function (measure) { const dt = 1, t = (this.t += dt), r = this.r; // 1. arrivals at the corridor's entry points for (const key in this.pending) { const link = this.links[key]; const n = poisson((link.A.q * dt) / 3600, r); for (let k = 0; k < n; k++) this.pending[key].push(this.newVehicle(link.A)); } for (const key in this.pending) { const q = this.pending[key], link = this.links[key]; while (q.length && this.place(link, q[0], 0)) { q.shift(); this.stats.inserted++; } } for (const key in this.links) { const link = this.links[key]; // mid-block balancing inflow if (link.balance > 0) { const n = poisson((link.balance * dt) / 3600, r); for (let k = 0; k < n; k++) { const v = this.newVehicle(link.A); v.v = link.vmax * 0.6; if (v.move === "L") v.move = "T"; this.place(link, v, link.len * 0.4); } } } // 2. move every vehicle (front to back in each lane), cross the stop line when the signal allows for (const key in this.links) { const link = this.links[key], bay = link.nt; for (let k = 0; k <= link.nt; k++) { const lane = link.lanes[k]; for (let j = 0; j < lane.length; j++) { const v = lane[j], lead = j > 0 ? lane[j - 1] : null; let gap = 1e9, vl = 0; if (lead) { gap = lead.pos - VLEN - MINGAP - v.pos; vl = lead.v; } if (k !== bay && v.move === "L" && v.pos >= link.bayStart - 1) { // move into the left-turn bay if it has room const bl = link.lanes[bay], blast = bl[bl.length - 1]; if (!blast || blast.pos - VLEN - MINGAP > link.bayStart) { lane.splice(j, 1); v.lane = bay; v.pos = Math.max(v.pos, link.bayStart); bl.push(v); j--; continue; } gap = Math.min(gap, link.bayStart - 0.5 - v.pos); vl = 0; } let go = false; if (!lead && (k === bay || v.move !== "L")) { const dist = link.len - v.pos; if (dist < 60) { go = this.canGo(link, v); if (!go) { gap = Math.min(gap, dist - 0.5); vl = 0; } } } const vs = vl + (gap - vl * TAU) / ((v.v + vl) / (2 * DEC) + TAU); let vn = Math.min(v.v + ACC * dt, v.vmax, Math.max(vs, 0)); vn = Math.max(0, vn - SIGMA * ACC * dt * r() * (vn > 0.5 ? 1 : 0)); if (v.v > 0.5 && vn <= 0.1) this.stats.stops++; v.stopT = vn <= 0.1 ? v.stopT + dt : 0; v.v = vn; v.pos += vn * dt; if (measure) this.stats.loss += dt * (1 - vn / v.vmax); if (v.pos >= link.len) { if (!go && !lead && (k === bay || v.move !== "L")) go = this.canGo(link, v); const tgt = go ? this.target(link, v.move) : null; let ok = go; if (go && tgt) { if (tgt.balance < 0 && r() < -tgt.balance / (tgt.A.q - tgt.balance)) tgt.dummy = 0; // leaves at a driveway else { const nv = { move: this.chooseMove(tgt.A), v: v.v, sf: v.sf, stopT: 0, id: v.id, born: v.born }; ok = this.place(tgt, nv, 0); } } if (ok) { lane.splice(j, 1); j--; this.lastCross[link.lid + "_" + link.dir + "_" + v.move] = t; if (!tgt && measure) this.stats.trips++; } else { v.pos = link.len - 0.01; v.v = 0; } } } } } if (measure) for (const key in this.pending) this.stats.waitEnter += this.pending[key].length * dt; }; Sim.prototype.vehicles = function () { let n = 0; for (const k in this.links) for (const ln of this.links[k].lanes) n += ln.length; return n; }; /* run warm-up + measured hour without drawing; returns delay in vehicle-hours per hour */ function runHeadless(data, plan, seed, opts) { const s = new Sim(data, plan, seed), W = (opts && opts.warmup) || data.meta.warmup_s, M = (opts && opts.measure) || data.meta.measure_s; for (let k = 0; k < W; k++) s.step(false); for (let k = 0; k < M; k++) s.step(true); const h = M / 3600; return { delay: (s.stats.loss + s.stats.waitEnter) / 3600 / h, stops: s.stats.stops, trips: s.stats.trips / h, inserted: s.stats.inserted }; } const api = { Sim, buildProgram, runHeadless }; if (typeof module !== "undefined" && module.exports) module.exports = api; else root.MiniSim = api;})(typeof self !== "undefined" ? self : this);sim/ui.jsDrawing (corridor + intersection close-up), controls and live counters on this page.
/* Page code for the mini-simulator: drawing, controls, live counters. Engine: core.js (window.MiniSim). */(function () { "use strict"; const $ = (id) => document.getElementById(id); const COL = { G: "#1f9d3a", g: "#8fd18f", y: "#e0b000", r: "#c0392b", s: "#c0392b" }; let data, sim, plan, running = false, speed = 5, acc = 0, last = 0, zoomLight = null; function planFromControls() { const base = data.plans[$("ms-plan").value] || data.plans["county-current"]; if (!$("ms-custom").checked) return base; const C = +$("ms-cycle").value, share = +$("ms-share").value / 100, lights = {}; for (const l of data.lights) { const L = data.timing[l.id].L, gmin = data.model.g_min; const g = Math.min(Math.max(share * (C - L), gmin), C - L - gmin); lights[l.id] = { g_main: g, offset: (base.lights[l.id].offset / base.C) * C }; } return { label: "Custom", C, lights }; } function reset() { plan = planFromControls(); try { sim = new MiniSim.Sim(data, plan, +$("ms-seed").value || 1); $("ms-err").textContent = ""; } catch (e) { $("ms-err").textContent = "This timing is not possible: " + e.message; sim = null; } draw(); stats(); } /* ---------- drawing ---------- */ function drawOverview() { const c = $("ms-overview"), x = c.getContext("2d"), W = c.width, H = c.height, L = data.lights; const tot = L[L.length - 1].s + data.geometry.end_len, ys = (s) => 24 + (s * (H - 48)) / tot, cx = 105, k = 60 / data.geometry.side_len; x.fillStyle = "#fff"; x.fillRect(0, 0, W, H); x.strokeStyle = "#bbb"; x.lineWidth = 12; x.beginPath(); x.moveTo(cx, ys(0)); x.lineTo(cx, ys(tot)); x.stroke(); for (const l of L) { x.beginPath(); x.moveTo(cx - 64, ys(l.s)); x.lineTo(cx + 64, ys(l.s)); x.stroke(); } x.fillStyle = "#000"; x.font = "12px Times New Roman"; x.textAlign = "left"; L.forEach((l, i) => { x.fillText(`${i + 1}. ${l.name}`, cx + 68, ys(l.s) + 4); if (sim) { x.fillStyle = COL[sim.signal(l.id, "SB_T", sim.t)] || COL.r; x.fillRect(cx - 9, ys(l.s) - 14, 5, 5); x.fillStyle = COL[sim.signal(l.id, "NB_T", sim.t)] || COL.r; x.fillRect(cx + 4, ys(l.s) + 9, 5, 5); x.fillStyle = "#000"; } }); x.fillText("N ↑", 8, 16); if (!sim) return; for (const key in sim.links) { const lk = sim.links[key], l = L[lk.i]; for (const ln of lk.lanes) for (const v of ln) { let px, py; if (lk.dir === "SB") { px = cx - 3; py = ys(l.s - lk.len + v.pos); } else if (lk.dir === "NB") { px = cx + 3; py = ys(l.s + lk.len - v.pos); } else if (lk.dir === "EB") { px = cx - (lk.len - v.pos) * k; py = ys(l.s) + 3; } else { px = cx + (lk.len - v.pos) * k; py = ys(l.s) - 3; } x.fillStyle = v.v < 0.5 ? "#c0392b" : "#000"; x.fillRect(px - 1.5, py - 1.5, 3, 3); } } } function drawZoom() { const c = $("ms-zoom"), x = c.getContext("2d"), W = c.width, H = c.height, z = 2.2, w = 3.2, cx = W / 2, cy = H / 2; const li = data.lights.findIndex((l) => l.id === zoomLight), l = data.lights[li]; x.fillStyle = "#fff"; x.fillRect(0, 0, W, H); const A = l.approaches, hi = 14; const wid = (d) => (A[d].nt + 1) * w; x.fillStyle = "#d9d9d9"; const nsW = (wid("SB") + wid("NB")) * z, ewW = (wid("EB") + wid("WB")) * z; x.fillRect(cx - wid("SB") * z, 0, nsW, H); x.fillRect(0, cy - wid("WB") * z, W, ewW); x.strokeStyle = "#fff"; x.lineWidth = 1; x.setLineDash([6, 6]); x.beginPath(); x.moveTo(cx, 0); x.lineTo(cx, cy - hi * z); x.moveTo(cx, cy + hi * z); x.lineTo(cx, H); x.moveTo(0, cy); x.lineTo(cx - hi * z, cy); x.moveTo(cx + hi * z, cy); x.lineTo(W, cy); x.stroke(); x.setLineDash([]); // where a car sits on screen: distance from the stop line (dist), lane offset from the centre line (off, metres) const place = (dir, dist, off) => { const d = (dist + hi) * z, o = off * z; if (dir === "SB") return [cx - o, cy - d, 0]; if (dir === "NB") return [cx + o, cy + d, 0]; if (dir === "EB") return [cx - d, cy + o, 1]; return [cx + d, cy - o, 1]; }; const laneOff = (lk, k) => (k === lk.nt ? 0.5 * w : (lk.nt - k + 0.5) * w); if (sim) { const L = data.lights; const drawCar = (dir, dist, off, v) => { const [px, py, horiz] = place(dir, dist, off); if (px < -10 || px > W + 10 || py < -10 || py > H + 10) return; x.fillStyle = v.v < 0.5 ? "#c0392b" : "#111"; if (horiz) x.fillRect(px - 2.5 * z, py - 1 * z, 5 * z, 2 * z); else x.fillRect(px - 1 * z, py - 2.5 * z, 2 * z, 5 * z); }; for (const d of ["NB", "SB", "EB", "WB"]) { const lk = sim.links[l.id + "_" + d]; lk.lanes.forEach((ln, k) => ln.forEach((v) => drawCar(d, lk.len - v.pos, laneOff(lk, k), v))); // signal heads at the stop line: left, through ["L", "T"].forEach((m, j) => { const st = sim.signal(l.id, d + "_" + m, sim.t); const [px, py, horiz] = place(d, -1.5, (m === "L" ? 0.5 : 1.5 + j * 0) * w + (m === "T" ? 0 : 0)); x.fillStyle = COL[st] || COL.r; if (horiz) x.fillRect(px - 1.5, py - 3, 3, 6); else x.fillRect(px - 3, py - 1.5, 6, 3); }); } // cars that just left this intersection on Big Bend (they are on the next light's approach) if (li + 1 < L.length) { const lk = sim.links[L[li + 1].id + "_SB"]; lk.lanes.forEach((ln, k) => ln.forEach((v) => { if (v.pos < 160) drawCar("NB", -2 * hi - v.pos, -laneOff(lk, k), v); })); } if (li - 1 >= 0) { const lk = sim.links[L[li - 1].id + "_NB"]; lk.lanes.forEach((ln, k) => ln.forEach((v) => { if (v.pos < 160) drawCar("SB", -2 * hi - v.pos, -laneOff(lk, k), v); })); } } x.fillStyle = "#000"; x.font = "14px Times New Roman"; x.textAlign = "left"; x.fillText(`${li + 1}. Big Bend & ${l.name}`, 8, 18); x.font = "12px Times New Roman"; x.fillText("Big Bend ↑ N", cx + nsW / 2 + 4, 34); x.fillText(l.cross, 8, cy - wid("WB") * z - 6); x.fillText("■ moving ", 8, H - 10); x.fillStyle = "#c0392b"; x.fillText("■ stopped", 70, H - 10); } function draw() { drawOverview(); drawZoom(); } function clock(t) { const W = data.meta.warmup_s, sec = Math.max(0, t - W), base = 17 * 3600 + sec - (t < W ? (W - t) : 0); const h = Math.floor(base / 3600), m = Math.floor((base % 3600) / 60), s = Math.floor(base % 60); return `${((h + 11) % 12) + 1}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")} PM`; } function stats() { if (!sim) return; const W = data.meta.warmup_s, meas = Math.max(0, sim.t - W), hrs = meas / 3600; $("ms-clock").textContent = clock(sim.t) + (sim.t < W ? " (warming up: the road fills before 5:00 PM)" : ""); $("ms-cars").textContent = sim.vehicles(); const wait = Object.values(sim.pending).reduce((a, q) => a + q.length, 0); $("ms-waiting").textContent = wait; $("ms-delay").textContent = hrs > 0.02 ? ((sim.stats.loss + sim.stats.waitEnter) / 3600 / hrs).toFixed(0) : "–"; $("ms-trips").textContent = hrs > 0.02 ? (sim.stats.trips / hrs).toFixed(0) : "–"; $("ms-plan-label").textContent = plan.label + ` · cycle ${plan.C.toFixed(0)} s`; } function frame(ts) { if (running && sim) { acc += ((ts - last) / 1000) * speed; let n = 0; while (acc >= 1 && n < 400) { sim.step(sim.t >= data.meta.warmup_s); acc -= 1; n++; } if (sim.t >= data.meta.warmup_s + data.meta.measure_s) running = false; draw(); stats(); } last = ts; requestAnimationFrame(frame); } function runFull() { const p = planFromControls(); const btn = $("ms-full"); btn.disabled = true; btn.textContent = "Running…"; setTimeout(() => { try { const seeds = [1, 2, 3], r = seeds.map((s) => MiniSim.runHeadless(data, p, s)); const m = r.reduce((a, x) => a + x.delay, 0) / r.length; const sumo = p.sumo_delay ? p.sumo_delay.toFixed(0) : "not run in SUMO"; const row = document.createElement("tr"); row.innerHTML = `<td>${p.label}</td><td>${p.C.toFixed(0)}</td><td>${m.toFixed(0)}</td><td>${sumo}</td>`; $("ms-results").appendChild(row); $("ms-results-wrap").hidden = false; } catch (e) { $("ms-err").textContent = "This timing is not possible: " + e.message; } btn.disabled = false; btn.textContent = "Run the full hour instantly"; }, 30); } function init(d) { data = d; zoomLight = data.lights[data.lights.length - 1].id; const sel = $("ms-plan"); for (const [k, p] of Object.entries(data.plans)) { const o = document.createElement("option"); o.value = k; o.textContent = p.label; sel.appendChild(o); } const zs = $("ms-zoomsel"); data.lights.forEach((l, i) => { const o = document.createElement("option"); o.value = l.id; o.textContent = `${i + 1}. ${l.name}`; zs.appendChild(o); }); zs.value = zoomLight; const syncCustom = () => { const on = $("ms-custom").checked; $("ms-cycle").disabled = !on; $("ms-share").disabled = !on; $("ms-cycle-v").textContent = $("ms-cycle").value + " s"; $("ms-share-v").textContent = $("ms-share").value + "%"; }; ["ms-plan", "ms-custom", "ms-cycle", "ms-share", "ms-seed"].forEach((id) => $(id).addEventListener("input", () => { syncCustom(); reset(); })); zs.addEventListener("input", () => { zoomLight = zs.value; draw(); }); $("ms-play").addEventListener("click", () => { running = !running; $("ms-play").textContent = running ? "Pause" : "Play"; }); $("ms-reset").addEventListener("click", () => { running = false; $("ms-play").textContent = "Play"; reset(); }); $("ms-skip").addEventListener("click", () => { if (!sim) return; while (sim.t < data.meta.warmup_s) sim.step(false); draw(); stats(); }); document.querySelectorAll("[data-speed]").forEach((b) => b.addEventListener("click", () => { speed = +b.dataset.speed; document.querySelectorAll("[data-speed]").forEach((x) => x.classList.toggle("on", x === b)); })); $("ms-full").addEventListener("click", runFull); syncCustom(); reset(); requestAnimationFrame(frame); if (location.hash === "#demo" && sim) { while (sim.t < data.meta.warmup_s + 1800) sim.step(sim.t >= data.meta.warmup_s); draw(); stats(); } } fetch("sim/data.json").then((r) => r.json()).then(init).catch((e) => { $("ms-err").textContent = "Could not load the simulator data: " + e; });})();src/sim_export.pyExports the corridor, County phases, timing plans and SUMO results the simulator reads (sim/data.json).
"""Export what the browser mini-simulator needs -> build/site/sim/data.json.Same sources as the SUMO pipeline: build/corridor.json (measured volumes, turn shares, lanes, spacing, speeds),build/sumo/demand.json (mid-block balancing flows), data/measured/county_timing.json (County phase sequence),plans/*.json (the timing plans), build/results_summary.json (SUMO delay per plan, for comparison)."""import json, tomllib, datetime, pathlib, syssys.path.insert(0, str(pathlib.Path(__file__).parent))from common import ROOT, BUILD, corridorimport plans as PLABELS = {"county-current": "County's current timing (real)", "formula-optimum-standin": "Math model's best (stand-in)", "study1-sumo-loop": "Optimized in SUMO (Study 1)", "sumo-coordinated": "SUMO's built-in tool", "webster-common": "Webster (common cycle)", "webster-per-light": "Webster (per light)", "equal-split": "Equal split"}ORDER = ["county-current", "formula-optimum-standin", "study1-sumo-loop", "sumo-coordinated", "webster-common", "equal-split"]def main(): cor = corridor(); cfg = tomllib.load(open(ROOT/"config/corridor.toml", "rb")) dem = json.load(open(BUILD/"sumo/demand.json")); raw = json.load(open(ROOT/"data/measured/county_timing.json")) S = json.load(open(BUILD/"results_summary.json")) END, SIDE = 300.0, 200.0 s = END; lights = [] for i, l in enumerate(cor["lights"]): if i > 0: s += cor["links"][i-1]["length_m"] A = l["approaches"] lights.append(dict(id=l["id"], name=l["name"], cross=l["cross_street"], s=round(s, 1), approaches={d: dict(q=A[d]["q_vph"], L=A[d]["turn_share"]["L"], T=A[d]["turn_share"]["T"], R=A[d]["turn_share"]["R"], nt=(2 if d in ("NB", "SB") else max(A[d]["lanes"]-1, 1))) for d in A})) side_speed = {"Forest Park Parkway": 17.88, "Clayton Road": 15.65} timing = {} for l in cor["lights"]: T = l["timing"]; ph = raw[l["id"]]["phases"] timing[l["id"]] = dict(phases={k: dict(movement=v["movement"], yellow=v["yellow"], all_red=v["all_red"] or 0.0, min_green=v.get("min_green") or 4.0) for k, v in ph.items()}, splits=T["splits"], main_phases=T["main_phases"], clearance_main=T["clearance_main_s"], L=T["L_s"], C=T["C_s"], offset_county=T["offset_county_s"]) plans = {} for name in ORDER: try: p = P.load(name) except FileNotFoundError: continue plans[name] = dict(label=LABELS.get(name, name), C=p["C"], lights={k: dict(g_main=v["g_main"], offset=v["offset_s"]) for k, v in p["lights"].items()}, sumo_delay=S.get(name, {}).get("delay_mean"), sumo_sd=S.get(name, {}).get("delay_sd")) out = dict(meta=dict(built=datetime.date.today().isoformat(), design_hour=cor["meta"].get("design_hour", "17:00"), warmup_s=dem["warmup_s"], measure_s=dem["measure_s"], right_on_red=cfg.get("sumo", {}).get("right_on_red", True)), geometry=dict(end_len=END, side_len=SIDE, bay=cfg.get("network", {}).get("bay_m", 90.0), link_speed=[k["speed_mps"] for k in cor["links"]], side_speed={l["id"]: side_speed.get(l["cross_street"], 13.41) for l in cor["lights"]}), lights=lights, balancing=[dict(link=b["link"], dir=b["direction"], vph=b["balance_vph"]) for b in dem["balancing"]], timing=timing, plans=plans, model=dict(g_min=cor["params"]["g_min_s"], C_min=cor["params"]["C_min_s"], C_max=cor["params"]["C_max_s"])) d = BUILD/"site/sim"; d.mkdir(parents=True, exist_ok=True) json.dump(out, open(d/"data.json", "w"), indent=1) print(f"wrote sim/data.json: {len(lights)} lights, {len(plans)} plans")if __name__ == "__main__": main()sim/validate.jsRuns every plan through the mini-simulator and compares delays and ranking with SUMO.
// Run every plan through the mini-simulator (warm-up + measured hour, several seeds) and compare with SUMO.// Usage: node sim/validate.js [seeds] -> build/site/sim/validation.jsonconst path = require("path"), fs = require("fs");const S = require("./core.js");const ROOT = path.join(__dirname, "..");const data = JSON.parse(fs.readFileSync(path.join(ROOT, "build/site/sim/data.json")));const seeds = +(process.argv[2] || 5), rows = [];for (const [name, p] of Object.entries(data.plans)) { const res = []; for (let s = 1; s <= seeds; s++) res.push(S.runHeadless(data, p, s)); const m = res.reduce((a, r) => a + r.delay, 0) / seeds; const sd = Math.sqrt(res.reduce((a, r) => a + (r.delay - m) ** 2, 0) / Math.max(seeds - 1, 1)); rows.push({ plan: name, label: p.label, mini: m, mini_sd: sd, sumo: p.sumo_delay, trips: res.reduce((a, r) => a + r.trips, 0) / seeds }); console.log(`${name.padEnd(24)} mini ${m.toFixed(1).padStart(6)} ± ${sd.toFixed(1).padStart(4)} SUMO ${p.sumo_delay.toFixed(1).padStart(6)} trips/h ${(rows.at(-1).trips).toFixed(0)}`);}const rank = (k) => { const o = [...rows].sort((a, b) => a[k] - b[k]).map((r) => r.plan); return Object.fromEntries(o.map((p, i) => [p, i + 1])); };const rm = rank("mini"), rs = rank("sumo"); const n = rows.length;const d2 = rows.reduce((a, r) => a + (rm[r.plan] - rs[r.plan]) ** 2, 0); const spearman = 1 - (6 * d2) / (n * (n * n - 1));rows.forEach((r) => { r.rank_mini = rm[r.plan]; r.rank_sumo = rs[r.plan]; });fs.writeFileSync(path.join(ROOT, "build/site/sim/validation.json"), JSON.stringify({ seeds, spearman, rows }, null, 1));console.log("rank agreement (Spearman):", spearman.toFixed(2));Step 9 · Tables, charts and this website
Everything you see on the site is generated by these.
src/report_tables.pyReport tables (provenance, volumes, timing, results, validation) and figures.
"""Tables + figures for the report (Data / Setup / Results / Study 1) -> build/report/.Every table is regenerated from build/ outputs, so it always matches the current data and runs. provenance.md every model input: value, measured / derived / assumed, evidence volumes.md PM peak-hour volumes and turn shares per light and approach (+ lanes, effective s) timing.md County PM timing (pattern, cycle, offset, phase splits) and its 2-phase reduction results.md every plan: SUMO delay (mean ± sd over seeds), stops, throughput, formula delay validation.md simulated vs counted volumes (GEH) study1.md Study 1 summary (if run) figures: corridor.png, results.png, (study1 figures live in build/study1/)"""import json, sys, pathlib, tomllibsys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, ROOT, corridorimport plans as POUT = BUILD/"report"def md_table(head, rows): s = "| " + " | ".join(head) + " |\n|" + "|".join("---" for _ in head) + "|\n" return s + "".join("| " + " | ".join(str(x) for x in r) + " |\n" for r in rows)def main(): OUT.mkdir(parents=True, exist_ok=True) cor = corridor(); asm = tomllib.load(open(ROOT/"config/assumptions.toml", "rb")) # provenance rows = [] for l in cor["lights"]: for d, A in l["approaches"].items(): rows.append([f"{l['id']} {l['name']}", d, "volume q", f"{A['q_vph']:.0f} veh/h", A["q_source"], A["q_evidence"]]) rows.append([f"{l['id']} {l['name']}", d, "turn shares L/T/R", "/".join(f"{A['turn_share'][k]:.2f}" for k in "LTR"), A["turn_source"], A["turn_evidence"][:120]]) rows.append([f"{l['id']} {l['name']}", d, "lanes", A["lanes"], A["lanes_source"], ""]) rows.append([f"{l['id']} {l['name']}", d, "sat. flow s (model)", f"{A['s_vph']:.0f} veh/h", A["s_source"], A.get("s_evidence", f"{A['lanes']} lanes x {cor['params']['sat_flow_per_lane_vph']}")]) T = l.get("timing") if T: rows.append([f"{l['id']} {l['name']}", "-", "lost time L", f"{T['L_s']} s", "measured", f"County sheet {T['sheet']} ({T['sheet_date']}), {T['lost_time_basis']}"]) rows.append([f"{l['id']} {l['name']}", "-", "current timing", f"C {T['C_s']} s, offset {T['offset_county_s']} s", "measured", f"County pattern {T['pattern']} (PM weekday)"]) for k in cor["links"]: rows.append([f"link {k['from']}->{k['to']}", "-", "length / speed / tau", f"{k['length_m']} m / {k['speed_mps']} m/s / {k['tau_s']} s", f"{k['length_source']} / {k['speed_source']}", k["length_evidence"]]) p = cor["params"] for key, src in (("p", "model_source"), ("g_min_s", "model_source"), ("C_min_s", "model_source"), ("C_max_s", "model_source"), ("x_max", "model_source")): rows.append(["model", "-", key, p[key], p[src], asm["model"]["evidence"]]) dem = json.load(open(BUILD/"sumo/demand.json")) for b in dem.get("balancing", []): rows.append([f"link {b['link']}", b["direction"], "mid-block balancing flow", f"{b['balance_vph']:+.0f} veh/h", b["source"], b["evidence"]]) for key in ("bay_m",): v = tomllib.load(open(ROOT/"config/corridor.toml", "rb")).get("network", {}).get(key) rows.append(["network", "-", "left-turn bay length", f"{v} m", "assumed", "typical urban 75-100 m; not measured"]) (OUT/"provenance.md").write_text("# Input provenance\n\n" + md_table(["where", "approach", "input", "value", "source", "evidence"], rows)) # volumes rows = [[f"{l['id']} {l['name']}", d, f"{A['q_vph']:.0f}", *(f"{A['turn_share'][k]:.2f}" for k in "LTR"), A["lanes"], f"{A['s_vph']:.0f}", A["q_source"]] for l in cor["lights"] for d, A in l["approaches"].items()] (OUT/"volumes.md").write_text(f"# PM peak hour ({cor['meta'].get('design_hour','')}) volumes\n\n" + md_table(["light", "approach", "veh/h", "L", "T", "R", "lanes", "s (model)", "source"], rows)) # timing rows = [] for l in cor["lights"]: T = l.get("timing") if T: rows.append([f"{l['id']} {l['name']}", T["sheet_date"], T["pattern"], T["C_s"], T["offset_county_s"], " ".join(f"{k}:{v}" for k, v in sorted(T["splits"].items(), key=lambda kv: int(kv[0]))), T["main_block_s"], T["side_block_s"], T["g_main_s"], T["L_s"]]) (OUT/"timing.md").write_text("# County timing, PM pattern\n\n" + md_table( ["light", "sheet date", "pattern", "cycle", "offset", "phase splits (s)", "Big Bend block", "cross block", "g_main (2-phase)", "L"], rows)) # results S = json.load(open(BUILD/"results_summary.json")) if (BUILD/"results_summary.json").exists() else {} rows = [] for name, v in sorted(S.items(), key=lambda kv: kv[1]["delay_mean"]): try: pl = P.load(name); fd = P.formula_delay(cor, pl); src = pl["source"]; C = pl["C"] except FileNotFoundError: fd, src, C = None, "", "" rows.append([name, C, f"{v['delay_mean']:.1f} ± {v['delay_sd']:.1f}", f"{v['stops_mean']:.2f}", f"{v['throughput_mean']:.0f}", "n/a" if fd is None else f"{fd:.1f}", v["seeds"], src]) (OUT/"results.md").write_text("# Plan comparison (SUMO, corridor delay in the PM peak hour)\n\n" + md_table( ["plan", "cycle (s)", "SUMO delay veh-h/h", "stops/veh", "throughput veh/h", "formula delay veh-h/h", "seeds", "source"], rows)) # validation if (BUILD/"validation.json").exists(): V = json.load(open(BUILD/"validation.json")) (OUT/"validation.md").write_text("# Validation: simulated vs counted volumes\n\n" + md_table( ["light", "approach", "kind", "counted veh/h", "simulated veh/h", "GEH"], [[f"{r['light']} {r['name']}", r["approach"], r["kind"], r["target_vph"], r["sim_vph"], r["geh"]] for r in V])) if (BUILD/"study1/summary.json").exists(): s = json.load(open(BUILD/"study1/summary.json")) (OUT/"study1.md").write_text("# Study 1 summary\n\n```json\n" + json.dumps(s, indent=1) + "\n```\n") figures(cor, S) print("wrote", ", ".join(sorted(x.name for x in OUT.iterdir())))def figures(cor, S): import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt f, ax = plt.subplots(figsize=(4, 6)) xs = [l["lon"] for l in cor["lights"]]; ys = [l["lat"] for l in cor["lights"]] ax.plot(xs, ys, "-", color="0.6"); ax.scatter(xs, ys, s=60, zorder=3) for l in cor["lights"]: A = l["approaches"] ax.annotate(f"{l['name']} (#{l['id']})\nNB {A['NB']['q_vph']:.0f} SB {A['SB']['q_vph']:.0f}\nEB {A['EB']['q_vph']:.0f} WB {A['WB']['q_vph']:.0f}", (l["lon"], l["lat"]), xytext=(8, -4), textcoords="offset points", fontsize=7) for k, (a, b) in zip(cor["links"], zip(cor["lights"], cor["lights"][1:])): ax.annotate(f"{k['length_m']:.0f} m", ((a["lon"]+b["lon"])/2, (a["lat"]+b["lat"])/2), xytext=(-40, 0), textcoords="offset points", fontsize=7) ax.set_title("Big Bend Blvd corridor, PM peak (veh/h)", fontsize=9); ax.set_xticks([]); ax.set_yticks([]) ax.set_xlim(min(xs)-0.004, max(xs)+0.012); f.tight_layout(); f.savefig(OUT/"corridor.png", dpi=150) if S: items = sorted(S.items(), key=lambda kv: kv[1]["delay_mean"]) f, ax = plt.subplots(figsize=(6, 3.2)) ax.barh([k for k, _ in items], [v["delay_mean"] for _, v in items], xerr=[v["delay_sd"] for _, v in items], color="tab:blue") ax.invert_yaxis(); ax.set_xlabel("corridor delay, SUMO (veh-h per hour)"); ax.set_title("Timing plans compared", fontsize=9) f.tight_layout(); f.savefig(OUT/"results.png", dpi=150)if __name__ == "__main__": main()src/site_page.pyGenerates the main website page from the results.
"""Public progress page for the group -> build/site/ (index.html + figures). Regenerated from build/; never hand-edit.Deploy: npx wrangler pages deploy build/site --project-name bigbend-signal-study"""import json, html, shutil, pathlib, sys, datetimesys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, ROOT, corridorimport plans as Pimport site_figs as Fimport site_explain as XSITE = BUILD/"site"E = html.escapedef tbl(head, rows, cls=""): return (f'<div class="tw"><table class="{cls}"><thead><tr>' + "".join(f"<th>{h}</th>" for h in head) + "</tr></thead><tbody>" + "".join("<tr>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>" for r in rows) + "</tbody></table></div>")def main(): SITE.mkdir(parents=True, exist_ok=True) for src, dst in ((BUILD/"report/results.png", "results.png"), (BUILD/"report/corridor.png", "corridor.png"), (BUILD/"study1/prediction.png", "study1-prediction.png"), (BUILD/"study1/convergence.png", "study1-convergence.png")): shutil.copy(src, SITE/dst) cor = corridor(); S = json.load(open(BUILD/"results_summary.json")); V = json.load(open(BUILD/"validation.json")) s1 = json.load(open(BUILD/"study1/summary.json")); dem = json.load(open(BUILD/"sumo/demand.json")) cur = S["county-current"]["delay_mean"]; fo = S["formula-optimum-standin"]["delay_mean"]; sl = S["study1-sumo-loop"]["delay_mean"] inter = [r for r in V if r["kind"] == "interior"]; ok = sum(r["geh"] < 5 for r in inter) tot = sum(A["q_vph"] for l in cor["lights"] for A in l["approaches"].values()) today = datetime.date.today().strftime("%B %-d, %Y") # tables vol = [[f"{l['name']} (#{l['id']})", d, f"{A['q_vph']:.0f}", f"{A['turn_share']['L']:.2f}", f"{A['turn_share']['T']:.2f}", f"{A['turn_share']['R']:.2f}", A["lanes"], E(A["q_ref"].split("/")[-1])] for l in cor["lights"] for d, A in l["approaches"].items()] tim = [] for l in cor["lights"]: T = l["timing"] tim.append([f"{l['name']} (#{l['id']})", E(T["sheet_date"]), T["pattern"], T["C_s"], T["offset_county_s"], " ".join(f"{k}:{v}" for k, v in sorted(T["splits"].items(), key=lambda kv: int(kv[0]))), T["main_block_s"], T["side_block_s"], T["L_s"]]) links = [[f"{k['from']} → {k['to']}", f"{k['length_m']:.0f}", f"{k['speed_mps']:.1f}", f"{k['tau_s']:.1f}"] for k in cor["links"]] res = [] for name, v in sorted(S.items(), key=lambda kv: kv[1]["delay_mean"]): pl = P.load(name); fd = P.formula_delay(cor, pl) res.append([f"<b>{E(name)}</b>" if name in ("county-current",) else E(name), f"{pl['C']:.1f}", f"{v['delay_mean']:.1f} ± {v['delay_sd']:.1f}", f"{100*(v['delay_mean']/cur-1):+.0f}%", f"{v['stops_mean']:.2f}", f"{v['throughput_mean']:.0f}", "—" if fd is None else f"{fd:.1f}", E(pl["source"])]) val = [[f"{r['name']} (#{r['light']})", r["approach"], r["kind"], r["target_vph"], r["sim_vph"], f"{r['geh']:.2f}"] for r in V] bal = [[b["link"], b["direction"], f"{b['propagated_vph']:.0f}", f"{b['target_vph']:.0f}", f"{b['balance_vph']:+.0f}"] for b in dem["balancing"]] prov = [] for l in cor["lights"]: for d, A in l["approaches"].items(): prov.append([f"#{l['id']} {d}", "volume", f"{A['q_vph']:.0f} veh/h", A["q_source"], E(A["q_evidence"])]) prov.append([f"#{l['id']} {d}", "saturation flow (model)", f"{A['s_vph']:.0f} veh/h", A["s_source"], E(A.get("s_evidence", ""))]) prov.append([f"#{l['id']}", "lost time L", f"{l['timing']['L_s']} s", "measured", E(f"County sheet, {l['timing']['lost_time_basis']}")]) pm = cor["params"] for k in ("p", "g_min_s", "C_min_s", "C_max_s", "x_max"): prov.append(["model", k, pm[k], pm["model_source"], "model defaults from the Nov 10 formulation"]) prov.append(["network", "left-turn bay length", "90 m", "assumed", "typical urban 75–100 m; not measured"]) pipeline = [ ["1", "Parse + verify County data", "County PDFs (timing sheets, turning counts)", "count CSVs, timing JSON; every count checked against the sheet's printed totals"], ["2", "Build corridor dataset", "config, raw + measured data", "corridor.json: every number tagged measured / derived / assumed"], ["3", "Optimizer input", "corridor.json", "optimizer_input.json / .csv for the model"], ["4", "SUMO network", "corridor.json", "4 signals at real spacing, real approach lanes + left bays, posted speeds"], ["5", "SUMO demand", "corridor.json", "entry flows, measured turn shares, mid-block balancing flows"], ["6", "Timing plans", "corridor.json, County timing", "baselines, County current plan, formula optimum"], ["7", "Simulate", "plans", "10 seeded runs per plan: delay, stops, throughput"], ["8", "Validate", "runs vs counts", "GEH per approach"], ["9", "Tables + figures", "everything above", "report tables, figures, this page"], ] css = """:root{--bg:#fff;--fg:#000;--mut:#444;--rule:#000;--hair:#bbb;--shade:#f3f3f3;color-scheme:light}*{box-sizing:border-box}html{background:var(--bg)}body{margin:0;background:var(--bg);color:var(--fg);font-family:"Times New Roman",Times,"Liberation Serif",serif;font-size:17px;line-height:1.5; padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:40px 64px}main{max-width:860px;margin:0 auto}header{text-align:center;border-bottom:2px solid var(--rule);padding-bottom:18px;margin-bottom:22px}h1{font-size:28px;font-weight:700;line-height:1.2;margin:0 0 8px;text-wrap:balance}.meta{color:var(--mut);font-size:15px;margin:2px 0}h2{font-size:20px;margin:34px 0 8px;border-bottom:1px solid var(--rule);padding-bottom:3px}h3{font-size:17px;margin:20px 0 6px;font-style:italic;font-weight:400}p,li{max-width:72ch} ol,ul{padding-left:22px}.abstract{margin:0 auto 10px;max-width:72ch;font-size:16px}.abstract b{font-variant:small-caps;letter-spacing:.04em}.tw{overflow-x:auto;margin:8px 0 4px}table{border-collapse:collapse;width:100%;font-size:14.5px;font-variant-numeric:tabular-nums}thead th{border-top:1.5px solid var(--rule);border-bottom:1px solid var(--rule);text-align:left;padding:5px 7px;font-weight:700;vertical-align:bottom}td{border-bottom:1px solid var(--hair);padding:4px 7px;vertical-align:top}tbody tr:last-child td{border-bottom:1.5px solid var(--rule)}.cap{font-size:14px;color:var(--mut);margin:2px 0 14px}figure{margin:14px 0}figure img,figure svg{display:block;max-width:100%;border:1px solid var(--hair);background:#fff}figcaption{font-size:14px;color:var(--mut);margin-top:4px}.figs{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px}.figs>*{min-width:0}code,pre{font-family:"Courier New",Courier,monospace;font-size:13.5px}pre{background:var(--shade);padding:10px 12px;overflow-x:auto;border:1px solid var(--hair)}.status td:nth-child(2){font-weight:700;white-space:nowrap}details{border-top:1px solid var(--hair);margin-top:10px;padding-top:6px}summary{cursor:pointer;font-weight:700}details.explain{border:1px solid var(--rule);border-top:1px solid var(--rule);margin:6px 0 12px;padding:0}details.explain>summary{font-weight:400;font-style:italic;font-size:15px;padding:4px 10px;list-style:none}details.explain>summary::-webkit-details-marker{display:none}details.explain>summary::before{content:"▸ "}details.explain[open]>summary::before{content:"▾ "}details.explain[open]>summary{border-bottom:1px solid var(--hair)}.exp{padding:4px 14px 8px;font-size:16px}.exp p,.exp li{max-width:none}a{color:var(--fg)}footer{margin-top:40px;border-top:1px solid var(--rule);padding-top:8px;font-size:13px;color:var(--mut)}""" status = [ ["Real corridor data: County timing + turning counts for all 4 signals, verified", "Done"], ["SUMO simulation of the corridor, validated against counts", "Done"], ["All timing plans simulated (10 seeds each); results tables + figures", "Done"], ["Study 1 (simulator-in-the-loop vs formula model)", "Done (first full run)"], ["Reproducible code package + README (one command)", "Done (data/simulation part)"], ["Michael + Noah's optimizer (signal_opt.py) plugged in", "Open: stand-in used"], ["Group agreement on the modelling choices in §8", "Open"], ["Written report sections (Data, Setup, Study 1)", "Open"], ["Full report (8–12 pp), Contributions, submission + code to TA", "Open"], ] page = rf"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Big Bend Signal Timing Study</title><meta name="description" content="CSE 5403 traffic-signal project: data, simulation and validation progress report"><style>{css}</style></head><body><main><nav style="font-size:15px;text-align:right"><a href="code.html" style="color:#000">Simulation + Code →</a></nav><header><h1>Optimizing Traffic-Signal Timing on Big Bend Boulevard:<br>Data, Simulation and Validation</h1><p class="meta">CSE 5403 Algorithms for Nonlinear Optimization · Washington University in St. Louis · Fall 2026</p><p class="meta">Progress report from the data and simulation workstream · {today}</p></header><p class="abstract"><b>Summary.</b> 4 County signals on Big Bend Blvd · weekday 5–6 PM · real County timing + counts · SUMO simulation validated ({ok}/{len(inter)} GEH < 5) · County plan {cur:.0f} veh-h/h → model plan {fo:.0f} ({100*(1-fo/cur):.0f}% less) → simulator-optimized {sl:.0f} ({100*(1-sl/cur):.0f}% less). Preliminary: optimizer is our stand-in for the group's code.</p><h2>1. Corridor and scope</h2><p>4 signals, north → south · main road Big Bend (NB/SB), cross streets (EB/WB) · design hour weekday 5–6 PM · {tot:,.0f} veh/h total approach volume (summed over the 4 intersections).</p><figure>{F.map_svg(cor)}<figcaption>Figure 1. Study area, St. Louis County (Clayton / University City): the four signals and the Big Bend corridor (bold).</figcaption></figure><div class="figs"><figure><img src="corridor.png" alt="Schematic of the four signals with PM approach volumes and spacing"><figcaption>Figure 2. Schematic: PM approach volumes (veh/h) and spacing.</figcaption></figure><div>{tbl(["link", "length (m)", "speed (m/s)", "travel time τ (s)"], links)}<p class="cap">Table 1. Links between consecutive signals (length from County coordinates; posted speeds from MoDOT 2025).</p></div></div><h2>2. Data</h2><h3>2.1 Sources</h3>{tbl(["source", "what we use", "status"], [ ["St. Louis County timing sheets (4 signals)", "PM pattern 37: cycle, splits, offsets, yellow/all-red, phase sequence", "measured"], ["St. Louis County turning counts (4 signals)", "5–6 PM volumes by approach + L/T/R · Forsyth 2017, FPP 2021, Wydown 2025, Clayton 2026", "measured · verified vs sheet totals"], ["MoDOT 2025", "lanes, speed limits", "measured"], ["County signal inventory", "signal IDs, ownership, coordinates", "measured"], ["OpenStreetMap", "approach lanes at the stop line", "measured"]])}<p class="cap">Every number is tagged measured / derived / assumed (appendix).</p><h3>2.2 PM peak-hour volumes</h3>{tbl(["intersection", "approach", "veh/h", "L", "T", "R", "lanes", "source"], vol)}<p class="cap">Table 2. Measured approach volumes and turning shares, 5:00–6:00 PM. Lanes are approach lanes at the stop line.</p><h3>2.3 Current signal timing (County, PM pattern)</h3>{tbl(["intersection", "sheet", "pattern", "cycle (s)", "offset (s)", "phase splits (s)", "Big Bend block", "cross block", "lost time L (s)"], tim)}<p class="cap">Table 3. County timing, weekday PM. Splits include yellow and all-red. Lost time is the total clearance along the phase sequence.</p><h2>3. Method</h2><h3>3.1 Pipeline</h3>{tbl(["step", "what", "input", "output"], pipeline)}<p class="cap">Table 4. One command (<code>./run_all.sh</code>) reruns all steps. <a href="code.html" style="color:#000">Simulation + Code: live mini-simulation and every program →</a></p><h3>3.2 Timing model</h3><p>Variables: cycle <i>C</i>, Big Bend green <i>g<sub>i</sub></i>, offsets · objective: Webster + platoon delay · constraints: 60 ≤ C ≤ 150 s, min greens, x ≤ 0.9 · solver: multistart SLSQP.</p><h3>3.3 Simulation</h3>{tbl(["setting", "value"], [ ["software", "SUMO 1.28"], ["network", "4 signals at real spacing · real approach lanes · left-turn bays · posted speeds"], ["demand", "measured volumes + turn shares · mid-block balancing flows (Table 5)"], ["signals", "County phase sequence (incl. left arrows), scaled to each plan · right turn on red"], ["run", "15 min warm-up + 60 min measured · 10 seeds per plan"], ["metric", "delay = time lost on corridor links + time waiting to enter (veh-h per hour)"]])}{tbl(["link", "direction", "propagated veh/h", "counted veh/h", "balancing veh/h"], bal)}<p class="cap">Table 5. Mid-block balancing flows: counted volume into a signal minus the volume propagated from the previous signal.</p><h2>4. Validation</h2><p>Simulated vs counted volumes, GEH < 5 = pass · interior approaches: <b>{ok}/{len(inter)} pass</b>.</p>{tbl(["intersection", "approach", "kind", "counted veh/h", "simulated veh/h", "GEH"], val)}<p class="cap">Table 6. Simulated vs counted volumes under the County's current timing (mean of 10 seeds).</p><h2>5. Results</h2>{tbl(["plan", "cycle (s)", "SUMO delay, veh-h/h (mean ± sd)", "vs County", "stops / veh", "throughput veh/h", "formula delay", "source"], res)}<p class="cap">Table 7. All plans, 10 seeds each. formula-optimum-standin = our stand-in for the group's optimizer.</p><figure>{F.results_svg(S)}<figcaption>Figure 3. Simulated corridor delay by plan; County's current timing in black (error bars: one standard deviation over seeds).</figcaption></figure><h2>6. Study 1: simulator-in-the-loop vs formula model</h2>{tbl(["test", "result"], [ ["Does the formula rank plans like SUMO? ({s1['prediction']['n_plans']} random plans)", "weakly · Spearman ρ = {s1['prediction']['spearman']:.2f}"], ["Formula optimizer", "{fo:.0f} veh-h/h · {s1['formula_optimizer']['seconds']} s"], ["Simulator-in-the-loop (Nelder–Mead, {s1['sumo_loop']['evaluations']} evals)", "{sl:.0f} veh-h/h · ~{s1['sumo_loop']['seconds']//60} min"]])}<div class="figs"><figure>{F.prediction_svg(BUILD/"study1/prediction.csv")}<figcaption>Figure 4. Formula vs simulated delay, 30 random feasible plans.</figcaption></figure><figure>{F.convergence_svg(BUILD/"study1/optimization.csv")}<figcaption>Figure 5. Simulator-in-the-loop optimization: best delay found vs evaluations.</figcaption></figure></div><h2>7. Interfaces for the optimizer</h2><p>In: <code>optimizer_input.json</code> (q, s per approach; τ per link; parameters) · Out: plan file:</p><pre>{{ "name": "...", "C": 124.7, "lights": {{ "051": {{"g_main": 37.0, "offset_s": 0.0}}, "040": {{"g_main": 49.8, "offset_s": 52.7}}, ... }} }}g_main = Big Bend green (s); cross-street green = C - L_i - g_mainoffset_s = start of the Big Bend block relative to Forest Park Pkwy (s)</pre><h2>8. Modelling choices for the group to confirm</h2><ol><li>Lost time + capacity computed along the real signal sequence (L ≈ 21–27 s) · needs Michael + Noah's OK · switchable back.</li><li>Real signals use left-turn arrows · simulation includes them · revisit "future work".</li><li>Simulated network generated from measured geometry (full OpenStreetMap version jammed).</li><li>Assumed: 1,800 veh/h/lane · p = 0.8 · 90 m left bays · right turn on red.</li></ol><h2>9. Status</h2>{tbl(["item", "status"], [[a, b] for a, b in status], "status")}<h2>10. Reproducing the results</h2><pre>cd pipeline./run_all.sh # data, network, plans, 10-seed runs, validation, tables.venv/bin/python src/study1.py --n-random 30 --budget 120 # Study 1</pre><p>Inputs: <code>data/</code>, <code>config/</code> · outputs: <code>build/</code> (regenerated) · <a href="code.html" style="color:#000">Simulation + Code: all code, settings and data, plus a zip →</a></p><details><summary>Appendix: where every number comes from</summary>{tbl(["where", "input", "value", "source", "evidence"], prov)}</details><footer>Generated from the project pipeline on {today}. All values on this page are produced by the code; nothing is typed in by hand.</footer></main></body></html>""" vals = dict(cur=cur, fo=fo, sl=sl, ok=ok, n_inter=len(inter), rho=s1["prediction"]["spearman"], pct_fo=100*(1-fo/cur)) heads = {"1": "<h2>1. Corridor and scope</h2>", "2": "<h2>2. Data</h2>", "3": "<h2>3. Method</h2>", "4": "<h2>4. Validation</h2>", "5": "<h2>5. Results</h2>", "6": "<h2>6. Study 1: simulator-in-the-loop vs formula model</h2>", "7": "<h2>7. Interfaces for the optimizer</h2>", "8": "<h2>8. Modelling choices for the group to confirm</h2>", "9": "<h2>9. Status</h2>", "10": "<h2>10. Reproducing the results</h2>"} for k, h in heads.items(): assert h in page, h page = page.replace(h, h + X.block(k, **vals), 1) i = page.index('<p class="abstract">'); j = page.index("</p>", i) + 4 page = page[:j] + '<div style="max-width:72ch;margin:0 auto">' + X.block("summary", **vals) + "</div>" + page[j:] (SITE/"index.html").write_text(page) print("wrote", SITE/"index.html")if __name__ == "__main__": main()src/site_figs.pyDraws the map and charts for the website.
"""Figures for the public page as INLINE SVG strings (no image files, so image blockers can't hide them).map_svg: street map of the area from OpenStreetMap data (data/raw/osm/context/*.osm) with the 4 signals highlighted."""import io, glob, csv, json, re, pathlibimport xml.etree.ElementTree as ETimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltROOT = pathlib.Path(__file__).resolve().parents[1]plt.rcParams.update({"font.family": "serif", "font.serif": ["Times New Roman", "Times", "DejaVu Serif"], "font.size": 10, "svg.fonttype": "none", "axes.edgecolor": "black", "axes.linewidth": 0.8})def _svg(fig): buf = io.StringIO(); fig.savefig(buf, format="svg", bbox_inches="tight"); plt.close(fig) s = buf.getvalue(); s = s[s.index("<svg"):] return re.sub(r'<svg([^>]*?) width="[^"]*" height="[^"]*"', r'<svg\1 width="100%" style="height:auto;max-width:100%"', s, count=1)ROADS = {"motorway": 3.0, "trunk": 2.6, "primary": 2.2, "secondary": 1.8, "tertiary": 1.3, "unclassified": 0.7, "residential": 0.6, "motorway_link": 1.2, "trunk_link": 1.2, "primary_link": 1.0, "secondary_link": 1.0, "tertiary_link": 0.8}LABEL_ROADS = {"Forest Park Parkway", "Forsyth Boulevard", "Wydown Boulevard", "Clayton Road", "Delmar Boulevard", "South Hanley Road", "North Skinker Boulevard", "Pershing Avenue"}def map_svg(cor): nodes, ways = {}, [] for f in sorted(glob.glob(str(ROOT/"data/raw/osm/context/*.osm"))): r = ET.parse(f).getroot() for n in r.iter("node"): nodes[n.get("id")] = (float(n.get("lon")), float(n.get("lat"))) for w in r.iter("way"): t = {x.get("k"): x.get("v") for x in w.findall("tag")} if t.get("highway") in ROADS or t.get("amenity") == "university" or t.get("leisure") == "park": ways.append(([x.get("ref") for x in w.findall("nd")], t)) lights = cor["lights"] lon0, lon1 = -90.3335, -90.3015; lat0, lat1 = 38.6315, 38.6560 fig, ax = plt.subplots(figsize=(7.2, 6.2)) seen = set(); labels = {} for nds, t in ways: pts = [nodes[n] for n in nds if n in nodes] if len(pts) < 2: continue xs, ys = zip(*pts) if t.get("amenity") == "university" or t.get("leisure") == "park": if nds[0] == nds[-1] and (t.get("amenity") == "university"): ax.fill(xs, ys, color="#e9e9e9", zorder=0, lw=0) elif nds[0] == nds[-1]: ax.fill(xs, ys, color="#f2f2f2", zorder=0, lw=0) continue key = (tuple(nds),) if key in seen: continue seen.add(key) name = t.get("name", "") big = "Big Bend" in name ax.plot(xs, ys, color="#9a9a9a" if not big else "#555", lw=ROADS[t["highway"]]*(1.0 if not big else 1.1), zorder=1, solid_capstyle="round") if name in LABEL_ROADS and len(pts) > 1: labels.setdefault(name, []).extend(pts) # highlight the corridor (Big Bend between first and last light) la, lb = lights[0]["lat"]+0.0006, lights[-1]["lat"]-0.0006 for nds, t in ways: if "Big Bend" in t.get("name", "") and t.get("highway") in ROADS: pts = [nodes[n] for n in nds if n in nodes and lb <= nodes[n][1] <= la] if len(pts) >= 2: xs, ys = zip(*pts); ax.plot(xs, ys, color="black", lw=4.2, zorder=3, solid_capstyle="round") for name, pts in labels.items(): pts = [p for p in pts if lon0+0.002 < p[0] < lon1-0.002 and lat0+0.001 < p[1] < lat1-0.0015 and abs(p[0]-lights[0]["lon"]) > 0.005] if not pts: continue pts.sort(); x, y = pts[len(pts)//2] ax.text(x, y+0.0004, name.replace("North ", "").replace("South ", ""), fontsize=7.5, color="#333", style="italic", ha="center", zorder=2, bbox=dict(fc="white", ec="none", pad=0.4, alpha=0.85)) for i, l in enumerate(lights, 1): ax.scatter([l["lon"]], [l["lat"]], s=170, facecolor="white", edgecolor="black", linewidth=2.2, zorder=5) ax.text(l["lon"], l["lat"], str(i), ha="center", va="center", fontsize=9, fontweight="bold", zorder=6) ax.annotate(f"{i}. Big Bend & {l['name']} (#{l['id']})", (l["lon"], l["lat"]), xytext=(-12, 0), textcoords="offset points", ha="right", va="center", fontsize=9, fontweight="bold", zorder=6, bbox=dict(fc="white", ec="black", lw=0.6, pad=2)) ax.text(-90.3065, 38.6505, "Washington University\n(Danforth Campus)", fontsize=8, ha="center", color="#333", zorder=2) ax.text(-90.3245, 38.6495, "Clayton", fontsize=9, ha="center", color="#333", zorder=2, style="italic") ax.text(lon1-0.0003, lat0+0.0003, "Map data © OpenStreetMap contributors", fontsize=6.5, ha="right", va="bottom", color="#555") ax.annotate("N", xy=(lon0+0.0012, lat1-0.0010), xytext=(lon0+0.0012, lat1-0.0030), ha="center", fontsize=10, fontweight="bold", arrowprops=dict(arrowstyle="->", lw=1.2)) ax.set_xlim(lon0, lon1); ax.set_ylim(lat0, lat1); ax.set_aspect(1/0.7815) ax.set_xticks([]); ax.set_yticks([]) for s in ax.spines.values(): s.set_linewidth(1) return _svg(fig)def results_svg(S): items = sorted(S.items(), key=lambda kv: kv[1]["delay_mean"]) fig, ax = plt.subplots(figsize=(6.5, 2.9)) names = [k for k, _ in items] cols = ["black" if k == "county-current" else "#8a8a8a" for k in names] ax.barh(names, [v["delay_mean"] for _, v in items], xerr=[v["delay_sd"] for _, v in items], color=cols, error_kw=dict(lw=0.8)) for i, (_, v) in enumerate(items): ax.text(v["delay_mean"]+v["delay_sd"]+4, i, f"{v['delay_mean']:.0f}", va="center", fontsize=8.5) ax.invert_yaxis(); ax.set_xlabel("corridor delay in SUMO (vehicle-hours per hour)"); ax.spines[["top", "right"]].set_visible(False) ax.set_xlim(0, max(v["delay_mean"] for _, v in items)*1.15) return _svg(fig)def prediction_svg(path): rows = list(csv.DictReader(open(path))) fig, ax = plt.subplots(figsize=(4.2, 3.4)) ax.scatter([float(r["formula"]) for r in rows], [float(r["sumo"]) for r in rows], s=16, color="black") ax.set_xlabel("formula model delay (veh-h/h)"); ax.set_ylabel("SUMO delay (veh-h/h)"); ax.spines[["top", "right"]].set_visible(False) return _svg(fig)def convergence_svg(path): rows = list(csv.DictReader(open(path))) best, cur = [], float("inf") for r in rows: cur = min(cur, float(r["sumo_delay"])); best.append(cur) fig, ax = plt.subplots(figsize=(4.2, 3.4)) ax.plot(range(1, len(best)+1), best, color="black") ax.set_xlabel("SUMO evaluations"); ax.set_ylabel("best delay so far (veh-h/h)"); ax.spines[["top", "right"]].set_visible(False) return _svg(fig)src/site_explain.pyThe plain-English 'Explain this section' texts.
"""Short explanations for the public page: one collapsible "Explain" block per section.Direct and concise by request. Numbers are filled in from the current results. site_page.py inserts each block under its heading."""EXPLAIN = {"summary": """<p><b>Question:</b> can the four lights on Big Bend Blvd be timed so drivers wait less at evening rush hour?</p><p><b>Split:</b> Michael + Noah build the math model and optimizer. Gabriel + Diego get real data, simulate the street, and test every timing.</p><p><b>Delay</b> = total time all drivers lose at the lights in one hour (veh-h/h). Today's County timing: {cur:.0f}. Best found: {sl:.0f}.</p><p><b>Status:</b> data, simulation and tests done. Report and the group's own optimizer still to come.</p>""","1": """<p>The four intersections we study, the traffic at each, and the distance between them.</p><p>Lights this close affect each other: timed well, cars from one light arrive on green at the next.</p><p><b>Terms:</b> NB/SB/EB/WB = northbound/southbound/eastbound/westbound. Approach = traffic arriving from one direction. τ = drive time between lights.</p>""","2": """<p>The County emailed one document per light: the light's timing settings and hand-counted traffic (direction and turn of every car).</p><p>Scanned count sheets were typed in, then checked by program against the sheet totals. Everything matched.</p><p>Every number is tagged <b>measured</b> (real source), <b>derived</b> (calculated from measured) or <b>assumed</b> (textbook value).</p><p><b>Terms:</b> L/T/R = share turning left/straight/right. Cycle = one full round of a light (120 s here). Split = seconds a phase gets. Offset = how the lights' cycles are staggered. Lost time = seconds per cycle spent on yellow and all-red.</p>""","3": """<p><b>Workflow:</b></p><ol><li>Read and check the County documents.</li><li>Build one data file, every number tagged with its source.</li><li>Give the math team its input.</li><li>Build the virtual street (lights, lanes, distances, speed limits).</li><li>Add traffic matching the real counts.</li><li>Prepare timing plans: County, textbook methods, optimized.</li><li>Simulate each plan; measure delay.</li><li>Check the simulation against the counts.</li><li>Produce tables, charts and this site.</li></ol><p>One command reruns all of it (~2 min).</p><p><b>Model:</b> chooses cycle length, Big Bend's green time, and offsets to minimize total delay, within limits (60–150 s cycle, minimum green, no road over 90% full). Michael + Noah's part.</p><p><b>Simulation:</b> SUMO, a traffic simulator that moves every car individually. Each plan runs 10 times (random arrivals) and is averaged; 15 min warm-up, then one measured hour. Lights run the County's real sequence including left arrows; right turn on red allowed; small flows between lights stand in for side streets.</p><p><b>Where it runs:</b> Gabriel's laptop (<code>pipeline/</code> folder). This site only displays results.</p>""","4": """<p>Simulated car counts vs the County's real counts.</p><p>The test is the six points between lights, where the simulation must produce the right traffic on its own.</p><p><b>Result:</b> {ok} of {n_inter} match (GEH under 5, the standard threshold). The simulation reproduces the real street.</p>""","5": """<p>Every timing plan, ranked by delay.</p><ul><li><b>study1-sumo-loop</b> ({sl:.0f}): best timing found by searching inside the simulation.</li><li><b>formula-optimum-standin</b> ({fo:.0f}): the math model's best (our stand-in for Michael + Noah's code).</li><li><b>sumo-coordinated</b>: SUMO's built-in timing tool.</li><li><b>webster</b>: 1958 textbook formula.</li><li><b>county-current</b> ({cur:.0f}): what runs on Big Bend today.</li><li><b>equal-split</b>: equal green for both streets (naive baseline).</li></ul><p><b>Columns:</b> vs County = % change from today (negative is better). Stops/veh = average stops per car. Throughput = cars served (same for all plans, so the comparison is fair).</p><p><b>Result:</b> the model's timing cuts delay {pct_fo:.0f}% vs today. Provisional until Michael + Noah's code is plugged in.</p>""","6": """<p>Two ways to find a timing: the <b>formula</b> (~1 s, simplified) vs <b>searching inside the simulation</b> (~7 min, realistic).</p><p><b>Left chart:</b> 30 random timings. If the formula judged like the simulation, the dots would form a rising line. They don't (Spearman {rho:.2f}; 1 = perfect agreement).</p><p><b>Right chart:</b> the simulation search improving, then levelling off.</p><p><b>Result:</b> the formula gets close fast but can't reliably rank timings. Simulation search finds ~5% better timings at ~300× the compute.</p>""","7": """<p>The files passed between our part and Michael + Noah's: we send traffic data; they send back timings; we simulate them.</p><p>If their format differs, one small file changes.</p>""","8": """<p>Choices that affect the report's claims. The group should agree.</p><ol><li><b>Real lost time and capacity</b> (21–27 s per cycle, from the County's sequence) fed to the model. Needed for its timings to work. Michael + Noah to approve.</li><li><b>Left-turn arrows:</b> all four real lights have them. Revisit "future work".</li><li><b>Simplified virtual street:</b> the full map jammed the simulation; we built a clean one from real distances and lanes.</li><li><b>Assumptions</b> where nothing was measured (e.g. left-turn lane length), all labelled.</li></ol>""","9": """<p><b>Done:</b> data, simulation, testing, Study 1.</p><p><b>Open:</b> Michael + Noah's optimizer, group sign-off on section 8, our report sections, final report and submission.</p>""","10": """<p>The commands the grader uses to rerun everything from the original County documents.</p><p><b>Appendix:</b> the source of every number (measured / derived / assumed, with evidence).</p>""",}def block(key, **vals): return ('<details class="explain"><summary>Explain this section</summary><div class="exp">' + EXPLAIN[key].format(**vals) + "</div></details>")src/code_page.pyGenerates this page (Simulation + Code).
"""Public "Code" page -> build/site/code.html + build/site/code/ (raw files) + a zip of the package.Every program, settings file and data file the pipeline uses, grouped by workflow step, each readable in the page(collapsible, with line numbers), viewable raw, and all downloadable as one zip. The County PDFs are NOT published(obtained by email); their parsed contents are."""import html, pathlib, shutil, zipfile, datetime, syssys.path.insert(0, str(pathlib.Path(__file__).parent))from common import ROOT, BUILDSITE = BUILD/"site"; RAW = SITE/"code"E = html.escapeGROUPS = [ ("Run everything", "How the whole workflow is started, and what it needs.", [ ("run_all.sh", "The one command: runs every step below in order and rebuilds all results."), ("README.md", "Instructions: how to rerun, how the pieces fit, how to change things."), ("requirements.txt", "Software the pipeline needs (SUMO, Python libraries), with exact versions."), ]), ("Settings", "Every choice in plain files: which lights, which hour, every assumption with its evidence.", [ ("config/corridor.toml", "Which four lights, which count stations feed each approach, lanes, design hour, timing pattern, simulation options."), ("config/assumptions.toml", "Every value not measured (turn shares fallback, saturation flow, model defaults) with the reason for it."), ]), ("Step 1 · Read and check the County data", "Turns the County documents into data tables and checks every number.", [ ("src/parse_county_counts.py", "Reads the hourly turning counts from the County count sheets (text-based sheets)."), ("src/parse_county_timing.py", "Reads the timing sheets: phases, yellow/all-red, cycle, splits, offsets for every pattern."), ("src/verify_counts.py", "Re-adds every count row and column and compares with the totals printed on the sheets."), ]), ("Step 2 · Build the master data file", "One file with every number, each labelled measured / derived / assumed.", [ ("src/derive.py", "Combines County counts and timing, MoDOT and map data into corridor.json; computes lost time and capacity."), ]), ("Step 3 · Hand-off to the math team", "The data file the optimizer reads.", [ ("src/to_optimizer.py", "Writes the optimizer input (volumes, capacities, travel times, parameters). Only file that knows their input format."), ]), ("Step 4 · Build the virtual street", "The SUMO road network.", [ ("src/build_network.py", "Builds the network: the generated corridor (default) or the full OpenStreetMap network."), ("src/build_network_gen.py", "Generates the corridor from the data: 4 signals at real spacing, real lanes, left-turn bays, speeds."), ("src/common.py", "Shared helpers: file paths, loading the network, labelling each approach as NB/SB/EB/WB."), ]), ("Step 5 · Fill it with traffic", "Virtual cars that match the real counts.", [ ("src/build_demand.py", "Entry flows, measured turn shares at each light, balancing flows between lights, routes."), ]), ("Step 6 · The timing plans", "Every light timing we test.", [ ("src/plans.py", "Plan format and the baselines: County current, equal split, Webster, SUMO coordination, formula optimum."), ("src/formula.py", "The delay formula (Webster + platoon) and its optimizer: our stand-in for the math team's code."), ]), ("Step 7 · Run the simulations", "Each plan, 10 runs, delay measured.", [ ("src/run_sumo.py", "Runs SUMO for each plan and seed in parallel; measures delay, stops, throughput."), ("src/plan_to_sumo.py", "Turns a plan into SUMO signal programs (County phase sequence or simple two-phase)."), ("src/nema.py", "Builds the County's real phase sequence (incl. left arrows) scaled to a plan's timing."), ]), ("Step 8 · Check against reality", "Simulated vs counted traffic.", [ ("src/validate.py", "Compares simulated volumes with the counts (GEH score) at every approach."), ]), ("Study 1", "Formula model vs optimizing inside the simulation.", [ ("src/study1.py", "Part A: 30 random plans, formula vs simulation ranking. Part B: Nelder–Mead search using the simulation."), ]), ("Browser mini-simulator", "The simplified simulation that runs on this page, and how it is checked against SUMO.", [ ("sim/core.js", "The engine: cars follow the Krauss rule (SUMO's default), lights run the County sequence; runs in the browser and in Node."), ("sim/ui.js", "Drawing (corridor + intersection close-up), controls and live counters on this page."), ("src/sim_export.py", "Exports the corridor, County phases, timing plans and SUMO results the simulator reads (sim/data.json)."), ("sim/validate.js", "Runs every plan through the mini-simulator and compares delays and ranking with SUMO."), ]), ("Step 9 · Tables, charts and this website", "Everything you see on the site is generated by these.", [ ("src/report_tables.py", "Report tables (provenance, volumes, timing, results, validation) and figures."), ("src/site_page.py", "Generates the main website page from the results."), ("src/site_figs.py", "Draws the map and charts for the website."), ("src/site_explain.py", "The plain-English 'Explain this section' texts."), ("src/code_page.py", "Generates this page (Simulation + Code)."), ("src/review_page.py", "A local review page with every table (REVIEW.html)."), ]), ("Data used (parsed from the County documents)", "The measured inputs, as the pipeline reads them.", [ ("data/measured/county_timing.json", "All four timing sheets, parsed: phases, yellow/all-red, every pattern's cycle, splits, offset."), ("data/measured/county-counts/034-clayton-rd-2026-06-24.csv", "Clayton Rd turning counts, hourly (parsed from the sheet's text)."), ("data/measured/county-counts/063-wydown-2025-09-26.csv", "Wydown turning counts, hourly (parsed from the sheet's text)."), ("data/measured/county-counts/040-forsyth-2017-03-03.csv", "Forsyth turning counts, hourly (typed from the scanned sheet, verified)."), ("data/measured/county-counts/051-forest-park-pkwy-2021-06-30.csv", "Forest Park Pkwy counts, 5–6 PM by 15 min (typed from the scan, verified)."), ("data/raw/county/county-signals.csv", "St. Louis County signal inventory near the corridor (IDs, locations, owner)."), ("data/raw/modot/modot_aadt_2025_corridor.csv", "MoDOT 2025 road segments: daily traffic, lanes, speed limits."), ]),]ARC = "https://services2.arcgis.com/w657bnjzrjguNyOy/arcgis/rest/services/STLCO_Transportation_Assets_File_Geodatabase_All_Layers_View/FeatureServer"ORIGINALS = [ ("From St. Louis County Transportation & Public Works (Traffic Operations), by email, November 17, 2026", "The four documents exactly as received: signal timing sheets plus turning-movement counts. Byte-for-byte the email attachments.", [ ("data/measured/county-timing/051-forest-park-pkwy.pdf", "Big Bend Blvd & Forest Park Pkwy.pdf", "Signal #051: timing sheet (Oct 21, 2026) + counts (Feb 5 / Jun 30, 2021, scanned)", None), ("data/measured/county-timing/040-forsyth.pdf", "Big Bend Blvd & Forsyth Blvd.pdf", "Signal #040: timing sheet (Dec 10, 2024) + counts (Mar 3, 2017, scanned)", None), ("data/measured/county-timing/063-wydown.pdf", "Big Bend Blvd & Wydown Blvd.pdf", "Signal #063: timing sheet (Dec 10, 2024) + counts (Sep 26, 2025)", None), ("data/measured/county-timing/034-clayton-rd.pdf", "Big Bend Blvd & Clayton Rd.pdf", "Signal #034: timing sheet (May 12, 2026) + counts (Jun 24-25, 2026)", None), ]), ("Downloaded from public online sources, November 17, 2026", "Exactly as saved from each service (JSON / XML as returned), with the address it came from.", [ ("data/raw/county/county-signals-raw.json", None, "St. Louis County signal inventory near the corridor (Signals layer), raw JSON", ARC+"/40/query?where=1%3D1&geometry=-90.340,38.626,-90.298,38.660&geometryType=esriGeometryEnvelope&inSR=4326&outSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&f=json"), ("data/raw/county/county-count-locations-raw.json", None, "St. Louis County traffic count stations near the corridor (latest counts), raw JSON", ARC+"/13/query?where=1%3D1&geometry=-90.340,38.626,-90.298,38.660&geometryType=esriGeometryEnvelope&inSR=4326&outSR=4326&spatialRel=esriSpatialRelIntersects&outFields=*&f=json"), ("data/raw/county/county-count-history-raw.json", None, "St. Louis County count history for the corridor stations, raw JSON", ARC+"/14/query?where=Location_ID+IN+(119,1063,132,123,1064,1062,117,118,388,387,296)&outFields=*&orderByFields=Location_ID,Count_Year&f=json"), ("data/raw/county/stlco_traffic_counts_corridor.csv", None, "Same County count stations, wider area, saved as CSV (converted from the service's JSON)", "https://services2.arcgis.com/w657bnjzrjguNyOy/arcgis/rest/services/STLCO_Transportation_Assets_File_Geodatabase_Traffic_Counts_Public_Display/FeatureServer/13"), ("data/raw/modot/modot_aadt_2025_corridor.csv", None, "MoDOT 2025 traffic segments near the corridor (daily traffic, lanes, speed), saved as CSV from the service", "https://mapping.modot.mo.gov/arcgis/rest/services/BusinessInt/TrafficInfoSegAADT/MapServer"), ("data/raw/osm/bigbend.osm", None, "OpenStreetMap data for the corridor (roads, lanes, signals), raw XML (© OpenStreetMap contributors, ODbL)", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.3235,38.6315,-90.3105,38.6545"), ("data/raw/osm/context/t1.osm", None, "OpenStreetMap, wider area for the map (tile 1 of 5), raw XML", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.336,38.636,-90.318,38.6465"), ("data/raw/osm/context/t2.osm", None, "OpenStreetMap, wider area (tile 2 of 5)", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.318,38.636,-90.300,38.6465"), ("data/raw/osm/context/t3.osm", None, "OpenStreetMap, wider area (tile 3 of 5)", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.336,38.6465,-90.318,38.657"), ("data/raw/osm/context/t4.osm", None, "OpenStreetMap, wider area (tile 4 of 5)", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.318,38.6465,-90.300,38.657"), ("data/raw/osm/context/t5.osm", None, "OpenStreetMap, wider area (tile 5 of 5)", "https://api.openstreetmap.org/api/0.6/map?bbox=-90.326,38.627,-90.306,38.636"), ]),]SOURCE_PAGES = [ ("St. Louis County: Traffic Studies and Maps (counts map)", "https://stlouiscountymo.gov/st-louis-county-departments/transportation-and-public-works/operations-division/traffic-studies-and-maps/"), ("St. Louis County: Traffic Signal Network", "https://stlouiscountymo.gov/st-louis-county-departments/transportation-and-public-works/operations-division/traffic-signal-network/"), ("St. Louis County public GIS data (signals, count stations)", ARC), ("MoDOT traffic volume map service", "https://mapping.modot.mo.gov/arcgis/rest/services/BusinessInt/TrafficInfoSegAADT/MapServer"), ("OpenStreetMap", "https://www.openstreetmap.org/#map=16/38.6430/-90.3165"),]def sim_html(): import json for f in ("core.js", "ui.js"): shutil.copy(ROOT/"sim"/f, SITE/"sim"/f) shots = sorted((ROOT/"data/screenshots").glob("sumo-*.png")) (SITE/"shots").mkdir(exist_ok=True) caps = {"sumo-1.png": "The whole simulated corridor in SUMO, north at the top: Forest Park Pkwy, Forsyth, Wydown, Clayton Rd (the short cross-bars between lights are the mid-block side-street access points).", "sumo-2.png": "Close-up of one of the four intersections at rush hour: queues on Big Bend waiting at red, cross-street traffic moving.", "sumo-3.png": "SUMO's own window (toolbar, clock, log) showing an intersection with queues on both streets.", "sumo-4.png": "Another intersection close-up in SUMO: long queues on Big Bend and on the cross street.", "sumo-5.png": "A quieter moment at one of the lights, cross-street traffic queued at the stop line."} gal = "" for s in shots: shutil.copy(s, SITE/"shots"/s.name) gal += f'<figure><a href="shots/{s.name}" target="_blank"><img src="shots/{s.name}" alt="{E(caps.get(s.name, "SUMO screenshot"))}"></a><figcaption>{E(caps.get(s.name, ""))}</figcaption></figure>' V = json.load(open(SITE/"sim/validation.json")) vrows = "".join(f"<tr><td>{E(r['label'])}</td><td>{r['mini']:.0f} ± {r['mini_sd']:.0f}</td><td>{r['rank_mini']}</td><td>{r['sumo']:.0f}</td><td>{r['rank_sumo']}</td></tr>" for r in sorted(V["rows"], key=lambda r: r["sumo"])) return f"""<h2>Live mini-simulation of our corridor</h2><p class='brief'>A simplified version of our SUMO model that runs right here in your browser: the same four lights, real County traffic counts and turn shares, the same timing plans.</p><details class="explain"><summary>Explain this simulator</summary><div class="exp"><p>A simplified version of our SUMO model, written for this page. Same four lights, real County counts and turn shares, same timing plans and signal programs as SUMO.</p><p><b>Cars:</b> drive at the speed limit, keep a safe gap (SUMO's default rule), stop at red.</p><p><b>Use:</b> pick a plan, press Play. Left: whole corridor (red = stopped). Right: one intersection up close. "Custom timing" sets your own cycle and Big Bend green share. "Run the full hour instantly" simulates 5–6 PM in ~1 s and compares with SUMO.</p><p><b>Limits:</b> no lane-changing tactics or vehicle types, so delays are lower than SUMO's. It ranks plans similarly (table below).</p></div></details><div class="ctrl"><label>Timing plan <select id="ms-plan"></select></label><label><input type="checkbox" id="ms-custom"> Custom timing:</label><label>cycle <input type="range" id="ms-cycle" min="60" max="150" step="1" value="120"> <span id="ms-cycle-v"></span></label><label>Big Bend share of green <input type="range" id="ms-share" min="30" max="80" step="1" value="55"> <span id="ms-share-v"></span></label></div><div class="ctrl"><button id="ms-play">Play</button> <button id="ms-reset">Reset</button> <button id="ms-skip">Skip to 5:00 PM</button><span>Speed: <button data-speed="1">1×</button><button data-speed="5" class="on">5×</button><button data-speed="20">20×</button><button data-speed="60">60×</button></span><label>Close-up <select id="ms-zoomsel"></select></label><label>Random seed <input type="number" id="ms-seed" value="1" min="1" max="999" style="width:4em"></label><button id="ms-full">Run the full hour instantly</button></div><p id="ms-err" class="err"></p><div class="simgrid"><canvas id="ms-overview" width="300" height="640"></canvas><canvas id="ms-zoom" width="640" height="640"></canvas></div><table class="live"><tr><th>Plan</th><td id="ms-plan-label"></td><th>Simulated time</th><td id="ms-clock"></td></tr><tr><th>Cars on the road</th><td id="ms-cars"></td><th>Cars waiting to enter</th><td id="ms-waiting"></td></tr><tr><th>Delay so far (veh-h per hour)</th><td id="ms-delay"></td><th>Cars through per hour</th><td id="ms-trips"></td></tr></table><div id="ms-results-wrap" hidden><h3>Full-hour runs (3 seeds each)</h3><div class="tw"><table class="orig"><thead><tr><th>plan</th><th>cycle (s)</th><th>mini-sim delay</th><th>SUMO delay</th></tr></thead><tbody id="ms-results"></tbody></table></div></div><h2>What the real SUMO looks like</h2><p class='brief'>Screenshots of SUMO's own viewer running our simulated corridor at rush hour (County's current timing). Click to enlarge.</p><div class="shots">{gal}</div><h2>Mini-simulation vs SUMO</h2><p class='brief'>Every plan run through both, full rush hour ({V['seeds']} runs each for the mini-simulation, 10 for SUMO). Delay in vehicle-hours per hour; rank 1 = least delay.</p><div class="tw"><table class="orig"><thead><tr><th>plan</th><th>mini-sim delay</th><th>mini-sim rank</th><th>SUMO delay</th><th>SUMO rank</th></tr></thead><tbody>{vrows}</tbody></table></div><p class='brief'>Rank agreement (Spearman): {V['spearman']:.2f} (1 = identical order). Both put the optimized plans first and equal split last; the mini-simulation is kinder to the County's timing and its delays are lower overall, because it leaves out lane-changing friction.</p><script src="sim/core.js"></script><script src="sim/ui.js"></script>"""def originals_html(): import urllib.parse out = ["<h2>Original source files (exactly as received)</h2><p class='brief'>Before any processing: the County's emailed documents and " "the raw downloads from public websites. Everything else on this page is built from these.</p>"] for title, brief, files in ORIGINALS: rows = [] for rel, orig_name, desc, url in files: src = ROOT/rel if not src.exists(): continue name = orig_name or src.name dst = RAW/"originals"/name; dst.parent.mkdir(parents=True, exist_ok=True); shutil.copy(src, dst) href = "code/originals/" + urllib.parse.quote(name) size = src.stat().st_size sz = f"{size/1e6:.1f} MB" if size > 1e6 else f"{size/1e3:.0f} KB" srccell = f'<a href="{E(url)}" target="_blank">source address</a>' if url else "email attachment" rows.append(f'<tr><td><a href="{href}" target="_blank"><code>{E(name)}</code></a></td><td>{E(desc)}</td><td>{sz}</td><td>{srccell}</td></tr>') out.append(f"<h3>{E(title)}</h3><p class='brief'>{E(brief)}</p><div class='tw'><table class='orig'><thead><tr><th>file (opens / downloads)</th>" f"<th>what it is</th><th>size</th><th>where it came from</th></tr></thead><tbody>{''.join(rows)}</tbody></table></div>") out.append("<h3>Live source pages</h3><ul>" + "".join(f'<li><a href="{E(u)}" target="_blank">{E(n)}</a></li>' for n, u in SOURCE_PAGES) + "</ul>") return "".join(out)def main(): RAW.mkdir(parents=True, exist_ok=True) total_lines = 0; nfiles = 0; sections = [] for title, brief, files in GROUPS: items = [] for rel, desc in files: src = ROOT/rel if not src.exists(): continue dst = RAW/rel; dst.parent.mkdir(parents=True, exist_ok=True); shutil.copy(src, dst) text = src.read_text(errors="replace"); n = text.count("\n")+1; total_lines += n; nfiles += 1 body = "".join(f'<span class="l">{E(line)}</span>' for line in text.splitlines()) items.append(f'<details class="file"><summary><code>{E(rel)}</code><span class="meta"> · {n} lines</span>' f'<span class="desc">{E(desc)}</span></summary>' f'<p class="raw"><a href="code/{E(rel)}" target="_blank">view raw file</a></p>' f'<pre class="src"><code>{body}</code></pre></details>') sections.append(f"<h2>{E(title)}</h2><p class='brief'>{E(brief)}</p>" + "".join(items)) # zip of the package (no County PDFs, no regenerated outputs, no local Python install) zp = RAW/"bigbend-pipeline-code.zip" with zipfile.ZipFile(zp, "w", zipfile.ZIP_DEFLATED) as z: done = set() _w = z.write def add(path, arc): if arc not in done: done.add(arc); _w(path, arc) z.write = add for _, _, files in GROUPS: for rel, _ in files: if (ROOT/rel).exists(): z.write(ROOT/rel, f"pipeline/{rel}") for extra in sorted((ROOT/"data/raw").rglob("*")): if extra.is_file() and "osm/context" not in str(extra): z.write(extra, f"pipeline/{extra.relative_to(ROOT)}") for extra in sorted((ROOT/"data/measured/county-counts").glob("*.totals.csv")): z.write(extra, f"pipeline/{extra.relative_to(ROOT)}") size_mb = zp.stat().st_size/1e6 css = """:root{--bg:#fff;--fg:#000;--mut:#444;--rule:#000;--hair:#bbb;--shade:#f5f5f5;color-scheme:light}*{box-sizing:border-box} html{background:var(--bg)}body{margin:0;background:var(--bg);color:var(--fg);font-family:"Times New Roman",Times,serif;font-size:17px;line-height:1.5; padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:32px 64px}main{max-width:980px;margin:0 auto}nav{font-size:15px;margin-bottom:10px} nav a{color:var(--fg)}header{text-align:center;border-bottom:2px solid var(--rule);padding-bottom:14px;margin-bottom:18px}h1{font-size:26px;margin:0 0 6px} .meta{color:var(--mut);font-size:14px}h2{font-size:19px;margin:28px 0 4px;border-bottom:1px solid var(--rule);padding-bottom:3px}.brief{margin:2px 0 8px;color:var(--mut);font-style:italic}details.file{border:1px solid var(--hair);margin:6px 0}details.file>summary{cursor:pointer;padding:6px 10px;list-style:none}details.file>summary::-webkit-details-marker{display:none}details.file>summary::before{content:"▸ "} details.file[open]>summary::before{content:"▾ "}details.file[open]>summary{border-bottom:1px solid var(--hair);background:var(--shade)}summary code{font-family:"Courier New",Courier,monospace;font-size:15px;font-weight:700}.desc{display:block;font-size:15px;margin-left:18px}.raw{margin:6px 10px;font-size:14px} .raw a{color:var(--fg)}pre.src{margin:0;padding:8px 0;overflow-x:auto;max-height:70vh;font-family:"Courier New",Courier,monospace;font-size:13px;line-height:1.4;counter-reset:ln}pre.src .l{display:block;padding:0 12px 0 0;white-space:pre}pre.src .l::before{counter-increment:ln;content:counter(ln);display:inline-block;width:3.2em;padding-right:10px;text-align:right;color:#888;user-select:none}.box{border:1.2px solid var(--rule);padding:10px 14px;margin:10px 0}.box a{color:var(--fg);font-weight:700}h3{font-size:17px;margin:16px 0 2px;font-style:italic;font-weight:400}.tw{overflow-x:auto} table.orig{border-collapse:collapse;width:100%;font-size:14.5px}table.orig th{border-top:1.5px solid var(--rule);border-bottom:1px solid var(--rule);text-align:left;padding:5px 7px}table.orig td{border-bottom:1px solid var(--hair);padding:5px 7px;vertical-align:top}table.orig a{color:var(--fg)} ul a{color:var(--fg)}.ctrl{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;margin:8px 0;font-size:15px}.ctrl button,.ctrl select,.ctrl input{font-family:inherit;font-size:15px}.ctrl button{border:1px solid #000;background:#fff;padding:2px 9px;cursor:pointer}.ctrl button.on{background:#000;color:#fff}.simgrid{display:grid;grid-template-columns:300px minmax(0,640px);gap:12px;margin:8px 0}.simgrid canvas{border:1px solid #000;max-width:100%;height:auto;background:#fff}@media (max-width:760px){.simgrid{grid-template-columns:1fr}}table.live{border-collapse:collapse;font-size:15px;margin:6px 0} table.live th{text-align:left;font-weight:400;color:#444;padding:2px 8px 2px 0}table.live td{padding:2px 18px 2px 0;font-variant-numeric:tabular-nums;font-weight:700}.err{color:#c0392b;margin:2px 0}.shots{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.shots figure{margin:0} .shots img{width:100%;border:1px solid #bbb} .shots figcaption{font-size:14px;color:#444}details.explain{border:1px solid #000;margin:6px 0 10px} details.explain>summary{font-style:italic;padding:4px 10px;list-style:none;cursor:pointer}details.explain>summary::-webkit-details-marker{display:none} details.explain>summary::before{content:"▸ "} details.explain[open]>summary::before{content:"▾ "}.exp{padding:4px 14px 8px;font-size:16px}footer{margin-top:36px;border-top:1px solid var(--rule);padding-top:8px;font-size:13px;color:var(--mut)}""" today = datetime.date.today().strftime("%B %-d, %Y") page = f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Big Bend Simulation and Code</title><meta name="description" content="All code, settings and data behind the Big Bend signal timing study"><style>{css}</style></head><body><main><nav><a href="index.html">← Back to the study</a></nav><header><h1>Simulation + Code</h1><p class="meta">Every program, setting and data file the workflow uses · {nfiles} files · {total_lines:,} lines · generated {today}</p></header><div class="box"><b>How to use this page.</b> Start with the live mini-simulation, then the SUMO screenshots, then the original data and all the code. Files are grouped in the order the workflow runs them. Click a file to read it (click again to close);"view raw file" opens it on its own. <br><a href="code/bigbend-pipeline-code.zip">Download everything as one zip</a> ({size_mb:.1f} MB).<br><span class="meta">Where it runs: on Gabriel's laptop, with Python and the free SUMO traffic simulator (versions in requirements.txt);<code>./run_all.sh</code> reruns every step. The original County documents and raw downloads are in the first section; outputs the code regenerates are not included.</span></div>{sim_html()}{originals_html()}{''.join(sections)}<footer>Generated by src/code_page.py from the project folder; the files shown are the exact files the pipeline runs.</footer></main></body></html>""" (SITE/"code.html").write_text(page) # show code and text files as readable text in the browser (Cloudflare Pages _headers) rules = "".join(f"/code/*{ext}\n Content-Type: text/plain; charset=utf-8\n" for ext in (".py", ".toml", ".sh", ".md", ".txt", ".csv", ".osm")) (SITE/"_headers").write_text(rules) print(f"wrote code.html: {nfiles} files, {total_lines} lines, zip {size_mb:.1f} MB")if __name__ == "__main__": main()src/review_page.pyA local review page with every table (REVIEW.html).
"""One local page to review everything built so far -> pipeline/REVIEW.html (regenerated from build/, never hand-edited)."""import json, re, html, pathlib, syssys.path.insert(0, str(pathlib.Path(__file__).parent))from common import BUILD, ROOTREP = BUILD/"report"def md_to_html(md): out, rows = [], [] def flush(): if rows: head, body = rows[0], [r for r in rows[2:]] out.append("<table><thead><tr>" + "".join(f"<th>{html.escape(c)}</th>" for c in head) + "</tr></thead><tbody>" + "".join("<tr>" + "".join(f"<td>{html.escape(c)}</td>" for c in r) + "</tr>" for r in body) + "</tbody></table>") rows.clear() for line in md.splitlines(): if line.startswith("|"): rows.append([c.strip() for c in line.strip("|").split("|")]) else: flush() if line.startswith("# "): continue elif line.strip(): out.append(f"<p>{html.escape(line)}</p>") flush() return "\n".join(out)def section(title, body, open_=False): return f"<details {'open' if open_ else ''}><summary>{title}</summary><div class='in'>{body}</div></details>"def main(): S = json.load(open(BUILD/"results_summary.json")) cur = S["county-current"]["delay_mean"] best = min(S.items(), key=lambda kv: kv[1]["delay_mean"]) s1 = json.load(open(BUILD/"study1/summary.json")) V = json.load(open(BUILD/"validation.json")); inter = [r for r in V if r["kind"] == "interior"] rd = lambda n: (REP/n).read_text() if (REP/n).exists() else "" ready = [ ("Real corridor data (County timing + counts, all 4 lights), verified against printed totals", "ready", "data/measured/, build/report/volumes.md, timing.md"), ("Where every number comes from (measured / derived / assumed)", "ready", "build/report/provenance.md"), ("SUMO network + traffic demand, checked against counts", "ready", f"validation: {sum(r['geh'] < 5 for r in inter)}/{len(inter)} interior approaches GEH < 5"), ("Plan → SUMO pipeline, every plan run with 10 seeds", "ready", "build/results_summary.json, build/report/results.md"), ("Baselines: County current (real), equal split, Webster, SUMO coordination", "ready", "plans/"), ("Study 1 (simulator-in-the-loop vs formula)", "ready (first full run)", "build/study1/"), ("Code package + README rerun (./run_all.sh)", "ready for our part", "pipeline/README.md"), ("Michael + Noah's optimizer plugged in", "NOT YET: stand-in used", "src/plans.py::from_their_format, src/to_optimizer.py"), ("Group sign-off: corridor switch, model input changes (lost time, capacity), left arrows", "NOT YET", "message the group"), ("Written report (8-12 pp): our Data/Setup/Study 1 sections", "NOT YET written", "tables + figures ready to drop in"), ("Other members' sections, Contributions lines, final PDF, package email to TA", "NOT YET", "comes after the above"), ] status_rows = "".join(f"<tr><td>{a}</td><td class='{'ok' if s.startswith('ready') else 'no'}'>{s}</td><td>{w}</td></tr>" for a, s, w in ready) page = f"""<!doctype html><html><head><meta charset="utf-8"><title>Traffic Project Review</title><style>:root{{--bg:#fff;--fg:#111;--mut:#555;--line:#ddd;--ok:#0a7d32;--no:#b3261e;--card:#f6f6f6}}@media (prefers-color-scheme:dark){{:root{{--bg:#151515;--fg:#eee;--mut:#aaa;--line:#333;--ok:#4cc276;--no:#ff7b72;--card:#1f1f1f}}}}body{{background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,Helvetica,Arial,sans-serif;max-width:1050px;margin:24px auto;padding:0 16px}}h1{{font-size:24px;margin:0}} .sub{{color:var(--mut);margin:2px 0 18px}}.kpis{{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin:14px 0}}.k{{background:var(--card);padding:12px;border-radius:8px}} .k b{{font-size:22px;display:block}}table{{border-collapse:collapse;width:100%;font-size:13px;margin:8px 0}} th,td{{border-bottom:1px solid var(--line);padding:5px 7px;text-align:left;vertical-align:top}}.ok{{color:var(--ok);font-weight:600}} .no{{color:var(--no);font-weight:600}}details{{border:1px solid var(--line);border-radius:8px;margin:10px 0}} summary{{cursor:pointer;padding:10px 12px;font-weight:600}}.in{{padding:0 12px 12px;overflow-x:auto}} img{{max-width:100%;background:#fff;border-radius:6px}}.figs{{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}}</style></head><body><h1>CSE 5403 traffic project: our part, review</h1><div class="sub">Big Bend Blvd, Forest Park Pkwy → Clayton Rd, PM peak · generated from pipeline/build · not the final report</div><div class="kpis"><div class="k"><b>{cur:.0f}</b>veh-h/h delay, County's current PM timing (simulated)</div><div class="k"><b>{best[1]['delay_mean']:.0f}</b>best plan ({best[0]}): {100*(1-best[1]['delay_mean']/cur):.0f}% less delay</div><div class="k"><b>{sum(r['geh'] < 5 for r in inter)}/{len(inter)}</b>simulated volumes match County counts (GEH < 5)</div><div class="k"><b>{s1['prediction']['spearman']:.2f}</b>formula vs SUMO rank correlation (Study 1, 30 plans)</div></div><h2>Is it submission-ready?</h2><p><b>No.</b> Our technical pieces are done and reproducible; the report and the final package are not written yet, and two things wait on the group.</p><table><thead><tr><th>piece</th><th>status</th><th>where</th></tr></thead><tbody>{status_rows}</tbody></table><div class="figs"><img src="build/report/results.png" alt="results"><img src="build/report/corridor.png" alt="corridor"><img src="build/study1/prediction.png" alt="study 1 prediction"><img src="build/study1/convergence.png" alt="study 1 convergence"></div>{section("Results: every plan (SUMO, 10 seeds)", md_to_html(rd("results.md")), True)}{section("Validation: simulated vs counted volumes", md_to_html(rd("validation.md")))}{section("Measured PM volumes and turn shares", md_to_html(rd("volumes.md")))}{section("County PM timing (from the sheets)", md_to_html(rd("timing.md")))}{section("Where every number comes from", md_to_html(rd("provenance.md")))}{section("Study 1 numbers", "<pre>"+html.escape(json.dumps(s1, indent=1))+"</pre>")}{section("Choices to tell the group", "<ol><li>Simulated network generated from real data (raw OpenStreetMap version jammed on side merges; still available).</li><li>SUMO runs each plan with the County's real phase sequence incl. left arrows, arrows sized to measured left-turn traffic.</li><li><b>Model inputs changed (Michael + Noah to approve):</b> lost time and capacity worked out along the real signal sequence. Switchable back.</li><li>Right turn on red; 90 m left bays (assumed); small mid-block flows for side streets/driveways; design hour 5-6 PM.</li><li>'formula-optimum-standin' is our implementation of their model until signal_opt.py arrives.</li></ol>")}</body></html>""" (ROOT/"REVIEW.html").write_text(page) print("wrote", ROOT/"REVIEW.html")if __name__ == "__main__": main()Data used (parsed from the County documents)
The measured inputs, as the pipeline reads them.
data/measured/county_timing.jsonAll four timing sheets, parsed: phases, yellow/all-red, every pattern's cycle, splits, offset.
{ "034": { "file": "034-clayton-rd.pdf", "date": "May 12, 2026", "phases": { "1": { "movement": "SECONDS Big Bend Blvd. SB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 20.0 }, "2": { "movement": "Big Bend Blvd. NB", "recall": "RECALL-ON", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 40.0 }, "3": { "movement": "Clayton Rd. EB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.7, "min_green": 6.0, "max_green": 20.0 }, "4": { "movement": "Clayton Rd. WB", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.7, "min_green": 6.0, "max_green": 35.0 }, "5": { "movement": "Big Bend Blvd. NB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 20.0 }, "6": { "movement": "Big Bend Blvd. SB", "recall": "RECALL-ON", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 40.0 }, "7": { "movement": "SECONDS Clayton Rd. WB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.7, "min_green": 6.0, "max_green": 20.0 }, "8": { "movement": "Clayton Rd. EB", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.7, "min_green": 6.0, "max_green": 35.0 } }, "schedule": [ "Pattern 19 on 5:30 AM - 9:15 AM (M-F)", "Pattern 55 on 5:30 AM - 12:00 MN (Sat & Sun)" ], "patterns": { "19": { "cycle": 120, "splits": { "1": 18, "2": 45, "3": 19, "4": 38, "5": 18, "6": 45, "7": 23, "8": 34 }, "offset": 13 }, "37": { "cycle": 120, "splits": { "1": 27, "2": 39, "3": 20, "4": 34, "5": 24, "6": 42, "7": 23, "8": 31 }, "offset": 23 }, "55": { "cycle": 120, "splits": { "1": 23, "2": 40, "3": 23, "4": 34, "5": 23, "6": 40, "7": 26, "8": 31 }, "offset": 15 } }, "coordinated_phases": [ 2, 6 ] }, "040": { "file": "040-forsyth.pdf", "date": "December 10, 2024", "phases": { "1": { "movement": "SECONDS Big Bend Blvd. SB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 4.8, "all_red": 0.5, "min_green": 6.0, "max_green": 25.0 }, "2": { "movement": "Big Bend Blvd. NB", "recall": "RECALL-ON", "yellow": 4.8, "all_red": 0.5, "min_green": 20.0, "max_green": 40.0 }, "3": { "movement": "Forsyth Blvd. WB & LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 4.9, "all_red": 0.5, "min_green": 6.0, "max_green": 25.0 }, "4": { "movement": "Forsyth Blvd. EB & LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 4.9, "all_red": 0.5, "min_green": 6.0, "max_green": 25.0 }, "5": { "movement": "Big Bend Blvd. NB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 4.8, "all_red": 0.5, "min_green": 6.0, "max_green": 25.0 }, "6": { "movement": "Big Bend Blvd. SB", "recall": "RECALL-ON", "yellow": 4.8, "all_red": 0.5, "min_green": 20.0, "max_green": 40.0 } }, "schedule": [ "Pattern 1 on 12:00 MN \u2013 5:30 AM (Everyday)", "Pattern 19 on 5:30 AM - 9:15 AM (M-F)", "Pattern 55 on 5:30 AM - 12:00 MN (Sat & Sun)" ], "patterns": { "1": { "cycle": 80, "splits": { "1": 12, "2": 28, "3": 19, "4": 21, "5": 12, "6": 28 }, "offset": 1 }, "19": { "cycle": 120, "splits": { "1": 16, "2": 45, "3": 30, "4": 29, "5": 31, "6": 30 }, "offset": 105 }, "37": { "cycle": 120, "splits": { "1": 15, "2": 41, "3": 34, "4": 30, "5": 19, "6": 37 }, "offset": 44 } }, "coordinated_phases": [ 2, 6 ] }, "051": { "file": "051-forest-park-pkwy.pdf", "date": "October 21, 2026", "phases": { "1": { "movement": "Forest Park Pkwy. EB LT", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 15.0 }, "2": { "movement": "Forest Park Pkwy. WB", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 50.0 }, "3": { "movement": "Big Bend Blvd. SB LT", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.4, "all_red": 0.5, "min_green": 6.0, "max_green": 20.0 }, "4": { "movement": "Big Bend Blvd. NB", "recall": "RECALL-ON", "yellow": 5.4, "all_red": 0.5, "min_green": 6.0, "max_green": 35.0 }, "5": { "movement": "Forest Park Pkwy. WB LT", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 15.0 }, "6": { "movement": "Forest Park Pkwy. EB", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 50.0 }, "7": { "movement": "Big Bend Blvd. NB LT", "recall": "RECALL OFF \u2013 NON LOCKING", "yellow": 5.4, "all_red": 0.5, "min_green": 6.0, "max_green": 20.0 }, "8": { "movement": "Big Bend Blvd. SB", "recall": "RECALL-ON", "yellow": 5.4, "all_red": 0.5, "min_green": 6.0, "max_green": 35.0 } }, "schedule": [], "patterns": { "37": { "cycle": 120, "splits": { "1": 18, "2": 42, "3": 18, "4": 42, "5": 18, "6": 42, "7": 18, "8": 42 }, "offset": 10 } }, "coordinated_phases": [ 4, 8 ] }, "063": { "file": "063-wydown.pdf", "date": "December 10, 2024", "phases": { "1": { "movement": "SECONDS Big Bend Blvd. SB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 10.0 }, "2": { "movement": "Big Bend Blvd. NB", "recall": "RECALL-ON", "yellow": 6.0, "all_red": 0.8, "min_green": 25.0, "max_green": 50.0 }, "3": { "movement": "Wydown Blvd. EB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 10.0 }, "4": { "movement": "Wydown Blvd. WB", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 30.0 }, "5": { "movement": "Big Bend Blvd. NB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 6.0, "all_red": 0.8, "min_green": 6.0, "max_green": 10.0 }, "6": { "movement": "Big Bend Blvd. SB", "recall": "RECALL-ON", "yellow": 6.0, "all_red": 0.8, "min_green": 25.0, "max_green": 50.0 }, "7": { "movement": "SECONDS Wydown Blvd. WB LT", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 10.0 }, "8": { "movement": "Wydown Blvd. EB", "recall": "RECALL-OFF & NON-LOCKING", "yellow": 5.3, "all_red": 0.5, "min_green": 6.0, "max_green": 30.0 } }, "schedule": [ "Pattern 1 on 12:00 MN \u2013 5:30 AM (Everyday)", "Pattern 19 on 5:30 AM - 9:15 AM (M-F)", "Pattern 55 on 5:30 AM - 12:00 MN (Sat & Sun)" ], "patterns": { "1": { "cycle": 80, "splits": { "1": 13, "2": 32, "3": 12, "4": 23, "5": 13, "6": 32, "7": 12, "8": 23 }, "offset": 38 }, "19": { "cycle": 120, "splits": { "1": 22, "2": 44, "3": 20, "4": 34, "5": 22, "6": 44, "7": 20, "8": 34 }, "offset": 79 }, "37": { "cycle": 120, "splits": { "1": 19, "2": 47, "3": 20, "4": 34, "5": 15, "6": 51, "7": 20, "8": 34 }, "offset": 68 }, "55": { "cycle": 120, "splits": { "1": 19, "2": 52, "3": 15, "4": 34, "5": 15, "6": 56, "7": 15, "8": 34 }, "offset": 64 } }, "coordinated_phases": null }}data/measured/county-counts/034-clayton-rd-2026-06-24.csvClayton Rd turning counts, hourly (parsed from the sheet's text).
# St. Louis County turning-movement count, 6/24/2026, hourly. Parsed from the text layer of 034-clayton-rd.pdf page 8 by parse_county_counts.py.# approach: SB = Big Bend from North, WB = from East, NB = Big Bend from South, EB = from Westhour,approach,L,T,R,peds,app_total06:00,SB,43,260,8,0,31107:00,SB,148,672,31,0,85108:00,SB,262,1037,72,1,137209:00,SB,166,924,49,1,114010:00,SB,61,432,24,0,51711:00,SB,79,581,11,0,67112:00,SB,136,808,73,0,101713:00,SB,119,848,37,0,100414:00,SB,147,983,37,0,116715:00,SB,184,1219,41,0,144416:00,SB,269,1330,29,0,162817:00,SB,344,1244,38,0,162618:00,SB,213,1037,16,0,126606:00,WB,75,109,35,1,22007:00,WB,141,607,101,4,85308:00,WB,273,1017,153,0,144309:00,WB,157,634,65,2,85810:00,WB,139,384,55,1,57911:00,WB,100,380,62,1,54312:00,WB,202,398,119,3,72213:00,WB,193,468,105,5,77114:00,WB,246,565,86,1,89815:00,WB,267,782,102,2,115316:00,WB,264,867,117,5,125317:00,WB,237,685,109,2,103318:00,WB,169,450,96,2,71706:00,NB,24,226,31,0,28107:00,NB,87,361,43,1,49208:00,NB,102,464,54,1,62109:00,NB,85,476,100,0,66110:00,NB,55,244,65,0,36411:00,NB,58,373,78,0,50912:00,NB,99,413,106,0,61813:00,NB,76,319,72,2,46914:00,NB,84,370,60,0,51415:00,NB,90,394,83,40,60716:00,NB,99,451,64,1,61517:00,NB,126,419,77,4,62618:00,NB,71,335,91,7,50406:00,EB,16,61,25,1,10307:00,EB,40,210,56,1,30708:00,EB,76,283,73,0,43209:00,EB,65,263,58,0,38610:00,EB,28,84,28,0,14011:00,EB,65,222,50,0,33712:00,EB,91,254,93,2,44013:00,EB,45,239,42,0,32614:00,EB,69,234,50,0,35315:00,EB,91,304,75,0,47016:00,EB,120,400,141,1,66217:00,EB,110,558,224,0,89218:00,EB,78,413,112,0,603data/measured/county-counts/063-wydown-2025-09-26.csvWydown turning counts, hourly (parsed from the sheet's text).
# St. Louis County turning-movement count, 9/26/2025, hourly. Parsed from the text layer of 063-wydown.pdf page 8 by parse_county_counts.py.# approach: SB = Big Bend from North, WB = from East, NB = Big Bend from South, EB = from Westhour,approach,L,T,R,peds,app_total06:00,SB,20,295,1,0,31607:00,SB,49,634,6,0,68908:00,SB,88,909,13,4,101409:00,SB,29,758,11,4,80210:00,SB,32,702,15,2,75111:00,SB,29,872,19,1,92112:00,SB,35,938,12,0,98513:00,SB,37,993,29,0,105914:00,SB,28,1158,29,1,121615:00,SB,143,1502,34,3,168216:00,SB,101,1778,37,3,191917:00,SB,64,1511,55,4,163418:00,SB,49,1017,20,1,108706:00,WB,11,6,15,35,6707:00,WB,29,34,41,30,13408:00,WB,109,98,106,22,33509:00,WB,79,43,66,21,20910:00,WB,44,33,28,15,12011:00,WB,74,55,40,11,18012:00,WB,53,56,40,8,15713:00,WB,61,26,29,4,12014:00,WB,86,33,37,1,15715:00,WB,289,416,176,10,89116:00,WB,148,215,51,22,43617:00,WB,80,159,59,8,30618:00,WB,48,60,26,7,14106:00,NB,14,275,24,0,31307:00,NB,59,464,78,1,60208:00,NB,70,600,74,4,74809:00,NB,43,416,42,3,50410:00,NB,39,299,43,4,38511:00,NB,30,434,52,7,52312:00,NB,35,505,65,5,61013:00,NB,48,466,64,3,58114:00,NB,39,550,83,2,67415:00,NB,43,561,97,3,70416:00,NB,37,576,67,3,68317:00,NB,33,602,108,6,74918:00,NB,30,499,57,8,59406:00,EB,11,18,3,46,7807:00,EB,32,61,24,31,14808:00,EB,34,70,24,19,14709:00,EB,36,48,27,10,12110:00,EB,32,44,37,16,12911:00,EB,45,55,32,9,14112:00,EB,25,42,34,13,11413:00,EB,37,51,33,3,12414:00,EB,29,71,33,3,13615:00,EB,40,136,57,55,28816:00,EB,34,119,97,23,27317:00,EB,37,124,90,12,26318:00,EB,30,62,29,26,147data/measured/county-counts/040-forsyth-2017-03-03.csvForsyth turning counts, hourly (typed from the scanned sheet, verified).
# Big Bend Blvd & Forsyth Blvd, St. Louis County turning-movement count, 3/3/2017 (Counted by Larry/Jesse), hourly.# TRANSCRIBED BY EYE from the scanned page 5 of data/measured/county-timing/040-forsyth.pdf; verified by verify_counts.py against the sheet's printed totals.# approach: SB = Big Bend from North, WB = Forsyth from East, NB = Big Bend from South, EB = Forsyth from Westhour,approach,L,T,R,peds,app_total06:00,SB,17,106,9,2,13407:00,SB,64,510,12,1,58708:00,SB,106,530,22,0,65809:00,SB,50,308,17,2,37710:00,SB,27,224,18,6,27511:00,SB,37,282,18,6,34312:00,SB,52,317,10,4,38313:00,SB,55,365,22,6,44814:00,SB,34,426,19,3,48215:00,SB,35,419,12,1,46716:00,SB,58,720,31,0,80917:00,SB,102,842,33,2,97918:00,SB,68,499,33,2,60206:00,WB,14,55,20,9,9807:00,WB,55,167,78,9,30908:00,WB,67,187,96,34,38409:00,WB,77,94,93,25,28910:00,WB,82,100,89,35,30611:00,WB,140,107,115,38,40012:00,WB,134,124,146,40,44413:00,WB,127,102,92,17,33814:00,WB,162,139,124,32,45715:00,WB,160,121,136,21,43816:00,WB,269,166,169,51,65517:00,WB,333,198,214,59,80418:00,WB,203,161,212,32,60806:00,NB,69,179,38,2,28807:00,NB,214,422,73,2,71108:00,NB,314,639,184,11,114809:00,NB,134,370,108,14,62610:00,NB,83,340,72,9,50411:00,NB,107,383,84,14,58812:00,NB,129,448,83,21,68113:00,NB,119,424,79,15,63714:00,NB,107,379,80,19,58515:00,NB,146,544,99,12,80116:00,NB,143,553,82,59,83717:00,NB,164,580,110,44,89818:00,NB,106,485,71,13,67506:00,EB,13,42,22,6,8307:00,EB,22,123,170,0,31508:00,EB,40,207,156,1,40409:00,EB,25,146,86,9,26610:00,EB,26,110,69,6,21111:00,EB,30,109,137,5,28112:00,EB,39,169,135,2,34513:00,EB,36,120,159,4,31914:00,EB,45,156,128,11,34015:00,EB,60,179,168,4,41116:00,EB,35,235,300,13,58317:00,EB,51,296,363,17,72718:00,EB,33,156,159,0,348data/measured/county-counts/051-forest-park-pkwy-2021-06-30.csvForest Park Pkwy counts, 5–6 PM by 15 min (typed from the scan, verified).
# Big Bend Blvd & Forest Park Pkwy, St. Louis County turning-movement count, 6/30/2021 (Moses/Jesse/Louis), 15-minute rows, 5:00-6:00 PM.# TRANSCRIBED BY EYE from scanned page 7 of data/measured/county-timing/051-forest-park-pkwy.pdf; verified by verify_counts.py.# approach: SB = Big Bend from North, WB = Forest Park Pkwy from East, NB = Big Bend from South, EB = Forest Park Pkwy from Westhour,approach,L,T,R,peds,app_total17:00,SB,26,115,31,5,17717:15,SB,30,146,24,0,20017:30,SB,27,113,25,2,16717:45,SB,37,131,25,1,19417:00,WB,41,216,61,0,31817:15,WB,47,201,68,0,31617:30,WB,23,154,50,0,22717:45,WB,37,142,41,0,22017:00,NB,25,105,18,3,15117:15,NB,26,118,21,4,16917:30,NB,29,90,16,1,13617:45,NB,15,102,20,0,13717:00,EB,63,185,14,0,26217:15,EB,86,200,19,0,30517:30,EB,39,142,13,2,19617:45,EB,51,134,17,0,202data/raw/county/county-signals.csvSt. Louis County signal inventory near the corridor (IDs, locations, owner).
signal_id,location,route,type,owner,file_number,turned_on,lat,lon,notes125,Delmar Boulevard and North and South Road,Delmar_Boulevard_McKelvey_to_Big_Bend,Traffic Signal,COUNTY,6-15,1972-06-01,38.65933,-90.33751,Accepted on ARS119,Delmar Boulevard and Hanley Road,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,2-37,1968-01-01,38.65888,-90.33276,121,Delmar Boulevard and Jackson Avenue,Delmar_Boulevard_McKelvey_to_Big_Bend,Traffic Signal,COUNTY,3-29,1971-01-19,38.6583,-90.32868,210,Kingsland Avenue and Loop North,Kingsland_Avenue_Delmar_to_Olive,Traffic Signal,COUNTY,5-9,1972-06-01,38.65749,-90.30854,124,Delmar Boulevard and Midland Boulevard,Delmar_Boulevard_McKelvey_to_Big_Bend,Traffic Signal,COUNTY,2-14,1971-01-19,38.65749,-90.32062,037,Big Bend Boulevard and Delmar Avenue,Delmar_Boulevard_McKelvey_to_Big_Bend,Traffic Signal,COUNTY,6-3,1972-06-01,38.65682,-90.31394,Accepted on ARS045,Big Bend Boulevard and Kingsbury Boulevard,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,5-24,1981-10-06,38.65421,-90.31447,178,Hanley Road and Pershing Avenue,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,3-1,1968-01-01,38.65404,-90.33351,157,Forest Park Parkway and Pershing Avenue,Forest_Park_Parkway_170_to_STLCity_Limit,Traffic Signal,COUNTY,2-43,1970-12-10,38.65214,-90.32177,257,"Forest Park Parkway, east of Williams Avenue, near Flynn Park Elementary School",Forest_Park_Parkway_170_to_STLCity_Limit,Pedestrian Signal,COUNTY,11-39,1972-06-01,38.65187,-90.31821,Accepted on ARS051,Big Bend Boulevard and Forest Park Parkway,Forest_Park_Parkway_170_to_STLCity_Limit,Traffic Signal,COUNTY,5-33,1972-06-01,38.6515,-90.31493,Accepted on ARS493,Hanley Road (North) and Maryland Avenue,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-5,1996-09-23,38.65129,-90.33392,Accepted on ARS256,"Forest Park Parkway and Washington University West Entrance (Throop Drive), east of Big Bend Boulevard",Forest_Park_Parkway_170_to_STLCity_Limit,Traffic Signal,COUNTY,3-16,1972-06-01,38.651,-90.31125,Accepted on ARS492,Hanley Road and Forsyth Boulevard,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-4,1996-09-23,38.64989,-90.33408,Accepted on ARS255,"Forest Park Parkway and Washington University East Entrance (Hoyt Drive), west of Skinker Boulevard",Forest_Park_Parkway_170_to_STLCity_Limit,Traffic Signal,COUNTY,3-14,1972-06-01,38.64959,-90.30371,Accepted on ARS497,Forsyth Boulevard and Bland Drive,Bland_Drive_Forest_Park_Parkway_to_Forsyth,Traffic Signal,COUNTY,9-49,1997-04-14,38.64862,-90.32814,Accepted on ARS491,Hanley Road (South) and Carondelet Avenue -Carondelet Plaza,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-2,1996-09-23,38.64854,-90.3343,Accepted on ARS040,Big Bend Boulevard and Forsyth Boulevard,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,5-23,1972-12-01,38.64736,-90.31578,Accepted on ARS490,Hanley Road (South) and Bonhomme Avenue -Commercial Entrance,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-1,1996-09-23,38.64727,-90.33447,Accepted on ARS448,Shaw Park Drive and Bemiston Avenue (South),Shaw_Park_Drive_Forest_Park_to_Hanley,Traffic Signal,COUNTY,9-2,1992-03-13,38.64616,-90.33737,Accepted on ARS063,Big Bend Boulevard and Wydown Boulevard,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,7-17,1972-12-01,38.64332,-90.3166,Accepted on ARS489,Hanley Road (South) and Polo Drive -Wydown Boulevard,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-6,1996-09-23,38.6431,-90.33496,Accepted on ARS494,Hanley Road (South) and Davis Drive - Commercial Exit,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,10-3,1996-09-23,38.64056,-90.33534,Accepted on ARS108,Clayton Road and Hanley Road,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,5-20,1970-11-02,38.63776,-90.33557,106,Clayton Road and Central Avenue (South) - East Linden Avenue,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,7-30,1974-08-22,38.63766,-90.33948,175,Hanley Road and Lake Forest Drive,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,5-20,1970-11-02,38.63731,-90.33537,107,Clayton Road and Glenridge Drive,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,6-24,1972-12-01,38.63683,-90.32976,102,Clayton Road and Boland Place - Crestwood Drive,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,6-23,1975-06-01,38.63588,-90.32499,034,Big Bend Boulevard and Clayton Road,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,7-19,1972-12-01,38.63473,-90.31856,Accepted on ARS471,"Clayton Road at Esquire Theatre, west of Concordia Lane",Clayton_Road_Lay_to_STLCity_Limit,Pedestrian Signal,COUNTY,12-27,1994-12-16,38.63459,-90.31659,477,Clayton Road and Highland Terrace at St. Rita Avenue,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,9-44,1995-07-05,38.63429,-90.3142,101,Clayton Road and Bellevue Avenue - Seminary Place,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,6-25,1972-12-01,38.63412,-90.31189,Accepted on ARS105,Clayton Road and DeMun Avenue - St. Mary's Health Center Entrance,Clayton_Road_Lay_to_STLCity_Limit,Traffic Signal,COUNTY,6-26,1972-12-01,38.6339,-90.30975,Accepted on ARS500,Big Bend Boulevard and Ethel Avenue,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,10-7,1997-07-16,38.63307,-90.31885,062,Big Bend Boulevard and Wise Avenue,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,8-16,1974-11-13,38.63104,-90.31927,738,Hanley Road and I-64 Eastbound Collector Road and I-64 Westbound Off Ramp,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,5-43,2009-12-06,38.62973,-90.3349,591,Eager Road and Musick Memorial Drive,Eager_Road_Brentwood_to_Hanley,Traffic Signal,COUNTY,1-35,2003-10-23,38.62921,-90.33775,548,"Eager Road and Brentwood Pointe Shopping Center West Entrance, west of Musick Memorial Drive",Eager_Road_Brentwood_to_Hanley,Traffic Signal,COUNTY,1-11,2001-11-16,38.6292,-90.34002,739,Big Bend Boulevard and I-64 Eastbound Off Ramp and I-64 Westbound Collector Road,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,6-8,2009-12-06,38.62919,-90.31971,036,Big Bend Boulevard and Dale Avenue,Big_Bend_Boulevard_Berry_to_Delmar,Traffic Signal,COUNTY,8-17,1974-08-19,38.62779,-90.31995,169,Hanley Road and Dale Avenue - Musick Memorial Drive,Hanley_Road_Laclede_Station_to_Saint_Charles_Rock,Traffic Signal,COUNTY,1-44,1970-10-01,38.62766,-90.33488,data/raw/modot/modot_aadt_2025_corridor.csvMoDOT 2025 road segments: daily traffic, lanes, speed limits.
road,inv_dir,beg_log,end_log,seg_desc,dir_aadt,roadway_aadt,aadt_year,lanes,speed_limit,roadway_type,pct_commercial,start_lat,start_lon,end_lat,end_lonBIG BEND BLVD,E,4.773,5.437,IS 64,13657.0,28367.0,2025,2,35,MULTI-LANE,0.05,38.61969,-90.32158,38.62924,-90.31969BIG BEND BLVD,E,5.437,5.827,CLAYTON RD,11468.0,23748.0,2025,2,35,MULTI-LANE,0.063,38.62924,-90.31969,38.63482,-90.31854BIG BEND BLVD,E,5.827,6.711,FORSYTH BLVD,10886.0,21909.0,2025,2,35,MULTI-LANE,0.05,38.63482,-90.31854,38.64739,-90.31577BIG BEND BLVD,E,6.711,7.005,FOREST PARK PKWY,11909.0,25570.0,2025,2,30,MULTI-LANE,0.05,38.64739,-90.31577,38.65159,-90.31489BIG BEND BLVD,E,7.005,7.373,DELMAR BLVD,11909.0,25570.0,2025,2,30,MULTI-LANE,0.05,38.65159,-90.31489,38.65685,-90.31396BIG BEND BLVD,W,0.0,0.368,DELMAR BLVD,13661.0,25570.0,2025,2,30,MULTI-LANE,0.05,38.65685,-90.31396,38.65159,-90.31489BIG BEND BLVD,W,0.368,0.662,FOREST PARK PKWY,13661.0,25570.0,2025,2,30,MULTI-LANE,0.05,38.65159,-90.31489,38.64739,-90.31577BIG BEND BLVD,W,0.662,1.546,FORSYTH BLVD,11023.0,21909.0,2025,2,35,MULTI-LANE,0.059,38.64739,-90.31577,38.63482,-90.31854BIG BEND BLVD,W,1.546,1.936,CLAYTON RD,12280.0,23748.0,2025,2,35,MULTI-LANE,0.05,38.63482,-90.31854,38.62924,-90.31969BIG BEND BLVD,W,1.936,2.6,IS 64,14710.0,28367.0,2025,2,35,MULTI-LANE,0.05,38.62924,-90.31969,38.61969,-90.32158BLAND DR,E,0.113,0.142,CST BLAND DR E,3642.0,3642.0,2025,1, ,,0.051,38.64841,-90.32855,38.64859,-90.32807CLAYTON RD,E,17.459,17.549,CST S BRENTWOOD BLVD,6931.0,12293.0,2025,2,35,5 LANE SECTION,0.06,38.63812,-90.34558,38.63796,-90.34392CLAYTON RD,E,17.549,18.002,IS 170,6891.0,12253.0,2025,3,35,5 LANE SECTION,0.033,38.63796,-90.34392,38.63775,-90.33554CLAYTON RD,E,18.002,18.949,HANLEY RD,6854.0,12576.0,2025,3,35,5 LANE SECTION,0.033,38.63775,-90.33554,38.63482,-90.31854CLAYTON RD,E,18.949,19.612,BIG BEND BLVD,8321.0,18111.0,2025,4,35,5 LANE SECTION,0.05,38.63482,-90.31854,38.63359,-90.30639CLAYTON RD,E,19.612,19.727,BIG BEND BLVD,8321.0,18111.0,2025,5,35,5 LANE SECTION,0.05,38.63359,-90.30639,38.63341,-90.30428CLAYTON RD,W,0.0,0.115,BIG BEND BLVD,9790.0,18111.0,2025,3,35,5 LANE SECTION,0.05,38.63341,-90.30428,38.63359,-90.30639CLAYTON RD,W,0.115,0.778,BIG BEND BLVD,9790.0,18111.0,2025,3,35,5 LANE SECTION,0.05,38.63359,-90.30639,38.63482,-90.31854CLAYTON RD,W,0.778,1.723,HANLEY RD,5722.0,12576.0,2025,2,35,5 LANE SECTION,0.047,38.63482,-90.31854,38.63775,-90.33554CLAYTON RD,W,1.723,2.176,IS 170,5362.0,12253.0,2025,2,35,5 LANE SECTION,0.037,38.63775,-90.33554,38.63796,-90.34392CLAYTON RD,W,2.176,2.266,CST S BRENTWOOD BLVD,5362.0,12293.0,2025,2,35,5 LANE SECTION,0.037,38.63796,-90.34392,38.63812,-90.34558DELMAR BLVD,E,0.51,1.706,CST MCKNIGHT RD,7869.0,14746.0,2025,1, ,MULTI-LANE,0.05,38.66082,-90.35713,38.65909,-90.33515DELMAR BLVD,E,1.706,2.862,BEMISTON AVE,8758.0,17697.0,2025,1, ,MULTI-LANE,0.05,38.65909,-90.33515,38.65685,-90.31396DELMAR BLVD,E,2.862,3.372,BIG BEND BLVD,6126.0,12475.0,2025,1, ,3 LANE SECTION,0.033,38.65685,-90.31396,38.65594,-90.3046DELMAR BLVD,E,3.372,3.521,WESTGATE AVE,8758.0,17697.0,2025,1, ,3 LANE SECTION,0.05,38.65594,-90.3046,38.65566,-90.30186DELMAR BLVD,E,3.521,4.344,SKINKER BLVD,4094.0,7441.0,2025,1, ,EXPRESSWAY,0.051,38.65566,-90.30186,38.65411,-90.28678DELMAR BLVD,W,2.804,3.507,SKINKER BLVD,3347.0,7441.0,2025,1, ,EXPRESSWAY,0.05,38.65423,-90.28677,38.65546,-90.29968DELMAR BLVD,W,3.507,3.626,WESTGATE AVE,8939.0,17697.0,2025,1, ,3 LANE SECTION,0.05,38.65546,-90.29968,38.65566,-90.30186DELMAR BLVD,W,3.626,3.775,WESTGATE AVE,8939.0,17697.0,2025,1, ,3 LANE SECTION,0.05,38.65566,-90.30186,38.65594,-90.3046DELMAR BLVD,W,3.775,4.285,BIG BEND BLVD,6349.0,12475.0,2025,1, ,3 LANE SECTION,0.049,38.65594,-90.3046,38.65685,-90.31396DELMAR BLVD,W,4.285,5.441,BEMISTON AVE,8939.0,17697.0,2025,1, ,MULTI-LANE,0.05,38.65685,-90.31396,38.65909,-90.33515DELMAR BLVD,W,5.441,6.637,CST N BEMISTON AVE,6877.0,14746.0,2025,1, ,MULTI-LANE,0.05,38.65909,-90.33515,38.66082,-90.35713FOREST PARK PKWY,E,0.0,0.837,IS 170,11832.0,19353.0,2025,2,40,EXPRESSWAY,0.05,38.64662,-90.34959,38.64671,-90.3345FOREST PARK PKWY,E,0.837,2.002,CST HANLEY RD,6271.0,12632.0,2025,2,40,EXPRESSWAY,0.027,38.64671,-90.3345,38.65159,-90.31489FOREST PARK PKWY,E,2.002,2.668,CST BIG BEND BLVD,6593.0,13186.0,2025,2,40,EXPRESSWAY,0.05,38.65159,-90.31489,38.64954,-90.30289FOREST PARK PKWY,E,2.668,2.788,CST BIG BEND BLVD,6593.0,13186.0,2025,2,40,EXPRESSWAY,0.05,38.64954,-90.30289,38.64931,-90.30069FOREST PARK PKWY,E,2.788,3.624,SKINKER BLVD,5617.0,9859.0,2025,2,40,EXPRESSWAY,0.051,38.64931,-90.30069,38.64762,-90.28542FOREST PARK PKWY,W,1.279,2.115,SKINKER BLVD,4242.0,9859.0,2025,1,40,EXPRESSWAY,0.049,38.6477,-90.28542,38.64931,-90.30069FOREST PARK PKWY,W,2.115,2.235,CST BIG BEND BLVD,6593.0,13186.0,2025,1,40,,0.05,38.64931,-90.30069,38.64954,-90.30289FOREST PARK PKWY,W,2.235,2.901,CST BIG BEND BLVD,6593.0,13186.0,2025,1,40,EXPRESSWAY,0.05,38.64954,-90.30289,38.65159,-90.31489FOREST PARK PKWY,W,2.901,4.065,CST HANLEY RD,6361.0,12632.0,2025,1,40,EXPRESSWAY,0.05,38.65159,-90.31489,38.6469,-90.33449FOREST PARK PKWY,W,4.065,4.899,IS 170,7521.0,19353.0,2025,1,40,EXPRESSWAY,0.05,38.6469,-90.33449,38.64667,-90.34959FORSYTH BLVD,E,0.0,0.243,KINGSBURY AVE,3578.0,7156.0,2025,1, ,EXPRESSWAY,0.05,38.65583,-90.34373,38.65236,-90.34346FORSYTH BLVD,E,0.243,1.18,MARYLAND AVE,2928.0,5856.0,2025,1, ,MULTI-LANE,0.05,38.65236,-90.34346,38.64874,-90.32828FORSYTH BLVD,E,1.18,2.541,FOREST PARK PKWY W,3448.0,6896.0,2025,1, ,TWO-LANE,0.05,38.64874,-90.32828,38.64621,-90.30342FORSYTH BLVD,E,2.541,2.663,FOREST PARK PKWY W,3448.0,6896.0,2025,1, ,TWO-LANE,0.05,38.64621,-90.30342,38.646,-90.30119FORSYTH BLVD,W,0.0,0.122,FOREST PARK PKWY W,3448.0,6896.0,2025,1, ,TWO-LANE,0.05,38.646,-90.30119,38.64621,-90.30342FORSYTH BLVD,W,0.122,1.483,FOREST PARK PKWY W,3448.0,6896.0,2025,1, ,TWO-LANE,0.05,38.64621,-90.30342,38.64874,-90.32828FORSYTH BLVD,W,1.483,2.42,MARYLAND AVE,2928.0,5856.0,2025,1, ,MULTI-LANE,0.05,38.64874,-90.32828,38.65236,-90.34346FORSYTH BLVD,W,2.42,2.667,KINGSBURY AVE,3578.0,7156.0,2025,1, ,EXPRESSWAY,0.05,38.65236,-90.34346,38.65585,-90.34362HANLEY RD,N,0.0,2.233,CLAYTON RD,14203.0,28002.0,2025,2,35,MULTI-LANE,0.05,38.60592,-90.33202,38.63775,-90.33554HANLEY RD,N,2.233,4.585,MO 340,5807.0,11823.0,2025,2,35,MULTI-LANE,0.05,38.63775,-90.33554,38.67167,-90.33162HANLEY RD,S,1.945,4.297,MO 340,6016.0,11823.0,2025,2,35,MULTI-LANE,0.05,38.67167,-90.33162,38.63775,-90.33554HANLEY RD,S,4.297,6.53,CLAYTON RD,13799.0,28002.0,2025,2,35,MULTI-LANE,0.05,38.63775,-90.33554,38.60592,-90.33202SKINKER BLVD,N,0.0,0.054,CLAYTON RD,6118.0,11840.0,2025,2,35,5 LANE SECTION,0.051,38.63265,-90.3045,38.63341,-90.30428SKINKER BLVD,N,0.054,1.17,FOREST PARK PKWY,13052.0,26195.0,2025,2,35,5 LANE SECTION,0.05,38.63341,-90.30428,38.64931,-90.30069SKINKER BLVD,N,1.17,1.968,OLIVE BLVD,11382.0,21922.0,2025,2,35,5 LANE SECTION,0.07,38.64931,-90.30069,38.66056,-90.29771SKINKER BLVD,S,0.0,0.798,OLIVE BLVD,10540.0,21922.0,2025,2,35,5 LANE SECTION,0.085,38.66061,-90.29783,38.64931,-90.30069SKINKER BLVD,S,0.798,1.914,FOREST PARK PKWY,13143.0,26195.0,2025,2,35,5 LANE SECTION,0.05,38.64931,-90.30069,38.63341,-90.30428SKINKER BLVD,S,1.914,1.968,CLAYTON RD,5722.0,11840.0,2025,2,35,5 LANE SECTION,0.051,38.63341,-90.30428,38.63265,-90.3045WYDOWN BLVD,E,0.0,1.728,HANLEY RD,1817.0,3650.0,2025,1, ,EXPRESSWAY,0.041,38.64301,-90.33499,38.64465,-90.30387WYDOWN BLVD,E,1.728,1.853,HANLEY RD,1817.0,3650.0,2025,1, ,EXPRESSWAY,0.041,38.64465,-90.30387,38.64451,-90.3016WYDOWN BLVD,W,0.0,0.122,HANLEY RD,1833.0,3650.0,2025,1, ,EXPRESSWAY,0.025,38.64451,-90.3016,38.64482,-90.30379WYDOWN BLVD,W,0.122,1.855,HANLEY RD,1833.0,3650.0,2025,1, ,EXPRESSWAY,0.025,38.64482,-90.30379,38.64324,-90.33497