"""Release of the atom-chip double well, Schemmer et al., Fig. 3.

Run with the versioned PDF arXiv:1810.07170v2, NumPy, SciPy and pdftocairo.
The smooth plotted t=0 profile initializes both solvers. Later plotted theory
curves are never used to evolve the density. Units: micrometres, milliseconds,
nK for energy divided by k_B, inverse micrometres for Bethe wavenumbers.
"""
import argparse
from collections import defaultdict
from pathlib import Path
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET

import numpy as np
from scipy.constants import atomic_mass, Boltzmann, hbar
from scipy.fft import irfft, next_fast_len, rfft
from scipy.integrate import simpson
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares
from scipy.special import expit

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "measurements"))
from atom_chip_panel import coordinates

mass = 86.90918053 * atomic_mass
alpha = hbar / mass * 1e9
kinetic = hbar**2 / (2 * mass * Boltzmann) * 1e21
pressure_factor = Boltzmann / mass * 1e-3


def projected_fig4_profiles(pdf):
    """Invert the perspective plot using labeled position, time and density grids."""
    with tempfile.TemporaryDirectory() as folder:
        svg = Path(folder) / "figure4.svg"
        subprocess.run(["pdftocairo","-svg","-f","4","-l","4",str(pdf),str(svg)],check=True)
        all_paths = ET.parse(svg).getroot().findall(".//{*}path")
    grouped = defaultdict(list)
    for path in all_paths:
        if path.get("stroke") and path.get("transform"):
            grouped[path.get("transform")].append(path)
    paths = next(ps for ps in grouped.values()
                 if sum(p.get("stroke-width")=="1.2" and len(coordinates(p))>200 for p in ps)==10)
    grid = [coordinates(p) for p in paths if p.get("stroke","").startswith("rgb(89.999")
            and coordinates(p).shape == (3,2)]
    assert len(grid)==17  # three position grids, ten time grids, four density grids
    def line(points):
        return np.cross(np.r_[points[0],1],np.r_[points[1],1])
    def intersection(first,second):
        value=np.cross(line(first),line(second))
        return value[:2]/value[2]
    design=[]
    target=[]
    for x,pos_grid in zip((-200,0,200),grid[:3]):
        for t,time_grid in zip(range(0,181,20),grid[3:13]):
            uv=intersection(pos_grid[:2],time_grid[1:])
            for axis in range(2):
                row=np.zeros(8)
                row[axis*3:axis*3+3]=[t,x,1]
                row[6:]=-uv[axis]*np.array([t,x])
                design.append(row)
                target.append(uv[axis])
    floor=np.r_[np.linalg.lstsq(design,target,rcond=None)[0],1].reshape(3,3)
    floor_polygon=next(coordinates(p) for p in paths if p.get("fill","").startswith("rgb(86.999"))
    # Density grids follow near-left -> far-left -> far-right, in floor-polygon order.
    corners=np.linalg.solve(floor,np.c_[floor_polygon[:3],np.ones(3)].T).T
    corners /= corners[:,2,None]
    def misfit(params):
        height,floor_density=params[:3],params[3]
        residuals=[]
        for density,printed_grid in zip((10,20,30,40),grid[13:]):
            proj=corners@floor.T + (density-floor_density)*height
            residuals.extend((proj[:,:2]/proj[:,2,None]-printed_grid).ravel())
        return residuals
    calibration=least_squares(misfit,[0,4,0,-1],xtol=1e-14,ftol=1e-14,gtol=1e-14)
    assert max(abs(calibration.fun))<0.06
    height, floor_density=calibration.x[:3],calibration.x[3]
    def invert(points,time_ms):
        # At fixed t this is a 2-D projective map from (x,n,1) to (u,v,1).
        matrix=np.column_stack((floor[:,1],height,
                                floor[:,2]+time_ms*floor[:,0]-floor_density*height))
        p=np.linalg.solve(matrix,np.c_[points,np.ones(len(points))].T).T
        p=p[:,:2]/p[:,2,None]
        p=p[np.argsort(p[:,0])]
        return p.T
    measured=[coordinates(p) for p in paths if p.get("stroke-width")=="1.2" and len(coordinates(p))>200]
    return [invert(profile,20*j) for j,profile in enumerate(measured)]


