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:
objectAggregate 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/unlinkrelations 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-namedDataproperty over every boundData;model_*properties flatten the matchingModelproperty over every boundModel. The family covers the following patterns (the_re_infix uses re-binned channels):data_chbin_mean/_re_,data_chbin_width/_re_(sourced fromrsp_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;
Nonemeans 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
Dataand oneModelin either order.
- property cdicts¶
Mapping from every model expression to its
cdictsdictionary.
- property pdicts¶
Mapping from every model/data expression to its
pdictsdictionary.
- property cfg¶
Flat
SuperDictof every model config parameter.
- property par¶
Flat
SuperDictof every model+data parameter (free or frozen).
- property pvalues¶
Tuple of current parameter values, preserving
parorder.
- property idpid¶
Map each
id(Par)to the set ofpar#indices it occupies.Used to detect which parameter slots share the same underlying
Parinstance (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(pids)[source]¶
Link every
Parinpidsso they share value/prior/posterior.- Parameters:
pids – Iterable of
par#indices (as strings or ints).
- unlink(pids)[source]¶
Undo any linking between every pair drawn from
pids.- Parameters:
pids – Iterable of
par#indices.
- property free_par¶
SuperDictof the freeParinstances keyed bypar#.
- property free_params¶
Rows from
all_paramsrestricted to the free parameters.
- property free_plabels¶
LaTeX-decorated labels of the free parameters, in canonical order.
- property clean_free_plabels¶
free_plabelswith 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
Infoview of every configuration parameter.
- property par_info¶
Tabular parameter view tagging free slots with
*and resolving linked aliases.
- property free_par_info¶
Tabular
Infoview 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_*andmodel_*property on this class flattens the same-named list from the underlyingData/Modelacross 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;
-infwhen 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 all_stat¶
Per-pair statistic summary plus a totals row, ready for
Info.from_dict.
- 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_funcwhen it has been set.- Parameters:
cube – Array-like of length
free_nparamsin[0, 1].- Returns:
Transformed parameter vector of the same length.
- class bayspec.infer.infer.BayesInfer(pairs=None)[source]¶
Bases:
InferInferextension that wires up MultiNest and emcee drivers.Adds
multinestandemceemethods that run the samplers, persist chains tosavepath, and return aPosteriorfor downstream analysis.- multinest_safe_prior_transform(cube, ndim, nparams)[source]¶
MultiNest C-callback wrapper that writes
cubein 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
-2e100when non-finite.
- multinest(nlive=500, resume=True, verbose=False, max_iter=None, ins=True, savepath='./', random_seed=None)[source]¶
Run MultiNest and return a
Posteriorwrapping 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 atnlive * 50, well above the~nlive * Ha 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 corruptsstats.dat. SetFalsefor 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(nstep=1000, discard=100, resume=True, savepath='./', random_seed=None)[source]¶
Run emcee and return a
Posteriorwrapping 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:
InferInferextension for maximum-likelihood fits with bootstrap sampling.Provides
lmfit()andiminuit()drivers. Both run the minimiser, cache the best fit, build a covariance-driven bootstrap sample respecting the free-parameter ranges, and return aBootstrapfor downstream analysis.- lmfit_residual(params)[source]¶
lmfit-facing residual callback; delegates to
calc_pseudo_residual().
- lmfit(savepath=None)[source]¶
Run
lmfit.minimizeon the pseudo-residuals and bootstrap the result.- Parameters:
savepath – Optional directory for persisted bootstrap samples and summary JSON; pass
Noneto skip disk IO.- 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:
objectBinds one
Dataand oneModeland evaluates their joint statistic.The class dispatches on each unit’s statistic tag (
pgstat,pstat,cstat,chi2, etc.) via_allowed_statsand 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 onModelbut are computed from the paireddatarather thanmodel.fit_to.- 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-namedModelproperty but uses the paireddataso the values are consistent with the currentPair.
- property conv_ctsrate_f64¶
Same as
conv_ctsratebut cast tofloat64for statistics.
- property conv_re_ctsrate¶
Convolved count rate on the re-binned detector response.
- property conv_ctsspec¶
conv_ctsratedivided 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_fluxbut 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
unitis 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_ergspecand their_re_/_errorvariants) 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) / erroron the full grid.
- property re_residual¶
Per-unit sigma residuals on the re-binned grid.
- property stat_func¶
Closure returning the per-unit statistic;
+infwhen 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:
InferWrap an
Inferwith 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 setsample_attributeto the instance attribute (posterior_sampleorbootstrap_sample) that stores the matrix.- Variables:
sample_attribute – Name of the source
Inferattribute; 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, orNone.
- par_quantile(q)[source]¶
Per-parameter
q-quantile of the posterior.- Parameters:
q – Probability or array of probabilities in
[0, 1].
- 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
paragainst theq-interval.- Parameters:
par – Sequence of per-parameter point estimates.
q – Central credible level.
- Returns:
List of
[lower_error, upper_error]pairs aligned withpar.
- 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
Infoof free parameters with posterior summaries.
- property stat_info¶
Tabular
Infoof the fit statistic evaluated at the best fit.
- property all_IC¶
Ordered dictionary of AIC/AICc/BIC/lnZ values.
- class bayspec.infer.analyzer.Posterior(infer)[source]¶
Bases:
SampleAnalyzerAnalyzer specialised for Bayesian posterior samples.
- sample_attribute = 'posterior_sample'¶
- analyzer_type = 'Posterior Results'¶
- save_prefix = 'post'¶
- class bayspec.infer.analyzer.Bootstrap(infer)[source]¶
Bases:
SampleAnalyzerAnalyzer specialised for maximum-likelihood bootstrap ensembles.
The first row of
bootstrap_sampleis treated as the best-fit truth; its value is copied onto each parameter’sPostso downstream consumers can access it aspar.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:
objectNumba-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.
- class bayspec.infer.statistic.Statistic[source]¶
Bases:
objectPure-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 poisson_logpmf(k, mu)[source]¶
Poisson log-PMF with Stirling’s approximation for
log(k!).Drops the
log(2πk) / 2term, so the result is accurate up to an additive constant that cancels in likelihood ratios.
Module contents¶
Inference layer: model-data pairing, statistics, samplers, and analyzers.