Skip to content

Latest commit

Β 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Traffic Light Optimization using Deep Q-Learning

An intelligent traffic signal control system that uses Deep Reinforcement Learning to optimize traffic flow at intersections. The AI agent learns to minimize vehicle waiting times through trial and error, adapting to different traffic patterns.

Python 3.12 TensorFlow 2.20 SUMO 1.24 License: MIT

🎯 Overview

Traditional traffic lights operate on fixed timers, causing unnecessary delays and congestion. This project implements an adaptive traffic control system using:

  • Deep Q-Learning: Reinforcement learning algorithm for decision making
  • Neural Networks: 5-layer deep network with 400 neurons per layer
  • SUMO Simulator: Realistic traffic simulation environment
  • Experience Replay: Stable learning from past experiences

Key Features

  • βœ… Real-time Decision Making: AI observes traffic and adapts signal timings
  • βœ… Learning from Experience: Improves over 100+ training episodes
  • βœ… Smart Traffic Management: Minimizes cumulative waiting time
  • βœ… Visualization: Training metrics and testing results with graphs

πŸš€ Quick Start

Prerequisites

  1. Python 3.12+ - Download
  2. SUMO 1.24+ - Download
  3. Git - Download

Installation

# Clone the repository
git clone https://github.com/sumitsingh3072/Traffic-Light-Optimization.git
cd Traffic-Light-Optimization

# Create virtual environment
python -m venv .venv

# Activate virtual environment
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate

# Install dependencies
pip install -r Requirements.txt

# Setup SUMO environment
# Windows: Set SUMO_HOME and add to PATH
setx SUMO_HOME "C:\Program Files (x86)\Eclipse\Sumo"
# Linux/Mac: Add to ~/.bashrc or ~/.zshrc
export SUMO_HOME="/usr/share/sumo"
export PATH="$SUMO_HOME/bin:$PATH"

Training the Model

cd TCLS
python training_main.py

Training Configuration (training_settings.ini):

  • Episodes: 100 (customizable)
  • Duration: ~6 hours for 100 episodes
  • GUI: Disabled by default (set gui = True to visualize)

Testing the Model

cd TCLS
python testing_main.py

Testing Configuration (testing_settings.ini):

  • Set model_to_test = X (model number to test)
  • GUI enabled by default
  • Single episode evaluation

πŸ“Š How It Works

The AI Agent

State Space (80 dimensions):

  • 4 incoming directions (North, South, East, West)
  • Each direction divided into 20 position cells
  • Binary representation: 1 = vehicle present, 0 = empty
  • Captures vehicle positions up to 750m from intersection

Action Space (4 discrete actions):

  • Action 0: North-South Green (straight/right turns)
  • Action 1: North-South Left Green (left turns only)
  • Action 2: East-West Green (straight/right turns)
  • Action 3: East-West Left Green (left turns only)

Each green phase lasts 10 seconds, with 4-second yellow transitions.

Reward Function:

reward = previous_cumulative_waiting_time - current_cumulative_waiting_time
  • Positive reward β†’ Reduced waiting time (good decision)
  • Negative reward β†’ Increased waiting time (poor decision)

Neural Network Architecture

Input Layer:    80 neurons (state representation)
Hidden Layer 1: 400 neurons (ReLU activation)
Hidden Layer 2: 400 neurons (ReLU activation)
Hidden Layer 3: 400 neurons (ReLU activation)
Hidden Layer 4: 400 neurons (ReLU activation)
Hidden Layer 5: 400 neurons (ReLU activation)
Output Layer:   4 neurons (Q-values for each action)

Learning Algorithm: Deep Q-Learning with Experience Replay

Q(s,a) = reward + Ξ³ Γ— max Q(s',a')

Where:

  • Ξ³ = 0.75 (discount factor)
  • Experience replay buffer: 50,000 samples
  • Batch size: 100
  • Training epochs per episode: 800

πŸ“ Project Structure

