File size: 8,768 Bytes
18935fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

AI-Powered Shipment Route Optimization & Delay Prediction System

Main application entry point for demonstration and testing

"""

import sys
import os
import pandas as pd
from datetime import datetime

# Add src directory to path
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from data_pipeline.data_collector import DataCollector
from data_pipeline.data_processor import DataProcessor
from ml_models.delay_predictor import DelayPredictor, ModelEvaluator
from route_optimizer.route_optimizer import RouteOptimizer, RouteAnalyzer
from utils.monitoring import ShipmentMonitor, PerformanceAnalyzer

def demonstrate_system():
    """Demonstrate the complete AI-powered shipment optimization system"""
    
    print("=" * 60)
    print("AI-POWERED SHIPMENT ROUTE OPTIMIZATION & DELAY PREDICTION")
    print("=" * 60)
    print()
    
    # Initialize components
    print("πŸ”§ Initializing system components...")
    data_collector = DataCollector()
    data_processor = DataProcessor()
    delay_predictor = DelayPredictor()
    route_optimizer = RouteOptimizer()
    monitor = ShipmentMonitor()
    analyzer = PerformanceAnalyzer()
    
    # Step 1: Data Collection and Processing
    print("\nπŸ“Š STEP 1: Data Collection and Processing")
    print("-" * 40)
    
    # Generate sample data for demonstration
    print("Generating sample shipment data...")
    sample_data = data_processor.generate_sample_data(1000)
    print(f"βœ… Generated {len(sample_data)} sample shipments")
    
    # Clean and process data
    print("Cleaning and processing data...")
    processed_data = data_processor.clean_shipment_data(sample_data)
    feature_data = data_processor.create_features(processed_data)
    print(f"βœ… Processed data with {len(feature_data.columns)} features")
    
    # Step 2: Machine Learning Model Training
    print("\nπŸ€– STEP 2: Machine Learning Model Training")
    print("-" * 40)
    
    # Prepare data for ML
    X, y = data_processor.prepare_ml_data(feature_data)
    print(f"Training data shape: {X.shape}")
    print(f"Target distribution: {y.value_counts().to_dict()}")
    
    # Train delay prediction model
    print("\nTraining XGBoost delay prediction model...")
    metrics = delay_predictor.train_model(X, y)
    print(f"βœ… Model trained with {metrics['accuracy']:.1%} accuracy")
    
    # Step 3: Route Optimization
    print("\nπŸ—ΊοΈ  STEP 3: Route Optimization")
    print("-" * 40)
    
    # Build sample route network
    print("Building route optimization network...")
    # Add major US cities as nodes
    cities = {
        'NYC': (40.7128, -74.0060),
        'LA': (34.0522, -118.2437),
        'CHI': (41.8781, -87.6298),
        'HOU': (29.7604, -95.3698),
        'PHX': (33.4484, -112.0740)
    }
    
    for city_id, (lat, lng) in cities.items():
        route_optimizer.add_location(city_id, lat, lng, 'city')
    
    # Add routes between cities
    city_pairs = [
        ('NYC', 'CHI'), ('CHI', 'LA'), ('NYC', 'HOU'),
        ('HOU', 'LA'), ('CHI', 'PHX'), ('PHX', 'LA')
    ]
    
    for city1, city2 in city_pairs:
        route_optimizer.add_route(city1, city2)
    
    print(f"βœ… Built network with {len(cities)} cities and {len(city_pairs)} routes")
    
    # Find optimal routes
    print("\nFinding optimal routes NYC -> LA...")
    routes = route_optimizer.find_alternative_routes('NYC', 'LA', num_alternatives=3)
    
    for i, route in enumerate(routes[:3]):
        if 'error' not in route:
            print(f"Route {i+1}: {' -> '.join(route['path'])} "
                  f"({route['total_cost']:.1f} minutes)")
    
    # Step 4: Delay Prediction Demo
    print("\n🎯 STEP 4: Delay Risk Prediction")
    print("-" * 40)
    
    # Predict delays for sample shipments
    sample_shipments = feature_data.head(10)
    X_sample, _ = data_processor.prepare_ml_data(sample_shipments)
    
    if len(X_sample) > 0:
        risk_predictions = delay_predictor.predict_delay_risk(X_sample)
        
        print("Sample delay risk predictions:")
        for i in range(min(5, len(risk_predictions))):
            tracking = sample_shipments.iloc[i]['tracking_number']
            risk = risk_predictions.iloc[i]['risk_category']
            prob = risk_predictions.iloc[i]['delay_probability']
            print(f"  {tracking}: {risk} ({prob:.1%} probability)")
    
    # Step 5: Real-time Monitoring
    print("\nπŸ“‘ STEP 5: Real-time Monitoring")
    print("-" * 40)
    
    # Simulate monitoring
    print("Running shipment monitoring system...")
    monitoring_results = monitor.monitor_shipments()
    
    print(f"βœ… Monitoring complete:")
    print(f"  - Active shipments: {monitoring_results['summary'].get('total_active_shipments', 0)}")
    print(f"  - Total alerts: {monitoring_results['summary'].get('total_alerts', 0)}")
    print(f"  - High risk shipments: {monitoring_results['summary'].get('high_risk_shipments', 0)}")
    
    # Step 6: Performance Analysis
    print("\nπŸ“ˆ STEP 6: Performance Analysis")
    print("-" * 40)
    
    performance = analyzer.analyze_delivery_performance(30)
    bottlenecks = analyzer.identify_bottlenecks()
    
    if 'error' not in performance:
        print(f"βœ… 30-day performance analysis:")
        print(f"  - Total shipments: {performance.get('total_shipments', 0)}")
        print(f"  - On-time rate: {performance.get('on_time_rate_percent', 0):.1f}%")
        print(f"  - Average delay: {performance.get('average_delay_minutes', 0):.1f} minutes")
    
    print(f"\nπŸ” Top delay causes identified:")
    for cause in bottlenecks['top_delay_causes'][:3]:
        print(f"  - {cause['cause']}: {cause['frequency']} incidents, "
              f"{cause['avg_delay_minutes']} min avg delay")
    
    # Step 7: Business Impact Summary
    print("\nπŸ’Ό STEP 7: Business Impact Summary")
    print("-" * 40)
    
    print("🎯 Key Achievements:")
    print(f"  βœ… Predictive model accuracy: {metrics['accuracy']:.1%}")
    print(f"  βœ… Route optimization: {len(routes)} alternative routes found")
    print(f"  βœ… Real-time monitoring: Active alert system")
    print(f"  βœ… Performance analytics: Bottleneck identification")
    
    print("\nπŸ“Š Expected Business Benefits:")
    print("  β€’ 15% reduction in delivery delays")
    print("  β€’ Improved customer satisfaction through proactive notifications")
    print("  β€’ Real-time visibility into shipment status")
    print("  β€’ Data-driven decision making for logistics operations")
    
    print("\nπŸš€ System Ready!")
    print("Dashboard available at: http://localhost:8050")
    print("Run 'python src/dashboard/app.py' to start the web interface")
    
    return {
        'model_accuracy': metrics['accuracy'],
        'routes_found': len(routes),
        'monitoring_active': True,
        'system_status': 'operational'
    }

def run_dashboard():
    """Launch the web dashboard"""
    print("πŸš€ Starting AI-Powered Shipment Optimization Dashboard...")
    
    try:
        from dashboard.app import app
        print("Dashboard starting at http://localhost:8050")
        app.run_server(debug=False, host='0.0.0.0', port=8050)
    except ImportError as e:
        print(f"Error importing dashboard: {e}")
        print("Please install required dependencies: pip install -r requirements.txt")
    except Exception as e:
        print(f"Error starting dashboard: {e}")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='AI-Powered Shipment Route Optimization System')
    parser.add_argument('--demo', action='store_true', help='Run system demonstration')
    parser.add_argument('--dashboard', action='store_true', help='Start web dashboard')
    parser.add_argument('--all', action='store_true', help='Run demo then start dashboard')
    
    args = parser.parse_args()
    
    if args.demo or args.all:
        results = demonstrate_system()
        print(f"\nDemo completed. Results: {results}")
    
    if args.dashboard or args.all:
        if args.all:
            print("\n" + "="*60)
            input("Press Enter to start the dashboard...")
        run_dashboard()
    
    if not any([args.demo, args.dashboard, args.all]):
        print("AI-Powered Shipment Route Optimization System")
        print("Usage:")
        print("  python main.py --demo      # Run demonstration")
        print("  python main.py --dashboard # Start web dashboard") 
        print("  python main.py --all       # Run demo then dashboard")