Skip to content

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,

\[ \mathbf{x} = \big(N_{11}, \dots, N_{45},\ \bar p\big), \qquad q\ \text{edges} = 5 \times 8^{\,k/4}\ (k = 0, \dots, 4), \qquad z\ \text{edges} = 0.01, 0.308, \dots, 1.5 . \]

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()

The true parameters of the mocks (simulator.THETA_FID) as a vector in NAMES order.

Source code in classy_szlite/sim/priors.py
def fiducial():
    """The true parameters of the mocks (simulator.THETA_FID) as a vector in NAMES order."""
    return np.array([getattr(THETA_FID, k) for k in NAMES])

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
def draw_prior(n, rng, box="map"):
    """n parameter vectors (n, 10) from the prior with the flat box ``box`` ("map", "paper" or a dict)."""
    flat = _box(box)
    th = np.empty((n, len(NAMES)))
    for j, name in enumerate(NAMES):
        if name in flat:
            th[:, j] = rng.uniform(*flat[name], n)
        else:
            mu, sd = GAUSS[name]
            v = rng.normal(mu, sd, n)
            if name in POSITIVE:
                while np.any(v <= 0):
                    bad = v <= 0
                    v[bad] = rng.normal(mu, sd, bad.sum())
            th[:, j] = v
    return th

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
def 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."""
    seeds = seeds or (SEEDS_MAP if box == "map" else SEEDS_CATALOGUE)
    n = n or {"train": 10000, "heldout": 500, "truth": 100}[set_name]
    if set_name == "truth":
        return np.tile(fiducial(), (n, 1))
    return draw_prior(n, np.random.default_rng(seeds[set_name]), box)

to_theta(row)

A simulator.Theta from a vector in NAMES order (other fields at their fiducial values).

Source code in classy_szlite/sim/priors.py
def to_theta(row):
    """A simulator.Theta from a vector in NAMES order (other fields at their fiducial values)."""
    return THETA_FID._replace(**dict(zip(NAMES, (float(v) for v in row))))

derived(samples)

(Omega_m, S8) from samples (n, 10) in NAMES order.

Source code in classy_szlite/sim/priors.py
def derived(samples):
    """(Omega_m, S8) from samples (n, 10) in NAMES order."""
    s = np.asarray(samples)
    om = (s[:, 1] + s[:, 5] + OMEGA_NU_H2) / s[:, 4] ** 2
    return om, s[:, 0] * np.sqrt(om / 0.3)

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
def sbi_prior(box="map"):
    """The prior as a torch distribution for sbi (needs the optional ``sbi`` extra)."""
    import torch
    from sbi.utils import MultipleIndependent
    from torch.distributions import Normal, Uniform
    flat = _box(box)
    d = []
    for n in NAMES:
        if n in flat:
            lo, hi = flat[n]
            d.append(Uniform(torch.tensor([lo], dtype=torch.float32), torch.tensor([hi], dtype=torch.float32)))
        else:
            mu, sd = GAUSS[n]
            d.append(Normal(torch.tensor([mu], dtype=torch.float32), torch.tensor([sd], dtype=torch.float32)))
    return MultipleIndependent(d, validate_args=False)

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
def paint_tables(dln=None, directory=None, log=print):
    """The painter's radial tables (paint.build_tables), built once and cached."""
    dln = DLN if dln is None else dln
    path = os.path.join(directory or cache_dir(), f"paint_tables_dln{dln:g}.npz")
    if os.path.exists(path):
        d = np.load(path)
        return pt.PaintTables(lnth0=float(d["lnth0"]), dln=float(d["dln"]), rP=d["rP"], tab=d["tab"],
                              th_split=float(d["th_split"]))
    t0 = time.time()
    tb = pt.build_tables(dln=dln)
    tmp = path + f".tmp{os.getpid()}.npz"
    np.savez(tmp, **tb._asdict())
    os.replace(tmp, path)
    log(f"paint tables built in {time.time() - t0:.1f} s: {tb.tab.shape}, cached in {path}")
    return tb

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
def 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)."""
    path = os.environ.get("MAPSIM_CMB_TABLE", "")
    if path not in _CMB:
        _CMB[path] = ins.cmb_cl_from_table(path) if path else ins.cmb_cl_emulator()
    return _CMB[path]

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
def expected_occupation(lam, cg, theta, cells, tb):
    """Expected halos per painter footprint class, and on the direct (large-halo) path."""
    from ..sz_scaling import theta500_arcmin
    zc = 0.5 * (cells.z_edges[1:] + cells.z_edges[:-1])
    mc = 0.5 * (cells.lnM_edges[1:] + cells.lnM_edges[:-1])
    H0c = theta.h * 100.0 / 299792.458
    Ez = np.interp(zc, np.asarray(cg.z), np.asarray(cg.Hz)) / H0c
    DA = np.interp(zc, np.asarray(cg.z), np.asarray(cg.Da))
    th = np.asarray(theta500_arcmin(np.exp(mc)[None, :], Ez[:, None], DA[:, None], theta.h, theta.one_minus_b))
    cls = np.asarray(pt.footprint_class(jnp.asarray(th.ravel()), tb, jnp.asarray(tb.rP))).reshape(th.shape)
    lam = np.asarray(lam)
    return np.array([lam[cls == c].sum() for c in range(len(pt.SIDES) + 1)])

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
def 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")."""
    cells = hl.default_cells()
    tb = paint_tables(dln, log=log)
    cs = jax.jit(lambda th: simu.cosmology_stage(th, cells))(theta)
    occ = expected_occupation(cs.lam, cs.cg, theta, cells, tb)
    lam_tot = float(np.sum(cs.lam))
    halo_cap = int(np.ceil((lam_tot + 6 * np.sqrt(lam_tot) + 1024) / 4096) * 4096)
    cap_big = int(np.ceil((margin * occ[-1] + 64) / 32) * 32)
    pcfg = pt.make_config(tb, occ[:-1], cap_big, margin=margin)
    cfg = simu.TileConfig(halo_cap=halo_cap, paint=pcfg)
    st = simu.tile_static(cmb_cl or default_cmb(), tb, mode=mode)
    info = dict(lambda_total=lam_tot, halo_cap=halo_cap, occupation=occ.round(1).tolist(), caps=list(pcfg.caps),
                blocks=list(pcfg.blocks), cap_big=cap_big,
                contributions=float(sum(o * s * s for o, s in zip(occ[:-1], pt.SIDES))))
    return TileSetup(cells, tb, cs, cfg, st, info)

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
def 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."""
    theta = simu.THETA_FID if theta is None else theta
    cmb = default_cmb()
    ts = tile_setup(theta, cmb, log=log)
    cfg = ts.cfg._replace(q_final=q_final, peak_cap=6144)
    cells, tb, cs, st = ts.cells, ts.tables, ts.cosmo, ts.static
    key = jax.random.fold_in(jax.random.fold_in(jax.random.key(seed), mock), tile)

    @jax.jit
    def run(key):
        halos, X, ovf = simu.tile_maps(key, cs, theta, st, tb, cells, cfg, None)
        yk, _ = pt.paint_y(halos, tb._replace(tab=st.paint_tab, rP=st.paint_rP), cfg.paint, st.T_tab)
        k_h, k_m = jax.random.split(key)
        k_cmb = jax.random.split(k_m, 3)[0]
        cmbk = jnp.fft.rfft2(jax.random.normal(k_cmb, (N, N), dtype=jnp.float32)) * st.cmb_amp
        tsz, cmbm = st.a_full[I145] * yk, st.B_full[I145] * cmbk
        q0, sig0, C0 = mmf.q_cube(X, st.fs)
        pk0 = mmf.find_peaks(q0, cfg.peak_cap, cfg.q_mask)
        mask, _ = mmf.cluster_mask(pk0, st.fs, cfg.q_mask)
        C, _ = mmf.masked_cov(X, mask, C0, st.fs)
        q1, sig1, _ = mmf.q_cube(X, st.fs, C=C)
        pk = mmf.find_peaks(q1, cfg.peak_cap, cfg.q_final)
        keep = sm.merge_local_max(pk, cfg.r_merge)
        cf = sm.confirm(pk, keep, halos, cfg.M_conf, cfg.r_conf, cfg.conf_cap)
        ir = lambda a: jnp.fft.irfft2(a, s=(N, N))
        return dict(y=ir(yk), m145=ir(X[I145]), tsz145=ir(tsz), cmb145=ir(cmbm), noise145=ir(X[I145] - tsz - cmbm),
                    q_first=jnp.max(q0, 0), q_final=jnp.max(q1, 0), mask=mask, sigma_first=sig0, sigma_final=sig1,
                    pk=pk, keep=keep & pk.valid, conf=cf.ok, halo=cf.halo, halos=halos,
                    overflow=jnp.any(ovf) | halos.overflow | pk.overflow)
    o = jax.device_get(run(key))
    if o["overflow"]:
        raise RuntimeError("buffer overflow")
    h = o["halos"]
    hv = np.asarray(h.valid) & (np.asarray(h.lnM) >= np.log(cfg.M_conf))
    slot = np.flatnonzero(hv)
    sig_model, lnth = ct.analytic_sigma_y0_forecast(cmb, "goal")
    th500 = np.asarray(h.theta500)[hv]
    qmod = np.asarray(h.y0)[hv] / np.exp(np.interp(np.log(np.clip(th500, np.exp(lnth[0]), np.exp(lnth[-1]))), lnth, np.log(sig_model[0])))
    kp = np.asarray(o["keep"])
    pk = o["pk"]
    conf = np.asarray(o["conf"])[kp]
    hidx = np.full(kp.sum(), -1)
    hidx[conf] = np.searchsorted(slot, np.asarray(o["halo"])[kp][conf])
    f32 = lambda a: np.asarray(a, np.float32)
    out = {k: f32(o[k]) for k in ("y", "m145", "tsz145", "cmb145", "noise145", "q_first", "q_final", "mask")}
    out.update(sigma_first=np.asarray(o["sigma_first"]), sigma_final=np.asarray(o["sigma_final"]), sigma_model=sig_model[0],
               thetas=np.asarray(mmf.THETAS15), pix_arcmin=PIX,
               peaks=dict(x=np.asarray(pk.ix)[kp], y=np.asarray(pk.iy)[kp], q=np.asarray(pk.q)[kp],
                          size=np.asarray(mmf.THETAS15)[np.asarray(pk.j)[kp]], confirmed=conf, halo=hidx),
               halos=dict(x=(np.asarray(h.ix)[hv] + np.asarray(h.ox)[hv]) * PIXF / PIX,
                          y=(np.asarray(h.iy)[hv] + np.asarray(h.oy)[hv]) * PIXF / PIX,
                          z=np.asarray(h.z)[hv], M500=np.exp(np.asarray(h.lnM)[hv]), theta500=th500,
                          y0=np.asarray(h.y0)[hv], q_model=qmod))
    return out

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
def 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)."""
    return np.sort(np.random.default_rng(SURVEY_SEED).choice(n_spec, n_tiles, replace=n_tiles > n_spec)).astype(np.int32)

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
def 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."""

    @jax.jit
    def sim(key, thv, st, nt, spec_arr):
        th = simu.THETA_FID._replace(**{n: thv[j] for j, n in enumerate(priors.NAMES)})
        cs = simu.cosmology_stage(th, cells)

        def tile(args):
            t, s = args
            ni = None if forecast else nz.NoiseInput(nt, s, jnp.float32(1.0))
            return simu.simulate_tile(jax.random.fold_in(key, t), cs, th, st, tables, cells, cfg, ni)
        o = jax.lax.map(tile, (jnp.arange(n_tiles), spec_arr), batch_size=chunk)
        n_p = jnp.sum(o["n_p"])
        x = jnp.concatenate([jnp.sum(o["counts"], axis=0).ravel().astype(jnp.float64),
                             (jnp.sum(o["p_sum"]) / jnp.maximum(n_p, 1))[None]])
        return dict(x=x, overflow=jnp.any(o["overflow"]), n_halos=jnp.sum(o["n_halos"]), n_det=n_p,
                    sigma=jnp.mean(o["sigma"], axis=0))
    return sim

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
def 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."""
    n = len(theta)
    forecast = noise == "forecast"
    if forecast:
        nt, specs = None, np.zeros(n_tiles, np.int32)
    else:                                       # "measured" (also accepted: "mss2")
        nt, _ = nz.load_mss2(spectra, "mean")
        specs = survey_spectra(nt.F.shape[0], n_tiles)
    cmb = cmb_cl or default_cmb()
    ts = tile_setup(simu.THETA_FID, cmb, log=log)
    cells, tb, st = ts.cells, ts.tables, ts.static
    base = jax.random.key(seed)

    lam_tot = jax.jit(jax.vmap(lambda v: simu.cosmology_stage(
        simu.THETA_FID._replace(**{nm: v[j] for j, nm in enumerate(priors.NAMES)}), cells).lam.sum()))
    L = np.concatenate([np.asarray(lam_tot(jnp.asarray(theta[a:a + 128]))) for a in range(0, n, 128)])
    edges = np.quantile(L, np.linspace(0, 1, n_classes + 1)[1:-1]) if n > n_classes else np.array([])
    cls = np.searchsorted(edges, L, side="left")
    class_theta = [theta[cls == c][np.argmax(L[cls == c])] if np.any(cls == c) else theta[np.argmax(L)]
                   for c in range(n_classes)]
    cfgs = []
    for c in range(n_classes):
        cfgs.append(tile_setup(priors.to_theta(class_theta[c]), cmb, log=log).cfg)
        log(f"class {c}: {int(np.sum(cls == c))} draws, halos per tile up to "
            f"{L[cls == c].max() if np.any(cls == c) else 0:.0f}, halo buffer {cfgs[c].halo_cap}")

    keys = ("x", "overflow", "n_halos", "n_det", "sigma", "class", "done")
    r = _load(path, theta, keys) or dict(x=np.full((n, 21), np.nan), overflow=np.zeros(n, bool),
                                         n_halos=np.zeros(n, np.int64), n_det=np.zeros(n, np.int64),
                                         sigma=np.zeros((n, 15)), **{"class": np.full(n, -1)},
                                         done=np.zeros(n, bool))
    if r["done"].any():
        log(f"resuming: {r['done'].sum()} done")
    settings = json.dumps(dict(n_tiles=n_tiles, noise="2019 SO forecast, goal" if forecast else "measured per-tile spectra",
                               lens_table="goal", seed=seed, survey_seed=SURVEY_SEED, classes=n_classes))

    def save():
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        np.savez(path, theta=theta, names=np.array(priors.NAMES), specs=specs, settings=settings, **r)

    sims = {}
    t0 = time.time()
    count = 0
    todo = np.flatnonzero(~r["done"])
    while todo.size:
        for i in todo:
            c = int(cls[i])
            if c not in sims:
                sims[c] = make_survey_sim(cells, tb, cfgs[c], n_tiles, chunk, forecast=forecast)
            o = jax.device_get(sims[c](jax.random.fold_in(base, int(i)), jnp.asarray(theta[i]), st, nt, jnp.asarray(specs)))
            if bool(o["overflow"]) and c < n_classes - 1:
                cls[i] = c + 1
                continue
            for k in ("x", "overflow", "n_halos", "n_det", "sigma"):
                r[k][i] = o[k]
            r["class"][i], r["done"][i] = c, True
            count += 1
            if count % save_every == 0:
                save()
                log(f"[{time.time() - t0:7.0f} s] {r['done'].sum()}/{n} ({count / (time.time() - t0):.2f} per s)")
        todo = np.flatnonzero(~r["done"])
    save()
    nd = r["n_det"]
    log(f"done: {n} in {time.time() - t0:.0f} s; detections {nd.min()}-{nd.max()} (median {int(np.median(nd))}); "
        f"overflow left {int(r['overflow'].sum())}; mean p {np.nanmin(r['x'][:, 20]):.3f}-{np.nanmax(r['x'][:, 20]):.3f}")
    return r

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
def 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)."""
    from . import calibration as cal
    if model == "paper":
        sz, le = ct.paper_tables()
        return sz, le, ct.CatalogueConfig()
    cfg = ct.CatalogueConfig(f_sky=f_sky(n_tiles), capacity=2 ** 19)
    le = ct.lens_table(mode)
    if model == "published":
        sig, lnth = ct.analytic_sigma_y0_forecast(cmb_cl or default_cmb(), mode)
        return ct.PatchTable(lnth=jnp.asarray(lnth), lnsig=jnp.asarray(np.log(sig))), le, cfg
    if calibration is None:
        raise ValueError(f"model {model!r} needs a calibration file")
    if model == "calibrated-point":
        qc, tab = ct.load_qcal(calibration)
        cfg = cfg._replace(qcal=qc)
    elif model == "calibrated-noise":
        qc, tab, size = cal.load_noise_level(calibration)
        cfg = cfg._replace(qcal_conf=qc, qcal_size=size)
    elif model == "calibrated-theta":
        qt, tab = cal.load_theta(calibration)
        cfg = cfg._replace(qcal_theta=qt)
    else:
        raise ValueError(f"unknown catalogue model {model!r}; one of {CATALOGUE_MODELS}")
    tab = tab._replace(lnsig=jnp.log(jnp.mean(jnp.exp(tab.lnsig), axis=0, keepdims=True)))
    return tab, le, cfg

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
def 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."""
    n = len(theta)
    cells = ct.survey_cells()
    base = jax.random.key(seed)
    t0 = time.time()
    lam_tot = jax.jit(jax.vmap(lambda *v: ct.survey_rates(simu.THETA_FID._replace(**dict(zip(priors.NAMES, v))), cells)[0].sum()))
    N_exp = np.concatenate([np.asarray(lam_tot(*[jnp.asarray(theta[a:a + 256, j]) for j in range(len(priors.NAMES))]))
                            for a in range(0, n, 256)]) * cfg.f_sky
    caps = np.asarray(CATALOGUE_CAPACITIES)
    cls = np.searchsorted(caps, N_exp + 8.0 * np.sqrt(N_exp))
    if np.any(cls >= len(caps)):
        raise ValueError(f"expected halos up to {N_exp.max():.3g}: beyond the largest buffer")
    log(f"{n} draws; expected halos {N_exp.min():.3g}-{N_exp.max():.3g}; buffers {np.bincount(cls, minlength=len(caps)).tolist()}")

    keys = ("x", "n_halos", "n_sel", "capacity", "done")
    r = _load(path, theta, keys) or dict(x=np.full((n, 21), np.nan), n_halos=np.zeros(n, np.int64),
                                         n_sel=np.zeros(n, np.int64), capacity=np.zeros(n, np.int64),
                                         done=np.zeros(n, bool))
    if r["done"].any():
        log(f"resuming: {r['done'].sum()} done")
    sims = {}

    def sim_fn(c):
        if c not in sims:
            cfg_c = cfg._replace(capacity=int(caps[c]))

            def one(i, *v):
                th = simu.THETA_FID._replace(**dict(zip(priors.NAMES, v)))
                cat = ct.simulate(jax.random.fold_in(base, i), th, cells, sz, le, cfg_c)
                return ct.data_vector(cat), cat.n_halos, cat.n_sel, cat.overflow
            sims[c] = jax.jit(jax.vmap(one))
        return sims[c]

    def save():
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        np.savez(path, theta=theta, names=np.array(priors.NAMES), **r,
                 settings=json.dumps(dict(f_sky=cfg.f_sky, seed=seed, qcal=cfg.qcal, qcal_theta=cfg.qcal_theta,
                                          qcal_conf=cfg.qcal_conf, qcal_size=cfg.qcal_size, **(info or {}))))

    t0 = time.time()
    todo = np.flatnonzero(~r["done"])
    while todo.size:
        for c in np.unique(cls[todo]):
            idx = todo[cls[todo] == c]
            for a in range(0, idx.size, batch):
                b = idx[a:a + batch]
                pad = np.concatenate([b, np.repeat(b[-1:], batch - b.size)])
                xv, nh, ns, ov = jax.device_get(sim_fn(int(c))(jnp.asarray(pad, dtype=jnp.uint32),
                                                               *[jnp.asarray(theta[pad, j]) for j in range(len(priors.NAMES))]))
                for k, i in enumerate(b):
                    if ov[k]:
                        cls[i] = min(cls[i] + 1, len(caps) - 1)
                        continue
                    r["x"][i], r["n_halos"][i], r["n_sel"][i], r["capacity"][i], r["done"][i] = xv[k], nh[k], ns[k], caps[c], True
                if r["done"].sum() % chunk < batch:
                    save()
        todo = np.flatnonzero(~r["done"])
    save()
    log(f"done: {n} in {time.time() - t0:.0f} s; selected {r['n_sel'].min()}-{r['n_sel'].max()} "
        f"(median {int(np.median(r['n_sel']))}); mean p {np.nanmin(r['x'][:, 20]):.3f}-{np.nanmax(r['x'][:, 20]):.3f}")
    return r

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):

  1. 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).
  2. 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).
  3. 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
