"""Toy SZ cluster survey: Y-M relation with a hydrostatic bias, lognormal scatter,
an S/N selection, and the sigma8 - (1 - b) degeneracy that follows.

Sources, as read (full text of the sections cited):
- Planck 2015 results XXIV, arXiv:1502.01597v3.
  Eq. (7): E^-beta(z) D_A^2 Ybar500 / 1e-4 Mpc^2 = Y* (h/0.7)^(-2+alpha) [(1-b) M500 / 6e14 Msun]^alpha,
  with log10 Y* = -0.19, alpha = 1.79, beta = 0.66 (their Table 1 X-ray calibration).
  Eq. (9): lognormal scatter sigma_lnY = 0.173.
  Eq. (14): completeness chi = (1/2)[1 - erf((q_cat - q_m) / sqrt(2))], q_cat = 6.
- The halo mass function comes from cluster_mass_function.py (Tinker et al. 2008).

What is a toy here, on purpose:
- The noise is sigma_Ybar = NOISE_ARCMIN2 * (theta500 / 5 arcmin), the same everywhere
  on the sky. It grows with cluster size, as a matched filter's noise does, so large
  nearby clusters are not all detected; the constant was chosen so the toy sample has a
  few hundred clusters. Planck's real noise map varies across the sky.
- Ybar500 is treated as the spherical Y inside R500, divided by D_A^2. The section we
  read does not say whether Ybar500 is spherical or cylindrical; the tutorial assumes
  spherical and says so.
- Only the total number of detected clusters is fitted, so sigma8 and (1 - b) are
  completely degenerate. Planck breaks part of it with N(z, q) and external priors.
"""
import math

import numpy as np
from scipy.integrate import quad
from scipy.optimize import brentq
from scipy.special import erf

from cluster_mass_function import SPEED_OF_LIGHT_KM_S, ClusterMassFunction, FlatLambdaCdm, tinker_multiplicity

LOG10_Y_STAR = -0.19
Y_MASS_SLOPE = 1.79
Y_REDSHIFT_SLOPE = 0.66
LOG_SCATTER = 0.173
DETECTION_THRESHOLD = 6.0
NOISE_ARCMIN2 = 2.0e-4
NOISE_REFERENCE_ARCMIN = 5.0
SKY_FRACTION = 0.65
REDSHIFT_EDGES = np.round(np.arange(0.0, 1.01, 0.1), 2)
LOG_MASS_GRID = np.linspace(math.log(5e13), math.log(3e15), 180)
ARCMIN2_PER_STERADIAN = (180 * 60 / math.pi) ** 2


def trapezoid(values, positions):
    return float(np.sum(0.5 * (values[1:] + values[:-1]) * np.diff(positions)))


class ComovingGeometry:
    def __init__(self, cosmology):
        self.cosmology = cosmology
        self.hubble_distance = SPEED_OF_LIGHT_KM_S / (100 * cosmology.hubble)

    def comoving_distance(self, redshift):
        value, _ = quad(lambda z: 1 / self.cosmology.hubble_rate_ratio(z), 0, redshift)
        return self.hubble_distance * value

    def angular_diameter_distance(self, redshift):
        return self.comoving_distance(redshift) / (1 + redshift)

    def shell_volume(self, low, high):
        """Comoving volume of the redshift shell over SKY_FRACTION of the sky, Mpc^3."""
        return SKY_FRACTION * 4 * math.pi / 3 * (self.comoving_distance(high) ** 3 - self.comoving_distance(low) ** 3)


class RedshiftSlice:
    """sigma(M) at sigma8 = 1 is tabulated once; sigma8 only rescales it."""

    def __init__(self, cosmology, geometry, low, high):
        self.redshift = 0.5 * (low + high)
        self.volume = geometry.shell_volume(low, high)
        self.angular_distance = geometry.angular_diameter_distance(self.redshift)
        self.evolution = cosmology.hubble_rate_ratio(self.redshift)
        radius500 = (3 * np.exp(LOG_MASS_GRID) / (4 * math.pi * 500 * cosmology.critical_density(self.redshift))) ** (1 / 3)
        theta500_arcmin = radius500 / self.angular_distance * 180 * 60 / math.pi
        self.noise = NOISE_ARCMIN2 * theta500_arcmin / NOISE_REFERENCE_ARCMIN
        unit = ClusterMassFunction(cosmology, 1.0, self.redshift)
        self.parameters = unit.parameters
        self.mean_density = unit.mean_density
        masses = np.exp(LOG_MASS_GRID)
        self.unit_sigma = np.array([unit.sigma_of_mass(m) for m in masses])
        step = 0.01
        self.dln_inverse_sigma = np.array([
            -(math.log(unit.sigma_of_mass(m * math.exp(step))) - math.log(unit.sigma_of_mass(m * math.exp(-step)))) / (2 * step)
            for m in masses])

    def mass_function_per_log_mass(self, sigma8):
        """dn/dlnM in Mpc^-3 on LOG_MASS_GRID."""
        masses = np.exp(LOG_MASS_GRID)
        multiplicity = tinker_multiplicity(sigma8 * self.unit_sigma, self.parameters)
        return multiplicity * self.mean_density / masses * self.dln_inverse_sigma

    def mean_log_signal(self, one_minus_bias):
        """ln of the mean Ybar500 in arcmin^2 on LOG_MASS_GRID, from Planck Eq. (7) with h = 0.7."""
        masses = np.exp(LOG_MASS_GRID)
        scaled = 1e-4 * 10 ** LOG10_Y_STAR * (one_minus_bias * masses / 6e14) ** Y_MASS_SLOPE
        physical = scaled * self.evolution ** Y_REDSHIFT_SLOPE
        return np.log(physical / self.angular_distance ** 2 * ARCMIN2_PER_STERADIAN)


