"""Synthetic neutron, susceptibility and photoemission benchmarks. NumPy and SciPy."""
from itertools import combinations
from math import pi, sin, sqrt

import numpy as np
from numpy.polynomial.hermite import hermgauss
from numpy.polynomial.legendre import leggauss
from scipy.optimize import least_squares
from scipy.special import ndtr


def occupied(mask):
    return bin(mask).count("1")


def neutron_bin(center, momentum_width=0.06, n=48):
    """Average an illustrative Müller line shape over momentum and an energy bin."""
    q_nodes, q_weights = hermgauss(n)
    x_nodes, x_weights = leggauss(n)
    result = 0.
    for z, weight in zip(q_nodes, q_weights):
        q = pi/2 + sqrt(2)*momentum_width*z
        lower = 17*pi*abs(sin(q))
        upper = 34*pi*abs(sin(q/2))
        length = np.arccosh(upper/lower)
        energies = lower*np.cosh((1+x_nodes)*length/2)
        detection = ndtr((center+1-energies)/2) - ndtr((center-1-energies)/2)
        result += weight/np.sqrt(pi)*length/2*(x_weights @ detection)
    return result


def spin_levels(n):
    """Periodic antiferromagnet with J=1, eigenvalues and matching total Sz."""
    levels, mags = [], []
    for n_up in range(n+1):
        basis = [b for b in range(1 << n) if occupied(b) == n_up]
        index = {b: i for i, b in enumerate(basis)}
        h = np.zeros((len(basis), len(basis)))
        for i, b in enumerate(basis):
            for j in range(n):
                bond = (1 << j) | (1 << ((j+1) % n))
                antiparallel = occupied(b & bond) == 1
                h[i,i] += -0.25 if antiparallel else 0.25
                if antiparallel:
                    h[i,index[b ^ bond]] += 0.5
        levels.extend(np.linalg.eigvalsh(h))
        mags.extend([n_up-n/2]*len(basis))
    return np.array(levels), np.array(mags)


def response(e, m, thermal, field):
    shifted = e-field*m
    prob = np.exp(-(shifted-min(shifted))/thermal)
    prob /= prob.sum()
    mean = prob @ m
    return mean/6, (prob @ (m*m) - mean**2)/(6*thermal)


def predict_resonance(e, m):
    """Calibrate J and g from two synthetic static measurements, then transfer g."""
    mu_b = 0.0578838  # meV/T
    thermal = (0.25,1.0)  # meV
    observed = np.array([.00115305106,.00201563229])
    def residual(params):
        exchange, g = params
        values = [(g*mu_b)**2/exchange * response(e,m,theta/exchange,0)[1]
                  for theta in thermal]
        return (values-observed)/(.01*observed)
    fit = least_squares(residual,[1.01,2.0],bounds=(0,np.inf))
    covariance = np.linalg.inv(fit.jac.T @ fit.jac)
    g = fit.x[1]
    field = 5.
    variance = mu_b**2*(field**2*covariance[1,1]+g**2*.01**2)
    print('fitted (J,g), covariance, resonance in meV with 1 SD:',
          fit.x,covariance,mu_b*g*field,sqrt(variance))


def velocity_sample():
    """Infer two velocities from quartiles of an ideal chiral removal spectrum."""
    rng = np.random.default_rng(780)
    q = np.array([.06,.10,.15])
    a = sin(pi/8)**2
    mixing = np.array([[1-a,a],[a,1-a]])
    def infer():
        energies = q[:,None]*(1.2 + 1.2*rng.beta(.5,.5,(len(q),2000)))
        slopes = (np.quantile(energies,[.25,.75],axis=1)/q).mean(axis=1)
        return np.linalg.solve(mixing,slopes)
    first = infer()
    samples = np.stack([infer() for _ in range(1000)])
    print('velocity estimates and sampling SD over further trials:',
          first,np.std(samples,axis=0,ddof=1))


