-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_complete_integration.py
More file actions
2039 lines (1684 loc) · 81.9 KB
/
main_complete_integration.py
File metadata and controls
2039 lines (1684 loc) · 81.9 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Manhattan Power Grid - COMPLETE World-Class Integration
All features from main_world_class.py PLUS advanced SUMO vehicle simulation
ORGANIZED ROUTE STRUCTURE:
1. Core Routes (Main page, debug)
2. Network & Status Routes
3. SUMO & Vehicle Management Routes
4. Power Grid Control Routes
5. V2G (Vehicle-to-Grid) Routes
6. ML Analytics Routes
7. AI & Chatbot Routes
"""
from flask import Flask, render_template_string, jsonify, request
from flask_cors import CORS
import json
import threading
import time
from datetime import datetime
import traceback
import random
import os
try:
from dotenv import load_dotenv
except Exception:
def load_dotenv(*args, **kwargs):
return False
# Import our systems
from core.power_system import ManhattanPowerGrid
from integrated_backend import ManhattanIntegratedSystem
from core.sumo_manager import ManhattanSUMOManager, SimulationScenario
from ml_engine import MLPowerGridEngine
from v2g_manager import V2GManager
from ai_chatbot import ManhattanAIChatbot
from ultra_intelligent_chatbot import initialize_ultra_intelligent_chatbot
try:
from openai import OpenAI
except Exception:
OpenAI = None
load_dotenv()
app = Flask(__name__)
CORS(app)
# Initialize systems
print("=" * 60)
print("MANHATTAN POWER GRID - COMPLETE INTEGRATION")
print("Power + Traffic + Vehicles - World Class System")
print("=" * 60)
# Initialize power grid
print("Initializing PyPSA power grid...")
power_grid = ManhattanPowerGrid()
# ADD THIS: Initialize loads with realistic values
print("Setting initial load values...")
# Around line 45 - REDUCE all loads to prevent overload
initial_loads = {
"Commercial_Hell's_Kitchen": 24, # was 120
"Commercial_Times_Square": 56, # was 280
"Commercial_Penn_Station": 44, # was 220
"Commercial_Grand_Central": 50, # was 250
"Commercial_Murray_Hill": 18, # was 90
"Commercial_Turtle_Bay": 22, # was 110
"Commercial_Chelsea": 17, # was 85
"Commercial_Midtown_East": 34, # was 170
"Industrial_Hell's_Kitchen": 9, # was 45
"Industrial_Times_Square": 6, # was 30
"Industrial_Penn_Station": 14, # was 70
"Industrial_Grand_Central": 10, # was 50
"Industrial_Murray_Hill": 8, # was 40
"Industrial_Turtle_Bay": 10, # was 50
"Industrial_Chelsea": 14, # was 70
"Industrial_Midtown_East": 10 # was 50
}
for load_name, load_mw in initial_loads.items():
# Fix the name format to match PyPSA (underscores instead of apostrophes)
fixed_load_name = load_name.replace("'", "")
if fixed_load_name in power_grid.network.loads.index:
power_grid.network.loads.at[fixed_load_name, 'p_set'] = load_mw
print(f" Set {fixed_load_name}: {load_mw} MW")
elif load_name in power_grid.network.loads.index:
power_grid.network.loads.at[load_name, 'p_set'] = load_mw
print(f" Set {load_name}: {load_mw} MW")
print(f"Total initial load: {sum(initial_loads.values())} MW")
# Initialize integrated system
print("Loading integrated distribution network...")
integrated_system = ManhattanIntegratedSystem(power_grid)
# Initialize SUMO manager
print("Initializing SUMO vehicle manager...")
sumo_manager = ManhattanSUMOManager(integrated_system)
# ADD THESE LINES HERE:
print("Initializing V2G energy trading system...")
v2g_manager = V2GManager(integrated_system, sumo_manager)
sumo_manager.set_v2g_manager(v2g_manager)
# Initialize Enhanced ML Engine with V2G integration
ml_engine = MLPowerGridEngine(integrated_system=integrated_system, power_grid=power_grid, v2g_manager=v2g_manager)
# Initialize World-Class AI Chatbot
ai_chatbot = ManhattanAIChatbot(integrated_system=integrated_system, ml_engine=ml_engine, v2g_manager=v2g_manager)
# Initialize ULTRA-INTELLIGENT CHATBOT with typo correction and suggestions
try:
from enhanced_v2g_manager import initialize_enhanced_v2g
enhanced_v2g_manager = initialize_enhanced_v2g(integrated_system)
ultra_chatbot = initialize_ultra_intelligent_chatbot(integrated_system, ml_engine, enhanced_v2g_manager, app)
print("ULTRA-INTELLIGENT CHATBOT WITH TYPO CORRECTION INTEGRATED")
except Exception as e:
print(f"Ultra-Intelligent Chatbot not available: {e}")
ultra_chatbot = None
# Initialize ADVANCED AI SYSTEM CONTROLLER with OpenAI + LangChain
try:
from advanced_ai_controller import initialize_advanced_ai
world_class_ai = initialize_advanced_ai(integrated_system, ml_engine, v2g_manager, app)
print("ADVANCED AI CONTROLLER WITH OPENAI + LANGCHAIN INTEGRATED")
except ImportError as e:
print(f"Advanced AI Controller not available: {e}")
world_class_ai = None
# Initialize OpenAI client (optional if key provided)
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
openai_client = OpenAI(api_key=OPENAI_API_KEY) if (OPENAI_API_KEY and OpenAI) else None
# Initialize REALISTIC LOAD MODEL and SCENARIO CONTROLLER
print("=" * 60)
print("INITIALIZING WORLD-CLASS REALISTIC LOAD MODEL")
print("=" * 60)
try:
from realistic_load_model import RealisticLoadModel
from scenario_controller import ScenarioController
from scenario_integration import integrate_scenario_controller
print("Initializing realistic load model with building types...")
load_model = RealisticLoadModel(integrated_system)
print("Initializing scenario controller...")
scenario_controller = ScenarioController(
integrated_system=integrated_system,
load_model=load_model,
power_grid=power_grid,
sumo_manager=sumo_manager
)
# Start automatic monitoring
scenario_controller.start_auto_monitoring()
# Add API endpoints
integrate_scenario_controller(app, scenario_controller, load_model)
print("=" * 60)
print("✓ REALISTIC LOAD MODEL ACTIVE")
print("✓ SCENARIO CONTROLLER ACTIVE")
print("✓ AUTOMATIC FAILURE DETECTION ENABLED")
print("=" * 60)
except Exception as e:
print(f"ERROR: Could not initialize realistic load model: {e}")
load_model = None
scenario_controller = None
# Optional: cache of SUMO edge shapes (lon/lat) for road-locked rendering
EDGE_SHAPES: dict = {}
def preload_edge_shapes(max_edges: int | None = None) -> int:
"""Preload and cache SUMO edge shapes into EDGE_SHAPES using traci.
Returns number of edges cached. Requires SUMO to be running.
"""
try:
import traci
except Exception:
return 0
if not (system_state.get('sumo_running') and getattr(sumo_manager, 'running', False)):
return 0
count = 0
try:
edge_ids = [e for e in traci.edge.getIDList() if not e.startswith(':')]
if max_edges is not None:
edge_ids = edge_ids[:max_edges]
for edge_id in edge_ids:
if edge_id in EDGE_SHAPES:
continue
try:
shape_xy = traci.edge.getShape(edge_id)
edge_shape = []
for sx, sy in shape_xy:
slon, slat = traci.simulation.convertGeo(sx, sy)
edge_shape.append([slon, slat])
EDGE_SHAPES[edge_id] = {'xy': shape_xy, 'lonlat': edge_shape}
count += 1
except Exception:
# Skip edges that fail shape retrieval
continue
except Exception:
return count
return count
# System state
system_state = {
'running': True,
'sumo_running': False,
'simulation_speed': 1.0,
'current_time': 0,
'scenario': SimulationScenario.MIDDAY
}
# EV Configuration
current_ev_config = {
'ev_percentage': 70,
'battery_min_soc': 20,
'battery_max_soc': 90,
'updated_at': datetime.now().isoformat()
}
def simulation_loop():
"""Main simulation loop - REALISTIC TIMING (Real-world synchronized)"""
global system_state
# REALISTIC TIMING CONFIGURATION
# All intervals in SUMO steps (1 SUMO step = 0.1 simulation seconds)
SUMO_STEP_TIME = 0.1 # seconds - Industry standard for traffic simulation
# Realistic update intervals (in seconds)
TRAFFIC_LIGHT_CYCLE = 60 # 60 seconds - Realistic traffic light cycle
POWER_GRID_UPDATE = 5 # 5 seconds - Realistic SCADA/state estimation
EV_LOAD_UPDATE = 5 # 5 seconds - Realistic smart meter updates
V2G_UPDATE = 60 # 60 seconds - Realistic V2G state changes
# Convert to SUMO steps (multiply by 10 because 1 SUMO step = 0.1s)
TRAFFIC_LIGHT_STEPS = int(TRAFFIC_LIGHT_CYCLE / SUMO_STEP_TIME) # 600 steps
POWER_GRID_STEPS = int(POWER_GRID_UPDATE / SUMO_STEP_TIME) # 50 steps
EV_LOAD_STEPS = int(EV_LOAD_UPDATE / SUMO_STEP_TIME) # 50 steps
V2G_STEPS = int(V2G_UPDATE / SUMO_STEP_TIME) # 600 steps
# Performance optimization: Use high-resolution timer
import time as time_module
next_step_time = time_module.perf_counter()
step_duration = 0.1 # Match SUMO step time (100ms)
# Cache for reducing update frequency
last_ev_update = 0
last_v2g_update = 0
last_power_flow = 0
# Performance monitoring
perf_stats = {'sumo_step': [], 'ev_update': [], 'power_flow': [], 'total_step': []}
last_perf_report = 0
print("\n" + "="*70)
print("REALISTIC TIMING MODE ENABLED")
print("="*70)
print(f"SUMO Traffic Step: {SUMO_STEP_TIME}s (0.1s - Industry standard)")
print(f"Traffic Light Cycle: {TRAFFIC_LIGHT_CYCLE}s (Realistic timing)")
print(f"Power Grid Update: {POWER_GRID_UPDATE}s (SCADA rate)")
print(f"EV Load Update: {EV_LOAD_UPDATE}s (Smart meter rate)")
print(f"V2G State Update: {V2G_UPDATE}s (V2G session rate)")
print("="*70 + "\n")
while system_state['running']:
try:
step_start = time_module.perf_counter()
current_time = step_start
# Skip if we're ahead of schedule (non-blocking timing)
if current_time < next_step_time:
time_module.sleep(0.001) # Short sleep to reduce CPU usage
continue
# REALISTIC TIMING: Traffic lights change every 60 seconds
if system_state['current_time'] % TRAFFIC_LIGHT_STEPS == 0:
integrated_system.update_traffic_light_phases()
if system_state['current_time'] > 0: # Don't print at startup
print(f"[TRAFFIC] Light phase change at {system_state['current_time']*0.1:.1f}s")
# Run SUMO step if active
if system_state['sumo_running'] and sumo_manager.running:
sumo_start = time_module.perf_counter()
# SUMO step - advances traffic simulation by 0.1 seconds
sumo_manager.step()
sumo_time = (time_module.perf_counter() - sumo_start) * 1000
perf_stats['sumo_step'].append(sumo_time)
# REALISTIC: V2G updates every 60 seconds (vehicle-to-grid state changes)
if system_state['current_time'] - last_v2g_update >= V2G_STEPS:
v2g_manager.update_v2g_sessions()
last_v2g_update = system_state['current_time']
# REALISTIC: EV load updates every 5 seconds (smart meter telemetry)
if system_state['current_time'] - last_ev_update >= EV_LOAD_STEPS:
ev_start = time_module.perf_counter()
update_ev_power_loads()
ev_time = (time_module.perf_counter() - ev_start) * 1000
perf_stats['ev_update'].append(ev_time)
last_ev_update = system_state['current_time']
# REALISTIC: Power flow every 5 seconds (SCADA state estimation)
if system_state['current_time'] - last_power_flow >= POWER_GRID_STEPS:
pf_start = time_module.perf_counter()
try:
power_grid.run_power_flow("dc")
pf_time = (time_module.perf_counter() - pf_start) * 1000
perf_stats['power_flow'].append(pf_time)
if pf_time > 100: # Warn if power flow takes >100ms
print(f"[WARNING] Power flow took {pf_time:.1f}ms")
except Exception as e:
print(f"[ERROR] Power flow failed: {e}")
last_power_flow = system_state['current_time']
system_state['current_time'] += 1
# Track total step time
total_time = (time_module.perf_counter() - step_start) * 1000
perf_stats['total_step'].append(total_time)
# Performance report every 30 seconds (300 SUMO steps)
if system_state['current_time'] - last_perf_report >= 300:
sim_time = system_state['current_time'] * SUMO_STEP_TIME
if perf_stats['sumo_step']:
avg_sumo = sum(perf_stats['sumo_step'][-100:]) / min(100, len(perf_stats['sumo_step']))
avg_total = sum(perf_stats['total_step'][-100:]) / min(100, len(perf_stats['total_step']))
avg_pf = sum(perf_stats['power_flow'][-10:]) / max(1, min(10, len(perf_stats['power_flow']))) if perf_stats['power_flow'] else 0
print(f"\n[PERF] Simulation time: {sim_time:.1f}s")
print(f" Avg SUMO step: {avg_sumo:.1f}ms, Total step: {avg_total:.1f}ms")
print(f" Power flow: {avg_pf:.1f}ms, Real-time ratio: {avg_total/100:.2f}x")
if sumo_manager.running:
stats = sumo_manager.get_statistics()
print(f" Vehicles: {stats.get('total_vehicles', 0)}, EVs: {stats.get('ev_vehicles', 0)}, Charging: {stats.get('vehicles_charging', 0)}")
last_perf_report = system_state['current_time']
# Calculate next step time (compensates for processing time)
next_step_time += step_duration / system_state['simulation_speed']
# If we're falling behind, reset timer
if current_time > next_step_time + 0.5:
next_step_time = current_time
print(f"[WARNING] Simulation running slow! Step took {total_time:.1f}ms (target: {step_duration*1000:.1f}ms)")
except Exception as e:
print(f"Simulation error: {e}")
traceback.print_exc()
time.sleep(1)
next_step_time = time_module.perf_counter()
def update_ev_power_loads():
"""Update power grid loads based on EV charging - OPTIMIZED FOR 1000+ VEHICLES"""
global power_grid
global previous_ev_load_mw
# Initialize previous load tracking
if 'previous_ev_load_mw' not in globals():
previous_ev_load_mw = 0
# Quick validation checks
if not power_grid or not sumo_manager.running:
return
# OPTIMIZATION: Get charging data directly from station manager (O(stations) instead of O(vehicles))
charging_counts = {}
if hasattr(sumo_manager, 'station_manager') and sumo_manager.station_manager:
# Direct access to station charging data - much faster!
for station_id, station in sumo_manager.station_manager.stations.items():
num_charging = len(station['vehicles_charging'])
if num_charging > 0:
charging_counts[station_id] = num_charging
else:
# Fallback: Count from vehicle states
for vehicle in sumo_manager.vehicles.values():
if (vehicle.config.is_ev and
vehicle.assigned_ev_station and
getattr(vehicle, 'is_charging', False)):
station_id = vehicle.assigned_ev_station
charging_counts[station_id] = charging_counts.get(station_id, 0) + 1
# OPTIMIZED: Calculate station loads efficiently
total_charging_kw = 0
substation_loads = {} # Track load per substation
# Bus name mapping cache (moved outside loop for efficiency)
bus_name_mapping = {
"Hell's Kitchen": "Hell's Kitchen_13.8kV",
"Times Square": "Times Square_13.8kV",
"Penn Station": "Penn Station_13.8kV",
"Grand Central": "Grand Central_13.8kV",
"Murray Hill": "Murray Hill_13.8kV",
"Turtle Bay": "Turtle Bay_13.8kV",
"Columbus Circle": "Chelsea_13.8kV",
"Midtown East": "Midtown East_13.8kV"
}
# Calculate power loads per station
for ev_id, ev_station in integrated_system.ev_stations.items():
chargers_in_use = charging_counts.get(ev_id, 0)
# Realistic variable charging rate based on station load
if chargers_in_use > 0:
if chargers_in_use <= 5:
power_per_vehicle = 150 # 150kW DC fast charging
elif chargers_in_use <= 10:
power_per_vehicle = 100 # 100kW
elif chargers_in_use <= 15:
power_per_vehicle = 50 # 50kW
else:
power_per_vehicle = 22 # 22kW (congested)
charging_power_kw = chargers_in_use * power_per_vehicle
else:
charging_power_kw = 0
total_charging_kw += charging_power_kw
# Update integrated system
ev_station['vehicles_charging'] = chargers_in_use
ev_station['current_load_kw'] = charging_power_kw
# Aggregate by substation
substation_name = ev_station['substation']
substation_loads[substation_name] = substation_loads.get(substation_name, 0) + charging_power_kw
# OPTIMIZED: Batch PyPSA updates (collect all updates then apply at once)
pypsa_updates = {} # {load_name: (bus_name, load_mw)}
for substation_name, load_kw in substation_loads.items():
load_mw = load_kw / 1000
# Get bus name
bus_name = bus_name_mapping.get(substation_name)
if not bus_name:
continue
# Check bus existence (with name variations)
bus_name_in_pypsa = None
for variant in [bus_name, bus_name.replace("'", ""), bus_name.replace(" ", "_")]:
if variant in power_grid.network.buses.index:
bus_name_in_pypsa = variant
break
if not bus_name_in_pypsa:
continue
# Prepare update
clean_name = substation_name.replace(' ', '_').replace("'", '')
ev_load_name = f"EV_{clean_name}"
pypsa_updates[ev_load_name] = (bus_name_in_pypsa, load_mw)
# Update integrated system
if substation_name in integrated_system.substations:
integrated_system.substations[substation_name]['ev_load_mw'] = load_mw
# OPTIMIZED: Apply all PyPSA updates in batch (silent for performance)
for ev_load_name, (bus_name_in_pypsa, load_mw) in pypsa_updates.items():
try:
if ev_load_name not in power_grid.network.loads.index:
power_grid.network.add("Load", ev_load_name, bus=bus_name_in_pypsa, p_set=load_mw)
else:
power_grid.network.loads.at[ev_load_name, 'p_set'] = load_mw
except Exception:
pass # Silent failure for performance
# Clear zero loads efficiently
for substation_name in bus_name_mapping.keys():
if substation_name not in substation_loads:
clean_name = substation_name.replace(' ', '_').replace("'", '')
ev_load_name = f"EV_{clean_name}"
if ev_load_name in power_grid.network.loads.index:
power_grid.network.loads.at[ev_load_name, 'p_set'] = 0
# OPTIMIZED: Track load changes (silent for performance)
total_ev_load_mw = total_charging_kw / 1000
previous_ev_load_mw = globals().get('previous_ev_load_mw', 0.0)
globals()['previous_ev_load_mw'] = total_ev_load_mw
def check_n_minus_1_contingency():
"""Check if system can survive any single component failure"""
critical_components = []
for line in power_grid.network.lines.index:
# Temporarily fail this line
original_capacity = power_grid.network.lines.at[line, 's_nom']
power_grid.network.lines.at[line, 's_nom'] = 0
# Run power flow
result = power_grid.run_power_flow("dc")
# Check if system survives
if not result.converged or result.max_line_loading > 1.0:
critical_components.append(line)
# Restore
power_grid.network.lines.at[line, 's_nom'] = original_capacity
return critical_components
def calculate_dynamic_charging_power(soc):
"""Calculate realistic charging power based on battery SOC"""
if soc < 0.2:
return 150 # 150kW DC fast charging for low battery
elif soc < 0.5:
return 100 # 100kW moderate fast charging
elif soc < 0.8:
return 50 # 50kW standard charging
else:
return 22 # 22kW trickle charging above 80%
def handle_grid_stress(power_flow_result, charging_details):
"""Handle grid stress conditions - WORLD CLASS"""
print("\n[EMERGENCY] GRID STRESS DETECTED - INITIATING RESPONSE")
# Identify critical lines
critical_lines = []
for line_name, line_data in power_grid.network.lines.iterrows():
loading = abs(line_data.p0 / line_data.s_nom) if line_data.s_nom > 0 else 0
if loading > 0.85:
critical_lines.append((line_name, loading))
critical_lines.sort(key=lambda x: x[1], reverse=True)
# Implement demand response
if charging_details['total_vehicles_charging'] > 20:
print(f" [DEMAND] Implementing demand response for {charging_details['total_vehicles_charging']} EVs")
# Reduce charging rate at critical stations
for station_name in charging_details['critical_stations']:
# Find station and reduce power
for ev_id, ev_station in integrated_system.ev_stations.items():
if ev_station['name'] == station_name:
# Signal SUMO to reduce charging rate
if hasattr(sumo_manager, 'reduce_charging_rate'):
sumo_manager.reduce_charging_rate(ev_id, 0.5) # 50% reduction
print(f" Reduced charging at {station_name} by 50%")
# Log critical lines
for line, loading in critical_lines[:3]:
print(f" POWER Line {line}: {loading:.1%} loaded")
def handle_voltage_issues(violations):
"""Handle voltage violations - WORLD CLASS"""
print("\nPOWER VOLTAGE CONTROL ACTIVATED")
# Group violations by severity
critical = [v for v in violations if abs(v['deviation']) > 0.1]
warning = [v for v in violations if 0.05 < abs(v['deviation']) <= 0.1]
if critical:
print(f" [CRITICAL] CRITICAL: {len(critical)} buses with >10% deviation")
# Implement voltage control actions
for violation in critical[:3]: # Show top 3
print(f" Bus {violation.get('bus', 'unknown')}: {violation.get('voltage', 0):.3f} pu")
if warning:
print(f" [WARNING] WARNING: {len(warning)} buses with 5-10% deviation")
def check_substation_overloads(substation_loads):
"""Check for substation overloads - WORLD CLASS"""
for substation_name, ev_load_kw in substation_loads.items():
if substation_name in integrated_system.substations:
substation = integrated_system.substations[substation_name]
# Total load including base + EV
total_load_mw = substation['load_mw'] + (ev_load_kw / 1000)
capacity_mva = substation['capacity_mva']
# Assume 0.9 power factor
capacity_mw = capacity_mva * 0.9
loading_percent = (total_load_mw / capacity_mw) * 100
if loading_percent > 90:
print(f"Fire SUBSTATION OVERLOAD: {substation_name}")
print(f" Load: {total_load_mw:.1f} MW / {capacity_mw:.1f} MW ({loading_percent:.1f}%)")
if loading_percent > 100:
print(f" [CRITICAL] {substation_name} WOULD TRIP - INITIATING LOAD SHED")
initiate_load_shedding(substation_name, total_load_mw - capacity_mw)
def initiate_emergency_response(charging_details):
"""Emergency response when power flow diverges"""
print("\n[EMERGENCY][EMERGENCY] EMERGENCY RESPONSE ACTIVATED [EMERGENCY][EMERGENCY]")
print(f" System cannot support {charging_details['total_power_kw']/1000:.1f} MW EV load")
# Stop all new charging
if hasattr(sumo_manager, 'stop_new_charging'):
sumo_manager.stop_new_charging()
# Reduce existing charging
print(" Reducing all charging rates to 25%")
# Signal critical state to dashboard
system_state['emergency'] = True
def initiate_load_shedding(substation_name, excess_mw):
"""Implement load shedding to prevent cascade"""
print(f"\nPOWER LOAD SHEDDING at {substation_name}: {excess_mw:.1f} MW")
# Priority order for shedding
# 1. Reduce EV charging
# 2. Turn off non-critical loads
# 3. Rolling blackouts if necessary
# This would interface with your actual control system
pass
# Start simulation thread
sim_thread = threading.Thread(target=simulation_loop, daemon=True)
sim_thread.start()
# ============================================================================
# FLASK ROUTE DEFINITIONS - ORGANIZED BY FUNCTIONALITY
# ============================================================================
# ============================================================================
# 1. CORE ROUTES (Main page, debug)
# ============================================================================
@app.route('/')
def index():
"""Serve complete dashboard with all features"""
return render_template_string(load_html_template())
@app.route('/api/debug/buses')
def debug_buses():
"""Show all bus names in PyPSA"""
buses_13kv = [b for b in power_grid.network.buses.index if '13.8kV' in b]
# Also show substation names from integrated system
substations = list(integrated_system.substations.keys())
return jsonify({
'pypsa_buses_13kv': buses_13kv,
'integrated_substations': substations,
'mapping_check': {
sub: f"{sub.replace(' ', '_')}_13.8kV" in power_grid.network.buses.index
for sub in substations
}
})
@app.route('/api/debug/pypsa')
def debug_pypsa():
"""Debug PyPSA network state"""
debug_info = {
'buses': list(power_grid.network.buses.index),
'loads': {},
'generators': {},
'total_load': 0,
'total_generation': 0
}
# Check all loads
for load_name in power_grid.network.loads.index:
load_value = power_grid.network.loads.at[load_name, 'p_set']
debug_info['loads'][load_name] = float(load_value)
debug_info['total_load'] += float(load_value)
# Check generators
for gen_name in power_grid.network.generators.index:
gen_p = power_grid.network.generators.at[gen_name, 'p_nom']
debug_info['generators'][gen_name] = float(gen_p)
debug_info['total_generation'] += float(gen_p)
# Check if loads_t exists and has wrong values
if hasattr(power_grid.network, 'loads_t') and hasattr(power_grid.network.loads_t, 'p'):
debug_info['loads_t_sum'] = float(power_grid.network.loads_t.p.sum().sum())
debug_info['loads_t_shape'] = power_grid.network.loads_t.p.shape
return jsonify(debug_info)
@app.route('/api/debug/ev_stations')
def debug_ev_stations():
"""Debug endpoint to check EV station status"""
status = {}
for ev_id, ev_station in integrated_system.ev_stations.items():
status[ev_id] = {
'name': ev_station['name'],
'substation': ev_station['substation'],
'operational': ev_station['operational'],
'substation_operational': integrated_system.substations[ev_station['substation']]['operational'],
'vehicles_charging': ev_station.get('vehicles_charging', 0),
'current_load_kw': ev_station.get('current_load_kw', 0)
}
return jsonify(status)
# ============================================================================
# 2. NETWORK & STATUS ROUTES
# ============================================================================
@app.route('/api/network_state')
def get_network_state():
"""Get complete network state including vehicles - OPTIMIZED FOR 1000+ VEHICLES"""
state = integrated_system.get_network_state()
# Add vehicle data if SUMO is running
if system_state['sumo_running'] and sumo_manager.running:
vehicles = []
station_charging_counts = {}
station_queued_counts = {}
try:
import traci
# OPTIMIZATION: Get all vehicle IDs once (batch API call)
active_vehicle_ids = set(traci.vehicle.getIDList())
# OPTIMIZATION: Only process vehicles that exist in SUMO
for vehicle in sumo_manager.vehicles.values():
if vehicle.id not in active_vehicle_ids:
continue
try:
# OPTIMIZATION: Single position call instead of multiple
x, y = traci.vehicle.getPosition(vehicle.id)
lon, lat = traci.simulation.convertGeo(x, y)
# OPTIMIZATION: Skip expensive edge shape calculation for API response
# Edge shapes should be sent once at initialization, not every frame
edge_id = traci.vehicle.getRoadID(vehicle.id)
# Track charging/queued counts (no change)
if getattr(vehicle, 'is_charging', False) and vehicle.assigned_ev_station:
station_charging_counts[vehicle.assigned_ev_station] = station_charging_counts.get(vehicle.assigned_ev_station, 0) + 1
if getattr(vehicle, 'is_queued', False) and vehicle.assigned_ev_station:
station_queued_counts[vehicle.assigned_ev_station] = station_queued_counts.get(vehicle.assigned_ev_station, 0) + 1
# OPTIMIZATION: Simplified vehicle data (removed unnecessary fields)
vehicles.append({
'id': vehicle.id,
'lat': lat,
'lon': lon,
'type': vehicle.config.vtype.value,
'speed_kmh': round(vehicle.speed * 3.6, 1),
'battery_percent': round(vehicle.config.current_soc * 100) if vehicle.config.is_ev else 100,
'is_charging': getattr(vehicle, 'is_charging', False),
'is_queued': getattr(vehicle, 'is_queued', False),
'is_v2g_active': vehicle.id in v2g_manager.active_sessions,
'is_ev': vehicle.config.is_ev,
'assigned_station': vehicle.assigned_ev_station,
'edge_id': edge_id if edge_id and not edge_id.startswith(':') else None
})
except Exception:
continue
except Exception:
pass
state['vehicles'] = vehicles
state['vehicle_stats'] = sumo_manager.get_statistics()
# Update EV station charging counts
for ev_station in state['ev_stations']:
ev_station['vehicles_charging'] = station_charging_counts.get(ev_station['id'], 0)
ev_station['vehicles_queued'] = station_queued_counts.get(ev_station['id'], 0)
else:
state['vehicles'] = []
state['vehicle_stats'] = {}
return jsonify(state)
@app.route('/api/status')
def get_status():
"""Get complete system status"""
power_status = power_grid.get_system_status()
# CRITICAL: Merge operational status from integrated_system (includes scenario controller failures!)
for sub_name in integrated_system.substations.keys():
if sub_name in power_status.get('substations', {}):
integrated_sub = integrated_system.substations[sub_name]
power_status['substations'][sub_name]['operational'] = integrated_sub.get('operational', True)
power_status['substations'][sub_name]['load_mw'] = integrated_sub.get('load_mw', 0)
power_status['substations'][sub_name]['lat'] = integrated_sub.get('lat', 0)
power_status['substations'][sub_name]['lon'] = integrated_sub.get('lon', 0)
# Add vehicle statistics
if system_state['sumo_running'] and sumo_manager.running:
vehicle_stats = sumo_manager.get_statistics()
power_status['vehicles'] = {
'total': vehicle_stats['total_vehicles'],
'active': len(sumo_manager.vehicles),
'evs': vehicle_stats['ev_vehicles'],
'charging': vehicle_stats['vehicles_charging'],
'avg_speed_kmh': round(vehicle_stats['avg_speed_mps'] * 3.6, 1),
'energy_consumed_kwh': round(vehicle_stats['total_energy_consumed_kwh'], 2)
}
else:
power_status['vehicles'] = {
'total': 0,
'active': 0,
'evs': 0,
'charging': 0,
'avg_speed_kmh': 0,
'energy_consumed_kwh': 0
}
power_status['simulation'] = {
'sumo_running': system_state['sumo_running'],
'speed': system_state['simulation_speed'],
'scenario': system_state['scenario'].value
}
return jsonify(power_status)
# ============================================================================
# 3. SUMO & VEHICLE ROUTES
# ============================================================================
@app.route('/api/sumo/start', methods=['POST'])
def start_sumo():
"""Start SUMO simulation"""
global system_state
if system_state['sumo_running']:
return jsonify({'success': False, 'message': 'SUMO already running'})
try:
# Start SUMO (headless for web interface)
success = sumo_manager.start_sumo(gui=False, seed=42)
if success:
system_state['sumo_running'] = True
# Spawn initial vehicles
data = request.json or {}
count = data.get('vehicle_count', 10)
ev_percentage = data.get('ev_percentage', 0.7)
battery_min_soc = data.get('battery_min_soc', 0.2)
battery_max_soc = data.get('battery_max_soc', 0.9)
spawned = sumo_manager.spawn_vehicles(count, ev_percentage, battery_min_soc, battery_max_soc)
# Preload edge shapes for road snapping (limit for faster start if needed)
try:
cached = preload_edge_shapes()
print(f"Preloaded {cached} SUMO edge shapes")
except Exception as e:
print(f"Edge preload skipped: {e}")
return jsonify({
'success': True,
'message': f'SUMO started with vehicles',
'vehicles_spawned': spawned
})
else:
return jsonify({'success': False, 'message': 'Failed to start SUMO'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/api/sumo/stop', methods=['POST'])
def stop_sumo():
"""Stop SUMO simulation"""
global system_state
if system_state['sumo_running']:
sumo_manager.stop()
system_state['sumo_running'] = False
return jsonify({'success': True, 'message': 'SUMO stopped'})
return jsonify({'success': False, 'message': 'SUMO not running'})
@app.route('/api/sumo/spawn', methods=['POST'])
def spawn_vehicles():
"""Spawn additional vehicles"""
if not system_state['sumo_running']:
return jsonify({'success': False, 'message': 'SUMO not running'})
data = request.json or {}
count = data.get('count', 5)
ev_percentage = data.get('ev_percentage', 0.7)
battery_min_soc = data.get('battery_min_soc', 0.2)
battery_max_soc = data.get('battery_max_soc', 0.9)
spawned = sumo_manager.spawn_vehicles(count, ev_percentage, battery_min_soc, battery_max_soc)
return jsonify({
'success': True,
'spawned': spawned,
'total_vehicles': sumo_manager.stats['total_vehicles']
})
@app.route('/api/sumo/scenario', methods=['POST'])
def set_scenario():
"""Scenario control minimized per request. Only EV rush supported."""
data = request.json or {}
scenario_name = data.get('scenario', 'EV_RUSH')
if not system_state['sumo_running']:
return jsonify({'success': False, 'message': 'SUMO not running'})
if scenario_name == 'EV_RUSH':
spawned = sumo_manager.spawn_vehicles(30, 0.9)
return jsonify({'success': True, 'scenario': 'EV_RUSH', 'spawned': spawned})
return jsonify({'success': False, 'message': 'Only EV_RUSH is supported now'})
@app.route('/api/simulation/speed', methods=['POST'])
def set_simulation_speed():
"""Set simulation speed"""
data = request.json or {}
speed = data.get('speed', 1.0)
system_state['simulation_speed'] = max(0.1, min(10.0, speed))
return jsonify({'success': True, 'speed': system_state['simulation_speed']})
@app.route('/api/ev/config', methods=['POST'])
def update_ev_config():
"""Update EV configuration settings"""
try:
data = request.json or {}
# Validate input
ev_percentage = data.get('ev_percentage', 70)
battery_min_soc = data.get('battery_min_soc', 20)
battery_max_soc = data.get('battery_max_soc', 90)
# Clamp values to valid ranges
ev_percentage = max(0, min(100, ev_percentage))
battery_min_soc = max(1, min(100, battery_min_soc))
battery_max_soc = max(1, min(100, battery_max_soc))
# Ensure min < max
if battery_min_soc >= battery_max_soc:
battery_min_soc = battery_max_soc - 1
# Store configuration globally
global current_ev_config
current_ev_config = {
'ev_percentage': ev_percentage,
'battery_min_soc': battery_min_soc,
'battery_max_soc': battery_max_soc,
'updated_at': datetime.now().isoformat()
}
# Update SUMO manager if running
if sumo_manager and sumo_manager.running:
sumo_manager.ev_percentage = ev_percentage / 100
sumo_manager.battery_min_soc = battery_min_soc / 100
sumo_manager.battery_max_soc = battery_max_soc / 100
print(f"Success EV Configuration Updated:")
print(f" EV Percentage: {ev_percentage}%")
print(f" Battery SOC Range: {battery_min_soc}% - {battery_max_soc}%")
return jsonify({
'success': True,
'message': 'EV configuration updated successfully',
'config': current_ev_config
})
except Exception as e:
print(f"[ERROR] EV config update error: {e}")
return jsonify({
'success': False,
'message': f'Failed to update EV configuration: {str(e)}'
}), 500
@app.route('/api/ev/config', methods=['GET'])
def get_ev_config():
"""Get current EV configuration"""
global current_ev_config
if not current_ev_config:
current_ev_config = {
'ev_percentage': 70,
'battery_min_soc': 20,
'battery_max_soc': 90,
'updated_at': datetime.now().isoformat()
}
return jsonify({
'success': True,
'config': current_ev_config
})
@app.route('/api/test/ev_rush', methods=['POST'])
def test_ev_rush():
"""Test scenario: spawn many low-battery EVs"""
if not system_state['sumo_running']:
return jsonify({'success': False, 'message': 'Start SUMO first'})
# Spawn 30 EVs with very low battery