bayspec.infer package

Submodules

bayspec.infer.infer module

Inference drivers: base aggregator, Bayesian samplers, and max-likelihood fits.

Infer aggregates one or more (Data, Model) pairs, resolves shared parameters through the linking machinery, and exposes the joint prior, log-likelihood, and fit-statistic entry points that the samplers consume. BayesInfer adds driver methods for MultiNest and emcee; MaxLikeFit adds lmfit and iminuit minimisers plus covariance-driven bootstrap sampling.

class bayspec.infer.infer.Infer(pairs=None)[source]

Bases: object

Aggregate of one or more (Data, Model) pairs with shared parameters.

Collects per-pair parameters into a single flat index, identifies which of them are free (after honouring Par.link/unlink relations and the frozen flag), and publishes the pooled log-likelihood, log-prior, fit statistic, and residuals.

Group docstring for aggregator properties. List-valued data_* properties flatten the same-named Data property over every bound Data; model_* properties flatten the matching Model property over every bound Model. The family covers the following patterns (the _re_ infix uses re-binned channels):

  • data_chbin_mean/_re_, data_chbin_width/_re_ (sourced from rsp_chbin_*);

  • data_{ctsrate,ctsspec,phtspec,flxspec,ergspec} plus their _error/_re_ variants (net counts and deconvolved spectra);

  • model_{ctsrate,ctsspec,phtspec,flxspec,ergspec} plus their _re_ variants (convolved model spectra sampled at the data channels).

Variables:
  • pairs – The raw list of (Data, Model) tuples.

  • Data/Model/Pair – Per-pair unpacked containers.

  • inference_type – Display label shown in __str__().

  • loglike_func/logprior_func/prior_transform_func – Optional user overrides for the corresponding computations; None means use the built-in implementation.

property pairs
append(*pair)[source]

Append a (Data, Model) or (Model, Data) pair and re-extract.

Parameters:

*pair – Two positional arguments, one Data and one Model in either order.

property cdicts

Mapping from every model expression to its cdicts dictionary.

property pdicts

Mapping from every model/data expression to its pdicts dictionary.

property cfg

Flat SuperDict of every model config parameter.

property par

Flat SuperDict of every model+data parameter (free or frozen).

property pvalues

Tuple of current parameter values, preserving par order.

static foo(id)[source]

Recover the Python object at address id via ctypes reflection.

property idpid

Map each id(Par) to the set of par# indices it occupies.

Used to detect which parameter slots share the same underlying Par instance (linked parameters).

property all_config

List of per-config rows tagged with component and class (model/data).

property all_params

List of per-parameter rows, with linked-parameter mates resolved.

Link every Par in pids so they share value/prior/posterior.

Parameters:

pids – Iterable of par# indices (as strings or ints).

Undo any linking between every pair drawn from pids.

Parameters:

pids – Iterable of par# indices.

property free_par

SuperDict of the free Par instances keyed by par#.

property free_params

Rows from all_params restricted to the free parameters.

property free_plabels

LaTeX-decorated labels of the free parameters, in canonical order.

property clean_free_plabels

free_plabels with LaTeX braces, dollars, and backslashes stripped.

property free_indexed_plabels

Free-parameter labels prefixed with their par# index.

property clean_free_indexed_plabels

Indexed labels with LaTeX markup removed.

property free_pvalues

Current values of every free parameter.

property free_pranges

Per-parameter (low, high) plausible ranges used by minimisers.

property free_nparams

Number of free parameters.

property cfg_info

Tabular Info view of every configuration parameter.

property par_info

Tabular parameter view tagging free slots with * and resolving linked aliases.

property notable_par_info

Parameter view like par_info but hides frozen data-level rows.

property free_par_info

Tabular Info view restricted to the free parameters.

save(savepath)[source]

Dump config and parameter tables under savepath.

Parameters:

savepath – Directory path. Created if missing.

property data_chbin_mean

Concatenated per-channel midpoints from every bound Data.

Every data_* and model_* property on this class flattens the same-named list from the underlying Data/Model across every pair, so downstream code can treat the whole inference as a single long series.

