Source code for discoeb.components.recfast

####################################################################################################################
# This file is not licensed under the MIT license that covers the rest of DISCO-EB!
# Large portions of this code, which is part of the DISCO-EB module have been adapted from the recfast code base.
# The original recfast code can be found at: https://www.astro.ubc.ca/people/scott/recfast.html
# The recfast code base is distributed under the following license:
####################################################################################################################
# Integrator for Cosmic Recombination of Hydrogen and Helium,
# developed by Douglas Scott (dscott@astro.ubc.ca)
# based on calculations in the papers Seager, Sasselov & Scott
# (ApJ, 523, L1, 1999; ApJS, 128, 407, 2000)
# and "fudge" updates in Wong, Moss & Scott (2008).
#
# Permission to use, copy, modify and distribute without fee or royalty at
# any tier, this software and its documentation, for any purpose and without
# fee or royalty is hereby granted, provided that you agree to comply with
# the following copyright notice and statements, including the disclaimer,
# and that the same appear on ALL copies of the software and documentation,
# including modifications that you make for internal use or for distribution:
#
# Copyright 1999-2010 by University of British Columbia.  All rights reserved.
####################################################################################################################
# This file contains a numba-CUDA version of the recfast equations, adapted for use in the DISCO-EB module.
# The rest of the DISCO-EB module is distributed under the MIT license.
####################################################################################################################
"""
RECFAST's recombination history as a :class:`~discoeb.components.recombination.Recombination`,
in Python after the original code by Douglas Scott.
"""

from __future__ import annotations

import math

from ._component import State, derivative
from .recombination import (
    Recombination,
    const_c,
    const_kB,
    const_mH,
    const_mHe_mH,
)

# RECFAST's physical and atomic constants (PDG 2023 where noted), beside those it imports.
const_me = 9.1093837015e-31  # Electron mass [kg], PDG 2023
const_h = 6.62607015e-34  # Planck's constant [Js], PDG 2023
const_sigma = 6.6524587321e-29  # Thomson scattering cross section [m^2], PDG 2023
const_arad = 4 * 5.670374419e-8 / const_c  # Radiation constant [Ws/m^3/K^4], PDG 2023


# The comments on the constants below follow the original RECFAST code.

const_EionHe12s = 6.314878282674e5  # HeII 1s ionization energy in [K]

# Two-photon rates and atomic levels
Lambda = 8.2245809  # H 2s-1s two photon rate
Lambda_He = 51.3  # HeI 2s-1s two photon rate
L_H_ion = 1.096787737e7  # level for H ionization in m^-1
L_H_alpha = 8.225916453e6  # level for H Ly alpha in m^-1
L_He1_ion = 1.98310772e7  # level for HeI ionization in m^-1
L_He_2s = 1.66277434e7  # level for HeI 2s in m^-1
L_He_2p = 1.71134891e7  # level for He 2p (21P1-11S0) in m^-1

# Atomic data for HeI
A2P_s = 1.798287e9  # Einstein A coefficient for He 21P1-11S0
A2P_t = 177.58  # Einstein A coefficient for He 23P1-11S0
L_He_2Pt = 1.690871466e7  # level for 23P012-11S0 in m^-1
L_He_2St = 1.5985597526e7  # level for 23S1-11S0 in m^-1
L_He2St_ion = 3.8454693845e6  # level for 23S1-continuum in m^-1
sigma_He_2Ps = 1.436289e-22  # H ionization x-section at HeI 21P1-11S0 freq. in m^2
sigma_He_2Pt = 1.484872e-22  # H ionization x-section at HeI 23P1-11S0 freq. in m^2

