#!/usr/bin/env python3
"""Independent reference implementation for the HEZ manuscript's deterministic figures.

Reproduces the algebraic/analytic reference profiles underlying Figures 2--5,
Table 3, and the matched-integrated-excess-damping check of Figure 6 / S7.
This is an independently prepared POST HOC reproduction aid, not recovered
original simulation source code, and not a full Lindblad/Keldysh field solver.

Requirements: Python 3, NumPy, Matplotlib. Run:
    python Supplementary_Code_S8_HEZ_Reproduction.py

Outputs: Table3_independent_check.csv, Figure2_reference.png through Figure6_reference.png,
and numerical_check_summary.txt within HEZ_S8_reference_output/.

The display mesh of 0.01 micrometers below is a documented choice for this
reference implementation. The original sampling step for Figures 2--5 was
not specified by the manuscript. A 0.01-micrometer step *was* specified for
Figure 6 and S7. All quantities use analytic, prescribed relationships.
"""
from __future__ import annotations

import csv
import math
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

LENGTH_UM = 450.0
CENTER_UM = 70.0
WIDTH_UM = 40.0
REFERENCE_STEP_UM = 0.01
TABLE_DEPTHS_UM = [0.0, 30.0, 50.0, 70.0, 100.0, 150.0, 200.0]
OUTPUT = Path(__file__).resolve().parent / "HEZ_S8_reference_output"


def gaussian(depth_um, center_um=CENTER_UM, width_um=WIDTH_UM):
    z = (np.asarray(depth_um, dtype=float) - center_um) / width_um
    return np.exp(-0.5 * z**2)


def linewidth_ratio(phi):
    return 1.0 + np.asarray(phi, dtype=float)


def correlation_time_ratio(phi):
    return 1.0 / linewidth_ratio(phi)


def lorentzian(u, r):
    """The normalized line shape L(u;r) = r/[pi*(u*u+r*r)]."""
    return r / (math.pi * (np.asarray(u, dtype=float) ** 2 + r**2))


def integrate(y, x):
    if hasattr(np, "trapezoid"):
        return float(np.trapezoid(y, x))
    return float(np.trapz(y, x))


def save_figure(fig, name):
    fig.tight_layout()
    fig.savefig(OUTPUT / name, dpi=200, bbox_inches="tight")
    plt.close(fig)