property data_re_chbin_mean
property data_chbin_width
property data_re_chbin_width
property data_ctsrate
property data_re_ctsrate
property data_ctsrate_error
property data_re_ctsrate_error
property data_ctsspec
property data_re_ctsspec
property data_ctsspec_error
property data_re_ctsspec_error
property data_phtspec
property data_re_phtspec
property data_phtspec_error
property data_re_phtspec_error
property data_flxspec
property data_re_flxspec
property data_flxspec_error
property data_re_flxspec_error
property data_ergspec
property data_re_ergspec
property data_ergspec_error
property data_re_ergspec_error
property model_ctsrate
property model_re_ctsrate
property model_ctsspec
property model_re_ctsspec
property model_phtspec
property model_re_phtspec
property model_flxspec
property model_re_flxspec
property model_ergspec
property model_re_ergspec
property residual

Per-unit sigma residuals aggregated across every pair.

property re_residual

Per-unit sigma residuals on the re-binned grid.

property prior_list

Per-parameter prior densities evaluated at the current free values.

property prior

Joint prior density as the product of prior_list.

property logprior

Joint log-prior; -inf when the prior vanishes.

property stat_list

Concatenated per-unit statistic across every pair.

property pseudo_residual_list

Concatenated per-unit pseudo-residual arrays across every pair.

property weight_list

Concatenated per-unit weights across every pair.

property stat

Summed fit statistic across every pair.

property pseudo_residual

Concatenated weight-scaled pseudo-residual vector across every pair.

property loglike_list

Concatenated per-unit log-likelihood across every pair.

property loglike

Summed log-likelihood across every pair.

property npoint_list

Concatenated per-unit point counts across every pair.

property npoint

Total number of fitted data points across every pair.

property dof

npoint minus the free-parameter count.

Type:

Degrees of freedom

property all_stat

Per-pair statistic summary plus a totals row, ready for Info.from_dict.

property stat_info

Tabular Info view of all_stat.

at_par(theta)[source]

Write free-parameter values from the 1-indexed sequence theta.

property prior_transform_func

Optional user override for the unit-cube to prior transform.

property logprior_func

Optional user override for the log-prior computation.

property loglike_func

Optional user override for the log-likelihood computation.

prior_transform(cube)[source]

Transform a unit cube to parameter space via each prior’s inverse CDF.

Delegates to prior_transform_func when it has been set.

Parameters:

cube – Array-like of length free_nparams in [0, 1].

Returns:

Transformed parameter vector of the same length.

calc_logprior(theta)[source]

Apply theta and return the log-prior (or the user override).

calc_stat(theta)[source]

Apply theta and return the summed fit statistic.

calc_pseudo_residual(theta)[source]

Apply theta and return the concatenated pseudo-residual vector.

calc_loglike(theta)[source]

Apply theta and return the log-likelihood (or the user override).

calc_logprob(theta)[source]

Return the unnormalised log-posterior; -inf outside the prior support.

calc_logprior_sample(theta_sample)[source]

Vectorized log-prior over a sample matrix; returns -inf where it vanishes.

Parameters:

theta_sample(nsample, nparams) array of draws.

Returns:

(nsample,) array of log-prior values.

class bayspec.infer.infer.BayesInfer(pairs=None)[source]

Bases: Infer

Infer extension that wires up MultiNest and emcee drivers.

Adds multinest and emcee methods that run the samplers, persist chains to savepath, and return a Posterior for downstream analysis.

multinest_prior_transform(cube)[source]

MultiNest-facing wrapper around prior_transform().

multinest_calc_loglike(theta)[source]

MultiNest-facing wrapper around calc_loglike().

multinest_safe_prior_transform(cube, ndim, nparams)[source]

MultiNest C-callback wrapper that writes cube in place.

Terminates the process on any Python-level exception so MultiNest does not silently swallow it.

multinest_safe_calc_loglike(cube, ndim, nparams, lnew)[source]

MultiNest C-callback log-likelihood; returns -2e100 when non-finite.

multinest(nlive=500, resume=True, verbose=False, max_iter=None, ins=True, savepath='./', random_seed=None)[source]

Run MultiNest and return a Posterior wrapping the result.

Parameters:
  • nlive – Number of live points.

  • resume – Resume from any chain already present under savepath.

  • verbose – Forward MultiNest’s verbose flag.

  • max_iter – Hard cap on nested-sampling iterations, a backstop against runs that never reach the evidence tolerance (e.g. likelihood plateaus). None (default) caps at nlive * 50, well above the ~nlive * H a normal run needs, so it never clips genuine convergence. A run that hits this cap has not converged; its result is unreliable.

  • ins – Enable INS for a more accurate evidence. True (default) suits most fits, but INS weights can underflow when the posterior rails against a hard prior boundary, yielding a NaN/subnormal evidence that corrupts stats.dat. Set False for such boundary-pinned fits to fall back to the robust plain nested-sampling evidence.

  • savepath – Directory for MultiNest outputs and cached samples.

  • random_seed – Seed forwarded to MultiNest for reproducible runs. None (default) lets MultiNest pick a system-time seed, so different runs differ.