# Gaussian corrections to the hydrogen fudge (Rubino-Martin et al. 2010) at
# the RECFAST 1.5.2 values, as in CLASS (recfast_AGauss2, recfast_zGauss2),
# CAMB and the Planck 2018 analysis. RECFAST 1.5.0's values (AGauss2 = 0.05,
# zGauss2 = 6.75, fudge 1.105) put x_e 1.8 percent above CLASS after
# recombination and TT 0.14 percent low at l = 300-2000.
AGauss1 = -0.14  # amplitude of the 1st Gaussian for the H fudging
AGauss2 = 0.079  # amplitude of the 2nd Gaussian for the H fudging
zGauss1 = 7.28  # ln(1+z) central value of the 1st Gaussian
zGauss2 = 6.73  # ln(1+z) central value of the 2nd Gaussian
wGauss1 = 0.18  # width of the 1st Gaussian
wGauss2 = 0.33  # width of the 2nd Gaussian
FUDGE_H = 1.125  # hydrogen Peebles fudge with the Gaussian corrections (RECFAST 1.5.2: 1.14 - 0.015)

H_frac = 1.0e-3

Lalpha = 1.0 / L_H_alpha  # Ly alpha wavelength in SI units
Lalpha_He = 1.0 / L_He_2p  # Helium I 2p-1s wavelength in SI units
DeltaB = (
    const_h * const_c * (L_H_ion - L_H_alpha)
)  # energy of first excited state from continuum = 3.4eV
CDB = DeltaB / const_kB  # DeltaB / k_B in K
DeltaB_He = (
    const_h * const_c * (L_He1_ion - L_He_2s)
)  # energy of first excited state from cont. for He = 3.4eV
CDB_He = DeltaB_He / const_kB  # DeltaB_He / k_B (n = 2 to continuum) in K
CB1 = (
    const_h * const_c * L_H_ion / const_kB
)  # H ionization energy / k_B in K (13.6 eV, 4 CDB)
CB1_He1 = const_h * const_c * L_He1_ion / const_kB  # CB1 for HeI ionization potential

CR = 2.0 * math.pi * (const_me / const_h) * (const_kB / const_h)
T_SAHA = 2.7255  # a reference temperature in K: the Saha factor's T_cmb^1.5 is taken relative to it
INV_C15_SAHA = 1.0 / (
    CR * T_SAHA * math.sqrt(CR * T_SAHA)
)  # 1 / (CR T_SAHA)^1.5, about 2e-24
CK = Lalpha**3 / (8.0 * math.pi)
CK_He = Lalpha_He**3 / (8.0 * math.pi)
CL = const_c * const_h / (const_kB * Lalpha)
CL_He = const_c * const_h / (const_kB / L_He_2s)
CT = (8.0 / 3.0) * (const_sigma / (const_me * const_c)) * const_arad
Bfact = const_h * const_c * (L_He_2p - L_He_2s) / const_kB
CL_PSt = const_h * const_c * (L_He_2Pt - L_He_2St) / const_kB
const_h_c_L_He_2St_kB = const_h * const_c * L_He_2St / (const_kB)

# Pequignot, Petitjean & Boisson fit parameters for hydrogen
a_PPB = 4.309
b_PPB = -0.6166
c_PPB = 0.6703
d_PPB = 0.5300

# Verner & Ferland type fit parameters for helium
a_VF = 10.0 ** (-16.744)
b_VF = 0.711
T_0 = 10 ** (0.477121)
T_1 = 10 ** (5.114)

# HeI triplet recombination rate fit parameters
a_trip = 10.0 ** (-16.306)
b_trip = 0.761

Z_H_SAHA_END = 1600.0
"""Redshift below which hydrogen follows the rate equation instead of Saha
equilibrium (CLASS's ``recfast_z_full_H_recombination``)."""

DZ_H_SAHA_BLEND = 50.0
"""Half-width in redshift of the blend from the Saha slope into the rate
equation (CLASS's ``recfast_delta_z_full_H_recombination``)."""

GAMMA_2PS = (
    3.0
    * A2P_s
    * const_c**2
    / (
        math.sqrt(math.pi)
        * sigma_He_2Ps
        * 8.0
        * math.pi
        * const_c
        * L_He_2p
        * (const_c * L_He_2p) ** 2
    )
)
GAMMA_2PT = (
    3.0
    * A2P_t
    * const_c**2
    / (
        math.sqrt(math.pi)
        * sigma_He_2Pt
        * 8.0
        * math.pi
        * const_c
        * L_He_2Pt
        * (const_c * L_He_2Pt) ** 2
    )
)

INV_8PI_L_HE_2PT_3 = 1.0 / (8.0 * math.pi * L_He_2Pt**3)

T_HE_2ST_ION = const_h * const_c * L_He2St_ion / const_kB


def saha_slope(z, T_cmb, Nnow, E_ion, offset, g_factor, f_factor):
    """``d x / d z`` of the Saha ionization fraction at ``z`` (RECFAST's Saha equation).

    Has a single return on purpose. numba-cuda-mlir gives a function that
    returns from several branches a result slot. Inlining it at two call
    sites of one caller merges the two slots into a memref phi, which LLVM's
    typed-pointer verifier rejects.
    """

    T = T_cmb * (1.0 + z)
    # Single precision: (CR T)^1.5 / (1 + z)^3 as (CR T_cmb)^1.5 / (1 + z)^1.5. The quotient rule on the
    # original forms 1e29 * 1e9, at float32's limit, though the value is 1e16.
    CR_T0 = CR * T_cmb
    w = 1.0 + z
    phi = CR_T0 * math.sqrt(CR_T0) / Nnow * (1.0 / w) * (1.0 / math.sqrt(w))
    R = g_factor * phi * math.exp(-E_ion / T)
    slope = 0.0
    if R > 1.0 and T <= E_ion * 0.1:
        # Single precision: the same fraction in r = 1 / R, x = 2 f / (s + 1 + o r) with
        # s = sqrt((1 + o r)^2 + 4 f r). Every term is of order one, where alpha^2 reaches 1e25
        # and the derivative of the quotient below 1e50, past float32's range.
        # r as a product, not as 1 / R: R reaches 1e14 here, and the second derivative of the
        # quotient divides by R^4. The temperature enters relative to T_SAHA, so that the powers
        # of CR T_cmb (1e16) are constants. The bounds keep a speculated evaluation of this
        # branch finite.
        t0 = T_cmb / T_SAHA
        r = (
            (Nnow * (INV_C15_SAHA / g_factor))
            * (w * math.sqrt(w))
            / (t0 * math.sqrt(t0))
            * math.exp(min(E_ion / T, 60.0))
        )
        r = min(r, 1.0)
        # E / (T_cmb w^2) as a product of reciprocals: differentiated twice in the scale factor,
        # the quotient by T_cmb w^2 (1e9 at z = 2e4) forms terms of 1e42
        dlnR = -1.5 / w + (E_ion / T_cmb) * (1.0 / w) * (1.0 / w)
        lead = 1.0 + offset * r
        root = math.sqrt(lead * lead + 4.0 * f_factor * r)
        denom = root + lead
        ddenom = (lead * offset + 2.0 * f_factor) / root + offset
        slope = 2.0 * f_factor / (denom * denom) * ddenom * r * dlnR
    elif R > 1.0e-20 and T <= E_ion * 0.1:
        R = min(R, 1.0)  # as above
        alpha = R + offset
        beta = R * f_factor
        dR = R * (-1.5 / w + (E_ion / T_cmb) * (1.0 / w) * (1.0 / w))
        discr = alpha * alpha + 4.0 * beta
        if discr < 1.0e-35:
            root = math.sqrt(1.0e-35)
            droot = 0.0
        else:
            root = math.sqrt(discr)
            droot = (alpha + 2.0 * f_factor) * dR / root
        denom = root + alpha
        slope = (2.0 * f_factor * dR * denom - 2.0 * beta * (droot + dR)) / (
            denom * denom
        )
    return slope


