-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_system.py
More file actions
267 lines (209 loc) · 7.39 KB
/
Copy pathrun_system.py
File metadata and controls
267 lines (209 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""
Intelligent Traffic Routing System
Main orchestration script.
"""
import argparse
import sys
import os
# Add parent directory to path
sys.path.insert(0, os.path.dirname(__file__))
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
import pandas as pd
import numpy as np
def setup_system():
"""Generate data and train model."""
print("=" * 60)
print("INTELLIGENT TRAFFIC ROUTING SYSTEM - Setup")
print("=" * 60)
# Step 1: Generate traffic data
print("\n[1/3] Generating traffic data...")
generator = TrafficDataGenerator(n_roads=20, n_samples=2000)
traffic_df = generator.generate_dataset(save_path='data/traffic_data.csv')
print(f" ✓ Generated {len(traffic_df)} traffic records")
# Step 2: Generate road segments
print("\n[2/3] Generating road segment data...")
roads_df = generator.generate_road_segments()
roads_df.to_csv('data/road_segments.csv', index=False)
print(f" ✓ Generated {len(roads_df)} road segments")
# Step 3: Train prediction model
print("\n[3/3] Training traffic prediction model...")
predictor = TrafficPredictor()
metrics = predictor.train(traffic_df)
# Save model
os.makedirs('models/saved', exist_ok=True)
predictor.save_model('models/saved/traffic_predictor.pkl')
print(f" ✓ Model saved to models/saved/traffic_predictor.pkl")
print("\n" + "=" * 60)
print("Setup Complete!")
print("=" * 60)
print(f"\nModel Performance:")
print(f" - MAPE: {metrics['mape']:.2f}%")
print(f" - MAE: {metrics['mae']:.2f}")
print(f" - R² Score: {metrics['r2_score']:.4f}")
return True
def demo_routing():
"""Demonstrate the routing system."""
print("\n" + "=" * 60)
print("ROUTE OPTIMIZATION DEMO")
print("=" * 60)
# Load data
traffic_df = pd.read_csv('data/traffic_data.csv')
roads_df = pd.read_csv('data/road_segments.csv')
# Load model
predictor = TrafficPredictor()
if os.path.exists('models/saved/traffic_predictor.pkl'):
predictor.load_model('models/saved/traffic_predictor.pkl')
else:
print("Model not found. Please run setup first.")
return False
# Demo scenarios
scenarios = [
("Morning Rush Hour (Monday 8:00)", 8, 0),
("Lunch Time (Wednesday 12:00)", 12, 2),
("Evening Rush Hour (Friday 18:00)", 18, 4),
("Late Night (Saturday 23:00)", 23, 5),
]
for scenario_name, hour, day in scenarios:
print(f"\n--- {scenario_name} ---")
# Get traffic predictions
traffic_pred = predictor.get_all_road_predictions(hour, day, n_roads=20)
# Build graph
graph = RoadNetworkGraph()
graph.build_from_road_segments(roads_df, traffic_pred)
# Create optimizer
optimizer = RouteOptimizer(graph)
# Find route (corner to corner)
nodes = graph.get_nodes()
start = nodes[0]
end = nodes[-1]
# Compare algorithms
result = optimizer.compare_routes(start, end)
print(f" Route: Node {start} → Node {end}")
print(f" Dijkstra: {result['dijkstra']['details']['estimated_time']:.1f} min, "
f"{result['dijkstra']['details']['total_distance']:.1f} km")
print(f" A*: {result['astar']['details']['estimated_time']:.1f} min, "
f"{result['astar']['details']['total_distance']:.1f} km")
print(f" Same path: {result['comparison']['same_path']}")
return True
def run_dashboard():
"""Launch the Streamlit dashboard."""
print("\n" + "=" * 60)
print("Launching Streamlit Dashboard...")
print("=" * 60)
print("\nThe dashboard will open in your browser.")
print("Press Ctrl+C to stop the server.\n")
import subprocess
subprocess.run(["streamlit", "run", "app/dashboard.py"])
def run_tests():
"""Run all tests."""
print("\n" + "=" * 60)
print("RUNNING TESTS")
print("=" * 60)
import unittest
# Discover and run tests
loader = unittest.TestLoader()
suite = unittest.TestSuite()
# Load test modules
from tests import test_traffic_prediction, test_route_optimization
suite.addTests(loader.loadTestsFromModule(test_traffic_prediction))
suite.addTests(loader.loadTestsFromModule(test_route_optimization))
# Run tests
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
# Summary
print("\n" + "=" * 60)
print("TEST SUMMARY")
print("=" * 60)
print(f"Tests run: {result.testsRun}")
print(f"Failures: {len(result.failures)}")
print(f"Errors: {len(result.errors)}")
print(f"Skipped: {len(result.skipped)}")
return len(result.failures) == 0 and len(result.errors) == 0
def evaluate_model():
"""Evaluate the ML model performance."""
print("\n" + "=" * 60)
print("MODEL EVALUATION")
print("=" * 60)
# Load data
traffic_df = pd.read_csv('data/traffic_data.csv')
# Train and evaluate
predictor = TrafficPredictor()
metrics = predictor.train(traffic_df)
print(f"\nPerformance Metrics:")
print(f" MAPE (Mean Absolute Percentage Error): {metrics['mape']:.2f}%")
print(f" MAE (Mean Absolute Error): {metrics['mae']:.2f} vehicles")
print(f" R² Score: {metrics['r2_score']:.4f}")
# Target evaluation
print(f"\nTarget: MAPE ~20%")
if 15 <= metrics['mape'] <= 25:
print(" ✓ Target achieved!")
else:
print(f" Current MAPE is {metrics['mape']:.1f}%")
return metrics
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Intelligent Traffic Routing System"
)
parser.add_argument(
'--setup',
action='store_true',
help='Generate data and train model'
)
parser.add_argument(
'--demo',
action='store_true',
help='Run routing demo'
)
parser.add_argument(
'--dashboard',
action='store_true',
help='Launch Streamlit dashboard'
)
parser.add_argument(
'--test',
action='store_true',
help='Run all tests'
)
parser.add_argument(
'--evaluate',
action='store_true',
help='Evaluate model performance'
)
parser.add_argument(
'--all',
action='store_true',
help='Setup, demo, and test'
)
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
return
if args.all:
args.setup = True
args.demo = True
args.test = True
success = True
if args.setup:
success = setup_system() and success
if args.demo:
success = demo_routing() and success
if args.evaluate:
evaluate_model()
if args.test:
success = run_tests() and success
if args.dashboard:
run_dashboard()
if not args.dashboard:
print("\n" + "=" * 60)
if success:
print("All operations completed successfully!")
else:
print("Some operations failed. Check output above.")
print("=" * 60)
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())