import os
from pathlib import Path

# --8<-- [start:code]
"""Taylor-Green vortex at Re = 400: a smooth 3-D flow breaks down into small scales, in a periodic cube.

    u_t + w x u + grad(P) = nu Delta u ,    w = curl u ,    Delta P = -div(w x u)    (P = p + |u|^2 / 2) ,

from u = (sin x cos y cos z, -cos x sin y cos z, 0) on [0, 2 pi)^3, with nu = 1 / Re. The velocity and the pressure
are Fourier unknowns on an odd number of nodes, the product w x u is formed on a 3/2 padded grid (Orszag), and the
linear terms are integrated exactly by ETDRK4. Checks: the exact initial enstrophy Z = 3 E, the energy budget
dE/dt = -2 nu Z at every saved time, div u at round-off, the reflection symmetries of the flow, and the spectrum of
the dissipation, which must have died out before the highest mode.
"""

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

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
RE, N, L = 400.0, 95, 2 * np.pi  # the Reynolds number, the Fourier nodes per axis (odd: no Nyquist plane), the box
NU, T, STEPS, SEGMENTS, SAVES = 1 / RE, 12.0, 1200, 4, 15  # four marches of 300 steps, 15 saved intervals each


def march(u0, T, steps, nsaves):
    """The velocity at nsaves times in [0, T] from the nodal velocity u0: u_t + w x u + grad(P) = nu Delta u."""
    d = jno.shape.box(0, 0, 0, L, L, L).domain(time=(0.0, T, steps + 1))
    Us = [d.unknown(space="fourier", order=(N, N, N), name=f"u{i}") for i in range(3)]
    Pr = d.unknown(space="fourier", order=(N, N, N), 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 = (U.bind(x=x, y=y, z=z, t=t, scheme=sp) for U in Us)
    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),
            lap(P) + f1.x + f2.y + f3.z,  # Delta P = -div(w x u)
            P.mean,
            *[U(*ci) - jax.numpy.asarray(u0[:, [i]]) for i, U in enumerate(Us)],
            *[F(*lo) - F(*hi) for F in (*Us, 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 Us[0].basis, np.stack([np.asarray(s) for s in sol[:3]], -1)


def diagnostics(B, u):
    """|w| (float32), E, Z, max |div u| and the energy spectrum by shell |k| of one velocity state u (nodes, 3)."""
    k = [B.wavenumbers(i).reshape([-1 if j == i else 1 for j in range(3)]) for i in range(3)]
    c = [B.coeffs(u[:, 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()
    wm = np.sqrt(sum(f**2 for f in w))
    shell = np.rint(np.sqrt(sum(q**2 for q in k))).astype(int).ravel()  # |k| in units of the lowest wavenumber
    ek = np.bincount(shell, 0.5 * sum(abs(np.asarray(q)).ravel() ** 2 for q in c), N)
    return wm.ravel().astype(np.float32), 0.5 * float(B.mean((u**2).sum(1))), 0.5 * float(B.mean(wm.ravel() ** 2)), div, ek


def reflections(u):
    """Largest violation of the flow's mirror symmetries x -> -x, y -> -y, z -> -z about the origin (a node):
    the normal velocity flips sign, the tangential components stay."""
    g = u.reshape(N, N, N, 3)
    worst = 0.0
    for axis in range(3):
        mirror = np.roll(np.flip(g, axis), 1, axis)
        sign = np.ones(3)
        sign[axis] = -1
        worst = max(worst, abs(g - mirror * sign).max())
    return worst


nodes = np.stack(np.meshgrid(*[np.arange(N) * L / N] * 3, indexing="ij"), -1).reshape(-1, 3)
x0, y0, z0 = nodes.T
u = np.stack([np.sin(x0) * np.cos(y0) * np.cos(z0), -np.cos(x0) * np.sin(y0) * np.cos(z0), 0 * x0], -1)

wmag, E, Z, div, spectra, sym = [], [], [], [], [], []
for _ in range(SEGMENTS):
    B, fr = march(u, T / SEGMENTS, STEPS // SEGMENTS, SAVES + 1)
    for v in fr[(1 if wmag else 0) :]:
        wm, e, z, dv, ek = diagnostics(B, v)
        wmag.append(wm), E.append(e), Z.append(z), div.append(dv), spectra.append(ek), sym.append(reflections(v))
    u = fr[-1]
ts = np.linspace(0.0, T, len(E))
E, Z, spectra = np.array(E), np.array(Z), np.array(spectra)

# Exact initial values: E = 1/8 and Z = 3 E = 3/8 for this field.
assert abs(E[0] - 1 / 8) < 1e-13 and abs(Z[0] - 3 * E[0]) < 1e-12

# Energy budget E(t) - E(0) = -2 nu int_0^t Z at every saved time (the integral of a cubic spline through Z).
budget = abs(E - E[0] + 2 * NU * CubicSpline(ts, Z).antiderivative()(ts)).max() / E[0]
tt = np.linspace(0.0, T, 24001)
eps = 2 * NU * CubicSpline(ts, Z)(tt)  # the dissipation rate -dE/dt
t_peak, eps_peak = tt[np.argmax(eps)], eps.max()
assert budget < 1e-4 and max(div) < 1e-10 * max(w.max() for w in wmag) and max(sym) < 1e-10

# Resolution: the dissipation spectrum 2 nu k^2 E(k) at the peak, its share in the shells beyond 2/3 of the highest mode,
# and k_max eta with the Kolmogorov length eta = (nu^3 / eps)^(1/4).
k_peak = int(np.argmax(Z))
dk = 2 * NU * np.arange(N) ** 2 * spectra[k_peak]
tail = dk[2 * (N // 2) // 3 : N // 2 + 1].sum() / dk[: N // 2 + 1].sum()
keta = (N // 2) * (NU**3 / eps_peak) ** 0.25
print(f"E {E[0]:.4f} -> {E[-1]:.4f}, Z {Z[0]:.4f} -> peak {Z.max():.3f}; budget {budget:.1e}; div {max(div):.1e}")
print(f"symmetry {max(sym):.1e}; peak dissipation {eps_peak:.5f} at t = {t_peak:.2f}; kmax eta {keta:.2f}; tail {tail:.1e}")
assert keta > 1.4 and tail < 3e-2
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "taylor_green_vortex_3d.npz",
        w=np.array(wmag).reshape(-1, N, N, N),
        t=ts,
        E=E,
        Z=Z,
        spectra=spectra,
        k_peak=k_peak,
        params=np.array([L, NU, float(N), t_peak, eps_peak]),
    )