def saha_fraction(z, T_cmb, Nnow, E_ion, offset, g_factor, f_factor):
    """The Saha ionization fraction at ``z``, the integral of :func:`saha_slope`.

    Returns ``f_factor`` (fully ionized) at high temperature, where
    :func:`saha_slope` is zero, and ``2 beta / (sqrt(alpha^2 + 4 beta) +
    alpha)`` below. A state integrated from full ionization with
    :func:`saha_slope` follows it. Single return, as in :func:`saha_slope`.
    """

    T = T_cmb * (1.0 + z)
    # Single precision: (CR T)^1.5 / (1 + z)^3 as (CR T_cmb)^1.5 / (1 + z)^1.5. The quotient rule on the
    # original forms 1e29 * 1e9, at float32's limit, though the value is 1e16.
    CR_T0 = CR * T_cmb
    w = 1.0 + z
    phi = CR_T0 * math.sqrt(CR_T0) / Nnow * (1.0 / w) * (1.0 / math.sqrt(w))
    R = g_factor * phi * math.exp(-E_ion / T)
    frac = f_factor
    if R > 1.0 and T <= E_ion * 0.1:
        # as in saha_slope: r as a product
        t0 = T_cmb / T_SAHA
        r = (
            (Nnow * (INV_C15_SAHA / g_factor))
            * (w * math.sqrt(w))
            / (t0 * math.sqrt(t0))
            * math.exp(min(E_ion / T, 60.0))
        )
        r = min(r, 1.0)
        lead = 1.0 + offset * r
        frac = 2.0 * f_factor / (math.sqrt(lead * lead + 4.0 * f_factor * r) + lead)
    elif T <= E_ion * 0.1:
        R = min(R, 1.0)
        alpha = R + offset
        beta = R * f_factor
        frac = 2.0 * beta / (math.sqrt(alpha * alpha + 4.0 * beta) + alpha)
    return frac


def hydrogen_rate(x_H, xe, Tmat, z, n_H, Hz, T_cmb, Nnow, K_peebles):
    """``d x_H / d z``: Saha above ``Z_H_SAHA_END``, blended into the rate equation below it."""

    saha = saha_slope(z, T_cmb, Nnow, CB1, 0.0, 1.0, 1.0)
    f0 = saha
    if z < Z_H_SAHA_END:
        fu = FUDGE_H
        one_minus_x_H = 1.0 - x_H
        ln_T = math.log(Tmat / 1.0e4)
        Rdown = (
            1.0e-19
            * a_PPB
            * math.exp(b_PPB * ln_T)
            / (1.0 + c_PPB * math.exp(d_PPB * ln_T))
        )
        CR_Tmat = CR * Tmat
        Rup = Rdown * (CR_Tmat * math.sqrt(CR_Tmat)) * math.exp(-CDB / Tmat)
        rate_diff = xe * x_H * n_H * Rdown - Rup * one_minus_x_H * math.exp(-CL / Tmat)
        K_Lambda_n_1_minus_x_H = K_peebles * Lambda * n_H * one_minus_x_H
        denom_term = (
            1.0 / fu
            + K_Lambda_n_1_minus_x_H / fu
            + K_peebles * Rup * n_H * one_minus_x_H
        )
        # 1 / H for H in 1/s, 1e-18 to 1e-6, scaled to order one as in every rate. Single
        # precision: the quotient rule squares the divisor, twice for a second derivative, and
        # H^4 is below the smallest float32.
        f0 = (
            rate_diff
            * (1.0 + K_Lambda_n_1_minus_x_H)
            * ((1.0 / (Hz * 1.0e13)) * 1.0e13)
            / ((1.0 + z) * denom_term)
        )
        if z > Z_H_SAHA_END - 2.0 * DZ_H_SAHA_BLEND:
            s_blend = (Z_H_SAHA_END - z) / (2.0 * DZ_H_SAHA_BLEND)
            w_full = s_blend * s_blend * (3.0 - 2.0 * s_blend)
            f0 = w_full * f0 + (1.0 - w_full) * saha
    return f0


