sphalde 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sphalde/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """
2
+ SPHALDE: Spherical collapse, halos and LDT density PDF for Dark Energy.
3
+
4
+ Subpackages
5
+ -----------
6
+ sphalde.models dark energy models (EdS, LCDM, wCDM, CPL, NonAbelian)
7
+ sphalde.cosmology flat FLRW background
8
+ sphalde.collapse spherical collapse, backscaling, linear P(k), LDT PDF
9
+ sphalde.mass_function Press-Schechter and Sheth-Tormen mass functions, cluster counts
10
+ sphalde.pipeline driver of the full calculation (the `sphalde` command)
11
+ """
12
+ __version__ = "1.1.0"
13
+
14
+ from sphalde.models import get_model, ALL_MODELS
15
+ from sphalde.cosmology import FlatFLRW
16
+
17
+ __all__ = ["__version__", "get_model", "ALL_MODELS", "FlatFLRW"]
@@ -0,0 +1,54 @@
1
+ """
2
+ Nonlinear spherical collapse, backscaling and the LDT density PDF.
3
+
4
+ classy (CLASS) is optional: class_pk imports without it and fails only if
5
+ CLASS is actually used.
6
+ """
7
+ from sphalde.collapse.equations import odes_linear, odes_nonlinear
8
+ from sphalde.collapse.solver import (
9
+ SphericalCollapseSolver,
10
+ BackscalingSolver,
11
+ find_delta_ini,
12
+ solve_tau,
13
+ THRESHOLD,
14
+ with_radiation,
15
+ get_numerics,
16
+ set_numerics,
17
+ )
18
+ from sphalde.collapse.variance import W_tophat, sigma2_L_batch, sigma_L
19
+ from sphalde.collapse.esscher import (
20
+ P_tilde_tab, solve_c_tab, P_final_tab, solve_scale_tab, P_rescaled_tab,
21
+ moments_check, var_ln_rho_tab, calibrate_s2_tab,
22
+ )
23
+ from sphalde.collapse.power_spectrum import LinearPowerSpectrum, growth_spline
24
+ from sphalde.collapse.pdf_ldt_analytic import (
25
+ build_sigma2L_loglog_spline,
26
+ build_tau_mu_interp,
27
+ compute_Psi_analytic,
28
+ P_tilde_analytic,
29
+ prepare_epoch_setup,
30
+ pdf_at_R,
31
+ assemble_pipeline,
32
+ default_tau_grid,
33
+ default_rho_grid,
34
+ lognormal_pdf,
35
+ lognormal_test,
36
+ )
37
+ from sphalde.collapse.class_pk import class_params, init_class, get_pk_lcdm
38
+
39
+ __all__ = [
40
+ "odes_linear", "odes_nonlinear",
41
+ "SphericalCollapseSolver", "BackscalingSolver",
42
+ "find_delta_ini", "solve_tau", "THRESHOLD", "with_radiation",
43
+ "get_numerics", "set_numerics",
44
+ "W_tophat", "sigma2_L_batch", "sigma_L",
45
+ "P_tilde_tab", "solve_c_tab", "P_final_tab", "solve_scale_tab", "P_rescaled_tab",
46
+ "moments_check", "var_ln_rho_tab", "calibrate_s2_tab",
47
+ "LinearPowerSpectrum", "growth_spline",
48
+ "build_sigma2L_loglog_spline", "build_tau_mu_interp",
49
+ "compute_Psi_analytic", "P_tilde_analytic",
50
+ "prepare_epoch_setup", "pdf_at_R", "assemble_pipeline",
51
+ "default_tau_grid", "default_rho_grid",
52
+ "lognormal_pdf", "lognormal_test",
53
+ "class_params", "init_class", "get_pk_lcdm",
54
+ ]
@@ -0,0 +1,82 @@
1
+ """
2
+ sphalde/collapse/class_pk.py
3
+ ----------------------------
4
+ Linear matter power spectrum of the reference LambdaCDM cosmology from the
5
+ Boltzmann code CLASS (Python wrapper classy, optional dependency).
6
+
7
+ SPHALDE uses CLASS only for P_L(k, z_i) of the reference cosmology; the
8
+ spectrum of each model is then obtained by rescaling with its own growth
9
+ factor (power_spectrum.LinearPowerSpectrum, Eq. PL_rescaling of the paper).
10
+ """
11
+ import numpy as np
12
+
13
+ try:
14
+ from classy import Class
15
+ except ImportError:
16
+ Class = None # the module imports without classy; it fails only if CLASS is used
17
+
18
+
19
+ def class_params(H0, Om_m, Om_b, n_s, sigma8, z_max_pk, N_ur=3.046, k_max=20.0):
20
+ """
21
+ CLASS input parameters for a flat LambdaCDM reference cosmology with
22
+ massless neutrinos, normalized to sigma8 at z = 0.
23
+
24
+ H0 in km/s/Mpc; k_max in h/Mpc; z_max_pk is the highest redshift at
25
+ which P(k) will be requested (the initial redshift z_i).
26
+ """
27
+ return {
28
+ "H0": H0,
29
+ "Omega_b": Om_b,
30
+ "Omega_cdm": Om_m - Om_b,
31
+ "n_s": n_s,
32
+ "sigma8": sigma8,
33
+ "N_ur": N_ur,
34
+ "N_ncdm": 0,
35
+ "output": "mPk",
36
+ "P_k_max_h/Mpc": k_max,
37
+ "z_max_pk": z_max_pk,
38
+ }
39
+
40
+
41
+ def init_class(params, verbose=True):
42
+ """
43
+ Run CLASS with the given parameters and return the computed instance.
44
+
45
+ Call cosmo.struct_cleanup() when it is no longer needed, to free the
46
+ memory held by CLASS, in particular when several instances are created
47
+ in the same process.
48
+ """
49
+ if Class is None:
50
+ raise ImportError("classy (CLASS) is not installed in this environment.")
51
+
52
+ cosmo = Class()
53
+ cosmo.set(params)
54
+ cosmo.compute()
55
+
56
+ if verbose:
57
+ Omega_m = cosmo.Omega_b() + cosmo.Omega0_cdm()
58
+ print(f"CLASS: h = {cosmo.h():.4f}, sigma8 = {cosmo.sigma8():.5f}, "
59
+ f"Omega_m = {Omega_m:.4f}, Omega_Lambda = {cosmo.Omega_Lambda():.4f}, "
60
+ f"Omega_r = {cosmo.Omega_r():.3e}")
61
+ return cosmo
62
+
63
+
64
+ def get_pk_lcdm(cosmo, k_arr, z, h_val):
65
+ """
66
+ P(k, z) from CLASS in (Mpc/h)^3, for k_arr in h/Mpc.
67
+
68
+ Uses the vectorized cosmo.get_pk_array when the installed classy provides
69
+ it, and otherwise falls back to one call of cosmo.pk() per wavenumber.
70
+ """
71
+ k_phys = np.asarray(k_arr, dtype=float) * h_val # 1/Mpc, the units of CLASS
72
+
73
+ if hasattr(cosmo, "get_pk_array"):
74
+ z_arr = np.array([z], dtype=float)
75
+ pk_flat = cosmo.get_pk_array(k_phys, z_arr, len(k_phys), len(z_arr), 0)
76
+ Pk_z = np.asarray(pk_flat).reshape(len(z_arr), len(k_phys))[0] * h_val**3
77
+ else:
78
+ Pk_z = np.array([cosmo.pk(k, z) for k in k_phys]) * h_val**3
79
+ return Pk_z
80
+
81
+
82
+ __all__ = ["class_params", "init_class", "get_pk_lcdm"]
@@ -0,0 +1,35 @@
1
+ """
2
+ sphalde/collapse/equations.py
3
+ -----------------------------
4
+ Spherical-collapse equations in x = ln a (the number of e-folds N in the paper).
5
+
6
+ Nonlinear equation:
7
+ delta'' = -(1/2)[1 - Om_r - 3 w Om_DE] delta' + (4/3) delta'^2/(1+delta)
8
+ + (3/2) Om_m (1+delta) delta
9
+
10
+ Linear equation:
11
+ delta'' = -(1/2)[1 - Om_r - 3 w Om_DE] delta' + (3/2) Om_m delta
12
+
13
+ The friction term uses 2 + E'/E = (1/2)[1 - Om_r - 3 w Om_DE], so no
14
+ derivative of E(a) is taken numerically.
15
+ """
16
+ from sphalde.cosmology.background import FlatFLRW
17
+
18
+
19
+ def odes_nonlinear(x: float, y: list, cosmo: FlatFLRW) -> list:
20
+ """Right-hand side of the nonlinear equation. State: y = [delta_NL, delta_NL']."""
21
+ delta, dp = y
22
+ _, eos, OmegaM, OmegaR, OmegaDE, _ = cosmo.cosmologic_quantities(x)
23
+ dpp = (-0.5*(1.0 - OmegaR - 3.0*eos*OmegaDE)*dp
24
+ + (4.0/3.0)*dp**2/(1.0 + delta)
25
+ + 1.5*OmegaM*(1.0 + delta)*delta)
26
+ return [dp, dpp]
27
+
28
+
29
+ def odes_linear(x: float, y: list, cosmo: FlatFLRW) -> list:
30
+ """Right-hand side of the linear equation. State: y = [delta_L, delta_L']."""
31
+ delta, dp = y
32
+ _, eos, OmegaM, OmegaR, OmegaDE, _ = cosmo.cosmologic_quantities(x)
33
+ dpp = (-0.5*(1.0 - OmegaR - 3.0*eos*OmegaDE)*dp
34
+ + 1.5*OmegaM*delta)
35
+ return [dp, dpp]
@@ -0,0 +1,142 @@
1
+ """
2
+ sphalde/collapse/esscher.py
3
+ ---------------------------
4
+ Normalization of the saddle-point density PDF.
5
+
6
+ Two prescriptions impose int P = <rho> = 1 on the raw PDF P~_R:
7
+
8
+ * "rescale" (default; Uhlemann et al. 2016, pyLDT-cosmo):
9
+ P_R(rho) = P~_R(rho s) s / N, N = int P~, s = int rho P~ / N
10
+ (solve_scale_tab, P_rescaled_tab)
11
+
12
+ * "esscher": exponential tilt
13
+
14
+ P~_R(rho) = sqrt[(Psi'' + Psi'/rho) / (2 pi s2)] exp(-Psi / s2)
15
+ P_R(rho) = exp(-c rho) P~_R(rho) / Z(c)
16
+ Z(c) = int d rho exp(-c rho) P~_R(rho)
17
+ F(c) = <rho>_c - 1 = 0 -> c_*
18
+ F'(c) = -Var_c(rho) < 0 -> unique root
19
+
20
+ Integrals use the trapezoidal rule on the tabulated rho grid; the tilt is
21
+ found with Brent's method (tolerances 1e-12).
22
+
23
+ `table` is the dict returned by pdf_ldt_analytic.compute_Psi_analytic
24
+ (keys "rho", "Psi", "sqrt_arg"); s2 is the width parameter, equal to
25
+ sigma_L^2(R, z) unless it is calibrated externally (calibrate_s2_tab).
26
+ """
27
+ import numpy as np
28
+ from scipy.optimize import brentq
29
+
30
+ _trapezoid = getattr(np, "trapezoid", None) or np.trapz
31
+
32
+
33
+ def P_tilde_tab(table, s2):
34
+ """Raw saddle-point PDF P~_R(rho) on table['rho']."""
35
+ prefactor = np.sqrt(table["sqrt_arg"] / (2.0 * np.pi * s2))
36
+ exponential = np.exp(-table["Psi"] / s2)
37
+ return prefactor * exponential
38
+
39
+
40
+ def _weights(c, table, s2):
41
+ rho = table["rho"]
42
+ return rho, np.exp(-c * rho) * P_tilde_tab(table, s2)
43
+
44
+
45
+ def F_tab(c, table, s2):
46
+ """F(c) = <rho>_c - 1."""
47
+ rho, w = _weights(c, table, s2)
48
+ return _trapezoid(rho * w, rho) / _trapezoid(w, rho) - 1.0
49
+
50
+
51
+ def F_prime_tab(c, table, s2):
52
+ """F'(c) = -Var_c(rho)."""
53
+ rho, w = _weights(c, table, s2)
54
+ Z = _trapezoid(w, rho)
55
+ m1 = _trapezoid(rho * w, rho) / Z
56
+ m2 = _trapezoid(rho**2 * w, rho) / Z
57
+ return -(m2 - m1**2)
58
+
59
+
60
+ def find_bracket_c(table, s2, lo0=-1.0, hi0=1.0, factor=2.0, max_iter=60):
61
+ """Widen [lo, hi] until F changes sign (F is monotonic)."""
62
+ lo, hi = lo0, hi0
63
+ for _ in range(max_iter):
64
+ if F_tab(lo, table, s2) * F_tab(hi, table, s2) < 0:
65
+ return lo, hi
66
+ lo *= factor
67
+ hi *= factor
68
+ raise RuntimeError("No bracket found for the tilt parameter c")
69
+
70
+
71
+ def solve_c_tab(table, s2, c_bracket=None):
72
+ """Tilt parameter c_* with <rho>_c = 1 (Brent, tol 1e-12)."""
73
+ lo, hi = c_bracket if c_bracket is not None else find_bracket_c(table, s2)
74
+ return brentq(lambda c: F_tab(c, table, s2), lo, hi, xtol=1e-12, rtol=1e-12)
75
+
76
+
77
+ def P_final_tab(table, c, s2):
78
+ """Tilted PDF P_R(rho), normalised and with <rho> = 1."""
79
+ rho, w = _weights(c, table, s2)
80
+ return w / _trapezoid(w, rho)
81
+
82
+
83
+ def var_ln_rho_tab(table, c, s2):
84
+ """Var(ln rho) of the tilted PDF."""
85
+ rho = table["rho"]
86
+ P = P_final_tab(table, c, s2)
87
+ m1 = _trapezoid(np.log(rho) * P, rho)
88
+ m2 = _trapezoid(np.log(rho)**2 * P, rho)
89
+ return m2 - m1**2
90
+
91
+
92
+ def calibrate_s2_tab(table, var_target, s2_bracket=(1e-4, 5.0)):
93
+ """
94
+ Optional external calibration: s2 such that the tilted PDF reproduces
95
+ a measured Var(ln rho). Returns (s2_*, c_*).
96
+ """
97
+ def G(s2):
98
+ return var_ln_rho_tab(table, solve_c_tab(table, s2), s2) - var_target
99
+ lo, hi = s2_bracket
100
+ if G(lo) * G(hi) > 0:
101
+ raise RuntimeError(f"No sign change of G in s2_bracket {s2_bracket}")
102
+ s2_star = brentq(G, lo, hi, xtol=1e-10, rtol=1e-10)
103
+ return s2_star, solve_c_tab(table, s2_star)
104
+
105
+
106
+ def moments_check(rho, P):
107
+ """(int P drho, <rho>) on a tabulated PDF."""
108
+ return _trapezoid(P, rho), _trapezoid(rho * P, rho)
109
+
110
+
111
+ __all__ = ["P_tilde_tab", "F_tab", "F_prime_tab", "find_bracket_c",
112
+ "solve_c_tab", "P_final_tab", "var_ln_rho_tab",
113
+ "calibrate_s2_tab", "moments_check"]
114
+
115
+
116
+ # ------------------------------------------------------------------
117
+ # Rescaling normalization (Uhlemann et al. 2016; pyLDT-cosmo)
118
+ # ------------------------------------------------------------------
119
+ def solve_scale_tab(table, s2):
120
+ """Scale s = <rho>/N of the raw PDF; s = 1 when P~ already has <rho> = 1."""
121
+ rho = table["rho"]
122
+ Pt = P_tilde_tab(table, s2)
123
+ N = _trapezoid(Pt, rho)
124
+ M = _trapezoid(rho * Pt, rho)
125
+ return M / N, N
126
+
127
+
128
+ def P_rescaled_tab(table, s2, scale=None, N=None):
129
+ """
130
+ P_R(rho) = P~_R(rho * s) * s / N on table['rho'].
131
+
132
+ P~ is interpolated in (ln rho, ln P~); outside the tabulated range it is
133
+ set to zero. Then int P = 1 and <rho> = 1 up to the tail beyond the grid.
134
+ """
135
+ rho = table["rho"]
136
+ Pt = P_tilde_tab(table, s2)
137
+ if scale is None or N is None:
138
+ scale, N = solve_scale_tab(table, s2)
139
+ lnP = np.log(np.clip(Pt, 1e-300, None))
140
+ x = np.log(rho * scale)
141
+ P = np.exp(np.interp(x, np.log(rho), lnP, left=-np.inf, right=-np.inf))
142
+ return P * scale / N