"""Independent hard-core Bose-gas equal-time Fredholm minor (NumPy and SciPy).

Optional figure comparison (requires Pillow): supply the authors' benchmarks.png,
in figures/ of the arXiv:2508.17908v2 TeX-source archive. Pixel calibrations below
belong to that exact file. Run: python3 thermal_bose_benchmark.py [benchmarks.png]
"""
import argparse
import hashlib
from pathlib import Path
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.optimize import brentq
from scipy.special import expit


def fermi_measure(nk, cutoff):
    """Positive momenta with both signs included in the quadrature weights."""
    q, w = leggauss(nk)
    k, weights = cutoff*(q+1)/2, cutoff*w/(2*np.pi)
    temperature = 5.
    mu = brentq(lambda h: weights @ expit((h-k*k)/temperature)-1, -20., 30.)
    measure = weights * expit((mu-k*k)/temperature)
    return mu, k, measure


def equal_time(x, nspace, k, measure):
    """Return the Bose Fredholm minor and mapped fermion kernel at separation x."""
    def kernel(d):
        return np.cos(np.asarray(d)[..., None] * k) @ measure

    x = abs(x)
    q, w = leggauss(nspace)
    z, root = x*(q+1)/2, np.sqrt(x*w/2)
    mat = np.empty((nspace+1, nspace+1))
    mat[0,0] = kernel(x)
    mat[0,1:] = root*kernel(z)
    mat[1:,0] = -2*root*kernel(x-z)
    mat[1:,1:] = np.eye(nspace) - 2*np.outer(root,root)*kernel(z[:,None]-z)
    return np.linalg.det(mat), mat[0, 0]


def minor(x, nspace, nk, cutoff):
    mu, k, measure = fermi_measure(nk, cutoff)
    bose, _ = equal_time(x, nspace, k, measure)
    return mu, bose


def check_parity_string():
    _, k, measure = fermi_measure(180, 24.)
    zero = brentq(lambda x: np.cos(k*x) @ measure, .8, 1.)
    bose, fermion = equal_time(zero, 36, k, measure)
    moment = k**2 @ measure
    prediction = measure.sum() * moment / 3
    print("fermion zero, Bose minor, fermion kernel", zero, bose, fermion)
    assert abs(fermion) < 1e-12 and abs(bose-.3724493748) < 1e-9
    errors = []
    for x in (.1, .05, .025, .0125):
        bose, fermion = equal_time(x, 36, k, measure)
        coefficient = (bose-fermion) / x**3
        errors.append(abs(coefficient-prediction))
        print("separation, cubic coefficient, prediction", x, coefficient, prediction)
    assert all(3.9 < a/b < 4.1 for a, b in zip(errors, errors[1:]))


def inspect_figure(path):
    from PIL import Image
    if hashlib.sha256(path.read_bytes()).hexdigest() != '0a7382cc24352aad85cb94c2fe2264df94cccd298dc9377addc16fbb56f97f41':
        raise ValueError('Expected the original benchmarks.png in arXiv:2508.17908v2')
    pixels = np.asarray(Image.open(path).convert('RGB'))
    for x in (.5,1.,1.5):
        col = round(189+x*(1130-189)/4)
        y = np.flatnonzero((pixels[:,col] == [0,114,189]).all(axis=1))
        if x > 1.25:
            y = y[y>360]  # inset lies above the main trace at this x
        print('Fig. 3a x', x, 'C from trace', (661-np.median(y))/(661-22))
    # Integrate only the displayed central part of the light-blue k=0 trace.
    # x ticks at 1747 and 2041 correspond to omega/kF^2 = 0 and 1.
    for wmax in (.2,.4):
        coords = np.arange(round(1747-294*wmax),round(1747+294*wmax)+1)
        heights = []
        for col in coords:
            y = np.flatnonzero((pixels[:,col] == [173,235,255]).all(axis=1))
            if not y.size:
                raise ValueError(f'No trace at pixel {col}')
            heights.append((693-np.median(y))/(693-21))
        print('Fig. 3b symmetric half-width',wmax,'plotted area',np.sum((np.array(heights[1:])+heights[:-1])/(2*294)))


if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('image',nargs='?',type=Path)
    args=p.parse_args()
    for x in (0.,.5,1.,1.5):
        a=minor(x,20,100,18.)
        b=minor(x,36,180,24.)
        print(f'x={x:.1f}, mu={b[0]:.10f}, C={b[1]:.10f}, refinement={abs(b[1]-a[1]):.2e}')
        assert abs(a[1]-b[1])<1e-10
    check_parity_string()
    if args.image:
        inspect_figure(args.image)