def helium_rate(x_H, x_He, xe, Tmat, z, a, n_H, Hz, T_cmb, Nnow, fHe):
    """``d x_He / d z``: both Saha stages while their fraction exceeds 0.9, the singlet and triplet rates below.

    The switch is RECFAST's ``x_He > 0.9``, tested on the Saha fraction at
    ``z`` instead of the state. While the Saha slope drives the state, the
    state equals that fraction, so the switch falls at the same redshift. A
    test on the state can switch back, though. A lane whose step lands just
    below 0.9 gets pulled back across and creeps along ``x_He = 0.9`` for a
    couple of hundred tiny steps (a few lanes of most warps, 40 percent of
    the recombination block's cost). Tested on the fraction, the switch
    depends only on ``z``, like hydrogen's (CLASS 3 does the same).

    Only one place calls the rate equation. A helper inlined at two call
    sites, or a local assigned in several branches, gives numba-cuda-mlir a
    memref phi that LLVM rejects.
    """

    saha = (
        saha_slope(z, T_cmb, Nnow, CB1_He1, 1.0, 4.0, fHe)
        + saha_slope(z, T_cmb, Nnow, const_EionHe12s, 1.0 + fHe, 1.0, fHe)
    ) / fHe
    saha_x = (
        saha_fraction(z, T_cmb, Nnow, CB1_He1, 1.0, 4.0, fHe)
        + saha_fraction(z, T_cmb, Nnow, const_EionHe12s, 1.0 + fHe, 1.0, fHe)
    ) / fHe
    # Two two-way merges, not one three-way: Enzyme's forward pass left the rate equation's tangent
    # as `poison` in the three-way phi of the single-precision build, and the Jacobian lost the row.
    use_saha = saha_x > 0.9 or a < 3.0e-4
    f1 = 0.0
    if x_He >= 1.0e-8 and not use_saha:
        f1 = helium_rate_equation(x_H, x_He, xe, Tmat, z, n_H, Hz, fHe)
    if use_saha:
        f1 = saha
    return f1


