"""Checks for the Library article "Generalized hydrodynamics at the Euler scale".

Hard rods of length a on the line, joined from two equilibrium reservoirs at x = 0 and t = 0.
Notation of "Hard rods and available length": f(v) is the physical density per velocity, n and j its
zeroth and first moments, F = f/(1 - a n) the density per free length, and
v_eff(v) = v + a int (v - w) F(w) dw = v (1 + a N_F) - a J_F, with N_F, J_F the moments of F.

Exact dynamics. Jepsen's map y_k = x_k - a k turns the ordered rods into free points. Sample the free
points as Poisson processes with densities F_L = n_L/(1 - a n_L) on y < 0 and F_R on y > 0, with Gaussian
velocities; move them freely, sort, and set x_k(t) = y_(k)(t) + a k. A velocity label keeps its free
point, so its physical position is y(t) + a times its rank.

Euler-scale GHD. On the ray zeta = x/t the normal density is F_L(v) for v_eff(v) > zeta and F_R(v)
otherwise. For hard rods v_eff increases with v, so a single switch v* solves v_eff(v*) = zeta, a scalar
monotone equation; then n = N_F/(1 + a N_F) and j = J_F/(1 + a N_F).

Checks: the simulated density and current profiles approach GHD as t grows; the junction state at
zeta = 0 matches; the simulated switch between left- and right-born labels follows v*(zeta).
Controls: free-gas Euler theory (a = 0) and a bare-velocity selector (switch at v = zeta) both miss.
Run with Python 3, NumPy and SciPy:  python3 hard_rod_partition.py
"""
import numpy as np
from scipy.optimize import brentq
from scipy.stats import norm

A = 1.0                       # rod length; lengths in units of a
N_L, N_R = 0.7, 0.1           # physical densities of the two reservoirs
S_L, S_R = 1.0, 1.0           # velocity standard deviations (mean zero): equal temperatures
F_L, F_R = N_L / (1 - A * N_L), N_R / (1 - A * N_R)


def _moments(vs):
    """N_F and J_F with the left reservoir above the switch vs and the right one below it."""
    up0, up1 = norm.sf(vs / S_L), S_L * norm.pdf(vs / S_L)
    lo0, lo1 = norm.cdf(vs / S_R), -S_R * norm.pdf(vs / S_R)
    return F_L * up0 + F_R * lo0, F_L * up1 + F_R * lo1


def ghd(zeta, a=A, selector='effective'):
    """(switch v*, density n, current j) on the ray zeta.

    selector='effective' is GHD; 'bare' puts the switch at v = zeta (the free-gas rule) while keeping the
    hard-rod dressing; a=0 with 'effective' is the free gas itself."""
    if selector == 'bare':
        vs = zeta
    else:
        g = lambda vs: vs * (1 + a * _moments(vs)[0]) - a * _moments(vs)[1] - zeta
        vs = brentq(g, -60.0, 60.0, xtol=1e-14)
    NF, JF = _moments(vs)
    if a == 0:
        return vs, NF, JF
    return vs, NF / (1 + a * NF), JF / (1 + a * NF)


def simulate(t, samples, seed=1, zeta_edges=np.linspace(-5, 5, 101), v_edges=np.linspace(-3, 3, 31),
             y_extent=None):
    """Average density and current per ray bin, and left-born label fractions on a (zeta, v) grid."""
    rng = np.random.default_rng(seed)
    Y = y_extent or (14.0 * t + 60.0)
    nz, nv = len(zeta_edges) - 1, len(v_edges) - 1
    dens, curr = np.zeros(nz), np.zeros(nz)
    left_counts, all_counts = np.zeros((nz, nv)), np.zeros((nz, nv))
    for _ in range(samples):
        nl, nr = rng.poisson(F_L * Y), rng.poisson(F_R * Y)
        y0 = np.concatenate([-rng.uniform(0, Y, nl), rng.uniform(0, Y, nr)])
        v = np.concatenate([rng.normal(0, S_L, nl), rng.normal(0, S_R, nr)])
        born_left = np.concatenate([np.ones(nl, bool), np.zeros(nr, bool)])
        yt = y0 + v * t
        order = np.argsort(yt, kind='stable')
        rank = np.empty(len(yt))
        rank[order] = np.arange(len(yt)) - nl          # the first right-born point starts at rank 0
        x = yt + A * rank
        zeta = x / t
        dens += np.histogram(zeta, zeta_edges)[0]
        curr += np.histogram(zeta, zeta_edges, weights=v)[0]
        H_all = np.histogram2d(zeta, v, [zeta_edges, v_edges])[0]
        H_left = np.histogram2d(zeta[born_left], v[born_left], [zeta_edges, v_edges])[0]
        all_counts += H_all
        left_counts += H_left
    width = np.diff(zeta_edges) * t * samples
    return dens / width, curr / width, left_counts, all_counts


