#!/usr/bin/env python3
"""Accelerated Monte Carlo simulation of hard rectangles in a circular cavity.

Translation of HRb.f90. The sequential Metropolis moves, compression stage,
radial density profile, and radial orientational order profile are preserved.
The computational kernels are compiled with Numba.

Input file HRb.par:
    init          # 0: generate and compress; 1: read HRb.inp
    N
    L D
    phi_target
    N_steps
    dx dang

When init == 1, HRb.inp contains:
    N L D R
    x y angle       (N lines)
"""

from __future__ import annotations

import argparse
import math
import time
from pathlib import Path

import numpy as np

try:
    from numba import njit
except ImportError as exc:  # pragma: no cover
    raise SystemExit(
        "This accelerated version requires Numba. Install it with:\n"
        "  python -m pip install numba"
    ) from exc

PI = math.pi
DRHO = 0.5
NX_BOX = 10


@njit(cache=True, inline="always")
def rectangles_overlap(dx: float, dy: float, a1: float, a2: float,
                       length: float, width: float) -> bool:
    """Strict overlap test for two identical oriented rectangles.

    Uses the separating-axis theorem. Mere contact is not counted as overlap,
    matching the strict inequalities in the Fortran segment test.
    """
    c1 = math.cos(a1)
    s1 = math.sin(a1)
    c2 = math.cos(a2)
    s2 = math.sin(a2)
    hl = 0.5 * length
    hw = 0.5 * width

    # Axes of rectangle 1: u1=(c1,s1), v1=(-s1,c1)
    t_u1 = abs(dx * c1 + dy * s1)
    t_v1 = abs(-dx * s1 + dy * c1)
    cd = abs(c1 * c2 + s1 * s2)
    sd = abs(s2 * c1 - c2 * s1)

    # Projection radii of rectangle 2 on axes of rectangle 1.
    if t_u1 >= hl + hl * cd + hw * sd:
        return False
    if t_v1 >= hw + hl * sd + hw * cd:
        return False

    # Axes of rectangle 2.
    t_u2 = abs(dx * c2 + dy * s2)
    t_v2 = abs(-dx * s2 + dy * c2)
    if t_u2 >= hl + hl * cd + hw * sd:
        return False
    if t_v2 >= hw + hl * sd + hw * cd:
        return False
    return True


@njit(cache=True, inline="always")
def overlaps_wall(x: float, y: float, angle: float,
                  length: float, width: float, radius: float) -> bool:
    """Return True when at least one rectangle corner lies outside the circle."""
    c = math.cos(angle)
    s = math.sin(angle)
    hl = 0.5 * length
    hw = 0.5 * width
    r2 = radius * radius

    # Four combinations of local corner signs.
    for sl in (-1.0, 1.0):
        for sw in (-1.0, 1.0):
            ux = x + sl * hl * c - sw * hw * s
            uy = y + sl * hl * s + sw * hw * c
            if ux * ux + uy * uy > r2:
                return True
    return False


@njit(cache=True)
def build_cells(x: np.ndarray, y: np.ndarray, radius: float,
                nx_box: int, max_per_cell: int):
    n = x.size
    box = 2.0 * radius / nx_box
    counts = np.zeros((nx_box, nx_box), dtype=np.int64)
    members = np.empty((nx_box, nx_box, max_per_cell), dtype=np.int64)
    ix = np.empty(n, dtype=np.int64)
    iy = np.empty(n, dtype=np.int64)

    for i in range(n):
        bx = int((x[i] + radius) / box)
        by = int((y[i] + radius) / box)
        # A centre exactly at +R is assigned to the last box.
        if bx == nx_box:
            bx = nx_box - 1
        if by == nx_box:
            by = nx_box - 1
        if bx < 0 or bx >= nx_box or by < 0 or by >= nx_box:
            raise ValueError("Particle centre lies outside cell-list domain")
        ix[i] = bx
        iy[i] = by
        c = counts[bx, by]
        if c >= max_per_cell:
            raise ValueError("Too many particles in one spatial cell")
        members[bx, by, c] = i
        counts[bx, by] = c + 1
    return ix, iy, counts, members


