import os
from pathlib import Path

# --8<-- [start:code]
"""Two coaxial vortex rings leapfrogging in a periodic box: velocity-pressure form, ETDRK4, 3/2 dealiasing.

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

Both rings have the same circulation and start one behind the other. The rear ring contracts and speeds up, slips
through the front ring, which widens and slows, and the roles swap; after two passes the cores overlap and the
pair merges into one ring. Checks: the self-induced speed of a single ring
against Saffman's thin-ring formula, the energy budget dE/dt = -nu int |w|^2, and div u at round-off.
"""

import jax
import numpy as np
from scipy.ndimage import gaussian_filter, maximum_filter

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
GAMMA, R, A, NU, GAP = 2.0, 1.0, 0.15, 5.0e-4, 1.5  # circulation, ring radius, core size, viscosity, initial gap
LXY, LZ, NXY, NZ = 5.0, 7.5, 85, 121  # the box, and the Fourier modes along x, y and z (odd: no Nyquist mode)
BOX, WIDE = (LXY, LZ, NXY, NZ), (10.0, 12.5, 101, 125)  # the working box, and one twice as wide for the checks
T, STEPS, SEGMENTS, SAVES = 12.0, 600, 6, 20  # time marched in 6 segments, 20 saved states in each


def rings(zs, box=BOX):
    """Nodes of a periodic box (side, height, modes across, modes along: odd) with the velocity and the vorticity
    magnitude there of Gaussian-core rings at heights zs: w_theta = G/(pi A^2) exp(-s^2/A^2) in the distance s to the
    ring circle, made divergence-free by the spectral projection, then u = curl(w / k^2)."""
    lxy, lz, nxy, nz = box
    P = np.stack(np.meshgrid(*[np.arange(n) * L / n for n, L in ((nxy, lxy), (nxy, lxy), (nz, lz))], indexing="ij"), -1)
    X, Z = P[..., :2] - lxy / 2, P[..., 2]
    rho = np.hypot(X[..., 0], X[..., 1])
    s2 = lambda z: (rho - R) ** 2 + ((Z - z + lz / 2) % lz - lz / 2) ** 2  # nearest periodic image in z
    w_theta = sum(GAMMA / (np.pi * A**2) * np.exp(-s2(z) / A**2) for z in zs)
    w = w_theta[..., None] * np.stack([-X[..., 1], X[..., 0], 0 * rho], -1) / np.maximum(rho, 1e-12)[..., None]
    k = np.stack(
        np.meshgrid(*[2 * np.pi * np.fft.fftfreq(n, L / n) for n, L in ((nxy, lxy), (nxy, lxy), (nz, lz))], indexing="ij"),
        -1,
    )
    k2 = np.maximum((k**2).sum(-1, keepdims=True), 1e-30)
    wh = np.fft.fftn(w, axes=(0, 1, 2))
    wh -= k * (k * wh).sum(-1, keepdims=True) / k2  # w - grad(div w / k^2): no source of vorticity lines
    wh[0, 0, 0] = 0
    u = np.fft.ifftn(1j * np.cross(k, wh) / k2, axes=(0, 1, 2)).real
    return P.reshape(-1, 3), u.reshape(-1, 3), np.abs(w_theta).ravel()