def loss_test(pdf):
    """Independent three-body coefficient, folded through the measured Fig. 4 profiles."""
    profiles=projected_fig4_profiles(pdf)
    omega=2*np.pi*5400
    osc_length=np.sqrt(hbar/(mass*omega))*1e6
    # kappa is an atom-loss coefficient, m^6/s -> micrometre^6/ms (factor 1e33).
    kappa=1.8e-41 * 1e33
    K0=kappa/(3*np.pi**2*osc_length**4)
    times=20*np.arange(10)
    area = np.trapezoid(profiles[0][1], profiles[0][0])
    for width,gain in ((0,1),(3.48,1),(6.96,1),(3.48,3500/area)):
        counts,rates=[],[]
        for x,n in profiles:
            grid=np.arange(x.min(),x.max(),0.5)
            v=gain*np.interp(grid,x,n)
            if width:
                v=gaussian_filter1d(v,width/0.5,mode="nearest")
            counts.append(np.trapezoid(v,grid))
            v=np.maximum(v,0)
            rates.append(K0*np.trapezoid(v**3/(1+2*0.0053*v),grid))
        print("width, gain, initial and final count, predicted losses (trapezoid and Simpson), plotted drop, K0:",
              width,gain,counts[0],counts[-1],np.trapezoid(rates,times),
              simpson(rates,x=times),counts[0]-counts[-1],K0)


def read_profiles(pdf):
    with tempfile.TemporaryDirectory() as folder:
        svg = Path(folder) / "figure.svg"
        subprocess.run(["pdftocairo", "-svg", "-f", "3", "-l", "3",
                        str(pdf), str(svg)], check=True)
        paths = ET.parse(svg).getroot().findall(".//{*}path")
    groups = defaultdict(list)
    for path in paths:
        if path.get("transform") and path.get("stroke"):
            groups[path.get("transform")].append(path)
    result = {}
    for paths in groups.values():
        theory = [p for p in paths if p.get("stroke-width") == "3.5" and len(coordinates(p)) > 20]
        if len(theory) != 1:
            continue
        color = theory[0].get("stroke")
        time = 0 if "86.669" in color else 25 if "44.963" in color else 40 if "63.529" in color else None
        if time is None:
            continue
        data = next(p for p in paths if p.get("stroke") == color and
                    p.get("stroke-width") == "0.5" and len(coordinates(p)) > 100)
        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)
        cx, cy = np.polyfit(xs, [-200,0,200], 1), np.polyfit(ys, [0,10,20,30], 1)
        def curve(p):
            xy = coordinates(p)
            return np.polyval(cx,xy[:,0]), np.polyval(cy,xy[:,1])
        result[time] = curve(data), curve(theory[0])
    assert set(result) == {0,25,40}
    return result