@njit(cache=True, inline="always")
def trial_overlaps_neighbours(i: int, tx: float, ty: float, ta: float,
                              x: np.ndarray, y: np.ndarray, ang: np.ndarray,
                              ix: np.ndarray, iy: np.ndarray,
                              counts: np.ndarray, members: np.ndarray,
                              length: float, width: float, nx_box: int) -> bool:
    bx0 = ix[i]
    by0 = iy[i]
    for bx in range(max(0, bx0 - 1), min(nx_box, bx0 + 2)):
        for by in range(max(0, by0 - 1), min(nx_box, by0 + 2)):
            for m in range(counts[bx, by]):
                j = members[bx, by, m]
                if j != i and rectangles_overlap(x[j] - tx, y[j] - ty,
                                                  ta, ang[j], length, width):
                    return True
    return False


@njit(cache=True)
def generate_configuration(n: int, length: float, width: float,
                           radius: float, max_attempts: int):
    x = np.empty(n, dtype=np.float64)
    y = np.empty(n, dtype=np.float64)
    ang = np.empty(n, dtype=np.float64)

    for i in range(n):
        placed = False
        for _ in range(max_attempts):
            # Preserves the Fortran radial proposal r=R*U (not area-uniform).
            r = radius * np.random.random()
            theta = 2.0 * PI * np.random.random()
            a = 2.0 * PI * np.random.random()
            tx = r * math.cos(theta)
            ty = r * math.sin(theta)
            if overlaps_wall(tx, ty, a, length, width, radius):
                continue
            bad = False
            for j in range(i):
                if rectangles_overlap(x[j] - tx, y[j] - ty,
                                      a, ang[j], length, width):
                    bad = True
                    break
            if not bad:
                x[i] = tx
                y[i] = ty
                ang[i] = a
                placed = True
                break
        if not placed:
            raise RuntimeError("Could not place all rectangles in initial cavity")
    return x, y, ang


@njit(cache=True)
def compression_radius(x: np.ndarray, y: np.ndarray,
                       length: float, width: float) -> float:
    rmax = 0.0
    for i in range(x.size):
        r = math.hypot(x[i], y[i])
        if r > rmax:
            rmax = r
    return rmax + 0.5 * math.hypot(length, width)


@njit(cache=True)
def compress_configuration(x: np.ndarray, y: np.ndarray, ang: np.ndarray,
                           length: float, width: float, target_phi: float,
                           nx_box: int, max_per_cell: int,
                           max_cycles: int):
    n = x.size
    move = 0.2
    turn = 0.05

    for cycle in range(max_cycles):
        radius = compression_radius(x, y, length, width)
        phi = n * length * width / (PI * radius * radius)
        if phi > target_phi:
            return radius, cycle

        # The original routine performs blocks of 100 sweeps at fixed radius.
        for sweep in range(100):
            ix, iy, counts, members = build_cells(
                x, y, radius, nx_box, max_per_cell
            )
            # Original Fortran uses eps=0 only at sweeps 20,40,...,100.
            eps = 0.0 if (sweep + 1) % 20 == 0 else 10.0

            for i in range(n):
                x0 = x[i]
                y0 = y[i]
                tx = x0 + (2.0 * np.random.random() - 1.0) * move
                ty = y0 + (2.0 * np.random.random() - 1.0) * move
                ta = ang[i] + (2.0 * np.random.random() - 1.0) * turn

                if overlaps_wall(tx, ty, ta, length, width, radius):
                    continue
                if trial_overlaps_neighbours(i, tx, ty, ta, x, y, ang,
                                             ix, iy, counts, members,
                                             length, width, nx_box):
                    continue

                du = eps * (math.hypot(tx, ty) - math.hypot(x0, y0))
                # This is the exact acceptance condition used by the Fortran.
                if math.exp(du) < np.random.random():
                    x[i] = tx
                    y[i] = ty
                    ang[i] = ta

    raise RuntimeError("Compression did not reach the target packing fraction")


