File size: 2,233 Bytes
2dd33e7 | 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 | #!/usr/bin/env python3
"""
Generate an animation GIF of a single KdV-Burgers sample time evolution.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from burgers_dataset import KdvBurgersDataset
def create_kdv_burgers_animation(sample, save_path="sample_animation.gif", fps=10):
"""Create an animation GIF from a KdV-Burgers sample"""
# Extract data
spatial_coordinates = sample['spatial_coordinates']
u_initial = sample['u_initial']
u_trajectory = sample['u_trajectory']
time_coordinates = sample['time_coordinates']
# Set up the figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(0, spatial_coordinates[-1])
# Determine y-axis limits based on data range
u_min = np.min(u_trajectory)
u_max = np.max(u_trajectory)
u_range = u_max - u_min
ax.set_ylim(u_min - 0.1 * u_range, u_max + 0.1 * u_range)
ax.set_xlabel('x')
ax.set_ylabel('u(x,t)')
ax.grid(True, alpha=0.3)
# Initialize empty line
line, = ax.plot([], [], 'b-', linewidth=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes,
bbox=dict(boxstyle="round", facecolor='white', alpha=0.8))
def animate(frame):
"""Animation function"""
line.set_data(spatial_coordinates, u_trajectory[frame])
time_text.set_text(f'Time: {time_coordinates[frame]:.3f}')
return line, time_text
# Create animation
anim = animation.FuncAnimation(
fig, animate, frames=len(time_coordinates),
interval=1000/fps, blit=True, repeat=True
)
# Save as GIF
anim.save(save_path, writer='pillow', fps=fps)
plt.close()
print(f"Animation saved to {save_path}")
if __name__ == "__main__":
# Set random seed for reproducibility
np.random.seed(42)
# Create dataset
dataset = KdvBurgersDataset()
# Generate a single sample
sample = next(iter(dataset))
print("Creating animation...")
print(f"Time steps: {len(sample['time_coordinates'])}")
print(f"Spatial points: {len(sample['spatial_coordinates'])}")
# Create animation
create_kdv_burgers_animation(sample) |