import os
from pathlib import Path

# --8<-- [start:code]
"""Rayleigh-Taylor instability in 3-D, Boussinesq: heavy fluid over light, in a periodic box, ETDRK4.

    u_t + w x u + grad(P) = nu Delta u - A g s e_z ,    div u = 0 ,    s_t + u . grad(s) = kappa Delta s ,

with w = curl u, P = p + |u|^2 / 2, so that Delta P = -div(w x u) - A g s_z. The scalar s in [-1, 1] is the density
(heavy: s = +1) and A is the Atwood number. The box holds one heavy slab: its lower face (heavy over light) is
the unstable interface, its upper face is stable. Checks: the growth rate of a single mode against the viscous,
diffusive dispersion relation (an eigenvalue problem for the diffusing profile), the mean of s, the energy budget
d(E + PE)/dt = -nu int |w|^2, and div u at round-off.
"""

import jax
import numpy as np
from scipy.interpolate import CubicSpline
from scipy.linalg import eigvals
from scipy.special import erf

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
AG, NU, KAPPA, DELTA = 1.0, 5.0e-4, 5.0e-4, 0.03  # A g, viscosity, diffusivity, initial half-width of the interface
LZ, Z1, Z2 = 3.0, 0.75, 2.25  # box height; the unstable interface at Z1, the stable one at Z2 (heavy half: mean s = 0)
LXY, NXY, NZ = 1.0, 73, 221  # the 3-D box (side, nodes across, nodes along z; all odd: no Nyquist mode)
T, STEPS, SEGMENTS, SAVES = 2.1, 1050, 3, 35  # the 3-D run: three marches of 350 steps, 35 saved intervals each


def profile(z, h=0.0, delta=DELTA):
    """Density of the heavy slab Z1 < z < Z2 with an interface at Z1 + h of half-width delta: s = -1 outside."""
    return erf((z - Z1 - h) / delta) - erf((z - Z2) / delta) - 1.0


def march(q0, box, T, steps, nsaves, kappa=KAPPA):
    """(u, s) at nsaves times in [0, T] from the nodal values q0 (nodes, 4) in a periodic box (lx, ly, lz, nx, ny, nz)."""
    lx, ly, lz, nx, ny, nz = box
    d = jno.shape.box(0, 0, 0, lx, ly, lz).domain(time=(0.0, T, steps + 1))
    Q = [d.unknown(space="fourier", order=(nx, ny, nz), name=n) for n in ("u1", "u2", "u3", "s")]
    Pr = d.unknown(space="fourier", order=(nx, ny, nz), name="P")
    x, y, z, t = d.variable("interior", split=True)
    ci = d.variable("initial", split=True)
    pairs = [
        (d.variable(a, split=True), d.variable(b, split=True))
        for a, b in (("left", "right"), ("bottom", "top"), ("front", "back"))
    ]
    sp = jno.sp(dealias=3 / 2)
    u1, u2, u3, s = (F.bind(x=x, y=y, z=z, t=t, scheme=sp) for F in Q)
    P = Pr.bind(x=x, y=y, z=z, scheme=sp)
    lap = lambda f: f.xx + f.yy + f.zz
    w1, w2, w3 = u3.y - u2.z, u1.z - u3.x, u2.x - u1.y  # the vorticity curl(u)
    f1, f2, f3 = w2 * u3 - w3 * u2, w3 * u1 - w1 * u3, w1 * u2 - w2 * u1  # w x u
    sol = jno.spectral(
        [
            u1.t + f1 + P.x - NU * lap(u1),
            u2.t + f2 + P.y - NU * lap(u2),
            u3.t + f3 + P.z - NU * lap(u3) + AG * s,  # buoyancy: heavy fluid (s > 0) is pulled down
            s.t + u1 * s.x + u2 * s.y + u3 * s.z - kappa * lap(s),
            lap(P) + f1.x + f2.y + f3.z + AG * s.z,  # Delta P = -div(w x u) - A g s_z
            P.mean,
            *[F(*ci) - jax.numpy.asarray(q0[:, [i]]) for i, F in enumerate(Q)],
            *[F(*lo) - F(*hi) for F in (*Q, Pr) for lo, hi in pairs],  # periodic in x, y and z
        ]
    ).solve(time=jno.solve.etdrk4(), save_ts=np.linspace(0.0, T, nsaves))
    return Q[0].basis, np.stack([np.asarray(f) for f in sol[:4]], -1)


