"""Synthetic thermometry, two-boson expansion and published gas-profile checks.

With --cradle-pdf, read the versioned Tang et al. author PDF (arXiv:1707.07031)
using pdftocairo. The thermometry fixture is synthetic; no experimental counts
are distributed. Units: micrometres, milliseconds and nK unless noted.
"""
import argparse
import hashlib
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET

import numpy as np
from scipy.constants import atomic_mass, Boltzmann, h, hbar
from scipy.integrate import quad
from scipy.interpolate import make_interp_spline
from scipy.optimize import least_squares
from scipy.special import erf

m = 86.90918053 * atomic_mass


def thermometer():
    # Fugacity expansion of the ideal Bose one-body density matrix.
    orders=np.arange(1,51)
    omega=2*np.pi*15
    energy_factor=m*omega**2*1e-12/(2*Boltzmann*1e-9)
    def g1(x,separation,T,z):
        wavelength=h/np.sqrt(2*np.pi*m*Boltzmann*T*1e-9)*1e6
        local=z*np.exp(-energy_factor*np.atleast_1d(x)[:,None]**2/T)
        return (local**orders*np.exp(-np.pi*separation**2/(orders*wavelength**2))/np.sqrt(orders)).sum(axis=1)/wavelength
    x=np.arange(-66,67,6)
    rng=np.random.default_rng(1847)
    sigma=0.0025  # atoms / micrometre
    data=g1(x,0,80,0.19)+rng.normal(0,sigma,len(x))
    measured=1.481
    for gain in [0.95,1,1.05]:
        fit=least_squares(lambda z:(gain*g1(x,0,*z)-data)/sigma,
                          [70,0.17],bounds=([10,0.01],[250,0.7]))
        T,z=fit.x
        n=g1(0,0,T,z)[0]
        pair=1+(g1(0,0.25,T,z)[0]/n)**2
        cov=np.linalg.inv(fit.jac.T@fit.jac)
        def pair_at(par):
            t,f=par;return 1+(g1(0,.25,t,f)[0]/g1(0,0,t,f)[0])**2
        delta=np.array([.001,.000001])
        deriv=np.array([(pair_at(fit.x+np.eye(2)[j]*delta[j])-pair_at(fit.x-np.eye(2)[j]*delta[j]))/(2*delta[j]) for j in range(2)])
        se=np.sqrt(deriv@cov@deriv)
        print("gain, T, fugacity, pair, prediction SE, chi2:",gain,T,z,pair,se,2*fit.cost)
    print("held-out independent synthetic pair statistic:", measured, "+/- 0.025")


def fermionization():
    # Harmonic-oscillator length and inverse length set x and k units.
    for tau in [0,1,4,12]:
        a=1-1j*tau
        def density(y):
            inner=2*np.exp(-a*y*y/2)/a+np.sqrt(2*np.pi/a)*y*erf(np.sqrt(a/2)*y)
            return np.exp(-y*y)*abs(inner)**2
        value,error=quad(density,-9,9,epsabs=2e-10,limit=500)
        scale=np.hypot(1,tau)/np.pi**2
        print("trap-unit time, boson n(0), quadrature error:",tau,value*scale,error*scale)
    print("free-fermion central occupation:",1/np.sqrt(np.pi))
    for time, width in [(0, 22), (12, 42)]:
        flight = 70 - time
        camera_scale = hbar / m * 1e9 * flight  # um per inverse um
        print("evolution ms, camera scale, optical and source widths in inverse um:",
              time, camera_scale, 4.8 / camera_scale, width / camera_scale)


def transverse_modes():
    for frequency in (8100, 1500):
        weight = np.exp(-h * frequency / (Boltzmann * 80e-9))
        excited = 1 - (1 - weight)**2
        relative_threshold = np.sqrt(8 * h * frequency / m)
        print("guide Hz, excited fraction (Boltzmann), collision threshold in mm/s:",
              frequency, excited, 1000 * relative_threshold)


def pixel_window(pdf):
    """Exact integrals of the published Schemmer Fig. 3(ii) linear strokes."""
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "measurements"))
    from atom_chip_panel import read_panel

    with tempfile.TemporaryDirectory() as folder:
        svg = Path(folder) / "panel.svg"
        subprocess.run(["pdftocairo", "-svg", "-f", "3", "-l", "3", str(pdf), str(svg)],
                       check=True)
        data, *theories = read_panel(svg)
    width = 1.74
    centers = width * np.arange(-143, 144)
    observed = np.interp(centers, *data)
    shoulder = (centers >= -45) & (centers <= -10)
    for theory in theories:
        integral = make_interp_spline(*theory, k=1).antiderivative()
        bins = (integral(centers + width/2) - integral(centers - width/2)) / width
        squared = (bins - observed)**2
        print("centers on shoulder, RMS all / shoulder / outside:",
              shoulder.sum(), *(np.sqrt(squared[mask].mean())
                                for mask in (np.ones_like(shoulder), shoulder, ~shoulder)))


