"""Four synthetic detector checks. Run with Python 3, NumPy and SciPy.

These controlled examples use the inputs printed in the associated readings.
No experimental measurement, fitting parameter or network access is required.
"""
from math import exp, pi, sin, sqrt

import numpy as np
from numpy.polynomial.hermite import hermgauss
from scipy.integrate import quad
from scipy.special import ndtr


def gaussian(z):
    return exp(-z*z/2)/sqrt(2*pi)


def pixel_image():
    """Integrate the rectangular aperture over the blurred cloud, then its moments."""
    gaussian_width = sqrt(3**2 + 2**2)
    pixel_width = 6.

    def density(x):
        # Even symmetry lets both CDFs be evaluated on their stable lower tail.
        return (ndtr((pixel_width/2-abs(x))/gaussian_width)
                - ndtr((-pixel_width/2-abs(x))/gaussian_width))/pixel_width

    mass, second, fourth = [
        2*quad(lambda x: x**order*density(x), 0, np.inf, epsabs=1e-10)[0]
        for order in (0,2,4)
    ]
    excess = fourth/second**2-3
    np.testing.assert_allclose([mass,second,excess], [1,16,-.0421875],
                               atol=2e-12, rtol=0)
    print(f"Pixel image: area {mass:.8f}, variance {second:.8f}, excess {excess:.8f}")


def gaussian_grid(order):
    nodes, weights = hermgauss(order)
    return sqrt(2)*nodes, weights/sqrt(pi)


def correlated_line_widths(order):
    """Integrate the joint Gaussian instrument and the independent physical linewidth."""
    nodes, weights = gaussian_grid(order)
    zq, ze, zi = np.meshgrid(nodes, nodes, nodes, indexing="ij")
    measure = np.einsum('i,j,k->ijk',weights,weights,weights)
    momentum_error = .1*zq
    energy_error = 2*(.5*zq + sqrt(.75)*ze)
    intrinsic = 2*zi
    variances = []
    for slope in [10.,-10.,0.]:
        residual = intrinsic+energy_error-slope*momentum_error
        mean = np.sum(measure*residual)
        variances.append(np.sum(measure*(residual-mean)**2))
    np.testing.assert_allclose(variances,[7,11,8],rtol=0,atol=1e-13)
    return np.array(variances)


def rapidity_images():
    """Convolve both positive-density preparations separately at nodes and midpoints."""
    width, blur, k = 2., .2, 4*pi
    spacing = pi*(width**2+blur**2)/(k*width**2)

    def convolved(v, sign):
        def integrand(z):
            u = v-blur*z
            signal = ndtr(u/3)+sign*.003*exp(-u*u/(2*width**2))*sin(k*u)
            return gaussian(z)*signal
        return quad(integrand,-12,12,epsabs=2e-14,epsrel=2e-14)[0]

    nodes = np.arange(-4,5)*spacing
    differences = [convolved(v,1)-convolved(v,-1) for v in nodes]
    assert max(map(abs,differences)) < 2e-14
    midpoint = spacing/2
    response = convolved(midpoint,1)-convolved(midpoint,-1)
    np.testing.assert_allclose([spacing,midpoint,response],
                               [.2525,.12625,.00026127],atol=5e-9,rtol=0)
    print(f"Ray sample spacing {spacing:.6f}; first midpoint {midpoint:.6f}, "
          f"normalized image difference {response:.10f}")


def measured_centroids(exchange2, order):
    """Fold the full cosine dispersion with both resolutions before energy integration."""
    nodes, weights = gaussian_grid(order)
    centroids = []
    for q0 in [0,pi/2,pi]:
        q = q0+.1*nodes
        centers = .4+1-np.cos(q)+exchange2*(1-np.cos(2*q))

        def profile(energy):
            scaled = (energy-centers)/.1
            return np.dot(weights,np.exp(-scaled**2/2))/(.1*sqrt(2*pi))

        # Integrate the full accessible band plus tails, splitting at line scales.
        knots = [-2.,.4,1.4,1.7,2.4,4.4]
        mass = quad(profile,knots[0],knots[-1],points=knots[1:-1],epsabs=2e-13)[0]
        moment = quad(lambda e:e*profile(e),knots[0],knots[-1],
                      points=knots[1:-1],epsabs=2e-13)[0]
        assert abs(mass-1)<2e-12
        centroids.append(moment/mass)
    contrast = centroids[1]-(centroids[0]+centroids[2])/2
    assert abs(contrast-2*exchange2*exp(-.02))<2e-12
    return contrast


if __name__ == "__main__":
    pixel_image()
    widths = correlated_line_widths(12)
    np.testing.assert_allclose(widths,correlated_line_widths(20),atol=1e-13)
    print("Variances at +10, -10, 0 meV per momentum unit:",widths)
    print("Inferred covariance:",(widths[1]-widths[0])/40)
    rapidity_images()
    for j2 in [0.,.15]:
        contrast = measured_centroids(j2,24)
        assert abs(contrast-measured_centroids(j2,48))<2e-12
        print(f"Three-centroid contrast, J2={j2:.2f} meV: {contrast:.10f} meV")
