#!/usr/bin/env python3
"""Density-functional calculation for one-dimensional hard rods.

Optimized Python translation of ``hard_rods.f``.

The program reads, by default, ``hard_rods.inp`` containing::

    h  chemical_potential  initial_density
    mixing_parameter

It solves the Euler--Lagrange equation by mixed fixed-point iteration,
then writes:

* ``hard_rods.dat``: h, chemical potential, mean density, free energy,
  and integrated pressure;
* ``profile.dat``: position, density, and local packing fraction.

Lengths are expressed in units of the rod length, which is equal to 1.
"""

from __future__ import annotations

import argparse
from dataclasses import dataclass
from pathlib import Path

import numpy as np


@dataclass(frozen=True)
class Parameters:
    h: float
    chemical_potential: float
    initial_density: float
    mixing_parameter: float


@dataclass(frozen=True)
class Grid:
    delta: float
    n_points: int
    n1: int
    n2: int
    lower_index: int
    upper_index: int


@dataclass(frozen=True)
class Results:
    density: np.ndarray
    weighted_density_0: np.ndarray
    weighted_density_1: np.ndarray
    mean_density: float
    free_energy: float
    pressure_integral: float
    iterations: int
    error: float


def read_parameters(filename: str | Path) -> Parameters:
    """Read the two-line Fortran input file."""
    path = Path(filename)
    values: list[float] = []

    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.split("!", maxsplit=1)[0].strip()
        if line:
            values.extend(float(item.replace("D", "E").replace("d", "e"))
                          for item in line.split())

    if len(values) < 4:
        raise ValueError(
            f"{path} must contain at least four numbers: "
            "h, chemical potential, initial density, and mixing parameter."
        )

    params = Parameters(*values[:4])

    if params.h <= 1.0:
        raise ValueError("The wall separation h must exceed one rod length.")
    if params.initial_density <= 0.0:
        raise ValueError("The initial density must be positive.")
    if not 0.0 <= params.mixing_parameter < 1.0:
        raise ValueError("The mixing parameter must satisfy 0 <= theta < 1.")

    return params


def make_grid(h: float, delta: float = 0.005) -> Grid:
    """Construct the same grid and accessible interval as the Fortran code."""
    n_points = int(h / delta)
    n1 = int(0.5 / delta)
    n2 = int((h - 0.5) / delta)

    # rho is needed from index -n1 to n_points+n1 in the weighted densities.
    lower_index = -n1
    upper_index = n_points + n1

    return Grid(delta, n_points, n1, n2, lower_index, upper_index)


def rho_position(index: int, grid: Grid) -> int:
    """Map a physical Fortran rho index to a zero-based NumPy index."""
    return index - grid.lower_index


def initialize_density(params: Parameters, grid: Grid) -> np.ndarray:
    """Initialize rho to a constant in the centre-accessible region."""
    rho = np.zeros(grid.upper_index - grid.lower_index + 1, dtype=float)
    start = rho_position(grid.n1, grid)
    stop = rho_position(grid.n2, grid) + 1
    rho[start:stop] = params.initial_density
    return rho


def compute_weighted_densities(
    rho: np.ndarray, grid: Grid
) -> tuple[np.ndarray, np.ndarray]:
    """Compute n0 and n1 in O(N) time using cumulative sums."""
    n = grid.n_points + 1
    width = 2 * grid.n1

    # Windows for k=0,...,n_points begin at rho-array positions 0,...,n-1.
    left = rho[:n]
    right = rho[width:width + n]
    dn0 = 0.5 * (left + right)

    cumulative = np.empty(rho.size + 1, dtype=float)
    cumulative[0] = 0.0
    np.cumsum(rho, out=cumulative[1:])
    window_sum = cumulative[width + 1:width + 1 + n] - cumulative[:n]
    dn1 = grid.delta * (window_sum - 0.5 * left - 0.5 * right)
    return dn0, dn1


def compute_all_correlations(
    dn0: np.ndarray, dn1: np.ndarray, grid: Grid
) -> np.ndarray:
    """Compute c^(1) at every accessible grid point in O(N) time."""
    free_volume = 1.0 - dn1
    if np.any(free_volume <= 0.0):
        raise FloatingPointError(
            "The local packing fraction reached or exceeded one. "
            "Try a lower initial density or stronger mixing."
        )

    integrand = dn0 / free_volume
    cumulative = np.empty(integrand.size + 1, dtype=float)
    cumulative[0] = 0.0
    np.cumsum(integrand, out=cumulative[1:])

    k = np.arange(grid.n1, grid.n2 + 1)
    left = k - grid.n1
    right = k + grid.n1
    window_sum = cumulative[right + 1] - cumulative[left]
    integral = grid.delta * (
        window_sum - 0.5 * integrand[left] - 0.5 * integrand[right]
    )
    endpoint_product = free_volume[left] * free_volume[right]
    return 0.5 * np.log(np.abs(endpoint_product)) - integral


