Skip to content
AdityaSharma2007Public

About

Autonomous vehicle reinforcement learning (PPO/SAC/DQN) in SUMO with strict traffic compliance scoring, Gymnasium API, and real-time telemetry.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Traffic Compliance RL (Safety-Constrained Autonomous Vehicle Control)

Python Gymnasium Stable-Baselines3 SUMO Simulator PyTorch Frontend Tests License: MIT

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.


Table of Contents

  1. Project Vision & Overview
  2. Operational Safety Policy & Intervention Contract
  3. System Architecture
  4. Core Features & Engineering Deep Dive
  5. Observation Space, Action Space & Reward Formulation
  6. Traffic Rule Violation Engine & Compliance Scoring
  7. Repository Structure
  8. Environment Configuration Reference
  9. Installation & Setup Instructions
  10. Starting the Application
  11. Automated Test Suite & Verification
  12. Control Center Dashboard Walkthrough
  13. Benchmarking & Empirical Results
  14. Security, Safety & Operational Guardrails
  15. Troubleshooting & Common FAQs
  16. Author
  17. License & Acknowledgments

1. Project Vision & Overview

Autonomous driving research with Reinforcement Learning (RL) frequently suffers from three systemic vulnerabilities:

  1. Unconstrained Exploration Hazards: Standard RL algorithms prioritize cumulative return, often learning aggressive maneuvers, speed-limit violations, and unsafe lane changes unless harshly penalized.
  2. Silent Failure & Reward Conflation: Collapsing rule compliance, collision avoidance, and transit efficiency into an opaque scalar reward obscures why an agent succeeds or fails.
  3. 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.

The Traffic Compliance RL Solution

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.

2. Operational Safety Policy & Intervention Contract

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, setting terminated = True with termination_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.

3. System Architecture

                         ┌─────────────────────────────────────────┐
                         │       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)

4. Core Features & Engineering Deep Dive

4.1 Single Ego-Car Controller in SUMO NPC Swarm

  • 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.

4.2 33-Feature Continuous Observation Space

  • 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.

4.3 Deterministic Rule Engine & Time-To-Collision (TTC)

  • 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}} &gt; v_{\text{leader}})$$
  • Triggers tiered penalties when $\text{TTC} &lt; \tau_{\text{critical}}$ alongside safe headway violations.

4.4 Tiered Safety Intervention Policy (100 → 50 → 20 Stop)

  • Implemented in backend/env/compliance_score.py and InterventionPolicy.
  • 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.

4.5 Multi-Algorithm RL Suite (PPO, SAC, DQN)

  • 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.

4.6 Telemetry Pipeline & JSONL Traces

  • 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.

4.7 Streamlit Control Center Dashboard

  • 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.

4.8 Research & Statistical Benchmarking Suite

  • 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.

5. Observation Space, Action Space & Reward Formulation

Observation Space (33 Canonical Features)

All features are normalized to $[-1.0, 1.0]$ or $[0.0, 1.0]$:

Index Feature Key Physical Description Normalization Range
0 ego_speed Current ego longitudinal velocity $[0, v_{\max}]$
1 speed_limit Regulatory posted speed limit on active lane $[0, v_{\max}]$
2 ego_acceleration Instantaneous longitudinal acceleration $[-a_{\max}, a_{\max}]$
3 waiting_time Cumulative time spent stationary ($v &lt; 0.1 \text{ m/s}$) $[0, t_{\max}]$
4–6 leader_dist, leader_spd, rel_spd Distance, absolute speed, and relative speed to leader $[0, 100\text{m}]$, $[-v, v]$
7–8 ttc, safe_distance Time-to-collision and minimum safe following headway $[0, \tau_{\max}]$, $[0, d_{\max}]$
9–11 left_lane_avail, right_lane_avail, current_lane Lateral lane presence flags and 0-indexed lane index ${0, 1}$
12–14 tl_state, tl_distance, tl_time_to_change Signal phase (Red/Yellow/Green), distance, and phase timer ${0, 1, 2}$, $[0, d_{\max}]$
15–16 route_progress, route_remaining Fraction of route completed and meters to destination $[0.0, 1.0]$, $[0, D_{\text{route}}]$
17–20 traffic_density, surrounding_count, mean_spd Fleet density, vehicles within 50m radius, mean flow speed $[0.0, 1.0]$, $[0, N_{\max}]$
21 emergency_present Active emergency vehicle siren/proximity flag ${0, 1}$
22–32 context_vector Extended temporal window & lateral positioning metrics $[-1.0, 1.0]$

Action Space

The continuous environment utilizes a 2-dimensional Box action space:

$$\mathbf{a} = \begin{bmatrix} a_{\text{accel}} \ a_{\text{lane}} \end{bmatrix} \in [-1.0, 1.0]^2$$

  • $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}} &lt; -0.5 \implies$ Initiate Left Lane Change
    • $a_{\text{lane}} &gt; +0.5 \implies$ Initiate Right Lane Change
    • $-0.5 \le a_{\text{lane}} \le +0.5 \implies$ Maintain Current Lane

6. Traffic Rule Violation Engine & Compliance Scoring

Compliance Score Formulation

The compliance score $S_t \in [0, 100]$ evolves dynamically at each timestep $t$:

$$S_t = \max\left(0, \min\left(100, S_{t-1} - \sum_{i \in \mathcal{V}_t} P_i + R_{\text{recovery}}\right)\right)$$

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.

Penalty Schedule

Category Rule Identifier Trigger Condition Penalty ($P_i$) 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 $\text{TTC} &lt; 1.5\text{s}$ at current delta speed -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 $v_{\text{ego}} &gt; v_{\text{limit}} + 2.0 \text{ km/h}$ -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 $&lt; -4.0 \text{ m/s}^2$ -5 5
Comfort weaving Rapid back-and-forth lane oscillations ($&lt; 3\text{s}$) -8 10
Efficiency excessive_wait Stationary with green signal and clear leader gap -5 20

7. Repository Structure

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

8. Environment Configuration Reference

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

9. Installation & Setup Instructions

Prerequisites

  • 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_HOME environment variable is set and sumo is available on your PATH.

Step-by-Step Setup (Windows PowerShell)

# 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.txt

10. Starting the Application

1. Launch the Streamlit Control Center

Start the interactive mission control dashboard:

streamlit run frontend/app.py

Access the dashboard in your browser at: $$\mathbf{http://localhost:8501}$$

2. Run Single-Algorithm Model Training

Train an individual algorithm (e.g., PPO) with custom timesteps:

python -m backend.rl.train_ppo --timesteps 50000

Or train SAC or DQN:

python -m backend.rl.train_sac --timesteps 50000
python -m backend.rl.train_dqn --timesteps 50000

3. Unified Multi-Algorithm Benchmark Training

Train all algorithms under identical seed constraints:

python -m backend.rl.train_all --algorithm ALL --timesteps 100000

(Alternatively, run train_all.bat on Windows).

4. Run Held-Out Research Evaluation

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).


11. Automated Test Suite & Verification

The repository includes a comprehensive, multi-layer verification suite.

Step 1: Asset Preflight Check

Validates road networks, SUMO configs, NPC definitions, and confirms no hardcoded machine paths exist:

python scripts/verify_assets.py

Step 2: Automated Pytest Suite

Executes unit tests, observation contract verifications, rule boundary assertions, and live TraCI integrations:

pytest -v

(Alternatively, run smoke_test.bat).


12. Control Center Dashboard Walkthrough

The Streamlit Control Center (frontend/app.py) provides an operational interface for engineers and researchers:

  1. 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.
  2. Fleet Monitor: Breakdown of active NPC vehicles across classes (passenger, bus, motorcycle, emergency, truck) and microscopic spatial density heatmaps.
  3. Compliance & Violations: Dynamic timeline of compliance score evolution, severity breakdown, and detailed event log with timestamps.
  4. RL Research: Comparative algorithm leaderboard with 95% bootstrap confidence intervals, Pareto frontier plots (Compliance vs. Return), and LaTeX export tabs.
  5. Live Monitor: Launches an interactive, opt-in SUMO visual validation session using TrafficEnv, streaming step-by-step telemetry directly to the browser.
  6. System Health: Integrity check over generated artifacts, directory paths, and SUMO TraCI socket communication.

13. Benchmarking & Empirical Results

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.

Benchmark Leaderboard (Sample Multi-Seed Evaluation)

Algorithm Mean Compliance Intervention Rate Collision Rate Mean Speed ($\text{km/h}$) 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%

14. Security, Safety & Operational Guardrails

  • 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 .jsonl files with cryptographic run IDs to prevent retroactive result tampering.

15. Troubleshooting & Common FAQs

Q1: SUMO_HOME environment variable is not set.

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")

Q2: Port binding or TraCI connection collision occurs when running multiple environments.

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.

Q3: How do I change the control frequency of the simulation?

Resolution: Modify step_length in config/config.yaml. The default is 0.2 (5 actions per second).

Q4: Streamlit port 8501 is already in use.

Resolution: Run Streamlit on a custom port:

streamlit run frontend/app.py --server.port 8502

16. Author

Aditya Sharma
BTech CSE (AI&ML)


17. License & Acknowledgments


Traffic Compliance RL — Engineering rigorous, safe, and verifiable autonomous mobility.

About

Autonomous vehicle reinforcement learning (PPO/SAC/DQN) in SUMO with strict traffic compliance scoring, Gymnasium API, and real-time telemetry.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages