-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraffic_signal_ai.py
More file actions
1672 lines (1355 loc) · 62.5 KB
/
Copy pathtraffic_signal_ai.py
File metadata and controls
1672 lines (1355 loc) · 62.5 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
"""
Adaptive traffic light controller using reinforcement learning to minimize congestion.
This module simulates, trains, and deploys AI controllers for traffic intersections.
"""
import numpy as np
import pandas as pd
import gym
from gym import spaces
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import random
import time
import os
import json
import logging
import pickle
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Any, Optional, Union
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("traffic_ai.log"), logging.StreamHandler()]
)
logger = logging.getLogger("TrafficSignalAI")
# Traffic light phases (simplification of actual traffic light patterns)
PHASES = {
0: "North-South Green, East-West Red",
1: "North-South Yellow, East-West Red",
2: "North-South Red, East-West Green",
3: "North-South Red, East-West Yellow"
}
# Vehicle types with their properties
VEHICLE_TYPES = {
'car': {'length': 4.5, 'max_speed': 15.0, 'accel': 2.5, 'decel': 4.5},
'bus': {'length': 12.0, 'max_speed': 12.0, 'accel': 1.5, 'decel': 3.0},
'truck': {'length': 8.0, 'max_speed': 13.0, 'accel': 1.8, 'decel': 3.5},
'motorcycle': {'length': 2.0, 'max_speed': 18.0, 'accel': 3.5, 'decel': 5.0},
'bicycle': {'length': 1.8, 'max_speed': 6.0, 'accel': 1.2, 'decel': 2.0}
}
class Vehicle:
"""
Represents a vehicle in the traffic simulation.
Each vehicle has position, speed, and other properties that evolve
as it moves through the traffic network.
"""
next_id = 0 # Class variable for unique vehicle IDs
def __init__(self, lane: str, position: float = 0.0, speed: float = 0.0,
vehicle_type: str = 'car', destination: str = None):
"""
Initialize a vehicle.
Args:
lane: Current lane ID (e.g., 'north_in_1')
position: Position along the lane in meters (0 = start of lane)
speed: Current speed in m/s
vehicle_type: Type of vehicle ('car', 'bus', etc.)
destination: Target lane (for routing)
"""
# Get unique ID
self.id = Vehicle.next_id
Vehicle.next_id += 1
# Location and movement
self.lane = lane
self.position = position
self.speed = speed
self.acceleration = 0.0
# Route and status
self.destination = destination
self.route = [] # List of lanes to follow
self.waiting_time = 0.0 # Time spent waiting at lights
self.total_travel_time = 0.0 # Total time in the network
self.arrived = False
# Verify and set vehicle type
if vehicle_type in VEHICLE_TYPES:
self.type = vehicle_type
self.properties = VEHICLE_TYPES[vehicle_type].copy()
else:
self.type = 'car'
self.properties = VEHICLE_TYPES['car'].copy()
logger.warning(f"Unknown vehicle type {vehicle_type}, defaulting to car")
def update(self, dt: float, traffic_light_state: int, leader_distance: float = float('inf'),
leader_speed: float = None):
"""
Update vehicle state for one timestep.
Args:
dt: Time step in seconds
traffic_light_state: Current state of the next traffic light
leader_distance: Distance to the vehicle ahead (if any)
leader_speed: Speed of the vehicle ahead (if any)
Returns:
Updated vehicle state
"""
# Check if already arrived
if self.arrived:
return
# Update travel time
self.total_travel_time += dt
# Calculate new acceleration, speed, and position
self._update_acceleration(traffic_light_state, leader_distance, leader_speed)
# Apply acceleration to update speed (with limits)
self.speed += self.acceleration * dt
self.speed = max(0.0, min(self.speed, self.properties['max_speed']))
# Update position
old_position = self.position
self.position += self.speed * dt
# Check if waiting (very slow speed)
if self.speed < 0.5: # Less than 0.5 m/s is considered waiting
self.waiting_time += dt
def _update_acceleration(self, traffic_light_state: int, leader_distance: float,
leader_speed: float = None):
"""
Calculate vehicle acceleration based on traffic conditions.
This uses a simplified Intelligent Driver Model (IDM) for car-following
and traffic light responses.
Args:
traffic_light_state: Current state of the next traffic light
leader_distance: Distance to the vehicle ahead
leader_speed: Speed of the vehicle ahead
Returns:
Updated acceleration value
"""
# Maximum acceleration in free traffic
free_road_accel = self.properties['accel']
# Desired speed - try to reach max speed when possible
v_desired = self.properties['max_speed']
acceleration = free_road_accel * (1 - (self.speed / v_desired)**4)
# Adjust for leader vehicle (if any) - simple car-following model
if leader_distance < float('inf'):
# Safety distance = min gap + time headway * speed
min_gap = self.properties['length'] + 1.0 # 1m minimum gap
time_headway = 1.5 # 1.5 seconds time gap
desired_gap = min_gap + time_headway * self.speed
# If we're too close to the leader
if leader_distance < desired_gap:
# If leader info available, use it
if leader_speed is not None:
# Deceleration to maintain safe distance
decel = ((self.speed - leader_speed)**2) / (2 * leader_distance)
acceleration -= min(decel, self.properties['decel'])
else:
# Conservative deceleration if we don't know leader speed
acceleration = -self.properties['decel'] * (desired_gap / leader_distance)**2
# Adjust for traffic lights
# Check if yellow or red for our direction (simplified)
light_distance = 50.0 # for example, distance to next traffic light
# Simple check if the light is red/yellow for our direction
# This is a simplification - in reality would depend on lane and exact state
is_red_or_yellow = ((self.lane.startswith('north') or self.lane.startswith('south')) and
traffic_light_state >= 1) or \
((self.lane.startswith('east') or self.lane.startswith('west')) and
(traffic_light_state == 0 or traffic_light_state == 1))
if is_red_or_yellow and light_distance < 50:
# Time to reach light at current speed
time_to_light = light_distance / max(0.1, self.speed)
# If we can't make it through before red, slow down
if time_to_light > 2.0: # if more than 2 seconds to light
stopping_decel = (self.speed**2) / (2 * light_distance)
acceleration = min(acceleration, -stopping_decel)
# Apply limits
self.acceleration = max(-self.properties['decel'],
min(self.properties['accel'], acceleration))
def __repr__(self) -> str:
return f"Vehicle(id={self.id}, type={self.type}, lane={self.lane}, pos={self.position:.1f}m, speed={self.speed:.1f}m/s)"
class Lane:
"""
Represents a single lane of traffic.
Lanes connect intersections and contain vehicles.
"""
def __init__(self, lane_id: str, length: float, max_speed: float,
origin: str = None, destination: str = None):
"""
Initialize a lane.
Args:
lane_id: Unique lane identifier
length: Length of lane in meters
max_speed: Maximum speed limit in m/s
origin: Start intersection ID
destination: End intersection ID
"""
self.id = lane_id
self.length = length
self.max_speed = max_speed
self.origin = origin
self.destination = destination
# List of vehicles in the lane (sorted by position)
self.vehicles = []
# Traffic counts
self.vehicles_entered = 0
self.vehicles_exited = 0
# Occupancy tracking (for congestion measurement)
self.occupancy_history = []
def add_vehicle(self, vehicle: Vehicle) -> None:
"""Add a vehicle to this lane and set its initial properties."""
# Set the vehicle's lane and initial position
vehicle.lane = self.id
# If lane is 'incoming', place at start, otherwise place at end (for testing)
if 'in' in self.id:
vehicle.position = 0.0
else:
vehicle.position = self.length
# Add to lane and sort vehicles by position
self.vehicles.append(vehicle)
self.vehicles.sort(key=lambda v: v.position)
# Update counts
self.vehicles_entered += 1
def remove_vehicle(self, vehicle: Vehicle) -> None:
"""Remove a vehicle from this lane."""
if vehicle in self.vehicles:
self.vehicles.remove(vehicle)
self.vehicles_exited += 1
def update(self, dt: float, traffic_light_state: int) -> List[Vehicle]:
"""
Update all vehicles in the lane for one timestep.
Args:
dt: Time step in seconds
traffic_light_state: Current state of the traffic light
Returns:
List of vehicles that have exited the lane
"""
exited_vehicles = []
# Update vehicles from back to front so we know leader positions
for i in range(len(self.vehicles) - 1, -1, -1):
vehicle = self.vehicles[i]
# Determine leader info
leader_distance = float('inf')
leader_speed = None
if i < len(self.vehicles) - 1: # If not the first vehicle
leader = self.vehicles[i + 1]
leader_distance = leader.position - vehicle.position - vehicle.properties['length']
leader_speed = leader.speed
# Update vehicle
vehicle.update(dt, traffic_light_state, leader_distance, leader_speed)
# Check if vehicle has exited the lane
if vehicle.position >= self.length:
exited_vehicles.append(vehicle)
# Remove exited vehicles
for vehicle in exited_vehicles:
self.remove_vehicle(vehicle)
# Calculate occupancy (percent of lane physically occupied by vehicles)
total_vehicle_length = sum(v.properties['length'] for v in self.vehicles)
occupancy = min(1.0, total_vehicle_length / self.length)
self.occupancy_history.append(occupancy)
# Keep history limited to last 100 steps
if len(self.occupancy_history) > 100:
self.occupancy_history = self.occupancy_history[-100:]
return exited_vehicles
def get_average_occupancy(self, window: int = 10) -> float:
"""Calculate average occupancy over the last n timesteps."""
if not self.occupancy_history:
return 0.0
window = min(window, len(self.occupancy_history))
return sum(self.occupancy_history[-window:]) / window
def get_average_speed(self) -> float:
"""Calculate average speed of all vehicles in the lane."""
if not self.vehicles:
return self.max_speed # Empty lane = free flow
return sum(v.speed for v in self.vehicles) / len(self.vehicles)
def __repr__(self) -> str:
return f"Lane(id={self.id}, length={self.length}m, vehicles={len(self.vehicles)})"
class Intersection:
"""
Represents a traffic intersection with connected lanes and traffic signals.
"""
def __init__(self, intersection_id: str, incoming_lanes: List[str] = None,
outgoing_lanes: List[str] = None):
"""
Initialize an intersection.
Args:
intersection_id: Unique identifier
incoming_lanes: List of incoming lane IDs
outgoing_lanes: List of outgoing lane IDs
"""
self.id = intersection_id
self.incoming_lanes = incoming_lanes or []
self.outgoing_lanes = outgoing_lanes or []
# Traffic signal state and timing
self.phase = 0 # Current phase
self.phase_time = 0.0 # Time in current phase
self.phase_durations = [30.0, 3.0, 30.0, 3.0] # Default durations for each phase
# Stats for monitoring
self.total_wait_time = 0.0
self.total_vehicles = 0
self.throughput_history = []
def update(self, dt: float, new_phase: int = None) -> None:
"""
Update the intersection state for one timestep.
Args:
dt: Time step in seconds
new_phase: Optional new phase to set
"""
# If a new phase is requested, set it
if new_phase is not None and new_phase != self.phase:
self.phase = new_phase
self.phase_time = 0.0
else:
# Otherwise, update phase time and check for phase transition
self.phase_time += dt
# Check if time to change to next phase
if self.phase_time >= self.phase_durations[self.phase]:
self.phase = (self.phase + 1) % len(self.phase_durations)
self.phase_time = 0.0
def get_state(self) -> Dict[str, Any]:
"""
Get the current state of the intersection.
Returns:
Dict with phase, phase_time, and other relevant info
"""
return {
'phase': self.phase,
'phase_time': self.phase_time,
'phase_duration': self.phase_durations[self.phase],
'phase_description': PHASES[self.phase]
}
def set_phase_durations(self, durations: List[float]) -> None:
"""Set new phase durations."""
if len(durations) != len(self.phase_durations):
logger.warning(f"Expected {len(self.phase_durations)} durations but got {len(durations)}")
return
self.phase_durations = durations
def __repr__(self) -> str:
return f"Intersection(id={self.id}, phase={self.phase}, phase_time={self.phase_time:.1f}s)"
class TrafficEnvironment:
"""
Traffic environment for the reinforcement learning agent.
Simulates a network of intersections, lanes, and vehicles.
"""
def __init__(self, config: Dict[str, Any] = None):
"""
Initialize the traffic environment.
Args:
config: Dictionary with configuration parameters
"""
# Set default config if none provided
self.config = config or {
'duration': 3600, # Simulation duration in seconds
'timestep': 1.0, # Simulation timestep in seconds
'max_vehicles': 1000, # Maximum number of vehicles
'spawn_rate': 0.1, # Vehicle spawn probability per second
'seed': 42, # Random seed
}
# Set random seed
random.seed(self.config['seed'])
np.random.seed(self.config['seed'])
# Initialize intersections and lanes
self.intersections = {}
self.lanes = {}
# Initialize time
self.time = 0.0
self.step_count = 0
# Stats and history
self.stats = {
'total_wait_time': 0.0,
'total_travel_time': 0.0,
'total_vehicles': 0,
'completed_trips': 0,
'throughput': 0,
}
self.history = {
'wait_times': [],
'throughput': [],
'queue_lengths': []
}
# Setup default network if no config provided
if 'network' not in self.config:
self._setup_default_network()
else:
self._load_network(self.config['network'])
logger.info(f"Traffic environment initialized with {len(self.intersections)} "
f"intersections and {len(self.lanes)} lanes")
def _setup_default_network(self) -> None:
"""
Create a simple default traffic network.
This creates a basic 4-way intersection with incoming and outgoing lanes.
"""
# Create a single intersection
intersection = Intersection('central',
incoming_lanes=['north_in', 'south_in', 'east_in', 'west_in'],
outgoing_lanes=['north_out', 'south_out', 'east_out', 'west_out'])
self.intersections['central'] = intersection
# Create lanes
for direction in ['north', 'south', 'east', 'west']:
# Incoming lane (towards intersection)
self.lanes[f'{direction}_in'] = Lane(
lane_id=f'{direction}_in',
length=500.0, # 500 meters
max_speed=13.9, # 50 km/h in m/s
destination='central'
)
# Outgoing lane (away from intersection)
self.lanes[f'{direction}_out'] = Lane(
lane_id=f'{direction}_out',
length=500.0,
max_speed=13.9,
origin='central'
)
logger.info("Created default 4-way intersection network")
def _load_network(self, network_config: Dict[str, Any]) -> None:
"""
Load a network from a configuration dictionary.
Args:
network_config: Dict with intersections and lanes definitions
"""
# Load intersections
for intersection_id, data in network_config.get('intersections', {}).items():
self.intersections[intersection_id] = Intersection(
intersection_id=intersection_id,
incoming_lanes=data.get('incoming_lanes', []),
outgoing_lanes=data.get('outgoing_lanes', [])
)
# Set phase durations if provided
if 'phase_durations' in data:
self.intersections[intersection_id].set_phase_durations(data['phase_durations'])
# Load lanes
for lane_id, data in network_config.get('lanes', {}).items():
self.lanes[lane_id] = Lane(
lane_id=lane_id,
length=data.get('length', 500.0),
max_speed=data.get('max_speed', 13.9),
origin=data.get('origin'),
destination=data.get('destination')
)
logger.info(f"Loaded network with {len(self.intersections)} intersections "
f"and {len(self.lanes)} lanes")
def reset(self) -> np.ndarray:
"""
Reset the environment to initial state.
Returns:
Initial observation
"""
# Reset time
self.time = 0.0
self.step_count = 0
# Clear all lanes (remove vehicles)
for lane in self.lanes.values():
lane.vehicles = []
lane.vehicles_entered = 0
lane.vehicles_exited = 0
lane.occupancy_history = []
# Reset intersections
for intersection in self.intersections.values():
intersection.phase = 0
intersection.phase_time = 0.0
intersection.total_wait_time = 0.0
intersection.total_vehicles = 0
intersection.throughput_history = []
# Reset stats
self.stats = {
'total_wait_time': 0.0,
'total_travel_time': 0.0,
'total_vehicles': 0,
'completed_trips': 0,
'throughput': 0,
}
self.history = {
'wait_times': [],
'throughput': [],
'queue_lengths': []
}
# Spawn initial vehicles
self._spawn_vehicles()
# Get initial observation
return self._get_observation()
def step(self, actions: Dict[str, int] = None) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]:
"""
Take a step in the environment.
Args:
actions: Dict mapping intersection IDs to phase actions
Returns:
Tuple of (observation, reward, done, info)
"""
# Default empty actions if none provided
if actions is None:
actions = {}
# Apply actions to intersections
for intersection_id, action in actions.items():
if intersection_id in self.intersections:
self.intersections[intersection_id].update(
self.config['timestep'], new_phase=action
)
else:
logger.warning(f"Action provided for unknown intersection {intersection_id}")
# Update intersections without explicit actions
for intersection_id, intersection in self.intersections.items():
if intersection_id not in actions:
intersection.update(self.config['timestep'])
# Update all lanes
throughput = 0
for lane_id, lane in self.lanes.items():
# Get the traffic light state affecting this lane
traffic_light_state = 0 # Default
# If lane has a destination intersection, get its state
if lane.destination and lane.destination in self.intersections:
traffic_light_state = self.intersections[lane.destination].phase
# Update the lane and get exited vehicles
exited_vehicles = lane.update(self.config['timestep'], traffic_light_state)
throughput += len(exited_vehicles)
# Handle exited vehicles (transfer to next lane or remove)
for vehicle in exited_vehicles:
# If the vehicle has a route, follow it
if vehicle.route and len(vehicle.route) > 0:
next_lane_id = vehicle.route.pop(0)
if next_lane_id in self.lanes:
self.lanes[next_lane_id].add_vehicle(vehicle)
else:
logger.warning(f"Vehicle tried to enter unknown lane {next_lane_id}")
# Count as completed anyway
self.stats['completed_trips'] += 1
else:
# No route or end of route = completed trip
self.stats['completed_trips'] += 1
self.stats['total_wait_time'] += vehicle.waiting_time
self.stats['total_travel_time'] += vehicle.total_travel_time
# Spawn new vehicles
new_vehicles = self._spawn_vehicles()
self.stats['total_vehicles'] += new_vehicles
# Update time
self.time += self.config['timestep']
self.step_count += 1
# Record history
self.stats['throughput'] = throughput
self.history['throughput'].append(throughput)
total_queue = sum(1 for lane in self.lanes.values()
for vehicle in lane.vehicles if vehicle.speed < 0.5)
self.history['queue_lengths'].append(total_queue)
# Check if simulation is done
done = self.time >= self.config['duration']
# Get observation and reward
observation = self._get_observation()
reward = self._calculate_reward()
# Compile info dictionary
info = {
'time': self.time,
'stats': self.stats.copy(),
'queues': {lane_id: len([v for v in lane.vehicles if v.speed < 0.5])
for lane_id, lane in self.lanes.items()},
'throughput': throughput
}
return observation, reward, done, info
def _spawn_vehicles(self) -> int:
"""
Spawn new vehicles at entrances to the network.
Returns:
Number of vehicles spawned
"""
num_spawned = 0
# Find source lanes (no origin intersection)
source_lanes = [lane_id for lane_id, lane in self.lanes.items()
if lane.origin is None]
# For each source lane, decide whether to spawn a vehicle
for lane_id in source_lanes:
# Check spawn probability
if random.random() < self.config['spawn_rate'] * self.config['timestep']:
# Check if lane has room (no vehicle near the start)
lane = self.lanes[lane_id]
# Only spawn if no vehicle in first 10m of lane
vehicle_in_spawn_area = any(v.position < 10.0 for v in lane.vehicles)
if not vehicle_in_spawn_area:
# Pick a random vehicle type with weights
vehicle_type = random.choices(
['car', 'bus', 'truck', 'motorcycle', 'bicycle'],
weights=[0.75, 0.08, 0.12, 0.04, 0.01],
k=1
)[0]
# Create vehicle
vehicle = Vehicle(
lane=lane_id,
position=0.0,
speed=lane.max_speed * 0.3, # Start at 30% of max speed
vehicle_type=vehicle_type
)
# Pick a random destination (any outgoing lane)
dest_lanes = [lane_id for lane_id, lane in self.lanes.items()
if lane.destination is None]
if dest_lanes:
destination = random.choice(dest_lanes)
vehicle.destination = destination
# Set a simple route (for now just source -> destination)
# In a real system, we'd use a routing algorithm here
vehicle.route = [destination]
# Add to the lane
lane.add_vehicle(vehicle)
num_spawned += 1
return num_spawned
def _get_observation(self) -> Dict[str, np.ndarray]:
"""
Get the current observation of the traffic state.
Returns:
Dictionary mapping intersection IDs to their observations
"""
observations = {}
# For each intersection, create an observation
for intersection_id, intersection in self.intersections.items():
# Get queue lengths for incoming lanes
queue_lengths = []
for lane_id in intersection.incoming_lanes:
if lane_id in self.lanes:
lane = self.lanes[lane_id]
# Count vehicles at or near stop line
queue = sum(1 for v in lane.vehicles if v.speed < 0.5)
queue_lengths.append(queue)
else:
queue_lengths.append(0)
# Get current phase and phase time
phase = intersection.phase
phase_time = intersection.phase_time
phase_remaining = intersection.phase_durations[phase] - phase_time
# Normalize phase time to [0, 1]
norm_phase_time = phase_time / intersection.phase_durations[phase]
# Get incoming lane average speeds
avg_speeds = []
for lane_id in intersection.incoming_lanes:
if lane_id in self.lanes:
avg_speed = self.lanes[lane_id].get_average_speed()
# Normalize by max speed
norm_speed = avg_speed / self.lanes[lane_id].max_speed
avg_speeds.append(norm_speed)
else:
avg_speeds.append(1.0) # Default to free flow
# Combine into observation vector
obs = np.array(
queue_lengths + [phase, norm_phase_time] + avg_speeds,
dtype=np.float32
)
observations[intersection_id] = obs
return observations
def _calculate_reward(self) -> float:
"""
Calculate the reward based on traffic state.
The reward is negative and based on queue lengths, wait times,
and throughput.
Returns:
Reward value (negative = cost)
"""
# Calculate total queue length
total_queue = sum(1 for lane in self.lanes.values()
for vehicle in lane.vehicles if vehicle.speed < 0.5)
# Calculate average travel time of completed trips
avg_travel_time = 0.0
if self.stats['completed_trips'] > 0:
avg_travel_time = self.stats['total_travel_time'] / self.stats['completed_trips']
# Calculate reward components
queue_penalty = -0.1 * total_queue
wait_penalty = -0.01 * avg_travel_time
throughput_reward = 1.0 * self.stats['throughput']
# Combine into final reward
reward = queue_penalty + wait_penalty + throughput_reward
return reward
def render(self, mode: str = 'human') -> None:
"""
Render the environment.
Args:
mode: Rendering mode
"""
if mode == 'human':
# Print simple text representation
print(f"\nTime: {self.time:.1f}s")
for intersection_id, intersection in self.intersections.items():
phase_desc = PHASES[intersection.phase]
print(f"Intersection {intersection_id}: {phase_desc}, "
f"Time in phase: {intersection.phase_time:.1f}s")
for lane_id, lane in self.lanes.items():
queue = sum(1 for v in lane.vehicles if v.speed < 0.5)
print(f"Lane {lane_id}: {len(lane.vehicles)} vehicles, {queue} in queue")
print(f"Throughput: {self.stats['throughput']} vehicles")
print(f"Completed trips: {self.stats['completed_trips']}")
def get_traffic_metrics(self) -> Dict[str, Any]:
"""
Calculate comprehensive traffic metrics.
Returns:
Dictionary of traffic metrics
"""
metrics = {
'time': self.time,
'completed_trips': self.stats['completed_trips'],
'total_vehicles': self.stats['total_vehicles'],
'completion_rate': self.stats['completed_trips'] / max(1, self.stats['total_vehicles']),
'avg_travel_time': self.stats['total_travel_time'] / max(1, self.stats['completed_trips']),
'avg_wait_time': self.stats['total_wait_time'] / max(1, self.stats['completed_trips']),
'throughput': self.stats['throughput'],
'avg_queues': np.mean(self.history['queue_lengths']),
'max_queue': max(self.history['queue_lengths']),
'lane_metrics': {}
}
# Calculate metrics for each lane
for lane_id, lane in self.lanes.items():
metrics['lane_metrics'][lane_id] = {
'avg_occupancy': lane.get_average_occupancy(),
'avg_speed': lane.get_average_speed(),
'flow': lane.vehicles_exited / max(1, self.time / 3600) # vehicles per hour
}
return metrics
class TrafficSignalGymEnv(gym.Env):
"""
OpenAI Gym environment wrapper for traffic signal control.
This provides a standardized interface for reinforcement learning algorithms.
"""
def __init__(self, config: Dict[str, Any] = None):
"""
Initialize the gym environment.
Args:
config: Dictionary with configuration parameters
"""
super(TrafficSignalGymEnv, self).__init__()
# Create traffic environment
self.env = TrafficEnvironment(config)
# Define action space
# Each intersection can set its phase to 0, 1, 2, or 3
self.intersection_ids = list(self.env.intersections.keys())
self.action_space = spaces.Discrete(len(PHASES))
# Define observation space
# Each intersection has incoming lane queues, phase, phase time, speeds
num_incoming_lanes = max(len(intersection.incoming_lanes)
for intersection in self.env.intersections.values())
# Observation includes queue lengths, phase, phase time, and speeds
obs_dim = num_incoming_lanes * 2 + 2 # queue + speed for each lane + phase + phase time
self.observation_space = spaces.Box(
low=0, high=float('inf'), shape=(obs_dim,), dtype=np.float32
)
def reset(self) -> np.ndarray:
"""
Reset the environment.
Returns:
Initial observation
"""
# Reset the traffic environment
observations = self.env.reset()
# Return observation for the first intersection (for single-agent)
return observations[self.intersection_ids[0]]
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]:
"""
Take a step in the environment.
Args:
action: Phase to set for the intersection
Returns:
Tuple of (observation, reward, done, info)
"""
# Convert action to dictionary for the traffic environment
action_dict = {self.intersection_ids[0]: action}
# Step the environment
observations, reward, done, info = self.env.step(action_dict)
# Return observation for the first intersection (for single-agent)
return observations[self.intersection_ids[0]], reward, done, info
def render(self, mode: str = 'human') -> None:
"""
Render the environment.
Args:
mode: Rendering mode
"""
self.env.render(mode)
class DQNTrafficController:
"""
Deep Q-Network agent for traffic signal control.
This implements a reinforcement learning agent that learns
optimal traffic light timings.
"""
def __init__(self, state_size: int, action_size: int,
learning_rate: float = 0.001, gamma: float = 0.95,
epsilon: float = 1.0, epsilon_decay: float = 0.995,
epsilon_min: float = 0.01, batch_size: int = 32,
memory_size: int = 2000):
"""
Initialize the DQN agent.
Args:
state_size: Size of the state vector
action_size: Number of possible actions
learning_rate: Learning rate for the neural network
gamma: Discount factor for future rewards
epsilon: Exploration rate (1.0 = always explore)
epsilon_decay: Rate at which epsilon decreases
epsilon_min: Minimum exploration rate
batch_size: Batch size for training
memory_size: Size of replay memory
"""
self.state_size = state_size
self.action_size = action_size
self.learning_rate = learning_rate
self.gamma = gamma # discount rate
self.epsilon = epsilon # exploration rate
self.epsilon_decay = epsilon_decay
self.epsilon_min = epsilon_min
self.batch_size = batch_size
# Neural network for predicting Q values
self.model = self._build_model()
# Target network for stability
self.target_model = self._build_model()
self.update_target_model()
# Experience replay memory
self.memory = []
self.memory_size = memory_size
logger.info(f"Initialized DQN traffic controller with state_size={state_size}, "
f"action_size={action_size}")
def _build_model(self) -> keras.Model:
"""
Build the neural network model for DQN.
Returns:
Keras Model
"""
model = keras.Sequential([
layers.Dense(24, activation='relu', input_shape=(self.state_size,)),
layers.Dense(24, activation='relu'),
layers.Dense(self.action_size, activation='linear')
])
model.compile(loss='mse', optimizer=keras.optimizers.Adam(learning_rate=self.learning_rate))
return model
def update_target_model(self) -> None:
"""Update the target model to match the main model weights."""
self.target_model.set_weights(self.model.get_weights())