import os
from pathlib import Path

# --8<-- [start:code]
"""Swift-Hohenberg defect labyrinths on a periodic box: 4th-order ETDRK4, cubic dealiasing, and disclination tracking.

    u_t = r u - (1 + Delta)^2 u - u^3 .

Tiny random noise amplifies modes on the critical ring |k| = 1 (wavelength 2 pi) and saturates into fingerprint-like
labyrinthine rolls populated by +-1/2 nematic disclinations that glide and annihilate in pairs. Checks: the Lyapunov
free energy F[u] decreases monotonically, net topological charge vanishes at every instant (Poincare-Hopf on T^2),
more than two-thirds of the initial defect pairs annihilate by t = 180, and the dealiased k >= 4.5 tail is < 1e-10.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
N_WAVES = 22
L, N = N_WAVES * 2 * np.pi, 384
R_PARAM = 0.28
T, STEPS, FRAMES = 180.0, 900, 91

d = jno.shape.rect(0.0, 0.0, L, L).domain(time=(0.0, T, STEPS + 1))
U = d.unknown(space=("fourier", "fourier"), order=(N, N), name="u")
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)

basis = U.basis  # the Fourier basis: coefficients, wavenumbers, values, integrals
kx, ky = (np.asarray(basis.wavenumbers(axis)) for axis in (0, 1))
K2 = kx[:, None] ** 2 + ky[None, :] ** 2  # |k|^2 on the coefficient grid

# Small random seed (std = 0.02): white noise kept only on 0 < |k| < 2.5, all orientations around the critical ring.
noise = np.random.default_rng(42).normal(size=N * N)
band = (K2 > 0) & (K2 < 2.5**2)
u0 = np.real(np.asarray(basis.values(band * np.asarray(basis.coeffs(noise))))).ravel()
u0 = 0.02 * u0 / u0.std()

# Explicit 4th-order partials fold -(1 + Delta)^2 into ETDRK4's exact linear propagator; dealias=2 pads u^3 to 768^2.
u = U.bind(x=x, y=y, t=t, scheme=jno.sp(dealias=2))
lap = u.xx + u.yy
biharm = u.xxxx + 2 * u.xxyy + u.yyyy
ts = np.linspace(0.0, T, FRAMES)
uf = np.asarray(
    jno.spectral(
        [
            u.t + (1.0 - R_PARAM) * u + 2 * lap + biharm + u**3,
            U(x0, y0) - jax.numpy.asarray(u0.reshape(-1, 1)),
            U(xl, yl) - U(xr, yr),
            U(xb, yb) - U(xt, yt),
        ]
    ).solve(time=jno.solve.etdrk4(), save_ts=ts)
).reshape(FRAMES, N, N)

# Lyapunov free energy F[u] = int [ 1/2 ((1 + Delta) u)^2 - (r/2) u^2 + (1/4) u^4 ] dA, through the basis:
# (1 + Delta) is the factor 1 - |k|^2 on the coefficients, the integral is the basis's own quadrature.
coeffs = [np.asarray(basis.coeffs(frame.ravel())) for frame in uf]


def energy(frame, c):
    one_plus_lap = np.real(np.asarray(basis.values((1.0 - K2) * c))).ravel()
    u_ = frame.ravel()
    return float(np.asarray(basis.integrate(0.5 * one_plus_lap**2 - 0.5 * R_PARAM * u_**2 + 0.25 * u_**4)))


F = np.array([energy(frame, c) for frame, c in zip(uf, coeffs)])
F_density = F / L**2
rms_hist = np.sqrt([float(np.asarray(basis.mean(frame.ravel() ** 2))) for frame in uf])
amp_rms = float(np.sqrt(2 * R_PARAM / 3))
i_sat = int(np.argmax(rms_hist > 0.70 * amp_rms))

# Azimuthally averaged power spectrum |c|^2, binned by |k|, at saturation onset and at the end.
dk = 2 * np.pi / L
k_bin = np.rint(np.sqrt(K2) / dk).astype(int).ravel()
p_rad_sat, p_rad_end = (np.bincount(k_bin, weights=np.abs(coeffs[m]).ravel() ** 2) for m in (i_sat, -1))
k_vals = np.arange(len(p_rad_end)) * dk
k_peak = float(k_vals[int(np.argmax(p_rad_end))])
tail_frac = float(np.abs(coeffs[-1])[K2 >= 4.5**2].__pow__(2).sum() / (np.abs(coeffs[-1]) ** 2).sum())
f_roll = -(R_PARAM**2) / 6

print(
    f"Swift-Hohenberg {N}^2 (dealias=2), r={R_PARAM}, {STEPS} steps to t={T}: "
    f"F/L^2 {F_density[0]:.3e}->{F_density[-1]:.4f} (1-D roll {f_roll:.4f}), "
    f"k_peak={k_peak:.4f}, rms(u)={rms_hist[-1]:.3f} (roll {amp_rms:.3f}), tail(k>=4.5)={tail_frac:.2e}"
)
assert np.all(np.diff(F) <= 1e-10), f"Lyapunov energy increased: max dF={np.diff(F).max():.3e}"
assert f_roll - 1e-3 < F_density[-1] < 0.75 * f_roll
assert abs(k_peak - 1.0) <= 1.5 * dk
assert abs(rms_hist[-1] - amp_rms) / amp_rms < 0.10
assert tail_frac < 1e-10
# --8<-- [end:code]

# ---- the +-1/2 disclinations, for the figure and its checks: image analysis of the computed field, outside jNO ----
# Nematic stripe-orientation order parameter Psi_2 = <(u_x + i u_y)^2>_sigma (sigma = 2.0 damps the 2 k_c carrier);
# the plaquette phase winding of Psi_2 / (2 pi) in {-1, 0, +1} locates the cores on the periodic 2-torus.
fkx = 2 * np.pi * np.fft.fftfreq(N, d=L / N)
fky = 2 * np.pi * np.fft.rfftfreq(N, d=L / N)
FKX, FKY = np.meshgrid(fkx, fky, indexing="ij")
gauss_full = np.exp(-0.5 * (2.0 * np.hypot(*np.meshgrid(fkx, fkx, indexing="ij"))) ** 2)
h_grid = L / N


def disclinations(frame):
    frame_hat = np.fft.rfft2(frame)
    ux = np.fft.irfft2(1j * FKX * frame_hat, s=(N, N))
    uy = np.fft.irfft2(1j * FKY * frame_hat, s=(N, N))
    psi2 = np.fft.ifft2(gauss_full * np.fft.fft2((ux + 1j * uy) ** 2))
    z10 = np.roll(psi2, -1, axis=0)
    z11 = np.roll(z10, -1, axis=1)
    z01 = np.roll(psi2, -1, axis=1)
    wind = (
        np.angle(z10 * np.conj(psi2))
        + np.angle(z11 * np.conj(z10))
        + np.angle(z01 * np.conj(z11))
        + np.angle(psi2 * np.conj(z01))
    ) / (2 * np.pi)
    q2 = np.rint(wind).astype(int)
    ip, jp = np.nonzero(q2 > 0)
    im, jm = np.nonzero(q2 < 0)
    return (ip + 0.5) * h_grid, (jp + 0.5) * h_grid, (im + 0.5) * h_grid, (jm + 0.5) * h_grid, int(q2.sum())


cores = [disclinations(frame) for frame in uf]
n_plus = np.array([len(c[0]) for c in cores])
n_minus = np.array([len(c[2]) for c in cores])
n_defects = n_plus + n_minus
print(f"disclinations {n_defects[i_sat]} (t={ts[i_sat]:.1f}) -> {n_defects[-1]} (+1/2: {n_plus[-1]}, -1/2: {n_minus[-1]})")
assert all(c[4] == 0 for c in cores) and np.all(n_plus[i_sat:] == n_minus[i_sat:]), "charge neutrality violated"
assert n_defects[-1] < 0.40 * n_defects[i_sat], f"too little coarsening: {n_defects[i_sat]} -> {n_defects[-1]}"

if out := os.environ.get("JNO_FIGURE_DATA"):
    xp_all = np.concatenate([c[0] for c in cores])
    yp_all = np.concatenate([c[1] for c in cores])
    xm_all = np.concatenate([c[2] for c in cores])
    ym_all = np.concatenate([c[3] for c in cores])
    offsets_p = np.cumsum([0] + [len(c[0]) for c in cores])
    offsets_m = np.cumsum([0] + [len(c[2]) for c in cores])
    np.savez_compressed(
        Path(out) / "swift_hohenberg_spectral.npz",
        u=uf.astype(np.float32),
        t=ts,
        F_density=F_density,
        k=k_vals,
        p_rad_sat=p_rad_sat,
        p_rad_end=p_rad_end,
        n_defects=n_defects,
        i_sat=np.array(i_sat),
        xp=xp_all.astype(np.float32),
        yp=yp_all.astype(np.float32),
        xm=xm_all.astype(np.float32),
        ym=ym_all.astype(np.float32),
        offsets_p=offsets_p,
        offsets_m=offsets_m,
        params=np.array([L, R_PARAM, float(N)]),
    )