def detection_probability(mean_log_signal, noise):
    """P(Ybar_obs / sigma > q_cat | M): lognormal intrinsic scatter, then Gaussian noise (Eq. 14).

    The noise follows the true theta500, a simplification: Planck evaluates it at the
    size implied by the mass, which carries the same scatter."""
    nodes, weights = np.polynomial.hermite_e.hermegauss(40)
    weights = weights / weights.sum()
    signal = np.exp(mean_log_signal[:, None] + LOG_SCATTER * nodes[None, :])
    completeness = 0.5 * (1 - erf((DETECTION_THRESHOLD - signal / noise[:, None]) / math.sqrt(2)))
    return np.sum(completeness * weights[None, :], axis=1)


def expected_counts(slices, sigma8, one_minus_bias):
    counts = []
    for piece in slices:
        integrand = piece.mass_function_per_log_mass(sigma8) * detection_probability(piece.mean_log_signal(one_minus_bias), piece.noise)
        counts.append(piece.volume * trapezoid(integrand, LOG_MASS_GRID))
    return np.array(counts)


def monte_carlo_counts(slices, sigma8, one_minus_bias, generator):
    """Draw every halo above 5e13 Msun, give it a scattered Y and a noisy measurement, count detections."""
    counts = []
    for piece in slices:
        density = piece.mass_function_per_log_mass(sigma8)
        cumulative = np.concatenate([[0.0], np.cumsum(0.5 * (density[1:] + density[:-1]) * np.diff(LOG_MASS_GRID))])
        halo_count = generator.poisson(piece.volume * cumulative[-1])
        log_mass = np.interp(generator.random(halo_count) * cumulative[-1], cumulative, LOG_MASS_GRID)
        mean_log = np.interp(log_mass, LOG_MASS_GRID, piece.mean_log_signal(one_minus_bias))
        signal = np.exp(mean_log + LOG_SCATTER * generator.standard_normal(halo_count))
        noise = np.interp(log_mass, LOG_MASS_GRID, piece.noise)
        measured = signal + noise * generator.standard_normal(halo_count)
        counts.append(int(np.sum(measured / noise > DETECTION_THRESHOLD)))
    return np.array(counts)


def sigma8_matching_total(slices, total, one_minus_bias):
    return brentq(lambda s8: expected_counts(slices, s8, one_minus_bias).sum() - total, 0.5, 1.2, xtol=1e-6)


def build_slices(cosmology=None):
    cosmology = cosmology or FlatLambdaCdm()
    geometry = ComovingGeometry(cosmology)
    return [RedshiftSlice(cosmology, geometry, low, high) for low, high in zip(REDSHIFT_EDGES[:-1], REDSHIFT_EDGES[1:])]


def run(true_sigma8=0.81, true_one_minus_bias=0.8, realizations=200, seed=69):
    slices = build_slices()
    truth = expected_counts(slices, true_sigma8, true_one_minus_bias)
    generator = np.random.default_rng(seed)
    draws = np.array([monte_carlo_counts(slices, true_sigma8, true_one_minus_bias, generator) for _ in range(realizations)])
    totals = draws.sum(axis=1)
    one_draw = int(totals[0])
    degeneracy = []
    for one_minus_bias in (0.6, 0.7, 0.8, 0.9, 1.0):
        degeneracy.append({
            "assumedOneMinusBias": one_minus_bias,
            "sigma8FromExpectedTotal": sigma8_matching_total(slices, truth.sum(), one_minus_bias),
            "sigma8FromFirstRealization": sigma8_matching_total(slices, one_draw, one_minus_bias),
        })
    no_bias = expected_counts(slices, true_sigma8, 1.0)
    return {
        "setup": {
            "trueSigma8": true_sigma8, "trueOneMinusBias": true_one_minus_bias,
            "noiseArcmin2AtFiveArcmin": NOISE_ARCMIN2, "detectionThreshold": DETECTION_THRESHOLD,
            "skyFraction": SKY_FRACTION, "logScatter": LOG_SCATTER,
            "redshiftEdges": REDSHIFT_EDGES.tolist(), "realizations": realizations, "seed": seed,
        },
        "expectedCountsPerRedshiftBin": truth.tolist(),
        "expectedTotal": float(truth.sum()),
        "monteCarloMeanPerRedshiftBin": draws.mean(axis=0).tolist(),
        "monteCarloMeanTotal": float(totals.mean()),
        "monteCarloStandardDeviationTotal": float(totals.std(ddof=1)),
        "monteCarloMinusExpectedInStandardErrors": float((totals.mean() - truth.sum()) / (totals.std(ddof=1) / math.sqrt(realizations))),
        "firstRealizationTotal": one_draw,
        "predictedTotalAtTrueSigma8IfOneMinusBiasWereOne": float(no_bias.sum()),
        "degeneracy": degeneracy,
    }
