"""Attractive Wasserstein--Maas flow on the two-dimensional discrete torus.

The mass convention and factor 1/(2d) are those of the manuscript.
Run: python wasserstein.py --output wasserstein.json --seed 1729
"""

import argparse
import json
import math
import time

import numpy as np


def logarithmic_mean(a, b):
    out = np.zeros_like(a)
    active = (a > 0) & (b > 0)
    small = active & (np.abs(a - b) < 1e-6 * (a + b))
    # The expansion avoids cancellation near the diagonal.
    z = np.zeros_like(a)
    np.divide(a - b, a + b, out=z, where=small)
    out[small] = 0.5 * (a[small] + b[small]) * (1 - z[small] ** 2 / 3)
    far = active & ~small
    out[far] = (a[far] - b[far]) / (np.log(a[far]) - np.log(b[far]))
    return out


def interaction_kernel(n, beta):
    c = np.cos(2 * np.pi * np.arange(n) / n)
    return np.exp(beta * (c[:, None] + c[None, :]))


def vector_field(rho, kernel_fft):
    potential = np.fft.ifft2(np.fft.fft2(rho) * kernel_fft).real
    derivative = np.zeros_like(rho)
    # Each unoriented edge is counted once; 2 a(x,y) = 1/2 in d=2.
    for axis in (0, 1):
        other = np.roll(rho, -1, axis=axis)
        flux = 0.5 * logarithmic_mean(rho, other) * (
            potential - np.roll(potential, -1, axis=axis)
        )
        derivative += flux - np.roll(flux, 1, axis=axis)
    return derivative, potential


def initial_density(n, rng):
    y, x = np.mgrid[:n, :n]
    density = np.full((n, n), rng.uniform(0.03, 0.12))
    for _ in range(int(rng.integers(3, 7))):
        cx, cy = rng.uniform(0, n, 2)
        sx, sy = rng.uniform(0.06, 0.23, 2) * n
        dx = (x - cx + n / 2) % n - n / 2
        dy = (y - cy + n / 2) % n - n / 2
        density += rng.uniform(0.3, 1.2) * np.exp(-0.5 * ((dx / sx) ** 2 + (dy / sy) ** 2))
    density *= rng.uniform(0.94, 1.06, (n, n))
    return density / density.sum()


