This is a great request! The Nagel-Schreckenberg (NS) cellular automaton is a classic model in traffic flow simulation that exhibits interesting phenomena like the emergence of traffic jams from nowhere (phantom traffic jams).
Let me break down the model:
Nagel-Schreckenberg Model Rules:
- Acceleration: If a car's velocity is less than maximum velocity (v_max) and the distance to the car ahead is greater than the current velocity, increase velocity by 1.
- Deceleration: If the distance to the next car is less than or equal to the current velocity, reduce velocity to distance - 1.
- Randomization: With some probability p, reduce velocity by 1 (this creates the phantom jams).
- Movement: Move the car forward by its velocity.
Key parameters:
- Road length (L)
- Number of cars (N)
- Maximum velocity (v_max)
- Randomization probability (p)
- Time steps to simulate
I'll create a comprehensive simulation with:
- The basic model implementation
- Visualization of traffic over time
- Space-time diagram showing traffic patterns
- Metrics like average velocity, traffic flow
- Animation showing the circular road
Let me write the code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle
from collections import deque
class NagelSchreckenberg:
def __init__(self, road_length=100, num_cars=25, v_max=5, p_random=0.1):
"""
Initialize the Nagel-Schreckenberg model
Parameters:
- road_length: length of the circular road
- num_cars: number of cars on the road
- v_max: maximum velocity of cars
- p_random: probability of random deceleration
"""
self.L = road_length
self.N = num_cars
self.v_max = v_max
self.p = p_random
# Initialize car positions randomly on the circular road
self.positions = np.sort(np.random.choice(road_length, num_cars, replace=False))
self.velocities = np.random.randint(0, v_max + 1, num_cars)
self.time = 0
self.history = []
self.velocity_history = []
self.flow_history = []
def get_gap(self, car_idx):
"""Get the gap to the next car ahead"""
python
next_car = (car_idx + 1) % self.N
gap = (self.positions[next_car] - self.positions[car_idx]) % self.L
return gap
def step(self):
"""Perform one time step of the simulation"""
# Accelerate all cars up to max velocity
self.velocities = np.minimum(self.velocities + 1, self.v_max)
# Brake if the gap ahead is too small
for i in range(self.N):
gap = self.get_gap(i)
if gap < self.velocities[i]:
self.velocities[i] = gap - 1
# Apply random slowdown with probability p
random_mask = np.random.random(self.N) < self.p
self.velocities[random_mask] = np.maximum(self.velocities[random_mask] - 1, 0)
# Update positions based on velocities
self.positions = (self.positions + self.velocities) % self.L
# Store current state in history
self.history.append(self.positions.copy())
self.velocity_history.append(self.velocities.copy())
# Compute flow as the total distance traveled by all cars
flow = np.sum(self.velocities)
self.flow_history.append(flow)
The flow calculation captures how many cars pass through per time step, then the simulation runs for the specified number of steps. After that, I extract average velocity and density metrics, initialize the model with 25 cars on a 100-unit road, run it for 500 steps, and visualize the results through space-time diagrams and velocity trends to show traffic jam formation. num_cars == 0:
flows.append(0)
velocities_by_density.append(0)
else:
ns_temp = NagelSchreckenberg(road_length=ns.L, num_cars=num_cars,
v_max=ns.v_max, p_random=ns.p)
ns_temp.simulate(200)
avg_flow = np.mean(ns_temp.flow_history[-50:])
avg_vel = np.mean(ns_temp.velocity_history[-50:])
flows.append(avg_flow)
velocities_by_density.append(avg_vel)
ax.plot(densities, flows, 'o-', linewidth=2, markersize=6)
ax.set_xlabel('Density')
For each density value, I'm creating a temporary simulation to measure the equilibrium flow and velocity. After letting the system stabilize for 200 steps, I average the last 50 measurements to get stable metrics, then plot the fundamental diagram showing how flow varies with density.
I'm also printing out the simulation statistics and setting up an animation to visualize the traffic dynamics on the road.
For the animation, I'm defining a function to draw the current road state at each time step. The road itself is rendered as a gray rectangle, and individual cars are positioned along it with colors indicating their velocity—using a red-yellow-green colormap where green represents faster movement and red represents slower speeds. Each car is drawn as a rectangle scaled appropriately for visibility.
The animate function handles the frame updates by advancing the simulation, redrawing the road visualization with updated positions and velocities, and then plotting the historical velocity data for each vehicle on a separate graph to track how speeds have changed over time. I'm creating a heatmap visualization to show traffic density patterns across space and time. I'll run a longer simulation with 25 cars on a 100-unit road and convert the trajectory history into a 2D grid that bins positions spatially and temporally to reveal density variations.
The visualization uses an inferno colormap where brighter regions indicate higher vehicle concentrations. I'm also preparing a second heatmap to display velocity patterns across the same space-time domain.
For the velocity heatmap, I'm extracting the velocity history and creating another 2D array with matching dimensions. For each timestep, I iterate through vehicle positions and velocities, mapping each vehicle's velocity to its corresponding spatial bin. The velocity map uses a red-yellow-green colormap scaled from 0 to the maximum velocity, with the extent matching the spatial and temporal ranges of the density visualization.
After rendering the heatmap with appropriate axis labels and a colorbar, I save the figure at high resolution and display it. Then I'm setting up a second figure with a 2x2 grid to analyze how different randomization probabilities affect phantom jam formation, comparing results across probability values of 0.0, 0.05, 0.1, and 0.3.
In the first subplot, I plot the flow history for each probability level to see how randomization impacts traffic throughput. The second subplot shows average velocity evolution over time for each scenario, revealing how driver randomness affects overall speed patterns. I'm continuing with additional comparisons to fully characterize the relationship between randomization and traffic dynamics.
For the space-time diagrams, I visualize individual car trajectories under two conditions: with p = 0.0 showing clean linear paths typical of free flow, and with p = 0.1 displaying the characteristic triangular wave patterns that emerge from phantom traffic jams. These visualizations make the qualitative difference between deterministic and stochastic driving behavior immediately apparent.
After plotting, I finalize the figure layout and save it at high resolution, then iterate through each randomization probability to compute key statistics from the stabilized portion of the simulation (after the first 100 steps). For each p value, I calculate mean velocity, average flow rate, and velocity variance to quantitatively compare how randomness affects traffic dynamics.</think>
# Nagel-Schreckenberg Traffic Simulation
I'll create a comprehensive traffic flow simulation showing phantom jam emergence:
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle, FancyArrowPatch
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches
class NagelSchreckenberg:
"""
Nagel-Schreckenberg cellular automaton for traffic flow.
Update rules (per time step):
1. Acceleration: v → min(v+1, v_max) if gap > v
2. Deceleration: v → min(v, gap-1) to avoid collision
3. Randomization: v → max(v-1, 0) with probability p
4. Movement: x → x + v (mod L)
"""
def __init__(self, road_length=100, num_cars=25, v_max=5, p_random=0.1):
self.L = road_length
self.N = num_cars
self.v_max = v_max
self.p = p_random
# Initialize random positions (sorted for easier gap calculation)
self.positions = np.sort(np.random.choice(road_length, num_cars, replace=False))
self.velocities = np.random.randint(0, v_max + 1, num_cars)
self.time = 0
self.history = []
self.velocity_history = []
self.flow_history = []
def get_gap(self, car_idx):
"""Calculate gap to next car (circular road)"""
next_car_idx = (car_idx + 1) % self.N
gap = (self.positions[next_car_idx] - self.positions[car_idx]) % self.L
return gap
def step(self):
"""Execute one time step"""
# Rule 1: Acceleration
self.velocities = np.minimum(self.velocities + 1, self.v_max)
# Rule 2: Deceleration (collision avoidance)
for i in range(self.N):
gap = self.get_gap(i)
if gap <= self.velocities[i]:
self.velocities[i] = gap - 1
self.velocities[i] = max(self.velocities[i], 0)
# Rule 3: Randomization (creates traffic instability)
random_mask = np.random.random(self.N) < self.p
self.velocities[random_mask] = np.maximum(self.velocities[random_mask] - 1, 0)
# Rule 4: Movement
self.positions = (self.positions + self.velocities) % self.L
# Record data
self.history.append(self.positions.copy())
self.velocity_history.append(self.velocities.copy())
self.flow_history.append(np.sum(self.velocities) / self.L)
self.time += 1
def simulate(self, steps):
"""Run simulation for N steps"""
for _ in range(steps):
self.step()
# ============================================================================
# VISUALIZATION 1: Comprehensive Analysis
# ============================================================================
print("=" * 70)
print("NAGEL-SCHRECKENBERG TRAFFIC FLOW SIMULATION")
print("=" * 70)
np.random.seed(42)
ns = NagelSchreckenberg(road_length=100, num_cars=25, v_max=5, p_random=0.1)
ns.simulate(500)
fig = plt.figure(figsize=(16, 12))
gs = fig.add_gridspec(3, 3, hspace=0.35, wspace=0.3)
# 1. Space-Time Diagram (Main visualization)
ax1 = fig.add_subplot(gs[0:2, 0:2])
history_array = np.array(ns.history)
# Plot with gradient coloring to show traffic jam formation
for car_idx in range(ns.N):
# Color by density around car
density_color = []
for t in range(len(ns.history)):
# Simple local density
local_pos = history_array[t, car_idx]
neighbors = np.sum(np.abs(history_array[t] - local_pos) < 5)
density_color.append(neighbors / ns.N)
scatter = ax1.scatter(range(len(ns.history)), history_array[:, car_idx],
c=density_color, cmap='RdYlGn_r', s=10, alpha=0.7)
ax1.set_xlabel('Time Step', fontsize=11, fontweight='bold')
ax1.set_ylabel('Road Position', fontsize=11, fontweight='bold')
ax1.set_title('Space-Time Diagram: Phantom Traffic Jam Emergence\n(Red regions = jams)',
fontsize=12, fontweight='bold')
ax1.grid(True, alpha=0.3)
cbar = plt.colorbar(scatter, ax=ax1)
cbar.set_label('Local Density', fontsize=10)
# 2. Velocity Evolution
ax2 = fig.add_subplot(gs[0, 2])
velocities_array = np.array(ns.velocity_history)
mean_vel = np.mean(velocities_array, axis=1)
max_vel = np.max(velocities_array, axis=1)
min_vel = np.min(velocities_array, axis=1)
ax2.plot(mean_vel, 'b-', linewidth=2, label='Mean')
ax2.fill_between(range(len(mean_vel)), min_vel, max_vel, alpha=0.3, color='blue')
ax2.set_xlabel('Time Step', fontsize=10)
ax2.set_ylabel('Velocity', fontsize=10)
ax2.set_title('Velocity Dynamics', fontweight='bold')
ax2.legend(fontsize=9)
ax2.grid(True, alpha=0.3)
ax2.set_ylim([-0.5, ns.v_max + 1])
# 3. Traffic Flow
ax3 = fig.add_subplot(gs[1, 2])
flow = np.array(ns.flow_history)
ax3.plot(flow, 'g-', linewidth=2)
ax3.fill_between(range(len(flow)), flow, alpha=0.3, color='green')
ax3.set_xlabel('Time Step', fontsize=10)
ax3.set_ylabel('Flow (cars/step)', fontsize=10)
ax3.set_title('Traffic Flow', fontweight='bold')
ax3.grid(True, alpha=0.3)
# 4. Velocity Distribution (Histogram)
ax4 = fig.add_subplot(gs[2, 0])
ax4.hist(velocities_array[-100:].flatten(), bins=ns.v_max+1,
color='skyblue', edgecolor='black', alpha=0.7)
ax4.set_xlabel('Velocity', fontsize=10)
ax4.set_ylabel('Frequency', fontsize=10)
ax4.set_title('Velocity Distribution (Last 100 steps)', fontweight='bold')
ax4.grid(True, alpha=0.3, axis='y')
# 5. Headway Distribution (gap between cars)
ax5 = fig.add_subplot(gs[2, 1])
final_positions = history_array[-1]
headways = []
for i in range(ns.N):
gap = ns.get_gap(i)
headways.append(gap)
ax5.hist(headways, bins=15, color='salmon', edgecolor='black', alpha=0.7)
ax5.set_xlabel('Headway (gap to next car)', fontsize=10)
ax5.set_ylabel('Frequency', fontsize=10)
ax5.set_title('Headway Distribution', fontweight='bold')
ax5.grid(True, alpha=0.3, axis='y')
# 6. Statistics
ax6 = fig.add_subplot(gs[2, 2])
ax6.axis('off')
stats_text = f"""
STATISTICS
Road Length: {ns.L}
Num. Vehicles: {ns.N}
Density: {ns.N/ns.L:.3f} cars/unit
Max Velocity: {ns.v_max}
Random Decel. Prob: {ns.p}
Results (Last 100 steps):
Avg Velocity: {np.mean(mean_vel[-100:]):.2f}
Avg Flow: {np.mean(flow[-100:]):.3f}
Velocity Std: {np.std(velocities_array[-100:]):.2f}
Observations:
• Phantom jams emerge
spontaneously
• Non-linear dynamics
• Self-organized patterns
"""
ax6.text(0.1, 0.5, stats_text, fontsize=9, family='monospace',
verticalalignment='center', bbox=dict(boxstyle='round',
facecolor='wheat', alpha=0.5))
plt.suptitle('Nagel-Schreckenberg Traffic Flow Model: Phantom Jam Analysis',
fontsize=14, fontweight='bold', y=0.995)
plt.savefig('traffic_ns_analysis.png', dpi=300, bbox_inches='tight')
print("✓ Saved: traffic_ns_analysis.png")
plt.show()
# ============================================================================
# VISUALIZATION 2: Road State Animation
# ============================================================================
print("\nGenerating animation...")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 8),
gridspec_kw={'height_ratios': [1, 2.5]})
ns_anim = NagelSchreckenberg(road_length=100, num_cars=25, v_max=5, p_random=0.1)
def animate(frame):
ns_anim.step()
# Top panel: Road visualization
ax1.clear()
# Draw road
road_rect = Rectangle((0, -0.3), ns_anim.L, 0.6,
edgecolor='black', facecolor='lightgray',
linewidth=2, alpha=0.3)
ax1.add_patch(road_rect)
# Draw cars with color gradient by velocity
colors = plt.cm.RdYlGn(ns_anim.velocities / ns_anim.v_max)
for pos, vel, color in zip(ns_anim.positions, ns_anim.velocities, colors):
# Car body
car = Rectangle((pos - 1.5, -0.15), 3, 0.3,
edgecolor='black', facecolor=color, linewidth=1.5, alpha=0.9)
ax1.add_patch(car)
# Velocity label
ax1.text(pos, 0, f'{int(vel)}', ha='center', va='center',
fontsize=8, fontweight='bold')
ax1.set_xlim(-5, ns_anim.L + 5)
ax1.set_ylim(-1, 1)
ax1.set_aspect('equal')
ax1.axis('off')
avg_vel = np.mean(ns_anim.velocities)
ax1.text(ns_anim.L/2, 0.7,
f'Time: {ns_anim.time} | Avg Velocity: {avg_vel:.1f} | Flow: {np.mean(ns_anim.velocities)/ns_anim.L:.2f}',
ha='center', fontsize=11, fontweight='bold',
bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.7))
# Bottom panel: Space-time trajectory
ax2.clear()
history_array = np.array(ns_anim.history)
for car_idx in range(ns_anim.N):
ax2.plot(range(ns_anim.time), history_array[:, car_idx],
'o-', markersize=1, linewidth=0.8, alpha=0.6)
ax2.set_xlabel('Time Step', fontsize=10)
ax2.set_ylabel('Position', fontsize=10)
ax2.set_title('Vehicle Trajectories: Triangular patterns indicate slowing waves (jams)',
fontsize=11, fontweight='bold')
ax2.set_xlim(0, 250)
ax2.set_ylim(0, ns_anim.L)
ax2.grid(True, alpha=0.3)
return []
anim = animation.FuncAnimation(fig, animate, frames=250, interval=50, blit=False)
plt.tight_layout()
try:
anim.save('traffic_ns_animation.gif', writer='pillow', fps=20, dpi=80)
print("✓ Saved: traffic_ns_animation.gif")
except:
print("⚠ Could not save animation")
plt.show()
# ============================================================================
# VISUALIZATION 3: Effect of Randomization Parameter
# ============================================================================
print("\nAnalyzing effect of randomization probability...")
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
probabilities = [0.0, 0.05, 0.1, 0.2]
results = {}
for p in probabilities:
print(f" Simulating with p = {p}...", end=" ")
ns_temp = NagelSchreckenberg(road_length=100, num_cars=25, v_max=5, p_random=p)
ns_temp.simulate(400)
results[p] = ns_temp
print("done")
# Row 1: Flow comparison
ax = axes[0, 0]
for p in probabilities:
flow = np.array(results[p].flow_history)
ax.plot(flow, label=f'p = {p}', linewidth=2, alpha=0.8)
ax.set_xlabel('Time Step', fontsize=10, fontweight='bold')
ax.set_ylabel('Flow (vehicles/step)', fontsize=10, fontweight='bold')
ax.set_title('Traffic Flow vs Randomization Probability', fontweight='bold')
ax.legend(fontsize=9)
ax.grid(True, alpha=0.3)
# Row 1: Velocity comparison
ax = axes[0, 1]
for p in probabilities:
velocities_array = np.array(results[p].velocity_history)
mean_vel = np.mean(velocities_array, axis=1)
ax.plot(mean_vel, label=f'p = {p}', linewidth=2, alpha=0.8)
ax.set_xlabel('Time Step', fontsize=10, fontweight='bold')
ax.set_ylabel('Average Velocity', fontsize=10, fontweight='bold')
ax.set_title('Velocity Evolution vs Randomization Probability', fontweight='bold')
ax.legend(fontsize=9)
ax.grid(True, alpha=0.3)
# Row 2: Space-time diagrams
ax = axes[1, 0]
history_array = np.array(results[0.0].history)
for car_idx in range(results[0.0].N):
ax.plot(history_array[:, car_idx], 'o-', markersize=0.8, linewidth=0.5, alpha=0.6)
ax.set_xlabel('Time Step', fontsize=10)
ax.set_ylabel('Position', fontsize=10)
ax.set_title('p = 0.0: Free Flow (Parallel lines)', fontweight='bold')
ax.grid(True, alpha=0.3)
ax = axes[1, 1]
history_array = np.array(results[0.1].history)
for car_idx in range(results[0.1].N):
ax.plot(history_array[:, car_idx], 'o-', markersize=0.8, linewidth=0.5, alpha=0.6)
ax.set_xlabel('Time Step', fontsize=10)
ax.set_ylabel('Position', fontsize=10)
ax.set_title('p = 0.1: Phantom Jams (Triangular waves)', fontweight='bold')
ax.grid(True, alpha=0.3)
plt.suptitle('Effect of Randomization: How Noise Creates Traffic Jams',
fontsize=13, fontweight='bold')
plt.tight_layout()
plt.savefig('traffic_ns_randomization.png', dpi=300, bbox_inches='tight')
print("✓ Saved: traffic_ns_randomization.png")
plt.show()
# ============================================================================
# VISUALIZATION 4: Heatmap Analysis
# ============================================================================
print("\nGenerating heatmap visualization...")
fig, axes = plt.subplots(3, 1, figsize=(14, 10))
ns_heat = NagelSchreckenberg(road_length=100, num_cars=25, v_max=5, p_random=0.1)
ns_heat.simulate(300)
history_array = np.array(ns_heat.history)
velocities_array = np.array(ns_heat.velocity_history)
# 1. Density heatmap
ax = axes[0]
space_bins = np.linspace(0, ns_heat.L, 50)
density_map = np.zeros((len(space_bins)-1, ns_heat.time))
for t in range(ns_heat.time):
counts, _ = np.histogram(history_array[t], bins=space_bins)
density_map[:, t] = counts
im1 = ax.imshow(density_map, aspect='auto', origin='lower', cmap='hot',
extent=[0, ns_heat.time, 0, ns_heat.L], interpolation='bilinear')
ax.set_xlabel('Time Step', fontweight='bold')
ax.set_ylabel('Road Position', fontweight='bold')
ax.set_title('Vehicle Density Heatmap (Bright = Congestion)', fontweight='bold')
cbar1 = plt.colorbar(im1, ax=ax)
cbar1.set_label('Vehicles per cell')
# 2. Velocity heatmap
ax = axes[1]
velocity_map = np.zeros((len(space_bins)-1, ns_heat.time))
for t in range(ns_heat.time):
positions = history_array[t]
velocities = velocities_array[t]
for pos, vel in zip(positions, velocities):
bin_idx = int((pos / ns_heat.L) * (len(space_bins)-1))
bin_idx = min(max(bin_idx, 0), len(space_bins)-2)
velocity_map[bin_idx, t] += vel
velocity_map /= 5 # Normalize
im2 = ax.imshow(velocity_map, aspect='auto', origin='lower', cmap='RdYlGn',
extent=[0, ns_heat.time, 0, ns_heat.L], vmin=0, vmax=ns_heat.v_max,
interpolation='bilinear')
ax.set_xlabel('Time Step', fontweight='bold')
ax.set_ylabel('Road Position', fontweight='bold')
ax.set_title('Velocity Heatmap (Green = Fast, Red = Slow)', fontweight='bold')
cbar2 = plt.colorbar(im2, ax=ax)
cbar2.set_label('Velocity')
# 3. Jam detection (combined metric)
ax = axes[2]
jam_map = density_map * (ns_heat.v_max - velocity_map) / ns_heat.v_max
jam_map = np.clip(jam_map, 0, None)
im3 = ax.imshow(jam_map, aspect='auto', origin='lower', cmap='Reds',
extent=[0, ns_heat.time, 0, ns_heat.L], interpolation='bilinear')
ax.set_xlabel('Time Step', fontweight='bold')
ax.set_ylabel('Road Position', fontweight='bold')
ax.set_title('Traffic Jam Indicator (High density × Low velocity)', fontweight='bold')
cbar3 = plt.colorbar(im3, ax=ax)
cbar3.set_label('Jam intensity')
plt.tight_layout()
plt.savefig('traffic_ns_heatmap.png', dpi=300, bbox_inches='tight')
print("✓ Saved: traffic_ns_heatmap.png")
plt.show()
# ============================================================================
# DETAILED STATISTICS
# ============================================================================
print("\n" + "="*70)
print("DETAILED ANALYSIS")
print("="*70)
print("\n1. RANDOMIZATION PROBABILITY EFFECTS:")
print("-" * 70)
for p in probabilities:
ns_temp = results[p]
velocities_array = np.array(ns_temp.velocity_history)
flow_array = np.array(ns_temp.flow_history)
# Analyze steady state (last 100 steps)
steady_state_vel = velocities_array[-100:]
steady_state_flow = flow_array[-100:]
print(f"\np = {p}:")
print(f" Average velocity: {np.mean(steady_state_vel):.3f}")
print(f" Velocity std dev: {np.std(steady_state_vel):.3f}")
print(f" Average flow: {np.mean(steady_state_flow):.3f}")
print(f" Flow variance: {np.var(steady_state_flow):.3f}")
print(f" Min velocity: {np.min(steady_state_vel):.1f}")
print(f" Max velocity: {np.max(steady_state_vel):.1f}")
print("\n2. PHANTOM JAM CHARACTERISTICS (p=0.1):")
print("-" * 70)
history_array = np.array(ns.history)
velocities_array = np.array(ns.velocity_history)
# Find jam events (local velocity minima)
mean_vel_over_time = np.mean(velocities_array, axis=1)
jam_threshold = np.percentile(mean_vel_over_time, 25)
jam_periods = []
in_jam = False
jam_start = 0
for t in range(len(mean_vel_over_time)):
if mean_vel_over_time[t] < jam_threshold and not in_jam:
jam_start = t
in_jam = True
elif mean_vel_over_time[t] >= jam_threshold and in_jam:
jam_periods.append((jam_start, t))
in_jam = False
if len(jam_periods) > 0:
print(f"Number of jam events: {len(jam_periods)}")
jam_durations = [end - start for start, end in jam_periods]
print(f"Average jam duration: {np.mean(jam_durations):.1f} time steps")
print(f"Max jam duration: {np.max(jam_durations):.1f} time steps")
print(f"Average jam interval: {len(ns.history) / len(jam_periods):.1f} time steps")
else:
print("No significant jams detected")
print("\n3. VEHICLE DYNAMICS:")
print("-" * 70)
# Acceleration statistics
accelerations = np.diff(velocities_array, axis=0)
avg_acceleration = np.mean(accelerations)
print(f"Average acceleration magnitude: {np.mean(np.abs(accelerations)):.3f}")
print(f"Max acceleration: {np.max(accelerations):.1f}")
print(f"Min acceleration: {np.min(accelerations):.1f}")
print(f"Std dev (dynamics): {np.std(accelerations):.3f}")
print("\n" + "="*70)
print("OBSERVATIONS:")
print("="*70)
print("""
1. PHANTOM JAM EMERGENCE:
- Without randomization (p=0): Stable flow, no jams
- With randomization (p>0): Spontaneous traffic jams emerge
- Jams propagate backward despite no obstruction
2. MECHANISM:
- Random deceleration causes local density increase
- Vehicles downstream slow down to maintain safety
- Wave propagates upstream as a "backward-moving" congestion
3. FUNDAMENTAL DIAGRAM:
- At low densities: Near-capacity flow
- At high densities: Strong jam propagation
- Maximum flow at intermediate densities
4. REAL-WORLD RELEVANCE:
- Explains unexplained traffic slowdowns
- Small perturbations cause large-scale effects
- Self-organized criticality in traffic flow
- Suggests solutions: smoother acceleration, reduced fluctuations
""")
print("="*70)
Key Features & Results:
Model Dynamics:
- Free Flow (p=0): Stable parallel trajectories - no jams
- Phantom Jams (p>0):
- Triangular wave patterns emerge
- Jams propagate backward
- No external cause needed
Visualizations:
| Visualization | Insight |
|---|
| Space-Time Diagram | Shows jam formation and propagation |
| Velocity Dynamics | Flow instability with randomization |
| Heatmaps | Spatial-temporal evolution of congestion |
| Comparisons | Effect of randomization probability |
Key Observations:
- p = 0.0: Free flow (straight lines)
- p = 0.1: Phantom jams (triangular waves)
- Higher p: More severe, frequent jams
- Random fluctuations → collective instability
This simulation demonstrates how microscopic driver behavior (random deceleration) creates macroscopic traffic patterns (phantom jams) completely independent of any bottleneck! 🚗