Repository navigation
Bayesian Inference and Samplers
Back to Home · Previous: SBI & Batch Pipeline · Next: Multi-Probe, Fisher & Topology
21cmCU includes a zero-external-dependency compiled C99 inference engine (src/py21cmfast/src/inference_samplers.c) coupled directly to Likelihood21cm and multi-GPU warm worker pools (BatchPool), plus optional dispatchers for UltraNest, emcee, and 21CMMC.
import py21cmcu as p21
prior = p21.PriorTransform(
[
p21.ParameterPrior("F_STAR10_ACG", kind="uniform", low=-2.5, high=-0.5),
p21.ParameterPrior("F_ESC10_ACG", kind="uniform", low=-2.0, high=-0.4),
p21.ParameterPrior("KP_h_Mpc", kind="log_uniform", low=1.0, high=30.0),
]
)
# Or quickly from uniform bounds dict:
uniform_prior = p21.PriorTransform.from_bounds(
{"F_STAR10_ACG": (-2.0, -0.6), "F_ESC10_ACG": (-2.0, -0.4)}
)Supported prior shapes: "uniform", "log_uniform", and "normal" (mean, std).
Likelihood21cm supports both coeval and lightcone forward models and accepts either scalar (ndim,) or vectorized batch (n_batch, ndim) parameter inputs:
import numpy as np
import py21cmcu as p21
base_inputs = p21.InputParameters.from_template(
"simple", random_seed=42, DIM=128, HII_DIM=64, BOX_LEN=128.0
)
ll = p21.Likelihood21cm(
base_inputs=base_inputs,
param_names=("F_STAR10_ACG", "F_ESC10_ACG"),
data_pk=data_pk,
sigma_pk=sigma_pk, # OR pass covariance=... OR cov_inv=...
mode="coeval", # or "lightcone"
out_redshift=8.0, # recommended explicit target when node_redshifts has >1 entry
ps_n_bins=12,
wedge_filter=True, # supported in both coeval and lightcone modes
wedge_buffer=0.05,
model_error_frac=0.2, # optional fractional modeling uncertainty in quadrature
cuda_mode="fast",
use_cuda=True,
devices=(0,),
workers_per_gpu=1,
)-
Consistent coeval redshift resolution:
simulate()andsimulate_batch()share unified_resolve_coeval_redshiftlogic so single-point checks and batched sampler draws select identical redshift slices (always set explicitout_redshift=...whenbase_inputs.node_redshiftscontains multiple redshifts). -
Lightcone wedge filtering: When
mode="lightcone"andwedge_filter=True,Likelihood21cmappliesapply_wedge_filter_3dprior to computing the 1D power spectrum. -
Fixed observation mask & strict
NaNrejection: Observed bins are fixed at initialization (_obs_mask). If the physical model returnsNaN/infin any required observed bin,log_likelihoodreturns-infrather than dropping the bin and inflating$\log \mathcal{L}$ . -
Marginalized precision (
cov_inv) with missing bins: Whendata_pkcontains masked/NaNbins alongside a full precision matrixcov_inv,Likelihood21cmperforms exact Schur-complement marginalization (P_oo - P_om P_mm^-1 P_mo) with scale-invariant block detection (scale * 1e-14), matching passing the sub-selectedcovariancematrix. -
Full Gaussian normalization with
model_error_frac > 0: Because fractional modeling error$\sigma_{\mathrm{model}, i} = f \cdot |m_i(\theta)|$ depends on$\theta$ , the likelihood includes$-\sum \log \sigma_{\mathrm{eff},i}$ (or$-\frac{1}{2}\log|\Sigma_{\mathrm{eff}}|$ ) so Bayesian model evidence and parameter comparison remain normalized.
Combine 21cm power-spectrum likelihoods with CMB Thomson optical depth compute_tau_e) or external probes using JointLikelihood with optional weights and automatic -inf short-circuiting:
def tau_e_loglike(theta_batch: np.ndarray) -> np.ndarray:
# Wrap reionization history (redshifts, xHI) -> compute_tau_e(...)
tau_pred = compute_predicted_tau(theta_batch)
return -0.5 * ((tau_pred - 0.0544) / 0.0073) ** 2
joint = p21.JointLikelihood(
{"ps21": ll, "planck_tau_e": tau_e_loglike},
weights={"ps21": 1.0, "planck_tau_e": 1.0},
short_circuit=True, # skips expensive downstream probes if ps21 returns -inf
)NativeNestedSampler / run_nested_sampling implements multi-ellipsoid clustering (k-means + covariance bounding) and differential hit-and-run slice proposals in C99 (inference_samplers.c, compiled with -O3 -ffast-math -fno-finite-math-only to preserve ±inf/NaN semantics) with warm BatchPool GPU evaluation:
from pathlib import Path
import py21cmcu as p21
ns_res = p21.run_nested_sampling(
log_likelihood=joint,
prior=prior,
n_live=200,
batch_size=32,
dlogz=0.1,
max_clusters=4,
slice_fraction=0.5,
devices=(0,),
workers_per_gpu=1,
checkpoint_path=Path("native_ns_ckpt.h5"),
checkpoint_every=50,
resume=True,
model_id="21cm_tau_v1", # required when resuming non-Likelihood21cm custom callables
)
print(ns_res.summary())
ns_res.save_h5("posterior_ns.h5") # or ns_res.save_npz("posterior_ns.npz")Safety features in v1.0.0–v1.1.0:
-
Plateau bulk-eviction: Flat prior plateaus (such as wide
-infhard boundaries or tied likelihood values) are evicted and replenished consistently under variable$N_{\mathrm{live}}$ quadrature so evidence$\log Z$ does not overestimate invalid volume. -
Provenance-verified HDF5 resume:
Likelihood21cm(and all-Likelihood21cmJointLikelihood) automatically hashes full simulation + data/covariance configuration; custom Python callables (such as surrogate wrappers or customJointLikelihoodprobes) must pass a matching explicitmodel_id="..."(orJointLikelihood(..., model_id="...")) when resuming withresume=True, or aValueErroris raised rather than reusing stale checkpoints. Matching runs additionally re-evaluate up to 32 stratified probe points before resuming.
NativeEnsembleMCMC / run_native_mcmc runs independent walker ensembles alternating Goodman–Weare Stretch moves and Differential Evolution (DE-MC) updates in C99, returning a NestedSamplingResult with full convergence diagnostics:
mcmc_res = p21.run_native_mcmc(
log_likelihood=joint,
prior=prior,
n_walkers=32,
n_steps=400,
burnin=100,
thin=1,
n_ensembles=2, # >= 2 ensembles enables split-Rhat across ensembles & halves
stretch_a=2.0,
de_prob=0.5,
checkpoint_path=Path("native_mcmc_ckpt.h5"),
resume=True,
model_id="21cm_tau_v1", # required when resuming custom callables
)
print(mcmc_res.summary())
print(
"diagnostics_ok:", mcmc_res.metadata["diagnostics_ok"],
"| max_rhat:", mcmc_res.metadata["max_rhat"],
"| min_N/IAT:", mcmc_res.metadata["min_n_over_iat"],
"| ESS:", mcmc_res.ess,
)Built-in diagnostics (inference_samplers.c):
-
Autocorrelation-adjusted ESS: Effective Sample Size accounts for Sokal Integrated Autocorrelation Time (
$\mathrm{ESS} = N_{\mathrm{samples}} / \max \tau_{\mathrm{int}}$ ) rather than raw sample count. -
Zero-variance stuck-chain detection: If acceptance collapses and chains sit motionless (
v_max - v_minwithin 1-ULP tolerance), split-$\widehat{R}$ and IAT reportNaN/inf,ess = 0.0, andmetadata["diagnostics_ok"] = Falseinstead of falsely claiming convergence.
Switch between backends (native_ns, native_mcmc, ultranest, emcee, 21cmmc) with one API:
res = p21.run_21cmmc(
base_inputs=base_inputs,
param_names=("F_STAR10_ACG", "F_ESC10_ACG"),
prior={"F_STAR10_ACG": (-2.0, -0.6), "F_ESC10_ACG": (-2.0, -0.4)},
data_pk=data_pk,
sigma_pk=sigma_pk,
backend="native_ns", # or "native_mcmc", "ultranest", "emcee", "21cmmc"
mode="coeval",
out_redshift=8.0,
ps_n_bins=12,
devices=(0,),
batch_size=16,
min_num_live_points=200,
dlogz=0.2,
use_cuda=True,
)Or run directly from the shell via 21cmcu infer (input .npz containing data_pk and optional sigma_pk or cov_inv):
21cmcu infer obs_pk.npz \
--bounds '{"F_STAR10_ACG": [-2.0, -0.6], "F_ESC10_ACG": [-2.0, -0.4]}' \
--backend native_ns \
--mode coeval \
--dim 128 --hii-dim 64 --box-len 128.0 --out-redshift 8.0 \
--devices 0 --workers-per-gpu 1 --batch-size 16 \
--n-live 200 --dlogz 0.2 --model-error-frac 0.2 \
--checkpoint infer_ckpt.h5 --resume \
--out posterior_ns.h5For MCMC from CLI, pass --backend native_mcmc --n-walkers 32 --n-steps 400 --burnin 100.
Verify posterior samples generated by a fast surrogate or neural emulator by evaluating an equal-weight posterior subsample through Likelihood21cm.simulate_batch:
audit = p21.audit_posterior_native(
ns_res,
likelihood=ll,
surrogate_predict=my_emulator_predict, # (n_draws, ndim) -> (n_draws, n_k)
n_draws=16,
)
print(
f"valid_rms_z={audit.valid_rms_zscore:.3f}, "
f"p90_L2={audit.l2_p90:.3f}, "
f"failure_rate={audit.failure_rate:.1%} ({audit.n_failed_draws}/{audit.n_draws})"
)The default selection="posterior" draws from ns_res.samples, the equal-weight posterior sample. Use selection="likelihood_range" with a nested result to recover the previous spread over log-likelihood ranks. In that mode, the RMS, percentiles, and failure rate summarize coverage draws, not posterior probability. The result records its selection.
audit_posterior_native evaluates over the fixed observation mask (required_mask) and reports n_failed_draws, failure_rate, and bin_failure_rate separately whenever native draws return NaN/inf, rather than treating failed predictions as zero error.
Project out the top spectrally smooth eigenmodes along the line-of-sight axis before computing power spectra or feeding SBI networks:
diag = p21.remove_foreground_pca_3d(
tb_cube, n_modes=3, los_axis=2, return_diagnostics=True
)
cleaned_cube = diag["cleaned"]
explained = diag["explained_variance_ratio"]See the complete runnable example in examples/10_ultranest_and_21cmmc_inference.py.
Jointly constrain galaxy star-formation efficiency alongside 21cm power spectra by evaluating 21cmFAST's native ComputeLF UV luminosity function across redshifts inside UVLFLikelihood:
ll_uv = p21.UVLFLikelihood(
base_inputs=base_inputs,
param_names=["F_STAR10_ACG", "F_ESC10_ACG"],
redshifts=[6.0, 8.0, 10.0],
m_uv_obs=muv_grid, # shape (n_z, n_mag)
log10_phi_obs=log10_phi_grid, # shape (n_z, n_mag)
sigma_log10_phi=0.15,
component="both", # "both", "acg", or "mcg"
model_error_frac=0.05, # includes -sum log(sigma_eff) normalization
)
joint = p21.JointLikelihood(
components={"21cm": ll_21cm, "uvlf": ll_uv},
weights={"21cm": 1.0, "uvlf": 1.0},
)UVLFLikelihood shares Likelihood21cm's deterministic SHA-256 checkpoint provenance: modifying observed magnitudes, errors, redshifts, or component causes resume=True to reject stale checkpoints.
Pair SBISimulator with sequential posterior-density, ensemble epistemic uncertainty, max-entropy, or hybrid acquisition functions while reducing cosmic variance via fixed_paired_initial_conditions:
# Generate variance-reduced Fixed-and-Paired initial conditions (Angulo & Pontzen 2016)
ic_plus, ic_minus = p21.fixed_paired_initial_conditions(
dim=128, hii_dim=64, box_len=200.0, seed=42, fix_amplitude=True, paired=True
)
# Run active simulation rounds with diverse candidate acquisition
loop = p21.ActiveSBILoop(
sbi_sim,
param_bounds={"F_STAR10_ACG": (-2.0, -0.5), "F_ESC10_ACG": (-2.0, -0.3)},
acquisition="hybrid", # "posterior_density", "ensemble_std", "max_entropy", "hybrid"
n_init=64,
n_per_round=32,
n_candidates=1024,
diversity_weight=0.25,
)
steps = loop.run(n_rounds=3, train_fn=train_posterior_or_ensemble, x_obs=obs_summary)
print(steps[-1].n_total, steps[-1].wall_s)Each round returns an ActiveSBIStepResult containing selected_theta, selected_x, scores, total_theta, and total_x.
21cmCU v1.0.0 · Native C/CUDA + cuFFT Engine for 21cmFAST v4 · See CHANGELOG.md and BENCHMARKS.md in the main repository.
Getting Started
Simulation & Science Pipelines
- Precision Modes & Calibration
- Multi-GPU & Large Grids
- Distributed NCCL & Multi-Node
- Residency & I/O
- SBI & Batch Pipeline
- Bayesian Inference & Samplers
- Multi-Probe, Fisher & Topology
- Interferometer Mock & Forecast
- Lightcone Optimization & 3D Viz
Reference