Returns:

A Posterior.

emcee_calc_logprob(theta)[source]

emcee-facing wrapper around calc_logprob().

emcee(nstep=1000, discard=100, resume=True, savepath='./', random_seed=None)[source]

Run emcee and return a Posterior wrapping the flattened chain.

Parameters:
  • nstep – Number of MCMC steps per walker.

  • discard – Burn-in steps discarded before flattening.

  • resume – Reuse an existing chain cached under savepath.

  • savepath – Directory for chain outputs.

  • random_seed – Seed for reproducible runs. None (default) lets emcee draw fresh entropy, so different runs differ.

Returns:

A Posterior.

class bayspec.infer.infer.MaxLikeFit(pairs=None)[source]

Bases: Infer

Infer extension for maximum-likelihood fits with bootstrap sampling.

Provides lmfit() and iminuit() drivers. Both run the minimiser, cache the best fit, build a covariance-driven bootstrap sample respecting the free-parameter ranges, and return a Bootstrap for downstream analysis.

lmfit_residual(params)[source]

lmfit-facing residual callback; delegates to calc_pseudo_residual().

lmfit(savepath=None)[source]

Run lmfit.minimize on the pseudo-residuals and bootstrap the result.

Parameters:

savepath – Optional directory for persisted bootstrap samples and summary JSON; pass None to skip disk IO.

Returns:

A Bootstrap.

iminuit_cost(*theta)[source]

iminuit-facing cost function; returns 1e100 when the stat is non-finite.

iminuit(savepath=None)[source]

Run iminuit’s migrad + hesse + minos and bootstrap the result.

Parameters:

savepath – Optional directory for persisted bootstrap samples and summary JSON.

Returns:

A Bootstrap.

bayspec.infer.pair module

Binding between a Data and a Model for fit evaluation.

Holds the bound model-data pair, caches the forward convolution through the detector response, exposes both observed and convolved count rates/densities, and aggregates the per-unit likelihood statistic that the inference layer minimises.

class bayspec.infer.pair.Pair(data, model)[source]

Bases: object

Binds one Data and one Model and evaluates their joint statistic.

The class dispatches on each unit’s statistic tag (pgstat, pstat, cstat, chi2, etc.) via _allowed_stats and publishes convolved spectra, residuals, and the total log-likelihood.

Most list-valued properties (conv_ctsrate, phtspec_at_rsp, cts_to_pht, deconv_*, …) mirror the same-named properties on Model but are computed from the paired data rather than model.fit_to.

Variables:
  • data – The bound Data.

  • model – The bound Model.

property data
property model
property conv_ctsrate

Per-unit convolved count rate for the paired model.

Every conv_*, *_at_rsp, cts_to_*, deconv_* family on this class mirrors the same-named Model property but uses the paired data so the values are consistent with the current Pair.

property conv_ctsrate_f64

Same as conv_ctsrate but cast to float64 for statistics.

property conv_re_ctsrate

Convolved count rate on the re-binned detector response.

property conv_ctsspec

conv_ctsrate divided by bin width.

Type:

Convolved count density

property conv_re_ctsspec

Convolved count density on the re-binned response.

property phtspec_at_rsp

Photon spectrum sampled at the response channel midpoints.

property re_phtspec_at_rsp
property flxspec_at_rsp
property re_flxspec_at_rsp
property ergspec_at_rsp
property re_ergspec_at_rsp
property cts_to_pht
property re_cts_to_pht
property cts_to_flx
property re_cts_to_flx
property cts_to_erg
property re_cts_to_erg
property rate_to_flux

Per-unit ratio of integrated energy flux to observed net count rate.

property conv_rate_to_flux

Like rate_to_flux but using the convolved-model count rate.

rate_to_fluxdensity(E=1, T=None, unit='fv')[source]

Per-unit conversion from net count rate to flux density at (E, T).

Parameters:
  • E – Energy at which the flux density is evaluated.

  • T – Optional time.

  • unit'NE' (photon flux density), 'Fv' (energy flux density), or 'Jy'.

Returns:

A list of per-unit conversion factors.