def diagnostics(B, q, lz):
    """Per state q (nodes, 4): kinetic energy, potential energy A g int s z, dissipation nu int |w|^2, mean s, the
    largest |div u| and the vorticity magnitude |w| (float32), from the Fourier coefficients: w = i k x u_hat."""
    k = [B.wavenumbers(i).reshape([-1 if j == i else 1 for j in range(3)]) for i in range(3)]
    c = [B.coeffs(q[:, i]) for i in range(3)]
    ddx = lambda f, a: np.asarray(B.values(1j * k[a] * f))
    w = [ddx(c[2], 1) - ddx(c[1], 2), ddx(c[0], 2) - ddx(c[2], 0), ddx(c[1], 0) - ddx(c[0], 1)]
    div = abs(ddx(c[0], 0) + ddx(c[1], 1) + ddx(c[2], 2)).max()
    wm2 = sum(f**2 for f in w).ravel()
    vol = lz * LXY * LXY
    z = np.asarray(B.nodes)[:, 2]
    return (
        0.5 * float(B.mean((q[:, :3] ** 2).sum(1))) * vol,
        AG * float(B.mean(q[:, 3] * z)) * vol,
        NU * float(B.mean(wm2)) * vol,
        float(B.mean(q[:, 3])),
        div,
        np.sqrt(wm2).astype(np.float32),
    )


def growth_rate(k, delta, kappa=KAPPA):
    """Largest growth rate of a mode exp(i k x) on the frozen profile s0(z) of half-width delta (both interfaces),
    from the linearised equations  sigma (D^2-k^2) w = nu (D^2-k^2)^2 w + A g k^2 s',  sigma s' = -s0' w + kappa (D^2-k^2) s'
    on a Fourier collocation grid in z."""
    n = 512
    z = np.arange(n) * LZ / n
    kz = 2 * np.pi * np.fft.fftfreq(n, LZ / n)
    D2 = np.real(np.fft.ifft(-(kz[:, None] ** 2) * np.fft.fft(np.eye(n), axis=0), axis=0)) - k**2 * np.eye(n)  # D^2 - k^2
    ds0 = 2 / (delta * np.sqrt(np.pi)) * (np.exp(-(((z - Z1) / delta) ** 2)) - np.exp(-(((z - Z2) / delta) ** 2)))
    M = np.block([[NU * D2, AG * k**2 * np.linalg.inv(D2)], [-np.diag(ds0), kappa * D2]])
    return float(eigvals(M).real.max())


# 1. One mode in a thin box. A small cosine ripple of the unstable interface grows at the rate of the eigenvalue
#    problem for the frozen profile; the density diffuses much more slowly here (kappa = 2e-5) so that the profile
#    stays frozen, which the eigenvalue problem assumes (with kappa = nu the interface widens as fast as the mode grows).
KAPPA1, LAM, A0, T1, N1 = 2.0e-5, 0.5, 2.0e-4, 1.8, 46
nx1, ny1, nz1 = 43, 5, NZ
nodes = np.stack(np.meshgrid(*[np.arange(n) * L / n for n, L in ((nx1, LAM), (ny1, LAM), (nz1, LZ))], indexing="ij"), -1)
q1 = np.zeros(nodes.shape[:-1] + (4,))
q1[..., 3] = profile(nodes[..., 2], A0 * np.cos(2 * np.pi * nodes[..., 0] / LAM))
B, fr = march(q1.reshape(-1, 4), (LAM, LAM, LZ, nx1, ny1, nz1), T1, 450, N1, KAPPA1)
ts1 = np.linspace(0.0, T1, N1)[1:]
rms = np.array([float(np.sqrt(B.mean(f[:, 2] ** 2))) for f in fr[1:]])  # amplitude of the mode: rms of w
rate = np.gradient(np.log(rms), ts1)  # d ln|w| / dt
k1 = 2 * np.pi / LAM
rate_th = np.array([growth_rate(k1, np.sqrt(DELTA**2 + 4 * KAPPA1 * t), KAPPA1) for t in ts1])
late = ts1 > 1.2  # after the start-up from rest (the rate settles on the eigenmode), while the ripple is still small
dev = abs(rate[late] / rate_th[late] - 1).max()
print(f"one mode, k = {k1:.2f}: inviscid sharp sqrt(A g k) = {np.sqrt(AG * k1):.3f}; ", end="")
print(f"measured {rate[late].mean():.3f}, dispersion relation {rate_th[late].mean():.3f} (largest deviation {dev:.1%})")
assert dev < 0.01

