Fleet Route Optimizer [CVRPTW]
Capacitated Vehicle Routing Problem with Time Windows - An advanced optimization system for logistics and delivery route planning
β οΈ Note: This is a production-ready project with clean architecture, demonstrating professional vehicle routing optimization techniques.
π Overview
Fleet Route Optimizer is a comprehensive web-based application for solving complex vehicle routing problems with constraints including:
- Vehicle Capacity: Each vehicle has a maximum load capacity
- Time Windows: Deliveries must be made within specific time slots
- Fleet Optimization: Minimize number of vehicles while maximizing utilization
- Real Distance Matrix: Uses actual travel distances and times (morning/afternoon/evening traffic)
- **Dyβ¦
Fleet Route Optimizer [CVRPTW]
Capacitated Vehicle Routing Problem with Time Windows - An advanced optimization system for logistics and delivery route planning
β οΈ Note: This is a production-ready project with clean architecture, demonstrating professional vehicle routing optimization techniques.
π Overview
Fleet Route Optimizer is a comprehensive web-based application for solving complex vehicle routing problems with constraints including:
- Vehicle Capacity: Each vehicle has a maximum load capacity
- Time Windows: Deliveries must be made within specific time slots
- Fleet Optimization: Minimize number of vehicles while maximizing utilization
- Real Distance Matrix: Uses actual travel distances and times (morning/afternoon/evening traffic)
- Dynamic Service Time: Calculated based on delivery size (10 min + 2 min per unit)
β¨ Key Features
- π― Two Solver Engines: OR-Tools (open-source) and Gurobi (commercial)
- π Interactive Web UI: Real-time visualization and route management
- πΊοΈ Map Integration: Visual representation of routes on interactive maps
- πΎ Distance Cache: Persistent storage to avoid redundant calculations
- π Real Distance Matrix: OSRM routing service for accurate travel times
- π Time-Based Routing: Different travel times for morning/afternoon/evening traffic
- π Detailed Analytics: Comprehensive metrics and statistics
- π³ Docker Support: Easy deployment with Docker Compose
- ποΈ Clean Architecture: Modular, maintainable, and scalable codebase
- π Server-Sent Events: Real-time log streaming during optimization
- π¨ Pydantic Models: Type-safe data validation and serialization
ποΈ Project Structure
solver/
βββ src/ # Source code (refactored architecture)
β βββ api/ # API Layer - HTTP endpoints
β β βββ __init__.py
β β βββ routes.py # FastAPI routes (health, solve, solve-stream, download)
β β
β βββ core/ # Core Layer - Business logic
β β βββ __init__.py
β β βββ solvers/ # Solver implementations
β β βββ __init__.py
β β βββ base.py # Abstract BaseSolver + SolverType enum
β β βββ factory.py # SolverFactory (Factory Pattern)
β β βββ ortools_solver.py # OR-Tools wrapper
β β βββ ortools_impl.py # OR-Tools implementation
β β βββ gurobi_solver.py # Gurobi wrapper
β β βββ gurobi_impl.py # Gurobi implementation
β β
β βββ models/ # Data Models Layer
β β βββ __init__.py
β β βββ domain.py # Domain models (15+ Pydantic models)
β β β # Location, Customer, Vehicle, Route, etc.
β β βββ api.py # API request/response models
β β
β βββ services/ # Service Layer - Business logic orchestration
β β βββ __init__.py
β β βββ distance_cache.py # Distance/time caching with OSRM
β β βββ problem_builder.py # Problem construction from JSON
β β βββ solver_service.py # Main solver orchestration
β β
β βββ utils/ # Utilities Layer
β β βββ __init__.py
β β βββ distance_calculator.py # Haversine & Euclidean distance
β β βββ time_formatter.py # Time formatting utilities
β β
β βββ config/ # Configuration Layer
β β βββ __init__.py
β β βββ settings.py # Pydantic BaseSettings (env-based config)
β β βββ logging.py # Centralized logging configuration
β β
β βββ app.py # FastAPI application entry point
β βββ __init__.py
β
βββ webui/ # React Frontend
β βββ src/
β β βββ components/
β β βββ pages/
β β βββ App.js
β βββ public/
β βββ package.json
β
βββ inputs/ # Example input JSON files
β βββ CVRPTW_SMALL.json
β βββ CVRPTW_MEDIUM.json
β βββ CVRPTW_LARGE.json
β
βββ results/ # Solution output files
βββ docker/ # Docker configuration
β βββ docker-compose.yml
β βββ README.md
β
βββ requirements.txt # Python dependencies
βββ .env.example # Environment configuration template
βββ Dockerfile
βββ README.md
π― Architecture Highlights
The project follows Clean Architecture principles with clear separation of concerns:
- API Layer (
src/api/): HTTP endpoints, request/response handling - Core Layer (
src/core/): Solver implementations, business rules - Service Layer (
src/services/): Orchestration, workflow management - Models Layer (
src/models/): Type-safe data structures with Pydantic - Utils Layer (
src/utils/): Reusable helper functions - Config Layer (
src/config/): Environment-based configuration
Design Patterns Used:
- β Factory Pattern (SolverFactory)
- β Service Layer Pattern
- β Repository Pattern (DistanceCache)
- β Dependency Injection
- β Abstract Base Classes
π Quick Start
Prerequisites
- Python 3.10+
- Node.js 18+ (for Web UI)
- (Optional) Gurobi license for Gurobi solver
Installation
- Clone the repository:
git clone <repository-url>
cd solver
- Create virtual environment:
python -m venv venv
# Windows
.\venv\Scripts\activate
# Linux/Mac
source venv/bin/activate
- Install dependencies:
pip install -r requirements.txt
- Configure environment (optional):
cp .env.example .env
# Edit .env with your settings (API_TITLE, PORT, DEFAULT_SOLVER, etc.)
- Run the API server:
# Recommended: New modular architecture
python -m src.app
# Alternative: Using uvicorn directly
uvicorn src.app:app --port 8000 --reload
# Note: Old server.py has been deprecated and removed
- Run the Web UI (separate terminal):
cd webui
npm install
npm start
- Access the application:
- Web UI: http://localhost:3000
- API Docs (Swagger): http://localhost:8000/docs
- API Docs (ReDoc): http://localhost:8000/redoc
π API Endpoints
1. Health Check
GET /health
Response:
{
"status": "ready", # or "busy" if solver is running
"message": null
}
2. Solve Problem (Standard)
POST /solve?time_limit=60&solver=ortools&vehicle_penalty_weight=100000&distance_weight=1.0
Content-Type: application/json
{
"date": "2025-01-15",
"depot": {
"location": [45.464, 9.190]
},
"vehicles": [
{
"id": "V1",
"capacity_units": 33,
"time_window": {
"start_min": 240,
"end_min": 1260
}
}
],
"customers": [
{
"id": "C1",
"name": "Customer 1",
"location": [45.470, 9.200],
"demand_units": 10,
"time_window": {
"start_min": 480,
"end_min": 720
}
}
]
}
Response: Complete solution with routes, metrics, and timeline
3. Solve with Real-time Streaming (SSE)
POST /solve-stream?time_limit=60&solver=ortools
Content-Type: application/json
# Same payload as /solve
Response: Server-Sent Events stream with logs and final result
Events:
- {"type": "log", "message": "Starting solver..."}
- {"type": "log", "message": "Building model..."}
- {"type": "result", "data": {...}}
4. Download Example Files
GET /download-examples
Response: ZIP file with CVRPTW_SMALL.json, CVRPTW_MEDIUM.json, CVRPTW_LARGE.json
Query Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
time_limit | int | 60 | Time limit in seconds (1-3600) |
solver | str | βortoolsβ | Solver type: βortoolsβ or βgurobiβ |
vehicle_penalty_weight | float | Auto | Weight for minimizing vehicles (OR-Tools: 100000, Gurobi: 1000) |
distance_weight | float | 1.0 | Weight for distance minimization |
mip_gap | float | 0.01 | MIP optimality gap for Gurobi (1% default) |
βοΈ Configuration
Configuration is managed through environment variables (.env file) or src/config/settings.py:
| Variable | Default | Description |
|---|---|---|
APP_NAME | βFleet Route Optimizer APIβ | Application name |
API_HOST | 127.0.0.1 | API server host |
API_PORT | 8000 | API server port |
DEBUG | false | Debug mode |
DEFAULT_SOLVER | ortools | Default solver (ortools/gurobi) |
ORTOOLS_VEHICLE_PENALTY | 100000.0 | OR-Tools vehicle penalty weight |
GUROBI_VEHICLE_PENALTY | 1000.0 | Gurobi vehicle penalty weight |
DISTANCE_CACHE_DB | distance_cache.db | SQLite database path |
OSRM_BASE_URL | http://router.project-osrm.org | OSRM API base URL |
LOG_LEVEL | INFO | Logging level |
π§ Development
Adding a New Solver
- Create implementation in
src/core/solvers/newsolver_impl.py - Create wrapper in
src/core/solvers/newsolver_solver.pyextendingBaseSolver - Add solver type to
SolverTypeenum inbase.py - Register in
SolverFactoryinfactory.py
Project Structure Best Practices
The refactored structure follows Python best practices:
- Modular Design: Each module has a single responsibility
- Type Hints: Comprehensive type annotations throughout
- Pydantic Models: Strong data validation and serialization
- Dependency Injection: Services are injected, not hard-coded
- Configuration Management: Centralized, environment-aware settings
- Logging: Structured logging with configurable levels
- Error Handling: Comprehensive error handling with proper HTTP status codes
Adding a New Solver
- Create solver class in
src/core/solvers/:
from .base import BaseSolver
class MySolver(BaseSolver):
def solve(self, **kwargs):
# Implementation
pass
- Register in factory (
src/core/solvers/factory.py):
elif solver_type_lower == "mysolver":
return MySolver(problem)
π¦ Dependencies
Core Dependencies
- FastAPI (0.121.0+): Modern web framework
- Pydantic (2.0+): Data validation and settings
- pydantic-settings (2.0+): Environment-based configuration
- OR-Tools (9.7+): Constraint programming solver
- Gurobi (11.0+): Commercial optimization solver (optional)
- python-dotenv (1.0+): Environment variable management
- uvicorn: ASGI server
- pandas: Data manipulation
- requests: HTTP client for OSRM
Development Dependencies
All dependencies are listed in requirements.txt. Install with:
pip install -r requirements.txt
π³ Docker Deployment
# Build and run with Docker Compose
cd docker
docker-compose up --build
# Access services
# API: http://localhost:8000
# Web UI: http://localhost:3000
# Note: Update docker-compose.yml to use src.app:app instead of src.server:app
π Performance Considerations
- Distance Cache: Uses SQLite to cache OSRM API calls, drastically reducing API requests
- Traffic Patterns: Adjusts travel times based on delivery time windows (morning/afternoon/evening)
- Service Time: Dynamic calculation based on delivery size (10 min base + 2 min per unit)
- Solver Selection: OR-Tools for speed, Gurobi for optimality
- Modular Architecture: Improved maintainability and testability
- Type Safety: Pydantic models ensure data integrity
π€ Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Follow the existing code structure and style
- Add type hints and docstrings
- Update tests if applicable
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Submit a pull request
Code Style
- Follow PEP 8 guidelines
- Use type hints for all functions
- Add comprehensive docstrings
- Keep functions small and focused
- Use Pydantic models for data validation
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
- Google OR-Tools: Powerful open-source optimization library
- Gurobi: Industry-leading mathematical optimization solver
- OSRM: Open Source Routing Machine for real-world routing data
- FastAPI: Modern, fast web framework for building APIs
- React: Frontend library for building user interfaces
- Pydantic: Data validation using Python type annotations
π Support
For questions, issues, or suggestions:
- π Open an issue on GitHub
π Roadmap
- Complete unit test coverage
- Add integration tests
- Add more solver engines (e.g., LocalSolver, HGS-CVRP)
- WebSocket support for real-time updates
- Enhanced map visualization
- Multi-depot support
- Vehicle type constraints
Fleet Route Optimizer [CVRPTW]
Made with β€οΈ for logistics optimization
π Clean Architecture β’ ποΈ Modular Design β’ β‘ High Performance