Spaces:
Running
Running
File size: 22,100 Bytes
06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 06dd70b 3a1af59 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | # openenv.yaml
# IntelliFlow Urban Traffic Control Environment
# OpenEnv Specification Metadata v1.2.0
# βββββββββββββββββββββββββββββββββββββββββββββ
name: IntelliFlow Urban Traffic Control
version: "1.2.0"
description: >
A production-grade reinforcement learning simulation environment modelling
a realistic urban intersection (single-node) and a 3Γ3 multi-intersection
grid (MARL) as controllable episodic decision systems.
An intelligent agent dynamically optimises traffic signal phases to minimise
congestion, waiting time, lane starvation, and emission proxies while
maximising vehicle throughput and systemic efficiency.
New in v1.1: MARL grid tasks, emergency vehicle preemption, weather-aware
simulation, COβ/economic impact tracking, and LLM meta-controller.
authors:
- IntelliFlow Research Team
real_world_domain: Urban Transportation / Smart City Infrastructure
tags:
- traffic-control
- reinforcement-learning
- urban-simulation
- multi-objective
- multi-agent
- openenv
# βββββββββββββββββββββββββββββββββββββββββββββ
# Observation Space β Single-Node Tasks
# βββββββββββββββββββββββββββββββββββββββββββββ
observation_space:
type: Box
dtype: float32
shape: [57]
bounds:
low: -1.0 # pressure_differential can be negative
high: 1.0
description: >
57-dimensional continuous observation vector encoding the full intersection
state at each simulation step (single-node tasks only).
MARL grid tasks use a 73-dimensional extended vector β see marl_observation_space.
components:
- name: queue_lengths
indices: [0, 11] # inclusive range
dim: 12
description: >
Normalised queue length per lane [0,1].
0 = empty, 1 = at capacity.
Lane order: N_through, N_right, S_through, S_right,
E_through, E_right, W_through, W_right,
N_left, S_left, E_left, W_left.
- name: throughput_recent
indices: [12, 23]
dim: 12
description: >
Recent 10-step normalised throughput per lane.
Computed as vehicles_cleared / capacity.
- name: arrival_intensity
indices: [24, 35]
dim: 12
description: >
Estimated Poisson arrival intensity per lane, normalised
by saturation flow rate. Derived from 10-step sliding window.
- name: phase_onehot
indices: [36, 39]
dim: 4
description: >
One-hot encoding of current signal phase.
[NS_GREEN, EW_GREEN, ALL_RED, NS_MINOR]
- name: phase_elapsed_norm
indices: [40]
dim: 1
description: >
Elapsed time in current phase normalised by max_phase_duration.
- name: fairness_score
indices: [41]
dim: 1
description: >
Normalised variance of per-lane accumulated wait times.
0 = perfectly fair, 1 = maximally unfair.
- name: pressure_differential
indices: [42]
dim: 1
description: >
(NS_pressure - EW_pressure) / total_pressure.
In [-1, 1]. Positive = NS approach has more queue pressure.
- name: avg_delay_norm
indices: [43]
dim: 1
description: >
Rolling average vehicle delay (s) normalised by 120s.
Clamped to [0, 1].
- name: step_norm
indices: [44]
dim: 1
description: Episode progress in [0, 1].
- name: spillback_flags
indices: [45, 56]
dim: 12
description: >
Binary spillback risk indicator per lane.
1 = queue β₯ 85% of capacity (spillback imminent).
# βββββββββββββββββββββββββββββββββββββββββββββ
# Observation Space β MARL Grid Tasks
# βββββββββββββββββββββββββββββββββββββββββββββ
marl_observation_space:
type: Box
dtype: float32
shape: [73]
obs_dim: 73
bounds:
low: -1.0
high: 1.0
description: >
73-dimensional extended observation vector per agent in MARL grid tasks.
Appended to the standard 57-dim base observation.
components:
- name: base_observation
indices: [0, 56]
dim: 57
description: >
Standard single-node observation (see observation_space above).
- name: lstm_predictions
indices: [57, 68]
dim: 12
description: >
12-dim predicted inflow vector for the next step from the per-node
LSTMPredictor trained on historical arrival data. All zeros if
lstm_weights.json is absent or training has not yet occurred.
- name: neighbor_queue_pressures
indices: [69, 72]
dim: 4
description: >
Normalised total queue pressure (NS + EW combined) from up to 4
adjacent nodes in the 3Γ3 grid. Zero-padded for corner/edge nodes
with fewer than 4 neighbors.
Grid adjacency (row-major): node 0 = top-left, node 8 = bottom-right.
Neighbors: 0β[1,3], 1β[0,2,4], 2β[1,5], 3β[0,4,6],
4β[1,3,5,7], 5β[2,4,8], 6β[3,7], 7β[4,6,8], 8β[5,7].
# βββββββββββββββββββββββββββββββββββββββββββββ
# Action Space
# βββββββββββββββββββββββββββββββββββββββββββββ
action_space:
type: Discrete
n: 5
actions:
0:
name: MAINTAIN
description: Keep current signal phase unchanged
1:
name: SWITCH_PHASE
description: Toggle to orthogonal phase (N-S β E-W green)
constraint: Only effective if phase_elapsed >= min_phase_duration (5 steps)
2:
name: EXTEND_GREEN
description: >
Implicitly extend current green phase. The agent signals intent
to hold the current phase; the phase auto-switches at max_phase_duration.
3:
name: FORCE_ALL_RED
description: Immediately enter all-red safety interval (3 steps)
4:
name: YIELD_MINOR
description: >
Enter NS_MINOR phase to give brief green to minor side-road
right-turn approaches.
# βββββββββββββββββββββββββββββββββββββββββββββ
# Reward Function
# βββββββββββββββββββββββββββββββββββββββββββββ
reward:
type: dense
frequency: every_step
range: "approximately [-1.5, +1.5] per step under normal conditions"
marl_note: >
In MARL grid tasks each agent receives its own per-node reward plus a
shared coordination bonus: -0.15 * total_network_spillback_count.
This incentivises agents to cooperate and reduce cascade spillback.
design_principles:
- "Positive baseline: near zero on neutral steps, clearly positive when doing well"
- "Delta-based queue signal: rewards queue REDUCTION, not just penalising absolute size"
- "Context-aware switch penalty: oscillation penalised; pressure-justified switches are not"
- "Max-deviation fairness: detects single starved lane; variance averages it away"
- "Escalating spillback: quadratic severity above 85% capacity"
- "Proactive bonus: rewards switching when pressure differential is genuinely high"
components:
throughput_bonus:
formula: "w_throughput * (vehicles_cleared / max_possible_clearance_this_step)"
range: "[0, ~+1.2]"
queue_delta_reward:
formula: "w_wait * clip((prev_queue - curr_queue) / (n_lanes * capacity), -1, 1)"
range: "[-0.8, +0.8]"
congestion_pressure:
formula: "-0.3 * (occupancy_rate ** 2)"
range: "[-0.3, 0]"
starvation_penalty:
formula: "w_fairness * max_deviation(main_through_lane_occupancies)"
range: "[-0.5, 0]"
switch_penalty:
formula: "w_switch * [1.0 if premature+unjustified | 0.3 if premature+justified | 0 otherwise]"
range: "[-0.25, 0]"
spillback_severity:
formula: "w_spillback * mean(max(0, (occ - 0.85)/0.15) for each lane)"
range: "[-0.85, 0]"
gridlock_cliff:
formula: "-8.0 * fraction_of_gridlocked_lanes"
range: "[-8.0, 0]"
proactive_bonus:
formula: "0.2 * pressure_diff if (switched AND pressure_diff > 0.3)"
range: "[0, +0.2]"
coordination_bonus_marl_only:
formula: "-0.15 * total_network_spillback_count"
range: "[-1.35, 0]"
description: >
Applied to every agent's reward in MARL grid tasks. Promotes
network-wide cooperation to suppress cascade spillback.
# βββββββββββββββββββββββββββββββββββββββββββββ
# Tasks
# βββββββββββββββββββββββββββββββββββββββββββββ
tasks:
# --- Single-node tasks ---
- id: task_suburban_steady
name: Suburban Steady Flow
difficulty: easy
horizon: 600
obs_dim: 57
grid_mode: false
description: >
Low, symmetric, near-deterministic arrivals. Optimal policy is
fair green time allocation. Good baseline for verifying signal logic.
grader: weighted_composite
score_range: [0.0, 1.0]
expected_baseline_score: 0.55
baseline_policy: pressure
baseline_seed: 42
score_note: >
Measured via /benchmark endpoint, pressure policy, seed 42.
LLM agent (gpt-4o-mini) achieves 0.61-0.67 on this task.
- id: task_urban_stochastic
name: Urban Stochastic Rush
difficulty: medium
horizon: 1200
obs_dim: 57
grid_mode: false
description: >
Bursty, asymmetric inflows with stochastic lambda perturbation.
Requires adaptive timing and predictive reasoning.
grader: weighted_composite
score_range: [0.0, 1.0]
expected_baseline_score: 0.42
- id: task_rush_hour_crisis
name: Rush Hour Crisis
difficulty: hard
horizon: 1800
obs_dim: 57
grid_mode: false
description: >
Maximum load scenario: rain, blocked lane, near-saturation arrivals,
congestion cascade risk. Agent must survive gridlock and maintain
minimum viable throughput.
grader: weighted_composite
score_range: [0.0, 1.0]
expected_baseline_score: 0.30
# --- MARL 3x3 grid tasks ---
- id: task_grid_steady
name: "Grid: Suburban Steady Flow (3x3)"
difficulty: medium
horizon: 600
obs_dim: 73
grid_mode: true
n_agents: 9
description: >
Nine suburban intersections in a 3x3 grid under steady symmetric flow.
Agents must coordinate to prevent cascade spillback. Per-node dynamics
mirror task_suburban_steady. Observation extended with LSTM predictions
and neighbor queue pressures. Score = mean across 9 nodes.
grader: weighted_composite_mean_9
score_range: [0.0, 1.0]
expected_baseline_score: 0.50
- id: task_grid_rush
name: "Grid: Urban Stochastic Rush (3x3)"
difficulty: hard
horizon: 1200
obs_dim: 73
grid_mode: true
n_agents: 9
description: >
Nine urban intersections under stochastic asymmetric rush-hour flow.
Agents must coordinate green corridors across the network.
Per-node dynamics mirror task_urban_stochastic.
Score = mean across 9 nodes.
grader: weighted_composite_mean_9
score_range: [0.0, 1.0]
expected_baseline_score: 0.36
- id: task_grid_crisis
name: "Grid: Rush Hour Crisis (3x3)"
difficulty: hard
horizon: 1800
obs_dim: 73
grid_mode: true
n_agents: 9
description: >
Nine intersections under maximum load β rain, blocked lane per node,
near-saturation arrivals. Early termination if any node sustains
gridlock for 20 steps. Score = mean across 9 nodes.
grader: weighted_composite_mean_9
score_range: [0.0, 1.0]
expected_baseline_score: 0.24
# βββββββββββββββββββββββββββββββββββββββββββββ
# Episode Configuration
# βββββββββββββββββββββββββββββββββββββββββββββ
episode:
termination_conditions:
- horizon_reached: "step_count >= horizon"
- sustained_gridlock: "gridlock_steps >= 20 AND is_gridlock"
- marl_any_node_gridlock: >
In MARL grid tasks, episode terminates if ANY node sustains
gridlock for 20 consecutive steps.
reset: stochastic_seed_or_fixed
seeding: supported
# βββββββββββββββββββββββββββββββββββββββββββββ
# Features
# βββββββββββββββββββββββββββββββββββββββββββββ
features:
marl_grid:
description: >
3x3 grid of 9 cooperating traffic agents. Activate via grid_mode=true
in /reset or use MARL task IDs directly.
endpoints: [/reset, /ab_reset, /ab_step]
emergency_preemption:
description: >
Emergency vehicle (ambulance/fire/police) dispatched through the grid.
BFS route planned; preemption signals lock intersection phases ahead
of vehicle arrival. Active emergencies create a green corridor.
endpoints: [/emergency]
weather_control:
description: >
Live mid-episode weather toggle. Affects discharge multipliers and
arrival variance. Modes: CLEAR (1.0x), RAIN (0.75x), HEAVY_RAIN (0.60x),
FOG (0.85x). Can be changed any step without resetting the episode.
endpoints: [/weather]
discharge_multipliers:
CLEAR: 1.00
RAIN: 0.75
HEAVY_RAIN: 0.60
FOG: 0.85
incident_injection:
description: >
Lane-level incident simulation. BLOCKAGE sets sat_flow=0,
BREAKDOWN sets sat_flow=0.5x, DEMAND_SPIKE adds +0.4 to arrival lambda.
Auto-clears after duration_steps.
endpoints: [/incident]
llm_meta_controller:
description: >
Natural language traffic management commands interpreted by an LLM.
Translates to phase overrides and reward weight deltas injected into
the environment for a specified duration. Requires OPENAI_API_KEY.
endpoints: [/commander, /narrate]
impact_tracking:
description: >
Per-session COβ, fuel, and economic impact calculator relative to a
fixed-cycle baseline. Constants: petrol idle burn 0.5 ml/s, COβ per ml
petrol 2.31g, βΉ95/litre, 1 tree absorbs 21kg COβ/year.
endpoints: [/grader, /narrate]
ab_comparison:
description: >
Paired MARL vs fixed-cycle baseline sessions from identical seeds.
Step both simultaneously and compare delta metrics.
endpoints: [/ab_reset, /ab_step]
visualiser_3d:
description: >
BabylonJS/Three.js 3D WebGL dashboard. Polls /state every 500ms.
Displays signal colours, queue visual counts, weather particles,
and green corridor overlay for emergency vehicles.
endpoints: [/viz, /viz3d, /state]
lstm_predictor:
description: >
Pure NumPy LSTM predictor (no PyTorch/TF). Provides 12-dim inflow
predictions per MARL agent. Trains offline at end of each episode
and serialises weights to app/api/lstm_weights.json.
# βββββββββββββββββββββββββββββββββββββββββββββ
# API Endpoints
# βββββββββββββββββββββββββββββββββββββββββββββ
api:
framework: FastAPI
base_url: "/"
endpoints:
# Core OpenEnv
- path: /reset
method: POST
description: >
Initialize new episode session. Set grid_mode=true for MARL 3x3 grid.
params: [task_id, seed, grid_mode]
- path: /step
method: POST
description: Apply single-node action, advance simulation one step
params: [session_id, action]
- path: /state
method: GET
description: >
Current full environment state including render_hints block
(signal_colors, queue_visual_counts, weather_mode,
corridor_active, corridor_path).
params: [session_id]
- path: /tasks
method: GET
description: List all 6 tasks with action/observation schemas
- path: /tasks/{task_id}
method: GET
description: Get specification for a specific task
- path: /grader
method: POST
description: >
Compute episode score [0,1] with sub-scores and impact_summary
(co2_saved_g, fuel_saved_ml, economic_value_inr, trees_equivalent).
params: [session_id]
- path: /baseline
method: POST
description: Run baseline policy evaluation (pressure/fixed_cycle/random)
params: [task_id, policy, seed, use_llm]
- path: /analytics
method: GET
description: >
Rich episode analytics: phase stats, LOS breakdown, time-series,
emissions, green split, efficiency vs theoretical maximum.
params: [session_id]
- path: /benchmark
method: POST
description: Multi-seed reproducibility benchmark with meanΒ±std score
params: [task_id, seeds]
# MARL / Grid
- path: /ab_reset
method: POST
description: >
Create paired MARL session and fixed-cycle baseline session from
identical seeds for A/B comparison.
params: [task_id, seed]
- path: /ab_step
method: POST
description: >
Step both MARL and baseline sessions simultaneously.
Returns delta_score, delta_throughput, delta_avg_delay.
params: [marl_session_id, baseline_session_id, marl_actions]
# Feature toggles
- path: /weather
method: POST
description: >
Toggle weather mode mid-episode. Modes: CLEAR, RAIN, HEAVY_RAIN, FOG.
Returns discharge_multiplier and projected_throughput_change.
params: [session_id, mode]
- path: /incident
method: POST
description: >
Inject lane incident. Types: BLOCKAGE, BREAKDOWN, DEMAND_SPIKE.
Auto-clears after duration_steps.
params: [session_id, node_id, lane_id, incident_type, duration_steps]
# Emergency vehicle
- path: /emergency
method: POST
description: >
Dispatch emergency vehicle through grid. Returns BFS path,
preemption schedule, and vehicle_id. Attaches to session;
scheduler ticks automatically on each /step call.
params: [session_id, entry_node, dest_node, vehicle_type]
# LLM Commander
- path: /commander
method: POST
description: >
Natural language traffic command interpreted by LLM (OpenAI).
Returns llm_reasoning, actions_injected, override_duration,
affected_nodes. Requires OPENAI_API_KEY.
params: [session_id, natural_language_command]
- path: /narrate
method: POST
description: >
Generate 3-sentence human-readable impact narrative for current episode.
Returns narrative_text, co2_saved_g, fuel_saved_ml,
economic_value_inr, trees_equivalent.
params: [session_id]
# Visualisation
- path: /viz
method: GET
description: Live BabylonJS 3D traffic simulation dashboard
- path: /viz3d
method: GET
description: >
Three.js WebGL 3D visualiser page. Polls /state every 500ms.
Renders signal colours, queue volumes, rain particles (weather),
and green corridor overlay (emergency vehicles).
- path: /viz/snapshot
method: GET
description: Lightweight visualisation-ready data snapshot
params: [session_id]
# Admin
- path: /health
method: GET
description: Service health check with active session count
- path: /sessions
method: GET
description: List all active sessions with type (single/marl)
- path: /save_weights
method: POST
description: Persist DQN weights to disk and HuggingFace Hub
- path: /load_weights
method: GET
description: Load DQN weights from disk or HuggingFace Hub
# βββββββββββββββββββββββββββββββββββββββββββββ
# Deployment
# βββββββββββββββββββββββββββββββββββββββββββββ
deployment:
platform: "Hugging Face Docker Space"
framework: "FastAPI + Uvicorn"
port: 7860
health_endpoint: /health
environment_variables:
required: []
optional:
- name: OPENAI_API_KEY
description: >
Required for /commander and /narrate LLM endpoints.
If absent those endpoints return HTTP 503.
- name: HF_TOKEN
description: HuggingFace token for DQN weight persistence across restarts
- name: HF_REPO_ID
description: HuggingFace repo for weight storage (default: your-username/your-repo-name)
# βββββββββββββββββββββββββββββββββββββββββββββ
# References
# βββββββββββββββββββββββββββββββββββββββββββββ
references:
- "Varaiya, P. (2013). Max pressure control of a network of signalized intersections."
- "Webster, F.V. (1958). Traffic signal settings. Road Research Technical Paper No. 39."
- "Sutton, R.S. & Barto, A.G. (2018). Reinforcement Learning: An Introduction. 2nd ed."
- "Lowrie, P.R. (1990). SCATS - Sydney Coordinated Adaptive Traffic System."
- "Hochreiter, S. & Schmidhuber, J. (1997). Long Short-Term Memory. Neural Computation." |