"""Strict energy ascent on a two-dimensional discrete torus.

The kernel and one-particle increment are those of Local Moves, Global
Clusters, equations (2.4), (3.4), and (5.2).  Time means accepted moves.
Run: python particles.py --N 12 --particles 64 --beta 0.0001 --output run.json
"""
from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np


def torus_kernel(N: int, beta: float):
    yy, xx = np.mgrid[:N, :N]
    sites = np.column_stack((xx.ravel(), yy.ravel()))
    delta = sites[:, None, :] - sites[None, :, :]
    a = 2.0 - np.cos(2.0 * np.pi * delta / N).sum(axis=2)
    # Subtracting a constant kernel and dividing by beta preserve every
    # move ranking. expm1 keeps the gains accurate when beta is small.
    B = np.expm1(-beta * a) / beta
    neighbors = []
    for x, y in sites:
        neighbors.append([
            y * N + (x + 1) % N, y * N + (x - 1) % N,
            ((y + 1) % N) * N + x, ((y - 1) % N) * N + x,
        ])
    return B, np.asarray(neighbors, dtype=np.int32), float(a.max())


def simulate(params: dict | None = None) -> dict:
    params = params or {}
    N = int(params.get("N", 12))
    n = int(params.get("particles", 64))
    beta = float(params.get("beta", 0.0001))
    steps = int(params.get("steps", 2500))
    snapshots = int(params.get("snapshots", 121))
    seed = int(params.get("seed", 173))
    if not 3 <= N <= 32 or not 1 <= n <= 4096:
        raise ValueError("Choose 3 <= N <= 32 and 1 <= particles <= 4096.")
    if not math.isfinite(beta) or not 1e-8 <= beta <= 30:
        raise ValueError("beta must lie between 1e-8 and 30.")
    if not 1 <= steps <= 20000 or not 2 <= snapshots <= 400:
        raise ValueError("Invalid move budget or number of snapshots.")

    rng = np.random.default_rng(seed)
    B, neighbors, A = torus_kernel(N, beta)
    # A new random mass profile, followed by an integer particle sample.
    weights = rng.gamma(shape=0.8, scale=1.0, size=N * N)
    weights /= weights.sum()
    c = rng.multinomial(n, weights).astype(np.int64)
    potential = B @ c
    rows = np.arange(N * N)[:, None]
    edge_correction = -B[rows, neighbors]
    history = [c.astype(np.uint16).copy()]
    energies = [1.0 + beta * float(c @ potential) / n**2]
    accepted_gains = []
    tolerance = 128.0 * np.finfo(float).eps * max(1, n) * max(1.0, A)
    stationary = False

    for _ in range(steps):
        gain = 2.0 * (potential[neighbors] - potential[:, None] + edge_correction)
        gain[c == 0, :] = -np.inf
        p, direction = np.unravel_index(int(np.argmax(gain)), gain.shape)
        best = float(gain[p, direction])
        if best <= tolerance:
            stationary = True
            break
        q = int(neighbors[p, direction])
        c[p] -= 1
        c[q] += 1
        potential += B[:, q] - B[:, p]
        # Refresh the cached potential occasionally; this limits long-run drift.
        if len(history) % 128 == 0:
            potential = B @ c
        accepted_gains.append(beta * best)
        history.append(c.astype(np.uint16).copy())
        energies.append(1.0 + beta * float(c @ potential) / n**2)

    total_moves = len(history) - 1
    chosen = np.unique(np.rint(np.linspace(0, total_moves, min(snapshots, total_moves + 1))).astype(int))
    selected = [history[k].astype(float) / n for k in chosen]
    edge_a = 1.0 - math.cos(2.0 * math.pi / N)
    threshold = edge_a / ((n - 1) * A**2) if n > 1 else None
    if np.count_nonzero(c) == 1:
        stationary = True
    return {
        "x": list(range(N)),
        "y": list(range(N)),
        "frames": [state.tolist() for state in selected],
        "times": [int(k) for k in chosen],
        "diagnostics": {
            "energy": [float(energies[k]) for k in chosen],
            "occupied": [int(np.count_nonzero(history[k])) for k in chosen],
            "max_density": [float(history[k].max() / n) for k in chosen],
            "mass": [float(history[k].sum() / n) for k in chosen],
        },
        "meta": {
            "model": "Global steepest one-particle ascent on (Z/NZ)^2",
            "kernel": "exp(beta*(cos(2*pi*dx/N)+cos(2*pi*dy/N)-2))",
            "time_label": "Accepted moves",
            "density_label": "c(x) / n",
            "N": N, "particles": n, "beta": beta, "seed": seed,
            "accepted_moves": total_moves,
            "stationary": stationary,
            "termination": "stationary_to_tolerance" if stationary else "move_budget_reached",
            "occupied_final": int(np.count_nonzero(c)),
            "sufficient_beta_threshold": threshold,
            "inside_proved_regime": bool(n == 1 or beta <= threshold),
            "scaled_gain_tolerance": float(tolerance),
            "minimum_accepted_gain": float(min(accepted_gains)) if accepted_gains else None,
            "mass_error": float(abs(c.sum() - n)),
            "energy_normalization": "E_K(c) / n^2",
        },
    }


def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--N", type=int, default=12)
    parser.add_argument("--particles", type=int, default=64)
    parser.add_argument("--beta", type=float, default=0.0001)
    parser.add_argument("--steps", type=int, default=2500)
    parser.add_argument("--seed", type=int, default=173)
    parser.add_argument("--snapshots", type=int, default=121)
    parser.add_argument("--output", default="particles-run.json")
    args = vars(parser.parse_args())
    output = args.pop("output")
    result = simulate(args)
    Path(output).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
    print(json.dumps(result["meta"], ensure_ascii=False, indent=2))


if __name__ == "__main__":
    _main()
