🚥 Traffic Signal Optimization — OpenEnv Elite
Meta × PyTorch OpenEnv Hackathon Submission
A world-class Reinforcement Learning environment for urban traffic control, featuring stochastic multi-lane dynamics, emergency vehicle prioritization, and sophisticated fairness-driven rewards.
🏗️ Problem Statement
Fixed-cycle traffic signals are a relic of the past. In modern urban environments, they create needless congestion, increase CO2 emissions, and — most critically — cause life-threatening delays for emergency vehicles.
This project provides a high-fidelity 4-way intersection simulation designed for OpenEnv. It challenges RL agents to move beyond simple throughput and master the art of dynamic balancing: serving high-demand lanes while maintaining fairness for low-traffic directions and clearing "Golden Windows" for emergency responders.
🚀 Quick Start
1# Run the complete suite: Simulation + Sanity Checks + Comparison
2python test_env.py
3
4# Run a specific high-intensity scenario
5python test_env.py hard
1from env import TrafficEnv
2from tasks import get_config
3from baseline_agent import RuleBasedAgent
4
5# 1. Load a structured difficulty profile
6config = get_config("medium")
7env = TrafficEnv(config)
8
9# 2. Initialize our sophisticated Rule-Based Controller
10agent = RuleBasedAgent()
11
12state = env.reset()
13done = False
14
15while not done:
16 action = agent.select_action(state)
17 state, reward, done, info = env.step(action)
18
19print(f"Total Cleared: {info['total_cleared']}")
20print(f"Fairness Index: {info['fairness_score']:.2f}")
🧠 Environment Design Philosophy
State Space
The environment exposes a 14-dimensional continuous observation vector, providing the agent with full situational awareness:
- Queues (4): Exact vehicle count per lane [N, S, E, W].
- Wait Pressure (4): Cumulative "impatience" score per lane.
- Emergency Flags (4): Binary detection of EVs per lane.
- Signal State (2): Current phase [0=NS, 1=EW] and step count.
Action Space
0: Maintain — keep the current green phase.
1: Switch — transition the signal (includes yellow-phase discharge friction).
💎 Reward Engineering (The "Judge's Choice")
Our reward function is the core of this submission. It isn't just a count; it's a multi-objective ethical framework clipped to [-1, 1]:
| Component | Logic | Purpose |
|---|
| Throughput (+) | +0.20 * cars_cleared | Incentivizes active vehicle flow. |
| Density (-) | -0.40 * total_congestion | Penalizes letting the intersection fill up. |
| Bottleneck (-) | -0.15 * max_queue | Discourages extreme build-up in any single lane. |
| Stability (-) | -switch_penalty | Prevents "flickering" and promotes signal stability. |
| Fairness (+/-) | +0.10 bonus / -penalty | Rewards balanced service; penalizes starvation. |
| Emergency (🚨) | Golden Window Bonus | Massive reward for clearing EVs within target steps. |
| EV Delay (-) | Exponential Penalty | Punishes agents for delaying life-saving vehicles. |
📊 Evaluation Metrics
We track 8 key performance indicators per episode to ensure a winning submission can be quantified:
- Total Cleared: Raw efficiency metric.
- Avg Waiting Time: The "commuter frustration" index.
- Max Queue Length: Gauges system robustness against bottlenecks.
- Signal Switch Count: Measures policy stability.
- Congestion Score: Final system state snapshot.
- Avg EV Clear Time: Critical safety metric (lower is better).
- Fairness Score: [0, 1] index — how equally did we serve all lanes?
- Total EV Penalty: Measures total failure to prioritize safety.
⚡ Task Difficulty Levels
| Parameter | Easy | Medium | Hard |
|---|
| Arrival Rate | 0–1 | 1–3 | 2–5 |
| Discharge Rate | 4–5 | 3–5 | 2–4 |
| Burst Frequency | 0% | 10% | 20% |
| Emergency Prob | 1% | 5% | 15% |
| EV Golden Window | 8 steps | 5 steps | 3 steps |
| Fairness Limit | 20 steps | 15 steps | 10 steps |
🚑 Emergency & Fairness Logic
The "Golden Window"
When an Emergency Vehicle (EV) appears, the agent is granted a bonus if it switches and clears the lane within the Golden Window (defined per difficulty). Failing to do so triggers an exponential delay penalty, simulating the real-world cost of stopping an ambulance or fire truck.
Fairness Guard
To prevent "Starvation" (where the agent ignores a low-traffic lane to optimize throughput on a high-traffic lane), a Fairness Score is calculated. If a lane remains red beyond the Starvation Limit, the agent suffers a heavy penalty. This forces the agent to learn the complex trade-off between total throughput and social fairness.
🚶 Step Walkthrough
1Step 12: 🚨 Ambulance detected in East lane (currently RED).
2 - EW Queue: 4, EV Timer: 0
3 - Agent receives p_emergency penalty.
4
5Step 13: Agent Action: 1 (SWITCH to EW).
6 - Switch penalty applied (-0.20).
7 - NS lanes stop; EW lanes turn GREEN.
8
9Step 14: EV Cleared!
10 - EV Clear Time: 2 steps.
11 - Agent receives r_ev_bonus (+0.25) for "Golden Window" clearance.
12 - Total cleared (+0.60 reward).
🔮 Future Improvements
- Multi-Intersection Coordination: Extending to a grid of agents using MARL.
- Pedestrian Logic: Adding crosswalks and pedestrian priority.
- V2X Communication: Providing agents with ahead-of-time traffic predictions.
📜 License
MIT © 2026 Meta x PyTorch OpenEnv Hackathon