File size: 8,007 Bytes
d681572
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Generate an animation GIF of a single Schrödinger equation sample time evolution.

Animates quantum wave packet dynamics including:
- Real and imaginary parts of wavefunction
- Probability density |ψ|²
- Wave packet motion in harmonic potential
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from dataset import SchrodingerDataset


def create_schrodinger_animation(sample, save_path="sample_animation.gif", fps=15):
    """Create an animation GIF from a Schrödinger sample"""
    # Extract data
    x = sample['spatial_coordinates']
    t = sample['time_coordinates']
    psi_r = sample['psi_r_trajectory']
    psi_i = sample['psi_i_trajectory']
    prob = sample['probability_density']
    V = sample['potential']
    energy = sample['total_energy']
    
    # Set up the figure with subplots
    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 10))
    fig.suptitle(f'Quantum Harmonic Oscillator Evolution\n' + 
                 f'ℏ={sample["hbar"]}, m={sample["mass"]}, ω={sample["omega"]}', 
                 fontsize=14, fontweight='bold')
    
    # Colors for consistency
    color_real = '#1f77b4'
    color_imag = '#ff7f0e'
    color_prob = '#2ca02c'
    color_potential = '#d62728'
    
    # Subplot 1: Wavefunction components
    ax1.set_xlim(x[0], x[-1])
    psi_max = max(np.max(np.abs(psi_r)), np.max(np.abs(psi_i))) * 1.1
    ax1.set_ylim(-psi_max, psi_max)
    ax1.set_ylabel('ψ(x,t)')
    ax1.set_title('Wavefunction Components')
    ax1.grid(True, alpha=0.3)
    
    # Plot potential well (scaled for background)
    V_scaled = V / np.max(V) * psi_max * 0.2
    ax1.fill_between(x, -psi_max, V_scaled - psi_max, alpha=0.1, color=color_potential)
    ax1.plot(x, V_scaled - psi_max, '--', alpha=0.5, color=color_potential, linewidth=1, label='V(x)')
    
    real_line, = ax1.plot([], [], color=color_real, linewidth=2, label='ψᵣ(x,t)')
    imag_line, = ax1.plot([], [], color=color_imag, linewidth=2, label='ψᵢ(x,t)')
    ax1.legend(loc='upper right')
    
    # Subplot 2: Probability density
    ax2.set_xlim(x[0], x[-1])
    prob_max = np.max(prob) * 1.1
    ax2.set_ylim(0, prob_max)
    ax2.set_ylabel('|ψ(x,t)|²')
    ax2.set_title('Probability Density')
    ax2.grid(True, alpha=0.3)
    
    # Plot potential well (scaled for background)
    V_scaled_prob = V / np.max(V) * prob_max * 0.3
    ax2.fill_between(x, V_scaled_prob, alpha=0.2, color=color_potential)
    
    prob_line, = ax2.plot([], [], color=color_prob, linewidth=2, label='|ψ|²')
    ax2.legend(loc='upper right')
    
    # Subplot 3: Energy over time
    ax3.set_xlim(t[0], t[-1])
    E_mean = np.mean(energy)
    E_range = np.max(energy) - np.min(energy)
    if E_range > 0:
        ax3.set_ylim(np.min(energy) - 0.1*E_range, np.max(energy) + 0.1*E_range)
    else:
        ax3.set_ylim(E_mean - 0.1*abs(E_mean), E_mean + 0.1*abs(E_mean))
        
    ax3.set_xlabel('Time t')
    ax3.set_ylabel('Total Energy')
    ax3.set_title('Energy Conservation')
    ax3.grid(True, alpha=0.3)
    
    # Plot full energy trace as background
    ax3.plot(t, energy, 'k-', alpha=0.3, linewidth=1)
    ax3.axhline(E_mean, color='red', linestyle='--', alpha=0.7, linewidth=1)
    
    # Current energy point
    energy_point, = ax3.plot([], [], 'o', color='darkgreen', markersize=8)
    energy_line, = ax3.plot([], [], color='darkgreen', linewidth=2)
    
    # Time text
    time_text = fig.text(0.02, 0.02, '', fontsize=12, fontweight='bold',
                        bbox=dict(boxstyle="round,pad=0.3", facecolor='yellow', alpha=0.7))
    
    # Store fill object
    prob_fill = None
    
    def animate(frame):
        """Animation function"""
        nonlocal prob_fill
        
        # Update wavefunction components
        real_line.set_data(x, psi_r[frame])
        imag_line.set_data(x, psi_i[frame])
        
        # Update probability density
        prob_line.set_data(x, prob[frame])
        
        # Remove old fill and create new one
        if prob_fill is not None:
            prob_fill.remove()
        prob_fill = ax2.fill_between(x, prob[frame], alpha=0.3, color=color_prob)
        
        # Update energy plot
        current_t = t[:frame+1]
        current_e = energy[:frame+1]
        energy_line.set_data(current_t, current_e)
        energy_point.set_data([t[frame]], [energy[frame]])
        
        # Update time display
        time_text.set_text(f'Time: {t[frame]:.3f} / {t[-1]:.3f}')
        
        return real_line, imag_line, prob_line, energy_line, energy_point, time_text
    
    # Create animation with more frames for smoother motion
    print(f"Creating animation with {len(t)} frames...")
    anim = animation.FuncAnimation(
        fig, animate, frames=len(t),
        interval=1000/fps, blit=False, repeat=True  # blit=False due to fill_between
    )
    
    # Save as GIF
    print(f"Saving animation to {save_path}...")
    anim.save(save_path, writer='pillow', fps=fps)
    plt.close()
    
    print(f"Animation saved to {save_path}")