def resolution_check(order=48):
    """Fixed q, chiral equal exponents, independently calibrated Gaussian blur."""
    q, slow, fast, sigma = .15, 1.2, 2.4, .04
    nodes, weights = leggauss(order)
    blur, gaussian_weights = hermgauss(12)
    lower, upper = q*slow, q*fast
    angle = pi*(nodes+1)/2
    ideal = (upper+lower)/2 + (upper-lower)*np.cos(angle)/2
    measured = ideal[:, None] + sqrt(2)*sigma*blur
    joint = np.outer(weights/2, gaussian_weights/sqrt(pi))
    mean = np.sum(joint*measured)
    variance = np.sum(joint*(measured-mean)**2)
    np.testing.assert_allclose(variance, (upper-lower)**2/8 + sigma**2, atol=1e-14)
    loss = weights @ (ndtr((lower-ideal)/sigma) + ndtr((ideal-upper)/sigma))/2
    def slopes(noise):
        return (mean + np.array([-1,1])*sqrt(2*(variance-noise**2)))/q
    np.testing.assert_allclose(slopes(sigma), [slow,fast], atol=1e-13)
    return mean, variance, loss, slopes(0)


def basis(n, up, down):
    def masks(number):
        return [sum(1 << j for j in sites) for sites in combinations(range(n), number)]
    return [a | (b << n) for a in masks(up) for b in masks(down)]


def remove(b, j):
    if not b & (1 << j):
        return None
    sign = (-1)**occupied(b & ((1 << j)-1))
    return b ^ (1 << j), sign


def hubbard(n, states, interaction):
    index = {b: i for i,b in enumerate(states)}
    h = np.zeros((len(states), len(states)))
    for i,b in enumerate(states):
        h[i,i] += interaction*occupied(b & (b >> n) & ((1 << n)-1))
        for spin in (0,n):
            for j in range(n):
                nxt = (j+1) % n
                coefficient = 1. if nxt == 0 else -1.  # antiperiodic seam
                for source,target in ((j,nxt),(nxt,j)):
                    move = remove(b,spin+source)
                    if move is None or move[0] & (1 << (spin+target)):
                        continue
                    rest,sign = move
                    sign *= (-1)**occupied(rest & ((1 << (spin+target))-1))
                    h[index[rest | (1 << (spin+target))],i] += coefficient*sign
    assert np.array_equal(h,h.T)
    return np.linalg.eigh(h)


def electron_removal(interaction):
    n = 6
    initial, final = basis(n,2,2), basis(n,1,2)
    index = {b:i for i,b in enumerate(final)}
    e, vectors = hubbard(n,initial,interaction)
    ef, vf = hubbard(n,final,interaction)
    assert e[1]-e[0] > 1e-8
    occupations = []
    for k in (2*np.arange(n)+1)*pi/n:
        projected = np.zeros(len(final),complex)
        for coeff,b in zip(vectors[:,0],initial):
            for j in range(n):
                move = remove(b,j)
                if move:
                    rest,sign = move
                    projected[index[rest]] += coeff*sign*np.exp(-1j*k*j)/sqrt(n)
        weights = abs(vf.T @ projected)**2
        assert np.isclose(sum(weights),np.vdot(projected,projected).real,atol=1e-12)
        occupations.append(weights.sum())
        if k <= pi/2+1e-8:
            grouped = {}
            for energy,w in zip(ef-ef[0],weights):
                key = round(energy,9)
                grouped[key] = grouped.get(key,0.)+w
            print('U, k/pi, n(k), strongest lines (excitation energy, weight):',
                  interaction,k/pi,weights.sum(),
                  [(t,w) for t,w in sorted(grouped.items(),key=lambda x:-x[1])[:4] if w>1e-9])
    assert abs(sum(occupations)-2) < 1e-12


if __name__ == '__main__':
    for order in (24,48,80):
        for width in (0.,0.06):
            print('quadrature, momentum width, bin intensities:',order,width,
                  [round(neutron_bin(c,width,order),9) for c in (51.,55.,65.,77.)])
    e,m = spin_levels(6)
    for temp in (.25,.5,1.,2.):
        value,chi = response(e,m,temp,0.)
        diff = (response(e,m,temp,1e-4)[0]-response(e,m,temp,-1e-4)[0])/2e-4
        print('T/J, magnetization, dimensionless susceptibility, finite difference:',temp,value,chi,diff)
    predict_resonance(e,m)
    velocity_sample()
    for order in (32, 64):
        print('resolution test: mean, variance, outside weight, uncorrected velocities',
              *resolution_check(order))
    for u in (0.,4.):
        electron_removal(u)
