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

emcee(nstep=1000, discard=100, resume=True, savepath='./')[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.

Returns:

A Posterior.

emcee_calc_logprob(theta)[source]

emcee-facing wrapper around calc_logprob().

multinest(nlive=500, resume=True, verbose=False, savepath='./')[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.

  • savepath – Directory for MultiNest outputs and cached samples.

Returns:

A Posterior.

multinest_calc_loglike(theta)[source]

MultiNest-facing wrapper around calc_loglike().

multinest_prior_transform(cube)[source]

MultiNest-facing wrapper around prior_transform().

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

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

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.

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

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

property all_stat

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

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.

at_par(theta)[source]

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

calc_loglike(theta)[source]

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

calc_logprior(theta)[source]

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

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.

calc_logprob(theta)[source]

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

calc_pseudo_residual(theta)[source]

Apply theta and return the concatenated pseudo-residual vector.

calc_stat(theta)[source]

Apply theta and return the summed fit statistic.

property cdicts

Mapping from every model expression to its cdicts dictionary.

property cfg

Flat SuperDict of every model config parameter.

property cfg_info

Tabular Info view of every configuration parameter.

property clean_free_indexed_plabels

Indexed labels with LaTeX markup removed.

property clean_free_plabels

free_plabels with LaTeX braces, dollars, and backslashes stripped.

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_chbin_width
property data_ctsrate
property data_ctsrate_error
property data_ctsspec
property data_ctsspec_error
property data_ergspec
property data_ergspec_error
property data_flxspec
property data_flxspec_error
property data_phtspec
property data_phtspec_error
property data_re_chbin_mean
property data_re_chbin_width
property data_re_ctsrate
property data_re_ctsrate_error
property data_re_ctsspec
property data_re_ctsspec_error
property data_re_ergspec
property data_re_ergspec_error
property data_re_flxspec
property data_re_flxspec_error
property data_re_phtspec
property data_re_phtspec_error
property dof

npoint minus the free-parameter count.

Type:

Degrees of freedom

static foo(id)[source]

Recover the Python object at address id via ctypes reflection.

property free_indexed_plabels

Free-parameter labels prefixed with their par# index.

property free_nparams

Number of free parameters.

property free_par

SuperDict of the free Par instances keyed by par#.

property free_par_info

Tabular Info view restricted to the free parameters.

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 free_pranges

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

property free_pvalues

Current values of every free parameter.

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

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

Parameters:

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

property loglike

Summed log-likelihood across every pair.

property loglike_func

Optional user override for the log-likelihood computation.

property loglike_list

Concatenated per-unit log-likelihood across every pair.

property logprior

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

property logprior_func

Optional user override for the log-prior computation.

property model_ctsrate
property model_ctsspec
property model_ergspec
property model_flxspec
property model_phtspec
property model_re_ctsrate
property model_re_ctsspec
property model_re_ergspec
property model_re_flxspec
property model_re_phtspec
property notable_par_info

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

property npoint

Total number of fitted data points across every pair.

property npoint_list

Concatenated per-unit point counts across every pair.

property pairs
property par

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

property par_info

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

property pdicts

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

property prior

Joint prior density as the product of prior_list.

property prior_list

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

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.

property prior_transform_func

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

property pseudo_residual

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

property pseudo_residual_list

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

property pvalues

Tuple of current parameter values, preserving par order.

property re_residual

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

property residual

Per-unit sigma residuals aggregated across every pair.

save(savepath)[source]

Dump config and parameter tables under savepath.

Parameters:

savepath – Directory path. Created if missing.

property stat

Summed fit statistic across every pair.

property stat_info

Tabular Info view of all_stat.

property stat_list

Concatenated per-unit statistic across every pair.

Undo any linking between every pair drawn from pids.

Parameters:

pids – Iterable of par# indices.

property weight_list

Concatenated per-unit weights across every pair.

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.

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.

iminuit_cost(*theta)[source]

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

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.

lmfit_residual(params)[source]

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

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.

data

The bound Data.

model

The bound 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_ctsspec

conv_ctsrate divided by bin width.

Type:

Convolved count density

property conv_rate_to_flux

Like rate_to_flux but using the convolved-model count rate.

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

Like rate_to_fluxdensity() but using convolved count rates.

property conv_re_ctsrate

Convolved count rate on the re-binned detector response.

property conv_re_ctsspec

Convolved count density on the re-binned response.

property cts_to_erg
property cts_to_flx
property cts_to_pht
property data
property deconv_ergspec
property deconv_ergspec_error
property deconv_flxspec
property deconv_flxspec_error
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_phtspec_error
property deconv_re_ergspec
property deconv_re_ergspec_error
property deconv_re_flxspec
property deconv_re_flxspec_error
property deconv_re_phtspec
property deconv_re_phtspec_error
property ergspec_at_rsp
property flxspec_at_rsp
property loglike

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

property loglike_list

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

property model
property npoint

Total number of fitted data points across all units.

property npoint_list

Per-unit number of fitted data points.

property phtspec_at_rsp

Photon spectrum sampled at the response channel midpoints.

property pseudo_residual

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

property pseudo_residual_func

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

property pseudo_residual_list

List of per-unit pseudo-residual arrays.

property rate_to_flux

Per-unit ratio of integrated energy flux to observed net 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.

property re_cts_to_erg
property re_cts_to_flx
property re_cts_to_pht
property re_ergspec_at_rsp
property re_flxspec_at_rsp
property re_phtspec_at_rsp
property re_residual

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

property residual

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

property stat

Total weighted statistic summed across all units.

property stat_func

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

property stat_list

Array of per-unit statistic values.

property weight_list

Per-unit likelihood weights taken from the paired Data.

bayspec.infer.posterior module

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.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 Gstat(**kwargs)[source]

Gaussian source-background statistic (Gstat/chi2).

PGstat()[source]

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

static PGstat_UL(**kwargs)[source]

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

static PPstat(**kwargs)[source]

Profile Poisson-Poisson statistic (cstat equivalent).

static PPstat_UL(**kwargs)[source]

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

static Pstat(**kwargs)[source]

Pure-Poisson statistic when the background is ignored.

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

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

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 xdivy(x, y)[source]

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

static xlogy(x, y)[source]

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

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 PGstat(**kwargs)[source]

Profile Poisson-Gaussian statistic; uses _pgstat_core().

static PGstat_UL(**kwargs)[source]

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

static PPstat(**kwargs)[source]

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

static PPstat_UL(**kwargs)[source]

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

static Pstat(**kwargs)[source]

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

Module contents

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