"""Read the authors' vector trace for Fig. 4b of arXiv:2505.05839v2.

Extract DWD_GPE_vs_exp_resub.pdf from that version's TeX-source archive.
Requires NumPy, SciPy, and Poppler pdftocairo. Run:
    python3 bipartite_profile.py DWD_GPE_vs_exp_resub.pdf
The two coordinates are calibrated against the published gridlines. The
extracted curve is a plotted experimental density, not per-shot atom counts.
"""
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 numpy.polynomial.hermite import hermgauss
from scipy.constants import hbar, physical_constants


def profile(velocity, plateau, sound):
    return plateau*np.clip((velocity+2*sound)/(3*sound),0.,1.)**2


def trace_points(node):
    return np.array([tuple(map(float,p)) for p in
                     re.findall(r'[ML]\s*([-\d.]+)[ ,]+([-\d.]+)',node.attrib['d'])])


def measurements(path):
    if hashlib.sha256(path.read_bytes()).hexdigest() != '0aa410943d9c80852165c81d5e8cefdcaf44da63b20b5a150e56f3113d308f20':
        raise ValueError('Use Fig. 4b from the arXiv v2 source')
    with tempfile.TemporaryDirectory() as folder:
        svg=Path(folder)/'figure.svg'
        subprocess.run(['pdftocairo','-svg',str(path),str(svg)],check=True)
        paths=[n for n in ET.parse(svg).getroot().iter() if n.tag.endswith('path') and n.get('d')]
    # The red and dashed black model are the two multi-segment strokes.
    curves=[p for p in paths if p.get('d').count('L')>40 and
            ('stroke' in p.attrib or 'stroke:' in p.get('style',''))]
    if len(curves)!=2:
        raise RuntimeError('SVG path representation changed; inspect the calibrated source.')
    red=max(curves,key=lambda p:trace_points(p)[0,0])
    black=next(p for p in curves if p is not red)
    def convert(p):
        xy=trace_points(p)
        x=(xy[:,0]-174.299394)*10/(290.435098-174.299394)
        y=(xy[:,1]-50.383118)*50/(197.471626-50.383118)
        ix=np.argsort(x)
        return x[ix],y[ix]
    return convert(red),convert(black)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('figure',type=Path)
    measured,theory=measurements(parser.parse_args().figure)
    z=np.array([-5.,-2.5,0.,2.5,5.])
    n0=49.       # atoms/um, rounded plateau of the published dashed curve
    g=2*5.3e-9*hbar*(2*np.pi*2560)
    mass=86.90918053*physical_constants['atomic mass constant'][0]
    c0=1e3*np.sqrt(g*n0*1e6/mass)     # m/s -> micrometres/ms
    print('sound speed in micrometres/ms',c0)
    print('ray, measured curve, published dashed curve, independent hydrodynamic prediction')
    print(np.column_stack([z,np.interp(z,*measured),np.interp(z,*theory),profile(z,n0,c0)]))
    # Sensitivity only. A 2 um Gaussian width at t=10 ms gives 0.2 um/ms.
    q,w=hermgauss(40)
    averaged=profile(z[:,None]+np.sqrt(2)*.2*q,n0,c0) @ w/np.sqrt(np.pi)
    print('change after illustrative 2 um Gaussian blur',averaged-profile(z,n0,c0))
    # Descriptive scatter of vector vertices, not a shot-level uncertainty.
    x, density = measured
    reservoir = density[(x>=4) & (x<=9)]
    print('high-density sample count and standard deviation',len(reservoir),np.std(reservoir,ddof=1))
    width, wave_number, sigma = 2., 4*np.pi, .2
    amplitude = width/np.sqrt(width**2+sigma**2) * np.exp(
        -wave_number**2*width**2*sigma**2/(2*(width**2+sigma**2)))
    print('synthetic image difference bound, reservoir units',.006*amplitude)