def main():
    OUTPUT.mkdir(parents=True, exist_ok=True)
    x = np.linspace(0.0, LENGTH_UM, int(LENGTH_UM / REFERENCE_STEP_UM) + 1)
    phi = gaussian(x)
    r = linewidth_ratio(phi)
    t = correlation_time_ratio(phi)

    # Figure 2: imposed dimensionless reference kernel.
    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    ax.plot(x, phi, lw=2)
    ax.set(xlabel="Stromal depth (µm)", ylabel="Reference kernel φ(x)",
           title="Figure 2: Prescribed Gaussian reference profile", xlim=(0, 450), ylim=(0, 1.05))
    ax.grid(alpha=0.25)
    save_figure(fig, "Figure2_reference.png")

    # Figure 3: deterministic normalized linewidth and correlation time.
    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    ax.plot(x, r, label="Γeff/Γbg = 1 + φ(x)", lw=2)
    ax.plot(x, t, label="τΨ/τbg = 1/[1 + φ(x)]", lw=2)
    ax.set(xlabel="Stromal depth (µm)", ylabel="Normalized response",
           title="Figure 3: Local-Markovian benchmark", xlim=(0, 450))
    ax.legend(); ax.grid(alpha=0.25)
    save_figure(fig, "Figure3_reference.png")

    # Table 3: sample the analytic functions at the seven specified depths.
    with (OUTPUT / "Table3_independent_check.csv").open("w", newline="", encoding="utf-8") as fh:
        writer = csv.writer(fh)
        writer.writerow(["depth_um", "phi", "Gammaeff_over_Gammabg", "tauPsi_over_taubg"])
        for depth in TABLE_DEPTHS_UM:
            value = float(gaussian(depth))
            writer.writerow([f"{depth:g}", f"{value:.3f}",
                             f"{1.0 + value:.3f}", f"{1.0/(1.0 + value):.3f}"])

    # Figure 4: unit-area Lorentzians on the whole real line by construction.
    # The finite plotting interval is visualization-only, not an assertion
    # about the original plot's axis limits or finite-domain normalization.
    u = np.linspace(-12.0, 12.0, 5001)
    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    ax.plot(u, lorentzian(u, 1.0), label="Background r = 1", lw=2)
    ax.plot(u, lorentzian(u, 2.0), label="Reference center r = 2", lw=2)
    ax.set(xlabel="u = 2(ω − ω₀)/Γbg", ylabel="L(u; r)",
           title="Figure 4: Equal-area Lorentzian illustration", xlim=(-12, 12))
    ax.legend(); ax.grid(alpha=0.25)
    save_figure(fig, "Figure4_reference.png")

    # Figure 5: two parameter sweeps; the displayed depth range is 0--225 µm.
    front = x[x <= 225.0]
    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    for center in (50.0, 70.0, 90.0):
        ax.plot(front, linewidth_ratio(gaussian(front, center, 40.0)),
                lw=2, label=f"x₀ = {center:.0f} µm")
    ax.set(xlabel="Stromal depth (µm)", ylabel="Γeff/Γbg",
           title="Figure 5a: Center sensitivity", xlim=(0, 225), ylim=(0.98, 2.08))
    ax.legend(); ax.grid(alpha=0.25)
    save_figure(fig, "Figure5a_reference.png")

    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    for width in (30.0, 40.0, 50.0):
        ax.plot(front, linewidth_ratio(gaussian(front, 70.0, width)),
                lw=2, label=f"σ = {width:.0f} µm")
    ax.set(xlabel="Stromal depth (µm)", ylabel="Γeff/Γbg",
           title="Figure 5b: Width sensitivity", xlim=(0, 225), ylim=(0.98, 2.08))
    ax.legend(); ax.grid(alpha=0.25)
    save_figure(fig, "Figure5b_reference.png")

    # Figure 6 and S7: depth-integrated excess damping is held fixed.
    phi_a = gaussian(x, 70.0, 40.0)
    phi_p = gaussian(x, 380.0, 40.0)
    integral_a = integrate(phi_a, x)
    integral_p = integrate(phi_p, x)
    phi_u = np.full_like(x, integral_a / LENGTH_UM)
    integral_u = integrate(phi_u, x)
    anterior_mask = x <= 150.0
    shares = [integrate(y[anterior_mask], x[anterior_mask])/integrate(y, x)
              for y in (phi_a, phi_u, phi_p)]
    fig, ax = plt.subplots(figsize=(7.2, 4.0))
    for y, name in ((phi_a, "Anterior"), (phi_u, "Uniform"), (phi_p, "Posterior")):
        ax.plot(x, linewidth_ratio(y), lw=2, label=name)
    ax.set(xlabel="Stromal depth (µm)", ylabel="Γeff/Γbg",
           title="Figure 6: Equal-integrated-excess-damping controls", xlim=(0, 450))
    ax.legend(); ax.grid(alpha=0.25)
    save_figure(fig, "Figure6_reference.png")

    # Deterministic integrity checks (not experimental validation).
    assert np.isclose(float(gaussian(70.0)), 1.0, atol=1e-14)
    assert np.isclose(float(linewidth_ratio(gaussian(70.0))), 2.0, atol=1e-14)
    assert np.isclose(float(correlation_time_ratio(gaussian(70.0))), 0.5, atol=1e-14)
    assert np.isclose(float(lorentzian(0.0, 1)), 1/math.pi, atol=1e-14)
    assert np.isclose(float(lorentzian(0.0, 2)), 1/(2*math.pi), atol=1e-14)
    assert abs(integral_a - integral_p) < 1e-10
    assert abs(integral_a - integral_u) < 1e-10
    assert abs(integral_a - 96.2486) < 0.0001
    assert abs(shares[0] - 0.9763005) < 1e-6
    assert abs(shares[1] - 1.0/3.0) < 1e-10
    assert abs(shares[2] - 4.65e-9) < 1e-10

    summary = (
        "Independent numerical reproduction of HEZ deterministic benchmarks\n"
        "===============================================================\n"
        "Provenance: post hoc reference implementation; original source code is not available.\n"
        f"Display/reference spatial mesh: {REFERENCE_STEP_UM} µm.\n"
        "Original Figures 2--5 plotting steps not specified; Figure 6 used 0.01 µm.\n"
        f"At 70 µm: φ={float(gaussian(70.0)):.3f}, Γeff/Γbg=2.000, τΨ/τbg=0.500.\n"
        f"Integral excess damping I_A={integral_a:.7f} µm, I_P={integral_p:.7f} µm, I_U={integral_u:.7f} µm.\n"
        f"Uniform modulation I/L={integral_a/LENGTH_UM:.7f}.\n"
        f"Anterior share F_A(0--150)={shares[0]:.9f}, F_U={shares[1]:.9f}, F_P={shares[2]:.10g}.\n"
        "Gaussian-excess FWHM for σ=30,40,50 µm: "
        + ", ".join(f"{2*math.sqrt(2*math.log(2))*sig:.2f}" for sig in (30,40,50)) + " µm.\n"
        "All deterministic analytic/integral checks passed.\n"
        "No full open-QFT dynamics, reservoir entropy production, fluid transport, or data fitting performed.\n"
    )
    (OUTPUT / "numerical_check_summary.txt").write_text(summary, encoding="utf-8")
    print(summary)
    print("Files written to:", OUTPUT)


if __name__ == "__main__":
    main()