@njit(cache=True)
def run_mc(x: np.ndarray, y: np.ndarray, ang: np.ndarray,
           length: float, width: float, radius: float,
           n_steps: int, move: float, turn: float,
           drho: float, nx_box: int, max_per_cell: int):
    n = x.size
    nr = int(radius / drho) + 1
    rho = np.zeros(nr, dtype=np.float64)
    orient = np.zeros(nr, dtype=np.float64)
    accepted = 0
    attempted = n * n_steps

    for _ in range(n_steps):
        ix, iy, counts, members = build_cells(
            x, y, radius, nx_box, max_per_cell
        )
        for i in range(n):
            tx = x[i] + (2.0 * np.random.random() - 1.0) * move
            ty = y[i] + (2.0 * np.random.random() - 1.0) * move
            ta = ang[i] + (2.0 * np.random.random() - 1.0) * turn

            if not overlaps_wall(tx, ty, ta, length, width, radius):
                if not trial_overlaps_neighbours(i, tx, ty, ta, x, y, ang,
                                                 ix, iy, counts, members,
                                                 length, width, nx_box):
                    x[i] = tx
                    y[i] = ty
                    ang[i] = ta
                    accepted += 1

            r = math.hypot(x[i], y[i])
            ir = int(r / drho)
            if ir >= nr:
                ir = nr - 1
            rho[ir] += 1.0
            if r > 0.0:
                sp = (x[i] * math.cos(ang[i]) +
                      y[i] * math.sin(ang[i])) / r
                orient[ir] += 2.0 * sp * sp - 1.0
            else:
                # Radial direction is undefined exactly at the origin.
                orient[ir] += 0.0

    return rho, orient, accepted, attempted


def read_parameters(path: Path):
    tokens: list[str] = []
    for raw in path.read_text().splitlines():
        line = raw.split("!", 1)[0].split("#", 1)[0].strip()
        if line:
            tokens.extend(line.split())
    if len(tokens) < 8:
        raise ValueError(f"Malformed parameter file: {path}")
    init = int(tokens[0])
    n = int(tokens[1])
    length = float(tokens[2])
    width = float(tokens[3])
    phi_target = float(tokens[4])
    n_steps = int(tokens[5])
    move = float(tokens[6])
    turn = float(tokens[7])
    return init, n, length, width, phi_target, n_steps, move, turn


def read_configuration(path: Path):
    with path.open() as f:
        header = f.readline().split()
        if len(header) < 4:
            raise ValueError(f"Malformed header in {path}")
        n = int(header[0])
        length, width, radius = map(float, header[1:4])
        rows = []
        for line in f:
            fields = line.split()
            if fields:
                if len(fields) < 3:
                    raise ValueError(f"Malformed particle row in {path}")
                rows.append(tuple(map(float, fields[:3])))
    particles = np.asarray(rows, dtype=np.float64)
    if particles.shape != (n, 3):
        raise ValueError(f"Expected {n} particle rows in {path}")
    return n, length, width, radius, particles[:, 0].copy(), particles[:, 1].copy(), particles[:, 2].copy()


def write_configuration_plot(path: Path, length: float, width: float,
                             radius: float, x: np.ndarray,
                             y: np.ndarray, ang: np.ndarray) -> None:
    with path.open("w") as f:
        corners = np.array([
            [ length / 2.0,  width / 2.0],
            [-length / 2.0,  width / 2.0],
            [-length / 2.0, -width / 2.0],
            [ length / 2.0, -width / 2.0],
        ])
        for xi, yi, ai in zip(x, y, ang):
            c = math.cos(ai)
            s = math.sin(ai)
            rot = np.array([[c, -s], [s, c]])
            pts = corners @ rot.T
            pts = np.vstack((pts, pts[0]))
            for px, py in pts:
                f.write(f"{xi + px: .16e} {yi + py: .16e}\n")
            f.write("\n")
        for degree in range(1, 361):
            a = degree * PI / 180.0
            f.write(f"{radius * math.cos(a): .16e} {radius * math.sin(a): .16e}\n")


