Spaces:
Running
Running
Commit Β·
06dd70b
0
Parent(s):
clean start
Browse filesFiles changed (18)
- .gitignoreAdded
- DockerfileAdded+45
- README.mdAdded+338
- app/__init__.pyAdded
- app/api/__init__.pyAdded
- app/api/main.pyAdded+457
- app/baseline/__init__.pyAdded
- app/baseline/policies.pyAdded+420
- app/core/__init__.pyAdded
- app/core/environment.pyAdded+837
- app/core/session.pyAdded+138
- app/tasks/__init__.pyAdded
- app/tasks/registry.pyAdded+369
- app/viz/__init__.pyAdded
- app/viz/dashboard.pyAdded
- inference.pyAdded+426
- openenv.yamlAdded+291
- requirements.txtAdded+8
123456789101112131415161718192021222324252627282930313233343536373839404142434445# IntelliFlow Urban Traffic Control# Hugging Face Docker Space compatible image# Port: 7860 (HF default)
FROM python:3.11-slim
# MetadataLABEL maintainer="IntelliFlow Research"LABEL description="OpenEnv-compliant Urban Traffic RL Environment"LABEL version="1.0.0"
# System depsRUN apt-get update && apt-get install -y --no-install-recommends \ curl \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install Python dependencies first (layer caching)COPY requirements.txt .RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Create non-root user (HF requirement)RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app# Create persistent data directory for DQN weight storageRUN mkdir -p /data && chown -R appuser:appuser /dataUSER appuser
# Expose portEXPOSE 7860
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \ CMD curl -f http://localhost:7860/health || exit 1
# LaunchCMD ["uvicorn", "app.api.main:app", \ "--host", "0.0.0.0", \ "--port", "7860", \ "--workers", "1", \ "--log-level", "info"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338---title: IntelliFlow Openenvemoji: π¦colorFrom: redcolorTo: greensdk: dockerpinned: false---
### Team: Neural Ninjas π₯·# π¦ IntelliFlow Urban Traffic Control
> **OpenEnv-compliant reinforcement learning environment for intelligent urban traffic signal optimisation.** > A production-grade digital twin of a 4-way intersection with dense reward shaping, 3 progressive tasks, and a live visualisation dashboard.
---
## Motivation
Traffic signal control is one of the highest-impact, underdigitised optimisation problems in urban infrastructure. In a typical city, poorly timed signals account for 5β10% of total vehicle delay and significant idle-emission overhead. Adaptive signal control β directing green phases based on real-time queue pressure β can reduce average vehicle delay by 20β40% compared to fixed-cycle timers.
This environment models that decision problem as a formal RL task: an agent observes the intersection state and selects signal actions each second, with dense reward feedback that reflects throughput, fairness, and congestion avoidance simultaneously.
---
## Architecture
```intelliflow/βββ app/| βββ__init__.py β βββ core/| βββ βββ__init__.py β β βββ environment.py # Core simulation engine (TrafficEnvironment, Observation, Action)β β βββ session.py # Session management for stateful APIβ βββ tasks/| | βββ __init__.py β β βββ registry.py # Task specs, graders (TaskSpec, EpisodeGrader)β βββ api/| | βββ __init__.pyβ β βββ main.py # FastAPI application, all REST endpoints| | βββ dqn_weights.json # Pre-trained dqn agentβ βββ baseline/| | βββ __init__.py β β βββ policies.py # PressurePolicy, FixedCycle, Random, LLMPolicyβ βββ viz/| βββ __init__.pyβ βββ dashboard.py # Live HTML visualisation dashboardβββ inference.py # Standalone CLI baseline evaluation scriptβββ openenv.yaml # OpenEnv specification metadataβββ requirements.txtβββ Dockerfileβββ README.md```
---
## Quick Start
### Docker (recommended)
```bashdocker build -t intelliflow .docker run -p 7860:7860 intelliflow# Open http://localhost:7860```
### Local dev
```bashpip install -r requirements.txtuvicorn app.api.main:app --port 7860 --reload```
---
## API Reference
| Method | Endpoint | Description ||--------|----------|-------------|| `GET` | `/` | Landing page || `GET` | `/health`| Service health check || `POST` | `/reset` | Create new episode session || `POST` | `/step` | Apply action, advance simulation || `GET` | `/state` | Full current environment state || `GET` | `/tasks` | List all tasks + action/observation schemas || `GET` | `/tasks/{task_id}` | Specific task specification || `POST` | `/grader`| Score current/completed episode || `POST` | `/baseline` | Run baseline policy evaluation || `GET` | `/viz` | Live visualisation dashboard || `GET` | `/docs` | OpenAPI documentation |
### Example flow
```pythonimport requests
BASE = "http://localhost:7860"
# 1. Resetsession = requests.post(f"{BASE}/reset", json={ "task_id": "task_suburban_steady", "seed": 42}).json()sid = session["session_id"]obs = session["observation"]
# 2. Step loopfor _ in range(600): result = requests.post(f"{BASE}/step", json={ "session_id": sid, "action": 0 # MAINTAIN }).json() if result["done"]: break
# 3. Gradescore = requests.post(f"{BASE}/grader", json={"session_id": sid}).json()print(f"Score: {score['score']:.4f}")```
---
## Observation Space (57-dim float32)
| Component | Indices | Dim | Description ||-----------|---------|-----|-------------|| `queue_lengths` | 0β11 | 12 | Normalised queue per lane [0,1] || `throughput_recent` | 12β23 | 12 | 10-step rolling throughput per lane || `arrival_intensity` | 24β35 | 12 | Estimated Poisson Ξ» per lane (normalised) || `phase_onehot` | 36β39 | 4 | One-hot: [NS_GREEN, EW_GREEN, ALL_RED, NS_MINOR] || `phase_elapsed_norm` | 40 | 1 | Elapsed phase time / max_duration || `fairness_score` | 41 | 1 | Normalised wait-time variance || `pressure_differential` | 42 | 1 | (NS β EW pressure) / total β [β1, 1] || `avg_delay_norm` | 43 | 1 | Rolling avg delay / 120s || `step_norm` | 44 | 1 | Episode progress [0, 1] || `spillback_flags` | 45β56 | 12 | Binary spillback risk per lane |
---
## Action Space (Discrete, 5 actions)
| ID | Name | Description ||----|------|-------------|| 0 | MAINTAIN | Hold current phase || 1 | SWITCH_PHASE | Toggle N-S β E-W green || 2 | EXTEND_GREEN | Signal intent to hold green (delay auto-switch) || 3 | FORCE_ALL_RED | Immediate all-red safety interval || 4 | YIELD_MINOR | Brief green for minor road right-turns |
---
## Reward Function (dense, every step)
```R = w_throughput Γ vehicles_cleared + w_wait Γ (βtotal_queue) + w_fairness Γ (βfairness_variance) + w_switch Γ (βphase_switched) + w_spillback Γ (βspillback_count) + w_emission Γ (βtotal_queue) # emission proxy β 10.0 Γ gridlock_active```
Typical range: **[β20, +15]** per step. No sparse terminal rewards β the agent receives meaningful gradient signal throughout the trajectory.
---
## Tasks
### Task 1: Suburban Steady Flow `[EASY]` β Horizon: 600 steps
Low, symmetric, near-deterministic arrivals (Ξ» β 0.2 veh/step/lane). The optimal policy is straightforward green time balancing. Useful for verifying basic signal timing logic and establishing performance baselines.
**Grader formula:**```Score = 0.40 Γ throughput_efficiency + 0.30 Γ delay_score + 0.20 Γ fairness_score + 0.10 Γ stability_score```
Expected pressure-baseline score: **~0.55**
---
### Task 2: Urban Stochastic Rush `[MEDIUM]` β Horizon: 1200 steps
Heavy morning rush with asymmetric N-S dominance (Ξ»_N β 0.45). Lambda values are randomly perturbed each episode. The agent must adapt timing dynamically and predict inflow intensity to prevent starvation of minor approaches.
**Grader formula:**```Score = 0.35 Γ throughput_efficiency + 0.30 Γ delay_score + 0.20 Γ fairness_score + 0.15 Γ spillback_resilience```
Expected pressure-baseline score: **~0.42**
---
### Task 3: Rush Hour Crisis `[HARD]` β Horizon: 1800 steps
Near-saturation arrivals, rain reducing discharge by 25%, one lane blocked by incident. Congestion cascades are likely. The agent must survive gridlock and maintain minimum viable throughput. Early termination on sustained gridlock.
**Grader formula:**```Score = 0.30 Γ throughput_efficiency + 0.25 Γ delay_score + 0.20 Γ survival_bonus + 0.15 Γ fairness_score + 0.10 Γ stability_score```
Expected pressure-baseline score: **~0.30**
---
## Baseline Policies
### Pressure Policy (recommended baseline)
Implements Max-Pressure signal control (Varaiya, 2013): switch phase when pressure differential exceeds threshold, extend green when current approach is heavily loaded.
```bashpython inference.py --policy pressure --task all --seed 42```
### Fixed-Cycle Controller
Webster's optimal fixed-time controller (30s N-S, 30s E-W, 3s amber).
```bashpython inference.py --policy fixed_cycle --task all```
### LLM Agent (OpenAI)
```bashexport OPENAI_API_KEY=sk-...python inference.py --policy llm --task task_suburban_steady --seed 42```
### Using the `/baseline` endpoint
```bashcurl -X POST http://localhost:7860/baseline \ -H "Content-Type: application/json" \ -d '{"task_id": "task_suburban_steady", "policy": "pressure", "seed": 42}'```
---
## Grader
```bash# Via APIcurl -X POST http://localhost:7860/grader \ -H "Content-Type: application/json" \ -d '{"session_id": "<your-session-id>"}'```
Returns:```json{ "score": 0.5731, "sub_scores": { "throughput_efficiency": 0.6120, "delay_score": 0.5240, "fairness_score": 0.6800, "stability_score": 0.4900, "spillback_resilience": 0.7200, "survival_bonus": 1.0000 }, "trajectory_summary": { "total_cleared": 482, "total_arrived": 531, "steps_survived": 600, "avg_delay_seconds": 18.4 }}```
---
## Visualisation
Open `http://localhost:7860/viz` for the live dashboard featuring:
- Real-time intersection queue map with colour-coded signal states- Per-lane queue bar charts (green β amber β red as queues fill)- Live reward trajectory chart- Episode metrics: throughput, avg delay, fairness, score- Run the pressure policy live from the browser- ### Dashboard Preview