def solve(
    params: Parameters,
    grid: Grid,
    tolerance: float = 1.0e-10,
    max_iterations: int = 6000,
    verbose: bool = False,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, float]:
    """Solve the Euler--Lagrange equation by vectorized mixed iteration."""
    rho = initialize_density(params, grid)
    start = rho_position(grid.n1, grid)
    stop = rho_position(grid.n2, grid) + 1
    final_error = np.inf

    for iteration in range(1, max_iterations + 1):
        dn0, dn1 = compute_weighted_densities(rho, grid)
        c1 = compute_all_correlations(dn0, dn1, grid)

        old = rho[start:stop].copy()
        new = (
            params.mixing_parameter * old
            + (1.0 - params.mixing_parameter)
            * np.exp(params.chemical_potential + c1)
        )
        final_error = float(np.abs(old - new).sum())
        rho[start:stop] = new

        if verbose:
            print(f"iteration {iteration:5d}: error = {final_error:.12e}")
        if final_error < tolerance:
            dn0, dn1 = compute_weighted_densities(rho, grid)
            return rho, dn0, dn1, iteration, final_error

    raise RuntimeError(
        f"The iteration did not converge after {max_iterations} iterations; "
        f"last error = {final_error:.6e}."
    )


def thermodynamic_quantities(
    h: float,
    rho: np.ndarray,
    dn0: np.ndarray,
    dn1: np.ndarray,
    grid: Grid,
) -> tuple[float, float, float]:
    """Calculate mean density, intrinsic free energy, and pressure integral."""
    density_values = rho[
        rho_position(grid.n1, grid):rho_position(grid.n2, grid) + 1
    ]

    if np.any(density_values <= 0.0):
        raise FloatingPointError("A non-positive density occurred in log(rho).")

    ideal_integrand = density_values * (np.log(density_values) - 1.0)
    phi_id = grid.delta * (
        ideal_integrand.sum()
        - 0.5 * ideal_integrand[0]
        - 0.5 * ideal_integrand[-1]
    )

    rho_integral = grid.delta * (
        density_values.sum()
        - 0.5 * density_values[0]
        - 0.5 * density_values[-1]
    )
    mean_density = rho_integral / h

    free_volume = 1.0 - dn1
    if np.any(free_volume <= 0.0):
        raise FloatingPointError("The local packing fraction is not below one.")

    excess_integrand = -dn0 * np.log(free_volume)
    phi_ex = grid.delta * (
        excess_integrand.sum()
        - 0.5 * excess_integrand[0]
        - 0.5 * excess_integrand[-1]
    )

    pressure_density = dn0 / free_volume
    pressure_integral = grid.delta * (
        pressure_density.sum()
        - 0.5 * pressure_density[0]
        - 0.5 * pressure_density[-1]
    )

    return mean_density, (phi_id + phi_ex)/h, pressure_integral/h


def run(
    input_file: str | Path = "hard_rods.inp",
    summary_file: str | Path = "hard_rods.dat",
    profile_file: str | Path = "profile.dat",
    tolerance: float = 1.0e-10,
    max_iterations: int = 6000,
    verbose: bool = False,
) -> Results:
    """Run the complete calculation and write the output files."""
    params = read_parameters(input_file)
    grid = make_grid(params.h)

    rho, dn0, dn1, iterations, error = solve(
        params,
        grid,
        tolerance=tolerance,
        max_iterations=max_iterations,
        verbose=verbose,
    )

    mean_density, free_energy, pressure_integral = thermodynamic_quantities(
        params.h, rho, dn0, dn1, grid
    )

    with Path(summary_file).open("a", encoding="utf-8") as output:
        output.write(
            f"  {params.h:12.6e}  {params.chemical_potential:12.6e}  "
            f"{mean_density:12.6e}  {free_energy:12.6e}  "
            f"{pressure_integral:12.6e}\n"
        )

    x = np.arange(grid.n_points + 1, dtype=float) * grid.delta
    physical_rho = rho[
        rho_position(0, grid):rho_position(grid.n_points, grid) + 1
    ]
    profile = np.column_stack((x, physical_rho, dn1))
    np.savetxt(profile_file, profile, fmt="  %.6e  %.6e  %.6e")

    return Results(
        density=rho,
        weighted_density_0=dn0,
        weighted_density_1=dn1,
        mean_density=mean_density,
        free_energy=free_energy,
        pressure_integral=pressure_integral,
        iterations=iterations,
        error=error,
    )


def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Density-functional calculation for one-dimensional hard rods."
    )
    parser.add_argument("--input", default="hard_rods.inp", help="input parameter file")
    parser.add_argument("--summary", default="hard_rods.dat", help="summary output file")
    parser.add_argument("--profile", default="profile.dat", help="profile output file")
    parser.add_argument("--tolerance", type=float, default=1.0e-10)
    parser.add_argument("--max-iterations", type=int, default=6000)
    parser.add_argument("--verbose", action="store_true")
    return parser.parse_args()


def main() -> None:
    args = parse_arguments()
    results = run(
        input_file=args.input,
        summary_file=args.summary,
        profile_file=args.profile,
        tolerance=args.tolerance,
        max_iterations=args.max_iterations,
        verbose=args.verbose,
    )
    print(
        f"Converged in {results.iterations} iterations "
        f"(error = {results.error:.3e})."
    )
    print(f"Mean density      = {results.mean_density:.10g}")
    print(f"Free energy       = {results.free_energy:.10g}")
    print(f"Pressure integral = {results.pressure_integral:.10g}")


if __name__ == "__main__":
    main()