def survey_cells(z_per_bin=30, n_bins_z=10, Mmin=5e13, Mmax=1e16, 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."""
    z0 = float(sm.Z_EDGES[0])
    nz = z_per_bin * n_bins_z
    return hl.CellGrid(z0 + Z_BIN_WIDTH * np.arange(nz + 1) / z_per_bin,
                       np.linspace(np.log(Mmin), np.log(Mmax), n_m + 1))

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
def paper_tables(data_dir=None):
    """The paper's sigma_y0 and sigma_kappa fits from cosmocnc_jax's data files (theta in radians)."""
    d = data_dir or COSMOCNC_DATA
    to_arcmin = 180.0 * 60.0 / np.pi
    sz = np.load(os.path.join(d, "so_sim_sz_mf_noise.npy"))
    le = np.load(os.path.join(d, "so_sim_lensing_mf_noise.npy"))
    return fit_table(sz[0] * to_arcmin, sz[1]), fit_table(le[0] * to_arcmin, le[1])

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
def noise_sigma(tab, theta_arcmin, clamp=False, patch=None):
    """sigma at theta from a NoiseFit (cubic, the paper's) or a PatchTable (per patch)."""
    if isinstance(tab, NoiseFit):
        return eval_fit(tab, theta_arcmin, clamp)
    return eval_table(tab, theta_arcmin, patch)

lens_table(mode='goal')

Our sigma_kappa table (lens_tables.py) as a one-row PatchTable.

Source code in classy_szlite/sim/catalogue.py
def lens_table(mode="goal"):
    """Our sigma_kappa table (lens_tables.py) as a one-row PatchTable."""
    lnth, lnsig = lensing.table(mode)
    return PatchTable(lnth=jnp.asarray(lnth), lnsig=jnp.asarray(lnsig)[None])

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
def 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."""
    from . import mmf, instrument as ins
    from .flatsky import grid
    G = grid()
    fs = fs or mmf.filter_static()
    B = ins.beams(G.m_L)
    C = (ins.noise_cov(G.m_L, mode) + B[:, None, :] * B[None, :, :] * cmb_cl(G.m_L)[None, None, :]) * G.Npx / G.Om
    Cb = np.stack([np.stack([np.bincount(G.m_binpos, weights=G.m_W * C[i, j], minlength=G.n_bins)
                             / G.bin_count for j in range(6)], -1) for i in range(6)], 1)
    _, aCa = mmf.weights(jnp.asarray(Cb), fs)
    norm = jnp.sum(fs.m_W[None, :] * fs.tau_m ** 2 * aCa[None, :], axis=1)
    return np.asarray(1.0 / jnp.sqrt(norm))[None], np.log(np.asarray(mmf.THETAS15))

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
def 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."""
    from . import mmf, instrument as ins
    from .flatsky import grid
    G = grid()
    fs = fs or mmf.filter_static()
    b = np.asarray(noise_tables.bin_idx).ravel()[np.asarray(G.m_idx)]
    B = ins.beams(G.m_L)
    cmb = B[:, None, :] * B[None, :, :] * cmb_cl(G.m_L)[None, None, :] * G.Npx / G.Om      # (6, 6, n_modes)
    F = np.asarray(noise_tables.F, dtype=np.float64)
    out = []
    for s in np.atleast_1d(specs):
        N = np.einsum("bik,bjk->bij", F[s], F[s])[b] * G.Npx                                 # (n_modes, 6, 6)
        C = np.moveaxis(cmb, -1, 0) + N
        Cb = np.stack([np.stack([np.bincount(G.m_binpos, weights=G.m_W * C[:, i, j], minlength=G.n_bins)
                                 / G.bin_count for j in range(6)], -1) for i in range(6)], 1)
        _, aCa = mmf.weights(jnp.asarray(Cb), fs)
        norm = jnp.sum(fs.m_W[None, :] * fs.tau_m ** 2 * aCa[None, :], axis=1)
        out.append(np.asarray(1.0 / jnp.sqrt(norm)))
    return np.array(out), np.log(np.asarray(mmf.THETAS15))

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.

Source code in classy_szlite/sim/catalogue.py
def data_vector(cat: Catalogue):
    """The paper's 21 numbers: the 4 x 5 counts (q-major) and the mean p over all selected."""
    return jnp.concatenate([cat.counts.ravel().astype(jnp.float64),
                            (cat.p_sum / jnp.maximum(cat.n_sel, 1))[None]])

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
def 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)."""
    cs = simu.cosmology_stage(theta, cells)
    s = SR_FULL / hl.OMEGA_TILE
    return cs.lam * s, cs.d2N * s, cs.cg, cs.chi_star

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
def draw(key, theta, cells, sz_fit, lens_fit, cfg: CatalogueConfig = CatalogueConfig()) -> HaloDraw:
    """The halos of one catalogue and their observables (traceable in theta)."""
    lam_all, d2N_all, cg, chi_s = survey_rates(theta, cells)
    lam, d2N = lam_all * cfg.f_sky, d2N_all * cfg.f_sky
    k_pois, k_attr = jax.random.split(key)
    n_z, n_m = lam.shape
    counts = jax.random.poisson(k_pois, lam.ravel(), dtype=jnp.int32)
    csum = jnp.cumsum(counts)
    total = csum[-1]
    slot = jnp.arange(cfg.capacity, dtype=jnp.int32)
    valid = slot < total
    cell = jnp.minimum(jnp.searchsorted(csum, slot, side="right").astype(jnp.int32), n_z * n_m - 1)
    iz, im = cell // n_m, cell % n_m
    j_in_cell = slot - (csum[cell] - counts[cell])

    def draws(c, j):
        k = jax.random.fold_in(jax.random.fold_in(k_attr, c), j)
        ku, kn = jax.random.split(k)
        return jax.random.uniform(ku, (2,), dtype=jnp.float64), jax.random.normal(kn, (4,), dtype=jnp.float64)
    U, G = jax.vmap(draws)(cell, j_in_cell)                      # (C, 2), (C, 4)

    f00, f10 = d2N[iz, im], d2N[iz + 1, im]
    f01, f11 = d2N[iz, im + 1], d2N[iz + 1, im + 1]
    tz = jnp.clip(hl._inv_linear_cdf(U[:, 0], f00 + f01, f10 + f11), 0.0, 1.0)
    tm = jnp.clip(hl._inv_linear_cdf(U[:, 1], (1 - tz) * f00 + tz * f10, (1 - tz) * f01 + tz * f11), 0.0, 1.0)
    ze, me = jnp.asarray(cells.z_edges), jnp.asarray(cells.lnM_edges)
    z = ze[iz] + tz * (ze[iz + 1] - ze[iz])
    M = jnp.exp(me[im] + tm * (me[im + 1] - me[im]))

    patch = None
    if isinstance(sz_fit, PatchTable) and sz_fit.lnsig.shape[0] > 1:     # equal-area patches, own key
        k_patch = jax.random.fold_in(key, 0x5A7C)
        patch = jax.vmap(lambda c, j: jax.random.randint(
            jax.random.fold_in(jax.random.fold_in(k_patch, c), j), (), 0, sz_fit.lnsig.shape[0]))(cell, j_in_cell)
    qc, sz_fit = _calibration(cfg, theta, sz_fit)
    qbar, pbar = _qbar_pbar(M, z, theta, cg, chi_s, sz_fit, lens_fit, cfg, patch)
    r = cfg.corr_lnq_lnp
    q_true = qbar * jnp.exp(theta.sigma_lnq * G[:, 0])
    p_true = pbar * jnp.exp(theta.sigma_lnp * (r * G[:, 0] + np.sqrt(1.0 - r * r) * G[:, 1]))
    if qc is None:
        q_obs = jnp.sqrt(q_true ** 2 + cfg.dof) + G[:, 2]
    else:                                                     # calibrated; the loss from its own key
        s_, k_, w_, f_ = qcal_params(qc, z, _theta500(M, z, theta, cg) if cfg.qcal_size else None, cfg.qcal_size)
        q_obs = jnp.sqrt(jnp.maximum((s_ * q_true) ** 2 + k_, 0.0)) + w_ * G[:, 2]
        k_loss = jax.random.fold_in(key, 0x1055)
        u = jax.vmap(lambda c, j: jax.random.uniform(jax.random.fold_in(jax.random.fold_in(k_loss, c), j), (),
                                                     dtype=jnp.float64))(cell, j_in_cell)
        q_obs = jnp.where(u < f_, -jnp.inf, q_obs)
    p_obs = p_true + G[:, 3]
    return HaloDraw(z=z, M=M, qbar=qbar, pbar=pbar, q_true=q_true, p_true=p_true, q_obs=q_obs,
                    p_obs=p_obs, valid=valid, total=total)

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
def 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]."""
    t = jnp.asarray(np.asarray(qcal, dtype=np.float64)) if isinstance(qcal, tuple) else qcal
    if size_edges is None:
        i = jnp.clip(jnp.searchsorted(t[:, 0], z, side="left"), 0, t.shape[0] - 1)
    else:
        ns = len(size_edges)
        nz = t.shape[0] // ns
        iz = jnp.clip(jnp.searchsorted(t[::ns, 0], z, side="left"), 0, nz - 1)
        js = jnp.clip(jnp.searchsorted(jnp.asarray(np.asarray(size_edges, dtype=np.float64)), th, side="left"), 0, ns - 1)
        i = iz * ns + js
    return tuple(t[:, c][i] for c in (1, 2, 3, 4))

quad_features(x)

1, x_i, x_i x_j (i <= j): 15 features of the 4 scaled parameters.

Source code in classy_szlite/sim/catalogue.py
def quad_features(x):
    """1, x_i, x_i x_j (i <= j): 15 features of the 4 scaled parameters."""
    q = [x[i] * x[j] for i in range(4) for j in range(i, 4)]
    return jnp.concatenate([jnp.ones(1, x.dtype), x, jnp.stack(q)])

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
def 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."""
    fid, width, u_coef, sig_ab, rows = qc
    x = jnp.stack([(getattr(theta, n) - fid[i]) / width[i] for i, n in enumerate(QCAL_PARAMS)])
    u = quad_features(x) @ jnp.asarray(np.asarray(u_coef, dtype=np.float64))
    ab = jnp.asarray(np.asarray(sig_ab, dtype=np.float64))
    dln = ab[:, 0] + ab[:, 1] * u
    R = jnp.asarray(np.asarray(rows, dtype=np.float64))
    o = R.shape[1] - 12                        # 1 (z_upper) or 2 (z_upper, th_upper: per (z, size) cell)
    poly = lambda c: R[:, o + c] + R[:, o + c + 1] * u + R[:, o + c + 2] * u * u
    tab = jnp.stack([R[:, 0], poly(0), poly(3), jnp.maximum(poly(6), 0.05), jnp.clip(poly(9), 0.0, 0.5)], 1)
    return tab, dln

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
def 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]."""
    fid, width, g_sig, d0_sig, rows = qt
    x = jnp.stack([(getattr(theta, n) - fid[i]) / width[i] for i, n in enumerate(QCAL_PARAMS)])
    dln = jnp.asarray(np.asarray(d0_sig)) + jnp.asarray(np.asarray(g_sig)) @ x
    R = jnp.asarray(np.asarray(rows, dtype=np.float64))
    lin = lambda c: R[:, c] + R[:, c + 1:c + 5] @ x
    tab = jnp.stack([R[:, 0], lin(1), lin(6), jnp.maximum(lin(11), 0.05), jnp.clip(lin(16), 0.0, 0.5)], 1)
    return tab, dln

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
def 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)."""
    d = np.load(path)
    qc = tuple(tuple(float(v) for v in row) for row in np.stack([d["z_upper"], d["s"], d["k"], d["w"], d["f"]], 1))
    return qc, PatchTable(lnth=jnp.asarray(d["lnth"]), lnsig=jnp.asarray(np.log(d["sigma"])))

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
def simulate(key, theta, cells, sz_fit, lens_fit, cfg: CatalogueConfig = CatalogueConfig()) -> Catalogue:
    """One catalogue (traceable in theta; jit with cells and cfg static)."""
    return summarise(draw(key, theta, cells, sz_fit, lens_fit, cfg), cfg)

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
def expected(theta, cells, sz_fit, lens_fit, cfg: CatalogueConfig = 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."""
    from jax.scipy.stats import norm
    lam_all, d2N_all, cg, chi_s = survey_rates(theta, cells)
    d2N = d2N_all * cfg.f_sky
    x, w = np.polynomial.legendre.leggauss(n_sub)
    x, w = 0.5 * (x + 1.0), 0.5 * w                                  # on [0, 1]
    ze, me = np.asarray(cells.z_edges), np.asarray(cells.lnM_edges)
    dz, dm = np.diff(ze), np.diff(me)
    Z = ze[:-1, None] + dz[:, None] * x[None, :]                     # (n_z, n_sub)
    LM = me[:-1, None] + dm[:, None] * x[None, :]                    # (n_m, n_sub)
    tz, tm = jnp.asarray(x), jnp.asarray(x)
    f = (d2N[:-1, :-1][:, :, None, None] * (1 - tz)[None, None, :, None] * (1 - tm)[None, None, None, :]
         + d2N[1:, :-1][:, :, None, None] * tz[None, None, :, None] * (1 - tm)[None, None, None, :]
         + d2N[:-1, 1:][:, :, None, None] * (1 - tz)[None, None, :, None] * tm[None, None, None, :]
         + d2N[1:, 1:][:, :, None, None] * tz[None, None, :, None] * tm[None, None, None, :])
    wt = f * (jnp.asarray(dz)[:, None, None, None] * jnp.asarray(dm)[None, :, None, None]
              * jnp.asarray(w)[None, None, :, None] * jnp.asarray(w)[None, None, None, :])   # (n_z, n_m, s, s)
    zz = jnp.broadcast_to(jnp.asarray(Z)[:, None, :, None], wt.shape)
    MM = jnp.exp(jnp.broadcast_to(jnp.asarray(LM)[None, :, None, :], wt.shape))
    n_patch = sz_fit.lnsig.shape[0] if isinstance(sz_fit, PatchTable) else 1
    gh, gw = np.polynomial.hermite_e.hermegauss(n_gh)
    gw = gw / gw.sum()
    g, gwj = jnp.asarray(gh), jnp.asarray(gw)
    r = cfg.corr_lnq_lnp
    qe = jnp.asarray(sm.Q_EDGES)
    counts = jnp.zeros((4, 5))
    n_sel = 0.0
    p_sum = 0.0
    zb = jnp.searchsorted(jnp.asarray(sm.Z_EDGES), zz, side="right") - 1      # z bin of each point
    inz = [(zb == j).astype(wt.dtype) for j in range(5)]
    for pa in range(n_patch):
        patch = None if n_patch == 1 else jnp.full(zz.shape, pa)
        qc, szf = _calibration(cfg, theta, sz_fit)
        qbar, pbar = _qbar_pbar(MM, zz, theta, cg, chi_s, szf, lens_fit, cfg, patch)
        if qc is None:
            s_, k_, w_, f_ = 1.0, cfg.dof, 1.0, 0.0
        else:
            s_, k_, w_, f_ = qcal_params(qc, zz, _theta500(MM, zz, theta, cg) if cfg.qcal_size else None, cfg.qcal_size)
        for a in range(n_gh):
            qt = jnp.sqrt(jnp.maximum((s_ * qbar * jnp.exp(theta.sigma_lnq * g[a])) ** 2 + k_, 0.0))
            wq = w_ if qc is None else w_[..., None]
            cdf = norm.cdf((qe[None, None, None, None, :] - qt[..., None]) / wq)   # P(q_obs < edge)
            P_bin = (1.0 - (f_ if qc is None else f_[..., None])) * (cdf[..., 1:] - cdf[..., :-1])
            P_sel = (1.0 - f_) * (1.0 - norm.cdf((cfg.q_min - qt) / w_))
            # E[exp(sigma_lnp (r g1 + sqrt(1-r^2) g2))] over g2 at fixed g1
            e_p = jnp.exp(theta.sigma_lnp * r * g[a] + 0.5 * (theta.sigma_lnp ** 2) * (1.0 - r * r))
            ww = wt * gwj[a] / n_patch
            for j in range(5):
                counts = counts.at[:, j].add(jnp.sum((ww * inz[j])[..., None] * P_bin, axis=(0, 1, 2, 3)))
            n_sel = n_sel + jnp.sum(ww * P_sel)
            p_sum = p_sum + jnp.sum(ww * P_sel * pbar * e_p)
    return counts, n_sel, p_sum

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_grid then fit_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_grid then fit_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
def 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."""
    theta = simu.THETA_FID if theta is None else theta
    setup_theta = theta if setup_theta is None else setup_theta
    bkey = (noise, spectra, setup_theta, cap, neighbours, n_tiles, os.environ.get("MAPSIM_CMB_TABLE", ""))
    if bkey not in _BUILT:
        _BUILT[bkey] = _build(*bkey)
    b = _BUILT[bkey]
    tile, specs, sig_model = b["tile"], b["specs"], b["sig_model"]
    cs = b["cosmo"](theta)
    base = jax.random.key(seed) if key is None else key
    nt_d, st_d = b["nt"], jax.device_put(b["st"])
    th = jax.tree_util.tree_map(jnp.asarray, theta)
    rows, per_tile = [], []
    t0 = time.time()
    fields = ("z", "lnM", "theta500", "y0", "q_model", "q_fsig", "q_obs", "n_match", "q_nb", "shadow")
    for i in range(n_mocks):
        km = jax.random.fold_in(base, i)
        for t in range(n_tiles):
            o = jax.device_get(tile(jax.random.fold_in(km, t), cs, th, st_d, nt_d, jnp.int32(specs[t]),
                                    jnp.asarray(np.log(sig_model[t]))))
            if o["overflow"]:
                raise RuntimeError(f"buffer overflow in mock {i}, tile {t}: size the buffers at a heavier setup_theta")
            k = o["ok"]
            rows.append(np.rec.fromarrays([np.full(k.sum(), i, np.int16), np.full(k.sum(), t, np.int16)] + [o[n][k] for n in fields],
                                          names="mock,tile," + ",".join(fields)))
            per_tile.append(dict(mock=i, tile=t, sigma=o["sigma"], sigma0=o["sigma0"], sigma_model=sig_model[t], counts=o["counts"]))
        log(f"[{time.time() - t0:6.0f} s] mock {i + 1}/{n_mocks}")
    H = np.concatenate(rows)
    T = {k: np.array([p[k] for p in per_tile]) for k in ("mock", "tile", "sigma", "sigma0", "sigma_model", "counts")}
    return H, dict(T, specs=specs, lnth=b["lnth"])

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
def 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."""
    from scipy.optimize import minimize
    from scipy.stats import norm
    det = np.isfinite(qo) & (qo > lo)

    def nll(p):
        s, k, w, f = p
        if not (0.0 <= f < 1.0 and w > 0.05):
            return np.inf
        mu = np.sqrt(np.maximum((s * q) ** 2 + k, 1e-6))
        ll = np.where(det, np.log1p(-f) + norm.logpdf(qo, mu, w),
                      np.logaddexp(np.log(max(f, 1e-300)), np.log1p(-f) + norm.logcdf((lo - mu) / w)))
        return -np.sum(ll)
    opts = dict(xatol=1e-6, fatol=1e-4, maxiter=8000, maxfev=12000)
    r = minimize(nll, [1.0, 1.0, 1.0, 0.01], method="Nelder-Mead", options=opts)
    r = minimize(nll, r.x, method="Nelder-Mead", options=opts)
    h = np.array([1e-3, 2e-2, 1e-3, 2e-4])
    Hm = np.zeros((4, 4))
    for a in range(4):
        for b in range(4):
            def fv(da, db):
                p = r.x.copy(); p[a] += da; p[b] += db
                return nll(p)
            Hm[a, b] = (fv(h[a], h[b]) - fv(h[a], -h[b]) - fv(-h[a], h[b]) + fv(-h[a], -h[b])) / (4 * h[a] * h[b])
    err = np.full(4, np.nan)
    use = [0, 1, 2, 3] if np.all(np.isfinite(Hm)) else [0, 1, 2]       # f at its boundary 0
    try:
        err[use] = np.sqrt(np.abs(np.diag(np.linalg.inv(Hm[np.ix_(use, use)]))))
    except np.linalg.LinAlgError:
        pass
    s_, k, w, f = r.x
    return dict(s=s_, k=k, w=w, f=f, s_err=err[0], k_err=err[1], w_err=err[2], f_err=err[3],
                n=int(q.size), n_det=int(det.sum()), converged=bool(r.success))

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
def 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."""
    q, qo, z = H[q_name].astype(float), H["q_obs"].astype(float), H["z"].astype(float)
    rows = []
    for a, b in zip(ZB[:-1], ZB[1:]):
        m = (z > a) & (z <= b) & (q > 2)
        r = censored_fit(q[m], qo[m])
        rows.append((r["s"], r["k"], r["w"], r["f"], r["n"]))
    return np.array(rows)

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
def fit_cells(H):
    """(n_z, n_size, 5): s, k, w, f, n per (redshift, size) cell; NaN where fewer than N_MIN halos."""
    qf, qo, z, th = (H[k].astype(float) for k in ("q_fsig", "q_obs", "z", "theta500"))
    out = np.full((len(ZB) - 1, len(SB) - 1, 5), np.nan)
    for i, (a, b) in enumerate(zip(ZB[:-1], ZB[1:])):
        for j, (c, d) in enumerate(zip(SB[:-1], SB[1:])):
            m = (z > a) & (z <= b) & (th > c) & (th <= d) & (qf > 2)
            out[i, j, 4] = m.sum()
            if m.sum() >= N_MIN:
                r = censored_fit(qf[m], qo[m])
                out[i, j, :4] = (r["s"], r["k"], r["w"], r["f"])
    return out

tile_sigma(T)

The finder's final-pass noise per tile (n_tiles, 15), mean over the mocks.

Source code in classy_szlite/sim/calibration.py
def tile_sigma(T):
    """The finder's final-pass noise per tile (n_tiles, 15), mean over the mocks."""
    return np.array([T["sigma"][T["tile"] == t].mean(0) for t in range(int(T["tile"].max()) + 1)])

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
def calibrate_point(H, T, path, noise="forecast"):
    """Write the one-point calibration (catalogue.load_qcal's format) from a halo table."""
    rows = fit_rows(H)
    np.savez(path, z_upper=np.array(ZB[1:]), s=rows[:, 0], k=rows[:, 1], w=rows[:, 2], f=rows[:, 3],
             sigma=tile_sigma(T), lnth=T["lnth"], specs=T["specs"], noise=noise, n_mocks=int(H["mock"].max()) + 1)
    return rows

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
def 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)."""
    box = priors.BOXES[box] if isinstance(box, str) else box
    rng = np.random.default_rng(seed)
    u = np.stack([(rng.permutation(n) + rng.uniform(size=n)) / n for _ in PARAMS], 1)
    lo = np.array([box[p][0] for p in PARAMS])
    hi = np.array([box[p][1] for p in PARAMS])
    fid = np.array([getattr(simu.THETA_FID, p) for p in PARAMS])
    return np.vstack([fid, lo + u * (hi - lo)])

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
def 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."""
    os.makedirs(os.path.join(out_dir, "points"), exist_ok=True)
    P = grid_points(n_points, box)
    thetas = [simu.THETA_FID._replace(**dict(zip(PARAMS, map(float, row)))) for row in P]
    from . import halos as hl
    cells = hl.default_cells()
    lam_f = jax.jit(lambda t: simu.cosmology_stage(t, cells).lam.sum())
    lam = [float(lam_f(t)) for t in thetas]
    heavy = thetas[int(np.argmax(lam))]
    log(f"{len(P)} points; halos per tile {min(lam):.0f}-{max(lam):.0f}")
    path = os.path.join(out_dir, "calib_grid.npz")
    rows = np.full((len(P), len(ZB) - 1, 5), np.nan)
    cells_ = np.full((len(P), len(ZB) - 1, len(SB) - 1, 5), np.nan)
    sig = np.full((len(P), n_tiles, 15), np.nan)
    flag = np.zeros(len(P), bool)
    if os.path.exists(path):
        old = np.load(path)
        if np.array_equal(old["theta"], P):
            rows, sig, flag = np.array(old["rows"]), np.array(old["sigma"]), np.array(old["done"])
            cells_ = np.array(old["cells"])
            log(f"resuming: {flag.sum()} points done")
    t0 = time.time()
    lnth = specs = None
    for i, th in enumerate(thetas):
        if flag[i]:
            continue
        H, T = halo_table(n_mocks, th, n_tiles=n_tiles, noise=noise, spectra=spectra, setup_theta=heavy, cap=cap,
                          key=jax.random.fold_in(jax.random.key(GRID_SEED), i), log=lambda m: None)
        rows[i] = fit_rows(H)
        if size:
            cells_[i] = fit_cells(H)
        sig[i] = tile_sigma(T)
        lnth, specs = T["lnth"], T["specs"]
        keep = H["q_fsig"] > 1.5
        np.savez_compressed(os.path.join(out_dir, "points", f"point_{i:02d}.npz"),
                            **{k: H[k][keep] for k in ("mock", "tile", "z", "lnM", "theta500", "y0", "q_model", "q_fsig", "q_obs")},
                            sigma=T["sigma"], sigma_tile=T["tile"], theta=P[i])
        flag[i] = True
        np.savez(path, theta=P, rows=rows, cells=cells_, sigma=sig, done=flag, params=np.array(PARAMS),
                 z_upper=np.array(ZB[1:]), size_upper=np.array(SB[1:]), lnth=lnth, specs=specs, noise=noise, mocks=n_mocks)
        log(f"[{time.time() - t0:6.0f} s] point {i}/{len(P) - 1}: {len(H)} halos; "
            f"noise at 2' / fiducial {np.mean(sig[i][:, 7]) / np.mean(sig[0][:, 7]) if flag[0] else float('nan'):.4f}")
    return path

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
def 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."""
    d = np.load(grid_path)
    assert d["done"].all(), "not all grid points are done"
    P, rows, sig = d["theta"], d["rows"], d["sigma"]
    fid, width, Fl, Fq = _features(P)
    lsig = np.log(sig.mean(1)) - np.log(sig[0].mean(0))[None, :]
    u = lsig[:, 7]
    if size:
        C = d["cells"]
        vals = np.where(np.isnan(C[..., :4]), rows[:, :, None, :4], C[..., :4])
        nz_, ns = vals.shape[1], vals.shape[2]
        vals = vals.reshape(len(P), nz_ * ns, 4)
        upper = [(ZB[i + 1], SB[j + 1]) for i in range(nz_) for j in range(ns)]
    else:
        vals = rows[:, :, :4]
        upper = [(ZB[b + 1],) for b in range(len(ZB) - 1)]
    u_coef, *_ = np.linalg.lstsq(Fq, u, rcond=None)
    Fu = np.c_[np.ones(len(P)), u]
    Fu2 = np.c_[Fu, u * u]
    sig_ab = np.array([np.linalg.lstsq(Fu, lsig[:, j], rcond=None)[0] for j in range(15)])
    out_rows, loo = [], {"u": (_loo(Fl, u), _loo(Fq, u))}
    for b, up in enumerate(upper):
        r = list(up)
        for c, nm in enumerate("skwf"):
            y = vals[:, b, c]
            r += list(np.linalg.lstsq(Fu2, y, rcond=None)[0])
            loo[f"{nm}{b}"] = (_loo(Fl, y), _loo(Fu2, y))
        out_rows.append(r)
    log(f"noise level u: leave-one-out rms {loo['u'][0]:.4f} (linear in the parameters) -> {loo['u'][1]:.4f} (quadratic)")
    np.savez(out_path, fid=fid, width=width, u_coef=u_coef, sig_ab=sig_ab, rows=np.array(out_rows), sigma=sig[0],
             lnth=d["lnth"], specs=d["specs"], noise=str(d["noise"]), size_upper=np.array(SB[1:]) if size else np.array([]))
    return loo

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
def 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."""
    d = np.load(grid_path)
    assert d["done"].all(), "not all grid points are done"
    P, rows, sig = d["theta"], d["rows"], d["sigma"]
    fid, width, X, _ = _features(P)
    lsig = np.log(sig.mean(1)) - np.log(sig[0].mean(0))[None, :]
    coef_sig, *_ = np.linalg.lstsq(X, lsig, rcond=None)
    coef_obs = np.zeros((len(ZB) - 1, 4, 5))
    for b in range(len(ZB) - 1):
        for c in range(4):
            coef_obs[b, c] = np.linalg.lstsq(X, rows[:, b, c], rcond=None)[0]
    np.savez(out_path, fid=fid, width=width, g_sig=coef_sig[1:].T, d0_sig=coef_sig[0],
             rows=np.concatenate([np.array(ZB[1:])[:, None], coef_obs.reshape(len(ZB) - 1, 20)], 1),
             sigma=sig[0], lnth=d["lnth"], specs=d["specs"], noise=str(d["noise"]))
    log(f"written {out_path}")

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
def load_noise_level(path):
    """(CatalogueConfig.qcal_conf, PatchTable of the fiducial per-tile noise, size edges or None)."""
    d = np.load(path)
    qc = (tuple(map(float, d["fid"])), tuple(map(float, d["width"])), tuple(map(float, d["u_coef"])), _tup(d["sig_ab"]), _tup(d["rows"]))
    size = tuple(map(float, d["size_upper"])) if "size_upper" in d.files and len(d["size_upper"]) else None
    return qc, ct.PatchTable(lnth=jnp.asarray(d["lnth"]), lnsig=jnp.asarray(np.log(d["sigma"]))), size