def simulate(params=None):
    p = params or {}
    n = int(p.get("N", 16))
    beta = float(p.get("beta", 0.8))
    horizon = float(p.get("T", 24))
    max_dt = float(p.get("dt", 0.08))
    seed = int(p.get("seed", 1729))
    snapshots = int(p.get("snapshots", 121))
    step_budget = int(p.get("max_steps", 30000))
    time_sampling = p.get("time_sampling", "auto")
    if not 4 <= n <= 40:
        raise ValueError("N must lie between 4 and 40.")
    if not 0.01 <= beta <= 3 or not 0 < horizon <= 1e6:
        raise ValueError("Parameters out of range: 0.01 ≤ β ≤ 3, 0 < T ≤ 1,000,000.")
    if not 0.0005 <= max_dt <= 1e4 or not 2 <= snapshots <= 301:
        raise ValueError("Time step or number of snapshots out of range.")
    if not 1 <= step_budget <= 200000:
        raise ValueError("The trial-step budget must lie between 1 and 200,000.")
    if time_sampling not in ("auto", "linear", "logarithmic"):
        raise ValueError("time_sampling must be auto, linear or logarithmic.")
    if time_sampling == "auto":
        time_sampling = "logarithmic" if horizon > 160 else "linear"

    started = time.perf_counter()
    rng = np.random.default_rng(seed)
    rho = initial_density(n, rng)
    kernel_fft = np.fft.fft2(interaction_kernel(n, beta))
    if time_sampling == "logarithmic":
        target_times = np.expm1(np.linspace(0, math.log1p(horizon), snapshots))
        target_times[-1] = horizon
    else:
        target_times = np.linspace(0, horizon, snapshots)
    times = []
    frames, energy, mass, maxima, support, first_modes = [], [], [], [], [], []
    t = 0.0
    dt = max_dt
    accepted = rejected = 0
    smallest_step, largest_step = math.inf, 0.0
    removed_mass = 0.0
    extinction = 1e-10
    atol, rtol = 2e-8 / (n * n), 4e-4
    stationary_from = None
    termination = None

    def snapshot():
        _, potential = vector_field(rho, kernel_fft)
        modes = np.fft.fft2(rho)
        frames.append(rho.ravel().tolist())
        energy.append(float(np.sum(rho * potential)))
        mass.append(float(rho.sum()))
        maxima.append(float(rho.max()))
        support.append(int(np.count_nonzero(rho)))
        first_modes.append(float(abs(modes[0, 1]) ** 2 + abs(modes[1, 0]) ** 2))
        times.append(float(t))

    snapshot()
    for target in target_times[1:]:
        if stationary_from is not None:
            t = float(target)
            snapshot()
            continue
        while t < target - 1e-12:
            f0, u0 = vector_field(rho, kernel_fft)
            if not np.any(f0):
                stationary_from = float(t)
                if t > times[-1]:
                    snapshot()
                t = float(target)
                break
            if accepted + rejected >= step_budget:
                termination = "step_budget"
                break
            negative = f0 < 0
            positivity_dt = np.min(-rho[negative] / f0[negative]) if negative.any() else np.inf
            h = min(dt, max_dt, target - t, 0.85 * positivity_dt)
            if not np.isfinite(h) or h <= 0 or t + h == t:
                termination = "precision_limit"
                break

            predictor = rho + h * f0
            f1, _ = vector_field(predictor, kernel_fft)
            candidate = rho + 0.5 * h * (f0 + f1)
            if not np.all(np.isfinite(candidate)) or candidate.min() < -1e-15:
                dt = h / 2
                rejected += 1
                continue
            scale = atol + rtol * np.maximum(rho, candidate)
            error = float(np.sqrt(np.mean(((candidate - predictor) / scale) ** 2)))
            _, u1 = vector_field(candidate, kernel_fft)
            e0, e1 = float(np.sum(rho * u0)), float(np.sum(candidate * u1))
            if error > 1.0 or e1 < e0 - 5e-13:
                dt = h * max(0.15, 0.85 / math.sqrt(max(error, 1.01)))
                rejected += 1
                continue

            # A nonzero drift is never replaced by a stationary continuation.
            if np.array_equal(candidate, rho):
                termination = "precision_limit"
                break

            rho = np.maximum(candidate, 0)
            dying = (rho > 0) & (rho < extinction) & (f1 < 0)
            lost = float(rho[dying].sum())
            if lost:
                rho[dying] = 0
                removed_mass += lost
            # Correct only round-off and the explicitly reported extinction mass.
            rho /= rho.sum()
            t += h
            accepted += 1
            smallest_step, largest_step = min(smallest_step, h), max(largest_step, h)
            dt = min(max_dt, h * min(2, max(0.3, 0.9 / math.sqrt(max(error, 1e-12)))))
        if termination is not None:
            if t > times[-1]:
                snapshot()
            break
        t = float(target)
        snapshot()

    completed = termination is None
    if completed:
        termination = "stationary" if stationary_from is not None else "target_reached"
    final_rhs = float(np.max(np.abs(vector_field(rho, kernel_fft)[0])))
    if termination == "stationary":
        status = (f"Reached t = {horizon:g}. The computed vector field became exactly zero "
                  f"at t = {stationary_from:g}; the remaining interval uses its constant continuation.")
    elif termination == "target_reached":
        status = f"Computed the trajectory to t = {t:g}."
    elif termination == "step_budget":
        status = (f"Stopped at t = {t:g} of the requested T = {horizon:g} after "
                  f"{accepted + rejected:,} trial steps. Later times have not been computed. "
                  "A larger maximum step may help; the Python script also accepts a larger step budget.")
    else:
        status = (f"Stopped at t = {t:g} of the requested T = {horizon:g}: a nonzero drift "
                  "could not produce a representable state or time increment. "
                  "No stationary continuation was substituted.")

    return {
        "x": list(range(n)), "y": list(range(n)), "frames": frames,
        "times": times,
        "diagnostics": {"energy": energy, "mass": mass, "maximum": maxima,
                        "support": support, "first_modes": first_modes},
        "meta": {"N": n, "beta": beta, "T": horizon, "dt": max_dt, "seed": seed,
                 "requested_T": horizon, "reached_T": times[-1], "completed": completed,
                 "termination": termination, "status_message": status,
                 "stationary_from": stationary_from, "final_rhs_max": final_rhs,
                 "integrated_until": stationary_from if stationary_from is not None else float(t),
                 "time_sampling": time_sampling, "time_sampling_scale": 1.0,
                 "step_budget": step_budget, "requested_snapshots": snapshots,
                 "saved_snapshots": len(times),
                 "accepted_steps": accepted, "rejected_steps": rejected,
                 "smallest_accepted_dt": smallest_step if accepted else None,
                 "largest_accepted_dt": largest_step if accepted else None,
                 "extinction_threshold": extinction, "removed_mass": removed_mass,
                 "mass_error": max(abs(v - 1) for v in mass),
                 "minimum_energy_increment": float(np.min(np.diff(energy))) if len(energy) > 1 else 0.0,
                 "seconds": time.perf_counter() - started,
                 "method": "Adaptive Heun scheme, conservative fluxes, continuation with nonincreasing support",
                 "time_label": "t", "field_label": "ρₜ(x)",
                 "continuation": "Numerical extinction threshold of 10⁻¹⁰; a single continuation is approximated."}
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", default="wasserstein.json")
    parser.add_argument("--seed", type=int, default=1729)
    parser.add_argument("--N", type=int, default=16)
    parser.add_argument("--beta", type=float, default=0.8)
    parser.add_argument("--T", type=float, default=24)
    parser.add_argument("--dt", type=float, default=0.08)
    parser.add_argument("--max-steps", dest="max_steps", type=int, default=30000)
    parser.add_argument("--time-sampling", dest="time_sampling", choices=["auto", "linear", "logarithmic"], default="auto")
    args = vars(parser.parse_args())
    output = args.pop("output")
    result = simulate(args)
    with open(output, "w", encoding="utf-8") as stream:
        json.dump(result, stream, separators=(",", ":"), allow_nan=False)
    print(json.dumps(result["meta"], indent=2, ensure_ascii=False))