class LiebLiniger:
    def __init__(self, dk, transverse_khz, cutoff=48):
        self.k = np.arange(-cutoff, cutoff+dk/2, dk)
        self.dk = dk
        size = len(self.k)
        self.fft_size = next_fast_len(2*size)
        distances = dk*np.arange(size)
        c = 2 * (2 * np.pi * transverse_khz) * 5.3e-3 / alpha
        cell = (np.arctan((distances+dk/2)/c)-np.arctan((distances-dk/2)/c))/np.pi
        weights = np.zeros(self.fft_size)
        weights[:size] = cell
        weights[-size+1:] = cell[:0:-1]
        self.multiplier = rfft(weights)

    def convolution(self, field):
        spectrum = rfft(field, self.fft_size, axis=-1)
        return irfft(spectrum*self.multiplier, self.fft_size, axis=-1)[...,:len(self.k)]

    def thermal(self, temperature):
        # The largest chemical potential covers the highest observed density.
        mu = np.unique(np.r_[np.linspace(-12*temperature,-temperature,16),
                             np.linspace(-temperature,0,20),np.linspace(0,260,80)])
        bare = (kinetic*self.k**2-mu[:,None])/temperature
        eps = bare.copy()
        for _ in range(550):
            nxt = bare-self.convolution(np.logaddexp(0,-eps))
            if np.max(abs(eps-nxt)) < 3e-9:
                break
            eps = nxt
        else:
            raise ArithmeticError("Yang–Yang pseudoenergy failed to converge.")
        fill = expit(-eps)
        # Dressing equation dr(1)=1+K(fill*dr(1)), solved for fill*dr(1).
        density = fill.copy()
        for _ in range(550):
            nxt = fill*(1+self.convolution(density))
            if np.max(abs(density-nxt)) < 5e-8:
                break
            density = nxt
        else:
            raise ArithmeticError("Thermal density dressing failed to converge.")
        measure = self.dk/(2*np.pi)
        n = density.sum(axis=1)*measure
        e = np.sum(density*(kinetic*self.k**2),axis=1)*measure
        pressure = np.sum(np.logaddexp(0,-eps),axis=1)*temperature*measure
        return n,e,pressure,density

    def flux(self, rho, guess):
        fill = rho/(1+self.convolution(rho))
        current = guess
        for _ in range(140):
            nxt = fill*(alpha*self.k+self.convolution(current))
            if np.max(abs(current-nxt)) < 2e-6:
                return nxt
            current = nxt
        raise ArithmeticError("Current dressing failed to converge.")


class EquationOfState:
    def __init__(self, gas, initial_temperature):
        self.densities = np.geomspace(0.002,45,110)
        arr_e, arr_p = [], []
        for temp in np.unique(np.r_[np.geomspace(5,900,30), initial_temperature]):
            ns,e,p,r = gas.thermal(temp)
            arr_e.append(np.interp(self.densities,ns,e/ns))
            arr_p.append(np.interp(self.densities,ns,p/ns))
            if temp == initial_temperature:
                self.initial = ns,e,p,r
        self.energy, self.pressure = np.array(arr_e).T,np.array(arr_p).T
        if np.min(np.diff(self.energy,axis=1)) < -1:
            raise ArithmeticError("Energy is not increasing on the tabulated density range.")
        self.energy = np.maximum.accumulate(self.energy,axis=1)

    def at(self, density, internal_energy):
        n = np.maximum(density, 1e-12)
        a = np.clip(np.searchsorted(self.densities,n)-1,0,len(self.densities)-2)
        weight = np.clip((n-self.densities[a])/(self.densities[a+1]-self.densities[a]),0,1)[:,None]
        es = (1-weight)*self.energy[a] + weight*self.energy[a+1]
        ps = (1-weight)*self.pressure[a] + weight*self.pressure[a+1]
        target = internal_energy/n
        b = np.clip(np.sum(es<target[:,None],axis=1)-1,0,es.shape[1]-2)
        ix = np.arange(len(n))
        v = np.clip((target-es[ix,b])/np.maximum(es[ix,b+1]-es[ix,b],1e-10),0,1)
        return n*((1-v)*ps[ix,b]+v*ps[ix,b+1])


def limited_gradient(y):
    left = y-np.roll(y,1,axis=0)
    right = np.roll(y,-1,axis=0)-y
    grad = np.sign(left)*np.minimum(abs(left), abs(right))*(left*right>0)
    grad[[0,-1]] = 0
    return grad


def ghd_step(rho, current, gas, dx):
    # Conservative TVD interface flux with upwind speed v_eff and minmod slope.
    velocity = np.divide(current,rho,out=np.zeros_like(rho),where=rho>1e-12)
    slope = limited_gradient(rho)
    speed = (velocity[:-1]+velocity[1:])/2
    f = np.where(speed>=0,speed*(rho[:-1]+slope[:-1]/2),
                 speed*(rho[1:]-slope[1:]/2))
    f = np.pad(f,((1,1),(0,0)))
    return -np.diff(f,axis=0)/dx


