-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanhattan_sumo_manager.py
More file actions
1970 lines (1594 loc) · 88.2 KB
/
manhattan_sumo_manager.py
File metadata and controls
1970 lines (1594 loc) · 88.2 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 SUMO Manager - World Class Vehicle Simulation
COMPLETE VERSION with all coordinate fixes and route validation
FIXED: Stranded vehicles stop properly and circling routes always work
"""
import os
import sys
import json
import random
import numpy as np
from typing import Dict, List, Tuple, Optional, Set
from dataclasses import dataclass, field
from enum import Enum
import subprocess
import time
from ev_battery_model import EVBatteryModel
from ev_station_manager import EVStationManager
# Check if SUMO is available
try:
import traci
import sumolib
SUMO_AVAILABLE = True
except ImportError:
print("Warning: SUMO not installed. Install with: pip install sumo")
SUMO_AVAILABLE = False
class VehicleType(Enum):
"""Vehicle types matching real NYC traffic"""
CAR = "car"
TAXI = "taxi"
BUS = "bus"
EV_SEDAN = "ev_sedan"
EV_SUV = "ev_suv"
DELIVERY = "delivery"
UBER = "uber"
class SimulationScenario(Enum):
"""Traffic scenarios for different times of day"""
MORNING_RUSH = "morning_rush"
MIDDAY = "midday"
EVENING_RUSH = "evening_rush"
NIGHT = "night"
WEEKEND = "weekend"
EMERGENCY = "emergency"
BLACKOUT = "blackout"
EV_SURGE = "ev_surge"
@dataclass
class VehicleConfig:
"""Vehicle configuration with realistic parameters"""
id: str
vtype: VehicleType
origin: str = None
destination: str = None
is_ev: bool = False
battery_capacity_kwh: float = 0
current_soc: float = 1.0
consumption_kwh_per_km: float = 0.2
depart_time: float = 0
route: List[str] = field(default_factory=list)
class ManhattanSUMOManager:
"""Professional SUMO integration for Manhattan traffic"""
def _calculate_straight_distance(self, lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate straight-line distance between two points (in degrees, for comparison)"""
return ((lat1 - lat2) ** 2 + (lon1 - lon2) ** 2) ** 0.5
def _find_nearest_charging_station(self, vehicle_id: str, current_edge: str) -> Optional[str]:
"""Find the nearest operational charging station with available space"""
import traci
if not self.station_manager:
return None
# Get vehicle position
try:
x, y = traci.vehicle.getPosition(vehicle_id)
vehicle_lon, vehicle_lat = traci.simulation.convertGeo(x, y)
except:
return None
best_station = None
min_distance = float('inf')
# Check ALL stations and find the nearest one
for station_id, station in self.station_manager.stations.items():
# Check if station is operational
if not station['operational']:
continue
# Check if station has space (strict 10 limit)
occupied = len(station['vehicles_charging'])
if occupied >= 10:
continue
# Calculate distance to station
station_info = self.integrated_system.ev_stations.get(station_id)
if not station_info:
continue
# Calculate straight-line distance
dist = self._calculate_straight_distance(
vehicle_lat, vehicle_lon,
station_info['lat'], station_info['lon']
)
if dist < min_distance:
min_distance = dist
best_station = station_id
return best_station
def __init__(self, integrated_system):
self.integrated_system = integrated_system
self.running = False
self.vehicles = {}
self.current_scenario = SimulationScenario.MIDDAY
self.v2g_manager = None # Will be set by main integration
# Manhattan bounds (34th to 59th Street)
self.bounds = {
'north': 40.770,
'south': 40.745,
'west': -74.010,
'east': -73.960
}
# SUMO configuration - traffic lights file removed to avoid errors
self.sumo_config = {
'net_file': 'data/sumo/manhattan.net.xml',
'additional_files': [
'data/sumo/types.add.xml'
],
'step_length': 0.1,
'collision_action': 'warn',
'device.rerouting.probability': '0.8',
'device.battery.probability': '0.3'
}
# Traffic light mapping
self.tl_power_to_sumo = {}
self.tl_sumo_to_power = {}
# EV charging stations in SUMO
self.ev_stations_sumo = {}
# Initialize smart station manager
self.station_manager = None
# Major routes and destinations
self.destinations = []
self.popular_routes = []
self.spawn_edges = []
# Statistics
self.stats = {
'total_vehicles': 0,
'ev_vehicles': 0,
'vehicles_charging': 0,
'total_distance_km': 0,
'total_energy_consumed_kwh': 0,
'avg_speed_mps': 0,
'total_wait_time': 0,
'traffic_light_violations': 0
}
# Load network data
self._load_network_data()
def _load_network_data(self):
"""Load SUMO network and establish mappings"""
if not os.path.exists(self.sumo_config['net_file']):
print("Warning: SUMO network not found. Run get_manhattan_sumo_network.py first!")
return False
if SUMO_AVAILABLE:
# Load network
self.net = sumolib.net.readNet(self.sumo_config['net_file'])
# Get all edges for routing
self.edges = [e.getID() for e in self.net.getEdges()
if not e.isSpecial() and e.allows("passenger")]
# Get junctions
try:
if hasattr(self.net, 'getNodes'):
nodes = self.net.getNodes()
else:
nodes = []
self.junctions = []
for node in nodes:
try:
if hasattr(node, 'getType') and node.getType() != "dead_end":
self.junctions.append(node.getID())
elif len(node.getIncoming()) > 1 or len(node.getOutgoing()) > 1:
self.junctions.append(node.getID())
except:
pass
except:
self.junctions = list(set([e.getFromNode().getID() for e in self.net.getEdges()[:100]] +
[e.getToNode().getID() for e in self.net.getEdges()[:100]]))
# Load validated spawn edges
try:
with open('data/good_spawn_edges.json', 'r') as f:
self.spawn_edges = json.load(f)
print(f"Loaded {len(self.spawn_edges)} validated spawn edges")
except:
print("Using all edges for spawning (may have connectivity issues)")
self.spawn_edges = self.edges[:200] if self.edges else []
# Setup destinations
self._setup_destinations()
print(f"Loaded SUMO network: {len(self.edges)} edges, {len(self.junctions)} junctions")
# Load connected network data if available
connected_network_file = 'data/manhattan_connected_network.json'
if os.path.exists(connected_network_file):
with open(connected_network_file, 'r') as f:
network_data = json.load(f)
if 'spawn_edges' in network_data and network_data['spawn_edges']:
self.spawn_edges = network_data['spawn_edges']
print(f"Loaded {len(self.spawn_edges)} spawn points from connected network")
return True
return False
def _setup_destinations(self):
"""Setup realistic Manhattan destinations"""
self.destinations = [
("Times Square", self._find_nearest_edge(40.7589, -73.9851)),
("Grand Central", self._find_nearest_edge(40.7527, -73.9772)),
("Penn Station", self._find_nearest_edge(40.7505, -73.9934)),
("Bryant Park", self._find_nearest_edge(40.7536, -73.9832)),
("Rockefeller Center", self._find_nearest_edge(40.7587, -73.9787)),
("Herald Square", self._find_nearest_edge(40.7484, -73.9878)),
("5th Ave Shopping", self._find_nearest_edge(40.7614, -73.9776)),
("MoMA", self._find_nearest_edge(40.7614, -73.9776)),
("Carnegie Hall", self._find_nearest_edge(40.7651, -73.9799)),
("Hell's Kitchen", self._find_nearest_edge(40.7638, -73.9918)),
("Murray Hill", self._find_nearest_edge(40.7478, -73.9750)),
("Turtle Bay", self._find_nearest_edge(40.7544, -73.9667)),
("Columbus Circle", self._find_nearest_edge(40.7680, -73.9819)),
("Plaza Hotel", self._find_nearest_edge(40.7644, -73.9747)),
("Waldorf Astoria", self._find_nearest_edge(40.7560, -73.9738))
]
self.destinations = [(name, edge) for name, edge in self.destinations if edge]
self._create_popular_routes()
def _find_nearest_edge(self, lat: float, lon: float) -> Optional[str]:
"""Find nearest SUMO edge to given coordinates"""
if not SUMO_AVAILABLE or not hasattr(self, 'net'):
return None
try:
x, y = self.net.convertLonLat2XY(lon, lat)
min_dist = float('inf')
nearest_edge = None
for edge in self.net.getEdges():
if not edge.allows("passenger") or edge.isSpecial():
continue
shape = edge.getShape()
if shape:
edge_x = sum(p[0] for p in shape) / len(shape)
edge_y = sum(p[1] for p in shape) / len(shape)
dist = ((x - edge_x) ** 2 + (y - edge_y) ** 2) ** 0.5
if dist < min_dist:
min_dist = dist
nearest_edge = edge.getID()
if not nearest_edge and self.edges:
nearest_edge = self.edges[0]
return nearest_edge
except:
return self.edges[0] if self.edges else None
def _create_popular_routes(self):
"""Create realistic routes between popular destinations"""
if not self.destinations:
return
route_patterns = [
("Hell's Kitchen", "Times Square"),
("Murray Hill", "Grand Central"),
("Turtle Bay", "Grand Central"),
("Columbus Circle", "Penn Station"),
("Times Square", "Rockefeller Center"),
("Grand Central", "Times Square"),
("Penn Station", "Herald Square"),
("Penn Station", "5th Ave Shopping"),
("Grand Central", "Herald Square"),
("Times Square", "MoMA"),
("Columbus Circle", "Carnegie Hall")
]
for origin_name, dest_name in route_patterns:
origin_edge = next((e for n, e in self.destinations if n == origin_name), None)
dest_edge = next((e for n, e in self.destinations if n == dest_name), None)
if origin_edge and dest_edge:
self.popular_routes.append((origin_edge, dest_edge))
def start_sumo(self, gui: bool = False, seed: int = None) -> bool:
"""Start SUMO simulation with proper configuration"""
if not SUMO_AVAILABLE:
print("SUMO not available")
return False
if self.running:
print("SUMO already running")
return False
# Build command
sumo_binary = "sumo-gui" if gui else "sumo"
cmd = [
sumo_binary,
"-n", self.sumo_config['net_file'],
"--step-length", str(self.sumo_config['step_length']),
"--collision.action", self.sumo_config['collision_action'],
"--device.rerouting.probability", self.sumo_config['device.rerouting.probability'],
"--no-warnings",
"--no-step-log",
"--duration-log.statistics",
"--device.emissions.probability", "1.0"
]
# Collect additional files
existing_additional_files = []
for add_file in self.sumo_config['additional_files']:
if os.path.exists(add_file):
existing_additional_files.append(add_file)
if existing_additional_files:
cmd.extend(["-a", ",".join(existing_additional_files)])
if seed is not None:
cmd.extend(["--seed", str(seed)])
try:
traci.start(cmd)
self.running = True
self._initialize_traffic_lights()
self._initialize_ev_stations()
# Initialize smart station manager AFTER network is loaded
if self.net:
self.station_manager = EVStationManager(self.integrated_system, self.net)
print("SUMO started successfully")
return True
except Exception as e:
print(f"Failed to start SUMO: {e}")
return False
def _initialize_traffic_lights(self):
"""Map traffic lights between power grid and SUMO"""
if not self.running:
return
tl_ids = traci.trafficlight.getIDList()
for tl_id in tl_ids:
try:
if hasattr(self.net, 'getNode'):
junction = self.net.getNode(tl_id)
else:
continue
if junction:
coord = junction.getCoord()
lon, lat = self.net.convertXY2LonLat(coord[0], coord[1])
min_dist = float('inf')
nearest_power_tl = None
for power_tl_id, power_tl in self.integrated_system.traffic_lights.items():
dist = ((lat - power_tl['lat'])**2 + (lon - power_tl['lon'])**2)**0.5
if dist < min_dist and dist < 0.001:
min_dist = dist
nearest_power_tl = power_tl_id
if nearest_power_tl:
self.tl_power_to_sumo[nearest_power_tl] = tl_id
self.tl_sumo_to_power[tl_id] = nearest_power_tl
except:
pass
print(f"Mapped {len(self.tl_power_to_sumo)} traffic lights to SUMO")
def _initialize_ev_stations(self):
"""Setup EV charging stations in SUMO"""
if not self.running:
return
for ev_id, ev_station in self.integrated_system.ev_stations.items():
edge_id = self._find_nearest_edge(ev_station['lat'], ev_station['lon'])
if edge_id:
self.ev_stations_sumo[ev_id] = {
'edge': edge_id,
'capacity': ev_station['chargers'],
'available': ev_station['chargers'] if ev_station['operational'] else 0,
'charging': []
}
def spawn_vehicles(self, count: int = 10, ev_percentage: float = 0.3, battery_min_soc: float = 0.2, battery_max_soc: float = 0.9) -> int:
"""Spawn vehicles - GUARANTEED to spawn exact count requested (MAX 100)"""
if not self.running:
return 0
# SAFETY CAP: Never spawn more than 100 vehicles total
if count > 100:
print(f"WARNING: Requested {count} vehicles, but capping at 100 for performance")
count = 100
import traci
spawned = 0
attempts = 0
max_attempts = count * 10 # Allow many attempts to get exact count
# Get ALL valid edges from SUMO
all_edges = traci.edge.getIDList()
valid_edges = [e for e in all_edges if not e.startswith(':') and traci.edge.getLaneNumber(e) > 0]
if not valid_edges:
print("ERROR: No valid edges found in SUMO network")
return 0
print(f"Spawning {count} vehicles using {len(valid_edges)} valid edges...")
# Keep trying until we get the exact count
while spawned < count and attempts < max_attempts:
attempts += 1
# Generate unique vehicle ID
vehicle_id = f"veh_{self.stats['total_vehicles'] + spawned}_{attempts}"
# Determine if EV using configurable percentage
is_ev = random.random() < ev_percentage
if is_ev:
vtype = "ev_sedan" if random.random() < 0.6 else "ev_suv"
# Use configurable battery SOC range
initial_soc = random.uniform(battery_min_soc, battery_max_soc)
else:
vtype = random.choice(["car", "taxi"])
initial_soc = 1.0
# Keep trying different edge combinations
route_found = False
edge_attempts = 0
while not route_found and edge_attempts < 20:
edge_attempts += 1
try:
# Pick random edges
origin = random.choice(valid_edges)
destination = random.choice(valid_edges)
# Ensure different
if origin == destination:
if len(valid_edges) > 1:
destination = random.choice([e for e in valid_edges if e != origin])
else:
continue
# Try to find route
route_result = traci.simulation.findRoute(origin, destination)
if route_result and route_result.edges and len(route_result.edges) > 0:
# Valid route found!
route_id = f"route_{vehicle_id}"
# Add route
traci.route.add(route_id, route_result.edges)
# Add vehicle
traci.vehicle.add(
vehicle_id,
route_id,
typeID=vtype,
depart="now"
)
# Set speed
traci.vehicle.setMaxSpeed(vehicle_id, 200)
traci.vehicle.setSpeedMode(vehicle_id, 0)
traci.vehicle.setSpeed(vehicle_id, 100)
traci.vehicle.setAccel(vehicle_id, 50)
traci.vehicle.setDecel(vehicle_id, 50)
traci.vehicle.setMinGap(vehicle_id, 0.5)
# Set color
if is_ev:
if initial_soc < 0.25:
traci.vehicle.setColor(vehicle_id, (255, 0, 0, 255)) # Red for needs charging
else:
traci.vehicle.setColor(vehicle_id, (0, 255, 0, 255)) # Green when charged
else:
# All non-EV vehicles are yellow
traci.vehicle.setColor(vehicle_id, (255, 255, 0, 255)) # Yellow for gas vehicles
# Set battery for EVs
if is_ev:
battery_capacity = 75000 if vtype == "ev_sedan" else 100000
traci.vehicle.setParameter(vehicle_id, "device.battery.maximumBatteryCapacity", str(battery_capacity))
traci.vehicle.setParameter(vehicle_id, "device.battery.actualBatteryCapacity", str(battery_capacity * initial_soc))
traci.vehicle.setParameter(vehicle_id, "has.battery.device", "true")
# Create vehicle object
vtype_enum = VehicleType.EV_SEDAN if vtype == "ev_sedan" else \
VehicleType.EV_SUV if vtype == "ev_suv" else \
VehicleType.TAXI if vtype == "taxi" else \
VehicleType.CAR
self.vehicles[vehicle_id] = Vehicle(
vehicle_id,
VehicleConfig(
id=vehicle_id,
vtype=vtype_enum,
origin=origin,
destination=destination,
is_ev=is_ev,
battery_capacity_kwh=75 if vtype == "ev_sedan" else (100 if vtype == "ev_suv" else 0),
current_soc=initial_soc,
route=route_result.edges
)
)
spawned += 1
route_found = True
if is_ev:
self.stats['ev_vehicles'] += 1
# Success message for each vehicle
if spawned % 5 == 0:
print(f" Spawned {spawned}/{count} vehicles...")
break # Exit edge_attempts loop
except Exception as e:
# This edge combination didn't work, try another
continue
# If we couldn't spawn with any edge combination after 20 tries,
# try a simple fallback route
if not route_found and len(valid_edges) >= 2:
try:
# Use first two edges as fallback
vehicle_id = f"veh_fallback_{self.stats['total_vehicles'] + spawned}_{attempts}"
route_id = f"route_fallback_{vehicle_id}"
traci.route.add(route_id, [valid_edges[0], valid_edges[1]])
traci.vehicle.add(
vehicle_id,
route_id,
typeID="car",
depart="now"
)
# Basic vehicle setup
self.vehicles[vehicle_id] = Vehicle(
vehicle_id,
VehicleConfig(
id=vehicle_id,
vtype=VehicleType.CAR,
origin=valid_edges[0],
destination=valid_edges[1],
is_ev=False,
battery_capacity_kwh=0,
current_soc=1.0,
route=[valid_edges[0], valid_edges[1]]
)
)
spawned += 1
print(f" Used fallback route for vehicle {spawned}/{count}")
except:
pass
# Final count
self.stats['total_vehicles'] += spawned
if spawned == count:
print(f"Success Successfully spawned exactly {spawned} vehicles!")
else:
print(f"WARNING Spawned {spawned}/{count} vehicles (some routes couldn't be created)")
print(f" EVs: {sum(1 for v in self.vehicles.values() if v.config.is_ev)}")
print(f" Gas: {sum(1 for v in self.vehicles.values() if not v.config.is_ev)}")
return spawned
def get_vehicle_positions_for_visualization(self) -> List[Dict]:
"""Get vehicle data with CORRECTED coordinates for web visualization"""
if not self.running:
return []
try:
import traci
vehicles_data = []
for vehicle in self.vehicles.values():
try:
if vehicle.id in traci.vehicle.getIDList():
# Get position from SUMO (in SUMO's internal coordinate system)
x, y = traci.vehicle.getPosition(vehicle.id)
# CRITICAL: Use SUMO's built-in coordinate conversion
# This ensures vehicles stay on the actual roads
lon, lat = traci.simulation.convertGeo(x, y)
# Additional validation - ensure within Manhattan bounds
if not (self.bounds['south'] <= lat <= self.bounds['north'] and
self.bounds['west'] <= lon <= self.bounds['east']):
# If outside bounds, try alternative conversion
lon, lat = self.net.convertXY2LonLat(x, y)
# Final bounds check
if (self.bounds['south'] <= lat <= self.bounds['north'] and
self.bounds['west'] <= lon <= self.bounds['east']):
# Get the actual road/edge the vehicle is on
edge_id = traci.vehicle.getRoadID(vehicle.id)
lane_pos = traci.vehicle.getLanePosition(vehicle.id)
lane_id = traci.vehicle.getLaneID(vehicle.id)
# Get vehicle angle for proper orientation
angle = traci.vehicle.getAngle(vehicle.id)
vehicles_data.append({
'id': vehicle.id,
'lat': lat,
'lon': lon,
'type': vehicle.config.vtype.value,
'speed': vehicle.speed,
'speed_kmh': round(vehicle.speed * 3.6, 1),
'soc': vehicle.config.current_soc if vehicle.config.is_ev else 1.0,
'battery_percent': round(vehicle.config.current_soc * 100) if vehicle.config.is_ev else 100,
'is_charging': vehicle.is_charging,
'is_ev': vehicle.config.is_ev,
'distance_traveled': round(vehicle.distance_traveled, 1),
'waiting_time': round(vehicle.waiting_time, 1),
'destination': vehicle.destination,
'assigned_station': vehicle.assigned_ev_station,
'color': self._get_vehicle_color(vehicle),
'angle': angle,
'edge': edge_id,
'lane_pos': lane_pos,
'lane_id': lane_id
})
except Exception as e:
continue
return vehicles_data
except Exception as e:
print(f"Error getting vehicle positions: {e}")
return []
def _get_vehicle_color(self, vehicle: 'Vehicle') -> str:
"""Get vehicle color based on type and state"""
# Check if vehicle is stranded (emergency)
if hasattr(vehicle, 'is_stranded') and vehicle.is_stranded:
return '#ff00ff' # Purple for emergency (will flash in handling)
# EV colors based on battery
if vehicle.config.is_ev:
if vehicle.config.current_soc <= 0.02: # 2% or less - emergency
return '#ff00ff' # Purple (will flash)
elif vehicle.config.current_soc < 0.25: # Needs charging
return '#ff0000' # Red
elif hasattr(vehicle, 'is_charging') and vehicle.is_charging:
return '#00ffff' # Cyan when charging
else:
return '#00ff00' # Green when charged/normal
# Non-EV vehicles - light blue to match frontend
else:
return '#6464ff' # Light blue for all gas vehicles
def update_traffic_lights(self):
"""Sync traffic lights from power grid to SUMO - FIXED for blackouts"""
if not self.running:
return
import traci
# Get all SUMO traffic lights
tl_ids = traci.trafficlight.getIDList()
for tl_id in tl_ids:
try:
# Get the current signal state to know its structure
current_state = traci.trafficlight.getRedYellowGreenState(tl_id)
state_length = len(current_state)
# Find corresponding power grid traffic light
power_tl = None
if tl_id in self.tl_sumo_to_power:
power_tl_id = self.tl_sumo_to_power[tl_id]
if power_tl_id in self.integrated_system.traffic_lights:
power_tl = self.integrated_system.traffic_lights[power_tl_id]
# Set traffic light state based on power status
if power_tl:
if not power_tl['powered']:
# NO POWER = FLASHING YELLOW (vehicles proceed with caution)
# Or OFF state - vehicles treat as uncontrolled intersection
# Option 1: All yellow (caution mode)
yellow_state = 'y' * state_length
traci.trafficlight.setRedYellowGreenState(tl_id, yellow_state)
# Option 2: Turn off traffic light program (vehicles use priority rules)
# traci.trafficlight.setProgram(tl_id, "off")
else:
# Normal operation - set based on power grid phase
if power_tl['phase'] == 'green':
# Create green phase pattern
if state_length == 4:
new_state = 'GGrr' # Green N-S, Red E-W
elif state_length == 8:
new_state = 'GGGGrrrr' # Green main direction
else:
# General pattern: half green, half red
half = state_length // 2
new_state = 'G' * half + 'r' * (state_length - half)
traci.trafficlight.setRedYellowGreenState(tl_id, new_state)
elif power_tl['phase'] == 'yellow':
# Yellow phase
if state_length == 4:
new_state = 'yyrr'
elif state_length == 8:
new_state = 'yyyyrrrr'
else:
half = state_length // 2
new_state = 'y' * half + 'r' * (state_length - half)
traci.trafficlight.setRedYellowGreenState(tl_id, new_state)
else: # red phase
# Red main, green cross
if state_length == 4:
new_state = 'rrGG' # Red N-S, Green E-W
elif state_length == 8:
new_state = 'rrrrGGGG' # Red main, Green cross
else:
half = state_length // 2
new_state = 'r' * half + 'G' * (state_length - half)
traci.trafficlight.setRedYellowGreenState(tl_id, new_state)
else:
# No mapping found - let SUMO handle normally
pass
except Exception as e:
# Continue with other lights if one fails
pass
def handle_blackout_traffic_lights(self, affected_substations):
"""Handle traffic lights during blackout - set to flashing yellow or off"""
if not self.running:
return
import traci
affected_count = 0
for tl_id in traci.trafficlight.getIDList():
if tl_id in self.tl_sumo_to_power:
power_tl_id = self.tl_sumo_to_power[tl_id]
if power_tl_id in self.integrated_system.traffic_lights:
power_tl = self.integrated_system.traffic_lights[power_tl_id]
# Check if this light's substation is affected
if power_tl['substation'] in affected_substations:
# Set to yellow (caution) - vehicles can proceed carefully
current_state = traci.trafficlight.getRedYellowGreenState(tl_id)
yellow_state = 'y' * len(current_state)
traci.trafficlight.setRedYellowGreenState(tl_id, yellow_state)
affected_count += 1
if affected_count > 0:
print(f"🚦 Set {affected_count} traffic lights to YELLOW (blackout mode)")
def force_all_lights_red(self):
"""Force all traffic lights to red (for testing)"""
if not self.running:
return
import traci
for tl_id in traci.trafficlight.getIDList():
try:
state = traci.trafficlight.getRedYellowGreenState(tl_id)
red_state = 'r' * len(state)
traci.trafficlight.setRedYellowGreenState(tl_id, red_state)
except:
pass
print("WARNING All traffic lights set to RED")
def step(self):
"""Advance simulation one step"""
if not self.running:
return
try:
import traci
traci.simulationStep()
# These are the ACTUAL methods in your code
self.update_traffic_lights() # This exists
self._update_vehicles() # This exists
self._handle_ev_charging() # This exists
self._update_statistics() # This exists around line 1752
except Exception as e:
print(f"Simulation step error: {e}")
import traceback
traceback.print_exc()
def _update_statistics(self):
"""Update simulation statistics"""
if not self.running:
return
try:
import traci
vehicle_ids = traci.vehicle.getIDList()
if vehicle_ids:
speeds = [traci.vehicle.getSpeed(v) for v in vehicle_ids]
self.stats['avg_speed_mps'] = sum(speeds) / len(speeds) if speeds else 0
self.stats['total_distance_km'] = sum(
traci.vehicle.getDistance(v) / 1000 for v in vehicle_ids
)
self.stats['total_wait_time'] = sum(
traci.vehicle.getWaitingTime(v) for v in vehicle_ids
)
# Calculate energy for EVs
total_energy = 0
for vehicle in self.vehicles.values():
if vehicle.config.is_ev:
energy_used = (1.0 - vehicle.config.current_soc) * vehicle.config.battery_capacity_kwh
total_energy += energy_used
self.stats['total_energy_consumed_kwh'] = total_energy
except Exception as e:
pass # Silent fail for stats
def _update_vehicles(self):
"""Update vehicle states with realistic battery drain"""
import traci
vehicle_ids = traci.vehicle.getIDList()
for veh_id in vehicle_ids:
if veh_id in self.vehicles:
vehicle = self.vehicles[veh_id]
try:
# Get vehicle dynamics
vehicle.position = traci.vehicle.getPosition(veh_id)
speed = traci.vehicle.getSpeed(veh_id)
vehicle.speed = speed
# FIXED: Check if stranded FIRST - don't allow movement
if hasattr(vehicle, 'is_stranded') and vehicle.is_stranded:
# FORCE STOP - don't allow any movement
traci.vehicle.setSpeed(veh_id, 0)
continue # Skip all other updates for stranded vehicle
# FORCE EXTREME SPEED if not charging
if not vehicle.is_charging:
if speed < 150: # If going slower than 150 m/s
traci.vehicle.setSpeed(veh_id, 200) # Force 200 m/s
traci.vehicle.setSpeedMode(veh_id, 0) # Ignore all safety
traci.vehicle.setAccel(veh_id, 50) # Super acceleration
vehicle.distance_traveled = traci.vehicle.getDistance(veh_id)
vehicle.waiting_time = traci.vehicle.getWaitingTime(veh_id)
# Handle EVs with CALIBRATED battery drain
if vehicle.config.is_ev and not vehicle.is_charging:
# CALIBRATED DRAIN RATE FOR MANHATTAN
# At 200 m/s, we travel 20m per step (0.1s steps)
# To drain 30% over 5km: 5000m / 20m = 250 steps
# 30% / 250 steps = 0.12% per step
# Base drain rate: 0.12% per step at full speed
# This ensures from farthest point with 38% battery,
# we arrive at farthest station with 8% left
if speed > 150: # Fast driving (normal for our simulation)
drain_rate = 0.0007 # 0.12% per step
elif speed > 50: # Medium speed
drain_rate = 0.0002 # 0.08% per step
elif speed > 10: # Slow/traffic
drain_rate = 0.0001 # 0.05% per step
else: # Stopped/crawling
drain_rate = 0.00005 # 0.02% per step (idle consumption)
# Additional drain if accelerating hard
try:
acceleration = traci.vehicle.getAcceleration(veh_id)
if acceleration > 10: # Hard acceleration
drain_rate *= 1.5
except:
pass
# Apply battery drain
old_soc = vehicle.config.current_soc
vehicle.config.current_soc -= drain_rate
vehicle.config.current_soc = max(0, vehicle.config.current_soc)
# Update SUMO battery parameter
try:
new_battery = vehicle.config.current_soc * vehicle.config.battery_capacity_kwh * 1000
traci.vehicle.setParameter(veh_id, "device.battery.actualBatteryCapacity", str(new_battery))
except:
pass
# Visual indication of battery level
if vehicle.config.current_soc <= 0.02:
# EMERGENCY - 2% or less (flashing purple)
import time
flash = int(time.time() * 3) % 2
if flash == 0:
traci.vehicle.setColor(veh_id, (255, 0, 255, 255)) # Bright purple
else:
traci.vehicle.setColor(veh_id, (139, 0, 139, 255)) # Dark purple
elif vehicle.config.current_soc < 0.25:
# Needs charging - red
traci.vehicle.setColor(veh_id, (255, 0, 0, 255))
else:
# Charged - green
traci.vehicle.setColor(veh_id, (0, 255, 0, 255))
# Route to charging when below 25% (gives margin to reach station)
if vehicle.config.current_soc < 0.38 and not vehicle.assigned_ev_station and self.station_manager:
current_edge = traci.vehicle.getRoadID(veh_id)
if current_edge and not current_edge.startswith(':'):
# Convert position for station manager
x, y = vehicle.position
lon, lat = traci.simulation.convertGeo(x, y)
# Use smart station manager
result = self.station_manager.request_charging(
veh_id,
vehicle.config.current_soc,
current_edge,
(lon, lat),
is_emergency=(vehicle.config.current_soc < 0.1)
)
if result:
station_id, target_edge, wait_time, distance = result
# Navigate to station
try:
route = traci.simulation.findRoute(current_edge, target_edge)
if route and route.edges: