Spaces:
Sleeping
Sleeping
File size: 13,053 Bytes
05354e5 | 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | # 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
|