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:
InferInferextension that wires up MultiNest and emcee drivers.Adds
multinestandemceemethods that run the samplers, persist chains tosavepath, and return aPosteriorfor downstream analysis.- emcee(nstep=1000, discard=100, resume=True, savepath='./')[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.
- Returns:
A
Posterior.
- multinest(nlive=500, resume=True, verbose=False, savepath='./')[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.
savepath – Directory for MultiNest outputs and cached samples.
- Returns:
A
Posterior.
- 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).
- 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 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
Dataand oneModelin either order.
- calc_logprior_sample(theta_sample)[source]¶
Vectorized log-prior over a sample matrix; returns
-infwhere it vanishes.- Parameters:
theta_sample –
(nsample, nparams)array of draws.- Returns:
(nsample,)array of log-prior values.
- calc_pseudo_residual(theta)[source]¶
Apply
thetaand return the concatenated pseudo-residual vector.
- property cdicts¶
Mapping from every model expression to its
cdictsdictionary.
- property cfg¶
Flat
SuperDictof every model config parameter.
- property cfg_info¶
Tabular
Infoview of every configuration parameter.
- property clean_free_indexed_plabels¶
Indexed labels with LaTeX markup removed.
- property clean_free_plabels¶
free_plabelswith LaTeX braces, dollars, and backslashes stripped.
- 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_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 free_indexed_plabels¶
Free-parameter labels prefixed with their
par#index.
- property free_nparams¶
Number of free parameters.
- property free_par¶
SuperDictof the freeParinstances keyed bypar#.
- property free_par_info¶
Tabular
Infoview restricted to the free parameters.
- 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 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 ofpar#indices it occupies.Used to detect which parameter slots share the same underlying
Parinstance (linked parameters).
- link(pids)[source]¶
Link every
Parinpidsso 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;
-infwhen 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 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
SuperDictof 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
pdictsdictionary.
- 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_funcwhen it has been set.- Parameters:
cube – Array-like of length
free_nparamsin[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
parorder.
- 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_list¶
Concatenated per-unit statistic across every pair.
- unlink(pids)[source]¶
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:
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.- iminuit(savepath=None)[source]¶
Run iminuit’s
migrad+hesse+minosand 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
1e100when the stat is non-finite.
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 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_ctsspec¶
conv_ctsratedivided by bin width.- Type:
Convolved count density
- property conv_rate_to_flux¶
Like
rate_to_fluxbut 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_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_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
unitis 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) / erroron the full grid.
- property stat¶
Total weighted statistic summed across all units.
- property stat_func¶
Closure returning the per-unit statistic;
+infwhen 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:
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 gaussian_logpdf(x, loc, scale)[source]¶
Gaussian log-PDF dropping the
log(2π σ²)normalization constant.
- 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.
Module contents¶
Inference layer: model-data pairing, statistics, samplers, and analyzers.