import os
from pathlib import Path

# --8<-- [start:code]
"""Decaying 2-D turbulence on a periodic box: vorticity-streamfunction ETDRK4 with 3/2 dealiasing.

    w_t + psi_y w_x - psi_x w_y = nu Delta w ,    Delta psi = -w ,    u = (psi_y, -psi_x) .

A narrow ring of random-phase modes stretches into thin filaments (direct enstrophy cascade, k^-3 spectrum) while
like-sign vortices merge into larger coherent cores (inverse energy cascade). Checks: mean vorticity stays zero,
kinetic energy E(t) obeys exact viscous decay dE/dt = -2 nu Z(t), and large-scale energy grows while enstrophy falls.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L, N, NU = 2 * np.pi, 384, 1.0e-4
T, STEPS, FRAMES = 24.0, 12000, 97

d = jno.shape.rect(0.0, 0.0, L, L).domain(time=(0.0, T, STEPS + 1))
W = d.unknown(space=("fourier", "fourier"), order=(N, N), name="w")
Psi = d.unknown(space=("fourier", "fourier"), order=(N, N), name="psi")
x, y, t = d.variable("interior", split=True)
x0, y0, _ = d.variable("initial", split=True)
(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)

# Band-limited initial vorticity peaked at k0 = 7.5, normalised to kinetic energy E(0) = 3.0.
kx, ky = 2 * np.pi * np.fft.fftfreq(N, d=L / N), 2 * np.pi * np.fft.rfftfreq(N, d=L / N)
KX, KY = np.meshgrid(kx, ky, indexing="ij")
K2 = KX**2 + KY**2
K = np.sqrt(K2)
rng = np.random.default_rng(7)
amp = np.where(K > 0, np.exp(-0.5 * ((K - 7.5) / 2.0) ** 2), 0.0)
w0 = np.fft.irfft2(amp * np.exp(1j * rng.uniform(0, 2 * np.pi, K.shape)), s=(N, N))
w0 -= w0.mean()
p0 = np.where(K2 > 0, np.fft.rfft2(w0) / np.where(K2 > 0, K2, 1.0), 0.0)
E0 = 0.5 * np.mean(np.fft.irfft2(1j * KY * p0, s=(N, N)) ** 2 + np.fft.irfft2(-1j * KX * p0, s=(N, N)) ** 2) * L**2
w0 *= np.sqrt(3.0 / E0)

dealiased = jno.sp(dealias=3 / 2)
w, psi = W.bind(x=x, y=y, t=t, scheme=dealiased), Psi.bind(x=x, y=y, scheme=dealiased)
ts = np.linspace(0.0, T, FRAMES)
fields = jno.spectral(
    [
        w.t + psi.y * w.x - psi.x * w.y - NU * (w.xx + w.yy),
        psi.xx + psi.yy + w,
        psi.mean,
        W(x0, y0) - jax.numpy.asarray(w0.reshape(-1, 1)),
        *[U(*lo) - U(*hi) for U in (W, Psi) for lo, hi in (((xl, yl), (xr, yr)), ((xb, yb), (xt, yt)))],
    ]
).solve(time=jno.solve.etdrk4(), save_ts=ts)
wf, psif = (np.asarray(f) for f in fields)

# Conservation, viscous dissipation budget, and dual cascade checks.
dA = (L / N) ** 2
E = 0.5 * (psif * wf).sum(1) * dA
Z = 0.5 * (wf**2).sum(1) * dA
diss = 2 * NU * np.trapezoid(Z, ts)
budget = abs((E[-1] - E[0]) + diss) / E[0]

mult = np.where((KY > 0) & (KY < N // 2), 2.0, 1.0)
k_int = np.rint(K).astype(int)
w_hat = np.fft.rfft2(wf.reshape(FRAMES, N, N), axes=(1, 2)) / N**2
P = 0.5 * np.sum(K2 * np.abs(w_hat) ** 2 * mult, axis=(1, 2)) * L**2
i_peak = int(np.argmax(P))
tail_z = 0.5 * float(np.sum(np.where(K >= N / 3, np.abs(w_hat[i_peak]) ** 2 * mult, 0.0))) * L**2


def spectrum(wh):
    e2d = np.where(K2 > 0, 0.5 * np.abs(wh) ** 2 / np.where(K2 > 0, K2, 1.0) * L**2 * mult, 0.0)
    return np.bincount(k_int.ravel(), weights=e2d.ravel(), minlength=N // 2 + 1)


ek0, ekp, ekf = spectrum(w_hat[0]), spectrum(w_hat[i_peak]), spectrum(w_hat[-1])
print(
    f"2-D turbulence {N}^2 (3/2 dealias), nu={NU:g}, {STEPS} steps to t={T}: "
    f"E {E[0]:.3f}->{E[-1]:.3f} ({100 * E[-1] / E[0]:.1f}%), "
    f"Z {Z[0]:.1f}->{Z[-1]:.1f} ({100 * Z[-1] / Z[0]:.1f}%), "
    f"budget err {budget:.2e}, k<=3 energy x{ekf[1:4].sum() / ek0[1:4].sum():.0f}"
)
assert abs(float(wf[-1].mean())) < 1e-12
assert budget < 5e-4 and E[-1] / E[0] > 0.80 and Z[-1] / Z[0] < 0.25
assert ekf[1:4].sum() > 20 * ek0[1:4].sum() and tail_z / Z[i_peak] < 5e-3
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "turbulence_2d_spectral.npz",
        w=wf.reshape(FRAMES, N, N).astype(np.float32),
        t=ts,
        E=E,
        Z=Z,
        P=P,
        k=np.arange(len(ek0)),
        ek0=ek0,
        ekp=ekp,
        ekf=ekf,
        i_peak=i_peak,
        params=np.array([L, NU, float(N)]),
    )
