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

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, retaining the original trapezoidal sums."""
    dn0 = np.empty(grid.n_points + 1, dtype=float)
    dn1 = np.empty(grid.n_points + 1, dtype=float)

    for k in range(grid.n_points + 1):
        k1 = k - grid.n1
        k2 = k + grid.n1
        segment = rho[
            rho_position(k1, grid):rho_position(k2, grid) + 1
        ]
        left = segment[0]
        right = segment[-1]

        dn0[k] = 0.5 * (left + right)
        dn1[k] = grid.delta * (segment.sum() - 0.5 * left - 0.5 * right)

    return dn0, dn1


def one_body_correlation(
    k: int,
    dn0: np.ndarray,
    dn1: np.ndarray,
    grid: Grid,
) -> float:
    """Return the one-body direct correlation function c^(1)(k)."""
    k1 = k - grid.n1
    k2 = k + grid.n1

    denominator = 1.0 - dn1[k1:k2 + 1]
    if np.any(denominator <= 0.0):
        raise FloatingPointError(
            "The local packing fraction reached or exceeded one. "
            "Try a lower initial density or stronger mixing."
        )

    integrand = dn0[k1:k2 + 1] / denominator
    integral = grid.delta * (
        integrand.sum() - 0.5 * integrand[0] - 0.5 * integrand[-1]
    )

    endpoint_product = (1.0 - dn1[k1]) * (1.0 - dn1[k2])
    return 0.5 * np.log(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 mixed fixed-point iteration."""
    rho = initialize_density(params, grid)
    final_error = np.inf

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

        # The Fortran program updates rho in place, sequentially.  We preserve
        # that detail rather than performing a simultaneous/Jacobi update.
        for k in range(grid.n_points + 1):
            pos = rho_position(k, grid)
            if k < grid.n1 or k > grid.n2:
                rho[pos] = 0.0
                continue

            c1 = one_body_correlation(k, dn0, dn1, grid)
            old_value = rho[pos]
            new_value = (
                params.mixing_parameter * old_value
                + (1.0 - params.mixing_parameter)
                * np.exp(params.chemical_potential + c1)
            )
            error += abs(old_value - new_value)
            rho[pos] = new_value

        print ("error=", str(error))
        final_error = error
        if verbose:
            print(f"iteration {iteration:5d}: error = {error:.12e}")
        if error < tolerance:
            # Recompute weighted densities so output corresponds exactly to
            # the final, updated density profile.
            dn0, dn1 = compute_weighted_densities(rho, grid)
            return rho, dn0, dn1, iteration, 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()