def march(u0, T, steps, nsaves, box=BOX):
    """The velocity at nsaves times in [0, T] from the velocity u0 at the nodes: u_t + w x u + grad(P) = nu lap(u)."""
    lxy, lz, nxy, nz = box
    d = jno.shape.box(0, 0, 0, lxy, lxy, lz).domain(time=(0.0, T, steps + 1))
    Us = [d.unknown(space="fourier", order=(nxy, nxy, nz), name=f"u{i}") for i in range(3)]
    Pr = d.unknown(space="fourier", order=(nxy, nxy, nz), 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 fields(B, u):
    """Vorticity magnitude |w|, the largest |div u| and the kinetic energy of velocity states u (frames, nodes, 3),
    state by state, from the Fourier coefficients of the basis: w = i k x u_hat."""
    k = [B.wavenumbers(i) for i in range(3)]
    k = [q.reshape([-1 if j == i else 1 for j in range(3)]) for i, q in enumerate(k)]  # n is odd: no Nyquist mode
    ddx = lambda f, a: B.values(1j * k[a] * f)

    def one(v):
        c = [B.coeffs(v[:, i]) for i in range(3)]
        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 = ddx(c[0], 0) + ddx(c[1], 1) + ddx(c[2], 2)
        return np.sqrt(sum(np.asarray(f) ** 2 for f in w)), float(abs(np.asarray(div)).max())

    wm, div = map(np.array, zip(*[one(v) for v in u]))
    return wm, div, 0.5 * (u**2).sum((1, 2)) * (LXY * LXY * LZ / u.shape[1])


# 1. One ring.  Its speed is that of its vorticity centroid, V = int (|w|/rho) u_z / int (|w|/rho) (|w|/rho is the
#    conserved density of the ring). (a) The initial field in the wide box (images far away) against Saffman's
#    thin-ring speed  U = G / (4 pi R) (ln(8R/a) - 0.558),  a = A.  (b) The march in the working box: the centroid
#    must travel the distance int V dt that the computed velocity gives (the box's images slow the ring).
saffman = lambda t: GAMMA / (4 * np.pi * R) * (np.log(8 * R / np.sqrt(A**2 + 4 * NU * t)) - 0.558)


def speed(P, wm, u, lxy):
    """Axial speed of the vorticity centroid: the mean of u_z with the weights |w|/rho (nodes P, frames of wm and u)."""
    w = wm / np.maximum(np.hypot(*(P[:, :2] - lxy / 2).T), 1e-3)
    return (w * u[..., 2]).sum(-1) / w.sum(-1)


Pw, uw, ww = rings([0.0], WIDE)
free = speed(Pw, ww, uw, WIDE[0])
print(f"initial ring, wide box: V = {free:.4f}, Saffman {saffman(0):.4f} ({100 * (free / saffman(0) - 1):+.1f} %)")
assert abs(free / saffman(0) - 1) < 0.02

T1, N1 = 6.0, 13
P, u1, _ = rings([0.0])
B, fr = march(u1, T1, 240, N1)
wm = fields(B, fr)[0]
V = speed(P, wm, fr, LXY)
phase = np.angle((wm / np.maximum(np.hypot(*(P[:, :2] - LXY / 2).T), 1e-3)) @ np.exp(2j * np.pi * P[:, 2] / LZ))
phase = np.unwrap(phase)
travel = (phase[-1] - phase[0]) * LZ / (2 * np.pi)  # the centroid's axial displacement
path = np.trapezoid(V, np.linspace(0.0, T1, N1))  # what the velocity says it should be
print(f"ring in the box: V = {V[0]:.4f} -> {V[-1]:.4f}; centroid travelled {travel:.4f}, the velocity integral {path:.4f}")
assert abs(travel / path - 1) < 0.02

# 2. Two rings, one behind the other: march in segments, keep |w| and the budget terms of every saved state.
P, u, _ = rings([GAP, 0.0])
wmag, div, E = [], [], []
for _ in range(SEGMENTS):
    B, fr = march(u, T / SEGMENTS, STEPS // SEGMENTS, SAVES + 1)
    wm, dv, en = fields(B, fr[(1 if wmag else 0) :])
    wmag, div, E, u = [*wmag, *wm.astype(np.float32)], [*div, *dv], [*E, *en], fr[-1]
ts = np.linspace(0.0, T, len(E))
dV = LXY * LXY * LZ / len(P)
D = NU * np.array([(w.astype(float) ** 2).sum() * dV for w in wmag])  # dissipation rate  nu int |w|^2
budget = abs((E[-1] - E[0]) + np.trapezoid(D, ts)) / (E[0] - E[-1])
print(f"two rings: E {E[0]:.4f} -> {E[-1]:.4f}, energy budget error {budget:.1e}, max |div u| {max(div):.1e}")
assert budget < 1e-3 and max(div) < 1e-10 * max(w.max() for w in wmag)

# 3. Count the passes: follow the two maxima of the azimuthal mean of |w| in the (rho, z) half plane; a pass is the
#    moment the rear ring overtakes the front one (the order of their heights along the axis flips).
rho = np.hypot(*(P[:, :2] - LXY / 2).T)
cell = np.minimum((rho / (LXY / NXY)).astype(int), NXY // 2) * NZ + np.rint(P[:, 2] / (LZ / NZ)).astype(int) % NZ
size = (NXY // 2 + 1) * NZ
wrap = lambda dz: (dz + LZ / 2) % LZ - LZ / 2


def rings_at(w, prev):
    """Heights (and radii) of the two rings in |w|, each matched to the ring it was before."""
    m = (np.bincount(cell, w, size) / np.maximum(np.bincount(cell, None, size), 1)).reshape(-1, NZ)
    m = gaussian_filter(m, 1.5, mode=("nearest", "wrap"))
    top = np.argwhere((m == maximum_filter(m, size=9, mode=("nearest", "wrap"))) & (m > 0.3 * m.max()))
    top = top[np.argsort(-m[tuple(top.T)])][:2] * [LXY / NXY, LZ / NZ]
    if len(top) < 2:  # the two coincide: both rings sit in the one maximum
        top = np.repeat(top[:1], 2, axis=0)
    swap = np.hypot(*(top - prev).T).sum() > np.hypot(*(top[::-1] - prev).T).sum()
    return top[::-1] if swap else top


pos = [np.array([[R, 0.0], [R, GAP]])]
for w in wmag:
    pos.append(rings_at(w, pos[-1]))
pos = np.array(pos[1:])  # (frames, ring, [radius, height]): ring 0 starts behind ring 1
order = np.sign(wrap(pos[:, 0, 1] - pos[:, 1, 1]))
order = order[order != 0]  # frames where the two maxima coincide carry no order
passes = int(np.sum(order[1:] * order[:-1] < 0))
print(f"{passes} passes in t = {T:g}; ring radii between {pos[..., 0].min():.2f} and {pos[..., 0].max():.2f}")
assert passes >= 2
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    zc = np.cumsum(np.r_[pos[0, :, 1].mean(), wrap(np.diff(pos[..., 1].mean(1)))])  # the rings' mean height, unwrapped
    np.savez_compressed(
        Path(out) / "leapfrogging_vortex_rings_3d.npz",
        w=np.array(wmag).reshape(-1, NXY, NXY, NZ),
        t=ts,
        zc=zc,
        pos=pos,
        E=E,
        D=D,
        box=np.array([LXY, LZ]),
        k_card=int(np.argmax(abs(pos[:, 0, 0] - pos[:, 1, 0]))),  # the rings most different in radius
        every=2,
    )