load_theta(path)

(CatalogueConfig.qcal_theta, PatchTable of the fiducial per-tile noise).

Source code in classy_szlite/sim/calibration.py
def load_theta(path):
    """(CatalogueConfig.qcal_theta, PatchTable of the fiducial per-tile noise)."""
    d = np.load(path)
    qt = (tuple(map(float, d["fid"])), tuple(map(float, d["width"])), _tup(d["g_sig"]), tuple(map(float, d["d0_sig"])), _tup(d["rows"]))
    return qt, ct.PatchTable(lnth=jnp.asarray(d["lnth"]), lnsig=jnp.asarray(np.log(d["sigma"])))

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
def load_set(path):
    """(theta, x) of a simulated set (.npz from survey.simulate_*_set), finished and finite rows only."""
    d = np.load(path)
    ok = d["done"] & np.all(np.isfinite(d["x"]), axis=1)
    return d["theta"][ok].astype(np.float32), d["x"][ok].astype(np.float32)

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
def train(theta, x, box="map", seed=0, log=print):
    """A posterior q(theta | x) trained on (theta, x); returns (posterior, info)."""
    import torch
    import sbi
    import sbi.inference as si
    NPE = getattr(si, "NPE", None) or getattr(si, "NPE_C", None) or getattr(si, "SNPE_C")
    try:
        from sbi.neural_nets import posterior_nn
    except ImportError:
        from sbi.utils import posterior_nn
    torch.manual_seed(seed)
    np.random.seed(seed)
    t0 = time.time()
    inf = NPE(prior=priors.sbi_prior(box), density_estimator=posterior_nn(model="maf"))
    inf.append_simulations(torch.from_numpy(np.asarray(theta, np.float32)), torch.from_numpy(np.asarray(x, np.float32)))
    de = inf.train(learning_rate=5e-4, stop_after_epochs=50, show_train_summary=False)
    post = inf.build_posterior(de)
    summ = getattr(inf, "summary", {}) or {}
    n_ep = len(summ.get("validation_loss", summ.get("validation_log_probs", [])))
    info = dict(n_train=len(theta), epochs=n_ep, seconds=time.time() - t0, sbi=sbi.__version__, seed=seed)
    log(f"trained on {len(theta)} simulations in {info['seconds']:.0f} s, {n_ep} epochs")
    return post, info

sample(post, x, n)

n posterior samples (n, 10) for one data vector.

Source code in classy_szlite/sim/npe.py
def sample(post, x, n):
    """n posterior samples (n, 10) for one data vector."""
    import torch
    return post.sample((n,), x=torch.from_numpy(np.asarray(x, np.float32)[None]), show_progress_bars=False).numpy()

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
def 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)."""
    mu, sd, rk, mu_d, sd_d = [], [], [], [], []
    for t, xo in zip(theta, x):
        s = sample(post, xo, n_samples)
        mu.append(s.mean(0)); sd.append(s.std(0)); rk.append(np.mean(s < t[None], axis=0))
        d = np.stack(priors.derived(s), 1)
        mu_d.append(d.mean(0)); sd_d.append(d.std(0))
    return dict(theta=np.asarray(theta), mu=np.array(mu), sd=np.array(sd), rank=np.array(rk),
                mu_derived=np.array(mu_d), sd_derived=np.array(sd_d))

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
def bias(summary):
    """Mean of (mu - truth) / sd and its error of the mean, per parameter; also for (Omega_m, S8)."""
    b = (summary["mu"] - summary["theta"]) / summary["sd"]
    td = np.stack(priors.derived(summary["theta"]), 1)
    bd = (summary["mu_derived"] - td) / summary["sd_derived"]
    err = lambda a: a.std(0, ddof=1) / np.sqrt(len(a))
    return dict(bias=b.mean(0), err=err(b), bias_derived=bd.mean(0), err_derived=err(bd))

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
def 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)."""
    rk = summary["rank"]
    return np.array([np.mean(np.abs(rk - 0.5) < lv / 2, axis=0) for lv in levels])

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
def tarp(post, theta, x, n_samples=1000):
    """TARP (Lemos et al. 2023) of the joint posterior: (area to the diagonal, KS p-value)."""
    import torch
    from sbi.diagnostics import run_tarp, check_tarp
    ecp, alpha = run_tarp(torch.from_numpy(np.asarray(theta, np.float32)), torch.from_numpy(np.asarray(x, np.float32)),
                          post, num_posterior_samples=n_samples)
    atc, ks_p = check_tarp(ecp, alpha)
    return float(atc), float(ks_p)

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
def 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)."""
    mus = np.stack([s["mu"] for s in summaries]); sds = np.stack([s["sd"] for s in summaries])
    mud = np.stack([s["mu_derived"] for s in summaries]); sdd = np.stack([s["sd_derived"] for s in summaries])
    return dict(theta=summaries[0]["theta"], mu=mus.mean(0), sd=np.sqrt((sds ** 2).mean(0) + mus.var(0)),
                rank=np.stack([s["rank"] for s in summaries]).mean(0), mu_derived=mud.mean(0),
                sd_derived=np.sqrt((sdd ** 2).mean(0) + mud.var(0)))

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
def cosmology_stage(theta: Theta, cells: hl.CellGrid) -> CosmoStage:
    """λ cells, corner densities and the cosmology grids on the cell z edges
    (traceable)."""
    p = {"omega_cdm": theta.omega_cdm, "H0": 100.0 * theta.h, "omega_b": theta.omega_b,
         "n_s": theta.n_s}
    # A_s by the linear-theory scaling about ln(10^10 A_s) = 3.0: exact, and safe
    # at the prior corners, which map outside the emulators' A_s box (2.5-3.5)
    p["ln10^{10}A_s"] = ln10As_from_sigma8(p, theta.sigma8, as_reference=LN10AS_REFERENCE)
    cg = build(p, z_grid=cells.z_edges, as_reference=LN10AS_REFERENCE)
    d2N = hl.corner_density(cg, p, cells)
    return CosmoStage(lam=hl.lambda_from_corners(d2N, cells), cg=cg, d2N=d2N,
                      chi_star=lensing.chi_star(theta.h, theta.omega_cdm, theta.omega_b))

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
def channel_maps(key, yk, st: TileStatic, noise: nz.NoiseInput | None = 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)."""
    k_cmb, k_w, k_a = jax.random.split(key, 3)
    f32 = jnp.float32
    cmb = jnp.fft.rfft2(jax.random.normal(k_cmb, (N, N), dtype=f32)) * st.cmb_amp
    if noise is not None:
        return st.a_full * yk[None] + st.B_full * cmb[None] + nz.draw(k_w, noise.tables, noise.spec, noise.depth)
    white = jnp.fft.rfft2(jax.random.normal(k_w, (6, N, N), dtype=f32)
                          * st.white_pix[:, None, None])
    g = jnp.fft.rfft2(jax.random.normal(k_a, (6, N, N), dtype=f32))       # 2 per tube
    r = f32(ins.SO_LAT["atm_corr"])
    s = jnp.sqrt(f32(1.0) - r * r)
    atm = []
    for t, (i, j) in enumerate(ins.SO_LAT["tubes"]):
        xa, xb = g[2 * t], g[2 * t + 1]
        atm.append((i, st.atm_amp[i] * xa))
        atm.append((j, st.atm_amp[j] * (r * xa + s * xb)))
    atm = jnp.stack([v for _, v in sorted(atm, key=lambda iv: iv[0])])
    return st.a_full * yk[None] + st.B_full * cmb[None] + white + atm

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
def tile_maps(key, cs: CosmoStage, theta: Theta, st: TileStatic, tables: pt.PaintTables,
              cells: hl.CellGrid, cfg: TileConfig,
              noise: nz.NoiseInput | None = None):
    """Halos, the six channel maps and the painter's overflow flags of one tile."""
    k_h, k_m = jax.random.split(key)
    halos = hl.sample_halos(k_h, cs.lam, cells, cfg.halo_cap, cs.cg, theta.h, theta.A_SZ,
                            theta.alpha_SZ, theta.sigma_lnq, theta.one_minus_b, d2N=cs.d2N)
    tabs = tables._replace(tab=st.paint_tab, rP=st.paint_rP)
    yk, ovf_paint = pt.paint_y(halos, tabs, cfg.paint, st.T_tab)
    return halos, channel_maps(k_m, yk, st, noise), ovf_paint

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
def simulate_tile(key, cs: CosmoStage, theta: Theta, st: TileStatic, tables: pt.PaintTables,
                  cells: hl.CellGrid, cfg: TileConfig,
                  noise: nz.NoiseInput | None = None):
    """Data vector and diagnostics of one tile."""
    halos, X, ovf_paint = tile_maps(key, cs, theta, st, tables, cells, cfg, noise)
    pk, sigma, mk = find_clusters(X, st.fs, cfg)
    keep = sm.merge_local_max(pk, cfg.r_merge)
    cf = sm.confirm(pk, keep, halos, cfg.M_conf, cfg.r_conf, cfg.conf_cap)
    counts = sm.histogram(pk.q, cf.z, keep & cf.ok)
    overflow = jnp.concatenate([halos.overflow[None], ovf_paint, mk["peak_overflow"][None],
                                cf.overflow[None]])
    p_sum, n_p = stacked_lensing(jax.random.fold_in(key, 7), pk, keep, cf, halos, cs, theta, st)
    return dict(counts=counts, n_halos=halos.count, n_peaks=pk.count,
                n_kept=jnp.sum(keep), n_conf=jnp.sum(keep & cf.ok),
                overflow=overflow, sigma=sigma, sigma0=mk["sigma0"],
                f_masked=mk["f_masked"], n_masked=mk["n_masked"],
                p_sum=p_sum, n_p=n_p)

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
def stacked_lensing(key, pk, keep, cf, halos, cs: CosmoStage, theta: Theta, st: TileStatic):
    """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)."""
    sel = keep & cf.ok & (pk.q > np.float32(sm.Q_EDGES[0]))
    M = jnp.exp(halos.lnM[cf.halo].astype(jnp.float64))
    z = halos.z[cf.halo].astype(jnp.float64)
    pbar = lensing.p_mean(M, z, cs.cg, theta.h, theta.beta_lens, cs.chi_star, st.lens_lnth, st.lens_lnsig)
    p = lensing.draw_p(key, jnp.where(sel, pbar, 1.0), theta.sigma_lnp)
    return jnp.sum(jnp.where(sel, p, 0.0)), jnp.sum(sel.astype(jnp.int32))

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
def find_clusters(X, fs: mmf.FilterStatic, cfg: TileConfig):
    """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."""
    q, sigma, C0 = mmf.q_cube(X, fs)
    pk = mmf.find_peaks(q, cfg.peak_cap, cfg.q_mask if cfg.n_iter else cfg.q_final)
    sigma0, ovf = sigma, pk.overflow
    f, n_masked = jnp.float64(1.0), jnp.int32(0)
    for it in range(cfg.n_iter):
        mask, n_masked = mmf.cluster_mask(pk, fs, cfg.q_mask)
        C, f = mmf.masked_cov(X, mask, C0, fs)
        q, sigma, _ = mmf.q_cube(X, fs, C=C)
        last = it == cfg.n_iter - 1
        pk = mmf.find_peaks(q, cfg.peak_cap, cfg.q_final if last else cfg.q_mask)
        ovf = ovf | pk.overflow
    return pk, sigma, dict(sigma0=sigma0, f_masked=1.0 - f, n_masked=n_masked,
                           peak_overflow=ovf)

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
def corner_density(cg, params, cells: CellGrid, 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.
    """
    kw = dict(delta_crit=500.0, tinker_interp="log10", nu_in_rho_m=False)
    kw.update(hmf_kwargs or {})
    n_m = cells.lnM_edges.size
    hg = build_halo_grids(cg, params, m_min=float(np.exp(cells.lnM_edges[0])),
                          m_max=float(np.exp(cells.lnM_edges[-1])), n_m=n_m, **kw)
    return hg.dndlnm * (cg.chi ** 2 / cg.Hz)[:, None] * OMEGA_TILE

lambda_from_corners(d2N, cells)

Cell integrals of the bilinear interpolant: corner mean × cell area.

Source code in classy_szlite/sim/halos.py
def lambda_from_corners(d2N, cells: CellGrid):
    """Cell integrals of the bilinear interpolant: corner mean × cell area."""
    corner = 0.25 * (d2N[:-1, :-1] + d2N[1:, :-1] + d2N[:-1, 1:] + d2N[1:, 1:])
    return corner * np.diff(cells.z_edges)[:, None] * np.diff(cells.lnM_edges)[None, :]

lambda_cells(cg, params, cells, hmf_kwargs=None)

Expected counts per cell for one tile, shape (n_z, n_m), float64.

Source code in classy_szlite/sim/halos.py
def lambda_cells(cg, params, cells: CellGrid, hmf_kwargs=None):
    """Expected counts per cell for one tile, shape (n_z, n_m), float64."""
    return lambda_from_corners(corner_density(cg, params, cells, hmf_kwargs), cells)

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
def sample_halos(key, lam, cells: CellGrid, capacity: int, 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.
    """
    k_pois, k_attr = jax.random.split(key)
    n_z, n_m = lam.shape
    counts = jax.random.poisson(k_pois, lam.ravel(), dtype=jnp.int32)
    csum = jnp.cumsum(counts)
    total = csum[-1]
    slot = jnp.arange(capacity, dtype=jnp.int32)
    valid = slot < total
    cell = jnp.searchsorted(csum, slot, side="right").astype(jnp.int32)
    cell = jnp.minimum(cell, n_z * n_m - 1)
    iz, im = cell // n_m, cell % n_m
    j_in_cell = slot - (csum[cell] - counts[cell])

    def draws(c, j):
        k = jax.random.fold_in(jax.random.fold_in(k_attr, c), j)
        ku, kn = jax.random.split(k)
        return (jax.random.uniform(ku, (6,), dtype=jnp.float64),
                jax.random.normal(kn, (), dtype=jnp.float64))
    U, G = jax.vmap(draws)(cell, j_in_cell)               # (C, 6), (C,)

    ze = jnp.asarray(cells.z_edges)
    me = jnp.asarray(cells.lnM_edges)
    u_z, u_m = U[:, 0], U[:, 1]
    if d2N is not None:
        f00, f10 = d2N[iz, im], d2N[iz + 1, im]            # (z, M) corners
        f01, f11 = d2N[iz, im + 1], d2N[iz + 1, im + 1]
        tz = _inv_linear_cdf(u_z, f00 + f01, f10 + f11)     # marginal in z
        tm = _inv_linear_cdf(u_m, (1 - tz) * f00 + tz * f10, (1 - tz) * f01 + tz * f11)
        u_z, u_m = jnp.clip(tz, 0.0, 1.0), jnp.clip(tm, 0.0, 1.0)
    z = ze[iz] + u_z * (ze[iz + 1] - ze[iz])
    lnM = me[im] + u_m * (me[im + 1] - me[im])

    # E(z) and D_A(z) at the halo redshifts (cosmology on the cell z edges)
    H0_over_c = h * 100.0 / 299792.458
    Ez = jnp.interp(z, cg.z, cg.Hz) / H0_over_c
    DA = jnp.interp(z, cg.z, cg.Da)
    M = jnp.exp(lnM)
    y0 = y0_median(M, Ez, h, A_SZ, alpha_SZ, one_minus_b)
    y0 = y0 * jnp.exp(sigma_lnq * G)
    th = theta500_arcmin(M, Ez, DA, h, one_minus_b)

    iy = jnp.minimum(jnp.floor(U[:, 2] * NF), NF - 1).astype(jnp.int32)
    ix = jnp.minimum(jnp.floor(U[:, 3] * NF), NF - 1).astype(jnp.int32)
    oy = U[:, 4].astype(jnp.float32)
    ox = U[:, 5].astype(jnp.float32)
    f32 = jnp.float32
    return Halos(iy=iy, ix=ix, oy=oy, ox=ox, z=z.astype(f32), lnM=lnM.astype(f32),
                 y0=jnp.where(valid, y0, 0.0).astype(f32), theta500=th.astype(f32),
                 valid=valid, count=total, overflow=total > capacity)

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:

  1. 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);
  2. rfft2, crop to the 0.5′ grid's modes, divide out the painting beam on the in-band modes (zero elsewhere);
  3. 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