Traffic-Light-Optimization/
β”œβ”€β”€ TCLS/                          # Main source code
β”‚   β”œβ”€β”€ training_main.py          # Training entry point
β”‚   β”œβ”€β”€ testing_main.py           # Testing entry point
β”‚   β”œβ”€β”€ model.py                  # Neural network definition
β”‚   β”œβ”€β”€ training_simulation.py    # Training simulation logic
β”‚   β”œβ”€β”€ testing_simulation.py     # Testing simulation logic
β”‚   β”œβ”€β”€ generator.py              # Traffic generation
β”‚   β”œβ”€β”€ memory.py                 # Experience replay buffer
β”‚   β”œβ”€β”€ utils.py                  # Helper functions
β”‚   β”œβ”€β”€ visualization.py          # Plotting utilities
β”‚   β”œβ”€β”€ training_settings.ini     # Training configuration
β”‚   β”œβ”€β”€ testing_settings.ini      # Testing configuration
β”‚   β”œβ”€β”€ intersection/             # SUMO simulation files
β”‚   β”‚   β”œβ”€β”€ environment.net.xml   # Road network definition
β”‚   β”‚   β”œβ”€β”€ episode_routes.rou.xml # Generated vehicle routes
β”‚   β”‚   └── sumo_config.sumocfg   # SUMO configuration
β”‚   └── models/                   # Saved trained models
β”‚       └── model_X/
β”‚           β”œβ”€β”€ trained_model.h5  # Trained neural network
β”‚           └── test/             # Test results
β”œβ”€β”€ .venv/                        # Virtual environment
β”œβ”€β”€ Requirements.txt              # Python dependencies
β”œβ”€β”€ LICENSE                       # MIT License
β”œβ”€β”€ README.md                     # This file
└── DOCUMENTATION.md              # Detailed documentation

πŸŽ“ Technical Details

Hyperparameters

Parameter Value Description
Learning Rate 0.001 Adam optimizer learning rate
Discount Factor (Ξ³) 0.75 Future reward discount
Epsilon Decay Linear (1.0 β†’ 0.0) Exploration rate
Memory Size 50,000 Experience replay buffer
Batch Size 100 Training samples per batch
Training Epochs 800 Per episode training iterations

Performance Metrics

  • Cumulative Negative Reward: Total waiting time penalty
  • Average Queue Length: Mean number of waiting vehicles
  • Cumulative Delay: Total seconds all vehicles waited

πŸ“ˆ Results

After 100 training episodes:

  • βœ… Learned optimal traffic light control strategies
  • βœ… Reduced average waiting time by 20-30% vs fixed timing
  • βœ… Adapted to varying traffic patterns
  • βœ… Made decisions in 30-50ms (real-time capable)

View results in TCLS/models/model_X/test/:

  • plot_reward.png - Reward progression
  • plot_queue.png - Queue length over time

πŸ› οΈ Configuration

Training Settings (training_settings.ini)

[simulation]
gui = False              # Enable/disable visualization
total_episodes = 100     # Number of training episodes
max_steps = 5400        # Steps per episode
n_cars_generated = 1000 # Traffic density

[model]
num_layers = 4          # Hidden layers (+ 1 = 5 total)
width_layers = 400      # Neurons per layer
batch_size = 100        # Training batch size
learning_rate = 0.001   # Adam optimizer rate
training_epochs = 800   # Training iterations/episode

[agent]
gamma = 0.75           # Discount factor

Testing Settings (testing_settings.ini)

[simulation]
gui = True             # Enable visualization
model_to_test = 5     # Which model to test

[agent]
episode_seed = 10000  # Random seed for reproducibility

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • SUMO - Simulation of Urban MObility
  • TensorFlow - Machine Learning framework
  • Deep Q-Learning - Based on DeepMind's DQN research

πŸ“š Further Reading

For detailed documentation, see DOCUMENTATION.md

For questions or issues, please open an issue on GitHub.

About

An AI-powered traffic light controller that uses Deep Reinforcement Learning (DQN) with Python, TensorFlow, and SUMO to intelligently optimize traffic flow and minimize vehicle wait times.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages