File size: 5,420 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 |
#!/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)
|