Raises:

ValueError – If unit is not recognized.

conv_rate_to_fluxdensity(E=1, T=None, unit='fv')[source]

Like rate_to_fluxdensity() but using convolved count rates.

property deconv_phtspec

net counts × paired-model cts_to_pht.

Sibling deconv_* properties (deconv_re_phtspec, deconv_phtspec_error, deconv_flxspec, deconv_ergspec and their _re_/_error variants) follow the same pattern for photon, flux, and energy spectra on the full or re-binned channel grids.

Type:

Deconvolved photon spectrum

property deconv_re_phtspec
property deconv_phtspec_error
property deconv_re_phtspec_error
property deconv_flxspec
property deconv_re_flxspec
property deconv_flxspec_error
property deconv_re_flxspec_error
property deconv_ergspec
property deconv_re_ergspec
property deconv_ergspec_error
property deconv_re_ergspec_error
property residual

Per-unit sigma residuals (observed - model) / error on the full grid.

property re_residual

Per-unit sigma residuals on the re-binned grid.

property stat_func

Closure returning the per-unit statistic; +inf when the model is non-finite.

property pseudo_residual_func

Closure returning the per-bin pseudo-residual from the chosen statistic.

property stat_list

Array of per-unit statistic values.

property pseudo_residual_list

List of per-unit pseudo-residual arrays.

property weight_list

Per-unit likelihood weights taken from the paired Data.

property stat

Total weighted statistic summed across all units.

property pseudo_residual

Weight-scaled pseudo-residual vector concatenated across all units.

property loglike_list

Per-unit log-likelihood, derived as -0.5 * stat_list.

property loglike

Total log-likelihood, derived as -0.5 * stat.

property npoint_list

Per-unit number of fitted data points.

property npoint

Total number of fitted data points across all units.

bayspec.infer.analyzer module

Post-fit analyzers for posterior samples and bootstrap ensembles.

SampleAnalyzer absorbs an Infer instance, reads a 2D sample matrix (param_sample plus a trailing log-probability column), attaches the draws to every free parameter’s Post, and exposes point estimates, credible intervals, and model-selection scores (AIC/AICc/BIC, optionally lnZ).

Posterior and Bootstrap are thin subclasses that pick which attribute of the underlying Infer carries the sample matrix.

class bayspec.infer.analyzer.SampleAnalyzer(infer)[source]

Bases: Infer

Wrap an Infer with posterior-/bootstrap-driven summary views.

The sample matrix is expected to have shape (nsample, nfree + 1), where the last column holds the log-probability associated with each draw. Subclasses set sample_attribute to the instance attribute (posterior_sample or bootstrap_sample) that stores the matrix.

Variables:
  • sample_attribute – Name of the source Infer attribute; set by each subclass.

  • analyzer_type – Display label shown in __str__().

  • save_prefix – File-name prefix used by save().

sample_attribute = None
analyzer_type = 'Sample Analysis Results'
save_prefix = 'sample'
property infer
property sample_statistic

Mean, median, and 1/2/3-sigma intervals of param_sample.

property par_mean

Per-parameter posterior means drawn from each Post.

property par_median

Per-parameter posterior medians.

property par_best

Per-parameter highest-log-probability draws.

property par_best_ci

Per-parameter draw selected via _allot_best_ci().

property par_truth

Per-parameter truth value stored in each Post, or None.

par_quantile(q)[source]

Per-parameter q-quantile of the posterior.

Parameters:

q – Probability or array of probabilities in [0, 1].

par_interval(q)[source]

Per-parameter central q-credible interval.

property par_Isigma

Per-parameter one-sigma credible interval.

property par_IIsigma

Per-parameter two-sigma credible interval.

property par_IIIsigma

Per-parameter three-sigma credible interval.

property par_ninety_percent

Per-parameter 90% credible interval.

par_error(par, q=0.6827)[source]

Per-parameter asymmetric errors of par against the q-interval.

Parameters:
  • par – Sequence of per-parameter point estimates.

  • q – Central credible level.

Returns:

List of [lower_error, upper_error] pairs aligned with par.

property max_loglike

Log-likelihood evaluated at the best-fit parameter vector.

property aic

Akaike information criterion AIC = -2 ln L + 2 k.

property aicc

Finite-sample corrected AIC.

property bic

Bayesian information criterion BIC = -2 ln L + k ln n.

property lnZ

Log-evidence supplied by the nested sampler, or None.

