"""Halo mass function for cluster counts: Tinker et al. (2008) f(sigma) on an
Eisenstein and Hu (1998) no-wiggle linear power spectrum, flat Lambda-CDM.

Masses are M500c in solar masses (no h), lengths in Mpc (no h), densities in
M_sun Mpc^-3. Only numpy and scipy are required.

Sources, as read:
- Tinker et al. 2008, arXiv:0803.2706v1: Eq. (2)-(3), Table 2, Eq. (5)-(8).
  Parameters between tabulated overdensities use a natural cubic spline in
  log10(Delta), following their Appendix B recommendation (we did not use
  their Table B3 second derivatives).
- Eisenstein and Hu 1998, arXiv:astro-ph/9709112v1: Eq. (26), (28)-(31).
"""
import math

import numpy as np
from scipy.integrate import quad
from scipy.interpolate import CubicSpline

SPEED_OF_LIGHT_KM_S = 299792.458
GRAVITATIONAL_CONSTANT_MPC_KM2_PER_MSUN_S2 = 4.300917270e-9  # G in Mpc (km/s)^2 / M_sun

TINKER_DELTA = np.array([200, 300, 400, 600, 800, 1200, 1600, 2400, 3200], dtype=float)
TINKER_A = np.array([0.186, 0.200, 0.212, 0.218, 0.248, 0.255, 0.260, 0.260, 0.260])
TINKER_LOWER_A = np.array([1.47, 1.52, 1.56, 1.61, 1.87, 2.13, 2.30, 2.53, 2.66])
TINKER_B = np.array([2.57, 2.25, 2.05, 1.87, 1.59, 1.51, 1.46, 1.44, 1.41])
TINKER_C = np.array([1.19, 1.27, 1.34, 1.45, 1.58, 1.80, 1.97, 2.24, 2.44])


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


class FlatLambdaCdm:
    def __init__(self, hubble=0.7, omega_matter=0.3, omega_baryon=0.048, spectral_index=0.965,
                 cmb_temperature=2.7255):
        self.hubble = hubble
        self.omega_matter = omega_matter
        self.omega_baryon = omega_baryon
        self.spectral_index = spectral_index
        self.theta_cmb = cmb_temperature / 2.7

    def hubble_rate_ratio(self, redshift):
        return math.sqrt(self.omega_matter * (1 + redshift) ** 3 + 1 - self.omega_matter)

    def critical_density(self, redshift):
        hubble_km_s_mpc = 100 * self.hubble * self.hubble_rate_ratio(redshift)
        return 3 * hubble_km_s_mpc ** 2 / (8 * math.pi * GRAVITATIONAL_CONSTANT_MPC_KM2_PER_MSUN_S2)

    def mean_matter_density_comoving(self):
        return self.critical_density(0.0) * self.omega_matter

    def omega_matter_at(self, redshift):
        return self.omega_matter * (1 + redshift) ** 3 / self.hubble_rate_ratio(redshift) ** 2

    def growth_factor(self, redshift):
        """Linear growth D(z)/D(0) from D proportional to H(a) * int_0^a da' / (a' H(a'))^3."""
        def unnormalised(scale_factor):
            integrand = lambda a: 1.0 / (a * self.hubble_rate_ratio(1 / a - 1)) ** 3
            integral, _ = quad(integrand, 1e-8, scale_factor, limit=200)
            return self.hubble_rate_ratio(1 / scale_factor - 1) * integral
        return unnormalised(1 / (1 + redshift)) / unnormalised(1.0)

    def no_wiggle_transfer(self, wavenumber_per_mpc):
        """Eisenstein and Hu (1998) Eq. (26), (28)-(31)."""
        h = self.hubble
        omega_matter_h2 = self.omega_matter * h * h
        omega_baryon_h2 = self.omega_baryon * h * h
        baryon_fraction = self.omega_baryon / self.omega_matter
        sound_horizon = 44.5 * np.log(9.83 / omega_matter_h2) / np.sqrt(1 + 10 * omega_baryon_h2 ** 0.75)
        alpha_gamma = (1 - 0.328 * np.log(431 * omega_matter_h2) * baryon_fraction
                       + 0.38 * np.log(22.3 * omega_matter_h2) * baryon_fraction ** 2)
        gamma_effective = self.omega_matter * h * (
            alpha_gamma + (1 - alpha_gamma) / (1 + (0.43 * wavenumber_per_mpc * sound_horizon) ** 4))
        q = wavenumber_per_mpc / h * self.theta_cmb ** 2 / gamma_effective
        logarithm = np.log(2 * math.e + 1.8 * q)
        coefficient = 14.2 + 731 / (1 + 62.5 * q)
        return logarithm / (logarithm + coefficient * q * q)


