"""Navier-Stokes blowup hunt, round 4.

Lower viscosity: nu = 0.0005, half the round 2 value, at 64^3, same
protocol otherwise (dt = 0.01, final time 10.0, 1000 steps;
pseudo-spectral, 2/3 dealiasing, RK4; periodic cube [0, 2*pi]^3).

Case 1, Kida-Pelz: u = sin x cos y cos z, v = cos x sin y cos z,
w = -2 cos x cos y sin z. Round 2 at nu = 0.001 gave enstrophy growth
18.86 and max vorticity growth 11.51 at 64^3, saturating with
resolution. Halving the viscosity tests whether the growth rises
again once viscous damping is weaker.

Stability check: with lower viscosity the CFL constraint is set by
the nonlinear term, so dt = 0.01 is expected to stay stable, but it
is verified first with a short probe run to final time 1.0 (100
steps). The probe passes only if all diagnostics stay finite, the
energy does not grow, and the enstrophy peak stays below ten times
its initial value (physical growth at t = 1.0 in round 2 was a few
times initial, so ten times is a wide margin that only a numerical
blowup would cross). If the probe fails, dt is halved to 0.005 and
the steps doubled to 2000, and that change is recorded in the output.

Solver note: the runs use the real-FFT solver in
compute/navier_stokes_r4.py, which is the same mathematics, float64
arithmetic, dealiasing, and RK4 as the reference solver in
compute/navier_stokes.py, with the state carried as real FFTs
instead of full complex FFTs. It was verified against the reference
solver by reproducing the stability probe (Kida-Pelz, 64^3,
nu = 0.0005, dt = 0.01, final time 1.0) to near machine precision:
enstrophy final 1.5355652070043826 against the reference
1.5355652070043828, max vorticity final 3.5115962038504724 against
3.5115962038504716, energy final 0.3737473399747231 against
0.37374733997472315. A 20-step cross-check also matched
enstrophy final 1.1384603595672738 against the reference
1.138460359567274. The real-FFT solver costs 0.475 CPU seconds per
step against the reference 0.815, a 1.71x speedup, which matters
because this VM is shared with the other simultaneous round and
each run otherwise takes hours at the available CPU share.

Case 2, Taylor-Green: u = sin x cos y cos z, v = -cos x sin y cos z,
w = 0, the standard test case, at nu = 0.0005 and 64^3, same
protocol. Taylor-Green is milder than Kida-Pelz (lower initial max
vorticity), so a dt that passes the Kida-Pelz probe is used for it
as well.

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

import json
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from navier_stokes import taylor_green  # noqa: E402
from navier_stokes_r4 import run_fields_rfft  # noqa: E402
from navier_stokes_hunt import kida_pelz, summarise  # noqa: E402


def stability_probe(nu, dt):
    """Short Kida-Pelz run to final time 1.0 (100 steps at dt 0.01).

    Returns (stable, probe_result, probe_series).
    """
    print("stability probe: kida-pelz 64^3, nu = %.4f, dt = %.3f, "
          "final time 1.0" % (nu, dt), flush=True)
    t0 = time.time()
    u0, v0, w0 = kida_pelz(64)
    result, series = run_fields_rfft(u0, v0, w0, n=64, nu=nu, dt=dt,
                                final_time=1.0)
    print("probe wall time %.2f s" % (time.time() - t0), flush=True)
    print(json.dumps(result, indent=2), flush=True)
    finite = result["stayed_smooth"]
    energy_ok = result["energy_final"] <= result["energy_initial"]
    ens_ratio = result["enstrophy_peak"] / result["enstrophy_initial"]
    stable = bool(finite and energy_ok and ens_ratio < 10.0)
    print("probe: finite=%s energy_ok=%s enstrophy_peak/initial=%.3f "
          "stable=%s" % (finite, energy_ok, ens_ratio, stable),
          flush=True)
    return stable, result, series


def main():
    nu = 0.0005
    dt = 0.01
    final_time = 10.0
    cases = []

    stable, probe_result, _probe_series = stability_probe(nu, dt)
    if not stable:
        dt = 0.005
        print("probe failed: halving dt to 0.005, doubling steps to "
              "2000", flush=True)
    else:
        print("probe passed: keeping dt = 0.01", flush=True)
    steps = int(round(final_time / dt))

    print("round 4 case 1: kida-pelz-type at 64^3, nu = 0.0005",
          flush=True)
    t0 = time.time()
    u0, v0, w0 = kida_pelz(64)
    result, _series = run_fields_rfft(u0, v0, w0, n=64, nu=nu, dt=dt,
                                 final_time=final_time)
    case = summarise(
        "kida-pelz-type-64^3-nu0.0005",
        "High-symmetry field u = sin x cos y cos z, "
        "v = cos x sin y cos z, w = -2 cos x cos y sin z. "
        "Round 4 rerun at 64^3 with viscosity halved to 0.0005.",
        result)
    cases.append(case)
    print(json.dumps(case, indent=2), flush=True)
    print("case 1 wall time %.2f s" % (time.time() - t0), flush=True)

    print("round 4 case 2: taylor-green at 64^3, nu = 0.0005",
          flush=True)
    t0 = time.time()
    u0, v0, w0 = taylor_green(64)
    result2, _series2 = run_fields_rfft(u0, v0, w0, n=64, nu=nu, dt=dt,
                                   final_time=final_time)
    case2 = summarise(
        "taylor-green-64^3-nu0.0005",
        "Standard Taylor-Green vortex u = sin x cos y cos z, "
        "v = -cos x sin y cos z, w = 0, at 64^3 with viscosity "
        "0.0005.",
        result2)
    cases.append(case2)
    print(json.dumps(case2, indent=2), flush=True)
    print("case 2 wall time %.2f s" % (time.time() - t0), flush=True)

    best_all = max(cases, key=lambda c: c["max_vorticity_growth_factor"])
    hunt = {
        "date": "2026-11-20",
        "round": 4,
        "protocol": "nu = 0.0005, dt = %.3f, final_time = 10.0, "
                    "%d steps; pseudo-spectral real-FFT solver "
                    "(compute/navier_stokes_r4.py, verified against "
                    "the reference solver to near machine precision), "
                    "2/3 dealiasing, RK4; "
                    "periodic cube [0, 2*pi]^3; dt chosen after a "
                    "stability probe to final time 1.0 "
                    "(100 steps at dt 0.01, passed=%s)" % (
                        dt, steps, stable),
        "cases": cases,
        "strongest_signal": {
            "case": best_all["name"],
            "max_vorticity_growth_factor":
                best_all["max_vorticity_growth_factor"],
            "enstrophy_growth_factor":
                best_all["enstrophy_growth_factor"],
            "final_time": best_all["final_time"],
            "stayed_smooth": best_all["stayed_smooth"],
        },
    }
    with open("data/navier_stokes_hunt_r4.json", "w") as fh:
        json.dump(hunt, fh, indent=2)
    print("wrote data/navier_stokes_hunt_r4.json", flush=True)
    return hunt


if __name__ == "__main__":
    main()
