import os
from pathlib import Path

# --8<-- [start:code]
"""Flow matching of 2-D turbulence: a generative model for vorticity fields, trained on jno.spectral snapshots.

The data are late-time snapshots of decaying 2-D turbulence on a periodic box (vorticity-streamfunction, ETDRK4,
64^2 modes, 3/2 dealiasing) from many random initial conditions. A U-Net with periodic padding learns the velocity
field of conditional flow matching (Lipman et al. 2023); sampling marches Gaussian noise along it with `Model.flow`.
Checks against held-out solver fields: isotropic energy spectrum E(k), vorticity histogram, zero mean vorticity, and a
nearest-neighbour search (all shifts, rotations and reflections) showing that samples are not copies of training fields.
"""

import equinox as eqx
import foundax
import jax
import jax.numpy as jnp
import numpy as np
import optax

import jno

run = jno.setup(__file__)
L, N, NU, T, STEPS = 2 * np.pi, 64, 1.0e-3, 8.0, 800  # periodic box, grid, viscosity, snapshot time, ETDRK4 steps
N_TRAIN, N_TEST, N_GEN = 512, 128, 256  # solver runs for training / held-out, generated samples
EPOCHS, BATCH, KEY = 20000, 32, jax.random.PRNGKey(0)

# 1. Data: one jno.spectral solve per random initial vorticity (a random-phase ring of modes around k = 5, rms 2).
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)
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)

k1, k2 = 2 * np.pi * np.fft.fftfreq(N, d=L / N), 2 * np.pi * np.fft.rfftfreq(N, d=L / N)
K = np.hypot(*np.meshgrid(k1, k2, indexing="ij"))


def initial_vorticity(seed):
    phase = np.random.default_rng(seed).uniform(0, 2 * np.pi, K.shape)
    w0 = np.fft.irfft2(np.where(K > 0, np.exp(-0.5 * ((K - 5.0) / 1.5) ** 2), 0.0) * np.exp(1j * phase), s=(N, N))
    return 2.0 * (w0 - w0.mean()) / w0.std()


def vorticity_at_T(w0):  # vorticity at t = T, shape (N, N)
    (wf, _) = 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) - jnp.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=np.array([0.0, T]))
    return np.asarray(wf)[-1].reshape(N, N)


fields = np.stack([vorticity_at_T(initial_vorticity(s)) for s in range(N_TRAIN + N_TEST)])
train, test = fields[:N_TRAIN], fields[N_TRAIN:]
SIGMA = train.std()  # the prior is N(0, 1): measure vorticity in units of its rms


def dihedral(a):  # the 8 symmetries of the square; a mirror image has the opposite vorticity
    return np.concatenate([s for k in range(4) for r in [np.rot90(a, k, (1, 2))] for s in (r, -r[:, ::-1])])


data = (dihedral(train) / SIGMA).astype(np.float32)[:, None, :, :, None]  # (8 N_TRAIN, 1, N, N, 1)

# 2. Flow matching. One sample per row; the path x_t = (1-t) x0 + t x1 and its velocity x1 - x0 are written as formulas.
rows = len(data) * jno.shape.rect(0.0, 0.0, 1.0, 1.0).structured(n=3).domain()
rows.variable("interior")
rows.variable("w", data)
x1 = rows.variable("w")
x0_, t_ = jno.noise.gaussian(std=1.0, like=x1), jno.noise.uniform(0.0, 1.0, ndim=1)
x_t = (1 - t_) * x0_ + t_ * x1


class Velocity(eqx.Module):  # a U-Net that also sees the time as one more (constant) channel, on any leading batch axes
    unet: eqx.Module

    def __call__(self, x, t):
        tau = jnp.broadcast_to(jnp.ravel(t)[0], (*x.shape[:-1], 1))
        h = jnp.concatenate([x, tau], axis=-1)
        return jax.vmap(self.unet)(h.reshape(-1, *h.shape[-3:])).reshape(x.shape)