def helium_rate_equation(x_H, x_He, xe, Tmat, z, n_H, Hz, fHe):
    """The singlet and triplet rate equations of HeI recombination, ``d x_He / d z``.

    ``1 - x_He`` has a floor of 1e-6. The equations hold for ``x_He < 1``
    (at the handover from Saha it is 1e-3 or more), and a solver stage that
    probes ``x_He >= 1`` makes the escape probabilities ``(1 - exp(-tau)) /
    tau`` overflow or 0/0. The NaN stalls the block at ``max_steps``.
    """

    iH = (1.0 / (Hz * 1.0e13)) * 1.0e13  # 1 / H, scaled as in hydrogen_rate
    inv_Hz_z = iH / (1.0 + z)
    n_He = fHe * n_H
    one_minus_x_He = max(1.0 - x_He, 1.0e-6)
    one_minus_x_H = 1.0 - x_H
    n_He_1_minus_x_He = n_He * one_minus_x_He
    CR_Tmat = CR * Tmat
    CR_Tmat_15 = CR_Tmat * math.sqrt(CR_Tmat)
    sq_0 = math.sqrt(Tmat / T_0)
    sq_1 = math.sqrt(Tmat / T_1)
    ln_0 = math.log(1.0 + sq_0)
    ln_1 = math.log(1.0 + sq_1)
    Rdown_He = a_VF / (sq_0 * math.exp((1.0 - b_VF) * ln_0 + (1.0 + b_VF) * ln_1))
    Rup_He = 4.0 * Rdown_He * CR_Tmat_15 * math.exp(-CDB_He / Tmat)
    # single precision: the factor's inverse, so that the ratio below is of terms of order one
    inv_Boltz = math.exp(-min(70.0, Bfact / Tmat))
    Rdown_trip = a_trip / (
        sq_0 * math.exp((1.0 - b_trip) * ln_0 + (1.0 + b_trip) * ln_1)
    )
    Rup_trip = (
        Rdown_trip
        * math.exp(
            -T_HE_2ST_ION / Tmat
        )  # single precision: (k_B T)^2 is below the smallest float32
        * CR_Tmat_15
        * (4.0 / 3.0)
    )

    tauHe_s = A2P_s * CK_He * 3.0 * n_He_1_minus_x_He * iH
    pHe_s = (1.0 - math.exp(-tauHe_s)) / tauHe_s
    Doppler_term = math.sqrt(
        2.0 * const_kB * Tmat / (const_mH * const_mHe_mH * const_c**2)
    )
    # Single precision, second derivatives: the quotient rule applied twice divides by the fourth
    # power of a divisor. K_He's is of order 1e10 and Doppler (1 - x_H) of order 1e-12, and both
    # fourth powers leave float32's range, which turned the helium row of every second-order sweep
    # into NaN through helium recombination. So K_He's divisor is scaled to order one. The
    # continuum terms A / (1 + c gamma^p) with gamma = g / (1 - x_H) are written as
    # A u^p / (u^p + c g^p) for u = 1 - x_H: gamma reaches 1e10 where hydrogen starts to recombine,
    # and its derivatives in x_H times A overflow, while u^p and g^p stay of order one.
    per_doppler = fHe * one_minus_x_He / Doppler_term
    if x_H < 0.9999999:
        # single precision: the constants as one factor (the quotient's parts are 1e25 and 1e21)
        u_s = math.exp(0.86 * math.log(one_minus_x_H))
        AHcon = (
            A2P_s
            * u_s
            / (u_s + 0.36 * math.exp(0.86 * math.log(GAMMA_2PS * per_doppler)))
        )
        K_He = (
            1.0 / ((A2P_s * pHe_s + AHcon) * (3.0e-10 * n_He_1_minus_x_He))
        ) * 1.0e-10
    else:
        K_He = (1.0 / (A2P_s * pHe_s * (3.0e-10 * n_He_1_minus_x_He))) * 1.0e-10

    rate_diff_He = xe * x_He * n_H * Rdown_He - Rup_He * one_minus_x_He * math.exp(
        -CL_He / Tmat
    )
    He_num_term = inv_Boltz + K_He * Lambda_He * n_He_1_minus_x_He
    He_denom_term = inv_Boltz + K_He * (Lambda_He + Rup_He) * n_He_1_minus_x_He
    f1 = rate_diff_He * He_num_term * inv_Hz_z / He_denom_term

    # single precision: the constant as a reciprocal. Enzyme squares a divisor, and (1.2e23)^2
    # overflows: the tangent then came out zero and the Jacobian lost the helium row.
    tauHe_t = A2P_t * n_He_1_minus_x_He * 3.0 * iH * INV_8PI_L_HE_2PT_3
    pHe_t = (1.0 - math.exp(-tauHe_t)) / tauHe_t
    exp_CL_PSt = math.exp(-CL_PSt / Tmat)
    # Single precision: no branch. With the two forms of CfHe_t merged at an if / else, Enzyme's
    # forward pass returned zero for the tangent of everything downstream (the value was right), and
    # the Jacobian lost the helium row. The continuum term is weighted in instead, its neutral
    # hydrogen fraction floored so that it stays finite where it is off.
    with_continuum = 0.0 if x_H > 0.99999 else 1.0
    # the floor is below where the continuum term switches on (1 - x_H = 1e-5)
    u_t = math.exp(0.9 * math.log(max(one_minus_x_H, 1.0e-6)))
    AHcon_t = (
        A2P_t
        * u_t
        / (u_t + 0.66 * math.exp(0.9 * math.log(GAMMA_2PT * per_doppler)))
        / 3.0
    )
    CfHe_t = (A2P_t * pHe_t + with_continuum * AHcon_t) * exp_CL_PSt
    # single precision: both terms underflow to zero below a few hundred kelvin, where the residual
    # x_He hovers at the 1e-8 switch, and 0 / 0 is NaN
    # (a floor of 1e-9: the fourth power of 1e-15 is not a float32, and both terms are of order
    # one or more while the helium fraction still moves)
    CfHe_t = CfHe_t / (Rup_trip + CfHe_t + 1.0e-9)
    trip_rate_diff = (
        xe * x_He * n_H * Rdown_trip
        - one_minus_x_He * 3.0 * Rup_trip * math.exp(-const_h_c_L_He_2St_kB / Tmat)
    )
    f1 = f1 + trip_rate_diff * CfHe_t * inv_Hz_z
    return f1