def simulated_switch(left_counts, all_counts, v_edges):
    """Velocity at which the left-born fraction crosses one half, per ray bin (NaN if not resolved)."""
    vc = 0.5 * (v_edges[1:] + v_edges[:-1])
    out = []
    for L, N in zip(left_counts, all_counts):
        with np.errstate(invalid='ignore', divide='ignore'):
            frac = np.where(N > 20, L / N, np.nan)
        ok = np.where(np.isfinite(frac[:-1]) & np.isfinite(frac[1:]) & (frac[:-1] < 0.5) & (frac[1:] >= 0.5))[0]
        if len(ok) == 0:
            out.append(np.nan)
            continue
        i = ok[0]
        out.append(vc[i] + (0.5 - frac[i]) * (vc[i + 1] - vc[i]) / (frac[i + 1] - frac[i]))
    return np.array(out)


def profile(zeta_centers, **kw):
    return np.array([ghd(z, **kw) for z in zeta_centers])


def free_gas(zeta):
    """Euler profile of noninteracting particles with the same physical densities: (density, current)."""
    n = N_L * norm.sf(zeta / S_L) + N_R * norm.cdf(zeta / S_R)
    j = N_L * S_L * norm.pdf(zeta / S_L) - N_R * S_R * norm.pdf(zeta / S_R)
    return n, j


def batched(t, samples, batches=8, seed=0, edges=np.linspace(-5, 5, 51), **kw):
    """Batch means and standard errors of the density and current profiles, plus pooled label counts."""
    runs = [simulate(t, samples, seed=seed + b, zeta_edges=edges, **kw) for b in range(batches)]
    D, J = np.array([r[0] for r in runs]), np.array([r[1] for r in runs])
    L, N = sum(r[2] for r in runs), sum(r[3] for r in runs)
    se = lambda X: X.std(0, ddof=1) / np.sqrt(len(X))
    return D.mean(0), se(D), J.mean(0), se(J), L, N


