"""3D incompressible Navier-Stokes solver, pseudo-spectral, Taylor-Green vortex.

Method: pseudo-spectral in space on a periodic cube [0, 2*pi]^3 with
2/3 dealiasing, classical 4th-order Runge-Kutta in time. The nonlinear
term is evaluated in physical space; derivatives and the divergence-free
projection are applied in Fourier space. Viscosity is treated as part of
the Runge-Kutta right-hand side (no integrating factor).

Initial condition: Taylor-Green vortex, the standard test case,
  u = sin(x) cos(y) cos(z)
  v = -cos(x) sin(y) cos(z)
  w = 0
which is divergence free and periodic.

Diagnostics, all volume averaged over the cube unless stated:
  energy    = 0.5 * mean(|u|^2)
  enstrophy = 0.5 * mean(|omega|^2), omega = curl(u)
  max vorticity = max over grid of |omega|
  max velocity  = max over grid of |u|

Stayed smooth: True when the run completes to the final time with all
diagnostics finite (no NaN or inf) and no blowup of max vorticity to
non-finite values. This is a statement about this run on this grid,
not a statement about the continuum equations.

No em dashes are used anywhere in this file.
"""

import json
import time

import numpy as np


def build_wavenumbers(n):
    k = np.fft.fftfreq(n, d=1.0 / n)
    kx, ky, kz = np.meshgrid(k, k, k, indexing="ij")
    return kx, ky, kz


def dealias_mask(kx, ky, kz, n):
    kmax = n // 3
    return (np.abs(kx) <= kmax) & (np.abs(ky) <= kmax) & (np.abs(kz) <= kmax)


def project_divergence_free(uh, vh, wh, kx, ky, kz, k2):
    k2_safe = np.where(k2 == 0, 1.0, k2)
    div = kx * uh + ky * vh + kz * wh
    factor = div / k2_safe
    factor = np.where(k2 == 0, 0.0, factor)
    return uh - kx * factor, vh - ky * factor, wh - kz * factor


def rhs(uh, vh, wh, kx, ky, kz, k2, mask, nu):
    # Physical-space velocities.
    u = np.fft.ifftn(uh).real
    v = np.fft.ifftn(vh).real
    w = np.fft.ifftn(wh).real
    # Derivatives in Fourier space, back to physical space.
    dudx = np.fft.ifftn(1j * kx * uh).real
    dudy = np.fft.ifftn(1j * ky * uh).real
    dudz = np.fft.ifftn(1j * kz * uh).real
    dvdx = np.fft.ifftn(1j * kx * vh).real
    dvdy = np.fft.ifftn(1j * ky * vh).real
    dvdz = np.fft.ifftn(1j * kz * vh).real
    dwdx = np.fft.ifftn(1j * kx * wh).real
    dwdy = np.fft.ifftn(1j * ky * wh).real
    dwdz = np.fft.ifftn(1j * kz * wh).real
    # Nonlinear term (u . grad) u, then to Fourier space and dealiased.
    nl_u = np.fft.fftn(u * dudx + v * dudy + w * dudz) * mask
    nl_v = np.fft.fftn(u * dvdx + v * dvdy + w * dvdz) * mask
    nl_w = np.fft.fftn(u * dwdx + v * dwdy + w * dwdz) * mask
    # Viscous term plus nonlinear term, then project onto divergence free.
    du = -nl_u - nu * k2 * uh
    dv = -nl_v - nu * k2 * vh
    dw = -nl_w - nu * k2 * wh
    return project_divergence_free(du, dv, dw, kx, ky, kz, k2)


def diagnostics(uh, vh, wh, kx, ky, kz, k2):
    u = np.fft.ifftn(uh).real
    v = np.fft.ifftn(vh).real
    w = np.fft.ifftn(wh).real
    # Vorticity in Fourier space: omega = i k x u_hat.
    oxh = 1j * (ky * wh - kz * vh)
    oyh = 1j * (kz * uh - kx * wh)
    ozh = 1j * (kx * vh - ky * uh)
    ox = np.fft.ifftn(oxh).real
    oy = np.fft.ifftn(oyh).real
    oz = np.fft.ifftn(ozh).real
    energy = 0.5 * float(np.mean(u**2 + v**2 + w**2))
    enstrophy = 0.5 * float(np.mean(ox**2 + oy**2 + oz**2))
    max_vort = float(np.max(np.sqrt(ox**2 + oy**2 + oz**2)))
    max_vel = float(np.max(np.sqrt(u**2 + v**2 + w**2)))
    return energy, enstrophy, max_vort, max_vel


