"""Two references for xi_plus and xi_minus of a pure E-mode field with power P(ell).

grid_expectation: the exact expectation on the simulation's periodic grid, averaged over lags
with the same pair weights as the estimator (what an unbiased estimator must return).
hankel_transform: the continuous flat-sky result
xi_plus  = 1/(2 pi) integral ell P(ell) J0(ell theta) d ell,
xi_minus = 1/(2 pi) integral ell P(ell) J4(ell theta) d ell (Kilbinger 2015, Eq. 35),
computed by direct quadrature with scipy's Bessel functions.
"""
import numpy as np
from scipy.integrate import quad
from scipy.special import jv

from restricted_shear_simulation import ARCMIN


def grid_expectation(power, ell_x, ell_y, pixel_arcmin, separation, angle, pair_counts, bin_edges):
    pixels = power.shape[0]
    box_area = (pixels * pixel_arcmin * ARCMIN) ** 2
    phi_ell = np.arctan2(ell_y, ell_x)
    xi_plus_lag = np.fft.ifft2(power).real * pixels ** 2 / box_area
    # <gamma(x) gamma(x + Delta)> = (1/A) sum_ell exp(4 i phi_ell) P exp(i ell . Delta); numpy's
    # ifft2 carries exp(+i ell . Delta).
    gamma_gamma_lag = np.fft.ifft2(np.exp(4j * phi_ell) * power) * pixels ** 2 / box_area
    xi_minus_lag = (gamma_gamma_lag * np.exp(-4j * angle)).real
    plus, minus = [], []
    for lower, upper in zip(bin_edges[:-1], bin_edges[1:]):
        selected = (separation >= lower) & (separation < upper)
        weight = pair_counts[selected].sum()
        plus.append((xi_plus_lag[selected] * pair_counts[selected]).sum() / weight)
        minus.append((xi_minus_lag[selected] * pair_counts[selected]).sum() / weight)
    return np.array(plus), np.array(minus)


def hankel_transform(power_function, theta_arcmin, order, ell_maximum):
    theta = theta_arcmin * ARCMIN
    def integrand(ell):
        return ell * power_function(ell) * jv(order, ell * theta) / (2.0 * np.pi)
    value, _ = quad(integrand, 1.0, ell_maximum, limit=4000, epsabs=0.0, epsrel=1e-8)
    return value
