"""Compare the published traces in Fig. 3(ii), t=40 ms, Schemmer et al.

Usage: python3 atom_chip_panel.py /path/to/1810.07170.pdf
Source: https://arxiv.org/pdf/1810.07170v2 ; requires pdftocairo, NumPy, SciPy.
No measurements are simulated. Coordinates are inferred from the figure's
own labeled ticks. No publisher image or raw shot data is distributed here.
"""
import argparse
import hashlib
from pathlib import Path
import re
import subprocess
import tempfile
import xml.etree.ElementTree as ET

import numpy as np
from scipy.ndimage import gaussian_filter1d


def coordinates(path):
    d = path.get("d", "")
    if re.search(r"[A-KN-Zac-z]", d):  # Only straight M/L polylines.
        return np.empty((0,2))
    vals = re.findall(r"[-+]?\d*\.?\d+(?:[eE][+-]?\d+)?",d)
    return np.array(vals, dtype=float).reshape((-1,2))


def read_panel(svg):
    paths = ET.parse(svg).getroot().findall(".//{*}path")
    # A thin green data trace, a thick green GHD trace and one black dashed
    # CHD trace share a coordinate system only in the 40-ms comparison panel.
    groups = {}
    for path in paths:
        if path.get("transform") and path.get("stroke"):
            groups.setdefault(path.get("transform"), []).append(path)
    for paths in groups.values():
        traces = []
        for p in paths:
            color = [float(v) for v in re.findall(r"[\d.]+(?=%)",p.get("stroke",""))]
            if len(color)==3 and color[0]==0 and abs(color[1]-63.53)<0.1 and color[2]==0:
                if len(coordinates(p))>20:
                    traces.append(p)
        dashed = [p for p in paths if p.get("stroke-dasharray") and len(coordinates(p))>20]
        if len(traces)==2 and len(dashed)==1:
            break
    else:
        raise ValueError("Could not identify the three trajectories in Fig. 3(ii), 40 ms.")

    ticks = [coordinates(p) for p in paths if p.get("stroke-width")=="0.5"]
    ticks = [v for v in ticks if v.shape==(2,2)]
    xs = sorted(v[0,0] for v in ticks if np.isclose(v[0,0],v[1,0]) and v[1,1]>v[0,1]+3)
    ys = sorted(v[0,1] for v in ticks if np.isclose(v[0,1],v[1,1]) and v[1,0]>v[0,0]+3)
    assert len(xs)==3 and len(ys)==4
    cx = np.polyfit(xs, [-200,0,200],1)
    cy = np.polyfit(ys, [0,10,20,30],1)
    assert max(abs(np.polyval(cx,xs)-[-200,0,200])) < 0.04
    assert max(abs(np.polyval(cy,ys)-[0,10,20,30])) < 0.004
    curves = []
    widths = []
    for p in sorted(traces,key=lambda p:float(p.get("stroke-width"))) + dashed:
        xy = coordinates(p)
        x,y = np.polyval(cx,xy[:,0]),np.polyval(cy,xy[:,1])
        assert np.all(np.diff(x)>0) and x[0]<-300 and x[-1]>300
        curves.append((x,y))
        widths.append(abs(cy[0])*float(p.get("stroke-width"))/2)
    print("Panel y half-stroke widths, atoms/um:",np.round(widths,3))
    return curves


def predictions(curves, spacing, blur, calibration=1.0):
    centers = 1.74*np.arange(-143,144)
    grid = np.arange(-360,340+spacing/2,spacing)
    # The measured trace represents the observed image and is sampled at pixel
    # centers. Apply the common response only to the two published theory curves.
    obs = calibration*np.interp(centers,*curves[0])
    predicted = []
    nodes,weights = np.polynomial.legendre.leggauss(8)
    for curve in curves[1:]:
        smooth = np.interp(grid,*curve)
        if blur:
            smooth = gaussian_filter1d(smooth,blur/spacing,mode="nearest",truncate=6)
        pixels = np.interp(centers[:,None]+0.87*nodes,grid,smooth) @ (weights/2)
        predicted.append(pixels)
    rms = [np.sqrt(np.mean((v-obs)**2)) for v in predicted]
    # Intervals are fixed on the physical axis, with no realignment of the peaks.
    central = (centers>=-45)&(centers<=-10)
    means = [np.mean(v[central]) for v in (obs,*predicted)]
    return np.array(rms),np.array(means)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pdf",type=Path)
    source = parser.parse_args().pdf
    print("Source SHA-256:",hashlib.sha256(source.read_bytes()).hexdigest())
    with tempfile.TemporaryDirectory() as folder:
        svg = Path(folder)/"figure3.svg"
        subprocess.run(["pdftocairo","-svg","-f","3","-l","3",str(source),str(svg)],check=True)
        curves = read_panel(svg)
    for blur in (0,3.48,8.70,17.4):
        rms,means = predictions(curves,0.05,blur)
        fine = predictions(curves,0.025,blur)
        print("extra Gaussian sigma, RMS(GHD,CHD), band(data,GHD,CHD):",
              blur,np.round(rms,4),np.round(means,4))
        assert max(np.max(abs(a-b)) for a,b in zip((rms,means),fine))<0.001
    for gain in (1-200/6300,1+200/6300):
        print("Density-scale sensitivity:",round(gain,5),np.round(predictions(curves,0.05,0,gain)[0],4))


if __name__ == "__main__":
    main()
