import os
from pathlib import Path

# --8<-- [start:code]
"""A buoyant smoke plume in 3-D, Boussinesq: a heated disc launches a plume that rolls up into a mushroom cap.

    u_t + w x u + grad(P) = nu Delta u + A g (theta - <theta>) e_z ,    div u = 0 ,
    theta_t + u . grad(theta) = kappa Delta theta + Q(x, y, z) - sigma(z) theta ,

in a periodic box (velocity-pressure form, ETDRK4, 3/2 dealiasing; P = p + |u|^2 / 2). Q is a Gaussian heat source
just above the floor of the picture, sigma is an absorbing layer that cools and slows the fluid leaving through the top, so
the heat balance is  d/dt int theta = int Q - int sigma theta.  The buoyancy is that of theta about its box mean
<theta>: in a periodic box a net lift would accelerate the whole fluid. Checks: that balance at every saved time and
div u at round-off.
"""

import jax
import numpy as np
from scipy.interpolate import CubicSpline

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
AG, NU, KAPPA = 2.0, 5.0e-4, 5.0e-4  # buoyancy A g per unit temperature, viscosity, diffusivity
Q0, RADIUS, THICK, ZS = 2.0, 0.16, 0.06, 0.4  # peak heating rate, radius and thickness of the heated disc, its height
SIG0, ZA, WA = 4.0, 2.55, 0.1  # the absorbing layer: rate, where it begins, how sharply
LXY, LZ, NXY, NZ = 1.6, 3.2, 81, 161  # the box and its nodes (odd: no Nyquist mode)
T, STEPS, SEGMENTS, SAVES = 14.0, 1440, 6, 16  # six marches of 240 steps, 16 saved intervals each


def march(q0, T, steps, nsaves):
    """(u, theta) at nsaves times in [0, T] from the nodal values q0 (nodes, 4)."""
    d = jno.shape.box(0, 0, 0, LXY, LXY, LZ).domain(time=(0.0, T, steps + 1))
    Q = [d.unknown(space="fourier", order=(NXY, NXY, NZ), name=n) for n in ("u1", "u2", "u3", "th")]
    Pr = d.unknown(space="fourier", order=(NXY, NXY, 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, th = (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
    sigma = SIG0 * (1 + jno.np.tanh((z - ZA) / WA)) / 2  # the absorbing layer: it also damps the velocity
    heat = Q0 * jno.np.exp(-((x - LXY / 2) ** 2 + (y - LXY / 2) ** 2) / RADIUS**2 - ((z - ZS) / THICK) ** 2)
    sol = jno.spectral(
        [
            u1.t + f1 + P.x - NU * lap(u1) + sigma * u1,
            u2.t + f2 + P.y - NU * lap(u2) + sigma * u2,
            u3.t + f3 + P.z - NU * lap(u3) - AG * (th - th.mean) + sigma * u3,  # hot fluid rises, the box does not
            th.t + u1 * th.x + u2 * th.y + u3 * th.z - KAPPA * lap(th) - heat + sigma * th,
            lap(P)
            + f1.x
            + f2.y
            + f3.z
            - AG * th.z
            + (sigma * u1).x
            + (sigma * u2).y
            + (sigma * u3).z,  # Delta P = -div(w x u) + A g theta_z - div(sigma u)
            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):
    """Per state q (nodes, 4): the heat int theta, the heat absorbed per time int sigma theta, the largest |div u|,
    the kinetic energy, the height of the highest node where theta exceeds 0.1 of its maximum and the box-mean w."""
    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)]
    div = abs(sum(np.asarray(B.values(1j * k[a] * c[a])) for a in range(3))).max()
    z = np.asarray(B.nodes)[:, 2]
    sigma = SIG0 * (1 + np.tanh((z - ZA) / WA)) / 2
    vol = LXY * LXY * LZ
    uz = float(B.mean(q[:, 2]))
    hot = np.flatnonzero(q[:, 3] > 0.1 * q[:, 3].max())
    return (
        float(B.mean(q[:, 3])) * vol,
        float(B.mean(sigma * q[:, 3])) * vol,
        div,
        0.5 * float(B.mean((q[:, :3] ** 2).sum(1))) * vol,
        z[hot].max() if len(hot) else 0.0,
        uz,
    )


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(1)
q = np.zeros(NODES.shape[:-1] + (4,))
q[..., 3] = 1e-4 * rng.standard_normal(NODES.shape[:-1])  # a trace of noise to break the symmetry of the start
q = q.reshape(-1, 4)
theta, heat, out, div, Ek, front, uzs = [], [], [], [], [], [], []
for _ in range(SEGMENTS):
    B, fr = march(q, T / SEGMENTS, STEPS // SEGMENTS, SAVES + 1)
    for f in fr[(1 if theta else 0) :]:
        h, o, dv, e, zf, uz = diagnostics(B, f)
        (
            theta.append(f[:, 3].astype(np.float32)),
            heat.append(h),
            out.append(o),
            div.append(dv),
            Ek.append(e),
            front.append(zf),
            uzs.append(uz),
        )
    q = fr[-1]
ts = np.linspace(0.0, T, len(heat))
X, Y, Z = NODES[..., 0], NODES[..., 1], NODES[..., 2]
H = (
    Q0 * np.exp(-((X - LXY / 2) ** 2 + (Y - LXY / 2) ** 2) / RADIUS**2 - ((Z - ZS) / THICK) ** 2).mean() * LXY * LXY * LZ
)  # int Q
absorbed = CubicSpline(ts, out).antiderivative()(ts)  # the heat removed by the absorbing layer up to t
balance = abs(np.array(heat) - H * ts + absorbed).max() / (H * T)
print(
    f"plume {NXY}x{NXY}x{NZ}, {STEPS} steps: heat in {H * T:.4f}, stored {heat[-1]:.4f}, absorbed {absorbed[-1]:.4f}, ",
    end="",
)
print(
    f"balance {balance:.1e}, max |div u| {max(div):.1e}, mean w {max(map(abs, uzs)):.1e}, front at z = {front[-1]:.2f} (theta max {max(f.max() for f in theta):.2f})"
)
assert balance < 2e-3 and max(div) < 1e-9 and max(map(abs, uzs)) < 1e-12  # the box does not lift
# --8<-- [end:code]

if out_dir := os.environ.get("JNO_FIGURE_DATA"):
    th = np.array(theta).reshape(-1, NXY, NXY, NZ)
    np.savez_compressed(
        Path(out_dir) / "buoyant_plume_3d.npz",
        theta=th,
        t=ts,
        heat=heat,
        absorbed=absorbed,
        front=front,
        Ek=Ek,
        params=np.array([LXY, LZ, H, ZS, ZA]),
    )
