"""Toy relic-abundance model used by the Sandbox Physics AC73 Lab and course.

Dimensionless Boltzmann equation, with x = m/T and Y = n/s:

    dY/dln x = -k(x) [Y^2 - Yeq(x)^2],   k(x) = A sigma0 F(x) / (x E(x))

    A    = s(m)/H_rad(m) = (2 pi sqrt(10)/15) sqrt(g*) m M_Pl   (g*s = g*)
    Yeq  = 45 g x^2 K2(x) / (4 pi^4 g*s)                      (Maxwell-Boltzmann)
    F(x) = <sigma v>(x)/sigma0 for a contact interaction with constant |M|^2 and
           massless final states (Gondolo-Gelmini average); F -> 1 for x >> 1 and
           F -> x^2/4 for x << 1.
    E(x) = H/H_rad = sqrt(1 + (x_r/x)^n): an extra fluid with rho ~ a^-(4+n) that
           equals radiation at T_r = m/x_r (D'Eramo, Fernandez & Profumo 2017).

Units: GeV for masses and temperatures, cm^3/s for sigma0 on input.
Requires Python 3.9+, NumPy and SciPy (tested with NumPy 2.0.2, SciPy 1.13.1).
"""
import math
import numpy as np
from scipy.special import kve

G_STAR = 86.25            # constant g* = g*s (SM, everything but t, W, Z, H massless)
G_DARK = 2.0              # internal states of the dark particle
REDUCED_PLANCK_GEV = 2.435e18
GEV_MINUS2_IN_CM3_PER_S = 1.167329e-17   # (hbar c)^2 c
T0_KELVIN = 2.7255
BOLTZMANN_EV_PER_K = 8.617333262e-5
HBAR_C_EV_CM = 1.973269804e-5
G_STAR_S_TODAY = 43.0 / 11.0
CRITICAL_DENSITY_OVER_H2_GEV_CM3 = 1.05371e-5
X_START = 1e-3
STEPS_PER_E_FOLD = 250

ENTROPY_TODAY_CM3 = 2 * math.pi**2 / 45 * G_STAR_S_TODAY * (T0_KELVIN * BOLTZMANN_EV_PER_K / HBAR_C_EV_CM) ** 3
OMEGA_H2_PER_GEV_Y = ENTROPY_TODAY_CM3 / CRITICAL_DENSITY_OVER_H2_GEV_CM3
EQUILIBRIUM_PREFACTOR = 45 * G_DARK / (4 * math.pi**4 * G_STAR)


def entropy_to_hubble_at_mass(mass_gev):
    """A = x s/H_rad, which is independent of x for g*s = g*. It has units of
    GeV^2, so A times sigma0 in GeV^-2 is dimensionless."""
    return 2 * math.pi * math.sqrt(10) / 15 * math.sqrt(G_STAR) * mass_gev * REDUCED_PLANCK_GEV


def equilibrium_yield(x):
    x = np.asarray(x, dtype=float)
    return EQUILIBRIUM_PREFACTOR * x**2 * kve(2, x) * np.exp(-x)


def cross_section_shape(x, nodes=600):
    """F(x) = 2/K2e(x)^2 * int_0^inf sqrt(y(1+y/4x)/x) (1+y/2x) K1e(2x+y) e^-y dy,
    by the trapezoid rule in ln y (y from 1e-10 to 80)."""
    lny = np.linspace(math.log(1e-10), math.log(80.0), nodes)
    y = np.exp(lny)
    integrand = np.sqrt(y * (1 + y / (4 * x)) / x) * (1 + y / (2 * x)) * kve(1, 2 * x + y) * np.exp(-y) * y
    integrate = np.trapezoid if hasattr(np, 'trapezoid') else np.trapz
    return float(2 * integrate(integrand, lny) / kve(2, x) ** 2)


def expansion_factor(x, n, x_r):
    x = np.asarray(x, dtype=float)
    return np.ones_like(x) if n == 0 else np.sqrt(1 + (x_r / x) ** n)


def grid(n, x_r):
    x_end = 1e3 if n == 0 else max(1e3, 50 * x_r)
    steps = int(math.ceil(math.log(x_end / X_START) * STEPS_PER_E_FOLD))
    return np.exp(np.linspace(math.log(X_START), math.log(x_end), steps + 1))


def solve(cross_section_cm3_s, mass_gev=100.0, n=0, equality_temperature_gev=None, start='thermal', shape=None):
    """Solve with second-order backward differentiation (BDF2) in ln x. Each
    implicit step is a quadratic in Y with one non-negative root."""
    x_r = 0.0 if n == 0 else mass_gev / equality_temperature_gev
    xs = grid(n, x_r)
    sigma0 = cross_section_cm3_s / GEV_MINUS2_IN_CM3_PER_S
    shapes = np.array([cross_section_shape(x) for x in xs]) if shape is None else shape(xs)
    k = entropy_to_hubble_at_mass(mass_gev) * sigma0 * shapes / (xs * expansion_factor(xs, n, x_r))
    yeq = equilibrium_yield(xs)
    h = math.log(xs[1] / xs[0])
    y = np.zeros_like(xs)
    y[0] = yeq[0] if start == 'thermal' else 0.0
    for i in range(1, len(xs)):
        if i == 1:
            a, c = k[i] * h, y[0] + h * k[i] * yeq[i] ** 2
        else:
            a = 2 * h / 3 * k[i]
            c = (4 * y[i - 1] - y[i - 2]) / 3 + 2 * h / 3 * k[i] * yeq[i] ** 2
        if c < 0:
            a, c = k[i] * h, y[i - 1] + h * k[i] * yeq[i] ** 2
        y[i] = 2 * c / (1 + math.sqrt(1 + 4 * a * c))
    return {'x': xs, 'Y': y, 'Yeq': yeq, 'rate_over_hubble': k * yeq, 'k': k}


def omega_h2(mass_gev, final_yield):
    return OMEGA_H2_PER_GEV_Y * mass_gev * final_yield


def summarize(solution, mass_gev):
    x, y, ratio = solution['x'], solution['Y'], solution['rate_over_hubble']
    final = y[-1]
    settle = x[0]
    for i in range(len(x) - 1, -1, -1):
        if abs(y[i] - final) > 0.1 * final:
            settle = x[min(i + 1, len(x) - 1)]
            break
    peak = int(np.argmax(ratio))
    freeze_out = None
    if ratio[peak] > 1:
        for i in range(len(x) - 1, peak, -1):
            if ratio[i - 1] >= 1 > ratio[i]:
                t = math.log(ratio[i - 1]) / (math.log(ratio[i - 1]) - math.log(ratio[i]))
                freeze_out = math.exp(math.log(x[i - 1]) + t * math.log(x[i] / x[i - 1]))
                break
    return {'final_yield': float(final), 'omega_h2': float(omega_h2(mass_gev, final)), 'settling_x': float(settle),
            'peak_rate_over_hubble': float(ratio[peak]), 'peak_x': float(x[peak]), 'freeze_out_x': freeze_out}


def freeze_in_linear_yield(cross_section_cm3_s, mass_gev=100.0):
    """Closed form of A sigma0 int_0^inf F Yeq^2 / x^2 dx for the contact shape:
    (3 pi^2 / 32) a^2 A sigma0 with a = 45 g / (4 pi^4 g*s)."""
    return 3 * math.pi**2 / 32 * EQUILIBRIUM_PREFACTOR**2 * entropy_to_hubble_at_mass(mass_gev) * cross_section_cm3_s / GEV_MINUS2_IN_CM3_PER_S
