Simulator API¶
classy_szlite.sim simulates the cluster counts of an SO-like survey from maps and from catalogues,
and fits the posterior of the parameters from them. A simulated survey is a set of 10-degree tiles,
each reduced to the same data vector of 21 numbers: the counts \(N_{ij}\) in four bins of the
signal-to-noise \(q\) and five bins of redshift \(z\), and the mean CMB-lensing signal \(\bar p\) of the
selected clusters,
The pipeline is also a command-line tool, mapsim <command> (see Command line).
For the method and results, see Cluster counts from maps.
| Module | What it does | Typical cost |
|---|---|---|
priors |
The ten parameters, their flat and Gaussian priors, and the derived \(\Omega_m\) and \(S_8\). | none |
setup |
Everything a tile needs before it can be simulated: paint tables, CMB spectrum, static arrays. | paint tables 1-3 min the first time (about 17 MB, then cached) |
tile |
One tile through every stage, keeping the intermediate maps for figures and checks. | 3-6 min on a laptop CPU the first time, then a few seconds; 1-2 GB of memory |
survey |
Sets of map-level and catalogue-level simulations of a survey of tiles, saved as they go. | per set, see the pipeline |
catalogue |
Catalogue-level simulator: halos, observed \(q\) and \(p\), selection and data vector, without maps. | |
calibration |
Fits the catalogue model's observation model to the finder's behaviour on map-level simulations. | one GPU, 41 tiles: 20 mocks about 1 min; a 25-point grid about 7 min plus fits (about 1 min per point on CPU) |
npe |
Neural posterior estimation of the ten parameters from the 21 numbers, with bias and coverage checks. | 10,000 simulations train in 2-7 min on 2-16 CPU cores |
cli |
The mapsim command line: tile, maps, calibrate, catalogues, train, compare. |
|
simulator |
One tile end to end: cosmology, halos, maps, matched filter, peaks, masking pass, histogram. | |
halos |
Poisson halos on one periodic tile, in fixed-capacity buffers. | up to about 130,000 halos per tile at the heaviest prior corner |
paint |
Band-limited painting of the Compton-\(y\) map of the halos. | |
instrument |
SO LAT channels (temperature): frequencies, beams, tSZ spectrum, forecast noise, CMB spectrum. | |
mmf |
Multi-frequency matched filter: covariance from the maps, \(q\) maps per scale, peaks, masking. | |
summaries |
Detections to data vector: merging, confirmation against halos, \((q, z)\) histogram. | |
lensing |
Stacked CMB-lensing observable \(p\) of each detection, from its matched halo. | |
flatsky |
Flat periodic tile geometry and its Fourier grid. |
Parameters and priors¶
Parameters and priors of the cluster-count inference.
Ten parameters, in this order everywhere (data files, posterior samples, figures):
sigma8, omega_cdm, A_SZ, alpha_SZ, h, omega_b, n_s, sigma_lnq, beta_lens, sigma_lnp
The first four have flat priors (the counts constrain them); the last six have the Gaussian priors of Zubeldia et al. (2025, Table 1), with the two scatters truncated at zero (redrawn).
Two boxes for the flat priors:
PAPER: the paper's Table 1 (omega_cdm clipped at 0.200, the emulators' training edge).MAP: the narrower box of the map-level simulations, chosen so that the heaviest corner stays affordable (about 130,000 halos per 10-degree tile).
The hydrostatic mass bias is fixed, 1 - b = 0.8. Omega_m and S8 = sigma8 sqrt(Omega_m / 0.3) are derived, with one massive neutrino of 0.02 eV x 3 as in the emulators (omega_nu = 0.06 / 93.14).
fiducial()
¶
draw_prior(n, rng, box='map')
¶
n parameter vectors (n, 10) from the prior with the flat box box ("map", "paper" or a dict).
Source code in classy_szlite/sim/priors.py
draws(set_name, n=None, box='map', seeds=None)
¶
The parameter vectors of a named set: 'truth' repeats the fiducial point; 'train' and 'heldout' are prior draws with the set's seed. Default sizes 10,000, 500 and 100.
Source code in classy_szlite/sim/priors.py
to_theta(row)
¶
A simulator.Theta from a vector in NAMES order (other fields at their fiducial values).
derived(samples)
¶
(Omega_m, S8) from samples (n, 10) in NAMES order.
sbi_prior(box='map')
¶
The prior as a torch distribution for sbi (needs the optional sbi extra).
Source code in classy_szlite/sim/priors.py
Tile set-up¶
Everything a 10-degree tile needs before it can be simulated: the paint tables, the CMB spectrum, the static arrays and buffer sizes for a given parameter point.
from classy_szlite.sim import setup
ts = setup.tile_setup() # fiducial point, emulator CMB, forecast-noise statics
# ts.cells, ts.tables, ts.cosmo, ts.cfg, ts.static, ts.info
The paint tables (radial y profiles on a grid of sizes; about 17 MB, 1-3 min of scipy work the first
time) are cached in $CLASSY_SZLITE_CACHE (default ~/.cache/classy_szlite).
The CMB: by default the lensed TT spectrum of the package's CMB emulator at its default (Planck 2018)
point (instrument.cmb_cl_emulator). MAPSIM_CMB_TABLE may point to a CAMB table in the format of
instrument.cmb_cl_from_table instead (the published runs used one; it agrees with the emulator to
0.4% for l <= 3000).
paint_tables(dln=None, directory=None, log=print)
¶
The painter's radial tables (paint.build_tables), built once and cached.
Source code in classy_szlite/sim/setup.py
default_cmb()
¶
C_l^TT [uK^2] of the lensed CMB as a function of l: the table at $MAPSIM_CMB_TABLE if set, else the emulator's (cached per process).
Source code in classy_szlite/sim/setup.py
expected_occupation(lam, cg, theta, cells, tb)
¶
Expected halos per painter footprint class, and on the direct (large-halo) path.
Source code in classy_szlite/sim/setup.py
tile_setup(theta=simu.THETA_FID, cmb_cl=None, margin=1.5, mode='goal', dln=None, log=print)
¶
Buffers sized for theta (with margin on the painter's expected occupation and 6 sigma plus
1024 slots on the halo count), the static arrays with the CMB cmb_cl (default_cmb()) and the
forecast noise at depth mode ("goal" or "baseline").
Source code in classy_szlite/sim/setup.py
One tile, every stage¶
One tile through every stage of the simulator and the finder, keeping the intermediate maps (for figures, notebooks and checks). Forecast noise (public).
from classy_szlite.sim import tile
out = tile.stages() # fiducial point, first tile of the first mock
out["y"], out["m145"], out["q_final"], out["peaks"], out["halos"]
Cost: about 3-6 min on a laptop CPU the first time (paint tables, compilation), then a few seconds; about 1-2 GB of memory.
stages(theta=None, seed=priors.SEEDS_MAP['truth'], mock=0, tile=0, q_final=4.0, log=print)
¶
The maps of one tile (1200 x 1200 pixels of 0.5', numpy float32) and its catalogue:
y Compton-y of every halo above 1e13 Msun tsz145, cmb145, noise145, m145 the 145 GHz map's three parts and their sum [uK] q_first, q_final the finder's S/N, maximised over its 15 sizes, before and after the masking pass mask the masking pass's discs (0 = masked) sigma_first, sigma_final, sigma_model the finder's noise at the 15 sizes (first pass, final pass) and the analytic noise of the instrument and the CMB peaks kept peaks with q > q_final: dict of x, y [pixels], q, size [arcmin], confirmed, halo halos halos above 5e13 Msun: dict of x, y [pixels], z, M500, theta500, y0, q_model
With the default seed this is tile tile of mock mock of the published 'truth' set.
Source code in classy_szlite/sim/tile.py
Survey sets¶
Simulated surveys: sets of map-level and catalogue-level simulations of a survey of 10-degree tiles, each reduced to the 21 numbers of the data vector (4 x 5 counts in q and z, and the mean CMB-lensing signal p of the clusters with q > 5).
Map level (simulate_map_set): per simulation, one cosmology stage, then every tile through
simulator.simulate_tile (halos, painted tSZ, lensed CMB, noise, the matched-filter finder with its masking
pass, merging, confirmation), summed over tiles.
Catalogue level (simulate_catalogue_set): catalogue.simulate on the same survey area, with a noise
model chosen by name (catalogue_model).
Both write one .npz per set (theta, x, done, ...), save as they go and resume where they stopped. Keys: simulation i of a set uses fold_in(key(seed), i), and tile t of it fold_in of that with t, so a survey of N tiles contains the skies of every smaller survey with the same seed.
survey_spectra(n_spec, n_tiles)
¶
Indices of the measured noise spectra used by the n_tiles tiles (numpy default_rng(SURVEY_SEED); without replacement when n_tiles <= n_spec).
Source code in classy_szlite/sim/survey.py
make_survey_sim(cells, tables, cfg, n_tiles, chunk=21, forecast=True)
¶
jitted (key, theta vector, static, noise tables, spectrum indices) -> the survey's 21 numbers and diagnostics. Static arrays are arguments, not constants, so the compiled program stays small.
Source code in classy_szlite/sim/survey.py
simulate_map_set(path, theta, seed, n_tiles=41, noise='forecast', spectra=None, chunk=21, save_every=200, n_classes=N_CLASSES, cmb_cl=None, log=print)
¶
Map-level simulations of the parameter vectors theta (n, 10), written to path (resumes).
noise: "forecast" (the 2019 SO forecast, goal depth; public) or "measured" with spectra the path to
a file of measured per-tile noise spectra (see the noise module). Buffers come in n_classes classes by expected
halo number, each sized at its heaviest draw; a simulation that overflows is rerun in the next class
with the same keys. Returns the dict that was saved.
Source code in classy_szlite/sim/survey.py
catalogue_model(model, n_tiles=41, calibration=None, cmb_cl=None, mode='goal')
¶
(sigma_y0 table, sigma_kappa table, CatalogueConfig) of a catalogue model of the survey.
paper the paper itself: its sigma_y0 and sigma_kappa fits, 40% of the sky published the paper's model of this survey: our filter's analytic sigma_y0 for the forecast noise and the CMB (no tSZ), our goal sigma_kappa, f_sky of n_tiles calibrated-point calibrated on map-level mocks at one point (calibration.calibrate_point's file) calibrated-noise calibrated across the prior through the finder's noise level (calibration.fit_noise_level's file; with size cells if it has them) calibrated-theta calibrated across the prior, linear in the parameters (calibration.fit_theta's file)
The calibrated models need calibration, the path to the corresponding file. Their per-tile noise
tables are averaged into one (forecast noise: the tiles differ only by sampling).
Source code in classy_szlite/sim/survey.py
simulate_catalogue_set(path, theta, seed, sz, le, cfg, batch=16, chunk=512, log=print, info=None)
¶
Catalogue-level simulations of the parameter vectors theta (n, 10), written to path
(resumes). Each draw goes to the smallest buffer that holds its expected halo number plus 8 standard
deviations; an overflowing draw is rerun in the next one.
Source code in classy_szlite/sim/survey.py
Catalogue-level simulator¶
Catalogue-level simulator of the SO-like cluster survey (the paper's model; PLAN M7).
Zubeldia, Bolliet, Challinor & Handley (2025, arXiv:2504.10230) train neural posterior
estimation on catalogues from cosmocnc's generator. This module is our own JAX version of that
model on classy_szlite's cosmology, mass function, scaling relations and lensing model (no
cosmocnc code is used). For parameters theta (simulator.Theta):
- Halos. Expected counts per (z, ln M500) cell over the survey area f_sky 4 pi (the map-level tile rates of simulator.cosmology_stage, scaled from one tile to the survey), Poisson counts per cell, and (z, ln M) drawn exactly from the bilinear interpolant of the corner densities inside each cell (as halos.sample_halos; no sky positions).
- Observables, for each halo: ln q_true = ln[ybar0(M, z) / sigma_y0(theta500)] + sigma_lnq g1 ln p_true = ln pbar(M, z) + sigma_lnp (r g1 + sqrt(1 - r^2) g2) q_obs = sqrt(q_true^2 + dof) + n1, p_obs = p_true + n2 with g1, g2, n1, n2 unit Gaussians, ybar0 and theta500 from sz_scaling (bias 1 - b), pbar = a_lens kappa(r_s) / sigma_kappa(theta500,lens) from lensing.py (mass beta_lens M500).
- Selection q_obs > q_min (strict), the paper's 4 x 5 counts in (q, z) (summaries.histogram, open intervals), and the mean p_obs over every selected cluster (any z, q above 40 included): the paper's data vector of 21 numbers.
Noise tables: "paper" the paper's sigma_y0 (SZiFi on SO-like Websky maps) and sigma_kappa tables, as cosmocnc's SO-like survey uses them: cubic fits of ln sigma in ln theta[arcmin], extrapolated outside the tables (or held at the table ends with clamp=True). The tables ship in classy_szlite/sim/data (from cosmocnc; COSMOCNC_DATA overrides); the fit is numpy.polyfit. sigma_y0 arrays (theta, sigma) from our own filter (variant (i)) are passed the same way.
Random numbers: one key per simulation. Each halo's draws come from a key folded with its cell and its index in the cell, so a count that changes in one cell changes only that cell's halos. Halo buffers have a static capacity; Catalogue.overflow flags a draw that does not fit (the caller reruns with a larger capacity).
survey_cells(z_per_bin=30, n_bins_z=10, Mmin=50000000000000.0, Mmax=1e+16, n_m=150)
¶
(z, ln M) cells aligned with the data vector's z edges: z from 0.01 in steps of Z_BIN_WIDTH / z_per_bin up to 0.01 + n_bins_z Z_BIN_WIDTH (2.99), M from M_min = 5e13.
Source code in classy_szlite/sim/catalogue.py
NoiseFit
¶
Bases: NamedTuple
ln sigma = polyval(coef, ln theta[arcmin]); within [lnth_min, lnth_max] unless extrapolated.
paper_tables(data_dir=None)
¶
The paper's sigma_y0 and sigma_kappa fits from cosmocnc_jax's data files (theta in radians).
Source code in classy_szlite/sim/catalogue.py
PatchTable
¶
Bases: NamedTuple
Noise tables per sky patch: ln sigma linear in ln theta[arcmin], held at the table ends (variant (i): our own filter's sigma_y0 per survey tile; or one row for sigma_kappa).
noise_sigma(tab, theta_arcmin, clamp=False, patch=None)
¶
sigma at theta from a NoiseFit (cubic, the paper's) or a PatchTable (per patch).
Source code in classy_szlite/sim/catalogue.py
lens_table(mode='goal')
¶
Our sigma_kappa table (lens_tables.py) as a one-row PatchTable.
analytic_sigma_y0_forecast(cmb_cl, mode='goal', fs=None)
¶
sigma_y0 of our filter at its 15 scales for the 2019 SO forecast noise (instrument.noise_cov: white plus atmospheric, correlated within a tube; the simulator's default) plus the lensed CMB: (1, 15) and the ln theta grid.
Source code in classy_szlite/sim/catalogue.py
analytic_sigma_y0(noise_tables, specs, cmb_cl, fs=None)
¶
sigma_y0 of our matched filter at its 15 scales (mmf.THETAS15) for measured per-tile noise
spectra specs (noise.NoiseTables rows) plus the lensed CMB, without tSZ: the covariance is
each mode's noise power (F F^T, per-mode units of noise.draw: E|X|^2 = N^2 C) plus
B_i B_j C_l N^2 / Omega_pix, averaged over the filter's bins as mmf's estimate is.
Returns (len(specs), 15) and the ln theta grid.
Source code in classy_szlite/sim/catalogue.py
CatalogueConfig
¶
Bases: NamedTuple
Static settings (hashable).
data_vector(cat)
¶
The paper's 21 numbers: the 4 x 5 counts (q-major) and the mean p over all selected.
survey_rates(theta, cells)
¶
Cosmology stage scaled from one map tile to the whole sky (multiply by f_sky): (lam per cell, corner densities, cosmology grids, chi_star).
Source code in classy_szlite/sim/catalogue.py
HaloDraw
¶
Bases: NamedTuple
Every slot of the halo buffer (valid marks the drawn halos).
draw(key, theta, cells, sz_fit, lens_fit, cfg=CatalogueConfig())
¶
The halos of one catalogue and their observables (traceable in theta).
Source code in classy_szlite/sim/catalogue.py
qcal_params(qcal, z, th=None, size_edges=None)
¶
(s, k, w, f) of each halo from the calibration table (see CatalogueConfig.qcal; a tuple, or an array from qcal_theta_eval / qcal_conf_eval). With size_edges (CatalogueConfig.qcal_size) the table has one row per (redshift, size) cell, redshift-major, and th gives each halo's theta500 [arcmin].
Source code in classy_szlite/sim/catalogue.py
quad_features(x)
¶
1, x_i, x_i x_j (i <= j): 15 features of the 4 scaled parameters.
qcal_conf_eval(qc, theta)
¶
Variant (iv) (CatalogueConfig.qcal_conf) at theta: the (n_z, 5) observation table and the shift of ln sigma at the 15 filter sizes, both through the finder's noise level u.
Source code in classy_szlite/sim/catalogue.py
qcal_theta_eval(qt, theta)
¶
The calibration at theta (CatalogueConfig.qcal_theta): the (n_z, 5) table of qcal_params and the shift of ln sigma at the 15 filter sizes. Linear in x = (theta - fid) / width; w is kept above 0.05 and f within [0, 0.5].
Source code in classy_szlite/sim/catalogue.py
load_qcal(path)
¶
Calibration from qcal.py (calibration.npz): the CatalogueConfig.qcal tuple and the PatchTable of the finder's noise (per tile, mean over the mocks).
Source code in classy_szlite/sim/catalogue.py
simulate(key, theta, cells, sz_fit, lens_fit, cfg=CatalogueConfig())
¶
One catalogue (traceable in theta; jit with cells and cfg static).
Source code in classy_szlite/sim/catalogue.py
expected(theta, cells, sz_fit, lens_fit, cfg=CatalogueConfig(), n_gh=24, n_sub=3)
¶
Expected 4 x 5 counts, expected number selected and expected sum of p over the selected clusters. Each cell is integrated with n_sub x n_sub Gauss-Legendre points weighted by the bilinear density (the sampler's), the scatter with Gauss-Hermite in (g1, g2), and the unit noise of q_obs exactly (normal CDF). E[p_obs | selected] uses E[n2] = 0.
Source code in classy_szlite/sim/catalogue.py
Calibration on maps¶
Calibrating the catalogue model on map-level simulations.
The catalogue model draws each halo's observed signal-to-noise as q_obs = q_true + N(0, 1) with q_true = y0 / sigma_y0(theta500) from a noise table. The finder on maps behaves differently: its noise includes the tSZ of faint clusters (confusion), its search over positions and sizes lifts faint clusters, and neighbours add scatter and steal matches. This module measures that behaviour halo by halo and fits the calibrated observation model of catalogue.CatalogueConfig:
q = y0 / sigma_finder(theta500); lost with probability f, else q_obs = sqrt((s q)^2 + k) + w N(0, 1)
per redshift bin (optionally per redshift and size cell), by censored maximum likelihood.
Three calibrations, each a file that survey.catalogue_model reads:
calibrate_point: at one parameter point (default the fiducial one) -> "calibrated-point";calibrate_gridthenfit_noise_level: at a Latin hypercube of points over the prior, written through the finder's noise level u = ln(sigma_finder(2') / sigma_finder(2'; fiducial)), quadratic in the parameters -> "calibrated-noise";calibrate_gridthenfit_theta: the same points, linear in the parameters -> "calibrated-theta".
Typical cost on one GPU (41 tiles, forecast noise): the per-halo table of 20 mocks takes about 1 min after compilation; a 25-point grid with 5 mocks each about 7 min plus the fits (about 1 min per point on CPU).
halo_table(n_mocks, theta=None, seed=priors.SEEDS_MAP['truth'], n_tiles=41, noise='forecast', spectra=None, setup_theta=None, cap=8192, neighbours=False, key=None, log=print)
¶
Every halo above 5e13 Msun of n_mocks map-level mocks of the survey at theta (default the
fiducial point; with the default seed, the mocks of the 'truth' set themselves), with three q's:
q_model y0 / sigma_y0(theta500): the catalogue model's q_true (analytic noise of the filter); q_fsig y0 / sigma_finder(theta500): the same with the finder's own final-pass noise of that tile; q_obs the highest q of the kept, confirmed peaks matched to the halo (-inf if none; peaks kept down to q = 4).
key replaces key(seed) as the base key. Buffers are sized at setup_theta (default theta). neighbours adds the largest q_model of other
halos within 3' (q_nb) and whether a heavier halo lies within 1.5' (shadow): a cap x cap comparison.
Returns (H, T): a record array of halos and a dict of per-tile arrays (sigma, sigma0, sigma_model,
counts) with the noise tables' ln theta grid and spectrum indices.
Source code in classy_szlite/sim/calibration.py
censored_fit(q, qo, lo=4.0)
¶
Maximum likelihood of: lost with probability f whatever q (peak merged into a brighter one, or
credited to a heavier halo within 1.5'), else q_obs ~ N(sqrt((s q)^2 + k), w), observed above lo
and censored below. Returns s, k, w, f, their errors (numerical Hessian), n and n_det.
Source code in classy_szlite/sim/calibration.py
fit_rows(H, q_name='q_fsig')
¶
(n_z, 5): s, k, w, f, n per redshift bin (ZB) against q_name on halos with q > 2.
Source code in classy_szlite/sim/calibration.py
fit_cells(H)
¶
(n_z, n_size, 5): s, k, w, f, n per (redshift, size) cell; NaN where fewer than N_MIN halos.
Source code in classy_szlite/sim/calibration.py
tile_sigma(T)
¶
The finder's final-pass noise per tile (n_tiles, 15), mean over the mocks.
calibrate_point(H, T, path, noise='forecast')
¶
Write the one-point calibration (catalogue.load_qcal's format) from a halo table.
Source code in classy_szlite/sim/calibration.py
grid_points(n, box='map', seed=GRID_SEED)
¶
The fiducial point followed by a Latin hypercube of n points in the flat box (4 parameters).
Source code in classy_szlite/sim/calibration.py
calibrate_grid(out_dir, n_points=24, n_mocks=5, size=False, n_tiles=41, noise='forecast', spectra=None, cap=16384, box='map', log=print)
¶
The calibration at the fiducial point and a Latin hypercube of n_points over the prior, each from
n_mocks map-level mocks with their own keys (fold_in(key(GRID_SEED), point)); buffers sized at the
heaviest point. Writes out_dir/calib_grid.npz (rows per z bin; with size, cells per (z, size) too)
and out_dir/points/point_XX.npz (the halos with q_fsig > 1.5, for refits). Resumes.
Source code in classy_szlite/sim/calibration.py
fit_noise_level(grid_path, out_path, size=False, log=print)
¶
The calibration through the finder's noise level u (quadratic in the scaled parameters): ln sigma at each filter size linear in u, s, k, w, f per redshift bin (or per (z, size) cell, where a cell short of halos at a point takes that point's z-bin value) quadratic in u. Writes the file survey.catalogue_model("calibrated-noise") reads; returns the leave-one-out errors.
Source code in classy_szlite/sim/calibration.py
fit_theta(grid_path, out_path, log=print)
¶
The calibration linear in the scaled parameters: ln sigma (tile mean, relative to the fiducial per-tile table) and s, k, w, f per z bin. Writes the file survey.catalogue_model("calibrated-theta") reads.
Source code in classy_szlite/sim/calibration.py
load_noise_level(path)
¶
(CatalogueConfig.qcal_conf, PatchTable of the fiducial per-tile noise, size edges or None).
Source code in classy_szlite/sim/calibration.py
load_theta(path)
¶
(CatalogueConfig.qcal_theta, PatchTable of the fiducial per-tile noise).
Source code in classy_szlite/sim/calibration.py
Posterior estimation¶
Neural posterior estimation of the ten parameters from the 21 numbers, and its checks.
Needs the optional sbi extra (sbi, torch): pip install "classy_szlite[sbi]".
Training follows Zubeldia et al. (2025, Sec. II.4): sbi's NPE (NPE_C) with a masked autoregressive flow of sbi's default size, one round, learning rate 5e-4, stop after 50 epochs without improvement of the validation loss. Typical cost: 10,000 training simulations train in 2-7 min on 2-16 CPU cores.
Checks, on simulations whose true parameters are known:
bias: the mean over data vectors of (posterior mean - truth) / posterior sd, with its error of the mean (on mocks at one parameter point; 0 for a calibrated posterior);coverage: the fraction of data vectors whose truth lies in the central credible interval of each level (on prior draws; equal to the level for a calibrated posterior), and TARP;ensemble: an equal mixture of posteriors trained with different seeds.
load_set(path)
¶
(theta, x) of a simulated set (.npz from survey.simulate_*_set), finished and finite rows only.
Source code in classy_szlite/sim/npe.py
train(theta, x, box='map', seed=0, log=print)
¶
A posterior q(theta | x) trained on (theta, x); returns (posterior, info).
Source code in classy_szlite/sim/npe.py
sample(post, x, n)
¶
n posterior samples (n, 10) for one data vector.
summarise(post, theta, x, n_samples=4000)
¶
Per data vector: posterior mean, sd, the rank of the truth among the samples, and the same for (Omega_m, S8). Arrays of shape (n, 10) and (n, 2).
Source code in classy_szlite/sim/npe.py
bias(summary)
¶
Mean of (mu - truth) / sd and its error of the mean, per parameter; also for (Omega_m, S8).
Source code in classy_szlite/sim/npe.py
coverage(summary, levels=LEVELS)
¶
(len(levels), 10): fraction of data vectors whose truth is in the central interval of each level (from the rank of the truth among the posterior samples).
Source code in classy_szlite/sim/npe.py
tarp(post, theta, x, n_samples=1000)
¶
TARP (Lemos et al. 2023) of the joint posterior: (area to the diagonal, KS p-value).
Source code in classy_szlite/sim/npe.py
ensemble(summaries)
¶
An equal mixture of posteriors (summaries of the same data vectors): mean of the means, variance = mean variance + variance of the means, rank = mean rank (exact for equal sample numbers).
Source code in classy_szlite/sim/npe.py
Command line¶
Command-line pipeline of the cluster-count simulations: mapsim <command> (or
python -m classy_szlite.sim <command>).
mapsim tile --out OUT one tile through every stage (maps and catalogue)
mapsim maps --out OUT --set truth|heldout|train [--tiles 41] [--n N]
mapsim calibrate --out OUT point|grid|fit-noise|fit-theta [--size] [--mocks M] [--points P]
mapsim catalogues --out OUT --model published|calibrated-point|calibrated-noise|calibrated-theta|paper
--set truth|heldout|train [--tiles 41]
mapsim train --out OUT --data maps|<catalogue model> [--tiles 41] [--seed S] [--name NAME]
mapsim compare --out OUT [--tiles 41]
Everything is written under OUT:
maps_t{tiles}/{set}.npz map-level sets (forecast noise)
calibration/point.npz, grid/, noise.npz, theta.npz
catalogues/{model}_t{tiles}/{set}.npz catalogue-level sets
npe/{data}_t{tiles}/{name}.json, {name}_{applied set}.npz
compare_t{tiles}.json bias and coverage of every trained posterior
Each step resumes where it stopped. The noise is the public 2019 SO forecast (goal depth) throughout;
--noise measured --spectra PATH selects measured per-tile noise spectra instead (maps, calibrate).
Building blocks¶
The modules below are the stages of one tile. Most users call them through tile, survey and
catalogue.
One tile, end to end¶
One tile, end to end (first version, for the M0 throughput spike).
θ → cosmology → λ cells (once per θ), then per tile:
halos → y(k) → six channel maps (tSZ + lensed CMB + noise: the 2019 forecast
model's white and atmospheric noise, or per-tile noise calibrated on MSS2,
noise.py) → matched filter (covariance from the maps) → peaks → masking
iteration (discs around the q > 4 peaks, covariance re-estimated outside
them, filter run again; TileConfig.n_iter times, 1 by default as SZiFi)
→ merging → confirmation → (q, z) histogram.
Stacked CMB lensing: the catalogue-level observable p of each data-vector detection, from its matched halo (lensing.py); each tile returns Σ p and the count.
Theta
¶
Bases: NamedTuple
Parameters of one simulation (the paper's SO-like set).
TileConfig
¶
Bases: NamedTuple
Static configuration (hashable).
TileStatic
¶
Bases: NamedTuple
Static arrays (jit arguments).
cosmology_stage(theta, cells)
¶
λ cells, corner densities and the cosmology grids on the cell z edges (traceable).
Source code in classy_szlite/sim/simulator.py
channel_maps(key, yk, st, noise=None)
¶
Six channel maps (6, N, N/2+1) c64 in rfft units [μK]. The noise is the 2019 forecast
model's (white plus atmospheric, correlated within a tube) unless noise gives the tile's
MSS2-calibrated spectra (noise.py). Either way the CMB uses the same key, so changing the
noise model leaves the sky unchanged. With noise, tile_static's mode still sets the
lensing noise table (σ_κ) of the stacked-lensing observable: keep it consistent with the
noise's depth (the per-tile depth scale does not reach it).
Source code in classy_szlite/sim/simulator.py
tile_maps(key, cs, theta, st, tables, cells, cfg, noise=None)
¶
Halos, the six channel maps and the painter's overflow flags of one tile.
Source code in classy_szlite/sim/simulator.py
simulate_tile(key, cs, theta, st, tables, cells, cfg, noise=None)
¶
Data vector and diagnostics of one tile.
Source code in classy_szlite/sim/simulator.py
stacked_lensing(key, pk, keep, cf, halos, cs, theta, st)
¶
Sum of the lensing observable p over the selected detections of one tile, and their number (the survey's stacked mean is Σ p_sum / Σ n_p). Selected: kept, confirmed and q > 5, at any redshift and including q above 40, as the paper's "averaged across the entire catalogue" (decided 2026-11-21; earlier: the 4 x 5 grid's detections only).
Source code in classy_szlite/sim/simulator.py
find_clusters(X, fs, cfg)
¶
Matched filter with the masking iteration: the final pass's peaks (q > cfg.q_final), its σ_j and diagnostics (first-pass σ_j, masked fraction and number of discs of the last iteration, and a peak-buffer overflow flag over all passes, since an overflowing pass masks only the peaks it holds). Passes that feed a mask keep every peak with q > cfg.q_mask.
Source code in classy_szlite/sim/simulator.py
Halos¶
Poisson halos on one periodic tile, in fixed-capacity buffers (traceable).
λ cells: expected counts per (z, ln M) cell of one tile,
λ_c = ∫∫_cell d²N/dz dlnM dz dlnM, d²N/dz dlnM = dn/dlnM (χ²/H) c Ω_tile,
from the corner values of the cell (exact for the bilinear interpolant). Sampling: Poisson counts per cell, then each buffer slot s < Σ counts is assigned to its cell through the cumulative counts; inside the cell, (z, ln M) are drawn exactly from the bilinear interpolant of the corner densities (or uniformly, without them).
Positions are uniform on the tile, stored as an int32 painting-grid pixel plus a float32 offset in [0, 1) pixel units. Overflow (Σ counts > capacity) is flagged, never truncated silently: the caller reruns the draw in a larger capacity class.
CellGrid
¶
Bases: NamedTuple
Static (z, ln M) cell edges.
corner_density(cg, params, cells, hmf_kwargs=None)
¶
d²N/dz dlnM of one tile at the cell corners, shape (n_z + 1, n_m + 1).
cg must be a CosmoGrids built on z = cells.z_edges.
hmf_kwargs go to build_halo_grids (production:
tinker_interp='log10', nu_in_rho_m=False). Tinker08 is interpolated
in log10 Δ since 2026-11-18; cosmocnc_jax's linear default gives up to
2.3% more halos at 1e13 M_sun.
Source code in classy_szlite/sim/halos.py
lambda_from_corners(d2N, cells)
¶
Cell integrals of the bilinear interpolant: corner mean × cell area.
Source code in classy_szlite/sim/halos.py
lambda_cells(cg, params, cells, hmf_kwargs=None)
¶
Expected counts per cell for one tile, shape (n_z, n_m), float64.
Halos
¶
Bases: NamedTuple
Halo buffer of one tile (capacity C). Padding slots have y0 = 0.
sample_halos(key, lam, cells, capacity, cg, h, A_SZ, alpha_SZ, sigma_lnq, one_minus_b, d2N=None)
¶
Draw the halos of one tile into a buffer of capacity slots.
With d2N (the corner densities, :func:corner_density), (z, ln M) are
drawn exactly from the bilinear interpolant inside each cell: z from its
linear marginal, then ln M from the linear conditional (closed-form
inverse CDFs, as szsim's sampler). Without it, uniformly in the cell.
Each halo's random numbers (position, offsets, z, ln M, scatter) come from a key folded with its cell and its index within the cell, not from its buffer slot. A count that changes in one cell (a different θ, or a last-bit difference in the Poisson sampler between CPU and GPU, which happens for λ ≥ 10) then adds or removes halos in that cell only; every other halo is unchanged.
Source code in classy_szlite/sim/halos.py
Painting the y map¶
Band-limited y painting on a periodic tile (PLAN §3.3).
One y map per tile, then the channels in Fourier space:
- scatter-add each halo's beam-convolved radial profile on the 0.25′ grid (2400²), with a 0.8′ painting beam (scheme A of the M0 spike);
- rfft2, crop to the 0.5′ grid's modes, divide out the painting beam on the in-band modes (zero elsewhere);
- halos with θ500 > θ_split are synthesised exactly on the in-band modes instead (few halos, large footprints).
The result is y(k) in coarse rfft units: y(k) = Σ_h y0_h θ_h² T(|k| θ_h) e^{-ik·x_h} / Ω_pix, the continuous template with no pixel window, as the finder's template.
Radial tables: P(r; θ) = (½π) ∫ dℓ ℓ θ² T(ℓθ) B_paint(ℓ) J0(ℓ r) on θ nodes uniform in ln θ, r uniform on [0, 5θ + 6σ_paint]; cubic Lagrange in r, linear in ln θ.
radial_profile(theta, rP, nr)
¶
P(r; θ) on r = linspace(0, rP, nr), per unit y0 (θ, r in arcmin).
Source code in classy_szlite/sim/paint.py
build_tables(th_min=0.1, th_split=6.0, dln=0.004, nr=2048)
¶
Radial tables on θ nodes from th_min to past th_split. dln = 0.004 keeps the ln θ interpolation error near 7e-6 of the peak (M0: 1.6e-4, 4.1e-5 and 1.1e-5 at 0.02, 0.01 and 0.005).
Source code in classy_szlite/sim/paint.py
half_width(rP_arcmin)
¶
Footprint half-width h [fine pixels] covering radius rP around a centre anywhere inside its pixel: offsets -h..h cover [iy - h, iy + h].
PaintConfig
¶
Bases: NamedTuple
Static painting configuration (hashable).
make_config(tables, expected_per_class, cap_big, margin=1.5, extra=256)
¶
Capacities from expected class occupations (host-side).
Source code in classy_szlite/sim/paint.py
theta_node(theta, tables)
¶
Node index i0 (clipped) and linear weight w in ln θ, traceable.
Source code in classy_szlite/sim/paint.py
footprint_class(theta, tables, rP_j)
¶
Class index of each halo (len(SIDES) for θ > θ_split or beyond).
Source code in classy_szlite/sim/paint.py
paint_fine(halos, tables, cfg)
¶
The fine 2400² y map (painting beam included) of the halos with θ500 ≤ θ_split, and per-class overflow flags.
Source code in classy_szlite/sim/paint.py
fine_to_coarse(fine)
¶
rfft2 of the fine map, cropped to the coarse modes, in coarse rfft units, painting beam divided out on the in-band modes (zero elsewhere).
Source code in classy_szlite/sim/paint.py
synth_direct(halos_sel, T_tab, dtype=jnp.float32)
¶
y(k) of the given halos on the coarse rfft grid (in-band modes only),
coarse rfft units. halos_sel: dict with iy, ix (int32, fine pixels),
oy, ox (offsets), y0, theta500 (arcmin), all (C,). Exact up to the T(u)
table: phases are reduced in integer arithmetic, so float32 keeps
~1e-7 rad at any position.
Source code in classy_szlite/sim/paint.py
paint_y(halos, tables, cfg, T_tab)
¶
y(k) of all halos of a tile (coarse rfft units, in-band), and overflow flags (per class, then the direct path).
Source code in classy_szlite/sim/paint.py
Instrument¶
SO LAT instrument model for mapsim (temperature only), as szsim's.
Numbers from The Simons Observatory Collaboration (Ade et al. 2019, JCAP 02, 056, arXiv:1808.07445):
- Table 1 (LAT, f_sky = 0.4): frequencies, beam FWHM, white noise (baseline and goal, μK-arcmin).
- Sec. 2.2, eq. 1: N_ℓ = N_red (ℓ/ℓ_knee)^α_knee + N_white, ℓ_knee = 1000, α_knee = -3.5; Table 2 LAT temperature N_red [μK² s]; atmospheric noise correlated with coefficient 0.9 between the two bands of an optics tube. The red level converts to μK² sr with A_sky / t_eff, A_sky = 4π f_sky, t_eff = 5 yr × 0.2 × 0.85.
tSZ SED: non-relativistic, at the band centres: ΔT/T_CMB = g(x) y, g(x) = x coth(x/2) - 4. Gaussian beams B_ℓ = exp(-ℓ² σ_b² / 2).
tsz_f_uK(nu_GHz)
¶
beams(L, fwhm=SO_LAT['fwhm'])
¶
red_levels()
¶
noise_cov(L, mode='goal', atm=True, atm_corr=None)
¶
Noise covariance N_ij(ℓ) [μK² sr], not beam-deconvolved, (6, 6) + L.shape.
Source code in classy_szlite/sim/instrument.py
cmb_cl_from_table(path)
¶
C_ℓ^TT [μK²] from szsim's CAMB table (data_real/cmb_lensed_TT_camb.npz):
returns a function of ℓ (power law above the stored range, 0 below ℓ = 2).
Source code in classy_szlite/sim/instrument.py
cmb_cl_emulator(cosmo=None)
¶
C_ℓ^TT [μK²] of the lensed CMB from the TT emulator at cosmo
(a CosmoParams; default: the emulator's default point). Returns a function
of ℓ: the emulator for 2 ≤ ℓ ≤ 9000, a power law in ln C_ℓ vs ln ℓ fitted
on 7000-9000 beyond, 0 below ℓ = 2. Host-side numpy.
Source code in classy_szlite/sim/instrument.py
Matched filter¶
Multi-frequency matched filter on one tile (PLAN §5, mmf.py).
- Covariance from the maps: n×n cross-spectra (n channels: the six SO
channels by default, or a subset,
filter_static(channels=...)) averaged over the in-band modes of each |k| bin (rfft multiplicities), accumulated in float64. The per-bin sums use a static padded layout (no atomics), so the reduction order is fixed. - Per-bin inverse (Cholesky, float64); shared weights w(k) = C_b⁻¹ a(k) for all scales, a_i(k) = f_i B_i(|k|); one combined map cx(k) = Σ_i w_i X_i.
- Per scale θ_j: ŷ0_j = irfft2(τ_j cx) N_px / norm_j with τ_j(k) = θ_j² T(|k| θ_j) / Ω_pix and norm_j = Σ_k W τ_j² aᵀC⁻¹a; σ_j = norm_j^(-½); q_j = ŷ0_j / σ_j.
- Peaks: q > q_th, strictly above the four map neighbours (periodic), q_j > q_{j-1} and q_j ≥ q_{j+1} along the scale axis (SZiFi's rules, as szsim). Compacted in catalogue order (scale, then row-major pixel) into a fixed-capacity buffer, with an overflow flag.
- Masking iteration (SZiFi's, as szsim's step-3 finder): every peak with q > 4 is masked with a binary disc of radius 3 θ_j (pixel centres at distance ≤ r, periodic). The discs are built as FFTs of per-scale peak maps times integer-disc kernels, which reproduces "distance ≤ r" exactly. The covariance is re-estimated outside the discs and the filter is run again on the unmasked maps. Estimator (szsim's 'whitened'): each in-band mode is whitened with the first-pass covariance of its bin, Z = C0^(-½) X; the whitened maps are masked; their binned spectra are divided by the kept fraction f and un-whitened, C0^(½) C_w C0^(½). The whitened field is nearly white, so the disc edges do not leak the steep low-ℓ CMB and atmosphere power to high ℓ (the literal binary-mask estimate inflates σ by 16-47% on noise-only tiles).
FilterStatic
¶
Bases: NamedTuple
Static arrays of the filter (pass as jit arguments).
disc_kernels(thetas=THETAS15, radius=MASK_RADIUS)
¶
rfft2 of the binary discs (1 at pixel offsets with dy² + dx² ≤ R_j², R_j = radius θ_j / PIX, periodic, centred on pixel 0), (n_th, N, N/2+1) float64. The discs are symmetric, so their transforms are real.
Source code in classy_szlite/sim/mmf.py
filter_static(thetas=THETAS15, mask_radius=MASK_RADIUS, channels=None)
¶
channels: indices of the SO channels the filter uses, in the maps' order (default all
six). The maps passed to q_cube and masked_cov must then hold exactly these channels.
Source code in classy_szlite/sim/mmf.py
binned_cov(Xm, fs)
¶
Binned n×n covariance (float64) from the in-band modes Xm (n, n_modes).
Source code in classy_szlite/sim/mmf.py
weights(C, fs)
¶
w(k) = C_b⁻¹ a(k) (n_modes, n) and aᵀC⁻¹a (n_modes,), float64.
Source code in classy_szlite/sim/mmf.py
q_cube(X, fs, C=None, dtype=jnp.float32)
¶
S/N cube (n_th, N, N), σ_j (n_th,) and the covariance used.
X: channel maps (n, N, N/2+1) in rfft units (complex), the filter's channels.
C: binned covariance; estimated from X if None.
Source code in classy_szlite/sim/mmf.py
find_peaks(q, capacity, qth=Q_TH)
¶
Peaks of the S/N cube (see the module docstring).
Source code in classy_szlite/sim/mmf.py
cluster_mask(peaks, fs, q_mask=Q_MASK)
¶
Binary mask (N, N) float32, 1 = kept, and the number of discs: 0 within MASK_RADIUS θ_j of every valid peak with q > q_mask (see the module docstring). Peaks beyond the buffer (overflow) are not masked.
Source code in classy_szlite/sim/mmf.py
whitening(C)
¶
C^(-½) and C^(½) per bin (symmetric square roots, float64).
masked_cov(X, mask, C0, fs)
¶
Binned covariance of the tile outside the mask (szsim's 'whitened' estimate, see the module docstring) and the kept fraction f.
X: channel maps (n, N, N/2+1) in rfft units, the filter's channels; mask: (N, N),
1 = kept; C0: the unmasked binned covariance of the same maps (whitening).
Source code in classy_szlite/sim/mmf.py
Summaries¶
Detections → data vector (PLAN §3.4), first version (M0 spike).
- Merging: a peak is kept unless another peak within r_merge has a higher q (ties: the earlier one in catalogue order wins). This is a local maximum within the merge radius, over all scales. M6 fixes the production rule against chains of overlapping peaks.
- Confirmation: a kept peak is confirmed if a halo with M500 ≥ M_conf lies within r_conf; it takes the redshift of the matched halo with the largest y0. Unconfirmed peaks are dropped.
- Histogram: four q bins with edges logspace(log10 5, log10 40, 5) and five z bins with edges linspace(0.01, 1.5, 6), open intervals; q ≥ 40 and z outside 0.01-1.5 are dropped.
merge_local_max(peaks, r_merge_arcmin)
¶
Boolean keep mask over the peak buffer.
Source code in classy_szlite/sim/summaries.py
in_data_vector(q, z, ok)
¶
Detections counted by :func:histogram (same open intervals).
Source code in classy_szlite/sim/summaries.py
histogram(q, z, ok)
¶
(4, 5) int32 counts in the paper's q and z bins.
Source code in classy_szlite/sim/summaries.py
CMB lensing¶
Stacked CMB-lensing observable (catalogue level, the paper's model; PLAN §3.2).
For each detection in the data vector, from its matched halo (M500, z):
p̄ = a_lens κ(r_s; β M500, z) / σ_κ(θ500(β M500, z)),
ln p_true = ln p̄ + σ_lnp N(0,1), p_obs = p_true + N(0,1),
with β = β_CMBlens (0.92), σ_lnp = σ_CMBlens (0.22), a_lens = 1. κ(r_s) is the convergence at the scale radius of an NFW halo with c500 = 3 truncated in 3D at 5 R500 (Zubeldia & Challinor 2019, Eqs. 18-20):
κ(r_s) = 4π (G/c²) Σ(r_s) D_l (1 − χ_l/χ*), Σ(r_s) = S_RS ρ0 r_s,
and σ_κ(θ500) is the matched-filter noise of that amplitude (lens_tables.py, SO baseline or goal). The summary is the mean of p_obs over the data-vector sample: each tile returns the sum of p_obs and the number of detections. Traceable (jnp).
chi_star(h, omega_cdm, omega_b)
¶
Comoving distance to last scattering [Mpc], flat ΛCDM with radiation (Gauss–Legendre in ln(1+z); ~0.1% accuracy is ample: κ depends on it only through 1 − χ_l/χ*).
Source code in classy_szlite/sim/lensing.py
kappa_rs(M500, z, cg, h, beta, chi_s)
¶
Convergence at the scale radius for lensing mass β M500 at redshift z.
Source code in classy_szlite/sim/lensing.py
table(mode='goal')
¶
sigma_kappa(theta500, lnth_tab, lnsig_tab)
¶
σ_κ at θ500 [arcmin]: linear in ln–ln, held at the end values outside the table.
p_mean(M500, z, cg, h, beta, chi_s, lnth_tab, lnsig_tab, a_lens=1.0)
¶
p̄ = a_lens κ(r_s) / σ_κ(θ500), both at the lensing mass β M500.
Source code in classy_szlite/sim/lensing.py
draw_p(key, pbar, sigma_lnp)
¶
p_obs: log-normal intrinsic scatter about p̄, then unit Gaussian noise.
Source code in classy_szlite/sim/lensing.py
Tile geometry¶
Flat periodic tile geometry and its Fourier grid (host-side numpy).
Conventions (as szsim's finder, for the identity tests):
- Tile 600′ × 600′, N = 1200 pixels of 0.5′; pixel (iy, ix) sits at (y, x) = (iy, ix) × 0.5′; array axis 0 is y. Periodic.
- Painting grid: NF = 2400 pixels of 0.25′.
- rfft2 layout: axis 0 full (
fftfreq), axis 1 the half plane 0..N/2. Integer wavenumbers (i0, i1); |k| = DK √(i0² + i1²) with DK = 2π/600′ = 36 exactly. - "rfft units": X(k) = Σ_p x(p) e^{-ik·p}. A field of power C_ℓ has E|X|² = Npx C_ℓ / Ω_pix.
- Band: 100 ≤ |k| ≤ 20000, a sharp cut (n² from 8 to 308641).
- Covariance bins of width 72 = 2 DK (SZiFi's bin_fac = 4): bin = ⌊√n² / 2⌋, with an exact integer square root.
- rfft multiplicities W = 2, except the i1 = 0 and i1 = N/2 columns (W = 1): sums over the half plane weighted by W are full-plane sums.
isqrt(n)
¶
Exact integer square root of a non-negative int64 array.
FlatGrid(n=N, pix=PIX, lmin=LMIN, lmax=LMAX, bin_dk=BIN_DK)
¶
Fourier grid of an n × n periodic tile of pixel pix arcmin.
Attributes (numpy): i0 (n,), i1 (n//2+1,), n2, L [rad⁻¹],
W (rfft multiplicities) and sel (in-band) of shape (n, n//2+1);
ib (bin index); the in-band mode list m_idx (flat indices, sorted
by bin) with m_L, m_W, m_bin; the padded per-bin layout
bin_pad (n_bins_used, max_count) of positions in the mode list, with
-1 for padding, and bin_count (W-weighted counts).
Source code in classy_szlite/sim/flatsky.py
grid(n=N, pix=PIX)
¶
fine_to_coarse_rows(n=N, nf=NF)
¶
Rows of the fine rfft2 array that hold the coarse grid's modes
(|i0| < n/2), in the coarse fftfreq order; columns are 0..n/2.