def main():
    edges = np.linspace(-5, 5, 51)
    zc = 0.5 * (edges[1:] + edges[:-1])
    theory = profile(zc)
    bare = profile(zc, selector='bare')
    free_n, free_j = free_gas(zc)
    v0, n0, j0 = ghd(0.0)
    print(f'reservoirs: n_L = {N_L}, n_R = {N_R} per rod length, Gaussian velocities with spreads {S_L}, {S_R}')
    print(f'GHD at the junction: switch v* = {v0:.6f}, density n = {n0:.6f}, current j = {j0:.6f} (j = v*/a)')
    print(f'GHD versus free streaming: largest density difference {np.max(np.abs(theory[:, 1] - free_n)):.4f}, '
          f'largest current difference {np.max(np.abs(theory[:, 2] - free_j)):.4f}')

    checks, controls = {}, {}
    grid = np.linspace(-6, 6, 241)
    g = np.array([v * (1 + A * _moments(v)[0]) - A * _moments(v)[1] for v in grid])
    checks['v_eff at the switch increases with v*, so each ray has one switch'] = bool(np.all(np.diff(g) > 0))
    checks['far rays reproduce the reservoir densities'] = abs(ghd(-40)[1] - N_L) < 1e-12 and abs(ghd(40)[1] - N_R) < 1e-12
    checks['the junction current equals v*/a'] = abs(j0 - v0 / A) < 1e-12
    rel = max(abs((ghd(z)[0] - ghd(z)[2] / ghd(z)[1]) - (1 - A * ghd(z)[1]) * (z - ghd(z)[2] / ghd(z)[1]))
              for z in np.linspace(-4, 4, 33))
    checks['the switch obeys v* - u = (1 - a n)(zeta - u) with u = j/n'] = rel < 1e-12

    chi = {}
    for t, samples in ((4, 2000), (16, 500), (64, 125), (256, 32)):
        dn, se_n, dj, se_j, L, N = batched(t, samples, seed=1000 * t, edges=edges)
        chi[t] = np.mean(((dn - theory[:, 1]) / se_n) ** 2)
        print(f't = {t:3d}: largest |n_sim - n_GHD| = {np.max(np.abs(dn - theory[:, 1])):.4f}, '
              f'chi2 per bin = {chi[t]:.2f}; free streaming {np.mean(((dn - free_n) / se_n) ** 2):.0f}, '
              f'bare selector {np.mean(((dn - bare[:, 1]) / se_n) ** 2):.0f}')
    checks['finite-time deviations shrink: chi2 per bin falls from t = 4 to t = 256'] = chi[256] < 0.5 * chi[4]
    checks['at t = 256 the density profile agrees with GHD within noise (chi2 per bin below 3)'] = chi[256] < 3
    chi_j = np.mean(((dj - theory[:, 2]) / se_j) ** 2)
    print(f't = 256 current: largest |j_sim - j_GHD| = {np.max(np.abs(dj - theory[:, 2])):.4f}, chi2 per bin = {chi_j:.2f}, '
          f'free streaming {np.mean(((dj - free_j) / se_j) ** 2):.0f}')
    checks['at t = 256 the current profile agrees with GHD within noise (chi2 per bin below 3)'] = chi_j < 3
    controls['free streaming is excluded by the density profile (chi2 per bin above 25)'] = np.mean(((dn - free_n) / se_n) ** 2) > 25
    controls['free streaming is excluded by the current profile (chi2 per bin above 25)'] = np.mean(((dj - free_j) / se_j) ** 2) > 25
    controls['the bare-velocity selector is excluded (chi2 per bin above 25)'] = np.mean(((dn - bare[:, 1]) / se_n) ** 2) > 25

    centre = np.abs(zc) < 0.25
    k = centre.sum()
    jn, jse_n, jj, jse_j = batched(1024, 8, batches=16, seed=77 * 1024, edges=edges)[:4]
    n_mid, n_err = jn[centre].mean(), jse_n[centre].mean() / np.sqrt(k)
    j_mid, j_err = jj[centre].mean(), jse_j[centre].mean() / np.sqrt(k)
    print(f'junction rays |zeta| < 0.25 at t = 1024 (16 batches): n = {n_mid:.4f} +- {n_err:.4f} '
          f'(GHD {theory[centre, 1].mean():.4f}), j = {j_mid:.4f} +- {j_err:.4f} (GHD {theory[centre, 2].mean():.4f})')
    checks['junction density and current within three standard errors of GHD at t = 1024'] = (
        abs(n_mid - theory[centre, 1].mean()) < 3 * n_err and abs(j_mid - theory[centre, 2].mean()) < 3 * j_err)

    v_edges = np.linspace(-3, 3, 31)
    L_fine, N_fine = simulate(256, 256, seed=7, zeta_edges=np.linspace(-5, 5, 101), v_edges=v_edges)[2:]
    zf = np.linspace(-4.95, 4.95, 100)
    sw = simulated_switch(L_fine, N_fine, v_edges)
    resolved = np.isfinite(sw) & (np.abs(zf) < 2.5)
    v_star = np.array([ghd(z)[0] for z in zf])
    sw_err = np.max(np.abs(sw[resolved] - v_star[resolved]))
    sw_bare = np.max(np.abs(sw[resolved] - zf[resolved]))
    print(f'switch between left- and right-born labels for |zeta| < 2.5 at t = 256: largest deviation from GHD '
          f'{sw_err:.3f}, from the free-streaming line v = zeta {sw_bare:.3f} (velocity bins of width 0.2)')
    checks['simulated switch follows v*(zeta) within one velocity bin (0.2)'] = sw_err < 0.2
    controls['the free-streaming line v = zeta misses the switch by more than 0.5'] = sw_bare > 0.5

    d1 = batched(64, 125, seed=64000, edges=edges)[0]
    d2 = batched(64, 125, seed=64000, edges=edges, y_extent=2 * (14.0 * 64 + 60.0))[0]
    print(f'doubling the sampled free-coordinate extent at t = 64 changes the profile by {np.max(np.abs(d2 - d1)):.4f} at most')
    checks['doubling the sampled extent changes the profile within noise (0.03)'] = np.max(np.abs(d2 - d1)) < 0.03

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('Exact hard-rod dynamics converges to the Euler-scale GHD solution; every control is excluded.')


if __name__ == '__main__':
    main()