class LinearPowerSpectrum:
    def __init__(self, cosmology, sigma8):
        self.cosmology = cosmology
        self.wavenumber = np.logspace(-5, 2.5, 3000)
        shape = self.wavenumber ** cosmology.spectral_index * cosmology.no_wiggle_transfer(self.wavenumber) ** 2
        radius8 = 8.0 / cosmology.hubble
        self.amplitude = sigma8 ** 2 / self._variance_of_shape(shape, radius8)
        self.shape = shape

    def _variance_of_shape(self, shape, radius):
        kr = self.wavenumber * radius
        window = 3 * (np.sin(kr) - kr * np.cos(kr)) / kr ** 3
        integrand = shape * window ** 2 * self.wavenumber ** 3 / (2 * math.pi ** 2)
        return trapezoid(integrand, np.log(self.wavenumber))

    def sigma(self, radius, growth=1.0):
        return growth * math.sqrt(self.amplitude * self._variance_of_shape(self.shape, radius))


def tinker_parameters(delta_mean, redshift):
    log_delta = np.log10(TINKER_DELTA)
    target = math.log10(delta_mean)
    amplitude = float(CubicSpline(log_delta, TINKER_A, bc_type="natural")(target))
    lower_a = float(CubicSpline(log_delta, TINKER_LOWER_A, bc_type="natural")(target))
    b = float(CubicSpline(log_delta, TINKER_B, bc_type="natural")(target))
    c = float(CubicSpline(log_delta, TINKER_C, bc_type="natural")(target))
    alpha = 10 ** (-(0.75 / math.log10(delta_mean / 75)) ** 1.2)  # Eq. (8)
    return (amplitude * (1 + redshift) ** -0.14, lower_a * (1 + redshift) ** -0.06,
            b * (1 + redshift) ** -alpha, c)


def tinker_multiplicity(sigma, parameters):
    amplitude, lower_a, b, c = parameters
    return amplitude * ((sigma / b) ** -lower_a + 1) * np.exp(-c / sigma ** 2)  # Eq. (3)


class ClusterMassFunction:
    """dn/dM and n(>M) for M500c at one redshift; Delta_mean = 500 / Omega_m(z)."""

    def __init__(self, cosmology, sigma8, redshift):
        self.cosmology = cosmology
        self.redshift = redshift
        self.power = LinearPowerSpectrum(cosmology, sigma8)
        self.growth = cosmology.growth_factor(redshift)
        self.delta_mean = 500.0 / cosmology.omega_matter_at(redshift)
        self.parameters = tinker_parameters(self.delta_mean, redshift)
        self.mean_density = cosmology.mean_matter_density_comoving()

    def sigma_of_mass(self, mass):
        radius = (3 * mass / (4 * math.pi * self.mean_density)) ** (1 / 3)
        return self.power.sigma(radius, self.growth)

    def differential(self, mass):
        """Comoving dn/dM in Mpc^-3 M_sun^-1 (Tinker Eq. 2)."""
        step = 0.01
        sigma_low = self.sigma_of_mass(mass * math.exp(-step))
        sigma_high = self.sigma_of_mass(mass * math.exp(step))
        dln_inverse_sigma_dln_mass = -(math.log(sigma_high) - math.log(sigma_low)) / (2 * step)
        sigma = self.sigma_of_mass(mass)
        return tinker_multiplicity(sigma, self.parameters) * self.mean_density / mass ** 2 * dln_inverse_sigma_dln_mass

    def cumulative(self, minimum_mass, maximum_mass=10 ** 16.5, samples=240):
        log_mass = np.linspace(math.log(minimum_mass), math.log(maximum_mass), samples)
        integrand = np.array([self.differential(math.exp(value)) * math.exp(value) for value in log_mass])
        return float(trapezoid(integrand, log_mass))
