disco-cmb 0.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.
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: disco-cmb
3
+ Version: 0.1.0
4
+ Summary: CMB angular power spectra on the GPU from DISCO-EB's Einstein-Boltzmann solve
5
+ Author-email: Lawrence Berry <lawrenceberry@outlook.com>, Oliver Hahn <oliver.hahn@univie.ac.at>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://cosmo-sims.github.io/DISCO-CMB/
8
+ Project-URL: Source, https://github.com/cosmo-sims/DISCO-CMB
9
+ Project-URL: Issues, https://github.com/cosmo-sims/DISCO-CMB/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: GPU :: NVIDIA CUDA
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
19
+ Classifier: Topic :: Scientific/Engineering :: Physics
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: disco-eb>=2.0.0
24
+ Requires-Dist: numpy
25
+ Requires-Dist: scipy
26
+ Provides-Extra: cuda12
27
+ Requires-Dist: disco-eb[cuda12]>=2.0.0; extra == "cuda12"
28
+ Provides-Extra: cuda13
29
+ Requires-Dist: disco-eb[cuda13]>=2.0.0; extra == "cuda13"
30
+ Dynamic: license-file
31
+
32
+ <h1 align="center">DISCO-CMB</h1>
33
+
34
+ <!--
35
+ The coverage badge reads a gist that the `tests` workflow rewrites on every
36
+ push to main; the id below is the repository variable COVERAGE_GIST_ID.
37
+ These badges sit above the `overview` snippet marker, so the documentation
38
+ site does not repeat them.
39
+ -->
40
+ <p align="center">
41
+ <a href="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/tests.yml"><img alt="tests" src="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/tests.yml/badge.svg?branch=main"></a>
42
+ <a href="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/tests.yml"><img alt="coverage" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgist.githubusercontent.com%2Flawrenceberry%2Fb451e14a9620fabb0d49c345f13b5414%2Fraw%2Fdiscocmb-coverage.json"></a>
43
+ <a href="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/lint.yml"><img alt="lint" src="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/lint.yml/badge.svg?branch=main"></a>
44
+ <a href="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/types.yml"><img alt="types" src="https://github.com/cosmo-sims/DISCO-CMB/actions/workflows/types.yml/badge.svg?branch=main"></a>
45
+ <a href="https://pypi.org/project/disco-cmb/"><img alt="PyPI" src="https://img.shields.io/pypi/v/disco-cmb"></a>
46
+ <a href="https://pypi.org/project/disco-cmb/"><img alt="Downloads" src="https://img.shields.io/pypi/dm/disco-cmb"></a>
47
+ <a href="https://pypi.org/project/disco-cmb/"><img alt="Python" src="https://img.shields.io/pypi/pyversions/disco-cmb"></a>
48
+ <a href="https://docs.jax.dev/"><img alt="JAX" src="https://img.shields.io/badge/JAX-compatible-3f51b5"></a>
49
+ <a href="https://arxiv.org/abs/2311.03291"><img alt="arXiv" src="https://img.shields.io/badge/arXiv-2311.03291-b31b1b.svg"></a>
50
+ <a href="https://www.conventionalcommits.org/en/v1.0.0/"><img alt="Conventional Commits" src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white"></a>
51
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
52
+ </p>
53
+
54
+ <p align="center">
55
+ <a href="#installation">Installation</a> •
56
+ <a href="#quickstart">Quickstart</a> •
57
+ <a href="https://cosmo-sims.github.io/DISCO-CMB/">Documentation</a> •
58
+ <a href="https://arxiv.org/abs/2311.03291">DISCO-EB paper</a> •
59
+ <a href="#citation">Citation</a>
60
+ </p>
61
+
62
+ <!-- start:overview -->
63
+
64
+ DISCO-CMB computes CMB angular power spectra for **batches of cosmologies on the GPU**. It builds on the Einstein-Boltzmann solver of [DISCO-EB](https://github.com/cosmo-sims/DISCO-EB) and adds line-of-sight integration, the unlensed TT, TE and EE spectra, the lensing potential and the lensed TT, TE, EE and BB spectra.
65
+
66
+ A single GPU launch evolves every wave mode of every cosmology in a batch, with the line-of-sight sources evaluated inside the solver's kernel. The unlensed TT spectrum agrees with CLASS to 0.25 percent for multipoles 2 to 1200, and JAX can differentiate the spectra with respect to the cosmological parameters.
67
+
68
+ <!-- end:overview -->
69
+
70
+ The [documentation](https://cosmo-sims.github.io/DISCO-CMB/) covers the API
71
+ and explains how the pipeline fits together.
72
+
73
+ ## Installation
74
+
75
+ <!-- start:install -->
76
+
77
+ DISCO-CMB needs an NVIDIA GPU. Install it from PyPI, which brings DISCO-EB with it:
78
+
79
+ ```bash
80
+ pip install "disco-cmb[cuda13]" # or [cuda12], which Python 3.10 needs
81
+ ```
82
+
83
+ <!-- end:install -->
84
+
85
+ ## Quickstart
86
+
87
+ <!-- start:quickstart -->
88
+
89
+ This example computes the unlensed spectra of three cosmologies that differ in their spectral index. The grids come from a fiducial cosmology once, and every later batch reuses them:
90
+
91
+ ```python
92
+ from discocmb import cmb_grids, compute_cl_power_spectrum_batch
93
+
94
+ planck = {
95
+ "Omegam": 0.3144,
96
+ "Omegab": 0.04939,
97
+ "H0": 67.32,
98
+ "Omegak": 0.0,
99
+ "A_s": 2.1e-9,
100
+ "n_s": 0.966,
101
+ "k_p": 0.05,
102
+ "Tcmb": 2.7255,
103
+ "YHe": 0.2454,
104
+ "Neff": 3.046,
105
+ "Nmnu": 0.0,
106
+ "mnu": 0.0,
107
+ "w_DE_0": -1.0,
108
+ "w_DE_a": 0.0,
109
+ "cs2_DE": 1.0,
110
+ }
111
+ batch = [planck | {"n_s": n_s} for n_s in (0.95, 0.966, 0.98)]
112
+
113
+ grids = cmb_grids(planck)
114
+ ells, cl, dl = compute_cl_power_spectrum_batch(batch, grids=grids)
115
+ dl.tt # (3, n_ell) in muK^2
116
+ ```
117
+
118
+ <!-- end:quickstart -->
119
+
120
+ ## Development
121
+
122
+ <!-- start:development -->
123
+
124
+ The repository uses [uv](https://docs.astral.sh/uv/):
125
+
126
+ ```bash
127
+ git clone https://github.com/cosmo-sims/DISCO-CMB.git
128
+ cd DISCO-CMB && uv sync --extra cuda13 # or --extra cuda12
129
+ uv run pytest tests # needs a CUDA GPU
130
+ uv run ruff format && uv run ruff check --fix
131
+ uv run ty check
132
+ uv run pre-commit install # the checks above, and a commit-message check
133
+ ```
134
+
135
+ The documentation (Sphinx with MyST and autodoc) builds in an environment of its own, the package plus the docs group:
136
+
137
+ ```bash
138
+ export UV_PROJECT_ENVIRONMENT=.venv-docs
139
+ uv sync --no-default-groups --group docs
140
+ uv run --no-sync sphinx-autobuild docs docs/_build/html # live preview
141
+ uv run --no-sync sphinx-build -W docs docs/_build/html # what CI runs
142
+ ```
143
+
144
+ <!-- end:development -->
145
+
146
+ ## Citation
147
+
148
+ <!-- start:citation -->
149
+
150
+ If you use DISCO-CMB in your research, please cite this repository (see
151
+ [CITATION.cff](https://github.com/cosmo-sims/DISCO-CMB/blob/main/CITATION.cff))
152
+ and the DISCO-EB article it builds on:
153
+
154
+ ```bibtex
155
+ @article{DISCO-EB:2024,
156
+ author = "Hahn, Oliver and List, Florian and Porqueres, Natalia",
157
+ title = "{DISCO-DJ I: a differentiable Einstein-Boltzmann solver for cosmology}",
158
+ eprint = "2311.03291",
159
+ archivePrefix = "arXiv",
160
+ primaryClass = "astro-ph.CO",
161
+ doi = "10.1088/1475-7516/2024/06/063",
162
+ journal = "JCAP",
163
+ volume = "06",
164
+ pages = "063",
165
+ year = "2024"
166
+ }
167
+ ```
168
+
169
+ <!-- end:citation -->
170
+
171
+ ## License
172
+
173
+ <!-- start:license -->
174
+
175
+ DISCO-CMB is released under the
176
+ [MIT License](https://github.com/cosmo-sims/DISCO-CMB/blob/main/LICENSE).
177
+
178
+ <!-- end:license -->
@@ -0,0 +1,12 @@
1
+ disco_cmb-0.1.0.dist-info/licenses/LICENSE,sha256=ydAPykNk9HUJblRKROxcRjV6bCAUdiRJV-CHAWvHIs0,1087
2
+ discocmb/__init__.py,sha256=4bE17H_os14ZDjb_xr8elBV-RjIH_2UqYmathG9sUmk,1203
3
+ discocmb/grids.py,sha256=nq4zPjCGL38BnHlcvGRlOhHvSzzpZEKIcwFJhiu_p4U,13731
4
+ discocmb/lensing.py,sha256=1SAlPkLLNGpkVnWpsqsOJTBoDdvPuwXjKPv58MAlGVo,18806
5
+ discocmb/main.py,sha256=Idycci1N9jUDh7SRAQnkL-uCq7NDAa_67hPApIcfeKs,12073
6
+ discocmb/sources.py,sha256=7_J6Nfjv25vzvQ_y4watngfDmCw6CzFMwxqFTYAHCWg,14778
7
+ discocmb/spectra.py,sha256=Afm2XDrS9ACg0rklVAx1lMXMD7mvLImSCobMiUPWhTw,3316
8
+ discocmb/transfer.py,sha256=VAVY3ZTePk9IGbLrwJ9JiC_Qok6D2MjNKnwKwH9XW1g,17192
9
+ disco_cmb-0.1.0.dist-info/METADATA,sha256=ZnYSTA3e4LSye2bP7HtfzLc7Ry62b5nNGvWWGqEBzOM,7174
10
+ disco_cmb-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ disco_cmb-0.1.0.dist-info/top_level.txt,sha256=xe6CdL2XvqVJbPU4HqtmTsCcOn4RVcfQjuGm073-6cE,9
12
+ disco_cmb-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lawrence Berry and Oliver Hahn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ discocmb
discocmb/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """DISCO-CMB: CMB angular power spectra from DISCO-EB's Einstein-Boltzmann solve.
2
+
3
+ The computation runs in four steps, one module each, brought together by
4
+ :mod:`discocmb.main`:
5
+
6
+ 1. :mod:`discocmb.sources` -- the line-of-sight source functions, a component
7
+ DISCO-EB's kernel evaluates at every save time;
8
+ 2. :mod:`discocmb.transfer` -- line-of-sight integration into the temperature
9
+ and E-mode transfer functions;
10
+ 3. :mod:`discocmb.spectra` -- the unlensed TT, TE and EE power spectra;
11
+ 4. :mod:`discocmb.lensing` -- the lensing potential and the lensed spectra.
12
+
13
+ :mod:`discocmb.grids` builds the grids every step shares. DISCO-EB is called
14
+ through its interface :mod:`discoeb` only.
15
+ """
16
+
17
+ from .grids import CMBGrids, cmb_grids, cmb_k_grid
18
+ from .lensing import cl_on_every_ell, lensed_spectra, lensing_tables
19
+ from .main import (
20
+ cl_power_spectrum_jax,
21
+ compute_cl_power_spectrum_batch,
22
+ compute_transfer_batch,
23
+ )
24
+ from .spectra import Spectra
25
+
26
+ __all__ = [
27
+ "CMBGrids",
28
+ "Spectra",
29
+ "cl_on_every_ell",
30
+ "cl_power_spectrum_jax",
31
+ "cmb_grids",
32
+ "cmb_k_grid",
33
+ "compute_cl_power_spectrum_batch",
34
+ "compute_transfer_batch",
35
+ "lensed_spectra",
36
+ "lensing_tables",
37
+ ]
discocmb/grids.py ADDED
@@ -0,0 +1,346 @@
1
+ """The grids of a CMB computation, shaped by a fiducial cosmology.
2
+
3
+ The sources have structure at recombination and on the sound-horizon scale in
4
+ ``tau``, and at the acoustic scale and the Silk damping scale in ``k``; the
5
+ grids here are dense where that structure is (:func:`cmb_tau_grid`,
6
+ :func:`cmb_k_grid`). The characteristic scales come from one trajectory of
7
+ the source kernel itself (:func:`_kernel_thermal_history`), so building them
8
+ compiles nothing new. :func:`cmb_grids` bundles them into :class:`CMBGrids`,
9
+ built once and shared by every batch of an inference loop.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ from typing import NamedTuple
16
+
17
+ import discoeb as eb
18
+ import numpy as np
19
+ from discoeb import TAU_START
20
+ from scipy import integrate
21
+
22
+ from .sources import solve_sources, visibility_on_grid
23
+
24
+ SUMMARY_GRID = 2048
25
+ """Points of the uniform ``log tau`` grid the grid summary reads the opacity on."""
26
+
27
+ DEFAULT_CMB_ELLS = np.unique(
28
+ np.concatenate(
29
+ [np.arange(2, 40, 2), np.arange(40, 200, 5), np.arange(200, 2501, 50)]
30
+ )
31
+ ).astype(np.int64)
32
+ """Default multipoles at which ``C_l`` is evaluated."""
33
+
34
+
35
+ Z_REION_SEARCH_MAX = 30.0
36
+ """Redshift below which a reionization visibility bump would be located."""
37
+
38
+
39
+ TAU_END_MARGIN = 0.01
40
+ """How far past the fiducial cosmology's ``tau0`` the save grid of :func:`cmb_grids`
41
+ extends, as a fraction, so that the grids built once from a fiducial serve every
42
+ batch whose conformal ages fall within it. Measured against per-batch grids on
43
+ the 128 nearby cosmologies of the tests, the shift onto the fiducial's grid
44
+ moves ``D_l`` by at most 2.7e-4 at 1 percent, 1.0e-3 at 2 percent and 4.4e-3
45
+ at 5 percent (the low multipoles' late-time sources sit on the coarse end of
46
+ the grid)."""
47
+
48
+
49
+ def _grhoa4(a, grhog, grhor, grhoc, grhob, grhov):
50
+ """``8 pi G rho a^4``: the expansion rate is ``a' = sqrt(grhoa4 / 3)``."""
51
+
52
+ return grhog + grhor + (grhoc + grhob) * a + grhov * a**4
53
+
54
+
55
+ def _dtau_da(a, *dens):
56
+ """``dtau/da = 1 / a'``."""
57
+
58
+ return np.sqrt(3.0 / _grhoa4(a, *dens))
59
+
60
+
61
+ SUMMARY_K = 1.0e-3
62
+ """Wave mode (Mpc^-1) of the one trajectory whose recombination block the grid summary reads."""
63
+
64
+
65
+ @functools.lru_cache(maxsize=64)
66
+ def _kernel_thermal_history(cosmology, n_grid: int = SUMMARY_GRID, n_save: int = 1000):
67
+ """``(tau_grid, a, opacity, tau0)`` of one cosmology on ``n_grid`` uniform ``log tau`` points, from the sources' own solve.
68
+
69
+ One trajectory of :func:`~discocmb.sources.solve_sources` (the kernel the spectra use, so
70
+ nothing more is compiled) records the opacity ``kappa'``, with
71
+ reionization, from its recombination block's dense output; the scale
72
+ factor is the background quadrature's. The kernel's save grid has
73
+ ``n_save`` times, part of its identity, and every launch records the
74
+ start, ``TAU_START``, so the grid is read in launches of ``n_save - 1``
75
+ points.
76
+ """
77
+
78
+ a_bg, tau_bg = eb.background_history(cosmology)
79
+ tau0 = float(tau_bg[-1])
80
+ tau_grid = np.exp(np.linspace(np.log(TAU_START), np.log(tau0), n_grid))
81
+ opacity = np.empty(n_grid)
82
+ for c0 in range(0, n_grid, n_save - 1):
83
+ chunk = tau_grid[c0 : c0 + n_save - 1]
84
+ times = np.full(n_save, tau_grid[-1])
85
+ times[0] = TAU_START
86
+ times[1 : 1 + len(chunk)] = chunk
87
+ # equal times past the chunk are not strictly increasing: nudge them
88
+ times[1 + len(chunk) :] += np.arange(1, n_save - len(chunk)) * 1.0e-6
89
+ solution = solve_sources((cosmology,), np.asarray([SUMMARY_K]), times)
90
+ channels = np.asarray(solution.values[0, :, 0, :]) # (6, n_save)
91
+ opacity[c0 : c0 + len(chunk)] = channels[4, 1 : 1 + len(chunk)]
92
+ return tau_grid, np.interp(tau_grid, tau_bg, a_bg), opacity, tau0
93
+
94
+
95
+ def _cmb_grid_summary(cosmology) -> dict[str, float]:
96
+ return _grid_summary(eb.as_cosmology(cosmology))
97
+
98
+
99
+ @functools.lru_cache(maxsize=4096)
100
+ def _grid_summary(cosmology) -> dict[str, float]:
101
+ """Return the characteristic scales that set the adaptive ``k`` / ``tau`` grids.
102
+
103
+ ``tau_star`` is the visibility peak and ``delta_tau_rec`` its Gaussian
104
+ equivalent width; ``r_s`` is the sound horizon at recombination (which sets
105
+ the acoustic oscillation period in ``k``) and ``k_D`` the Silk damping
106
+ wavenumber (which sets their envelope). Together they say where the CMB
107
+ sources have structure, and hence where the grids must be dense.
108
+ """
109
+
110
+ dens = eb.density_coefficients(cosmology)
111
+ tau_grid, a_vals, opacity, tau0 = _kernel_thermal_history(cosmology)
112
+
113
+ _, vis, _ = visibility_on_grid(tau_grid, opacity, tau_grid, float(tau0))
114
+ peak = int(np.argmax(vis))
115
+ tau_star = float(tau_grid[peak])
116
+ a_star = float(a_vals[peak])
117
+
118
+ half = 0.5 * float(vis[peak])
119
+ left = float(np.interp(half, vis[: peak + 1], tau_grid[: peak + 1]))
120
+ right = float(np.interp(half, vis[peak:][::-1], tau_grid[peak:][::-1]))
121
+ delta_tau_rec = max((right - left) / (2.0 * np.sqrt(2.0 * np.log(2.0))), 1.0)
122
+
123
+ grhog_v, grhor_v, grhoc_v, grhob_v, _ = dens
124
+ tau_eq = float(
125
+ np.interp((grhog_v + grhor_v) / (grhoc_v + grhob_v), a_vals, tau_grid)
126
+ )
127
+
128
+ # Comoving sound horizon r_s = int c_s dtau = int_0^{a_star} da / (a' sqrt(3(1+R))),
129
+ # with a' = sqrt(grhoa4/3) and R = 3 rho_b / (4 rho_g).
130
+ def sound_integrand(ap):
131
+ r = 0.75 * grhob_v * ap / grhog_v
132
+ return 1.0 / np.sqrt(_grhoa4(ap, *dens) * (1.0 + r))
133
+
134
+ r_s = float(integrate.quad(sound_integrand, 0.0, a_star, limit=200)[0])
135
+
136
+ # Silk damping scale from the photon diffusion length.
137
+ a_silk = np.linspace(max(float(a_vals[0]), 1.0e-8), a_star, 5000)
138
+ opacity_silk = np.maximum(np.interp(a_silk, a_vals, opacity), 1.0e-30)
139
+ r = 0.75 * grhob_v * a_silk / grhog_v
140
+ integrand_d = (
141
+ (r**2 + 16.0 * (1.0 + r) / 15.0)
142
+ / (6.0 * (1.0 + r) ** 2 * opacity_silk)
143
+ * _dtau_da(a_silk, *dens)
144
+ )
145
+ k_D = float(1.0 / np.sqrt(np.trapezoid(integrand_d, a_silk)))
146
+
147
+ # The secondary visibility bump from reionization when tau_reio > 0; without
148
+ # one, the save grid's late-time weight falls back to a broad bump.
149
+ post_rec = a_vals > 1.0 / (1.0 + Z_REION_SEARCH_MAX)
150
+ if np.any(post_rec) and np.max(np.where(post_rec, vis, 0.0)) > 1.0e-3 * vis[peak]:
151
+ reion_idx = int(np.argmax(np.where(post_rec, vis, 0.0)))
152
+ tau_reion = float(tau_grid[reion_idx])
153
+ delta_tau_reion = max(0.03 * tau0, 80.0)
154
+ else:
155
+ tau_reion = 0.6 * tau0
156
+ delta_tau_reion = 0.05 * tau0
157
+
158
+ out = {
159
+ "tau0": float(tau0),
160
+ "tau_eq": tau_eq,
161
+ "tau_star": tau_star,
162
+ "delta_tau_rec": delta_tau_rec,
163
+ "tau_reion": tau_reion,
164
+ "delta_tau_reion": delta_tau_reion,
165
+ "r_s": r_s,
166
+ "k_D": k_D,
167
+ }
168
+ return out
169
+
170
+
171
+ def _resample_from_density(x, density, n):
172
+ """Return ``n`` points drawn from ``x`` in proportion to ``density``."""
173
+
174
+ cdf = np.cumsum(density) * (x[1] - x[0])
175
+ cdf -= cdf[0]
176
+ cdf /= cdf[-1]
177
+ return np.interp(np.linspace(0.0, 1.0, n), cdf, x)
178
+
179
+
180
+ def cmb_k_grid(
181
+ cosmology,
182
+ *,
183
+ n: int = 200,
184
+ mode: str = "ode",
185
+ k_min: float = 1.0e-5,
186
+ k_max: float = 0.5,
187
+ ell_min: int = 2,
188
+ ell_max: int = 2500,
189
+ n_ell_samples: int = 30,
190
+ n_eval: int = 5000,
191
+ ) -> np.ndarray:
192
+ """Return a nonuniform wavenumber grid concentrated where the sources vary.
193
+
194
+ ``mode="ode"`` resolves the acoustic oscillations of the source itself
195
+ (period set by ``r_s``, envelope by Silk damping ``k_D``) and is the grid the
196
+ perturbation solve runs on. ``mode="cl"`` additionally weights each ``k`` by
197
+ how many multipoles project onto it, ``k ~ l / chi_star``, and is the finer
198
+ grid the ``C_l`` quadrature uses after the sources are interpolated.
199
+ """
200
+
201
+ cosmology = eb.as_cosmology(cosmology)
202
+ summary = _cmb_grid_summary(cosmology)
203
+ x = np.linspace(np.log(k_min), np.log(k_max), n_eval)
204
+ k = np.exp(x)
205
+ primordial = k ** (cosmology.n_s + 2.0)
206
+ acoustic_curv = (1.0 / summary["r_s"]) ** 2
207
+ damped = primordial * np.exp(-((k / summary["k_D"]) ** 2))
208
+
209
+ if mode == "cl":
210
+ sigma_k = 1.0 / summary["delta_tau_rec"]
211
+ chi_star = summary["tau0"] - summary["tau_star"]
212
+ ell_samples = np.unique(
213
+ np.geomspace(ell_min, ell_max, n_ell_samples).astype(int)
214
+ )
215
+ raw_weight = np.zeros_like(k)
216
+ for ell in ell_samples:
217
+ envelope = np.exp(-0.5 * ((k - ell / chi_star) / (3.0 * sigma_k)) ** 2)
218
+ raw_weight += np.maximum(acoustic_curv, sigma_k**2) * envelope * damped
219
+ floor = 1.0e-6 * np.max(raw_weight)
220
+ else:
221
+ smooth_curv = (k * summary["r_s"]) ** 2 / summary["tau_eq"] ** 2
222
+ raw_weight = np.maximum(acoustic_curv, smooth_curv) * damped
223
+ floor = 0.005 * np.max(raw_weight)
224
+
225
+ grid = np.exp(_resample_from_density(x, (raw_weight + floor) ** (1.0 / 3.0), n))
226
+ grid[0], grid[-1] = k_min, k_max
227
+ return grid
228
+
229
+
230
+ def cmb_tau_grid(
231
+ cosmology, k_values, n: int, *, tau_end: float | None = None, n_eval: int = 10000
232
+ ) -> np.ndarray:
233
+ """Return a nonuniform conformal-time grid on which to save the sources.
234
+
235
+ The sources are sharply peaked at recombination (width ``delta_tau_rec``),
236
+ modulated on the sound-horizon scale, and would have a secondary bump at
237
+ reionization, so the sampling density is the cube root of the sum of those
238
+ three weights. Endpoints are pinned to ``[TAU_START, tau_end]``, which the
239
+ solver's save grid requires.
240
+
241
+ ``tau_end`` defaults to this cosmology's ``tau0``. A batch of cosmologies
242
+ passes the *largest* ``tau0`` of the batch so that no trajectory's save grid
243
+ is cut short; the shaping weights still come from ``cosmology``.
244
+ """
245
+
246
+ k_arr = np.asarray(k_values, dtype=np.float64)
247
+ s = _cmb_grid_summary(cosmology)
248
+ tau0 = s["tau0"] if tau_end is None else float(tau_end)
249
+
250
+ tau = np.linspace(TAU_START, tau0, n_eval, dtype=np.float64)
251
+ weight = (
252
+ np.exp(-0.5 * ((tau - s["tau_star"]) / s["delta_tau_rec"]) ** 2)
253
+ / s["delta_tau_rec"] ** 2
254
+ )
255
+ weight += (
256
+ np.exp(-0.5 * ((tau - s["tau_star"]) / s["r_s"]) ** 2)
257
+ * (float(k_arr[-1]) / np.sqrt(3.0)) ** 2
258
+ )
259
+ weight += (
260
+ 0.3
261
+ * np.exp(-0.5 * ((tau - s["tau_reion"]) / s["delta_tau_reion"]) ** 2)
262
+ / s["delta_tau_reion"] ** 2
263
+ )
264
+
265
+ tau_save = _resample_from_density(
266
+ tau, (weight + 0.005 * np.max(weight)) ** (1.0 / 3.0), n
267
+ )
268
+ tau_save[0], tau_save[-1] = TAU_START, tau0
269
+ return tau_save
270
+
271
+
272
+ class CMBGrids(NamedTuple):
273
+ """The grids of one CMB spectrum computation, shaped by a fiducial cosmology.
274
+
275
+ ``k_values`` are the wave modes the hierarchy is solved on, ``k_fine`` the
276
+ quadrature grid in ``k`` the sources are refined onto, ``tau_save`` the
277
+ conformal times the sources are recorded at, ``ells`` the multipoles.
278
+ Built by :func:`cmb_grids`; passed to :func:`~discocmb.main.compute_cl_power_spectrum_batch`
279
+ they fix the line-of-sight projection operator across batches.
280
+ """
281
+
282
+ k_values: np.ndarray
283
+ ells: np.ndarray
284
+ k_fine: np.ndarray
285
+ tau_save: np.ndarray
286
+
287
+ @property
288
+ def tau_end(self) -> float:
289
+ return float(self.tau_save[-1])
290
+
291
+
292
+ def cmb_grids(
293
+ cosmology,
294
+ *,
295
+ k_values: np.ndarray | None = None,
296
+ ells: np.ndarray | None = None,
297
+ n_save: int = 1000,
298
+ n_k_fine: int = 1500,
299
+ k_fine_values: np.ndarray | None = None,
300
+ tau_end: float | None = None,
301
+ tau_end_margin: float = TAU_END_MARGIN,
302
+ ) -> CMBGrids:
303
+ """Return the :class:`CMBGrids` shaped by ``cosmology``, built once for many batches.
304
+
305
+ The grids adapt to where the sources have structure -- the recombination
306
+ epoch and the sound horizon in ``tau`` (:func:`cmb_tau_grid`), the acoustic
307
+ scale and Silk damping in ``k`` (:func:`cmb_k_grid`) -- and nearby
308
+ cosmologies share that structure, so one fiducial's grids serve them all;
309
+ a batch has always been solved on its first cosmology's grids. Fixing them
310
+ across batches is what lets the projection operator
311
+ (:func:`~discocmb.transfer.projection_operator`: the Bessel table and the ``ln k`` refinement
312
+ matrix) be built once rather than per batch, 0.3 s each time.
313
+
314
+ The save grid ends at ``tau_end``, by default ``tau_end_margin`` past the
315
+ fiducial's ``tau0``, and every cosmology projected on these grids must
316
+ have ``tau0 <= tau_end`` (its sources are shifted onto the shared
317
+ comoving-distance grid, which must reach ``tau0``). A cosmology's own
318
+ trajectory still stops at its own ``tau0``; the saves past it carry zero
319
+ sources. The shift grows with the margin and costs accuracy through the
320
+ source interpolation (see :data:`TAU_END_MARGIN` for the measured cost),
321
+ so keep the margin to what the batches need. A cosmology past ``tau_end``
322
+ raises ``ValueError`` rather than projecting short.
323
+ """
324
+
325
+ cosmology = eb.as_cosmology(cosmology)
326
+ if k_values is None:
327
+ k_values = cmb_k_grid(cosmology, n=128, mode="ode")
328
+ if ells is None:
329
+ ells = DEFAULT_CMB_ELLS
330
+ k_values = np.asarray(k_values, dtype=np.float64)
331
+ ells = np.asarray(ells, dtype=np.int64)
332
+ if tau_end is None:
333
+ tau_end = _cmb_grid_summary(cosmology)["tau0"] * (1.0 + float(tau_end_margin))
334
+ tau_save = cmb_tau_grid(cosmology, k_values, n_save, tau_end=float(tau_end))
335
+ if k_fine_values is None:
336
+ k_fine = cmb_k_grid(
337
+ cosmology,
338
+ n=n_k_fine,
339
+ mode="cl",
340
+ k_min=float(k_values[0]),
341
+ k_max=float(k_values[-1]),
342
+ ell_max=int(np.max(ells)),
343
+ )
344
+ else:
345
+ k_fine = np.asarray(k_fine_values, dtype=np.float64)
346
+ return CMBGrids(k_values, ells, k_fine, tau_save)