def write_restart(path: Path, n: int, length: float, width: float,
                  radius: float, x: np.ndarray, y: np.ndarray,
                  ang: np.ndarray) -> None:
    with path.open("w") as f:
        f.write(f"{n:d} {length:.16e} {width:.16e} {radius:.16e}\n")
        for xi, yi, ai in zip(x, y, ang):
            f.write(f"{xi:.16e} {yi:.16e} {ai:.16e}\n")


def write_profiles(rho: np.ndarray, orient: np.ndarray,
                   n_steps: int, drho: float) -> None:
    with Path("HRb.rho").open("w") as frho, Path("HRb.psi").open("w") as fpsi:
        for ir in range(rho.size):
            rr = (ir + 0.5) * drho
            # Exact annular area corresponding to the Fortran expression.
            area = PI * ((rr + 0.5 * drho) ** 2 -
                         (rr - 0.5 * drho) ** 2)
            frho.write(f"{rr:10.4f}{rho[ir] / n_steps / area:10.4f}\n")
            if abs(rho[ir]) > 1.0e-6:
                fpsi.write(f"{rr:10.4f}{orient[ir] / rho[ir]:10.4f}\n")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--param", default="HRb.par", help="parameter file")
    parser.add_argument("--input", default="HRb.inp", help="restart input file")
    parser.add_argument("--seed", type=int, default=None, help="random seed")
    parser.add_argument("--timing", action="store_true", help="print elapsed times")
    parser.add_argument("--max-cell", type=int, default=256,
                        help="maximum number of particle centres per cell")
    parser.add_argument("--max-compression-cycles", type=int, default=100000)
    args = parser.parse_args()

    init, n, length, width, phi_target, n_steps, move, turn = read_parameters(Path(args.param))
    if n <= 0 or n > 2000:
        raise ValueError("N must be in 1..2000")
    if length <= 0 or width <= 0 or phi_target <= 0:
        raise ValueError("L, D and target packing fraction must be positive")
    if n_steps <= 0 or move < 0 or turn < 0:
        raise ValueError("Invalid Monte Carlo parameters")

    if args.seed is not None:
        np.random.seed(args.seed)
        # Seed Numba's RNG in compiled context.
        seed_numba(args.seed)

    t0 = time.perf_counter()
    if init == 1:
        print(f"Reading configuration from {args.input}")
        n, length, width, radius, x, y, ang = read_configuration(Path(args.input))
    elif init == 0:
        radius = 1.5 * math.sqrt(n * length * width / (PI * phi_target))
        print(f"Locating {n} particles into cavity...")
        x, y, ang = generate_configuration(n, length, width, radius, 10_000_000)
        print("Compressing configuration up to required density...")
        radius, cycles = compress_configuration(
            x, y, ang, length, width, phi_target,
            NX_BOX, args.max_cell, args.max_compression_cycles
        )
        if args.timing:
            print(f"Compression cycles: {cycles}")
    else:
        raise ValueError("init must be 0 or 1")

    phi = n * length * width / (PI * radius * radius)
    write_configuration_plot(Path("HRb.pl0"), length, width, radius, x, y, ang)

    t1 = time.perf_counter()
    print("Simulation starts...")
    print(f"phi.................{phi:10.5f}")
    rho, orient, accepted, attempted = run_mc(
        x, y, ang, length, width, radius,
        n_steps, move, turn, DRHO, NX_BOX, args.max_cell
    )
    t2 = time.perf_counter()

    write_profiles(rho, orient, n_steps, DRHO)
    write_configuration_plot(Path("HRb.pl1"), length, width, radius, x, y, ang)
    write_restart(Path("HRb.out"), n, length, width, radius, x, y, ang)

    print(f"Acceptance ratio.....{accepted / attempted:10.5f}")
    print("Final configuration written to HRb.pl1 and HRb.out")
    if args.timing:
        print(f"Initialisation/compression: {t1 - t0:.6f} s")
        print(f"Production MC:             {t2 - t1:.6f} s")


@njit(cache=True)
def seed_numba(seed: int) -> None:
    np.random.seed(seed)


if __name__ == "__main__":
    main()
