import os
from pathlib import Path

# --8<-- [start:code]
"""Kelvin-Helmholtz shear instability in a Fourier x Chebyshev channel: vorticity-streamfunction with BDF2.

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

Periodic in x (Fourier, 3/2 dealiasing), free-slip walls at y = +-1 (Chebyshev, w = 0, psi = psi_wall).
Checks: the wall vorticity stays zero, the vertical kinetic energy grows into billows, and the spectra of
both axes decay.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
LX, DELTA, RE = 4.0, 0.16, 600.0
NX, NY = 48, 29
T, STEPS, FRAMES = 16.0, 140, 71

d = jno.shape.rect(0.0, -1.0, LX, 1.0).domain(time=(0.0, T, STEPS + 1))
W = d.unknown(space=("fourier", "chebyshev"), order=(NX, NY), name="w")
Psi = d.unknown(space=("fourier", "chebyshev"), order=(NX, NY), 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)

# Counter-flowing shear layer u_0(y) = tanh(y/delta) perturbed by primary (k_2) and subharmonic (k_1) streamfunction modes.
P_nodes = W.basis.nodes
X0, Y0 = P_nodes[:, 0], P_nodes[:, 1]
k1, k2 = 2 * np.pi / LX, 4 * np.pi / LX
A2, A1, SIG = 0.030, 0.010, 2 * DELTA
env = np.exp(-((Y0 / SIG) ** 2))
wave = A2 * np.cos(k2 * X0) + A1 * np.cos(k1 * X0 + 0.4)
wave_xx = -(k2**2) * A2 * np.cos(k2 * X0) - (k1**2) * A1 * np.cos(k1 * X0 + 0.4)
env_yy = (4 * Y0**2 / SIG**4 - 2.0 / SIG**2) * env
w0 = -(1.0 / DELTA) / (np.cosh(Y0 / DELTA) ** 2) - (env * wave_xx + env_yy * wave)
psi_wall = float(DELTA * np.log(np.cosh(1.0 / DELTA)))

sch = jno.sp(dealias=3 / 2)
w = W.bind(x=x, y=y, t=t, scheme=sch)
psi = Psi.bind(x=x, y=y, scheme=sch)
ts = np.linspace(0.0, T, FRAMES)

wf, psif = jno.spectral(
    [
        w.t + psi.y * w.x - psi.x * w.y - (1.0 / RE) * (w.xx + w.yy),
        psi.xx + psi.yy + w,
        W(x0, y0) - jax.numpy.asarray(w0.reshape(-1, 1)),
        W(xb, yb) - 0.0,
        W(xt, yt) - 0.0,
        Psi(xb, yb) - psi_wall,
        Psi(xt, yt) - psi_wall,
        W(xl, yl) - W(xr, yr),
        Psi(xl, yl) - Psi(xr, yr),
    ]
).solve(time=jno.solve.bdf2(), precond=jno.precond.spectral(), save_ts=ts)
wf, psif = np.asarray(wf), np.asarray(psif)

# Compute vertical velocity v = -psi_x, vertical kinetic energy E_v(t), and enstrophy Z(t).
ev = np.empty(FRAMES)
Z = np.empty(FRAMES)
for k in range(FRAMES):
    vk = -np.asarray(Psi.basis.grid.diff(psif[k], (1, 0))).reshape(-1)
    ev[k] = 0.5 * float(Psi.basis.integrate(vk**2))
    Z[k] = 0.5 * float(W.basis.integrate(wf[k] ** 2))

i_peak = int(np.argmax(ev))

# Fourier and Chebyshev modal spectra of vorticity at peak roll-up.
w_hat = np.abs(np.asarray(W.basis.coeffs(wf[i_peak])))  # (NX, NY)
f_spec = np.sqrt(np.mean(w_hat**2, axis=1))
f_modes = np.zeros(NX // 2 + 1)
f_modes[0] = f_spec[0]
f_modes[1 : NX // 2] = np.sqrt(f_spec[1 : NX // 2] ** 2 + f_spec[NX - 1 : NX // 2 : -1] ** 2)
f_modes[NX // 2] = f_spec[NX // 2]
t_modes = np.sqrt(np.mean(w_hat**2, axis=0))

# Evaluate vorticity on a uniform fine grid via exact spectral interpolation for rendering.
nx_p, ny_p = 240, 120
xg = np.linspace(0.0, LX, nx_p, endpoint=False)
yg = np.linspace(-1.0, 1.0, ny_p)
XX, YY = np.meshgrid(xg, yg, indexing="ij")
xq, yq = XX.ravel(), YY.ravel()
w_plot = np.stack([np.asarray(W.basis(wf[k], xq, yq)).reshape(nx_p, ny_p) for k in range(FRAMES)])

w_wall_err = float(max(np.abs(wf[-1].reshape(NX, NY)[:, 0]).max(), np.abs(wf[-1].reshape(NX, NY)[:, -1]).max()))
print(
    f"Kelvin-Helmholtz {NX}x{NY} (Fourier x Chebyshev, BDF2), Re={RE:g}, {STEPS} steps: "
    f"E_v {ev[1]:.3e} at t={ts[1]:.2f} -> peak {ev[i_peak]:.4f} at t={ts[i_peak]:.1f}, "
    f"wall|w|={w_wall_err:.2e}, tail(F)={f_modes[-1] / f_modes.max():.2e}, tail(T)={t_modes[-1] / t_modes.max():.2e}"
)
assert w_wall_err < 1e-11
assert ev[i_peak] > 8.0 * ev[1], f"too little growth: {ev[i_peak] / ev[1]:.1f}x"  # frame 0 holds no psi yet
assert f_modes[-1] / f_modes.max() < 5e-3 and t_modes[-1] / t_modes.max() < 5e-3
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "kelvin_helmholtz_spectral.npz",
        w=w_plot.astype(np.float32),
        t=ts,
        ev=ev,
        Z=Z,
        i_peak=i_peak,
        f_modes=f_modes,
        t_modes=t_modes,
        params=np.array([LX, RE, float(NX), float(NY)]),
    )