# 2. The 3-D run: the interface starts displaced by a few low modes of random phase; march in segments, keep the
#    diagnostics of every saved state.
NODES = np.stack(np.meshgrid(*[np.arange(n) * L / n for n, L in ((NXY, LXY), (NXY, LXY), (NZ, LZ))], indexing="ij"), -1)
rng = np.random.default_rng(3)
modes = [(2, 0), (0, 2), (2, 2), (2, -2), (3, 1), (1, 3)]
h = sum(
    0.004 * np.cos(2 * np.pi * (a * NODES[..., 0] + b * NODES[..., 1]) / LXY + rng.uniform(0, 2 * np.pi)) for a, b in modes
)
q = np.zeros(NODES.shape[:-1] + (4,))
q[..., 3] = profile(NODES[..., 2], h)
q = q.reshape(-1, 4)
sfield, Ek, Ep, Dis, mean_s, div, edge = [], [], [], [], [], [], []
for _ in range(SEGMENTS):
    B, fr = march(q, (LXY, LXY, LZ, NXY, NXY, NZ), T / SEGMENTS, STEPS // SEGMENTS, SAVES + 1)
    for f in fr[(1 if sfield else 0) :]:
        e, p, dd, m, dv, wm = diagnostics(B, f, LZ)
        (
            sfield.append(f[:, 3].astype(np.float32)),
            Ek.append(e),
            Ep.append(p),
            Dis.append(dd),
            mean_s.append(m),
            div.append(dv),
        )
        edge.append(abs(f[:, 3].reshape(NXY, NXY, NZ)[:, :, [0, -1]] + 1).max())
    q = fr[-1]
ts = np.linspace(0.0, T, len(Ek))
Ek, Ep, Dis = np.array(Ek), np.array(Ep), np.array(Dis)

drift = abs(np.array(mean_s) - mean_s[0]).max()
spline = CubicSpline(ts, Dis).antiderivative()(ts)  # the dissipated energy int_0^t nu |w|^2
budget = abs(Ek + Ep - (Ek[0] + Ep[0]) + spline).max() / abs(Ep[0] - Ep[-1])  # against the potential energy released
tail = float(
    np.abs(B.coeffs(q[:, 3])).reshape(NXY, NXY, NZ)[NXY // 3 + 1 : 2 * NXY // 3, :, :].max()
    / np.abs(B.coeffs(q[:, 3])).max()
)  # s spectrum across x beyond 2/3 of the highest mode
print(f"3-D run {NXY}x{NXY}x{NZ}, {STEPS} steps: E_k up to {Ek.max():.4f}, E_p {Ep[0]:.4f} -> {Ep[-1]:.4f}, ", end="")
print(
    f"budget {budget:.1e}, mean(s) drift {drift:.1e}, max |div u| {max(div):.1e}, far field {max(edge):.1e}, s tail {tail:.1e}"
)
assert budget < 2e-4 and tail < 1e-3 and drift < 1e-12 and max(edge) < 2e-2 and max(div) < 1e-9
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "rayleigh_taylor_3d.npz",
        s=np.array(sfield).reshape(-1, NXY, NXY, NZ),
        t=ts,
        Ek=Ek,
        Ep=Ep,
        Dis=Dis,
        params=np.array([LXY, LZ, Z1, Z2, AG, NU, KAPPA]),
        z=NODES[0, 0, :, 2],
        single=np.array([ts1, rate, rate_th]),
    )
