"""
Traffic Flow Simulation using Agent-Based Modeling
====================================================
This simulation models traffic flow using:
- Intelligent Driver Model (IDM) for car-following behavior
- Multiple vehicle agents with varying characteristics
- Traffic lights with configurable timing
- Real-time statistics and visualization
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle, Circle, FancyBboxPatch
from collections import deque
import random
from dataclasses import dataclass
from typing import List, Optional, Tuple
@dataclass
class IDMParameters:
"""Parameters for the Intelligent Driver Model"""
desired_velocity: float = 30.0 # m/s (≈108 km/h)
safe_time_headway: float = 1.5 # seconds
max_acceleration: float = 1.5 # m/s²
comfortable_deceleration: float = 2.0 # m/s²
min_spacing: float = 2.0 # meters
vehicle_length: float = 5.0 # meters
class Vehicle:
"""
Agent representing a vehicle using the Intelligent Driver Model (IDM).
The IDM is a time-continuous car-following model that describes the
acceleration of a vehicle as a function of its own velocity, the net
distance to the leading vehicle, and the velocity difference.
"""
_id_counter = 0
def __init__(self, position: float, velocity: float, lane: int = 0,
params: IDMParameters = None):
self.id = Vehicle._id_counter
Vehicle._id_counter += 1
self.position = position
self.velocity = velocity
self.lane = lane
self.acceleration = 0.0
# IDM parameters with some randomness for variety
self.params = params or IDMParameters()
self.desired_velocity = self.params.desired_velocity + random.uniform(-5, 5)
self.safe_time_headway = self.params.safe_time_headway + random.uniform(-0.2, 0.2)
self.max_acceleration = self.params.max_acceleration * random.uniform(0.8, 1.2)
self.comfortable_deceleration = self.params.comfortable_deceleration
self.min_spacing = self.params.min_spacing
self.vehicle_length = self.params.vehicle_length
# Statistics
self.total_distance = 0.0
self.waiting_time = 0.0
self.time_on_road = 0.0
# Visual properties
self.color = self._generate_color()
def _generate_color(self) -> str:
"""Generate a random realistic car color"""
colors = [
'#2C3E50', # Dark blue
'#E74C3C', # Red
'#3498DB', # Blue
'#2ECC71', # Green
'#F39C12', # Orange
'#9B59B6', # Purple
'#1ABC9C', # Teal
'#34495E', # Dark gray
'#E67E22', # Dark orange
'#95A5A6', # Silver
'#000000', # Black
'#FFFFFF', # White
]
return random.choice(colors)
def calculate_idm_acceleration(self, gap: float, velocity_diff: float) -> float:
"""
Calculate acceleration using the Intelligent Driver Model.
a = a_max * [1 - (v/v0)^4 - (s*/s)^2]
where s* = s0 + v*T + v*Δv / (2*sqrt(a*b))
"""
# Desired dynamical gap s*
s_star = (self.min_spacing +
max(0, self.velocity * self.safe_time_headway +
(self.velocity * velocity_diff) /
(2 * np.sqrt(self.max_acceleration * self.comfortable_deceleration))))
# Free road term
if self.desired_velocity > 0:
free_road_term = (self.velocity / self.desired_velocity) ** 4
else:
free_road_term = 0
# Interaction term
if gap > 0:
interaction_term = (s_star / gap) ** 2
else:
interaction_term = 100 # Emergency braking
# IDM acceleration
acceleration = self.max_acceleration * (1 - free_road_term - interaction_term)
return acceleration
def update(self, dt: float, leader: Optional['Vehicle'] = None,
traffic_light_distance: Optional[float] = None,
traffic_light_green: bool = True):
"""
Update vehicle state for one time step.
"""
self.time_on_road += dt
# Calculate gap and velocity difference to leader
if leader is not None:
gap = leader.position - self.position - leader.vehicle_length
velocity_diff = self.velocity - leader.velocity
else:
gap = float('inf')
velocity_diff = 0
# Base IDM acceleration
self.acceleration = self.calculate_idm_acceleration(gap, velocity_diff)
# Traffic light behavior
if traffic_light_distance is not None and not traffic_light_green:
if 0 < traffic_light_distance < 100:
# Calculate required deceleration to stop
stopping_distance = max(5, traffic_light_distance - self.vehicle_length - 2)
if self.velocity > 0.5:
required_decel = (self.velocity ** 2) / (2 * stopping_distance)
# Override acceleration if we need to stop
traffic_accel = -required_decel
if traffic_accel < self.acceleration:
self.acceleration = traffic_accel
# Clamp acceleration
max_decel = self.comfortable_deceleration * 3 # Emergency braking limit
self.acceleration = np.clip(self.acceleration, -max_decel, self.max_acceleration)
# Update velocity
self.velocity += self.acceleration * dt
self.velocity = max(0, self.velocity)
# Update position
self.position += self.velocity * dt + 0.5 * self.acceleration * dt ** 2
self.total_distance += self.velocity * dt
# Track waiting time
if self.velocity < 0.1:
self.waiting_time += dt
class TrafficLight:
"""Traffic light agent with configurable timing"""
def __init__(self, position: float,
green_duration: float = 30.0,
yellow_duration: float = 3.0,
red_duration: float = 30.0,
initial_offset: float = 0.0):
self.position = position
self.green_duration = green_duration
self.yellow_duration = yellow_duration
self.red_duration = red_duration
self.cycle_time = green_duration + yellow_duration + red_duration
self.time_in_cycle = initial_offset % self.cycle_time
self._update_state()
def _update_state(self):
"""Update light state based on time in cycle"""
t = self.time_in_cycle
if t < self.green_duration:
self.state = 'green'
elif t < self.green_duration + self.yellow_duration:
self.state = 'yellow'
else:
self.state = 'red'
@property
def is_green(self) -> bool:
return self.state == 'green'
@property
def is_red(self) -> bool:
return self.state == 'red'
@property
def is_yellow(self) -> bool:
return self.state == 'yellow'
def get_color(self) -> str:
colors = {'green': '#00FF00', 'yellow': '#FFD700', 'red': '#FF0000'}
return colors[self.state]
def time_until_green(self) -> float:
"""Calculate time until next green light"""
if self.state == 'green':
return 0
t = self.time_in_cycle
if t < self.green_duration:
return 0
elif t < self.green_duration + self.yellow_duration:
return (self.green_duration + self.yellow_duration - t +
self.red_duration)
else:
return self.cycle_time - t
def update(self, dt: float):
"""Update traffic light state"""
self.time_in_cycle = (self.time_in_cycle + dt) % self.cycle_time
self._update_state()
class Road:
"""
Road environment that manages vehicles and traffic lights.
Handles vehicle spawning, removal, and inter-vehicle interactions.
"""
def __init__(self, length: float = 500.0, num_lanes: int = 1):
self.length = length
self.num_lanes = num_lanes
self.vehicles: List[Vehicle] = []
self.traffic_lights: List[TrafficLight] = []
# Spawn control
self.spawn_rate = 0.3 # vehicles per second
self.time_since_spawn = 0.0
self.min_spawn_gap = 15.0 # minimum gap for spawning
# Statistics
self.stats = {
'throughput': deque(maxlen=1000),
'avg_speed': deque(maxlen=100),
'density': deque(maxlen=100),
'flow': deque(maxlen=100),
}
self.completed_vehicles = 0
def add_traffic_light(self, position: float, **kwargs) -> TrafficLight:
"""Add a traffic light at specified position"""
light = TrafficLight(position, **kwargs)
self.traffic_lights.append(light)
return light
def get_leader(self, vehicle: Vehicle) -> Optional[Vehicle]:
"""Find the vehicle directly ahead in the same lane"""
leader = None
min_gap = float('inf')
for v in self.vehicles:
if v.id != vehicle.id and v.lane == vehicle.lane:
gap = v.position - vehicle.position - v.vehicle_length
if 0 < gap < min_gap:
min_gap = gap
leader = v
return leader
def get_next_light(self, vehicle: Vehicle) -> Tuple[Optional[TrafficLight], float]:
"""Get the next traffic light ahead of the vehicle"""
next_light = None
min_distance = float('inf')
for light in self.traffic_lights:
distance = light.position - vehicle.position
if 0 < distance < min_distance:
min_distance = distance
next_light = light
if next_light:
return next_light, min_distance
return None, float('inf')
def can_spawn_vehicle(self) -> bool:
"""Check if there's enough space to spawn a new vehicle"""
for v in self.vehicles:
if v.position < self.min_spawn_gap + 10:
return False
return True
def spawn_vehicle(self) -> Optional[Vehicle]:
"""Spawn a new vehicle at the start of the road"""
if not self.can_spawn_vehicle():
return None
initial_velocity = random.uniform(15, 25)
vehicle = Vehicle(
position=0.0,
velocity=initial_velocity,
lane=0
)
self.vehicles.append(vehicle)
return vehicle
def update(self, dt: float):
"""Update all agents in the simulation"""
# Spawn new vehicles
self.time_since_spawn += dt
if self.time_since_spawn >= 1.0 / self.spawn_rate:
if random.random() < 0.8: # 80% chance to spawn
self.spawn_vehicle()
self.time_since_spawn = 0
# Update traffic lights
for light in self.traffic_lights:
light.update(dt)
# Update vehicles
vehicles_to_remove = []
speeds = []
for vehicle in self.vehicles:
leader = self.get_leader(vehicle)
next_light, light_distance = self.get_next_light(vehicle)
is_green = True
if next_light:
is_green = next_light.is_green
vehicle.update(dt, leader,
traffic_light_distance=light_distance if next_light else None,
traffic_light_green=is_green)
speeds.append(vehicle.velocity)
# Check if vehicle has left the road
if vehicle.position > self.length + 50:
vehicles_to_remove.append(vehicle)
# Remove completed vehicles
for vehicle in vehicles_to_remove:
self.vehicles.remove(vehicle)
self.completed_vehicles += 1
self.stats['throughput'].append(vehicle.total_distance / vehicle.time_on_road
if vehicle.time_on_road > 0 else 0)
# Update statistics
if speeds:
self.stats['avg_speed'].append(np.mean(speeds))
self.stats['density'].append(len(self.vehicles) / (self.length / 1000))
# Flow = density * average speed
if self.stats['density'] and self.stats['avg_speed']:
density = self.stats['density'][-1]
avg_speed = self.stats['avg_speed'][-1]
self.stats['flow'].append(density * avg_speed)
class TrafficVisualization:
"""Handles all visualization aspects of the traffic simulation"""
def __init__(self, road: Road):
self.road = road
self.time = 0.0
# Setup figure with subplots
self.fig = plt.figure(figsize=(16, 10))
self.fig.patch.set_facecolor('#1a1a2e')
# Create grid for subplots
gs = self.fig.add_gridspec(3, 3, height_ratios=[2, 1, 1],
hspace=0.3, wspace=0.3)
# Main road view
self.ax_road = self.fig.add_subplot(gs[0, :])
# Speed distribution
self.ax_speed_hist = self.fig.add_subplot(gs[1, 0])
# Time series
self.ax_timeseries = self.fig.add_subplot(gs[1, 1])
# Fundamental diagram (flow vs density)
self.ax_fundamental = self.fig.add_subplot(gs[1, 2])
# Statistics panel
self.ax_stats = self.fig.add_subplot(gs[2, :])
self._setup_style()
# Data storage
self.time_history = deque(maxlen=300)
self.speed_history = deque(maxlen=300)
self.density_history = deque(maxlen=300)
self.flow_history = deque(maxlen=300)
def _setup_style(self):
"""Setup plot styling"""
dark_style = {
'axes.facecolor': '#16213e',
'axes.edgecolor': '#0f3460',
'axes.labelcolor': 'white',
'text.color': 'white',
'xtick.color': 'white',
'ytick.color': 'white',
'grid.color': '#0f3460',
}
for ax in [self.ax_road, self.ax_speed_hist, self.ax_timeseries,
self.ax_fundamental, self.ax_stats]:
ax.set_facecolor(dark_style['axes.facecolor'])
ax.tick_params(colors='white')
for spine in ax.spines.values():
spine.set_color(dark_style['axes.edgecolor'])
def draw_road(self):
"""Draw the road and all vehicles"""
self.ax_road.clear()
self.ax_road.set_facecolor('#16213e')
road_height = 20
margin = 30
# Draw road background
road_bg = Rectangle((-margin, -road_height/2),
self.road.length + 2*margin, road_height,
facecolor='#2d3436', edgecolor='#636e72', linewidth=2)
self.ax_road.add_patch(road_bg)
# Draw lane markings
for x in range(0, int(self.road.length), 15):
marking = Rectangle((x, -1), 8, 2, facecolor='white', alpha=0.8)
self.ax_road.add_patch(marking)
# Draw road edges
self.ax_road.axhline(y=road_height/2 - 2, color='white', linewidth=3)
self.ax_road.axhline(y=-road_height/2 + 2, color='white', linewidth=3)
# Draw traffic lights
for light in self.road.traffic_lights:
# Light pole
self.ax_road.plot([light.position, light.position],
[road_height/2, road_height/2 + 8],
color='#636e72', linewidth=4)
# Light housing
housing = FancyBboxPatch((light.position - 4, road_height/2 + 5),
8, 10, boxstyle="round,pad=0.5",
facecolor='#2d3436', edgecolor='#636e72')
self.ax_road.add_patch(housing)
# Light bulb
bulb_color = light.get_color()
glow_alpha = 0.8
bulb = Circle((light.position, road_height/2 + 10), 3,
color=bulb_color, alpha=glow_alpha)
self.ax_road.add_patch(bulb)
# Glow effect
glow = Circle((light.position, road_height/2 + 10), 5,
color=bulb_color, alpha=0.3)
self.ax_road.add_patch(glow)
# Stop line
self.ax_road.axvline(x=light.position - 5,
ymin=0.3, ymax=0.7,
color='white', linewidth=2, linestyle='-')
# Draw vehicles
for vehicle in self.road.vehicles:
self._draw_vehicle(vehicle, road_height)
# Draw start/end markers
self.ax_road.annotate('START', xy=(0, -road_height/2 - 5),
fontsize=10, ha='center', color='#00ff88',
fontweight='bold')
self.ax_road.annotate('END', xy=(self.road.length, -road_height/2 - 5),
fontsize=10, ha='center', color='#ff6b6b',
fontweight='bold')
# Set limits and labels
self.ax_road.set_xlim(-margin, self.road.length + margin)
self.ax_road.set_ylim(-road_height, road_height + 10)
self.ax_road.set_title(f'Traffic Flow Simulation | Time: {self.time:.1f}s',
color='white', fontsize=14, fontweight='bold')
self.ax_road.set_xlabel('Position (m)', color='white')
self.ax_road.set_yticks([])
def _draw_vehicle(self, vehicle: Vehicle, road_height: float):
"""Draw a single vehicle with visual indicators"""
x = vehicle.position - vehicle.vehicle_length
y = -4
w = vehicle.vehicle_length
h = 8
# Vehicle body
car = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.5",
facecolor=vehicle.color, edgecolor='#1a1a2e',
linewidth=1.5)
self.ax_road.add_patch(car)
# Windshield
windshield = Rectangle((x + w - 1.5, y + 1), 1.2, h - 2,
facecolor='#74b9ff', alpha=0.7)
self.ax_road.add_patch(windshield)
# Headlights
for ly in [y + 1.5, y + h - 1.5]:
light = Circle((x + w - 0.5, ly), 0.5, color='#ffeaa7', alpha=0.9)
self.ax_road.add_patch(light)
# Brake lights (when decelerating)
if vehicle.acceleration < -0.5:
for ly in [y + 1.5, y + h - 1.5]:
brake = Circle((x + 0.3, ly), 0.6, color='#ff4757', alpha=0.9)
self.ax_road.add_patch(brake)
# Speed indicator (colored bar above vehicle)
speed_ratio = min(vehicle.velocity / 35, 1)
speed_color = plt.cm.RdYlGn(speed_ratio)
speed_bar = Rectangle((x, y + h + 1), w * speed_ratio, 2,
facecolor=speed_color, alpha=0.8)
self.ax_road.add_patch(speed_bar)
def draw_speed_distribution(self):
"""Draw histogram of vehicle speeds"""
self.ax_speed_hist.clear()
self.ax_speed_hist.set_facecolor('#16213e')
if self.road.vehicles:
speeds = [v.velocity for v in self.road.vehicles]
self.ax_speed_hist.hist(speeds, bins=12, range=(0, 40),
color='#00cec9', edgecolor='#1a1a2e',
alpha=0.8)
avg_speed = np.mean(speeds)
self.ax_speed_hist.axvline(avg_speed, color='#ffeaa7',
linestyle='--', linewidth=2,
label=f'Avg: {avg_speed:.1f} m/s')
self.ax_speed_hist.legend(loc='upper right', facecolor='#16213e',
labelcolor='white')
self.ax_speed_hist.set_title('Speed Distribution', color='white', fontsize=11)
self.ax_speed_hist.set_xlabel('Speed (m/s)', color='white')
self.ax_speed_hist.set_ylabel('Count', color='white')
self.ax_speed_hist.set_xlim(0, 40)
self.ax_speed_hist.grid(True, alpha=0.3, color='#0f3460')
def draw_timeseries(self):
"""Draw time series of traffic metrics"""
self.ax_timeseries.clear()
self.ax_timeseries.set_facecolor('#16213e')
if len(self.time_history) > 1:
times = list(self.time_history)
# Average speed
speeds = list(self.speed_history)
self.ax_timeseries.plot(times, speeds, color='#00cec9',
linewidth=2, label='Avg Speed (m/s)')
# Density on secondary axis
ax2 = self.ax_timeseries.twinx()
ax2.set_facecolor('#16213e')
densities = list(self.density_history)
ax2.plot(times, densities, color='#fd79a8',
linewidth=2, label='Density (veh/km)', alpha=0.8)
ax2.set_ylabel('Density (veh/km)', color='#fd79a8')
ax2.tick_params(axis='y', colors='#fd79a8')
ax2.set_ylim(0, 100)
self.ax_timeseries.set_title('Traffic Metrics Over Time', color='white', fontsize=11)
self.ax_timeseries.set_xlabel('Time (s)', color='white')
self.ax_timeseries.set_ylabel('Speed (m/s)', color='#00cec9')
self.ax_timeseries.tick_params(axis='y', colors='#00cec9')
self.ax_timeseries.set_ylim(0, 35)
self.ax_timeseries.grid(True, alpha=0.3, color='#0f3460')
self.ax_timeseries.legend(loc='upper left', facecolor='#16213e',
labelcolor='white', fontsize=8)
def draw_fundamental_diagram(self):
"""Draw the fundamental diagram (flow vs density)"""
self.ax_fundamental.clear()
self.ax_fundamental.set_facecolor('#16213e')
if len(self.density_history) > 5:
densities = list(self.density_history)
flows = list(self.flow_history)
# Color by recency
colors = plt.cm.viridis(np.linspace(0, 1, len(densities)))
self.ax_fundamental.scatter(densities, flows, c=colors,
s=20, alpha=0.7, edgecolors='none')
# Theoretical curve (simplified Greenshields model)
if densities:
max_density = max(100, max(densities) * 1.2)
k = np.linspace(0, max_density, 100)
# v = v_free * (1 - k/k_jam) -> q = k * v
v_free = 30
k_jam = 150
q_theory = k * v_free * (1 - k/k_jam)
q_theory = np.maximum(q_theory, 0)
self.ax_fundamental.plot(k, q_theory, '--', color='#ffeaa7',
alpha=0.6, linewidth=1.5,
label='Theoretical')
self.ax_fundamental.set_title('Fundamental Diagram', color='white', fontsize=11)
self.ax_fundamental.set_xlabel('Density (veh/km)', color='white')
self.ax_fundamental.set_ylabel('Flow (veh/h)', color='white')
self.ax_fundamental.set_xlim(0, 120)
self.ax_fundamental.set_ylim(0, max(2000, max(self.flow_history) * 1.2)
if self.flow_history else 2000)
self.ax_fundamental.grid(True, alpha=0.3, color='#0f3460')
self.ax_fundamental.legend(loc='upper right', facecolor='#16213e',
labelcolor='white', fontsize=8)
def draw_statistics(self):
"""Draw statistics panel"""
self.ax_stats.clear()
self.ax_stats.set_facecolor('#16213e')
self.ax_stats.axis('off')
# Calculate statistics
num_vehicles = len(self.road.vehicles)
if self.road.vehicles:
speeds = [v.velocity for v in self.road.vehicles]
avg_speed = np.mean(speeds)
std_speed = np.std(speeds)
max_speed = np.max(speeds)
min_speed = np.min(speeds)
stopped = sum(1 for v in self.road.vehicles if v.velocity < 0.5)
# Congestion level
density = num_vehicles / (self.road.length / 1000)
if density < 25:
congestion = "Free Flow 🟢"
congestion_color = '#00ff88'
elif density < 50:
congestion = "Moderate 🟡"
congestion_color = '#ffeaa7'
else:
congestion = "Congested 🔴"
congestion_color = '#ff6b6b'
else:
avg_speed = std_speed = max_speed = min_speed = stopped = 0
density = 0
congestion = "Empty"
congestion_color = '#636e72'
# Traffic light status
light_status = []
for i, light in enumerate(self.road.traffic_lights):
status = f"Light {i+1}: {light.state.upper()}"
if light.state == 'green':
status += " 🟢"
elif light.state == 'yellow':
status += " 🟡"
else:
status += " 🔴"
light_status.append(status)
# Create statistics text
stats_text = (
f"{'─' * 20} TRAFFIC STATISTICS {'─' * 20}\n\n"
f" 🚗 Active Vehicles: {num_vehicles:>5} "
f" ⏹️ Stopped: {stopped:>5}\n"
f" 📊 Avg Speed: {avg_speed:>8.1f} m/s "
f" 📈 Std Dev: {std_speed:>6.1f} m/s\n"
f" 🚀 Max Speed: {max_speed:>8.1f} m/s "
f" 🐢 Min Speed: {min_speed:>6.1f} m/s\n"
f" 📍 Density: {density:>10.1f} veh/km "
f" ✅ Completed: {self.road.completed_vehicles:>5}\n\n"
f" {' │ '.join(light_status)}\n"
)
self.ax_stats.text(0.5, 0.7, stats_text, transform=self.ax_stats.transAxes,
fontsize=11, fontfamily='monospace', color='white',
verticalalignment='center', horizontalalignment='center')
# Congestion indicator
self.ax_stats.text(0.5, 0.15, f"Traffic Status: {congestion}",
transform=self.ax_stats.transAxes,
fontsize=14, fontweight='bold', color=congestion_color,
verticalalignment='center', horizontalalignment='center')
def update(self, dt: float):
"""Update all visualizations"""
self.time += dt
# Store history
self.time_history.append(self.time)
if self.road.vehicles:
self.speed_history.append(np.mean([v.velocity for v in self.road.vehicles]))
else:
self.speed_history.append(0)
self.density_history.append(len(self.road.vehicles) / (self.road.length / 1000))
if self.road.stats['flow']:
self.flow_history.append(self.road.stats['flow'][-1] * 3600 / 1000) # Convert to veh/h
else:
self.flow_history.append(0)
# Redraw all components
self.draw_road()
self.draw_speed_distribution()
self.draw_timeseries()
self.draw_fundamental_diagram()
self.draw_statistics()
class TrafficSimulation:
"""Main simulation controller"""
def __init__(self, road_length: float = 500.0, dt: float = 0.1):
self.dt = dt
self.road = Road(length=road_length, num_lanes=1)
self.visualization = TrafficVisualization(self.road)
# Setup traffic lights with staggered timing
self.road.add_traffic_light(180, green_duration=25, red_duration=25,
initial_offset=0)
self.road.add_traffic_light(320, green_duration=20, red_duration=30,
initial_offset=15)
# Adjust spawn rate
self.road.spawn_rate = 0.35
def update(self, frame):
"""Update simulation state and visualization"""
# Run multiple physics updates per frame for smoother simulation
for _ in range(2):
self.road.update(self.dt)
self.visualization.update(self.dt * 2)
return []
def run(self):
"""Run the simulation"""
print("=" * 60)
print(" TRAFFIC FLOW SIMULATION - Agent-Based Model")
print("=" * 60)
print("\n📊 Simulation Features:")
print(" • Intelligent Driver Model (IDM) for car following")
print(" • Multiple traffic lights with configurable timing")
print(" • Real-time statistics and visualization")
print(" • Fundamental diagram (flow vs density)")
print("\n🚗 Vehicle behaviors:")
print(" • Accelerate towards desired speed")
print(" • Maintain safe following distance")
print(" • Stop at red lights")
print(" • React to leading vehicles")
print("\n📍 Close the window to stop the simulation")
print("=" * 60)
ani = animation.FuncAnimation(
self.visualization.fig,
self.update,
interval=50, # 50ms between frames = 20 FPS
blit=False,
cache_frame_data=False
)
plt.show()
def main():
"""Entry point for the simulation"""
simulation = TrafficSimulation(road_length=500.0, dt=0.1)
simulation.run()
if __name__ == "__main__":
main()