def create_simple_animation(sample, save_path="simple_animation.gif", fps=15):
    """Create a simpler single-panel animation focusing on probability density"""
    # Extract data
    x = sample['spatial_coordinates']
    t = sample['time_coordinates']
    prob = sample['probability_density']
    V = sample['potential']
    
    # Set up single plot
    fig, ax = plt.subplots(figsize=(10, 6))
    ax.set_xlim(x[0], x[-1])
    prob_max = np.max(prob) * 1.1
    ax.set_ylim(0, prob_max)
    ax.set_xlabel('Position x')
    ax.set_ylabel('Probability Density |ψ|²')
    ax.set_title(f'Quantum Wave Packet in Harmonic Oscillator\n' +
                 f'ℏ={sample["hbar"]}, m={sample["mass"]}, ω={sample["omega"]}')
    ax.grid(True, alpha=0.3)
    
    # Plot potential well (scaled)
    V_scaled = V / np.max(V) * prob_max * 0.3
    ax.fill_between(x, V_scaled, alpha=0.2, color='red', label='V(x) (scaled)')
    ax.plot(x, V_scaled, 'r--', alpha=0.7, linewidth=1)
    
    # Initialize probability line
    prob_line, = ax.plot([], [], 'b-', linewidth=3, label='|ψ(x,t)|²')
    
    # Time text
    time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes, fontsize=12,
                       bbox=dict(boxstyle="round", facecolor='white', alpha=0.8))
    
    ax.legend()
    
    # Store fill object
    prob_fill = None
    
    def animate(frame):
        """Simple animation function"""
        nonlocal prob_fill
        
        # Update probability line
        prob_line.set_data(x, prob[frame])
        
        # Remove previous fill if it exists
        if prob_fill is not None:
            prob_fill.remove()
        
        # Create new fill
        prob_fill = ax.fill_between(x, prob[frame], alpha=0.4, color='blue')
        
        # Update time text
        time_text.set_text(f'Time: {t[frame]:.3f}')
        return prob_line, time_text
    
    # Create animation
    anim = animation.FuncAnimation(
        fig, animate, frames=len(t),
        interval=1000/fps, blit=False, repeat=True
    )
    
    # Save as GIF
    anim.save(save_path, writer='pillow', fps=fps)
    plt.close()
    
    print(f"Simple animation saved to {save_path}")


if __name__ == "__main__":
    # Set random seed for reproducibility
    np.random.seed(42)
    
    # Create dataset
    dataset = SchrodingerDataset(
        Lx=20.0,
        Nx=128,  # Lower resolution for faster animation generation
        stop_sim_time=3.0,
        timestep=2e-3  # Slightly larger timestep for fewer frames
    )
    
    # Generate a single sample
    sample = next(iter(dataset))
    
    print("Creating animations...")
    print(f"Time steps: {len(sample['time_coordinates'])}")
    print(f"Spatial points: {len(sample['spatial_coordinates'])}")
    
    # Create both animations
    create_simple_animation(sample, "simple_animation.gif", fps=12)
    create_schrodinger_animation(sample, "sample_animation.gif", fps=10)