---
## Environment Design Notes
**Simulation model:** Discrete-time probabilistic digital twin. Each step = 1 second. **Arrivals:** Poisson sampling per lane with configurable Ξ», optionally perturbed per episode. **Discharge:** Constrained by saturation flow rate Γ weather factor Γ green permission. **Gridlock detection:** β₯70% of lanes at β₯90β95% capacity sustained for 20 steps triggers early termination. **Phase locking:** Minimum phase duration (5 steps) prevents oscillatory toggling β actions during lock are silently ignored.
---
## Expected Baseline Scores (seed=42)
| Task | Pressure | Fixed-Cycle | Random ||------|----------|-------------|--------|| Suburban Steady | ~0.55 | ~0.48 | ~0.25 || Urban Stochastic | ~0.42 | ~0.36 | ~0.18 || Rush Hour Crisis | ~0.30 | ~0.24 | ~0.11 |
LLM agents typically match or slightly exceed the pressure policy on tasks 1β2, and benefit from the pressure fallback on task 3.
---
## References
- Varaiya, P. (2013). Max pressure control of a network of signalized intersections. *Transportation Research Part C*, 36, 177β195.- Webster, F.V. (1958). *Traffic signal settings*. Road Research Technical Paper No. 39. HMSO, London.- Lowrie, P.R. (1990). *SCATS β Sydney Coordinated Adaptive Traffic System*. Roads and Traffic Authority NSW.- Sutton, R.S. & Barto, A.G. (2018). *Reinforcement Learning: An Introduction*. 2nd ed. MIT Press.
---
*IntelliFlow v1.0.0 β OpenEnv Hackathon Submission*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457"""IntelliFlow FastAPI ApplicationOpenEnv-compliant REST API for Urban Traffic Control Environment."""
from __future__ import annotations
import jsonfrom fastapi import Requestfrom fastapi.responses import JSONResponseimport osimport timefrom typing import Any, Dict, List, Optional
from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Field
from app.core.session import storefrom app.tasks.registry import TASK_REGISTRY, get_task_spec_dict
WEIGHTS_FILE = os.path.join(os.path.dirname(__file__), "dqn_weights.json")
# ---------------------------------------------------------------------------# App setup# ---------------------------------------------------------------------------
app = FastAPI( title="IntelliFlow Urban Traffic Control", description=( "A production-grade reinforcement learning simulation environment " "for intelligent urban traffic signal optimisation. " "Implements the OpenEnv specification with 3 progressive tasks." ), version="1.0.0", docs_url="/docs", redoc_url="/redoc",)
WEIGHTS_FILE = os.path.join(os.path.dirname(__file__), "dqn_weights.json")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
_start_time = time.time()
# ---------------------------------------------------------------------------# Pydantic schemas# ---------------------------------------------------------------------------
class ResetRequest(BaseModel): task_id: str = Field( default="task_suburban_steady", description="Task identifier. One of: task_suburban_steady, task_urban_stochastic, task_rush_hour_crisis" ) seed: Optional[int] = Field( default=None, description="Random seed for reproducibility. If None, a random seed is used." )
class StepRequest(BaseModel): session_id: str = Field(description="Session ID returned by /reset") action: int = Field(description="Action integer: 0=MAINTAIN, 1=SWITCH_PHASE, 2=EXTEND_GREEN, 3=FORCE_ALL_RED, 4=YIELD_MINOR")
class GraderRequest(BaseModel): session_id: str = Field(description="Session ID to grade")
class BaselineRequest(BaseModel): task_id: str = Field( default="task_suburban_steady", description="Task to evaluate baseline on" ) policy: str = Field( default="pressure", description="Baseline policy: 'pressure' (Webster/pressure heuristic), 'fixed_cycle', 'random'" ) seed: int = Field(default=42, description="Seed for reproducibility") use_llm: bool = Field( default=False, description="If True, uses OpenAI API for action selection (requires OPENAI_API_KEY)" )
# ---------------------------------------------------------------------------# Health & Info# ---------------------------------------------------------------------------
@app.get("/", response_class=HTMLResponse, tags=["Info"])async def root(): """Landing page with API overview.""" uptime = int(time.time() - _start_time) return f""" <html> <head> <title>IntelliFlow Traffic Control</title> <style> body {{ font-family: 'Courier New', monospace; background: #0a0e1a; color: #00ff88; padding: 40px; max-width: 900px; margin: 0 auto; }} h1 {{ color: #00d4ff; font-size: 2em; border-bottom: 1px solid #00ff88; }} h2 {{ color: #ffaa00; }} code {{ background: #1a2030; padding: 2px 8px; border-radius: 3px; color: #ff6688; }} .endpoint {{ background: #0d1525; border-left: 3px solid #00ff88; padding: 10px 15px; margin: 8px 0; border-radius: 0 5px 5px 0; }} .tag {{ color: #888; font-size: 0.85em; }} a {{ color: #00d4ff; }} </style> </head> <body> <h1>π¦ IntelliFlow Urban Traffic Control</h1> <p>OpenEnv-compliant RL environment for intelligent traffic signal optimisation.</p> <p class="tag">Uptime: {uptime}s | Version: 1.0.0 | Tasks: {len(TASK_REGISTRY)}</p>
<h2>Quick Start</h2> <div class="endpoint">POST <code>/reset</code> β Create new episode session</div> <div class="endpoint">POST <code>/step</code> β Apply action, advance simulation</div> <div class="endpoint">GET <code>/state?session_id=...</code> β Current observation + rich metrics</div> <div class="endpoint">GET <code>/tasks</code> β List all tasks + action schemas</div> <div class="endpoint">POST <code>/grader</code> β Score current/completed episode (0.0β1.0)</div> <div class="endpoint">GET <code>/analytics?session_id=...</code> β Phase stats, LOS, time-series, emissions</div> <div class="endpoint">POST <code>/baseline</code> β Run baseline policy evaluation</div> <div class="endpoint">POST <code>/benchmark?task_id=...&seeds=42,43,44</code> β Multi-seed reproducibility stats</div> <div class="endpoint">GET <code>/health</code> β Service health check</div> <div class="endpoint">GET <code>/docs</code> β Full OpenAPI documentation</div> <div class="endpoint">GET <code>/viz</code> β Live visualisation dashboard</div>
<h2>Tasks</h2> {"".join(f'<div class="endpoint"><b>{t.task_id}</b> [{t.difficulty.upper()}] β {t.name}</div>' for t in TASK_REGISTRY.values())}
<p>Full API docs: <a href="/docs">/docs</a> | <a href="/redoc">/redoc</a></p> </body> </html> """
@app.get("/health", tags=["Info"])async def health(): """Health check endpoint.""" return { "status": "ok", "uptime_seconds": round(time.time() - _start_time), "active_sessions": len(store._sessions), "tasks_available": list(TASK_REGISTRY.keys()), "version": "1.0.0", }
# ---------------------------------------------------------------------------# Core OpenEnv endpoints# ---------------------------------------------------------------------------
@app.post("/reset", tags=["OpenEnv"])async def reset(req: ResetRequest): """ Initialize a new episode session. Returns session_id, initial observation, and task metadata. """ try: session = store.create(req.task_id, seed=req.seed) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))
obs = session.env._build_observation() spec = TASK_REGISTRY[req.task_id]
return { "session_id": session.session_id, "task_id": req.task_id, "seed": req.seed, "observation": obs.to_dict(), "observation_vector": obs.to_vector().tolist(), "action_space": { "type": "Discrete", "n": spec.n_actions, "actions": {str(i): d for i, d in spec.action_descriptions.items()}, }, "horizon": spec.horizon, "obs_dim": spec.obs_dim, }
@app.post("/step", tags=["OpenEnv"])async def step(req: StepRequest): """ Apply action to environment, advance simulation by one step. Returns next observation, reward, done flag, and info dict. """ try: session = store.get(req.session_id) except KeyError as e: raise HTTPException(status_code=404, detail=str(e))
try: obs, reward, done, info = session.step(req.action) except RuntimeError as e: raise HTTPException(status_code=400, detail=str(e)) except AssertionError as e: raise HTTPException(status_code=422, detail=f"Invalid action: {e}")
return { "session_id": req.session_id, "observation": obs.to_dict(), "observation_vector": obs.to_vector().tolist(), "reward": reward, "done": done, "info": info, "step": session.step_count, }
@app.get("/state", tags=["OpenEnv"])async def state(session_id: str): """ Return full current environment state including lane details, metrics, and structured observation. """ try: session = store.get(session_id) except KeyError as e: raise HTTPException(status_code=404, detail=str(e))
state_dict = session.env.state() obs = session.env._build_observation() state_dict["observation_vector"] = obs.to_vector().tolist() state_dict["session_id"] = session_id state_dict["done"] = session.done return state_dict
# ---------------------------------------------------------------------------# Task registry# ---------------------------------------------------------------------------
@app.get("/tasks", tags=["Tasks"])async def list_tasks(): """List all available tasks with full specifications and action schemas.""" return { "tasks": [get_task_spec_dict(tid) for tid in TASK_REGISTRY], "count": len(TASK_REGISTRY), }
@app.get("/tasks/{task_id}", tags=["Tasks"])async def get_task(task_id: str): """Get specification for a specific task.""" if task_id not in TASK_REGISTRY: raise HTTPException( status_code=404, detail=f"Task {task_id!r} not found. Available: {list(TASK_REGISTRY.keys())}" ) return get_task_spec_dict(task_id)
# ---------------------------------------------------------------------------# Grader# ---------------------------------------------------------------------------
@app.post("/grader", tags=["Evaluation"])async def grader(req: GraderRequest): """ Compute episode score for a session. Can be called mid-episode or after completion. Returns score in [0.0, 1.0] with sub-score breakdown. """ try: session = store.get(req.session_id) except KeyError as e: raise HTTPException(status_code=404, detail=str(e))
return session.grade()
# ---------------------------------------------------------------------------# Baseline evaluation# ---------------------------------------------------------------------------
@app.post("/baseline", tags=["Evaluation"])async def baseline(req: BaselineRequest): """ Run a complete episode with a baseline policy and return score. Policies: 'pressure' (Webster heuristic), 'fixed_cycle', 'random'. Optionally uses OpenAI API if use_llm=True. """ from app.baseline.policies import run_baseline_episode
try: result = await run_baseline_episode( task_id=req.task_id, policy=req.policy, seed=req.seed, use_llm=req.use_llm, ) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"Baseline error: {e}")
return result
# ---------------------------------------------------------------------------# Visualisation# ---------------------------------------------------------------------------
@app.get("/viz", response_class=HTMLResponse, tags=["Visualisation"])async def visualisation(): """Live traffic simulation visualisation dashboard.""" from app.viz.dashboard import render_dashboard return render_dashboard()
@app.get("/viz/snapshot", tags=["Visualisation"])async def viz_snapshot(session_id: str): """Get visualisation-ready data snapshot for a session.""" try: session = store.get(session_id) except KeyError as e: raise HTTPException(status_code=404, detail=str(e))
state_dict = session.env.state() lanes = state_dict.get("lanes", [])
return { "session_id": session_id, "step": session.step_count, "done": session.done, "phase": state_dict.get("phase"), "phase_elapsed": state_dict.get("phase_elapsed"), "lanes": [ { "name": l["name"], "queue": l["queue"], "capacity": l["capacity"], "utilisation": round(l["queue"] / max(l["capacity"], 1), 3), "spillback": l["spillback"], "cleared": l["total_cleared"], "arrived": l["total_arrived"], } for l in lanes ], "metrics": state_dict.get("metrics", {}), }
# ---------------------------------------------------------------------------# Analytics & Benchmark# ---------------------------------------------------------------------------
@app.get("/analytics", tags=["Evaluation"])async def analytics(session_id: str): """ Rich episode analytics: phase statistics, LOS breakdown, time-series histories, emission estimates, green split, efficiency vs theoretical maximum. Use this for post-hoc analysis, visualisation, and judge review. """ try: session = store.get(session_id) except KeyError as e: raise HTTPException(status_code=404, detail=str(e))
return session.env.analytics()
@app.post("/benchmark", tags=["Evaluation"])async def benchmark(task_id: str = "task_suburban_steady", seeds: str = "42,43,44"): """ Run the pressure baseline across multiple seeds and return mean Β± std score β demonstrates reproducibility and score variance. """ from app.baseline.policies import run_baseline_episode
if task_id not in TASK_REGISTRY: raise HTTPException(status_code=400, detail=f"Unknown task: {task_id}")
seed_list = [int(s.strip()) for s in seeds.split(",") if s.strip().isdigit()] if not seed_list or len(seed_list) > 10: raise HTTPException(status_code=400, detail="Provide 1β10 comma-separated seeds")
results = [] for seed in seed_list: r = await run_baseline_episode(task_id=task_id, policy="pressure", seed=seed) results.append(r)
scores = [r["grade"]["score"] for r in results] mean_s = sum(scores) / len(scores) variance = sum((s - mean_s) ** 2 for s in scores) / max(len(scores), 1) std_s = variance ** 0.5
return { "task_id": task_id, "policy": "pressure", "seeds": seed_list, "scores": [round(s, 4) for s in scores], "mean_score": round(mean_s, 4), "std_score": round(std_s, 4), "min_score": round(min(scores), 4), "max_score": round(max(scores), 4), "reproducibility_note": ( "Score variance across seeds reflects genuine stochastic task difficulty, " "not implementation instability. Higher std on harder tasks is expected." ), "per_seed_details": [ { "seed": seed_list[i], "score": round(scores[i], 4), "metrics": results[i]["metrics"], } for i in range(len(seed_list)) ], }
# ---------------------------------------------------------------------------# Sessions management# ---------------------------------------------------------------------------
@app.get("/sessions", tags=["Admin"])async def list_sessions(): """List all active sessions.""" return {"sessions": store.list_sessions()}
# ---------------------------------------------------------------------------# DQN Weight Persistence# ---------------------------------------------------------------------------
@app.post("/save_weights", tags=["Admin"])async def save_weights(request: Request): """Save DQN weights to disk β called automatically by the dashboard JS.""" try: data = await request.json() with open(WEIGHTS_FILE, "w") as f: json.dump(data, f) return JSONResponse({"ok": True}) except Exception as e: return JSONResponse({"ok": False, "error": str(e)}, status_code=500)
@app.get("/load_weights", tags=["Admin"])async def load_weights(): """Load DQN weights from disk β called on dashboard startup.""" try: if not os.path.exists(WEIGHTS_FILE): return JSONResponse({"found": False}) with open(WEIGHTS_FILE, "r") as f: data = json.load(f) return JSONResponse({"found": True, "data": data}) except Exception as e: return JSONResponse({"found": False, "error": str(e)}, status_code=500)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420#!/usr/bin/env python3"""IntelliFlow Baseline Inference Script=====================================Runs the OpenAI-powered LLM agent (and pressure/fixed-cycle baselines)across all three tasks and outputs reproducible baseline scores.
Usage: python baseline_inference.py [--task all|<task_id>] [--policy pressure|fixed_cycle|random|llm] [--seed 42] [--host http://localhost:7860]
Requirements: pip install openai requests
Environment variables: OPENAI_API_KEY β required for --policy llm INTELLIFLOW_HOST β optional override for API host"""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport timeimport randomimport mathfrom typing import Any, Dict, List, Optional
try: import requestsexcept ImportError: print("ERROR: 'requests' package not found. Install with: pip install requests") sys.exit(1)
# ---------------------------------------------------------------------------# Configuration# ---------------------------------------------------------------------------
DEFAULT_HOST = os.environ.get("INTELLIFLOW_HOST", "http://localhost:7860")
TASKS = [ "task_suburban_steady", "task_urban_stochastic", "task_rush_hour_crisis",]
LANE_NAMES = [ "N_through", "N_right", "S_through", "S_right", "E_through", "E_right", "W_through", "W_right", "N_left", "S_left", "E_left", "W_left",]
# ---------------------------------------------------------------------------# Inline policies (no server dependency for action selection)# ---------------------------------------------------------------------------
class PressurePolicy: def __init__(self, switch_threshold: float = 3.0, min_steps: int = 5): self.threshold = switch_threshold self.min_steps = min_steps self._steps = 0
def act(self, obs: Dict) -> int: self._steps += 1 ql = obs.get("queue_lengths", [0.0]*12) phase_oh = obs.get("phase_onehot", [1,0,0,0]) idx = phase_oh.index(max(phase_oh)) elapsed_norm = obs.get("phase_elapsed_norm", 0) elapsed = elapsed_norm * 90
if elapsed < self.min_steps: return 0 # MAINTAIN
ns = sum(ql[i] for i in [0,1,2,3,8,9]) ew = sum(ql[i] for i in [4,5,6,7,10,11])
if idx == 2: # ALL_RED return 0 if idx == 0 and ew - ns > self.threshold * 0.1: self._steps = 0 return 1 if idx == 1 and ns - ew > self.threshold * 0.1: self._steps = 0 return 1 # Extend if high pressure on current if idx == 0 and ns > 0.75: return 2 if idx == 1 and ew > 0.75: return 2 return 0
class FixedCyclePolicy: def __init__(self, ns_green: int = 30, ew_green: int = 30): self.ns_green = ns_green self.ew_green = ew_green self._step = 0
def act(self, obs: Dict) -> int: self._step += 1 cycle = self.ns_green + 3 + self.ew_green + 3 pos = self._step % cycle if pos == self.ns_green: return 3 # FORCE_ALL_RED if pos == self.ns_green + 3: return 1 # SWITCH if pos == self.ns_green + 3 + self.ew_green: return 3 if pos == 0: return 1 return 0
class RandomPolicy: def __init__(self, seed: int = 42): self._rng = random.Random(seed)
def act(self, obs: Dict) -> int: return self._rng.randint(0, 4)
class LLMPolicy: SYSTEM = ( "You are an expert traffic signal controller AI. " "Control a 4-way intersection to maximise throughput and minimise delay.\n" "Actions: 0=MAINTAIN, 1=SWITCH_PHASE, 2=EXTEND_GREEN, 3=FORCE_ALL_RED, 4=YIELD_MINOR\n" "Respond ONLY with JSON: {\"action\": <0-4>}" )
def __init__(self, model: str = "gpt-4o-mini"): self.model = model self._fallback = PressurePolicy() self.calls = 0 self.latencies: List[float] = []
try: import openai self._client = openai.OpenAI( api_key=os.environ.get("OPENAI_API_KEY", "") ) self._available = True except ImportError: print("WARNING: openai package not installed. Falling back to pressure policy.") self._available = False
def act(self, obs: Dict) -> int: if not self._available or not os.environ.get("OPENAI_API_KEY"): return self._fallback.act(obs)
try: ql = obs.get("queue_lengths", []) phase_oh = obs.get("phase_onehot", [1,0,0,0]) phase_names = ["NS_GREEN","EW_GREEN","ALL_RED","NS_MINOR"] phase = phase_names[phase_oh.index(max(phase_oh))] queue_map = {LANE_NAMES[i]: round(ql[i], 2) for i in range(min(len(ql),12))}
msg = ( f"Phase: {phase} | " f"Elapsed(norm): {obs.get('phase_elapsed_norm',0):.2f} | " f"Queues: {json.dumps(queue_map)} | " f"Pressure NS-EW: {obs.get('pressure_differential',0):.3f} | " f"Fairness: {obs.get('fairness_score',0):.3f}" )
t0 = time.time() resp = self._client.chat.completions.create( model=self.model, messages=[ {"role": "system", "content": self.SYSTEM}, {"role": "user", "content": msg}, ], max_tokens=50, temperature=0.0, ) self.latencies.append(time.time() - t0) self.calls += 1
content = resp.choices[0].message.content.strip() parsed = json.loads(content) action = int(parsed.get("action", 0)) return max(0, min(4, action)) except Exception as e: return self._fallback.act(obs)
# ---------------------------------------------------------------------------# Episode runner (direct API calls)# ---------------------------------------------------------------------------
class IntelliFlowClient: def __init__(self, host: str): self.host = host.rstrip("/") self.session = requests.Session()
def health(self) -> Dict: return self.session.get(f"{self.host}/health", timeout=10).json()
def reset(self, task_id: str, seed: Optional[int] = None) -> Dict: body = {"task_id": task_id} if seed is not None: body["seed"] = seed r = self.session.post(f"{self.host}/reset", json=body, timeout=10) r.raise_for_status() return r.json()
def step(self, session_id: str, action: int) -> Dict: r = self.session.post( f"{self.host}/step", json={"session_id": session_id, "action": action}, timeout=10, ) r.raise_for_status() return r.json()
def grade(self, session_id: str) -> Dict: r = self.session.post( f"{self.host}/grader", json={"session_id": session_id}, timeout=10, ) r.raise_for_status() return r.json()
def get_tasks(self) -> Dict: return self.session.get(f"{self.host}/tasks", timeout=10).json()
def run_episode( client: IntelliFlowClient, task_id: str, policy_name: str, seed: int, verbose: bool = True,) -> Dict[str, Any]: """Run one complete episode, return scored result."""
# Reset reset_data = client.reset(task_id, seed=seed) session_id = reset_data["session_id"] horizon = reset_data.get("horizon", 600)
# Build policy if policy_name == "pressure": policy = PressurePolicy() elif policy_name == "fixed_cycle": policy = FixedCyclePolicy() elif policy_name == "random": policy = RandomPolicy(seed=seed) elif policy_name == "llm": policy = LLMPolicy() else: raise ValueError(f"Unknown policy: {policy_name}")
total_reward = 0.0 step_count = 0 done = False obs = reset_data.get("observation", {}) rewards = []
t_start = time.time()
while not done: action = policy.act(obs) step_data = client.step(session_id, action)
obs = step_data.get("observation", {}) reward = step_data.get("reward", 0.0) done = step_data.get("done", False) info = step_data.get("info", {})
total_reward += reward rewards.append(reward) step_count += 1
if verbose and step_count % 100 == 0: print(f" Step {step_count:4d}/{horizon} | " f"Reward: {reward:+7.3f} | " f"Cleared: {info.get('total_cleared',0):5d} | " f"Phase: {info.get('phase','?'):<10s} | " f"Delay: {info.get('avg_delay',0):.1f}s")
elapsed = time.time() - t_start
# Grade grade_data = client.grade(session_id)
result = { "task_id": task_id, "policy": policy_name, "seed": seed, "steps": step_count, "total_reward": round(total_reward, 4), "reward_mean": round(sum(rewards)/max(len(rewards),1), 4), "reward_std": round( (sum((r - sum(rewards)/len(rewards))**2 for r in rewards)/max(len(rewards),1))**0.5, 4 ) if rewards else 0, "score": grade_data.get("score", 0.0), "sub_scores": grade_data.get("sub_scores", {}), "trajectory_summary": grade_data.get("trajectory_summary", {}), "wall_time_seconds": round(elapsed, 2), }
if policy_name == "llm" and hasattr(policy, "calls"): result["llm_calls"] = policy.calls result["llm_avg_latency_ms"] = round( sum(policy.latencies)/max(len(policy.latencies),1)*1000, 1 )
return result
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------
def main(): parser = argparse.ArgumentParser( description="IntelliFlow baseline inference script" ) parser.add_argument( "--task", default="all", help="Task ID or 'all' (default: all)" ) parser.add_argument( "--policy", default="pressure", choices=["pressure", "fixed_cycle", "random", "llm"], help="Policy to evaluate (default: pressure)" ) parser.add_argument("--seed", type=int, default=42, help="Random seed") parser.add_argument( "--host", default=DEFAULT_HOST, help=f"API host (default: {DEFAULT_HOST})" ) parser.add_argument("--verbose", action="store_true", default=True) parser.add_argument("--output", default=None, help="JSON output file path") args = parser.parse_args()
client = IntelliFlowClient(args.host)
# Health check print(f"\n{'='*60}") print(" IntelliFlow Baseline Inference") print(f"{'='*60}") print(f" Host : {args.host}") print(f" Policy : {args.policy}") print(f" Seed : {args.seed}") print()
try: health = client.health() print(f" β Service online | Uptime: {health.get('uptime_seconds',0)}s") print(f" β Tasks: {', '.join(health.get('tasks_available', []))}") except Exception as e: print(f" β Health check failed: {e}") print(" Make sure the server is running: python -m uvicorn app.api.main:app --port 7860") sys.exit(1)
tasks = TASKS if args.task == "all" else [args.task] all_results = []
for task_id in tasks: print(f"\n{'β'*60}") print(f" Task: {task_id}") print(f"{'β'*60}")
try: result = run_episode( client, task_id, args.policy, args.seed, args.verbose ) all_results.append(result)
score = result["score"] bar = "β" * int(score * 30) + "β" * (30 - int(score * 30)) print(f"\n ββ RESULT βββββββββββββββββββββββββββββ") print(f" β Score : {score:.4f} [{bar}]") print(f" β Steps : {result['steps']}") print(f" β Total reward: {result['total_reward']}") print(f" β Reward mean : {result['reward_mean']}") for k, v in result.get("sub_scores", {}).items(): print(f" β β {k:<30s}: {v:.4f}") traj = result.get("trajectory_summary", {}) print(f" β Cleared : {traj.get('total_cleared', '?')}") print(f" β Avg delay : {traj.get('avg_delay_seconds', '?')}s") print(f" β Wall time : {result['wall_time_seconds']}s") if "llm_calls" in result: print(f" β LLM calls : {result['llm_calls']}") print(f" β LLM latency : {result['llm_avg_latency_ms']}ms avg") print(f" βββββββββββββββββββββββββββββββββββββββ")
except Exception as e: print(f" β Error: {e}") import traceback; traceback.print_exc()
# Summary table if len(all_results) > 1: print(f"\n{'='*60}") print(" SUMMARY") print(f"{'='*60}") print(f" {'Task':<35s} {'Score':>8s}") print(f" {'β'*35} {'β'*8}") for r in all_results: print(f" {r['task_id']:<35s} {r['score']:>8.4f}") scores = [r["score"] for r in all_results] print(f" {'β'*35} {'β'*8}") print(f" {'Average':<35s} {sum(scores)/len(scores):>8.4f}") print()
# Output JSON output_path = args.output if output_path: with open(output_path, "w") as f: json.dump({"results": all_results, "policy": args.policy, "seed": args.seed}, f, indent=2) print(f" Results written to: {output_path}") else: print("\n Full JSON results:") print(json.dumps({"results": all_results}, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837"""IntelliFlow Urban Traffic Control EnvironmentCore simulation engine implementing OpenEnv specification."""
from __future__ import annotations
import mathimport randomfrom dataclasses import dataclass, field, asdictfrom enum import IntEnumfrom typing import Any, Dict, List, Optional, Tupleimport numpy as np
# ---------------------------------------------------------------------------# Action space# ---------------------------------------------------------------------------
class Action(IntEnum): MAINTAIN = 0 # Keep current phase, no change SWITCH_PHASE = 1 # Toggle to orthogonal phase group EXTEND_GREEN = 2 # Add fixed time increment to current green FORCE_ALL_RED = 3 # Safety all-red interval (clears junction) YIELD_MINOR = 4 # Give short green to minor side-roads
ACTION_DESCRIPTIONS = { Action.MAINTAIN: "Maintain current signal phase", Action.SWITCH_PHASE: "Switch to orthogonal phase (N-S β E-W)", Action.EXTEND_GREEN: "Extend current green by +5 seconds", Action.FORCE_ALL_RED:"Force all-red safety interval", Action.YIELD_MINOR: "Yield short green to minor approaches",}
N_ACTIONS = len(Action)
# ---------------------------------------------------------------------------# Phase definitions# ---------------------------------------------------------------------------
class Phase(IntEnum): NS_GREEN = 0 # North-South green, East-West red EW_GREEN = 1 # East-West green, North-South red ALL_RED = 2 # All approaches red (safety / transition) NS_MINOR = 3 # Minor-road yielding for North-South
PHASE_PERMISSIONS = { # phase -> set of lane indices that may discharge # lanes: 0=N_through, 1=N_right, 2=S_through, 3=S_right, # 4=E_through, 5=E_right, 6=W_through, 7=W_right, # 8=N_left, 9=S_left, 10=E_left, 11=W_left Phase.NS_GREEN: {0, 1, 2, 3, 8, 9}, Phase.EW_GREEN: {4, 5, 6, 7, 10, 11}, Phase.ALL_RED: set(), Phase.NS_MINOR: {1, 3}, # right-turns only on minor approach}
LANE_NAMES = [ "N_through", "N_right", "S_through", "S_right", "E_through", "E_right", "W_through", "W_right", "N_left", "S_left", "E_left", "W_left",]N_LANES = len(LANE_NAMES)
# ---------------------------------------------------------------------------# Observation schema# ---------------------------------------------------------------------------
@dataclassclass Observation: # Queue lengths per lane (vehicles), normalised [0,1] by capacity queue_lengths: List[float] # shape (N_LANES,) # Recent throughput (vehicles cleared in last 10 steps), normalised throughput_recent: List[float] # shape (N_LANES,) # Estimated arrival intensity per lane (Ξ» estimate), normalised arrival_intensity: List[float] # shape (N_LANES,) # Current active phase one-hot phase_onehot: List[float] # shape (4,) # Elapsed seconds in current phase, normalised by max_phase_duration phase_elapsed_norm: float # Fairness metric: normalised variance of per-lane wait times fairness_score: float # Congestion spillback flags per lane (0/1) spillback_flags: List[float] # shape (N_LANES,) # Rolling average delay (s/vehicle) normalised avg_delay_norm: float # Step count in episode normalised by horizon step_norm: float # Pressure differential NS vs EW (for heuristic agents) pressure_differential: float
def to_vector(self) -> np.ndarray: v = ( self.queue_lengths + self.throughput_recent + self.arrival_intensity + self.phase_onehot + [self.phase_elapsed_norm, self.fairness_score, self.pressure_differential, self.avg_delay_norm, self.step_norm] + self.spillback_flags ) return np.array(v, dtype=np.float32)
def to_dict(self) -> Dict[str, Any]: return asdict(self)
OBS_DIM = N_LANES * 3 + 4 + 5 + N_LANES # = 12*3 + 4 + 5 + 12 = 57
# ---------------------------------------------------------------------------# Traffic lane model# ---------------------------------------------------------------------------
@dataclassclass Lane: name: str capacity: int # max vehicles that can queue sat_flow: float # saturation discharge flow (veh/step at green) arrival_lambda: float # Poisson arrival rate (veh/step) queue: float = 0.0 wait_accum: float = 0.0 # cumulative wait (vehicle-steps) total_arrived: int = 0 total_cleared: int = 0 recent_arrivals: List[int] = field(default_factory=lambda: [0]*10) recent_cleared: List[int] = field(default_factory=lambda: [0]*10)
def arrive(self, rng: random.Random) -> int: """Simulate arrivals this step (Poisson).""" n = rng.random() # Poisson via inversion (works well for small Ξ») arrivals = 0 p = math.exp(-self.arrival_lambda) cumul = p while n > cumul: arrivals += 1 p *= self.arrival_lambda / arrivals cumul += p if arrivals > 50: break actual = min(arrivals, self.capacity - int(self.queue)) actual = max(0, actual) self.queue += actual self.total_arrived += actual self.recent_arrivals.pop(0) self.recent_arrivals.append(actual) return actual
def discharge(self, green: bool, weather_factor: float = 1.0, rng: random.Random = None) -> int:
"""Discharge vehicles this step if green.""" if not green or self.queue <= 0: self.recent_cleared.pop(0) self.recent_cleared.append(0) return 0 max_discharge = self.sat_flow * weather_factor cleared_float = min(self.queue, max_discharge) cleared_float = max(0.0, cleared_float) floor_n = int(cleared_float) frac = cleared_float - floor_n bonus = 1 if (rng.random() if rng else random.random()) < frac else 0 n = min(floor_n + bonus, int(self.queue) + 1) n = max(0, n) self.queue = max(0.0, self.queue - cleared_float) self.total_cleared += n self.recent_cleared.pop(0) self.recent_cleared.append(n) return n
def accumulate_wait(self) -> None: self.wait_accum += self.queue
@property def estimated_lambda(self) -> float: return sum(self.recent_arrivals) / max(len(self.recent_arrivals), 1)
@property def recent_throughput(self) -> float: return sum(self.recent_cleared) / max(self.capacity, 1)
@property def spillback_risk(self) -> bool: return self.queue / max(self.capacity, 1) >= 0.85
# ---------------------------------------------------------------------------# Main environment# ---------------------------------------------------------------------------
class TrafficEnvironment: """ OpenEnv-compliant Urban Traffic Signal Control Environment.
Observation dim : 57 floats Action space : Discrete(5) Reward : Dense, multi-objective """
def __init__(self, config: Dict[str, Any]): self.config = config self.horizon: int = config.get("horizon", 1800) self.min_phase_duration: int = config.get("min_phase_duration", 5) self.max_phase_duration: int = config.get("max_phase_duration", 90) self.all_red_duration: int = config.get("all_red_duration", 3) self.extend_increment: int = config.get("extend_increment", 5) self.lane_capacity: int = config.get("lane_capacity", 20) self.seed: Optional[int] = config.get("seed", None) self.weather: str = config.get("weather", "clear") self.incident_lane: int = config.get("incident_lane", -1)
# reward weights self.w_throughput = config.get("w_throughput", 1.0) self.w_wait = config.get("w_wait", -0.05) self.w_fairness = config.get("w_fairness", -0.3) self.w_switch = config.get("w_switch", -0.2) self.w_spillback = config.get("w_spillback", -0.5) self.w_emission = config.get("w_emission", -0.01)
self._rng = random.Random(self.seed) self._np_rng = np.random.default_rng(self.seed) self.lanes: List[Lane] = [] self._reset_state()
# ------------------------------------------------------------------ # OpenEnv interface # ------------------------------------------------------------------
def reset(self, seed: Optional[int] = None) -> Observation: if seed is not None: self.seed = seed self._rng = random.Random(seed) self._np_rng = np.random.default_rng(seed) self._reset_state() return self._build_observation()
def step(self, action: int) -> Tuple[Observation, float, bool, Dict[str, Any]]: assert 0 <= action < N_ACTIONS, f"Invalid action {action}" self._step_count += 1
prev_phase = self._current_phase reward = 0.0 info: Dict[str, Any] = {}
# --- Apply action --- switched = self._apply_action(Action(action))
# --- Arrivals --- weather_factor = self._weather_factor() for lane in self.lanes: lane.arrive(self._rng)
# --- Discharge --- permissions = PHASE_PERMISSIONS[self._current_phase] total_cleared = 0 amber_dur = self.config.get("amber_duration", 2) for i, lane in enumerate(self.lanes): green = (i in permissions) and (self._phase_elapsed >= amber_dur) if i == self.incident_lane: green = False n = lane.discharge(green, weather_factor, self._rng) total_cleared += n
# --- Wait accumulation --- for lane in self.lanes: lane.accumulate_wait()
# --- Phase timer --- self._phase_elapsed += 1 if self._current_phase == Phase.ALL_RED and self._phase_elapsed >= self.all_red_duration: self._transition_to(self._next_major_phase())
# --- Reward computation --- reward = self._compute_reward(total_cleared, switched, prev_phase)
# --- Core metrics update --- self._total_cleared += total_cleared self._switch_count += int(switched) total_arrived_step = sum(l.total_arrived for l in self.lanes) step_arrived = total_arrived_step - self._total_arrived_all self._total_arrived_all = total_arrived_step
total_wait = sum(l.wait_accum for l in self.lanes) if self._total_cleared > 0: self._avg_delay = total_wait / max(self._total_cleared, 1)
# --- Rich analytics tracking --- ns_queue = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_queue = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) total_queue_now = ns_queue + ew_queue spillback_now = sum(1 for l in self.lanes if l.spillback_risk)
self._reward_history.append(reward) self._throughput_history.append(total_cleared) self._arrival_history.append(step_arrived) self._queue_ns_history.append(ns_queue) self._queue_ew_history.append(ew_queue) self._delay_history.append(self._avg_delay) self._spillback_history.append(spillback_now)
# Emission proxy: 0.5 g CO2/s per idling vehicle (COPERT idle model) self._total_emission_g += total_queue_now * 0.5
# Peak tracking if total_queue_now > self._peak_queue: self._peak_queue = total_queue_now if self._avg_delay > self._peak_delay: self._peak_delay = self._avg_delay if spillback_now > self._peak_spillback: self._peak_spillback = spillback_now
# Phase transition log if switched: duration = self._step_count - self._phase_start_step self._phase_durations[prev_phase.name].append(duration) self._phase_log.append({ "step": self._step_count, "from": prev_phase.name, "to": self._current_phase.name, "duration_held": duration, }) self._phase_start_step = self._step_count
# Trim history to rolling window for buf in [self._reward_history, self._throughput_history, self._arrival_history, self._queue_ns_history, self._queue_ew_history, self._delay_history, self._spillback_history]: if len(buf) > self._window * 5: buf.pop(0)
# --- Termination --- done = self._check_termination()
# --- Level of Service (HCM 2010 standard, Table 18-3) --- los = self._level_of_service(self._avg_delay)
# --- Efficiency ratio --- efficiency = (self._total_cleared / max(self._total_arrived_all, 1))
info = { "step": self._step_count, "phase": self._current_phase.name, "phase_elapsed": self._phase_elapsed, "total_cleared": self._total_cleared, "total_arrived": self._total_arrived_all, "avg_delay": round(self._avg_delay, 3), "switch_count": self._switch_count, "spillback_count": spillback_now, "gridlock": self._is_gridlock(), "step_cleared": total_cleared, "step_arrived": step_arrived, "step_reward": round(reward, 6), "ns_queue": round(ns_queue, 2), "ew_queue": round(ew_queue, 2), "total_queue": round(total_queue_now, 2), "efficiency_ratio":round(efficiency, 4), "los": los, "los_numeric": "ABCDEF".index(los), "emission_kg_co2": round(self._total_emission_g / 1000, 4), "peak_queue": round(self._peak_queue, 2), "peak_delay": round(self._peak_delay, 3), "peak_spillback": self._peak_spillback, "fairness_score": round(self._fairness_score(), 4), "rolling_throughput_rate": round( sum(self._throughput_history[-self._window:]) / max(self._window, 1), 4), "rolling_arrival_rate": round( sum(self._arrival_history[-self._window:]) / max(self._window, 1), 4), }
obs = self._build_observation() return obs, round(reward, 6), done, info
def state(self) -> Dict[str, Any]: obs = self._build_observation() ns_queue = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_queue = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) dominant_direction = "NS" if ns_queue > ew_queue else "EW" efficiency = self._total_cleared / max(self._total_arrived_all, 1) los = self._level_of_service(self._avg_delay) return { "observation": obs.to_dict(), "observation_vector": obs.to_vector().tolist(), "vector_dim": OBS_DIM, "step": self._step_count, "dominant_flow": dominant_direction, "horizon": self.horizon, "progress_pct": round(self._step_count / max(self.horizon, 1) * 100, 1), "phase": self._current_phase.name, "phase_elapsed": self._phase_elapsed, "lanes": [ { "name": l.name, "queue": round(l.queue, 2), "capacity": l.capacity, # FIX: queue_pct is the true queue occupancy (0-100%) "queue_pct": round(l.queue / max(l.capacity, 1) * 100, 1), # occupancy_pct: same as queue_pct β no artificial cap "occupancy_pct": round(l.queue / max(l.capacity, 1) * 100, 1), "wait_accum": round(l.wait_accum, 1), "total_cleared": l.total_cleared, "total_arrived": l.total_arrived, "efficiency": round(l.total_cleared / max(l.total_arrived, 1), 3), "lambda_est": round(l.estimated_lambda, 3), "spillback": l.spillback_risk, "recent_throughput_rate": round(l.recent_throughput, 3), } for l in self.lanes ], "direction_summary": { "NS": { "queue": round(sum(self.lanes[i].queue for i in [0,1,2,3,8,9]), 2), "cleared": sum(self.lanes[i].total_cleared for i in [0,1,2,3,8,9]), "arrived": sum(self.lanes[i].total_arrived for i in [0,1,2,3,8,9]), }, "EW": { "queue": round(sum(self.lanes[i].queue for i in [4,5,6,7,10,11]), 2), "cleared": sum(self.lanes[i].total_cleared for i in [4,5,6,7,10,11]), "arrived": sum(self.lanes[i].total_arrived for i in [4,5,6,7,10,11]), }, }, "metrics": { "throughput_rate": round(self._total_cleared / max(self._step_count, 1), 4), "avg_delay": round(self._avg_delay, 3), "peak_delay": round(self._peak_delay, 3), "switch_count": self._switch_count, "fairness_score": round(self._fairness_score(), 4), "efficiency_ratio": round(efficiency, 4), "los": los, "spillback_count": sum(1 for l in self.lanes if l.spillback_risk), "peak_spillback": self._peak_spillback, "emission_kg_co2": round(self._total_emission_g / 1000, 4), "total_cleared": self._total_cleared, "total_arrived": self._total_arrived_all, } }
def analytics(self) -> Dict[str, Any]: """Rich episode analytics for dashboard, judges, and post-hoc analysis.""" w = self._window steps = max(self._step_count, 1)
recent_tp = self._throughput_history[-w:] recent_arr = self._arrival_history[-w:] recent_delay = self._delay_history[-w:] recent_ns = self._queue_ns_history[-w:] recent_ew = self._queue_ew_history[-w:]
def downsample(lst, n=5): return [round(lst[i], 4) for i in range(0, len(lst), n)]
ns_green_steps = sum(self._phase_durations.get("NS_GREEN", [])) ew_green_steps = sum(self._phase_durations.get("EW_GREEN", [])) total_green = max(ns_green_steps + ew_green_steps, 1) green_split = { "NS_pct": round(ns_green_steps / total_green * 100, 1), "EW_pct": round(ew_green_steps / total_green * 100, 1), }
avg_phase_dur = {} for phase_name, durations in self._phase_durations.items(): if durations: avg_phase_dur[phase_name] = round(sum(durations) / len(durations), 1) else: avg_phase_dur[phase_name] = 0
efficiency_series = [] for i in range(len(self._throughput_history)): cl = sum(self._throughput_history[max(0,i-w):i+1]) ar = sum(self._arrival_history[max(0,i-w):i+1]) efficiency_series.append(round(cl / max(ar, 1), 4))
los_counts: Dict[str, int] = {g: 0 for g in "ABCDEF"} for d in self._delay_history: los_counts[self._level_of_service(d)] += 1
emission_kg = self._total_emission_g / 1000 emission_rate_kg_hr = emission_kg / max(steps / 3600, 1/3600)
sat = self.config.get("sat_flows", [0.9])[0] weather_factor = self._weather_factor() theoretical_max_per_step = N_LANES * sat * weather_factor theoretical_total = theoretical_max_per_step * steps actual_efficiency_vs_theory = round( self._total_cleared / max(theoretical_total, 1), 4 )
return { "episode_summary": { "steps_run": self._step_count, "horizon": self.horizon, "completion_pct": round(self._step_count / self.horizon * 100, 1), "total_cleared": self._total_cleared, "total_arrived": self._total_arrived_all, "efficiency_ratio": round(self._total_cleared / max(self._total_arrived_all, 1), 4), "avg_delay_s": round(self._avg_delay, 3), "peak_delay_s": round(self._peak_delay, 3), "los": self._level_of_service(self._avg_delay), "phase_switches": self._switch_count, "peak_spillback_lanes":self._peak_spillback, "emission_kg_co2": round(emission_kg, 4), "emission_rate_kg_hr": round(emission_rate_kg_hr, 4), "vs_theoretical_max": actual_efficiency_vs_theory, }, "phase_analysis": { "green_split": green_split, "avg_phase_duration": avg_phase_dur, "total_switches": self._switch_count, "switch_rate_per_100": round(self._switch_count / max(steps, 1) * 100, 2), "recent_transitions": self._phase_log[-10:], }, "los_breakdown": { "counts": los_counts, "pct": { g: round(c / max(steps, 1) * 100, 1) for g, c in los_counts.items() }, "description": { "A": "β€10s delay β free flow", "B": "β€20s delay β stable", "C": "β€35s delay β acceptable", "D": "β€55s delay β approaching unstable", "E": "β€80s delay β unstable", "F": ">80s delay β forced/breakdown", } }, "rolling_window": { "window_steps": w, "throughput": round(sum(recent_tp) / max(len(recent_tp), 1), 4), "arrival_rate":round(sum(recent_arr) / max(len(recent_arr), 1), 4), "avg_delay": round(sum(recent_delay) / max(len(recent_delay), 1), 3), "ns_queue": round(sum(recent_ns) / max(len(recent_ns), 1), 2), "ew_queue": round(sum(recent_ew) / max(len(recent_ew), 1), 2), }, "time_series": { "description": "Downsampled every 5 steps for bandwidth efficiency", "sample_interval": 5, "reward": downsample(self._reward_history), "throughput": downsample(self._throughput_history), "arrivals": downsample(self._arrival_history), "ns_queue": downsample(self._queue_ns_history), "ew_queue": downsample(self._queue_ew_history), "delay": downsample(self._delay_history), "spillback": downsample(self._spillback_history), "efficiency": downsample(efficiency_series), }, "direction_summary": { "NS": { "queue_now": round(sum(self.lanes[i].queue for i in [0,1,2,3,8,9]), 2), "cleared": sum(self.lanes[i].total_cleared for i in [0,1,2,3,8,9]), "arrived": sum(self.lanes[i].total_arrived for i in [0,1,2,3,8,9]), "green_pct": green_split["NS_pct"], }, "EW": { "queue_now": round(sum(self.lanes[i].queue for i in [4,5,6,7,10,11]), 2), "cleared": sum(self.lanes[i].total_cleared for i in [4,5,6,7,10,11]), "arrived": sum(self.lanes[i].total_arrived for i in [4,5,6,7,10,11]), "green_pct": green_split["EW_pct"], }, }, "lane_details": [ { "name": l.name, "occupancy_pct": round(l.queue / max(l.capacity, 1) * 100, 1), "total_cleared": l.total_cleared, "total_arrived": l.total_arrived, "efficiency": round(l.total_cleared / max(l.total_arrived, 1), 3), "wait_per_veh": round(l.wait_accum / max(l.total_cleared, 1), 2), "spillback": l.spillback_risk, "avg_lambda": round(l.estimated_lambda, 4), } for l in self.lanes ], }
# ------------------------------------------------------------------ # Internal helpers # ------------------------------------------------------------------
def _reset_state(self): base_lambdas = self.config.get("arrival_lambdas", [ 0.65, 0.25, 0.60, 0.25, 0.25, 0.10, 0.25, 0.10, 0.30, 0.30, 0.12, 0.12 ]) sat_flows = self.config.get("sat_flows", [0.9] * N_LANES) perturb = self.config.get("stochastic_lambdas", False)
self.lanes = [] for i, name in enumerate(LANE_NAMES): lam = base_lambdas[i % len(base_lambdas)] if perturb: lam = lam * (0.7 + self._rng.random() * 0.6) sf = sat_flows[i % len(sat_flows)] cap = self.lane_capacity self.lanes.append(Lane( name=name, capacity=cap, sat_flow=sf, arrival_lambda=lam, ))
self._current_phase = Phase.NS_GREEN self._phase_elapsed = 0 self._phase_green_start = self.config.get("amber_duration", 2) self._step_count = 0 self._total_cleared = 0 self._switch_count = 0 self._avg_delay = 0.0 self._episode_reward = 0.0 self._prev_action = -1 self._forced_switch = False self._gridlock_steps = 0 self._prev_total_queue = 0.0 self._last_pressure_diff = 0.0
self._window = 60 self._reward_history: List[float] = [] self._throughput_history: List[int] = [] self._arrival_history: List[int] = [] self._queue_ns_history: List[float] = [] self._queue_ew_history: List[float] = [] self._delay_history: List[float] = [] self._phase_log: List[Dict] = [] self._spillback_history: List[int] = []
self._total_emission_g = 0.0 self._peak_queue = 0.0 self._peak_delay = 0.0 self._peak_spillback = 0 self._total_arrived_all = 0
self._phase_start_step = 0 self._phase_durations: Dict[str, List[int]] = { p.name: [] for p in Phase }
def _apply_action(self, action: Action) -> bool: switched = False elapsed = self._phase_elapsed
if action == Action.MAINTAIN: pass
elif action == Action.SWITCH_PHASE: if elapsed >= self.min_phase_duration: self._transition_to(Phase.ALL_RED) self._forced_switch = True switched = True
elif action == Action.EXTEND_GREEN: if self._current_phase not in (Phase.ALL_RED,): self._phase_elapsed = max( self._phase_green_start, self._phase_elapsed - self.extend_increment )
elif action == Action.FORCE_ALL_RED: if self._current_phase != Phase.ALL_RED: self._transition_to(Phase.ALL_RED) self._forced_switch = False switched = True
elif action == Action.YIELD_MINOR: if self._current_phase != Phase.NS_MINOR and elapsed >= self.min_phase_duration: self._transition_to(Phase.NS_MINOR) switched = True
if (self._current_phase not in (Phase.ALL_RED,) and self._phase_elapsed >= self.max_phase_duration): self._transition_to(Phase.ALL_RED) self._forced_switch = True switched = True
self._prev_action = int(action) return switched
def _level_of_service(self, avg_delay_s: float) -> str: if avg_delay_s <= 10: return "A" if avg_delay_s <= 20: return "B" if avg_delay_s <= 35: return "C" if avg_delay_s <= 55: return "D" if avg_delay_s <= 80: return "E" return "F"
def _transition_to(self, phase: Phase): self._current_phase = phase self._phase_elapsed = 0 self._forced_switch = False
def _next_major_phase(self) -> Phase: if self._current_phase == Phase.ALL_RED: ns_pressure = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_pressure = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) return Phase.NS_GREEN if ns_pressure >= ew_pressure else Phase.EW_GREEN return Phase.ALL_RED
def _compute_reward(self, cleared: int, switched: bool, prev_phase: Phase) -> float: r = 0.0 n_lanes = len(self.lanes) cap = max(self.lane_capacity, 1)
permissions = PHASE_PERMISSIONS[self._current_phase] max_possible = len(permissions) * max( self.config.get("sat_flows", [0.9])[0], 0.1 ) throughput_norm = cleared / max(max_possible, 1) r += self.w_throughput * throughput_norm
total_queue_now = sum(l.queue for l in self.lanes) prev_queue = getattr(self, "_prev_total_queue", total_queue_now) queue_delta = prev_queue - total_queue_now queue_delta_norm = queue_delta / max(n_lanes * cap, 1) queue_delta_norm = max(-1.0, min(1.0, queue_delta_norm)) r += self.w_wait * queue_delta_norm self._prev_total_queue = total_queue_now
occupancy_rate = total_queue_now / max(n_lanes * cap, 1) congestion_penalty = -0.3 * (occupancy_rate ** 2) r += congestion_penalty
main_lanes = [0, 2, 4, 6] main_queues = [self.lanes[i].queue / cap for i in main_lanes] mean_q = sum(main_queues) / max(len(main_queues), 1) max_deviation = max(abs(q - mean_q) for q in main_queues) starvation = max_deviation if max(main_queues) > 0.4 else 0.0 r += self.w_fairness * starvation
if switched: phase_was_all_red = (prev_phase == Phase.ALL_RED) pressure_diff = abs(getattr(self, "_last_pressure_diff", 0.0)) premature = (self._phase_elapsed < 15 and not phase_was_all_red) justified = (pressure_diff > 0.25)
if premature and not justified: r += self.w_switch elif premature: r += self.w_switch * 0.3
spillback_severity = 0.0 for lane in self.lanes: occ = lane.queue / cap if occ >= 0.85: spillback_severity += (occ - 0.85) / 0.15 spillback_severity /= max(n_lanes, 1) r += self.w_spillback * spillback_severity
if self._is_gridlock(): gridlock_frac = sum( 1 for l in self.lanes if l.queue / cap >= self.config.get("gridlock_threshold", 0.95) ) / n_lanes r += -8.0 * gridlock_frac
if switched and not (prev_phase == Phase.ALL_RED): ns_q = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_q = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) total_q = max(ns_q + ew_q, 1) self._last_pressure_diff = (ns_q - ew_q) / total_q pressure_diff = abs(self._last_pressure_diff) if pressure_diff > 0.3: r += 0.2 * pressure_diff else: ns_q = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_q = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) total_q = max(ns_q + ew_q, 1) self._last_pressure_diff = (ns_q - ew_q) / total_q
self._episode_reward += r return r
def _fairness_score(self) -> float: waits = [l.wait_accum / max(l.total_arrived, 1) for l in self.lanes] if len(waits) < 2: return 0.0 mean = sum(waits) / len(waits) var = sum((w - mean) ** 2 for w in waits) / len(waits) return min(var / (max(waits) ** 2 + 1e-9), 1.0)
def _is_gridlock(self) -> bool: gridlock_threshold = self.config.get("gridlock_threshold", 0.95) blocked = sum(1 for l in self.lanes if l.queue / max(l.capacity, 1) >= gridlock_threshold) return blocked >= N_LANES * 0.7
def _check_termination(self) -> bool: if self._step_count >= self.horizon: return True if self._is_gridlock(): if not hasattr(self, "_gridlock_steps"): self._gridlock_steps = 0 self._gridlock_steps += 1 if self._gridlock_steps >= 20: return True else: self._gridlock_steps = 0 return False
def _weather_factor(self) -> float: factors = {"clear": 1.0, "rain": 0.75, "fog": 0.6, "snow": 0.5} return factors.get(self.weather, 1.0)
def _build_observation(self) -> Observation: ql = [l.queue / max(l.capacity, 1) for l in self.lanes] tp = [l.recent_throughput for l in self.lanes] ai = [min(l.estimated_lambda / max(l.sat_flow, 0.1), 1.0) for l in self.lanes]
phase_oh = [0.0] * 4 phase_oh[int(self._current_phase)] = 1.0
elapsed_norm = self._phase_elapsed / max(self.max_phase_duration, 1) fs = self._fairness_score() spillback = [1.0 if l.spillback_risk else 0.0 for l in self.lanes] avg_delay_norm = min(self._avg_delay / 120.0, 1.0) step_norm = self._step_count / max(self.horizon, 1)
ns_pressure = sum(self.lanes[i].queue for i in [0,1,2,3,8,9]) ew_pressure = sum(self.lanes[i].queue for i in [4,5,6,7,10,11]) max_p = max(ns_pressure + ew_pressure, 1) pressure_diff = (ns_pressure - ew_pressure) / max_p
return Observation( queue_lengths=ql, throughput_recent=tp, arrival_intensity=ai, phase_onehot=phase_oh, phase_elapsed_norm=elapsed_norm, fairness_score=fs, spillback_flags=spillback, avg_delay_norm=avg_delay_norm, step_norm=step_norm, pressure_differential=pressure_diff, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Session management for stateful environment instances.Each /reset call creates a new session with a UUID."""
from __future__ import annotations
import timeimport uuidfrom typing import Any, Dict, List, Optional, Tuple
from app.core.environment import TrafficEnvironment, Observationfrom app.tasks.registry import ( TASK_REGISTRY, EpisodeGrader, build_env, get_task_spec_dict)
class Session: def __init__( self, session_id: str, task_id: str, env: TrafficEnvironment, seed: Optional[int], ): self.session_id = session_id self.task_id = task_id self.env = env self.seed = seed self.created_at = time.time() self.last_active = time.time() self.done = False self.step_count = 0
# For grading self._peak_spillback = 0.0 self._final_info: Dict[str, Any] = {}
def step(self, action: int) -> Tuple[Observation, float, bool, Dict]: if self.done: raise RuntimeError("Episode is already done. Call /reset to start a new one.") obs, reward, done, info = self.env.step(action) self.done = done self.step_count += 1 self.last_active = time.time()
# track peak spillback spillback_frac = info.get("spillback_count", 0) / 12.0 if spillback_frac > self._peak_spillback: self._peak_spillback = spillback_frac
if done: self._final_info = info
return obs, reward, done, info
def grade(self) -> Dict[str, Any]: """Compute episode score. Can be called at any time (mid or end).""" analytics = self.env.analytics() summary = analytics["episode_summary"]
trajectory = { "total_cleared": summary["total_cleared"], "total_arrived": summary["total_arrived"], "steps_survived": self.step_count, "avg_delay": summary["avg_delay_s"], "switch_count": summary["phase_switches"], "peak_spillback_fraction": summary["peak_spillback_lanes"] / 12.0, "fairness_score": 1.0 - self.env._fairness_score(), "gridlock_terminated": (self.env._is_gridlock() and self.done), }
spec = TASK_REGISTRY[self.task_id] grader = EpisodeGrader(spec) result = grader.grade(trajectory) result["session_id"] = self.session_id result["done"] = self.done result["analytics_snapshot"] = { "los": summary["los"], "efficiency_ratio": summary["efficiency_ratio"], "emission_kg_co2": summary["emission_kg_co2"], "green_split": analytics["phase_analysis"]["green_split"], "switch_rate_per_100": analytics["phase_analysis"]["switch_rate_per_100"], "steps_at_los": analytics["los_breakdown"]["pct"], } return result
class SessionStore: """In-memory session store with TTL cleanup."""
TTL_SECONDS = 3600 # sessions expire after 1 hour
def __init__(self): self._sessions: Dict[str, Session] = {}
def create(self, task_id: str, seed: Optional[int] = None) -> Session: if task_id not in TASK_REGISTRY: raise ValueError(f"Unknown task_id: {task_id!r}. " f"Available: {list(TASK_REGISTRY.keys())}") session_id = str(uuid.uuid4()) env = build_env(task_id, seed=seed) env.reset(seed=seed) session = Session(session_id, task_id, env, seed) self._sessions[session_id] = session self._cleanup() return session
def get(self, session_id: str) -> Session: session = self._sessions.get(session_id) if session is None: raise KeyError(f"Session {session_id!r} not found. " "It may have expired. Call /reset to create a new session.") session.last_active = time.time() return session
def _cleanup(self): now = time.time() expired = [sid for sid, s in self._sessions.items() if now - s.last_active > self.TTL_SECONDS] for sid in expired: del self._sessions[sid]
def list_sessions(self) -> List[Dict[str, Any]]: return [ { "session_id": s.session_id, "task_id": s.task_id, "step_count": s.step_count, "done": s.done, "age_seconds": round(time.time() - s.created_at), } for s in self._sessions.values() ]
# Singleton storestore = SessionStore()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369"""IntelliFlow Task RegistryThree progressively challenging benchmark tasks with programmatic graders."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any, Dict, List, Optionalimport math
from app.core.environment import ( TrafficEnvironment, N_LANES, N_ACTIONS, OBS_DIM, Action, LANE_NAMES)
# ---------------------------------------------------------------------------# Task metadata schema# ---------------------------------------------------------------------------
@dataclassclass TaskSpec: task_id: str name: str description: str difficulty: str # easy | medium | hard horizon: int n_actions: int obs_dim: int action_descriptions: Dict[int, str] env_config: Dict[str, Any] grader_description: str theoretical_max_throughput: float # vehicles/step upper bound acceptable_avg_delay: float # seconds, threshold for full score
# ---------------------------------------------------------------------------# Task 1: Suburban Steady Flow (EASY)# ---------------------------------------------------------------------------
TASK_SUBURBAN = TaskSpec( task_id="task_suburban_steady", name="Suburban Steady Flow", description=( "A single four-way intersection in a quiet suburb with low, " "symmetric vehicle arrivals. Inflow is nearly deterministic and " "balanced across all approaches. The optimal policy is to maintain " "fair green time allocation. Good baseline for verifying basic " "signal timing logic." ), difficulty="easy", horizon=600, n_actions=N_ACTIONS, obs_dim=OBS_DIM, action_descriptions={i: d for i, d in enumerate([ "Maintain current phase", "Switch to orthogonal phase", "Extend green by 5s", "Force all-red safety interval", "Yield to minor roads", ])}, env_config={ "horizon": 600, "arrival_lambdas": [0.20, 0.05, 0.20, 0.05, 0.20, 0.05, 0.20, 0.05, 0.05, 0.05, 0.05, 0.05], "sat_flows": [0.95] * N_LANES, "min_phase_duration": 5, "max_phase_duration": 60, "all_red_duration": 3, "lane_capacity": 30, "stochastic_lambdas": False, "weather": "clear", "gridlock_threshold": 0.95, "w_throughput": 1.2, # normalised: max ~+1.2 per step "w_wait": -0.8, # queue-delta penalty (normalised to [-1,1]) "w_fairness": -0.4, # max-deviation starvation "w_switch": -0.25, # oscillation penalty "w_spillback": -0.6, # escalating spillback severity "w_emission": 0.0, # merged into congestion_penalty (no longer separate) }, grader_description=( "Score = 0.4*(throughput_efficiency) + 0.3*(delay_score) " "+ 0.2*(fairness_score) + 0.1*(stability_score). " "throughput_efficiency = min(actual_throughput / theoretical_max, 1.0). " "delay_score = max(0, 1 - avg_delay / acceptable_delay). " "fairness_score = 1 - normalised_wait_variance. " "stability_score = 1 - min(switch_rate / max_switch_rate, 1)." ), theoretical_max_throughput=0.85, # vehicles per step (sum over all lanes) acceptable_avg_delay=25.0,)
# ---------------------------------------------------------------------------# Task 2: Urban Stochastic Rush (MEDIUM)# ---------------------------------------------------------------------------
TASK_URBAN = TaskSpec( task_id="task_urban_stochastic", name="Urban Stochastic Rush", description=( "A busy urban intersection with bursty, asymmetric inflows. " "Morning rush creates heavy North-South flow while East-West traffic " "varies stochastically. Lambda values are perturbed each episode. " "The agent must adapt timing dynamically and predict flow intensities " "to prevent queue starvation on any approach." ), difficulty="medium", horizon=1200, n_actions=N_ACTIONS, obs_dim=OBS_DIM, action_descriptions={i: d for i, d in enumerate([ "Maintain current phase", "Switch to orthogonal phase", "Extend green by 5s", "Force all-red safety interval", "Yield to minor roads", ])}, env_config={ "horizon": 1200, "arrival_lambdas": [0.45, 0.10, 0.45, 0.10, 0.25, 0.08, 0.25, 0.08, 0.12, 0.12, 0.08, 0.08], "sat_flows": [0.90] * N_LANES, "min_phase_duration": 5, "max_phase_duration": 90, "all_red_duration": 3, "lane_capacity": 40, "stochastic_lambdas": True, # perturb each episode "weather": "clear", "gridlock_threshold": 0.92, "w_throughput": 1.0, "w_wait": -0.9, # higher wait penalty β stochastic surges punish delay "w_fairness": -0.5, # starvation matters more with asymmetric load "w_switch": -0.25, "w_spillback": -0.7, "w_emission": 0.0, }, grader_description=( "Score = 0.35*(throughput_efficiency) + 0.30*(delay_score) " "+ 0.20*(fairness_score) + 0.15*(spillback_resilience). " "spillback_resilience = 1 - min(peak_spillback_fraction, 1.0). " "Higher weights on throughput efficiency vs task 1." ), theoretical_max_throughput=1.40, acceptable_avg_delay=40.0,)
# ---------------------------------------------------------------------------# Task 3: Rush Hour Crisis (HARD)# ---------------------------------------------------------------------------
TASK_CRISIS = TaskSpec( task_id="task_rush_hour_crisis", name="Rush Hour Crisis", description=( "Maximum load scenario simulating peak rush hour with heavy skew, " "high arrival rates near saturation, rain reducing discharge by 25%, " "and a blocked lane simulating an incident. The agent must survive " "congestion cascades, prevent gridlock, and maintain minimum viable " "throughput under extreme pressure. Episode terminates early on " "sustained gridlock. Scores are calibrated against theoretical maximums " "under these adverse conditions." ), difficulty="hard", horizon=1800, n_actions=N_ACTIONS, obs_dim=OBS_DIM, action_descriptions={i: d for i, d in enumerate([ "Maintain current phase", "Switch to orthogonal phase", "Extend green by 5s", "Force all-red safety interval", "Yield to minor roads", ])}, env_config={ "horizon": 1800, "arrival_lambdas": [0.70, 0.18, 0.70, 0.18, 0.55, 0.15, 0.55, 0.15, 0.20, 0.20, 0.15, 0.15], "sat_flows": [0.85] * N_LANES, # degraded by congestion "min_phase_duration": 5, "max_phase_duration": 90, "all_red_duration": 3, "lane_capacity": 40, "stochastic_lambdas": True, "weather": "rain", # 25% discharge reduction "incident_lane": 0, # N_through blocked "gridlock_threshold": 0.90, "w_throughput": 1.0, "w_wait": -1.0, # maximum pressure: near-saturated arrivals make delay very costly "w_fairness": -0.45, "w_switch": -0.20, # slightly lower: sometimes rapid adaptation is necessary "w_spillback": -0.85, # heaviest: spillback cascade = episode failure "w_emission": 0.0, }, grader_description=( "Score = 0.30*(throughput_efficiency) + 0.25*(delay_score) " "+ 0.20*(survival_bonus) + 0.15*(fairness_score) + 0.10*(stability_score). " "survival_bonus = steps_survived / horizon (rewards not gridlocking). " "Calibrated against rain+incident baselines." ), theoretical_max_throughput=1.80, # unadjusted; actual effective ~1.2 acceptable_avg_delay=70.0,)
TASK_REGISTRY: Dict[str, TaskSpec] = { t.task_id: t for t in [TASK_SUBURBAN, TASK_URBAN, TASK_CRISIS]}
# ---------------------------------------------------------------------------# Grader# ---------------------------------------------------------------------------
class EpisodeGrader: """ Computes a scalar score in [0, 1] for a completed episode. """
def __init__(self, task_spec: TaskSpec): self.spec = task_spec
def grade(self, trajectory_info: Dict[str, Any]) -> Dict[str, Any]: """ Args: trajectory_info: dict with keys: total_cleared, total_arrived, steps_survived, avg_delay, switch_count, peak_spillback_fraction, fairness_score, gridlock_terminated Returns: dict with 'score' (float in [0,1]) and sub-scores """ spec = self.spec ti = trajectory_info
total_cleared = float(ti.get("total_cleared", 0)) total_arrived = float(ti.get("total_arrived", 1)) steps_survived = float(ti.get("steps_survived", spec.horizon)) avg_delay = float(ti.get("avg_delay", 999)) switch_count = float(ti.get("switch_count", 0)) peak_spillback = float(ti.get("peak_spillback_fraction", 0)) fairness_raw = float(ti.get("fairness_score", 1.0)) gridlock_term = bool(ti.get("gridlock_terminated", False))
# --- Sub-scores ---
# Throughput efficiency theoretical_max = spec.theoretical_max_throughput * steps_survived throughput_eff = min(total_cleared / max(theoretical_max, 1), 1.0) throughput_eff = max(throughput_eff, 0.0)
# Delay score (lower delay = better) # Use acceptable_avg_delay as the 0.5-score point; 0 delay = 1.0 score delay_score = max(0.0, 1.0 - avg_delay / max(spec.acceptable_avg_delay * 3.0, 1)) delay_score = min(delay_score, 1.0)
# Fairness score (lower variance = better) # fairness_raw from grader input is already 1-fairness_metric (higher=better) fairness_score = max(0.0, min(float(ti.get("fairness_score", 0.0)), 1.0))
# Stability: penalise excessive phase switching max_switches = steps_survived / max(spec.env_config.get("min_phase_duration", 5), 1) stability_score = max(0.0, 1.0 - switch_count / max(max_switches, 1))
# Spillback resilience spillback_resilience = max(0.0, 1.0 - peak_spillback)
# Survival bonus survival_bonus = steps_survived / max(spec.horizon, 1) if gridlock_term: survival_bonus *= 0.5 # penalise gridlock termination
# --- Weighted composite --- task_id = spec.task_id
if task_id == "task_suburban_steady": score = ( 0.40 * throughput_eff + 0.30 * delay_score + 0.20 * fairness_score + 0.10 * stability_score ) elif task_id == "task_urban_stochastic": score = ( 0.35 * throughput_eff + 0.30 * delay_score + 0.20 * fairness_score + 0.15 * spillback_resilience ) else: # rush hour crisis score = ( 0.30 * throughput_eff + 0.25 * delay_score + 0.20 * survival_bonus + 0.15 * fairness_score + 0.10 * stability_score )
score = round(max(0.0, min(score, 1.0)), 6)
return { "task_id": task_id, "score": score, "sub_scores": { "throughput_efficiency": round(throughput_eff, 4), "delay_score": round(delay_score, 4), "fairness_score": round(fairness_score, 4), "stability_score": round(stability_score, 4), "spillback_resilience": round(spillback_resilience, 4), "survival_bonus": round(survival_bonus, 4), }, "trajectory_summary": { "total_cleared": int(total_cleared), "total_arrived": int(total_arrived), "steps_survived": int(steps_survived), "avg_delay_seconds": round(avg_delay, 2), "switch_count": int(switch_count), "gridlock_terminated": gridlock_term, } }
def build_env(task_id: str, seed: Optional[int] = None) -> TrafficEnvironment: spec = TASK_REGISTRY[task_id] config = dict(spec.env_config) if seed is not None: config["seed"] = seed return TrafficEnvironment(config)
def get_task_spec_dict(task_id: str) -> Dict[str, Any]: spec = TASK_REGISTRY[task_id] return { "task_id": spec.task_id, "name": spec.name, "description": spec.description, "difficulty": spec.difficulty, "horizon": spec.horizon, "n_actions": spec.n_actions, "obs_dim": spec.obs_dim, "action_space": { "type": "Discrete", "n": spec.n_actions, "actions": spec.action_descriptions, }, "observation_space": { "type": "Box", "dim": spec.obs_dim, "description": ( "57-dimensional float32 vector: " "[queue_lengths(12), throughput_recent(12), arrival_intensity(12), " "phase_onehot(4), phase_elapsed_norm(1), fairness_score(1), " "pressure_differential(1), avg_delay_norm(1), step_norm(1), " "spillback_flags(12)]" ), "bounds": "[0.0, 1.0] for most; pressure_differential in [-1, 1]", }, "reward": { "type": "dense", "range": "(-inf, +inf) per step, typically [-20, +15]", "description": spec.grader_description, }, "grader_description": spec.grader_description, "env_config": spec.env_config, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426#!/usr/bin/env python3"""IntelliFlow Baseline Inference Script=====================================Runs the OpenAI-powered LLM agent (and pressure/fixed-cycle baselines)across all three tasks and outputs reproducible baseline scores.
Usage: python baseline_inference.py [--task all|<task_id>] [--policy pressure|fixed_cycle|random|llm] [--seed 42] [--host http://localhost:7860]
Requirements: pip install openai requests
Environment variables: OPENAI_API_KEY β required for --policy llm INTELLIFLOW_HOST β optional override for API host"""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport timeimport randomimport mathfrom typing import Any, Dict, List, Optional
try: import requestsexcept ImportError: print("ERROR: 'requests' package not found. Install with: pip install requests") sys.exit(1)
# ---------------------------------------------------------------------------# Configuration# ---------------------------------------------------------------------------
DEFAULT_HOST = os.environ.get("INTELLIFLOW_HOST", "http://localhost:7860")API_BASE_URL = os.environ.get("API_BASE_URL")MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")HF_TOKEN = os.environ.get("HF_TOKEN")OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")TASKS = [ "task_suburban_steady", "task_urban_stochastic", "task_rush_hour_crisis",]
LANE_NAMES = [ "N_through", "N_right", "S_through", "S_right", "E_through", "E_right", "W_through", "W_right", "N_left", "S_left", "E_left", "W_left",]
# ---------------------------------------------------------------------------# Inline policies (no server dependency for action selection)# ---------------------------------------------------------------------------
class PressurePolicy: def __init__(self, switch_threshold: float = 3.0, min_steps: int = 5): self.threshold = switch_threshold self.min_steps = min_steps self._steps = 0
def act(self, obs: Dict) -> int: self._steps += 1 ql = obs.get("queue_lengths", [0.0]*12) phase_oh = obs.get("phase_onehot", [1,0,0,0]) idx = phase_oh.index(max(phase_oh)) elapsed_norm = obs.get("phase_elapsed_norm", 0) elapsed = elapsed_norm * 90
if elapsed < self.min_steps: return 0 # MAINTAIN
ns = sum(ql[i] for i in [0,1,2,3,8,9]) ew = sum(ql[i] for i in [4,5,6,7,10,11])
if idx == 2: # ALL_RED return 0 if idx == 0 and ew - ns > self.threshold * 0.1: self._steps = 0 return 1 if idx == 1 and ns - ew > self.threshold * 0.1: self._steps = 0 return 1 # Extend if high pressure on current if idx == 0 and ns > 0.75: return 2 if idx == 1 and ew > 0.75: return 2 return 0
class FixedCyclePolicy: def __init__(self, ns_green: int = 30, ew_green: int = 30, amber: int = 3): # β amber added self.ns_green = ns_green self.ew_green = ew_green self.amber = amber # β initialised self._step = 0
def act(self, obs: Dict) -> int: self._step += 1 cycle = self.ns_green + self.amber + self.ew_green + self.amber pos = self._step % cycle
if pos == self.ns_green: return 3 if pos == self.ns_green + self.amber: return 1 if pos == self.ns_green + self.amber + self.ew_green: return 3 if pos == 0: return 1 return 0
class RandomPolicy: def __init__(self, seed: int = 42): self._rng = random.Random(seed)
def act(self, obs: Dict) -> int: return self._rng.randint(0, 4)
class LLMPolicy: SYSTEM = ( "You are an expert traffic signal controller AI. " "Control a 4-way intersection to maximise throughput and minimise delay.\n" "Actions: 0=MAINTAIN, 1=SWITCH_PHASE, 2=EXTEND_GREEN, 3=FORCE_ALL_RED, 4=YIELD_MINOR\n" "Respond ONLY with JSON: {\"action\": <0-4>}" )
def __init__(self, model: str = None): # β CHANGED self.model = model or os.environ.get("MODEL_NAME", "gpt-4o-mini") # β CHANGED self._fallback = PressurePolicy() self.calls = 0 self.latencies: List[float] = []
try: import openai self._client = openai.OpenAI( api_key=OPENAI_API_KEY, # β SAME base_url=API_BASE_URL or None, # β ADDED ) self._available = True except ImportError: print("WARNING: openai package not installed. Falling back to pressure policy.") self._available = False
def act(self, obs: Dict) -> int: if not self._available or not OPENAI_API_KEY: return self._fallback.act(obs)
try: ql = obs.get("queue_lengths", []) phase_oh = obs.get("phase_onehot", [1,0,0,0]) phase_names = ["NS_GREEN","EW_GREEN","ALL_RED","NS_MINOR"] phase = phase_names[phase_oh.index(max(phase_oh))] queue_map = {LANE_NAMES[i]: round(ql[i], 2) for i in range(min(len(ql),12))}
msg = ( f"Phase: {phase} | " f"Elapsed(norm): {obs.get('phase_elapsed_norm',0):.2f} | " f"Queues: {json.dumps(queue_map)} | " f"Pressure NS-EW: {obs.get('pressure_differential',0):.3f} | " f"Fairness: {obs.get('fairness_score',0):.3f}" )
t0 = time.time() resp = self._client.chat.completions.create( model=self.model, messages=[ {"role": "system", "content": self.SYSTEM}, {"role": "user", "content": msg}, ], max_tokens=50, temperature=0.0, ) self.latencies.append(time.time() - t0) self.calls += 1
content = resp.choices[0].message.content.strip() parsed = json.loads(content) action = int(parsed.get("action", 0)) return max(0, min(4, action)) except Exception as e: return self._fallback.act(obs)
# ---------------------------------------------------------------------------# Episode runner (direct API calls)# ---------------------------------------------------------------------------
class IntelliFlowClient: def __init__(self, host: str): self.host = host.rstrip("/") self.session = requests.Session()
def health(self) -> Dict: return self.session.get(f"{self.host}/health", timeout=10).json()
def reset(self, task_id: str, seed: Optional[int] = None) -> Dict: body = {"task_id": task_id} if seed is not None: body["seed"] = seed r = self.session.post(f"{self.host}/reset", json=body, timeout=10) r.raise_for_status() return r.json()
def step(self, session_id: str, action: int) -> Dict: r = self.session.post( f"{self.host}/step", json={"session_id": session_id, "action": action}, timeout=10, ) r.raise_for_status() return r.json()
def grade(self, session_id: str) -> Dict: r = self.session.post( f"{self.host}/grader", json={"session_id": session_id}, timeout=10, ) r.raise_for_status() return r.json()
def get_tasks(self) -> Dict: return self.session.get(f"{self.host}/tasks", timeout=10).json()
def run_episode( client: IntelliFlowClient, task_id: str, policy_name: str, seed: int, verbose: bool = True,) -> Dict[str, Any]: """Run one complete episode, return scored result."""
# Reset reset_data = client.reset(task_id, seed=seed) session_id = reset_data["session_id"] horizon = reset_data.get("horizon", 600)
# Build policy if policy_name == "pressure": policy = PressurePolicy() elif policy_name == "fixed_cycle": policy = FixedCyclePolicy() elif policy_name == "random": policy = RandomPolicy(seed=seed) elif policy_name == "llm": policy = LLMPolicy() else: raise ValueError(f"Unknown policy: {policy_name}")
total_reward = 0.0 step_count = 0 done = False obs = reset_data.get("observation", {}) rewards = []
t_start = time.time()
while not done: action = policy.act(obs) step_data = client.step(session_id, action)
obs = step_data.get("observation", {}) reward = step_data.get("reward", 0.0) done = step_data.get("done", False) info = step_data.get("info", {})
total_reward += reward rewards.append(reward) step_count += 1
if verbose and step_count % 100 == 0: print(f" Step {step_count:4d}/{horizon} | " f"Reward: {reward:+7.3f} | " f"Cleared: {info.get('total_cleared',0):5d} | " f"Phase: {info.get('phase','?'):<10s} | " f"Delay: {info.get('avg_delay',0):.1f}s")
elapsed = time.time() - t_start
# Grade grade_data = client.grade(session_id)
result = { "task_id": task_id, "policy": policy_name, "seed": seed, "steps": step_count, "total_reward": round(total_reward, 4), "reward_mean": round(sum(rewards)/max(len(rewards),1), 4), "reward_std": round( (sum((r - sum(rewards)/len(rewards))**2 for r in rewards)/max(len(rewards),1))**0.5, 4 ) if rewards else 0, "score": grade_data.get("score", 0.0), "sub_scores": grade_data.get("sub_scores", {}), "trajectory_summary": grade_data.get("trajectory_summary", {}), "wall_time_seconds": round(elapsed, 2), }
if policy_name == "llm" and hasattr(policy, "calls"): result["llm_calls"] = policy.calls result["llm_avg_latency_ms"] = round( sum(policy.latencies)/max(len(policy.latencies),1)*1000, 1 )
return result
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------
def main(): parser = argparse.ArgumentParser( description="IntelliFlow baseline inference script" ) parser.add_argument( "--task", default="all", help="Task ID or 'all' (default: all)" ) parser.add_argument( "--policy", default="pressure", choices=["pressure", "fixed_cycle", "random", "llm"], help="Policy to evaluate (default: pressure)" ) parser.add_argument("--seed", type=int, default=42, help="Random seed") parser.add_argument( "--host", default=DEFAULT_HOST, help=f"API host (default: {DEFAULT_HOST})" ) parser.add_argument("--verbose", action="store_true", default=True) parser.add_argument("--output", default=None, help="JSON output file path") args = parser.parse_args()
client = IntelliFlowClient(args.host)
# Health check print(f"\n{'='*60}") print(" IntelliFlow Baseline Inference") print(f"{'='*60}") print(f" Host : {args.host}") print(f" Policy : {args.policy}") print(f" Seed : {args.seed}") print()
try: health = client.health() print(f" β Service online | Uptime: {health.get('uptime_seconds',0)}s") print(f" β Tasks: {', '.join(health.get('tasks_available', []))}") except Exception as e: print(f" β Health check failed: {e}") print(" Make sure the server is running: python -m uvicorn app.api.main:app --port 7860") sys.exit(1)
tasks = TASKS if args.task == "all" else [args.task] all_results = []
for task_id in tasks: print(f"\n{'β'*60}") print(f" Task: {task_id}") print(f"{'β'*60}")
try: result = run_episode( client, task_id, args.policy, args.seed, args.verbose ) all_results.append(result)
score = result["score"] bar = "β" * int(score * 30) + "β" * (30 - int(score * 30)) print(f"\n ββ RESULT βββββββββββββββββββββββββββββ") print(f" β Score : {score:.4f} [{bar}]") print(f" β Steps : {result['steps']}") print(f" β Total reward: {result['total_reward']}") print(f" β Reward mean : {result['reward_mean']}") for k, v in result.get("sub_scores", {}).items(): print(f" β β {k:<30s}: {v:.4f}") traj = result.get("trajectory_summary", {}) print(f" β Cleared : {traj.get('total_cleared', '?')}") print(f" β Avg delay : {traj.get('avg_delay_seconds', '?')}s") print(f" β Wall time : {result['wall_time_seconds']}s") if "llm_calls" in result: print(f" β LLM calls : {result['llm_calls']}") print(f" β LLM latency : {result['llm_avg_latency_ms']}ms avg") print(f" βββββββββββββββββββββββββββββββββββββββ")
except Exception as e: print(f" β Error: {e}") import traceback; traceback.print_exc()
# Summary table if len(all_results) > 1: print(f"\n{'='*60}") print(" SUMMARY") print(f"{'='*60}") print(f" {'Task':<35s} {'Score':>8s}") print(f" {'β'*35} {'β'*8}") for r in all_results: print(f" {r['task_id']:<35s} {r['score']:>8.4f}") scores = [r["score"] for r in all_results] print(f" {'β'*35} {'β'*8}") print(f" {'Average':<35s} {sum(scores)/len(scores):>8.4f}") print()
# Output JSON output_path = args.output if output_path: with open(output_path, "w") as f: json.dump({"results": all_results, "policy": args.policy, "seed": args.seed}, f, indent=2) print(f" Results written to: {output_path}") else: print("\n Full JSON results:") print(json.dumps({"results": all_results}, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# openenv.yaml# IntelliFlow Urban Traffic Control Environment# OpenEnv Specification Metadata v1.0# βββββββββββββββββββββββββββββββββββββββββββββ
name: IntelliFlow Urban Traffic Controlversion: "1.0.0"description: > A production-grade reinforcement learning simulation environment modelling a realistic urban intersection as a controllable episodic decision system. 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.
authors: - IntelliFlow Research Team
real_world_domain: Urban Transportation / Smart City Infrastructuretags: - traffic-control - reinforcement-learning - urban-simulation - multi-objective - openenv
# βββββββββββββββββββββββββββββββββββββββββββββ# Observation Space# βββββββββββββββββββββββββββββββββββββββββββββ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. 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).
# βββββββββββββββββββββββββββββββββββββββββββββ# 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" 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]" description: > Normalised throughput. max_possible = sat_flow * active_green_lanes. Reward is in [0,1] regardless of how many lanes are green. queue_delta_reward: formula: "w_wait * clip((prev_queue - curr_queue) / (n_lanes * capacity), -1, 1)" range: "[-0.8, +0.8]" description: > Rewards actively draining queues, penalises growing them. Delta-based so agent gets positive signal for every vehicle it clears beyond arrivals. congestion_pressure: formula: "-0.3 * (occupancy_rate ** 2)" range: "[-0.3, 0]" description: Quadratic background penalty for sustained high occupancy only. starvation_penalty: formula: "w_fairness * max_deviation(main_through_lane_occupancies)" range: "[-0.5, 0]" description: > Max-deviation of the 4 main through-lanes from their mean occupancy. Much more sensitive than variance for catching a single starved approach. Only activates when queue occupancy exceeds 40%. switch_penalty: formula: "w_switch * [1.0 if premature+unjustified | 0.3 if premature+justified | 0 otherwise]" range: "[-0.25, 0]" description: > Context-aware. Premature = < 15 steps elapsed. Justified = pressure diff > 0.25. FORCE_ALL_RED is never penalised β it's a legitimate safety action. spillback_severity: formula: "w_spillback * mean(max(0, (occ - 0.85)/0.15) for each lane)" range: "[-0.85, 0]" description: Escalating penalty per lane based on depth into spillback zone. gridlock_cliff: formula: "-8.0 * fraction_of_gridlocked_lanes" range: "[-8.0, 0]" description: Scaled cliff β proportional to how many lanes are simultaneously jammed. proactive_bonus: formula: "0.2 * pressure_diff if (switched AND pressure_diff > 0.3)" range: "[0, +0.2]" description: Bonus for switching phase when incoming approach has much higher pressure.
# βββββββββββββββββββββββββββββββββββββββββββββ# Tasks# βββββββββββββββββββββββββββββββββββββββββββββtasks: - id: task_suburban_steady name: Suburban Steady Flow difficulty: easy horizon: 600 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
- id: task_urban_stochastic name: Urban Stochastic Rush difficulty: medium horizon: 1200 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 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
# βββββββββββββββββββββββββββββββββββββββββββββ# Episode Configuration# βββββββββββββββββββββββββββββββββββββββββββββepisode: termination_conditions: - horizon_reached: "step_count >= horizon" - sustained_gridlock: "gridlock_steps >= 20 AND is_gridlock" reset: stochastic_seed_or_fixed seeding: supported
# βββββββββββββββββββββββββββββββββββββββββββββ# API Endpoints# βββββββββββββββββββββββββββββββββββββββββββββapi: framework: FastAPI base_url: "/" endpoints: - path: /reset method: POST description: Initialize new episode session - path: /step method: POST description: Apply action, advance simulation - path: /state method: GET description: Current full environment state - path: /tasks method: GET description: List all tasks with action/observation schemas - path: /grader method: POST description: Compute episode score [0,1] - path: /baseline method: POST description: Run baseline policy evaluation - path: /viz method: GET description: Live visualisation dashboard - path: /health method: GET description: Service health check
# βββββββββββββββββββββββββββββββββββββββββββββ# Deployment# βββββββββββββββββββββββββββββββββββββββββββββdeployment: platform: "Hugging Face Docker Space" framework: "FastAPI + Uvicorn" port: 7860 health_endpoint: /health
# βββββββββββββββββββββββββββββββββββββββββββββ# 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."12345678fastapi==0.115.5uvicorn[standard]==0.32.1pydantic==2.10.3numpy==1.26.4openai==1.57.0requests==2.32.3python-multipart==0.0.20httpx==0.28.1.gitignoreAdded
DockerfileAdded+45
README.mdAdded+338
app/__init__.pyAdded
app/api/__init__.pyAdded
app/api/main.pyAdded+457
app/baseline/__init__.pyAdded
app/baseline/policies.pyAdded+420
app/core/__init__.pyAdded
app/core/environment.pyAdded+837
app/core/session.pyAdded+138
app/tasks/__init__.pyAdded
app/tasks/registry.pyAdded+369
app/viz/__init__.pyAdded
app/viz/dashboard.pyAdded
inference.pyAdded+426
openenv.yamlAdded+291
requirements.txtAdded+8