schrodinger-dedalus / plot_sample.py
ajthor's picture
Upload folder using huggingface_hub
d681572 verified
#!/usr/bin/env python3
"""
Plot a single sample from the Schrödinger equation dataset.
Visualizes quantum wave packet evolution including:
- Real and imaginary parts
- Probability density |ψ|²
- Potential well
- Energy conservation
"""
import numpy as np
import matplotlib.pyplot as plt
from dataset import SchrodingerDataset
def plot_schrodinger_sample(sample, save_path="sample_plot.png"):
"""Plot a single sample from the Schrödinger dataset"""
fig = plt.figure(figsize=(16, 12))
# Create subplot layout
gs = fig.add_gridspec(3, 2, height_ratios=[1, 1, 0.8], hspace=0.3, wspace=0.3)
# 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"]
# Colors for consistency
color_real = "#1f77b4"
color_imag = "#ff7f0e"
color_prob = "#2ca02c"
color_potential = "#d62728"
# Plot 1: Initial and final wavefunction components
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(x, psi_r[0], color=color_real, linewidth=2, label="ψᵣ(x,t=0)")
ax1.plot(x, psi_i[0], color=color_imag, linewidth=2, label="ψᵢ(x,t=0)")
ax1.plot(
x,
psi_r[-1],
"--",
color=color_real,
alpha=0.7,
linewidth=2,
label=f"ψᵣ(x,t={t[-1]:.1f})",
)
ax1.plot(
x,
psi_i[-1],
"--",
color=color_imag,
alpha=0.7,
linewidth=2,
label=f"ψᵢ(x,t={t[-1]:.1f})",
)
ax1.set_xlabel("Position x")
ax1.set_ylabel("ψ(x)")
ax1.set_title("Wavefunction Components")
ax1.grid(True, alpha=0.3)
ax1.legend()
# Plot 2: Probability density evolution
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(x, prob[0], color=color_prob, linewidth=2, label="|ψ(x,t=0)|²")
ax2.plot(
x,
prob[-1],
"--",
color=color_prob,
alpha=0.7,
linewidth=2,
label=f"|ψ(x,t={t[-1]:.1f})|²",
)
# Add potential well (scaled for visibility)
V_scaled = V / np.max(V) * np.max(prob[0]) * 0.3
ax2.fill_between(
x, V_scaled, alpha=0.2, color=color_potential, label="V(x) (scaled)"
)
ax2.set_xlabel("Position x")
ax2.set_ylabel("Probability Density")
ax2.set_title("Quantum Probability |ψ|²")
ax2.grid(True, alpha=0.3)
ax2.legend()
# Plot 3: Real part space-time evolution
ax3 = fig.add_subplot(gs[1, 0])
vmax = np.max(np.abs(psi_r))
im1 = ax3.pcolormesh(
x, t, psi_r, cmap="RdBu", vmin=-vmax, vmax=vmax, shading="gouraud"
)
ax3.set_xlabel("Position x")
ax3.set_ylabel("Time t")
ax3.set_title("Real Part Evolution ψᵣ(x,t)")
plt.colorbar(im1, ax=ax3, label="ψᵣ")
# Plot 4: Imaginary part space-time evolution
ax4 = fig.add_subplot(gs[1, 1])
vmax = np.max(np.abs(psi_i))
im2 = ax4.pcolormesh(
x, t, psi_i, cmap="RdBu", vmin=-vmax, vmax=vmax, shading="gouraud"
)
ax4.set_xlabel("Position x")
ax4.set_ylabel("Time t")
ax4.set_title("Imaginary Part Evolution ψᵢ(x,t)")
plt.colorbar(im2, ax=ax4, label="ψᵢ")
# Plot 5: Bottom spanning plots - Probability density heatmap and energy
ax5 = fig.add_subplot(gs[2, 0])
im3 = ax5.pcolormesh(x, t, prob, cmap="viridis", shading="gouraud")
ax5.set_xlabel("Position x")
ax5.set_ylabel("Time t")
ax5.set_title("Probability Density Evolution |ψ(x,t)|²")
plt.colorbar(im3, ax=ax5, label="|ψ|²")
# Plot 6: Energy conservation
ax6 = fig.add_subplot(gs[2, 1])
ax6.plot(t, energy, "o-", color="darkgreen", linewidth=2, markersize=4)
ax6.set_xlabel("Time t")
ax6.set_ylabel("Total Energy")
ax6.set_title("Energy Conservation")
ax6.grid(True, alpha=0.3)
# Add energy statistics
E_mean = np.mean(energy)
E_std = np.std(energy)
ax6.axhline(
E_mean, color="red", linestyle="--", alpha=0.7, label=f"Mean: {E_mean:.3f}"
)
ax6.text(
0.02,
0.95,
f"σ/⟨E⟩ = {E_std/E_mean:.2e}",
transform=ax6.transAxes,
bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
verticalalignment="top",
)
ax6.legend()
# Add main title with physical parameters
hbar = sample["hbar"]
mass = sample["mass"]
omega = sample["omega"]
fig.suptitle(
f"Quantum Harmonic Oscillator (ℏ={hbar}, m={mass}, ω={omega})",
fontsize=16,
fontweight="bold",
)
plt.savefig(save_path, dpi=200, bbox_inches="tight")
plt.close()
print(f"Schrödinger sample visualization saved to {save_path}")
if __name__ == "__main__":
# Set random seed for reproducibility
np.random.seed(42)
# Create dataset with reasonable parameters for visualization
dataset = SchrodingerDataset(Lx=20.0, Nx=256, stop_sim_time=2.0, timestep=1e-3)
# Generate a single sample
dataset_iter = iter(dataset)
sample = next(dataset_iter)
sample = next(dataset_iter)
print("Sample keys:", list(sample.keys()))
for key, value in sample.items():
if hasattr(value, "shape"):
print(f"{key}: shape {value.shape}")
else:
print(f"{key}: {type(value)} - {value}")
# Plot the sample
plot_schrodinger_sample(sample)