def chd_rhs(state, eos, dx):
    # Reconstruct n,u,e/n in primitive variables to keep the dilute wings positive.
    def prim(s):
        n = np.maximum(s[:,0],1e-10)
        u = s[:,1]/n
        esp = np.maximum(s[:,2]/n-u**2/(2*pressure_factor),0)
        return np.column_stack((n,u,esp))
    def physical(w):
        n,u,esp = w.T
        p = eos.at(n,n*esp)
        total = n*(esp+u**2/(2*pressure_factor))
        conserved = np.column_stack((n,n*u,total))
        flux = np.column_stack((n*u,n*u*u+pressure_factor*p,u*(total+p)))
        speed = abs(u)+np.sqrt(3*pressure_factor*p/np.maximum(n,1e-10))
        return conserved,flux,speed
    w=prim(state)
    slope=limited_gradient(w)
    # Reconstruct piecewise-constant states next to the vacuum. Extrapolating
    # velocity and specific energy independently there can violate positivity.
    dry = np.minimum.reduce([w[:,0],np.roll(w[:,0],1),np.roll(w[:,0],-1)]) < 0.025
    slope[dry] = 0
    left,fl,al=physical(w[:-1]+slope[:-1]/2)
    right,fr,ar=physical(w[1:]-slope[1:]/2)
    f=(fl+fr)/2-np.maximum(al,ar)[:,None]*(right-left)/2
    return -np.diff(np.pad(f,((1,1),(0,0))),axis=0)/dx


def run(pdf, dx, dk, temperature, gain=1, transverse_khz=8.1):
    profiles=read_profiles(pdf)
    gas=LiebLiniger(dk,transverse_khz)
    eos=EquationOfState(gas,temperature)
    x=np.arange(-1050,1050+dx/2,dx)
    ns,e,_,r=eos.initial
    initial=profiles[0][1]
    n0=gain*np.maximum(0,np.interp(x,*initial,left=0,right=0))
    rho=np.stack([np.interp(n0,ns,column,left=0) for column in r.T],axis=1)
    atmosphere = 1e-6
    state=np.column_stack((n0+atmosphere,np.zeros_like(x),
                           np.interp(n0,ns,e,left=0)+0.5*temperature*atmosphere))
    current=rho*alpha*gas.k
    t=0.
    print("dx dk T gain transverse-kHz N",dx,dk,temperature,gain,transverse_khz,np.sum(n0)*dx,flush=True)
    for stop in [25.,40.]:
        while t < stop-1e-10:
            dt=min(0.4*dx/(alpha*max(gas.k)),stop-t)
            current=gas.flux(rho,current)
            step1=rho+dt*ghd_step(rho,current,gas,dx)
            stepflux=gas.flux(step1,current)
            rho=(rho+step1+dt*ghd_step(step1,stepflux,gas,dx))/2
            first=state+dt*chd_rhs(state,eos,dx)
            state=(state+first+dt*chd_rhs(first,eos,dx))/2
            if not np.all(np.isfinite(state)) or np.min(state[:,0]) < 0:
                raise ArithmeticError("Conventional closure left the positive-density domain.")
            t+=dt
        centers=1.74*np.arange(-143,144)
        observed=np.interp(centers,*profiles[int(t+0.5)][0])
        nodes,weights=np.polynomial.legendre.leggauss(8)
        densities=(rho.sum(axis=1)*dk/(2*np.pi),state[:,0])
        predictions=[np.interp(centers[:,None]+0.87*nodes,x,n)@(weights/2) for n in densities]
        print(int(t+0.5),"ms rms",*[round(np.mean((a-observed)**2)**.5,4) for a in predictions],
              "atom numbers",*[round(a.sum()*dx,2) for a in densities],flush=True)


if __name__=="__main__":
    cli=argparse.ArgumentParser(description=__doc__)
    cli.add_argument("pdf",type=Path)
    cli.add_argument("--dx",type=float,default=6)
    cli.add_argument("--dk",type=float,default=0.5)
    cli.add_argument("--temperature",type=float,default=300)
    cli.add_argument("--gain",type=float,default=1)
    cli.add_argument("--transverse-khz",type=float,default=8.1)
    cli.add_argument("--loss-test",action="store_true",help="Evaluate loss in the separate Fig. 4 re-trapping run.")
    args=cli.parse_args()
    if args.loss_test:
        loss_test(args.pdf)
    else:
        run(args.pdf,args.dx,args.dk,args.temperature,args.gain,args.transverse_khz)
