physics-simulation / simulation_hydrogen.py
j25aiml013's picture
Upload 16 files
05354e5 verified
Raw History Blame Contribute Delete
13.1 kB
# app/core/simulations/simulation_hydrogen.py
from __future__ import annotations
import os
import sys
import math
from typing import Tuple, Optional
import numpy as np
import plotly.graph_objects as go
# Make project importable when run directly from UI folder
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, "..", "..", ".."))
if PROJECT_ROOT not in sys.path:
sys.path.append(PROJECT_ROOT)
# Physical constants
A0 = 5.29177210903e-11 # Bohr radius (m)
E_HYDROGEN_GROUND = -13.605693009 # eV (n=1)
# SciPy helpers (optional; fallbacks exist)
try:
from scipy.special import genlaguerre, factorial, sph_harm
SCIPY_AVAILABLE = True
except Exception:
SCIPY_AVAILABLE = False
# ----------------------------
# Core physics utilities
# ----------------------------
def hydrogen_energy(n: int) -> float:
"""Return hydrogen energy in eV for principal quantum number n."""
if n < 1:
raise ValueError("n must be >= 1")
return E_HYDROGEN_GROUND / (n ** 2)
def radial_wavefunction(n: int, l: int, r: Optional[np.ndarray] = None, a0: float = A0) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute radial wavefunction R_{n,l}(r) (SI units). If SciPy present, uses associated Laguerre.
r (optional) must be in meters. Returns (r_array_in_meters, R_nl(r)).
If SciPy is missing, returns a smooth approximate (shape-correct) radial function.
"""
if r is None:
r = np.linspace(0.0, 200 * a0, 1000)
if n < 1:
raise ValueError("n must be >= 1")
if l < 0:
raise ValueError("l must be >= 0")
rho = 2.0 * r / (n * a0) # dimensionless
if SCIPY_AVAILABLE:
# safe int conversion for SciPy functions
k = int(n - l - 1)
num = factorial(k)
den = factorial(int(n + l))
prefac = (2.0 / (n * a0)) ** 3
norm = np.sqrt(prefac * (num / (2.0 * n * den)))
L = genlaguerre(k, 2 * l + 1)
poly = L(rho)
R = norm * (rho ** l) * poly * np.exp(-rho / 2.0)
return r, R
else:
# fallback (shape only, normalized with radial measure)
R_approx = (rho ** l) * np.exp(-rho / 2.0)
# normalize with r^2 measure
norm = np.sqrt(np.trapz((R_approx ** 2) * r**2, r) + 1e-18)
if norm > 0:
R_approx = R_approx / norm
return r, R_approx
def radial_probability(n: int, l: int, r: Optional[np.ndarray] = None, a0: float = A0) -> Tuple[np.ndarray, np.ndarray]:
"""Return (r, P(r) = r^2 |R_{nl}(r)|^2). r in meters, P in arbitrary units."""
r, R = radial_wavefunction(n, l, r, a0=a0)
prob = (r ** 2) * (np.abs(R) ** 2)
return r, prob
# ----------------------------
# 2D plotting helpers
# ----------------------------
def plot_radial_wavefunction(n: int, l: int, rmax_m: float = 200 * A0, resolution: int = 800) -> go.Figure:
r = np.linspace(0.0, rmax_m, resolution)
r, R = radial_wavefunction(n, l, r)
fig = go.Figure()
fig.add_trace(go.Scatter(x=r / A0, y=R, mode="lines", name=f"R_{{{n},{l}}}(r)"))
fig.update_layout(
title=f"Radial wavefunction Rₙₗ(r) — n={n}, ℓ={l}",
xaxis_title="r (a₀)",
yaxis_title="R(r) (arb. units)",
template="plotly_dark",
)
return fig
def plot_radial_probability(n: int, l: int, rmax_m: float = 200 * A0, resolution: int = 800) -> go.Figure:
r = np.linspace(0.0, rmax_m, resolution)
r, prob = radial_probability(n, l, r)
fig = go.Figure()
fig.add_trace(go.Scatter(x=r / A0, y=prob, mode="lines", name=f"r²|R|² (n={n},ℓ={l})"))
fig.update_layout(
title=f"Radial probability density r² |Rₙₗ(r)|² — n={n}, ℓ={l}",
xaxis_title="r (a₀)",
yaxis_title="Probability (arb.)",
template="plotly_dark",
)
return fig
# ----------------------------
# 3D Probability Cloud (robust)
# ----------------------------
def plot_hydrogen_3d(n=1, l=0, m=0):
grid = 50
r_max = 25
x = np.linspace(-r_max, r_max, grid)
y = np.linspace(-r_max, r_max, grid)
z = np.linspace(-r_max, r_max, grid)
X, Y, Z = np.meshgrid(x, y, z)
R = np.sqrt(X**2 + Y**2 + Z**2) + 1e-12
prob = np.exp(-2 * R / n)
prob /= prob.max()
fig = go.Figure(data=[
go.Isosurface(
x=X.flatten(), y=Y.flatten(), z=Z.flatten(),
value=prob.flatten(),
isomin=0.12, isomax=1,
surface_count=4,
colorscale="Viridis",
opacity=0.6
)
])
fig.update_layout(title=f"Probability Density (n={n})", template="plotly_dark")
return fig
# ----------------------------
# Orbital shape (isosurface of probability; adaptive)
# ----------------------------
def plot_hydrogen_orbital(n: int = 1, l: int = 0, m: int = 0, rmax_a0: float = 10.0, res: int = 40):
"""
Real orbital shape using signed wavefunction (lobes visible).
"""
rmax_a0 = float(rmax_a0)
res = int(max(20, min(60, res)))
# Cartesian grid in Bohr radii
x = np.linspace(-rmax_a0, rmax_a0, res)
y = np.linspace(-rmax_a0, rmax_a0, res)
z = np.linspace(-rmax_a0, rmax_a0, res)
X, Y, Z = np.meshgrid(x, y, z, indexing="ij")
# Convert to meters for R(r)
R_cart_m = np.sqrt((X*A0)**2 + (Y*A0)**2 + (Z*A0)**2) + 1e-20
# ---- Radial ----
try:
flat_r = R_cart_m.flatten()
_, R_flat = radial_wavefunction(n=n, l=l, r=flat_r)
R_rad = R_flat.reshape(R_cart_m.shape)
except:
rho = 2.0 * R_cart_m / (n * A0)
R_rad = (rho**l) * np.exp(-rho/2.0)
# ---- Angular ----
phi = np.arctan2(Y, X)
theta = np.arccos(np.clip(Z / R_cart_m, -1, 1))
if SCIPY_AVAILABLE:
Ylm = sph_harm(m, l, phi, theta)
else:
# Stable angular fallback
if l == 0:
Ylm = np.ones_like(theta)
elif l == 1:
Ylm = np.cos(theta)
else:
Ylm = np.cos(theta) ** l
# ---- Real-valued wavefunction (critical fix) ----
psi = R_rad * np.real(Ylm)
# Normalize
psi /= np.max(np.abs(psi)) + 1e-20
val = psi.flatten()
# Coordinates
x_flat = X.flatten()
y_flat = Y.flatten()
z_flat = Z.flatten()
# Mask invalid
mask = np.isfinite(val)
val = val[mask]
x_flat = x_flat[mask]
y_flat = y_flat[mask]
z_flat = z_flat[mask]
# ---- Separate positive and negative lobes ----
pos_mask = val > 0.2
neg_mask = val < -0.2
traces = []
if np.count_nonzero(pos_mask) > 200:
traces.append(go.Isosurface(
x=x_flat, y=y_flat, z=z_flat, value=val,
isomin=0.2, isomax=1,
surface_count=3,
colorscale="Reds",
opacity=0.6,
showscale=False
))
if np.count_nonzero(neg_mask) > 200:
traces.append(go.Isosurface(
x=x_flat, y=y_flat, z=z_flat, value=-val,
isomin=0.2, isomax=1,
surface_count=3,
colorscale="Blues",
opacity=0.6,
showscale=False
))
# ---- Fallback if lobes fail ----
if not traces:
idx = np.argsort(np.abs(val))[-4000:]
traces.append(go.Scatter3d(
x=x_flat[idx], y=y_flat[idx], z=z_flat[idx],
mode="markers",
marker=dict(size=2, color=val[idx], colorscale="RdBu", opacity=0.8)
))
fig = go.Figure(data=traces)
fig.update_layout(
title=f"Orbital Shape (n={n}, l={l}, m={m})",
scene=dict(aspectmode="data"),
template="plotly_dark",
margin=dict(l=0, r=0, t=50, b=0)
)
return fig
# ----------------------------
# Nodes visualization (scatter of low-prob points)
# ----------------------------
def plot_hydrogen_nodes(n: int = 1, l: int = 0, m: int = 0, rmax_a0: float = 20.0, res: int = 30) -> go.Figure:
"""
Show node regions as a scatter of low-probability points (much more reliable than boolean isosurfaces).
"""
r = np.linspace(0.0, rmax_a0 * A0, max(3, int(res)))
theta = np.linspace(0.0, np.pi, max(3, int(res)))
phi = np.linspace(0.0, 2.0 * np.pi, max(3, int(res)))
Rg, Th, Ph = np.meshgrid(r, theta, phi, indexing="ij")
try:
r_flat = Rg.flatten()
_, R_flat = radial_wavefunction(n=n, l=l, r=r_flat)
R_rad = R_flat.reshape(Rg.shape)
except Exception:
rho = 2.0 * Rg / (n * A0)
R_rad = (rho ** l) * np.exp(-rho / 2.0)
if SCIPY_AVAILABLE:
Ylm = sph_harm(m, l, Ph, Th)
else:
if l == 0:
Ylm = np.ones_like(Th) * (1.0 / np.sqrt(4.0 * math.pi))
else:
Ylm = (np.cos(Th) ** l).astype(complex)
prob = (np.abs(R_rad * Ylm) ** 2).flatten()
X = (Rg * np.sin(Th) * np.cos(Ph)) / A0
Yc = (Rg * np.sin(Th) * np.sin(Ph)) / A0
Z = (Rg * np.cos(Th)) / A0
x_flat = X.flatten(); y_flat = Yc.flatten(); z_flat = Z.flatten()
mask = np.isfinite(prob)
prob = prob[mask]; x_flat = x_flat[mask]; y_flat = y_flat[mask]; z_flat = z_flat[mask]
if prob.size == 0:
raise RuntimeError("Node data empty.")
# bottom percentile considered nodes (tunable)
thr = np.percentile(prob, 8)
node_mask = prob <= thr
# ensure enough points
if node_mask.sum() < 60:
thr = np.percentile(prob, 20)
node_mask = prob <= thr
fig = go.Figure(
data=[
go.Scatter3d(
x=x_flat[node_mask],
y=y_flat[node_mask],
z=z_flat[node_mask],
mode="markers",
marker=dict(size=2.5, opacity=0.9, color="lightgrey"),
name="nodes"
)
]
)
fig.update_layout(title=f"Node points (low probability) — n={n}, ℓ={l}, m={m}", template="plotly_dark")
return fig
# ----------------------------
# Phase coloring (scatter of high-prob points colored by phase)
# ----------------------------
def plot_hydrogen_phase(n: int = 1, l: int = 0, m: int = 0, rmax_a0: float = 20.0, res: int = 28) -> go.Figure:
r = np.linspace(0.0, rmax_a0 * A0, max(3, int(res)))
theta = np.linspace(0.0, np.pi, max(3, int(res)))
phi = np.linspace(0.0, 2.0 * np.pi, max(3, int(res)))
Rg, Th, Ph = np.meshgrid(r, theta, phi, indexing="ij")
try:
r_flat = Rg.flatten()
_, R_flat = radial_wavefunction(n=n, l=l, r=r_flat)
R_rad = R_flat.reshape(Rg.shape)
except Exception:
rho = 2.0 * Rg / (n * A0)
R_rad = (rho ** l) * np.exp(-rho / 2.0)
if SCIPY_AVAILABLE:
Ylm = sph_harm(m, l, Ph, Th)
else:
if l == 0:
Ylm = np.ones_like(Th) * (1.0 / np.sqrt(4.0 * math.pi))
else:
Ylm = (np.cos(Th) ** l).astype(complex)
wave = R_rad * Ylm
prob = (np.abs(wave) ** 2).flatten()
phase = np.angle(wave).flatten()
X = (Rg * np.sin(Th) * np.cos(Ph)) / A0
Yc = (Rg * np.sin(Th) * np.sin(Ph)) / A0
Z = (Rg * np.cos(Th)) / A0
x_flat = X.flatten(); y_flat = Yc.flatten(); z_flat = Z.flatten()
mask = np.isfinite(prob) & np.isfinite(phase)
prob = prob[mask]; phase = phase[mask]
x_flat = x_flat[mask]; y_flat = y_flat[mask]; z_flat = z_flat[mask]
if prob.size == 0:
raise RuntimeError("Phase data empty.")
# show only the more probable points to avoid clutter
thr = np.percentile(prob, 70)
keep = prob >= thr
if keep.sum() < 200:
thr = np.percentile(prob, 50)
keep = prob >= thr
fig = go.Figure(
data=[
go.Scatter3d(
x=x_flat[keep],
y=y_flat[keep],
z=z_flat[keep],
mode="markers",
marker=dict(
size=3,
color=phase[keep],
colorscale="HSV",
cmin=-math.pi,
cmax=math.pi,
colorbar=dict(title="phase (rad)"),
opacity=0.9
)
)
]
)
fig.update_layout(title=f"Phase coloring (n={n}, ℓ={l}, m={m}) — points colored by phase", template="plotly_dark")
return fig
# ----------------------------
# Energy levels (2D)
# ----------------------------
def plot_energy_levels(max_n: int = 6) -> go.Figure:
ns = np.arange(1, max_n + 1)
energies = [hydrogen_energy(int(n)) for n in ns]
fig = go.Figure()
fig.add_trace(go.Scatter(x=ns, y=energies, mode="markers+lines"))
fig.update_layout(title="Hydrogen energy levels (eV)", xaxis_title="n", yaxis_title="E (eV)", template="plotly_dark")
return fig