def radial_profile(theta, rP, nr):
    """P(r; θ) on r = linspace(0, rP, nr), per unit y0 (θ, r in arcmin)."""
    lmax = 9.5 / SIG_PAINT                             # B_paint = e^-45
    npan = int(np.ceil(lmax / (3.0 / rP)))             # ℓ r changes ≤ 3 rad per panel
    xg, wg = np.polynomial.legendre.leggauss(10)
    edges = np.linspace(0.0, lmax, npan + 1)
    lo, hi = edges[:-1, None], edges[1:, None]
    ell = (0.5 * (hi - lo) * xg + 0.5 * (hi + lo)).ravel()
    w = (0.5 * (hi - lo) * wg).ravel()
    v = w * ell * theta ** 2 * profiles.T_interp(ell * theta) \
        * np.exp(-0.5 * (ell * SIG_PAINT) ** 2) / (2.0 * np.pi)
    r = np.linspace(0.0, rP, nr)
    out = np.empty(nr)
    for a in range(0, nr, 256):
        out[a:a + 256] = j0(np.outer(r[a:a + 256], ell)) @ v
    return out

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
def build_tables(th_min=0.1, th_split=6.0, dln=0.004, nr=2048) -> PaintTables:
    """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)."""
    n_th = int(np.ceil(np.log(th_split / th_min) / dln)) + 2
    th = th_min * np.exp(dln * np.arange(n_th))
    rP = R_SIGMAS * SIG_PAINT + 5.0 * th
    tab = np.stack([radial_profile(t, r, nr) for t, r in zip(th, rP)])
    return PaintTables(lnth0=float(np.log(th_min)), dln=float(dln), rP=rP, tab=tab,
                       th_split=float(th_split))

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].

