import os
from pathlib import Path

# --8<-- [start:code]
"""A wave packet through a double slit: the time-dependent Schrodinger equation, ETDRK4 on a periodic box.

    i psi_t = -1/2 Delta psi + V psi ,   psi = a + i b   ->   a_t = -1/2 Delta b + V b ,  b_t = 1/2 Delta a - V a .

A Gaussian packet of wavenumber K0 runs at a wall (V = V0) with two slits; behind it the two slit waves
interfere. The box is large enough that nothing reaches the periodic edge. Reference: the norm is conserved,
and the fringes on a screen behind the wall are spaced by lambda L / d, lambda = 2 pi / K0.
"""

import jax
import jno.numpy as jnn
import numpy as np
from scipy.signal import find_peaks

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
K0, SX, SY, X0 = 6.0, 1.5, 5.0, -8.0  # packet: wavenumber, widths, start
V0, WALL, GAP, SLIT = 200.0, 0.4, 5.0, 1.5  # wall height and thickness, slit spacing d, slit width
XS = 12.0  # the screen sits at x = XS
LX, LY, NX, NY = (-30.0, 30.0), (-24.0, 24.0), 768, 512
T, STEPS, FRAMES = 4.4, 4400, 111

d = jno.shape.rect(LX[0], LY[0], LX[1], LY[1]).domain(time=(0.0, T, STEPS + 1))
A, B = d.unknown(space="spectral", order=(NX, NY)), d.unknown(space="spectral", order=(NX, NY))
x, y, t = d.variable("interior", split=True)
x0, y0, _ = d.variable("initial", split=True)
a, b = A.bind(x=x, y=y, t=t), B.bind(x=x, y=y, t=t)
lap = lambda w: w.xx + w.yy
box = lambda s, lo, hi, e=0.04: 0.5 * (jnn.tanh((s - lo) / e) - jnn.tanh((s - hi) / e))  # smooth indicator of [lo, hi]
slits = box(y, -GAP / 2 - SLIT / 2, -GAP / 2 + SLIT / 2) + box(y, GAP / 2 - SLIT / 2, GAP / 2 + SLIT / 2)
V = V0 * box(x, -WALL / 2, WALL / 2) * (1 - slits)  # the wall, with two slits cut out
G = jnn.exp(-((x0 - X0) ** 2 / (2 * SX**2) + y0**2 / (2 * SY**2))) / np.sqrt(2 * np.pi * SX * SY)  # norm 1

(xl, yl, _), (xr, yr, _) = d.variable("left", split=True), d.variable("right", split=True)
(xb, yb, _), (xt, yt, _) = d.variable("bottom", split=True), d.variable("top", split=True)

fields = jno.spectral(
    [
        a.t + 0.5 * lap(b) - V * b,  # Re of  i psi_t = -1/2 lap psi + V psi
        b.t - 0.5 * lap(a) + V * a,  # Im
        A(x0, y0) - G * jnn.cos(K0 * x0),  # the packet, wavenumber K0 along x
        B(x0, y0) - G * jnn.sin(K0 * x0),
        *[P(*lo) - P(*hi) for P in (A, B) for lo, hi in (((xl, yl), (xr, yr)), ((xb, yb), (xt, yt)))],  # periodic box
    ]
).solve(time=jno.solve.etdrk4(), save_ts=np.linspace(0.0, T, FRAMES))
re, im = (np.asarray(f) for f in fields)  # (FRAMES, nodes)

# Checks. The box is Fourier on a uniform grid: the norm is a plain sum.
dA = (LX[1] - LX[0]) / NX * (LY[1] - LY[0]) / NY
rho = (re**2 + im**2).reshape(FRAMES, NX, NY)  # |psi|^2 on the grid, x first
ts = np.linspace(0.0, T, FRAMES)
norm = rho.sum((1, 2)) * dA
drift = np.abs(norm / norm[0] - 1).max()
edge = max(rho[:, [0, -1], :].max(), rho[:, :, [0, -1]].max()) / rho.max()
xs, ys = np.linspace(*LX, NX, endpoint=False), np.linspace(*LY, NY, endpoint=False)
ix = np.argmin(np.abs(xs - XS))
screen = rho[:, ix, :].sum(0) * (ts[1] - ts[0])  # time-integrated intensity on the screen
lam, L = 2 * np.pi / K0, xs[ix] - WALL / 2  # wavelength; wall face to screen
inside = np.abs(ys) < lam * L / SLIT  # the central lobe of one slit's diffraction
peaks = ys[inside][find_peaks(screen[inside], prominence=0.05 * screen.max())[0]]
central = peaks[np.abs(peaks) < 1.5 * lam * L / GAP]  # the fringe at 0 and its two neighbours
fringe, expected = np.diff(central).mean(), lam * L / GAP
print(
    f"norm drift {drift:.1e}, edge intensity {edge:.1e}; {len(peaks)} fringes, central spacing {fringe:.3f} vs lambda L / d = {expected:.3f}"
)
assert drift < 1e-6 and edge < 1e-3 and abs(fringe / expected - 1) < 0.05
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "schrodinger_double_slit.npz",
        re=re.reshape(FRAMES, NX, NY).astype(np.float32),
        im=im.reshape(FRAMES, NX, NY).astype(np.float32),
        x=xs,
        y=ys,
        t=ts,
        screen=screen,
        ix=ix,
        peaks=peaks,
        expected=expected,
        spacing=np.diff(peaks).mean(),
        params=np.array([K0, GAP, SLIT, WALL, XS, V0]),
    )