v = jno.nn(Velocity(foundax.unet2d(in_channels=2, out_channels=1, depth=4, wf=5, padding_mode="circular", key=KEY)))
v.optimizer(optax.chain(optax.clip_by_global_norm(1.0), optax.adam(optax.cosine_decay_schedule(1e-3, EPOCHS, 0.01))))
stats = jno.core([(v(x_t, t_) - (x1 - x0_)).mse]).solve(epochs=EPOCHS, batchsize=BATCH)
print(f"final CFM loss {float(stats.training_logs[-1]['total_loss'][-1]):.4f}")

# 3. Sampling: march Gaussian noise along the learned velocity (100 Heun steps), then back to physical units.
z = jax.random.normal(jax.random.PRNGKey(1), (N_GEN, N, N, 1))
march = lambda z, **kw: np.asarray(v.flow(z, time=(0.0, 1.0, 101), **kw))[..., 0] * SIGMA
samples = np.concatenate([march(c) for c in np.split(np.asarray(z), 4)])  # in chunks of 64: the march keeps every step
path = march(z[:4], save=True)  # the 4 first samples at every step: (101, 4, N, N)


# 4. Checks against the held-out solver fields.
def spectrum(a):  # isotropic kinetic-energy spectrum E(k), k = 1 .. N/3 (the dealiased range); E = |w_k|^2 / (2 k^2)
    kk = np.rint(np.hypot(*np.meshgrid(*[np.fft.fftfreq(N, 1 / N)] * 2, indexing="ij"))).astype(int)
    e = 0.5 * np.mean(np.abs(np.fft.fft2(a)) ** 2, 0) / N**4 / np.maximum(kk, 1) ** 2
    return np.bincount(kk.ravel(), e.ravel())[1 : N // 3 + 1]


def histogram(a):  # probability of w / SIGMA in 40 bins on [-4, 4]
    return np.histogram(a / SIGMA, bins=40, range=(-4, 4))[0] / a.size


def best_match(
    a, ref
):  # largest cosine similarity of each field in a with any field of ref, over shifts and the 8 symmetries
    nrm = lambda b: b / np.linalg.norm(b.reshape(len(b), -1), axis=1)[:, None, None]
    fr = np.fft.rfft2(nrm(ref))
    best = []
    for s in nrm(a):
        fs = np.fft.rfft2(dihedral(s[None]))  # (8, N, N/2+1)
        best.append(np.fft.irfft2(np.conj(fs)[:, None] * fr[None], s=(N, N)).max())
    return np.array(best)


gap = np.abs(np.log10(spectrum(samples) / spectrum(test))).max()  # largest factor between the spectra, in decades
floor = np.abs(np.log10(spectrum(train) / spectrum(test))).max()  # the same for two sets of real fields (sampling noise)
tv = 0.5 * np.abs(histogram(samples) - histogram(test)).sum()  # total-variation distance of the vorticity histograms
mean_w = np.abs(samples.mean((1, 2))).max() / SIGMA  # the box-mean vorticity of any sample, in units of rms
sim, sim_test = best_match(samples, train), best_match(test, train)
print(f"E(k) gap {gap:.3f} decades (train vs test {floor:.3f}), histogram TV {tv:.3f}, |mean w| <= {mean_w:.3f} rms")
print(
    f"nearest training field, cosine similarity: samples {np.median(sim):.2f} (max {sim.max():.2f}), held-out {np.median(sim_test):.2f}"
)
assert gap < 0.3 and tv < 0.07 and mean_w < 0.1 and sim.max() < 0.95 and np.median(sim) < np.median(sim_test) + 0.1
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "flow_matching_turbulence.npz",
        path=path.astype(np.float32),
        samples=samples[:16].astype(np.float32),
        test=test[:16].astype(np.float32),
        k=np.arange(1, N // 3 + 1),
        spec_gen=spectrum(samples),
        spec_test=spectrum(test),
        spec_train=spectrum(train),
        hist_gen=histogram(samples),
        hist_test=histogram(test),
        sigma=SIGMA,
        sim=sim,
        sim_test=sim_test,
        params=np.array([L, NU, T, N]),
    )