Source code in classy_szlite/sim/paint.py
def 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]."""
    return np.ceil(np.asarray(rP_arcmin) / PIXF).astype(np.int64) + 1

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
def make_config(tables: PaintTables, expected_per_class, cap_big, margin=1.5, extra=256):
    """Capacities from expected class occupations (host-side)."""
    caps, blocks = [], []
    for S, n in zip(SIDES, expected_per_class):
        B = max(1, BLOCK_BUDGET // (S * S))
        cap = int(np.ceil((margin * n + extra) / B)) * B if n > 0 else B
        caps.append(cap)
        blocks.append(B)
    return PaintConfig(sides=SIDES, caps=tuple(caps), blocks=tuple(blocks), cap_big=int(cap_big))

theta_node(theta, tables)

Node index i0 (clipped) and linear weight w in ln θ, traceable.

Source code in classy_szlite/sim/paint.py
def theta_node(theta, tables):
    """Node index i0 (clipped) and linear weight w in ln θ, traceable."""
    n_th = tables.rP.shape[0]
    t = (jnp.log(theta) - tables.lnth0) / tables.dln
    t = jnp.clip(t, 0.0, n_th - 1.000001)
    i0 = jnp.floor(t).astype(jnp.int32)
    return i0, (t - i0).astype(jnp.float32)

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
def footprint_class(theta, tables, rP_j):
    """Class index of each halo (len(SIDES) for θ > θ_split or beyond)."""
    i0, _ = theta_node(theta, tables)
    R = rP_j[i0 + 1]
    need = 2 * (jnp.ceil(R / PIXF).astype(jnp.int32) + 1) + 1
    cls = jnp.searchsorted(jnp.asarray(SIDES, dtype=jnp.int32), need, side="left")
    return jnp.where(theta > tables.th_split, len(SIDES), cls).astype(jnp.int32)

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
def paint_fine(halos, tables, cfg: PaintConfig):
    """The fine 2400² y map (painting beam included) of the halos with
    θ500 ≤ θ_split, and per-class overflow flags."""
    tab = jnp.asarray(tables.tab, dtype=jnp.float32)
    rP = jnp.asarray(tables.rP, dtype=jnp.float32)
    dr_inv = (tab.shape[1] - 1) / rP
    i0, w = theta_node(halos.theta500, tables)
    cls = footprint_class(halos.theta500, tables, rP)
    cls = jnp.where(halos.valid, cls, -1)
    buf = jnp.zeros((NF * NF,), dtype=jnp.float32)
    cap_n = halos.y0.shape[0]
    overflow = []
    for c, (S, cap, B) in enumerate(zip(cfg.sides, cfg.caps, cfg.blocks)):
        idx, cnt = compact(cls == c, cap, cap_n)
        overflow.append(cnt > cap)

        def take(x, fill=0):
            return jnp.take(x, idx, mode="fill", fill_value=fill)
        h = dict(iy=take(halos.iy), ix=take(halos.ix), oy=take(halos.oy), ox=take(halos.ox),
                 y0=take(halos.y0), i0=take(i0), w=take(w))
        buf = _paint_class(buf, h, tab, rP, dr_inv, S, B, cap)
    return buf.reshape(NF, NF), jnp.stack(overflow)

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
def 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)."""
    G = grid()
    F = jnp.fft.rfft2(fine)
    rows = jnp.asarray(fine_to_coarse_rows(), dtype=jnp.int32)
    Fc = F[rows][:, : N // 2 + 1] / 4.0
    dec = np.where(G.sel, np.exp(0.5 * (G.L * SIG_PAINT * ARCMIN) ** 2), 0.0)
    return Fc * jnp.asarray(dec, dtype=jnp.float32)

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
def 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."""
    G = grid()
    sel = jnp.asarray(G.sel)
    i0 = jnp.asarray(G.i0, dtype=jnp.int32)[:, None]                  # (N, 1)
    i1 = jnp.asarray(G.i1, dtype=jnp.int32)[None, :]                  # (1, N/2+1)
    L = jnp.asarray(G.L, dtype=dtype)
    Om = G.Om
    T_tab = jnp.asarray(T_tab, dtype=dtype)
    twopi_over_NF = dtype(2.0 * np.pi / NF)

    def one(iy, ix, oy, ox, y0, th):
        th_rad = th * dtype(ARCMIN)
        u = L * th_rad / dtype(DU_T)
        j = jnp.clip(jnp.floor(u).astype(jnp.int32), 0, T_tab.shape[0] - 2)
        t = u - j
        T = (1.0 - t) * T_tab[j] + t * T_tab[j + 1]
        amp = y0 * th_rad ** 2 * T / dtype(Om)
        # phase = 2π (i0 y + i1 x) / LBOX with y = (iy + oy) PIXF: exact integer part mod NF
        ph_int = ((i0 * iy) % NF + (i1 * ix) % NF) % NF
        ph = twopi_over_NF * (ph_int.astype(dtype) + i0.astype(dtype) * oy
                              + i1.astype(dtype) * ox)
        return amp * (jnp.cos(ph) - 1j * jnp.sin(ph))

    def step(acc, h):
        terms = jax.vmap(one)(*h)                                   # (CHUNK, N, N/2+1)
        return acc + jnp.where(sel, jnp.sum(terms, axis=0), 0.0), None

    cdtype = jnp.complex64 if dtype == jnp.float32 else jnp.complex128
    acc0 = jnp.zeros(G.L.shape, dtype=cdtype)
    xs = tuple(jnp.asarray(halos_sel[k]) for k in ("iy", "ix", "oy", "ox", "y0", "theta500"))
    xs = xs[:2] + tuple(x.astype(dtype) for x in xs[2:])
    n = xs[0].shape[0]
    c = min(DIRECT_CHUNK, n)
    pad = (-n) % c
    if pad:                                         # zero-amplitude padding halos
        xs = tuple(jnp.concatenate([x, jnp.zeros((pad,), x.dtype) + (1 if i == 5 else 0)])
                   for i, x in enumerate(xs))
    xs = tuple(x.reshape(-1, c) for x in xs)
    acc, _ = jax.lax.scan(step, acc0, xs)
    return acc

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
def paint_y(halos, tables, cfg: PaintConfig, T_tab):
    """y(k) of all halos of a tile (coarse rfft units, in-band), and overflow
    flags (per class, then the direct path)."""
    fine, ovf = paint_fine(halos, tables, cfg)
    yk = fine_to_coarse(fine)
    big = halos.valid & (halos.theta500 > tables.th_split)
    cap_n = halos.y0.shape[0]
    idx, nbig = compact(big, cfg.cap_big, cap_n)
    hb = {k: jnp.take(getattr(halos, k), idx, mode="fill", fill_value=0)
          for k in ("iy", "ix", "oy", "ox", "y0")}
    hb["theta500"] = jnp.take(halos.theta500, idx, mode="fill", fill_value=1.0)
    yk = yk + synth_direct(hb, T_tab)
    return yk, jnp.concatenate([ovf, (nbig > cfg.cap_big)[None]])

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)

ΔT [μK_CMB] per unit y.

Source code in classy_szlite/sim/instrument.py
def tsz_f_uK(nu_GHz):
    """ΔT [μK_CMB] per unit y."""
    return T_CMB * 1e6 * tsz_g(nu_GHz)

beams(L, fwhm=SO_LAT['fwhm'])

B_i(ℓ), shape (n_ch,) + L.shape.

Source code in classy_szlite/sim/instrument.py
def beams(L, fwhm=SO_LAT["fwhm"]):
    """B_i(ℓ), shape (n_ch,) + L.shape."""
    sb = sigma_beam_rad(fwhm)
    L = np.asarray(L, float)
    return np.exp(-0.5 * (L[None, ...] * sb.reshape((-1,) + (1,) * L.ndim)) ** 2)

red_levels()

Atmospheric amplitude at ℓ_knee [μK² sr] per channel.

Source code in classy_szlite/sim/instrument.py
def red_levels():
    """Atmospheric amplitude at ℓ_knee [μK² sr] per channel."""
    return SO_LAT["N_red"] * 4.0 * np.pi * SO_LAT["fsky"] / t_eff()

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
def noise_cov(L, mode="goal", atm=True, atm_corr=None):
    """Noise covariance N_ij(ℓ) [μK² sr], not beam-deconvolved, (6, 6) + L.shape."""
    L = np.asarray(L, float)
    r = SO_LAT["atm_corr"] if atm_corr is None else atm_corr
    w = SO_LAT["white"][mode] * ARCMIN
    Nn = np.zeros((6, 6) + L.shape)
    for i in range(6):
        Nn[i, i] += w[i] ** 2
    if atm:
        red, shp = red_levels(), atm_shape(L)
        for i in range(6):
            Nn[i, i] += red[i] * shp
        for (i, j) in SO_LAT["tubes"]:
            c = r * np.sqrt(red[i] * red[j]) * shp
            Nn[i, j] += c
            Nn[j, i] += c
    return Nn

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
def 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)."""
    d = np.load(path)
    le, cl = d["ell"].astype(float), d["cl_uK2"]
    sl, amp, lt = float(d["ext_slope"]), float(d["ext_lnamp"]), int(d["l_trust"])

    def f(ell):
        ell = np.asarray(ell, float)
        out = np.interp(ell, le, cl)
        hi = ell > lt
        out[hi] = np.exp(amp + sl * np.log(ell[hi]))
        out[ell < 2] = 0.0
        return out
    return f

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
def 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.
    """
    from ..api import cl_TTTEEE
    from ..params import CosmoParams
    out = cl_TTTEEE(cosmo or CosmoParams(), spectra=("tt",), ell_factor=False)
    le = np.asarray(out["ell"], float)
    cl = np.asarray(out["tt"], float) * (T_CMB * 1e6) ** 2
    keep = le <= EMU_LMAX_USED
    le, cl = le[keep], cl[keep]
    fit = (le >= EMU_FIT[0]) & (le <= EMU_FIT[1])
    slope, lnamp = np.polyfit(np.log(le[fit]), np.log(cl[fit]), 1)

    def f(ell):
        ell = np.asarray(ell, float)
        res = np.interp(ell, le, cl)
        hi = ell > le[-1]
        res[hi] = np.exp(lnamp + slope * np.log(ell[hi]))
        res[ell < 2] = 0.0
        return res
    f.slope, f.lnamp = slope, lnamp
    return f

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
def 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."""
    d = np.fft.fftfreq(N, d=1.0 / N).round().astype(np.int64)
    d2 = d[:, None] ** 2 + d[None, :] ** 2
    out = np.empty((len(thetas), N, N // 2 + 1))
    for j, t in enumerate(thetas):
        R = radius * float(t) / PIX
        assert R < N // 2
        out[j] = np.fft.rfft2((d2 <= R * R).astype(np.float64)).real
    return out

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
def filter_static(thetas=THETAS15, mask_radius=MASK_RADIUS, channels=None) -> FilterStatic:
    """``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."""
    G = grid()
    n_all = len(ins.SO_LAT["freqs"])
    ch = list(range(n_all)) if channels is None else [int(c) for c in channels]
    if not ch or len(set(ch)) != len(ch) or min(ch) < 0 or max(ch) >= n_all:
        raise ValueError(f"channels must be distinct indices in [0, {n_all}): {channels}")
    f = ins.tsz_f_uK(ins.SO_LAT["freqs"])
    a = (ins.beams(G.m_L) * f[:, None]).T[:, ch]                       # (n_modes, n_ch)
    T_m = np.stack([profiles.T_interp(G.m_L * t * ARCMIN) for t in thetas])
    tau_m = (np.asarray(thetas)[:, None] * ARCMIN) ** 2 * T_m / G.Om
    tau_full = np.zeros((len(thetas),) + G.L.shape, dtype=np.float32)
    flat = tau_full.reshape(len(thetas), -1)
    flat[:, G.m_idx] = tau_m
    return FilterStatic(
        m_idx=jnp.asarray(G.m_idx, dtype=jnp.int32), m_W=jnp.asarray(G.m_W),
        m_binpos=jnp.asarray(G.m_binpos, dtype=jnp.int32),
        bin_pad=jnp.asarray(G.bin_pad, dtype=jnp.int32),
        bin_count=jnp.asarray(G.bin_count), a=jnp.asarray(a), tau_m=jnp.asarray(tau_m),
        tau_full=jnp.asarray(tau_full),
        disc_k=jnp.asarray(disc_kernels(thetas, mask_radius).astype(np.float32)))

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
def binned_cov(Xm, fs: FilterStatic):
    """Binned n×n covariance (float64) from the in-band modes Xm (n, n_modes)."""
    n = _n_channels(Xm, fs)
    X = Xm.astype(jnp.complex128)
    W = fs.m_W
    pad = fs.bin_pad
    ok = pad >= 0
    pidx = jnp.where(ok, pad, 0)
    C = jnp.zeros((pad.shape[0], n, n), dtype=jnp.float64)
    for (i, j) in _pairs(n):
        prod = W * (X[i].real * X[j].real + X[i].imag * X[j].imag)   # (n_modes,)
        v = jnp.sum(jnp.where(ok, prod[pidx], 0.0), axis=1) / fs.bin_count
        C = C.at[:, i, j].set(v)
        if i != j:
            C = C.at[:, j, i].set(v)
    return C

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
def weights(C, fs: FilterStatic):
    """w(k) = C_b⁻¹ a(k) (n_modes, n) and aᵀC⁻¹a (n_modes,), float64."""
    n = fs.a.shape[1]
    L = jnp.linalg.cholesky(C)
    eye = jnp.broadcast_to(jnp.eye(n, dtype=C.dtype), C.shape)
    Ci = jax.scipy.linalg.cho_solve((L, True), eye)
    Ci = 0.5 * (Ci + jnp.swapaxes(Ci, 1, 2))
    b = fs.m_binpos
    cols = []
    for i in range(n):
        wi = sum(Ci[b, i, j] * fs.a[:, j] for j in range(n))
        cols.append(wi)
    w = jnp.stack(cols, axis=1)
    aCa = jnp.sum(w * fs.a, axis=1)
    return w, aCa

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
def q_cube(X, fs: FilterStatic, 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.
    """
    G = grid()
    n = _n_channels(X, fs)
    Xm = X.reshape(n, -1)[:, fs.m_idx]
    if C is None:
        C = binned_cov(Xm, fs)
    w, aCa = weights(C, fs)
    norm = jnp.sum(fs.m_W[None, :] * fs.tau_m ** 2 * aCa[None, :], axis=1)   # (n_th,)
    cdtype = jnp.complex64 if dtype == jnp.float32 else jnp.complex128
    # elementwise product and sum (not a dot): no TF32 on Ampere and later
    cx_m = jnp.sum(w.T.astype(dtype) * Xm.astype(cdtype), axis=0)
    cx = jnp.zeros((G.L.size,), dtype=cdtype).at[fs.m_idx].set(cx_m).reshape(G.L.shape)
    scale = (G.Npx / jnp.sqrt(norm)).astype(dtype)                           # (n_th,)
    q = jnp.fft.irfft2(fs.tau_full.astype(dtype) * cx[None], s=(N, N)) * scale[:, None, None]
    return q, 1.0 / jnp.sqrt(norm), C

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
def find_peaks(q, capacity: int, qth=Q_TH):
    """Peaks of the S/N cube (see the module docstring)."""
    one = jnp.ones((1,) + q.shape[1:], dtype=bool)
    above_prev = jnp.concatenate([one, q[1:] > q[:-1]], axis=0)     # q_j > q_{j-1}
    above_next = jnp.concatenate([q[:-1] >= q[1:], one], axis=0)    # q_j >= q_{j+1}
    m = ((q > qth)
         & (q > jnp.roll(q, 1, axis=1)) & (q > jnp.roll(q, -1, axis=1))
         & (q > jnp.roll(q, 1, axis=2)) & (q > jnp.roll(q, -1, axis=2))
         & above_prev & above_next)
    idx, count = compact(m.ravel(), capacity, 0)
    valid = jnp.arange(capacity) < count
    n2 = q.shape[1] * q.shape[2]
    j = idx // n2
    rem = idx % n2
    iy, ix = rem // q.shape[2], rem % q.shape[2]
    qv = jnp.where(valid, q.ravel()[idx], -jnp.inf)
    return Peaks(j=j, iy=iy, ix=ix, q=qv, valid=valid, count=count, overflow=count > capacity)

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
def cluster_mask(peaks: Peaks, fs: FilterStatic, 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."""
    n_th = fs.disc_k.shape[0]
    sel = peaks.valid & (peaks.q > q_mask)
    j = jnp.where(sel, peaks.j, n_th)                          # out of range: dropped
    pts = jnp.zeros((n_th, N, N), jnp.float32).at[j, peaks.iy, peaks.ix].add(
        jnp.float32(1.0), mode="drop")
    cover = jnp.fft.irfft2(jnp.sum(fs.disc_k * jnp.fft.rfft2(pts), axis=0), s=(N, N))
    return (cover < 0.5).astype(jnp.float32), jnp.sum(sel.astype(jnp.int32))

whitening(C)

C^(-½) and C^(½) per bin (symmetric square roots, float64).

Source code in classy_szlite/sim/mmf.py
def whitening(C):
    """C^(-1/2) and C^(1/2) per bin (symmetric square roots, float64)."""
    ev, U = jnp.linalg.eigh(C)
    Wm = jnp.einsum("bij,bj,bkj->bik", U, ev ** -0.5, U)
    Wi = jnp.einsum("bij,bj,bkj->bik", U, ev ** 0.5, U)
    return Wm, Wi

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
def masked_cov(X, mask, C0, fs: FilterStatic):
    """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)."""
    G = grid()
    n = _n_channels(X, fs)
    Wm, Wi = whitening(C0)
    Xm = X.reshape(n, -1)[:, fs.m_idx]
    b = fs.m_binpos
    Wm32 = Wm.astype(jnp.float32)
    Zm = jnp.stack([sum(Wm32[b, i, j] * Xm[j] for j in range(n)) for i in range(n)])
    Z = jnp.zeros((n, G.L.size), Zm.dtype).at[:, fs.m_idx].set(Zm).reshape((n,) + G.L.shape)
    z = jnp.fft.irfft2(Z, s=(N, N)) * mask[None]
    Zk = jnp.fft.rfft2(z).reshape(n, -1)[:, fs.m_idx]
    f = jnp.mean(mask.astype(jnp.float64))
    Cw = binned_cov(Zk, fs) / f
    return jnp.einsum("bij,bjk,bkl->bil", Wi, Cw, Wi), f

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
def merge_local_max(peaks, r_merge_arcmin: float):
    """Boolean keep mask over the peak buffer."""
    dy = _wrap(peaks.iy[:, None] - peaks.iy[None, :], N)
    dx = _wrap(peaks.ix[:, None] - peaks.ix[None, :], N)
    d2 = dy * dy + dx * dx                                       # pixels², exact int32
    r2 = (r_merge_arcmin / PIX) ** 2
    both = peaks.valid[:, None] & peaks.valid[None, :]
    near = both & (d2.astype(jnp.float32) <= r2)
    k = jnp.arange(peaks.q.shape[0])
    better = ((peaks.q[None, :] > peaks.q[:, None])
              | ((peaks.q[None, :] == peaks.q[:, None]) & (k[None, :] < k[:, None])))
    return peaks.valid & ~jnp.any(near & better, axis=1)

in_data_vector(q, z, ok)

Detections counted by :func:histogram (same open intervals).

Source code in classy_szlite/sim/summaries.py
def in_data_vector(q, z, ok):
    """Detections counted by :func:`histogram` (same open intervals)."""
    qe = jnp.asarray(Q_EDGES, dtype=jnp.float32)
    ze = jnp.asarray(Z_EDGES, dtype=jnp.float32)
    return ok & (q > qe[0]) & (q < qe[-1]) & (z > ze[0]) & (z < ze[-1])

histogram(q, z, ok)

(4, 5) int32 counts in the paper's q and z bins.

Source code in classy_szlite/sim/summaries.py
def histogram(q, z, ok):
    """(4, 5) int32 counts in the paper's q and z bins."""
    qe = jnp.asarray(Q_EDGES, dtype=jnp.float32)
    ze = jnp.asarray(Z_EDGES, dtype=jnp.float32)
    inside = in_data_vector(q, z, ok)
    iq = jnp.sum(q[:, None] > qe[None, 1:-1], axis=1)
    iz = jnp.sum(z[:, None] > ze[None, 1:-1], axis=1)
    return jnp.zeros((4, 5), dtype=jnp.int32).at[iq, iz].add(inside.astype(jnp.int32))

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
def 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/χ*)."""
    om = (omega_cdm + omega_b + OMEGA_NU_H2) / h ** 2
    orad = OMEGA_R_H2 / h ** 2
    a, b = 0.0, np.log(1.0 + Z_STAR)
    u = 0.5 * (b - a) * jnp.asarray(_U) + 0.5 * (b + a)
    zp1 = jnp.exp(u)
    E = jnp.sqrt(om * zp1 ** 3 + orad * zp1 ** 4 + (1.0 - om - orad))
    return C_KMS / (100.0 * h) * 0.5 * (b - a) * jnp.sum(jnp.asarray(_WU) * zp1 / E)

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
def kappa_rs(M500, z, cg, h, beta, chi_s):
    """Convergence at the scale radius for lensing mass β M500 at redshift z."""
    Ml = beta * M500
    Hc = jnp.interp(z, cg.z, cg.Hz)                      # H(z)/c [1/Mpc]
    rho_c = 3.0 * Hc ** 2 / (8.0 * np.pi * G_OVER_C2)    # M_sun / Mpc³
    R500 = (3.0 * Ml / (4.0 * np.pi * 500.0 * rho_c)) ** (1.0 / 3.0)
    rs = R500 / C500
    rho0 = Ml / (4.0 * np.pi * rs ** 3 * M_C)
    DA = jnp.interp(z, cg.z, cg.Da)
    chi = jnp.interp(z, cg.z, cg.chi)
    return 4.0 * np.pi * G_OVER_C2 * S_RS * rho0 * rs * DA * (1.0 - chi / chi_s)

table(mode='goal')

(ln θ500 [arcmin], ln σ_κ) arrays of the SO table for mode.

Source code in classy_szlite/sim/lensing.py
def table(mode="goal"):
    """(ln θ500 [arcmin], ln σ_κ) arrays of the SO table for ``mode``."""
    return (np.log(lens_tables.THETA500_ARCMIN), np.log(lens_tables.SIGMA_KAPPA[mode]))

sigma_kappa(theta500, lnth_tab, lnsig_tab)

σ_κ at θ500 [arcmin]: linear in ln–ln, held at the end values outside the table.

Source code in classy_szlite/sim/lensing.py
def sigma_kappa(theta500, lnth_tab, lnsig_tab):
    """σ_κ at θ500 [arcmin]: linear in ln–ln, held at the end values outside the table."""
    return jnp.exp(jnp.interp(jnp.log(theta500), lnth_tab, lnsig_tab))

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
def 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."""
    return a_lens * kappa_rs(M500, z, cg, h, beta, chi_s) / sigma_kappa(
        theta500_lens(M500, z, cg, h, beta), lnth_tab, lnsig_tab)

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
def draw_p(key, pbar, sigma_lnp):
    """p_obs: log-normal intrinsic scatter about p̄, then unit Gaussian noise."""
    k1, k2 = jax.random.split(key)
    lnp = jnp.log(pbar) + sigma_lnp * jax.random.normal(k1, pbar.shape, dtype=jnp.float64)
    return jnp.exp(lnp) + jax.random.normal(k2, pbar.shape, dtype=jnp.float64)

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.

Source code in classy_szlite/sim/flatsky.py
def isqrt(n):
    """Exact integer square root of a non-negative int64 array."""
    n = np.asarray(n, dtype=np.int64)
    r = np.floor(np.sqrt(n.astype(np.float64))).astype(np.int64)
    r -= (r * r > n)
    r += ((r + 1) * (r + 1) <= n)
    return r

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
def __init__(self, n=N, pix=PIX, lmin=LMIN, lmax=LMAX, bin_dk=BIN_DK):
    self.n, self.pix = n, pix
    self.lbox = n * pix
    self.dk = 2.0 * np.pi / (self.lbox * ARCMIN)
    self.Om = (pix * ARCMIN) ** 2                     # sr
    self.Npx = n * n
    self.i0 = np.fft.fftfreq(n, d=1.0 / n).round().astype(np.int64)
    self.i1 = np.arange(n // 2 + 1, dtype=np.int64)
    self.n2 = self.i0[:, None] ** 2 + self.i1[None, :] ** 2
    self.L = self.dk * np.sqrt(self.n2.astype(np.float64))
    self.k0 = (self.i0 * self.dk)[:, None] * np.ones((1, n // 2 + 1))
    self.k1 = np.ones((n, 1)) * (self.i1 * self.dk)[None, :]
    w = np.full(n // 2 + 1, 2.0)
    w[0] = 1.0
    if n % 2 == 0:
        w[-1] = 1.0
    self.W = np.broadcast_to(w[None, :], self.L.shape).copy()
    n2min = int(np.ceil((lmin / self.dk) ** 2 - 1e-9))
    n2max = int(np.floor((lmax / self.dk) ** 2 + 1e-9))
    self.sel = (self.n2 >= n2min) & (self.n2 <= n2max)
    self.ib = isqrt(self.n2) // bin_dk

    # in-band modes, sorted by bin (stable: row-major within a bin)
    flat = np.flatnonzero(self.sel.ravel())
    order = np.argsort(self.ib.ravel()[flat], kind="stable")
    self.m_idx = flat[order]
    self.m_L = self.L.ravel()[self.m_idx]
    self.m_W = self.W.ravel()[self.m_idx]
    self.m_bin = self.ib.ravel()[self.m_idx]
    self.bins_used, starts, counts = np.unique(self.m_bin, return_index=True,
                                               return_counts=True)
    self.n_bins = len(self.bins_used)
    self.m_binpos = np.searchsorted(self.bins_used, self.m_bin)   # 0..n_bins-1
    maxc = int(counts.max())
    pad = -np.ones((self.n_bins, maxc), dtype=np.int64)
    for b, (s0, c) in enumerate(zip(starts, counts)):
        pad[b, :c] = np.arange(s0, s0 + c)
    self.bin_pad = pad
    self.bin_count = np.bincount(self.m_binpos, weights=self.m_W,
                                 minlength=self.n_bins)
    self.bin_L = (self.bins_used + 0.5) * bin_dk * self.dk        # bin centres

grid(n=N, pix=PIX)

Cached FlatGrid.

Source code in classy_szlite/sim/flatsky.py
def grid(n=N, pix=PIX):
    """Cached FlatGrid."""
    key = (n, pix)
    if key not in _GRID:
        _GRID[key] = FlatGrid(n, pix)
    return _GRID[key]

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.

Source code in classy_szlite/sim/flatsky.py
def 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."""
    return np.r_[0:n // 2, nf - n // 2:nf]