def slice_asymmetry(pdf):
    """Fig. 6(b), Dubois et al. v2; left and right band means from the blue stroke."""
    digest = "a088060f79337b3e8e8681c0b4e9def1b872ace8d68a9768933b8aaba59f3e40"
    if hashlib.sha256(pdf.read_bytes()).hexdigest() != digest:
        raise ValueError("Use article_asymetrie_24-04-2024.pdf from arXiv:2505.05839v2.")
    with tempfile.TemporaryDirectory() as folder:
        svg = Path(folder) / "slice.svg"
        subprocess.run(["pdftocairo", "-svg", str(pdf), str(svg)], check=True)
        paths = ET.parse(svg).getroot().findall(".//{*}path")
    def points(path):
        return np.array(re.findall(r"[ML]\s*([-\d.]+)[ ,]+([-\d.]+)", path.get("d", "")),
                        dtype=float)

    grids = [points(p) for p in paths if p.get("stroke") == "rgb(100%, 100%, 100%)"]
    vertical = sorted(xy[0, 0] for xy in grids if xy.shape == (2, 2) and xy[1, 0] == xy[0, 0])
    horizontal = sorted(xy[0, 1] for xy in grids if xy.shape == (2, 2) and xy[1, 1] == xy[0, 1])
    xscale = np.polyfit(vertical, [-400, -200, 0, 200, 400], 1)
    yscale = np.polyfit(horizontal, [0, 1, 2, 3], 1)
    blue, = [points(p) for p in paths if p.get("stroke", "").startswith("rgb(12.156")
             and p.get("d", "").count("L") > 300]
    x, density = np.polyval(xscale, blue[:, 0]), np.polyval(yscale, blue[:, 1])
    order = np.argsort(x)
    integral = make_interp_spline(x[order], density[order], k=1).antiderivative()
    for center in (-17, -15, -19):
        left = (integral(center-100) - integral(center-180)) / 80
        right = (integral(center+180) - integral(center+100)) / 80
        print("reflection center (um), left and right wing means (atoms/um):",
              center, float(left), float(right))


def cradle_markers(pdf):
    if hashlib.sha256(Path(pdf).read_bytes()).hexdigest() != "5248d52e43c36d90a4e0f0dfc6b219b08a11649cc2329f79a813369d1180a647":
        raise ValueError("The marker coordinates were calibrated for arXiv:1707.07031v5.")
    with tempfile.TemporaryDirectory() as folder:
        svg=Path(folder)/"figure.svg"
        subprocess.run(["pdftocairo","-svg","-f","5","-l","5",str(pdf),str(svg)],check=True)
        paths=ET.parse(svg).getroot().findall(".//{*}path")
    # Main panel only. The plotting-library paths for circular markers
    # include cubic control points at their extrema; their center is invariant.
    points=[]
    for path in paths:
        if path.get("fill")!="rgb(35.299683%, 51.799011%, 67.098999%)" or path.get("transform"):
            continue
        xy=np.array(re.findall(r"[-+]?[0-9]+(?:[.][0-9]+)?",path.get("d","")),float).reshape(-1,2)
        x,y=(xy.min(axis=0)+xy.max(axis=0))/2
        if abs(x-389.3)<.1 and y<70: # marker printed inside the legend
            continue
        # Origin and slope from x-axis ticks 0, 0.5, ... 2.5 s, and
        # y-axis ticks log(DT)=1.0,1.5,...3.5, in PDF points.
        points.append(((x-354.676473)/80.09531,1+(166.734614-y)/40.3996))
    data=np.array(points)
    assert data.shape==(49,2)
    return data[np.argsort(data[:, 0])]


def log_contrast(times, start, strength, rate):
    return 1 + 0.5 * np.log1p(strength * np.exp(-2 * rate * (times - start)))


def cradle_forecast(data):
    """Fit 0.20 to 1.00 seconds and predict every later marker at 35 degrees."""
    time, observed = data[data[:, 0] >= 0.20].T
    train = time <= 1.00
    fit = least_squares(lambda p: log_contrast(time[train], 0.20, *p) - observed[train],
                        [2, 1], bounds=([0, 0], [100, 100]))
    forecast = log_contrast(time[~train], 0.20, *fit.x)
    constant = observed[train].mean()
    return time[~train], forecast - observed[~train], constant - observed[~train], fit.x


def fit_cradle(pdf):
    data = cradle_markers(pdf)
    for start in [.167,.2,.3]:
        t,log_distance=data[data[:,0]>=start].T
        def residual(par):
            return log_contrast(t, start, *par) - log_distance
        fit=least_squares(residual,[2,1],bounds=([0,0],[100,100]))
        print("start(s), count, amplitude squared, rate/s, rms, constant-model rms:",
              start,len(t),*fit.x,np.mean(fit.fun**2)**.5,np.std(log_distance))
    times, decay_error, constant_error, parameters = cradle_forecast(data)
    print("late test count, fitted A and rate/s, forecast RMS decay and constant:",
          len(times), *parameters, np.sqrt(np.mean(decay_error**2)),
          np.sqrt(np.mean(constant_error**2)))


if __name__=="__main__":
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument("--cradle-pdf",type=Path)
    p.add_argument("--chip-pdf", type=Path, help="Schemmer et al., arXiv:1810.07170v2")
    p.add_argument("--slice-figure", type=Path, help="Dubois et al., Fig. 6(b) source PDF")
    args=p.parse_args()
    thermometer()
    fermionization()
    transverse_modes()
    if args.cradle_pdf:
        fit_cradle(args.cradle_pdf)
    if args.chip_pdf:
        pixel_window(args.chip_pdf)
    if args.slice_figure:
        slice_asymmetry(args.slice_figure)
