import os
from pathlib import Path

# --8<-- [start:code]
"""The orbitals of the hydrogen atom: a 3-D finite-element eigenproblem, checked against the exact levels.

In atomic units (lengths in Bohr radii) the electron obeys  -1/2 Laplace(psi) - psi / r = E psi , which is solved
exactly by E = -1/(2 n^2), each level n^2-fold degenerate, and psi_1s = exp(-r) / sqrt(pi). Here it is solved on a
ball of radius R with psi = 0 on its sphere, on P2 tetrahedra that are fine at the nucleus and coarse far away.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
R, SHIFT = 30.0, -0.6  # ball radius, and the energy the shift-invert search is centred on
LEVELS = [1] + [2] * 4 + [3] * 9  # n of the 14 lowest states: 1 + 4 + 9
EXACT = -0.5 / np.array(LEVELS, float) ** 2


# --8<-- [start:solve]
def hydrogen(h0, grade, hmax):
    """The 14 lowest states on a ball whose mesh size grows with the distance r from the nucleus: h = min(h0 + grade r, hmax)."""
    size = lambda x, y, z: np.minimum(h0 + grade * np.sqrt(x**2 + y**2 + z**2), hmax)
    d = jno.shape.sphere(0, 0, 0, R).sized(size).domain()
    x, y, z, _ = d.variable("interior", split=True)
    xs, ys, zs, _ = d.variable("surface", split=True)
    u = d.unknown(order=2)
    ui, vi = u.bind(x=x, y=y, z=z), u.test().bind(x=x, y=y, z=z)
    r = jno.np.sqrt(x**2 + y**2 + z**2)
    H = jno.fem([0.5 * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z) - ui * vi / r, u(xs, ys, zs) - 0.0])  # -1/2 Laplace - 1/r
    E, psi = H.eigs(mass=[ui * vi], k=len(LEVELS), sigma=SHIFT, maxiter=800, tol=1e-6)
    M, _ = jno.fem([ui * vi]).operator  # the mass matrix: psi^T M psi = 1 for every state returned
    order = np.argsort(np.asarray(E).ravel())
    return d, H, M, np.asarray(E).ravel()[order], np.asarray(psi)[:, order]


# --8<-- [end:solve]


# --8<-- [start:study]
MESHES = {"coarse": (0.4, 0.4, 3.5), "fine": (0.15, 0.25, 3.0)}  # (h0 at the nucleus, grade, hmax)
runs, rel = {}, {}
for name, (h0, grade, hmax) in MESHES.items():
    runs[name] = d, H, M, E, psi = hydrogen(h0, grade, hmax)
    rel[name] = abs(E / EXACT - 1)
    spread = max(np.ptp(E[np.array(LEVELS) == n]) for n in (1, 2, 3))
    print(
        f"{name:>6}: {len(d.built_mesh.points)} vertices, {len(H.points)} unknowns; relative error of E: "
        f"1s {rel[name][0]:.1e}, n=2 up to {rel[name][1:5].max():.1e}, n=3 up to {rel[name][5:].max():.1e}"
    )
    gap = EXACT[5] - EXACT[1]  # the closest levels are n = 2 and n = 3: the split inside a level must stay far below it
    assert spread < 0.1 * gap, f"{name}: a degenerate level is split by {spread:.1e}"  # degeneracy n^2 of E = -1/(2 n^2)
    assert rel[name].max() < 0.1, f"{name}: a level is off by {rel[name].max():.1e}"  # the exact levels
assert rel["fine"].max() < 1e-2 and (rel["fine"] < rel["coarse"]).all()  # the finer mesh is closer, level by level

d, H, M, E, psi = runs["fine"]
pts = np.asarray(H.points)
r = np.linalg.norm(pts, axis=1)
for r0 in (0.5, 1.0, 2.0, 4.0):  # the 1s state against exp(-r)/sqrt(pi), at the unknown nearest each radius
    i = np.argmin(abs(r - r0))
    s = np.sign(psi[np.argmin(r), 0])  # the sign of an eigenvector is arbitrary: fix it positive at the nucleus
    exact = np.exp(-r[i]) / np.sqrt(np.pi)
    print(f"1s at r = {r[i]:.2f}: {s * psi[i, 0]:.5f} against exp(-r)/sqrt(pi) = {exact:.5f}")
    assert abs(s * psi[i, 0] / exact - 1) < 3e-2, f"1s wrong at r = {r[i]:.2f}"  # the exact ground state
# --8<-- [end:study]


# --8<-- [start:orbitals]
x, y, z = pts.T
shapes = {  # name: (n, an exact orbital up to its normalisation, written in x, y, z and r)
    "1s": (1, np.exp(-r)),
    "2s": (2, (2 - r) * np.exp(-r / 2)),
    "2p_z": (2, z * np.exp(-r / 2)),
    "3p_z": (3, z * (6 - r) * np.exp(-r / 3)),
    "3d_xz": (3, x * z * np.exp(-r / 3)),
    "3d_z2": (3, (3 * z**2 - r**2) * np.exp(-r / 3)),
}
orbitals = {}
for name, (n, g) in shapes.items():
    V = psi[:, np.array(LEVELS) == n]  # the degenerate level: any mix of these is an eigenfunction
    Mg = np.asarray(M @ g)
    c = V.T @ Mg  # the part of the exact orbital that the level's states hold, in the M inner product
    share = c @ c / (g @ Mg)
    assert share > 0.99, f"{name}: only {share:.4f} of the exact orbital lies in the computed level"  # exact orbitals
    orbitals[name] = V @ c / np.linalg.norm(c)  # the computed orbital: a normalised combination of the level's states
    print(f"{name:>5}: {share:.5f} of the exact orbital lies in the computed level n = {n}")
# --8<-- [end:orbitals]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/hydrogen_orbitals_3d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "hydrogen_orbitals_3d.npz",
        names=list(orbitals),
        orbitals=np.array(list(orbitals.values()), np.float32),
        energies=E,
        exact=EXACT,
        points=pts.astype(np.float32),
        vertices=np.asarray(d.built_mesh.points, np.float32),
        tets=np.asarray(d.mesh.cells_dict["tetra"]),
        coarse_error=rel["coarse"],
        fine_error=rel["fine"],
    )