def peebles_K(Hz, zred):
    """The Peebles ``K`` with the Gaussian fudges of Rubino-Martin et al. (2010)."""

    log_z_term = math.log(1.0 + zred)
    return (
        CK
        * ((1.0 / (Hz * 1.0e13)) * 1.0e13)
        * (
            1.0
            + AGauss1 * math.exp(-(((log_z_term - zGauss1) / wGauss1) ** 2))
            + AGauss2 * math.exp(-(((log_z_term - zGauss2) / wGauss2) ** 2))
        )
    )


def matter_temperature_rate(Tmat, xe, fHe, zred, Hz, T_cmb):
    """RECFAST's matter-temperature equation ``dT_m/dz``, ``T_m`` locked to ``T_rad`` in tight Compton coupling.

    The Hubble time of the switch is the model's own, ``2 / (3 H)``.
    RECFAST estimates it as ``2 / (3 H_0 (1+z)^1.5)``, which needs ``H_0``
    ahead of the solve.
    """

    z_term = 1.0 + zred
    inv_z = 1.0 / z_term
    Trad = T_cmb * z_term
    # single precision: the Compton rate over H, with T^2 / H as one factor. T^4 alone is 3e28 at the
    # start and its second derivative in a, which the sound speed's interpolant takes, 1e43.
    T2 = Trad * Trad
    compton_over_H = (
        CT * T2 * (T2 * ((1.0 / (Hz * 1.0e13)) * 1.0e13)) * xe / (1.0 + xe + fHe)
    )  # timeH / timeTh, up to 1.5
    locked = Tmat * inv_z
    full = compton_over_H * (Tmat - Trad) * inv_z + 2.0 * locked
    w_full = 1.0 if 1.5 >= H_frac * compton_over_H else 0.0  # timeTh >= H_frac timeH
    return w_full * full + (1.0 - w_full) * locked


# The code


def _thermo_initial(a, T_cmb, output):
    """Fully ionized and in Compton equilibrium: ``x_H = 1``, ``x_He = 2``, ``T_m = T_cmb / a``."""

    output[0] = 1.0
    output[1] = 2.0
    output[2] = T_cmb / a


[docs] class RECFAST(Recombination): """RECFAST's ``(x_H, x_He, T_m)`` as the state ``thermo``, whose rates in ``z`` convert with ``dz/dtau = -aH / a``. It provides the three quantities :class:`~discoeb.components.recombination.Recombination` asks of a recombination code: ``xe_rec = x_H + fHe x_He``, ``Tmat`` and its rate ``dTm_dz``, with no spline derivative. """ thermo = State(3, initial=_thermo_initial) def x_H(self, thermo): return min(max(thermo[0], 0.0), 1.0) def x_He(self, thermo): return min(max(thermo[1], 0.0), 2.0) def Tmat(self, thermo): return abs(thermo[2]) def xe_rec(self, x_H, x_He, fHe): """Free electrons per hydrogen nucleus from recombination, without reionization.""" return x_H + fHe * x_He # The rates def K_peebles(self, Hz, zred): return peebles_K(Hz, zred) def dTm_dz(self, Tmat, xe_rec, fHe, zred, Hz, T_cmb): return matter_temperature_rate(Tmat, xe_rec, fHe, zred, Hz, T_cmb) @derivative("thermo") def recfast( self, x_H, x_He, xe_rec, Tmat, zred, a, n_H, Hz, T_cmb, Nnow, fHe, K_peebles, dTm_dz, aH, output, ): inv_a = 1.0 / a dz_dtau = -aH * inv_a output[0] = ( hydrogen_rate(x_H, xe_rec, Tmat, zred, n_H, Hz, T_cmb, Nnow, K_peebles) * dz_dtau ) output[1] = ( helium_rate(x_H, x_He, xe_rec, Tmat, zred, a, n_H, Hz, T_cmb, Nnow, fHe) * dz_dtau ) output[2] = dTm_dz * dz_dtau