property free_par_info

Tabular Info of free parameters with posterior summaries.

property stat_info

Tabular Info of the fit statistic evaluated at the best fit.

property all_IC

Ordered dictionary of AIC/AICc/BIC/lnZ values.

property IC_info

Tabular Info view of all_IC.

save(savepath)[source]

Dump free-parameter, statistic, and IC tables under savepath.

Parameters:

savepath – Directory path. Created if missing.

class bayspec.infer.analyzer.Posterior(infer)[source]

Bases: SampleAnalyzer

Analyzer specialised for Bayesian posterior samples.

sample_attribute = 'posterior_sample'
analyzer_type = 'Posterior Results'
save_prefix = 'post'
class bayspec.infer.analyzer.Bootstrap(infer)[source]

Bases: SampleAnalyzer

Analyzer specialised for maximum-likelihood bootstrap ensembles.

The first row of bootstrap_sample is treated as the best-fit truth; its value is copied onto each parameter’s Post so downstream consumers can access it as par.post.truth.

sample_attribute = 'bootstrap_sample'
analyzer_type = 'Bootstrap Results'
save_prefix = 'boot'
property max_loglike

Log-likelihood evaluated at the best-fit truth vector.

bayspec.infer.statistic module

Likelihood-statistic kernels for spectral fitting.

Implements the Gaussian (Gstat), Poisson (Pstat), Poisson-source plus Poisson-background (PPstat/cstat), Poisson-source plus Gaussian-background (PGstat) statistics, and their upper-limit variants. StatisticNB exposes the numba-accelerated fast path (fused stat + signed residual per bin); Statistic is a pure-numpy fallback with the same interface.

Every statistic takes the same keyword arguments (S, B, m, ts, tb, sigma_S, sigma_B) and returns (stat, residual) where residual is the signed square-root of the per-bin statistic contribution.

class bayspec.infer.statistic.StatisticNB[source]

Bases: object

Numba-accelerated statistic dispatch table.

Every method takes the standard keyword bundle (S, B, m, ts, tb, sigma_S, sigma_B) and returns (stat, residual). Upper-limit variants compare a significance against a target (default 3σ) so that a minimiser can search for the model normalization that produces the requested sigma.

static Gstat(**kwargs)[source]

Gaussian statistic; delegates to _gstat_core().

static Pstat(**kwargs)[source]

Pure-Poisson statistic (no background); delegates to _pstat_core().

static PPstat(**kwargs)[source]

Profile Poisson-Poisson statistic (cstat); uses _ppstat_core().

static PGstat(**kwargs)[source]

Profile Poisson-Gaussian statistic; uses _pgstat_core().

static PPstat_UL(**kwargs)[source]

Upper-limit driver for PPstat: minimize (sigma - 3)^2.

static PGstat_UL(**kwargs)[source]

Upper-limit driver for PGstat: minimize (sigma - 3)^2.

class bayspec.infer.statistic.Statistic[source]

Bases: object

Pure-numpy fallback mirror of StatisticNB.

Same (stat, residual) contract as the numba-accelerated class, intended for debugging and for environments where numba cannot be used. Every method returns the total statistic plus the signed per-bin residual.

static xlogy(x, y)[source]

Return x * log(y) element-wise, treating 0 * log(y) as 0 for any y.

static xdivy(x, y)[source]

Return x / y element-wise, treating 0 / 0 as 0.

static poisson_logpmf(k, mu)[source]

Poisson log-PMF with Stirling’s approximation for log(k!).

Drops the log(2πk) / 2 term, so the result is accurate up to an additive constant that cancels in likelihood ratios.

static gaussian_logpdf(x, loc, scale)[source]

Gaussian log-PDF dropping the log(2π σ²) normalization constant.

static Gstat(**kwargs)[source]

Gaussian source-background statistic (Gstat/chi2).

static Pstat(**kwargs)[source]

Pure-Poisson statistic when the background is ignored.

static PPstat(**kwargs)[source]

Profile Poisson-Poisson statistic (cstat equivalent).

PGstat()[source]

Profile Poisson-Gaussian statistic (XSPEC-style pgstat).

static PPstat_UL(**kwargs)[source]

Upper-limit driver for PPstat: minimize (sigma - 3)^2.

static PGstat_UL(**kwargs)[source]

Upper-limit driver for PGstat: minimize (sigma - 3)^2.

Module contents

Inference layer: model-data pairing, statistics, samplers, and analyzers.