def run_fields(u0, v0, w0, n=32, nu=0.01, dt=0.01, final_time=10.0,
               record_every=10):
    uh = np.fft.fftn(u0)
    vh = np.fft.fftn(v0)
    wh = np.fft.fftn(w0)
    kx, ky, kz = build_wavenumbers(n)
    k2 = kx**2 + ky**2 + kz**2
    mask = dealias_mask(kx, ky, kz, n)
    uh, vh, wh = project_divergence_free(uh, vh, wh, kx, ky, kz, k2)

    steps = int(round(final_time / dt))
    times = []
    enstrophies = []
    max_vorts = []
    energies = []
    max_vels = []

    def record(t):
        e, ens, mv, mvel = diagnostics(uh, vh, wh, kx, ky, kz, k2)
        times.append(t)
        energies.append(e)
        enstrophies.append(ens)
        max_vorts.append(mv)
        max_vels.append(mvel)
        return e, ens, mv, mvel

    t_start = time.time()
    e0, ens0, mv0, mvel0 = record(0.0)
    for step in range(1, steps + 1):
        k1 = rhs(uh, vh, wh, kx, ky, kz, k2, mask, nu)
        k2s = rhs(uh + 0.5 * dt * k1[0], vh + 0.5 * dt * k1[1],
                  wh + 0.5 * dt * k1[2], kx, ky, kz, k2, mask, nu)
        k3s = rhs(uh + 0.5 * dt * k2s[0], vh + 0.5 * dt * k2s[1],
                  wh + 0.5 * dt * k2s[2], kx, ky, kz, k2, mask, nu)
        k4s = rhs(uh + dt * k3s[0], vh + dt * k3s[1],
                  wh + dt * k3s[2], kx, ky, kz, k2, mask, nu)
        uh = uh + (dt / 6.0) * (k1[0] + 2.0 * k2s[0] + 2.0 * k3s[0] + k4s[0])
        vh = vh + (dt / 6.0) * (k1[1] + 2.0 * k2s[1] + 2.0 * k3s[1] + k4s[1])
        wh = wh + (dt / 6.0) * (k1[2] + 2.0 * k2s[2] + 2.0 * k3s[2] + k4s[2])
        uh, vh, wh = uh * mask, vh * mask, wh * mask
        uh, vh, wh = project_divergence_free(uh, vh, wh, kx, ky, kz, k2)
        if step % record_every == 0 or step == steps:
            record(step * dt)
    runtime = time.time() - t_start

    ens_arr = np.array(enstrophies)
    mv_arr = np.array(max_vorts)
    finite = bool(np.all(np.isfinite(ens_arr)) and np.all(np.isfinite(mv_arr))
                  and np.all(np.isfinite(energies)))
    stayed_smooth = finite
    result = {
        "method": "Pseudo-spectral (Fourier, 2/3 dealiasing) with classical "
                  "4th-order Runge-Kutta; periodic cube [0, 2*pi]^3; "
                  "enstrophy = 0.5*mean(|omega|^2), "
                  "energy = 0.5*mean(|u|^2)",
        "grid": [n, n, n],
        "viscosity": nu,
        "dt": dt,
        "final_time": final_time,
        "steps": steps,
        "runtime_seconds": round(runtime, 2),
        "enstrophy_initial": float(ens_arr[0]),
        "enstrophy_final": float(ens_arr[-1]),
        "enstrophy_peak": float(np.max(ens_arr)),
        "max_vorticity_initial": float(mv_arr[0]),
        "max_vorticity_final": float(mv_arr[-1]),
        "max_vorticity_peak": float(np.max(mv_arr)),
        "energy_initial": float(energies[0]),
        "energy_final": float(energies[-1]),
        "max_velocity_initial": float(max_vels[0]),
        "max_velocity_final": float(max_vels[-1]),
        "stayed_smooth": stayed_smooth,
        "date": "2026-11-20",
    }
    series = {
        "time": [float(t) for t in times],
        "enstrophy": [float(e) for e in enstrophies],
        "max_vorticity": [float(m) for m in max_vorts],
        "energy": [float(e) for e in energies],
        "max_velocity": [float(m) for m in max_vels],
    }
    return result, series


def taylor_green(n):
    x = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
    xx, yy, zz = np.meshgrid(x, x, x, indexing="ij")
    u0 = np.sin(xx) * np.cos(yy) * np.cos(zz)
    v0 = -np.cos(xx) * np.sin(yy) * np.cos(zz)
    w0 = np.zeros_like(u0)
    return u0, v0, w0


def run(n=32, nu=0.01, dt=0.01, final_time=10.0, record_every=10):
    u0, v0, w0 = taylor_green(n)
    result, series = run_fields(u0, v0, w0, n=n, nu=nu, dt=dt,
                                final_time=final_time,
                                record_every=record_every)
    result["method"] = result["method"].replace(
        "periodic cube", "Taylor-Green vortex initial condition; periodic cube")
    return result, series


if __name__ == "__main__":
    result, series = run()
    print(json.dumps(result, indent=2))
    ens_growth = result["enstrophy_final"] / result["enstrophy_initial"]
    ens_peak_growth = result["enstrophy_peak"] / result["enstrophy_initial"]
    vort_growth = result["max_vorticity_final"] / result["max_vorticity_initial"]
    vort_peak_growth = result["max_vorticity_peak"] / result["max_vorticity_initial"]
    print("enstrophy growth factor (final/initial): %.4f" % ens_growth)
    print("enstrophy growth factor (peak/initial): %.4f" % ens_peak_growth)
    print("max vorticity growth factor (final/initial): %.4f" % vort_growth)
    print("max vorticity growth factor (peak/initial): %.4f" % vort_peak_growth)
    print("stayed smooth to final time: %s" % result["stayed_smooth"])
    with open("data/navier_stokes.json", "w") as fh:
        json.dump(result, fh, indent=2)
    with open("data/navier_stokes_series.json", "w") as fh:
        json.dump(series, fh, indent=2)
    print("wrote data/navier_stokes.json and data/navier_stokes_series.json")
