Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🚦 Intelligent Traffic Routing System

A beginner-friendly traffic prediction and route optimization system built with Python. This project demonstrates machine learning for traffic prediction and graph algorithms (Dijkstra & A*) for route optimization.

πŸ“‹ Overview

This system includes three main modules:

  1. Traffic Prediction Module - ML model (Random Forest) predicts traffic volume
  2. Route Optimization Module - Dijkstra & A* algorithms find optimal routes
  3. Dashboard Module - Interactive Streamlit UI for visualization

πŸ—οΈ Project Structure

traffic-routing-system/
β”œβ”€β”€ data/                      # Data generation and storage
β”‚   β”œβ”€β”€ generate_traffic_data.py
β”‚   β”œβ”€β”€ traffic_data.csv       # Generated traffic records
β”‚   └── road_segments.csv      # Road segment metadata
β”œβ”€β”€ models/                    # ML models
β”‚   β”œβ”€β”€ traffic_predictor.py   # Random Forest predictor
β”‚   └── saved/                 # Saved model files
β”œβ”€β”€ algorithms/                # Route optimization algorithms
β”‚   β”œβ”€β”€ graph_builder.py       # Road network graph construction
β”‚   └── route_optimizer.py     # Dijkstra & A* implementations
β”œβ”€β”€ app/                       # Streamlit dashboard
β”‚   └── dashboard.py
β”œβ”€β”€ tests/                     # Unit tests
β”‚   β”œβ”€β”€ test_traffic_prediction.py
β”‚   └── test_route_optimization.py
β”œβ”€β”€ run_system.py              # Main orchestration script
β”œβ”€β”€ requirements.txt           # Dependencies
└── README.md                  # This file

πŸš€ Quick Start

1. Install Dependencies

pip install -r requirements.txt

2. Setup the System

Generate data and train the model:

python run_system.py --setup

3. Run the Dashboard

Launch the interactive Streamlit dashboard:

python run_system.py --dashboard

Or directly:

streamlit run app/dashboard.py

πŸ“Š Features

Traffic Prediction

  • Dataset: 20 road segments with time-based features
  • Model: Random Forest Regressor
  • Features: road_id, time_of_day, day_of_week
  • Target: traffic_volume (vehicles/hour)
  • Target MAPE: ~20%

Route Optimization

  • Graph Representation: Nodes = intersections, Edges = roads
  • Edge Weights: Based on predicted traffic and distance
  • Algorithms:
    • Dijkstra's Algorithm (guaranteed shortest path)
    • A* Algorithm (heuristic-guided, more efficient)
  • Comparison: Shows time reduction between algorithms

Dashboard

  • Interactive route selection
  • Real-time traffic visualization
  • Route comparison between Dijkstra and A*
  • Network graph visualization

πŸ› οΈ Usage Examples

Run Complete Setup & Demo

python run_system.py --all

Run Individual Components

# Setup only
python run_system.py --setup

# Routing demo
python run_system.py --demo

# Run tests
python run_system.py --test

# Evaluate model
python run_system.py --evaluate

# Launch dashboard
python run_system.py --dashboard

Use Modules Programmatically

from data.generate_traffic_data import TrafficDataGenerator
from models.traffic_predictor import TrafficPredictor
from algorithms.graph_builder import RoadNetworkGraph
from algorithms.route_optimizer import RouteOptimizer

# Generate data
generator = TrafficDataGenerator(n_roads=20, n_samples=2000)
traffic_df = generator.generate_dataset()

# Train model
predictor = TrafficPredictor()
predictor.train(traffic_df)

# Get prediction
traffic = predictor.predict(road_id=1, time_of_day=8, day_of_week=0)
print(f"Predicted traffic: {traffic:.0f} vehicles/hour")

# Build graph
traffic_predictions = predictor.get_all_road_predictions(8, 0, 20)
graph = RoadNetworkGraph()
graph.build_from_road_segments(roads_df, traffic_predictions)

# Find optimal route
optimizer = RouteOptimizer(graph)
path, cost = optimizer.astar(start=0, end=24)
print(f"Optimal path: {path}")
print(f"Travel time: {cost:.1f} minutes")

πŸ§ͺ Testing

Run all tests:

python run_system.py --test

Or directly:

python -m pytest tests/

πŸ“ˆ Evaluation Metrics

The system targets the following performance metrics:

Metric Target Description
MAPE ~20% Mean Absolute Percentage Error
MAE Low Mean Absolute Error (vehicles)
RΒ² Score >0.7 Coefficient of determination

πŸ› οΈ Tech Stack

  • Python 3.8+
  • Pandas - Data manipulation
  • NumPy - Numerical operations
  • Scikit-learn - Machine Learning
  • NetworkX - Graph operations
  • Streamlit - Dashboard UI
  • Matplotlib - Visualization

πŸ“š Documentation

Module 1: Traffic Prediction

The traffic prediction module uses a Random Forest regressor to predict traffic volume based on:

  • Road ID (which road segment)
  • Time of day (hour 0-23)
  • Day of week (0=Monday to 6=Sunday)

Traffic patterns are generated with realistic rush hour peaks and weekend variations.

Module 2: Route Optimization

The route optimization module implements:

Dijkstra's Algorithm:

  • Explores all possible paths systematically
  • Guaranteed to find shortest path
  • Time complexity: O((V + E) log V)

A Algorithm:*

  • Uses heuristic (Euclidean distance) to guide search
  • More efficient than Dijkstra
  • Same optimal result when heuristic is admissible

Edge weights combine distance and traffic congestion:

weight = (distance / 40) * 60 * (1 + (traffic / 500)Β²)

Module 3: Dashboard

The Streamlit dashboard provides:

  • Sidebar controls for time, day, source, and destination
  • Real-time traffic predictions for all roads
  • Interactive route visualization
  • Algorithm comparison metrics

πŸ”§ Customization

Adjusting the Number of Roads

Modify n_roads in run_system.py:

generator = TrafficDataGenerator(n_roads=30, n_samples=2000)

Changing the ML Model

Edit models/traffic_predictor.py:

from sklearn.ensemble import GradientBoostingRegressor

self.model = GradientBoostingRegressor(n_estimators=100)

Adding Custom Heuristics for A*

Edit algorithms/route_optimizer.py:

def _heuristic(self, node: int, goal: int) -> float:
    # Add custom logic here
    return custom_distance_estimate

🀝 Contributing

This is a learning project. Feel free to:

  • Add more sophisticated ML models
  • Implement additional algorithms (Bellman-Ford, Floyd-Warshall)
  • Enhance the dashboard with real-time data
  • Add map integration (OpenStreetMap, Google Maps)

πŸ“ License

This project is for educational purposes.

πŸ™ Acknowledgments

  • Dijkstra's algorithm (Edsger W. Dijkstra, 1956)
  • A* algorithm (Peter Hart, Nils Nilsson, Bertram Raphael, 1968)
  • Scikit-learn team for the excellent ML library
  • Streamlit team for the amazing dashboard framework

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages