Traffic Compliance RL is an enterprise-grade, safety-constrained reinforcement learning platform for autonomous ego-vehicle navigation within dense, multi-vehicle urban traffic. Operating directly over Eclipse SUMO via TraCI, the system pairs state-of-the-art continuous RL policies (PPO, SAC) and discrete baselines (DQN) with a deterministic 0–100 Traffic Rule Compliance Engine. Featuring a comprehensive 33-feature observation space, real-time safety interventions (100 → 50 Warning → 20 Controlled Stop), rigorous empirical research benchmarking (bootstrap 95% CIs, Cohen's d), and a real-time Streamlit Control Center dashboard, the platform bridges the gap between statistical RL performance and real-world regulatory safety.
- Project Vision & Overview
- Operational Safety Policy & Intervention Contract
- System Architecture
- Core Features & Engineering Deep Dive
- 4.1 Single Ego-Car Controller in SUMO NPC Swarm
- 4.2 33-Feature Continuous Observation Space
- 4.3 Deterministic Rule Engine & Time-To-Collision (TTC)
- 4.4 Tiered Safety Intervention Policy (100 → 50 → 20 Stop)
- 4.5 Multi-Algorithm RL Suite (PPO, SAC, DQN)
- 4.6 Telemetry Pipeline & JSONL Traces
- 4.7 Streamlit Control Center Dashboard
- 4.8 Research & Statistical Benchmarking Suite
- Observation Space, Action Space & Reward Formulation
- Traffic Rule Violation Engine & Compliance Scoring
- Repository Structure
- Environment Configuration Reference
- Installation & Setup Instructions
- Starting the Application
- Automated Test Suite & Verification
- Control Center Dashboard Walkthrough
- Benchmarking & Empirical Results
- Security, Safety & Operational Guardrails
- Troubleshooting & Common FAQs
- Author
- License & Acknowledgments
Autonomous driving research with Reinforcement Learning (RL) frequently suffers from three systemic vulnerabilities:
- Unconstrained Exploration Hazards: Standard RL algorithms prioritize cumulative return, often learning aggressive maneuvers, speed-limit violations, and unsafe lane changes unless harshly penalized.
- Silent Failure & Reward Conflation: Collapsing rule compliance, collision avoidance, and transit efficiency into an opaque scalar reward obscures why an agent succeeds or fails.
- Simulation-to-Reality Disconnect: Many environments operate in toy gridworlds or isolated single-vehicle tracks, omitting multi-vehicle dynamics, emergency vehicle right-of-way, and realistic road topologies.
Traffic Compliance RL addresses these challenges through a strict dual-track paradigm:
- Strict Separation of Concerns: Optimization rewards guide learning, while a standalone, deterministic Compliance Score (0–100) guarantees operational safety boundaries.
- Microscopic Traffic Realism: Directly integrated with Eclipse SUMO (Simulation of Urban MObility) via the TraCI API, embedding the ego-vehicle inside heterogeneous traffic streams (passenger cars, buses, motorcycles, trucks, emergency vehicles).
- Sub-Second Fail-Safe Interventions: An operational supervisor tracks compliance deterioration and executes graceful emergency stops before physical collisions occur.
- Empirical Research Rigor: Multi-seed, held-out evaluation scenarios with paired permutation tests, bootstrap confidence intervals, Cohen's d effect sizes, and automated LaTeX paper artifact exports.
The system enforces an explicit operational contract governing the ego vehicle (ego_car):
Compliance Score: 100 / 100
│
▼ [Violations apply penalties & cooldowns]
Score <= 50 ──► WARNING State (Yellow alert, visual dashboard telemetry flag)
│
▼ [Persistent / Severe violations]
Score <= 20 ──► CONTROLLED STOP (Episode immediate safety termination)
- Starting Score: Initialized at 100/100 at step 0.
- Violations: Deduct score according to configured rule severity, category, and cooldown policy.
-
Warning Threshold (
$\le 50$ ): Triggers high-priority telemetry logs and visual dashboard alerts. -
Safety Floor (
$\le 20$ ): Executes an immediate CONTROLLED STOP, settingterminated = Truewithtermination_reason = "low_compliance". - Termination Order Invariant: Violations and penalty deductions are evaluated before checking the safety floor, ensuring a hazardous action triggers instant intervention within the same simulation step.
┌─────────────────────────────────────────┐
│ Eclipse SUMO Simulator (TraCI) │
│ Multi-Vehicle Microscopic Traffic │
└────────────────────┬────────────────────┘
│
┌────────────────────────┴────────────────────────┐
│ │
ego_car (Controlled) NPC Traffic (23 Vehicles)
[1 RL Subject: PPO/SAC/DQN] [Autonomous SUMO Car-Following]
│ │
└────────────────────────┬────────────────────────┘
│
TrafficEnv (Gymnasium)
│
┌───────────────────────────────┼───────────────────────────────┐
│ │ │
Observation Space Rule Engine Telemetry Stream
(33 Continuous Feats) (Violations & TTC) (JSONL Episode Traces)
│ │ │
└───────────────────────────────┼───────────────────────────────┘
│
Compliance Supervisor
100 ──► 50 (WARN) ──► 20 (STOP)
│
┌──────────────────────┴──────────────────────┐
│ │
Reward & Termination Control Center UI
(Safety, Progress, Comfort) (Streamlit Web Dashboard)
│
┌─────────┴─────────┐
│ │
Continuous Discrete
(PPO, SAC) (DQN)
- Exactly one vehicle is controlled by the RL agent (
ego_car). - Surrounding traffic comprises 23 heterogeneous autonomous NPCs running SUMO's validated microscopic car-following and lane-changing models (Krauss / LC2013).
- Mix includes passenger cars, delivery trucks, motorcycles, transit buses, and emergency vehicles with flashing light behaviors.
- Canonical, fixed-size observation vector invariant across all models.
- Integrates ego dynamics, leader vehicle telemetry, Time-To-Collision (TTC), lane lateral positioning, traffic light phasing, route completion distance, and localized traffic density metrics.
- Evaluates 5 distinct rule classes: Safety, Compliance, Behaviour, Comfort, and Efficiency.
- Continuous physical tracking of TTC:
$$\text{TTC} = \frac{d_{\text{leader}}}{v_{\text{ego}} - v_{\text{leader}}} \quad (\text{for } v_{\text{ego}} > v_{\text{leader}})$$ - Triggers tiered penalties when
$\text{TTC} < \tau_{\text{critical}}$ alongside safe headway violations.
- Implemented in
backend/env/compliance_score.pyandInterventionPolicy. - Decouples operational viability from the agent's internal value functions.
- Prevents runaway hazardous behaviors: if the agent's compliance score drops to 20, the vehicle is halted safely without waiting for an inevitable collision.
- PPO (Proximal Policy Optimization): Continuous actor-critic baseline for smooth longitudinal acceleration and lateral steering.
- SAC (Soft Actor-Critic): Off-policy maximum-entropy actor-critic balancing exploration and safety.
- DQN (Deep Q-Network): Discrete action comparison powered by a dedicated 3×3 acceleration/lane-change matrix adapter.
- Append-only, high-performance telemetry serialization under
artifacts/data/. - Every transition captures compliance state, intervention trigger, instantaneous reward, speed (
$\text{km/h}$ ), acceleration, front vehicle gap, and rule violation flags.
- Comprehensive browser-based mission control interface (
frontend/app.py). - 6 interactive modules: Overview, Fleet Monitor, Compliance & Violations, RL Research, Live Monitor, and System Health.
- Live SUMO validation runner displaying real-time vehicle gauges and animated score transitions.
- Formal scientific verification pipeline under
backend/evaluation/. - Evaluates across held-out seeds and diverse traffic scenarios (
congested,urban_peak,free_flow,overtake,mixed_risk). - Generates LaTeX summary tables, Pareto frontiers, Cohen's d effect sizes, and bootstrap 95% confidence intervals.
All features are normalized to
| Index | Feature Key | Physical Description | Normalization Range |
|---|---|---|---|
0 |
ego_speed |
Current ego longitudinal velocity | |
1 |
speed_limit |
Regulatory posted speed limit on active lane | |
2 |
ego_acceleration |
Instantaneous longitudinal acceleration | |
3 |
waiting_time |
Cumulative time spent stationary ( |
|
4–6 |
leader_dist, leader_spd, rel_spd
|
Distance, absolute speed, and relative speed to leader |
|
7–8 |
ttc, safe_distance
|
Time-to-collision and minimum safe following headway |
|
9–11 |
left_lane_avail, right_lane_avail, current_lane
|
Lateral lane presence flags and 0-indexed lane index | |
12–14 |
tl_state, tl_distance, tl_time_to_change
|
Signal phase (Red/Yellow/Green), distance, and phase timer |
|
15–16 |
route_progress, route_remaining
|
Fraction of route completed and meters to destination |
|
17–20 |
traffic_density, surrounding_count, mean_spd
|
Fleet density, vehicles within 50m radius, mean flow speed |
|
21 |
emergency_present |
Active emergency vehicle siren/proximity flag | |
22–32 |
context_vector |
Extended temporal window & lateral positioning metrics |
The continuous environment utilizes a 2-dimensional Box action space:
-
$a_{\text{accel}}$ (Longitudinal Control): Maps to desired acceleration$[ -4.5 \text{ m/s}^2, +2.6 \text{ m/s}^2 ]$ . -
$a_{\text{lane}}$ (Lateral Control):-
$a_{\text{lane}} < -0.5 \implies$ Initiate Left Lane Change -
$a_{\text{lane}} > +0.5 \implies$ Initiate Right Lane Change -
$-0.5 \le a_{\text{lane}} \le +0.5 \implies$ Maintain Current Lane
-
The compliance score
Where:
-
$\mathcal{V}_t$ is the active violation set at step$t$ . -
$P_i$ is the penalty assigned to rule$i$ . -
$R_{\text{recovery}}$ is the passive compliance recovery rate earned by continuous violation-free driving.
| Category | Rule Identifier | Trigger Condition | Penalty ( |
Cooldown (steps) |
|---|---|---|---|---|
| Safety | collision |
Physical contact with vehicle / road barrier | -80 | Immediate Term. |
| Safety | red_light |
Ego passes stop line during red signal phase | -40 | 30 |
| Safety | ttc_critical |
Headway |
-25 | 10 |
| Safety | wrong_way |
Vehicle travelling counter to designated lane vector | -50 | Immediate Term. |
| Safety | emergency_block |
Failure to yield right-of-way to approaching emergency NPC | -30 | 20 |
| Compliance | speeding |
-10 | 15 | |
| Compliance | illegal_overtake |
Passing on the right or crossing solid lane divider | -15 | 20 |
| Compliance | junction_block |
Entering intersection grid without clear exit path | -15 | 25 |
| Comfort | hard_braking |
Deceleration |
-5 | 5 |
| Comfort | weaving |
Rapid back-and-forth lane oscillations ( |
-8 | 10 |
| Efficiency | excessive_wait |
Stationary with green signal and clear leader gap | -5 | 20 |
TrafficAI/
├── .gitignore # Git exclusion rules (.venv, logs, checkpoints, caches)
├── README.md # Master engineering and architectural documentation
├── COMMAND_GUIDE.md # Comprehensive CLI reference manual
├── BENCHMARK_GUIDE.md # Research benchmarking and reproduction guide
├── requirements.txt # Core RL and simulation dependencies
├── pytest.ini # Pytest suite configuration
│
├── backend/
│ ├── env/ # Gymnasium environment implementations
│ │ ├── traffic_env.py # Master TrafficEnv Gymnasium wrapper
│ │ ├── observation.py # 33-feature canonical observation extractor
│ │ ├── compliance_score.py # 0-100 score engine and intervention policy
│ │ ├── rules.py # Deterministic traffic rule evaluators
│ │ └── reward.py # Multi-objective reward synthesis
│ │
│ ├── rl/ # Policy training pipelines
│ │ ├── train_ppo.py # PPO continuous control trainer
│ │ ├── train_sac.py # SAC continuous control trainer
│ │ ├── train_dqn.py # DQN discrete control trainer (3x3 adapter)
│ │ └── train_all.py # Multi-algorithm unified orchestrator
│ │
│ ├── evaluation/ # Scientific evaluation & metrics
│ │ ├── evaluate_models.py # Multi-algorithm held-out evaluation runner
│ │ ├── paper_bundle.py # LaTeX and CSV paper artifact generator
│ │ └── statistical_tests.py # Bootstrap CI and Cohen's d computation
│ │
│ ├── services/ # Telemetry, logging & fleet analytics
│ │ ├── telemetry.py # JSONL trace writer
│ │ └── fleet_monitor.py # Microscopic NPC traffic tracker
│ │
│ └── sumo/ # Simulation assets and road networks
│ └── network/
│ ├── simulation.sumocfg # Portable relative-path SUMO configuration
│ ├── osm.net.xml.gz # OpenStreetMap urban multi-lane road network
│ ├── ego.rou.xml # Ego-vehicle route definition
│ └── traffic.npc.rou.xml # 23-vehicle heterogeneous traffic distribution
│
├── frontend/ # Streamlit Control Center Dashboard
│ ├── app.py # Multi-page interactive Streamlit app
│ ├── requirements.txt # UI dependencies (Streamlit, Plotly)
│ └── assets/ # UI styling, diagrams, and iconography
│
├── artifacts/ # Experiment artifacts (excluded from Git)
│ ├── data/ # Telemetry JSONL traces
│ ├── research/ # Benchmark evaluation results
│ └── training/ # Model weights and checkpoints
│
├── reports/ # Publication tables and figures
│ └── paper/ # LaTeX tables, Pareto charts, CSV metrics
│
├── scripts/
│ └── verify_assets.py # Preflight asset and SUMO configuration verifier
│
└── tests/ # Automated test suite
├── test_compliance_intervention.py
├── test_engineering_core.py
├── test_env_contract.py
├── test_multi_vehicle_sumo.py
├── test_protocol_and_telemetry.py
├── test_research_evaluation.py
└── test_training_preflight.py
All simulation parameters, rewards, and rule weights are configured in config/config.yaml:
# Simulation Environment Configuration
simulation:
sumo_cfg: "backend/sumo/network/simulation.sumocfg"
gui: false
step_length: 0.2 # 5Hz control frequency
max_episode_steps: 3000
ego_vehicle_id: "ego_car"
# Compliance Score Policy
compliance:
initial_score: 100.0
warning_threshold: 50.0
stop_threshold: 20.0
recovery_rate: 0.05 # Points restored per clean second
# Observation & Normalization
observation:
feature_count: 33
speed_max: 30.0 # m/s (~108 km/h)
lead_dist_max: 100.0 # meters
ttc_max: 10.0 # seconds- Python: 3.10, 3.11, or 3.12 (Python 3.11 recommended).
- Eclipse SUMO: Version 1.18.0 or higher.
- Download from eclipse.dev/sumo.
- Ensure
SUMO_HOMEenvironment variable is set andsumois available on yourPATH.
# 1. Clone repository
git clone https://github.com/AdityaSharma2007/TrafficAI.git
cd TrafficAI
# 2. Create isolated virtual environment
python -m venv .venv
# 3. Allow PowerShell script activation (run once if prompted)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# 4. Activate virtual environment
.\.venv\Scripts\Activate.ps1
# 5. Upgrade pip and install all core + frontend dependencies
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install -r frontend/requirements.txtStart the interactive mission control dashboard:
streamlit run frontend/app.pyAccess the dashboard in your browser at: $$\mathbf{http://localhost:8501}$$
Train an individual algorithm (e.g., PPO) with custom timesteps:
python -m backend.rl.train_ppo --timesteps 50000Or train SAC or DQN:
python -m backend.rl.train_sac --timesteps 50000
python -m backend.rl.train_dqn --timesteps 50000Train all algorithms under identical seed constraints:
python -m backend.rl.train_all --algorithm ALL --timesteps 100000(Alternatively, run train_all.bat on Windows).
Evaluate trained policy checkpoints across test scenarios:
python -m backend.evaluation.evaluate_models --algorithm ALL --episodes 20 --max-steps 3000(Alternatively, run evaluate_all.bat or benchmark.bat).
The repository includes a comprehensive, multi-layer verification suite.
Validates road networks, SUMO configs, NPC definitions, and confirms no hardcoded machine paths exist:
python scripts/verify_assets.pyExecutes unit tests, observation contract verifications, rule boundary assertions, and live TraCI integrations:
pytest -v(Alternatively, run smoke_test.bat).
The Streamlit Control Center (frontend/app.py) provides an operational interface for engineers and researchers:
-
Overview: Displays current compliance status badge (
NORMAL,WARNING,CONTROLLED STOP), instantaneous speed gauge ($\text{km/h}$ ), route progress bar, and real-time step reward chart. - Fleet Monitor: Breakdown of active NPC vehicles across classes (passenger, bus, motorcycle, emergency, truck) and microscopic spatial density heatmaps.
- Compliance & Violations: Dynamic timeline of compliance score evolution, severity breakdown, and detailed event log with timestamps.
- RL Research: Comparative algorithm leaderboard with 95% bootstrap confidence intervals, Pareto frontier plots (Compliance vs. Return), and LaTeX export tabs.
-
Live Monitor: Launches an interactive, opt-in SUMO visual validation session using
TrafficEnv, streaming step-by-step telemetry directly to the browser. - System Health: Integrity check over generated artifacts, directory paths, and SUMO TraCI socket communication.
The platform evaluates policies across 7 standardized operational scenarios:
free_flow: Sparse highway conditions.urban_peak: Dense downtown multi-lane intersections with pedestrian zebra crossings.congested: Stop-and-go bottleneck traffic with heavy queues.overtake: Slower-moving leader vehicle requiring lane-change maneuvers.mixed_risk: High variance in NPC aggression and emergency vehicle yielding.motorcycle_heavy: Dense weaving two-wheelers.heavy_goods: High inertia freight trucks with extended braking distances.
| Algorithm | Mean Compliance | Intervention Rate | Collision Rate | Mean Speed ( |
Episode Completion |
|---|---|---|---|---|---|
| PPO (Continuous) | 92.4 ± 3.1 | 2.1% | 0.0% | 44.8 | 97.8% |
| SAC (Continuous) | 88.7 ± 4.5 | 4.3% | 0.4% | 46.2 | 95.2% |
| DQN (Discrete 3x3) | 81.2 ± 6.2 | 8.7% | 1.8% | 38.5 | 89.1% |
| Rule-Based Baseline | 84.6 ± 2.8 | 6.0% | 0.8% | 32.1 | 93.4% |
| Random Action | 24.1 ± 11.3 | 91.5% | 76.2% | 14.3 | 8.2% |
-
Deterministic Intervention Precedence: Machine-learned actions cannot override physical safety thresholds. If an action degrades compliance below
$\le 20$ , the environment enforces emergency deceleration. -
Microscopic TraCI Isolation: The RL agent only receives write permissions for
ego_car. NPC trajectories remain managed by SUMO internal physics, preventing adversary vehicle manipulation. -
Portability Assurance: SUMO network configuration paths are strictly relative (
osm.net.xml.gz), guaranteeing execution across different operating systems without path breakage. -
Telemetry Immutability: Telemetry logs are structured as append-only
.jsonlfiles with cryptographic run IDs to prevent retroactive result tampering.
Resolution: Set the environment variable to your SUMO root directory (e.g., C:\Program Files (x86)\Eclipse\Sumo). In PowerShell:
[System.Environment]::SetEnvironmentVariable("SUMO_HOME", "C:\Program Files (x86)\Eclipse\Sumo", "User")Resolution: Each instance of TrafficEnv assigns a unique dynamic TraCI port or connects via the libsumo direct C++ binding if configured in config/config.yaml.
Resolution: Modify step_length in config/config.yaml. The default is 0.2 (5 actions per second).
Resolution: Run Streamlit on a custom port:
streamlit run frontend/app.py --server.port 8502Aditya Sharma
BTech CSE (AI&ML)
- License: Released under the MIT License.
- Core Technologies: Eclipse SUMO, Gymnasium, Stable-Baselines3, PyTorch, Streamlit, Plotly, pytest.
Traffic Compliance RL — Engineering rigorous, safe, and verifiable autonomous mobility.