bayspec.util package¶
Submodules¶
bayspec.util.corner module¶
Plotly-based corner-plot renderer for posterior samples.
- bayspec.util.corner.corner_plotly(xs, bins=30, ranges=None, weights=None, color=None, smooth1d=1.0, smooth=1.0, labels=None, quantiles=None, levels=None)[source]¶
Render a Plotly corner plot of 1D marginals and 2D contours.
Draws smoothed 1D histograms on the diagonal and 2D contour plots on the lower triangle, with optional quantile markers.
- Parameters:
xs (ndarray | Sequence) – 1D or 2D array of samples; a 2D array is treated as rows of observations.
bins (int) – Number of bins used for both 1D and 2D histograms.
ranges (list[tuple[float, float]] | None) – Per-parameter plotting range. Defaults to full data range.
weights (ndarray | None) – Sample weights.
color (str | None) – Line color for 1D histograms; defaults to a dark blue.
smooth1d (float | None) – Gaussian smoothing sigma for 1D histograms.
smooth (float | None) – Gaussian smoothing sigma for 2D histograms.
labels (list[str] | None) – Axis labels, one per parameter.
quantiles (list[float] | None) – Quantiles to mark on the 1D histograms.
levels (list[float] | None) – Contour levels as enclosed probability mass. Defaults to the one- and two-sigma enclosed masses.
- Returns:
The assembled
plotly.graph_objects.Figure.- Return type:
Figure
- bayspec.util.corner.plot_hist2d(x, y, bins, ranges, weights, smooth, labels, levels, fig, subfig_idx)[source]¶
Add a smoothed 2D histogram with contour levels to
fig.Contour levels are chosen so that each encloses a requested cumulative probability mass of the 2D histogram.
- Parameters:
x (ndarray) – Horizontal samples.
y (ndarray) – Vertical samples.
bins (list[int]) – Bin counts
[nx, ny].ranges (list[tuple[float, float]]) – Axis ranges
[(xmin, xmax), (ymin, ymax)].weights (ndarray | None) – Sample weights.
smooth (float | None) – Gaussian smoothing sigma for the 2D histogram.
labels (list[str]) –
[xlabel, ylabel]used to tag the trace.levels (ndarray) – Enclosed probability masses for contour generation.
fig (Figure) – Figure to add the contour trace to.
subfig_idx (tuple[int, int]) –
(row, col)zero-based index of the target subplot.
- Returns:
The modified figure.
- Return type:
Figure
- bayspec.util.corner.quantile(x, q, weights=None)[source]¶
Return (optionally weighted) quantiles of
x.Falls back to
numpy.percentilewhenweightsisNone.- Parameters:
x (ndarray) – 1D sample array.
q (float | list[float]) – Quantile or list of quantiles, each in
[0, 1].weights (ndarray | None) – Optional sample weights.
- Returns:
The requested quantile values as a list.
- Raises:
ValueError – If any
qis outside[0, 1], or ifweightshas a different length thanx.- Return type:
list[float]
bayspec.util.info module¶
Tabular Info wrapper used to format structured metadata.
Normalizes between three equivalent shapes – a column-major dict of
lists, a header-plus-rows list, and a list of row dicts – and renders
the result as text or HTML for CLI and notebook display.
- class bayspec.util.info.Info(data_dict)[source]¶
Bases:
objectTabular view over a column-major dictionary of metadata.
Accepts scalar values by broadcasting them to single-element columns, and exposes common conversions (list, list-of-dicts, DataFrame) plus formatted text and HTML tables.
- Variables:
data_dict – Column-major dictionary with list-valued columns.
- property data_dict¶
- property data_list¶
Header-plus-rows list representation of the table.
- property data_list_dict¶
List of row dictionaries, one entry per row.
- property data_frame¶
Return the data as a
pandas.DataFrame.
- property sanitized_data_dict¶
Column-major dict with every value coerced to a display string.
Floats are formatted with three decimal places and
Nonevalues become the literal string'None'.
- classmethod from_dict(data_dict)[source]¶
Build an
Infofrom a column-major dictionary.- Raises:
TypeError – If
data_dictis not adict.
- classmethod from_list(data_list)[source]¶
Build an
Infofrom a header-plus-rows list.- Raises:
TypeError – If
data_listis not alist.
- classmethod from_list_dict(list_dict)[source]¶
Build an
Infofrom a list of row dictionaries.- Raises:
TypeError – If
list_dictis not a non-empty list of dicts.
- static dict_to_list_dict(data_dict)[source]¶
Convert a column-major dict into a list of row dictionaries.
- static list_to_list_dict(data_list)[source]¶
Convert a header-plus-rows list into a list of row dictionaries.
- static list_dict_to_dict(list_dict)[source]¶
Convert a list of row dictionaries into a column-major dict.
- static list_dict_to_list(list_dict)[source]¶
Convert a list of row dictionaries into a header-plus-rows list.
- property text_table¶
Fancy-grid text rendering of the table suitable for the CLI.
- property html_style¶
Inline CSS paired with
html_tablefor notebook rendering.
- property html_table¶
HTML rendering of the table tagged with the
my-tableclass.
bayspec.util.param module¶
Parameter and configuration objects used to build models.
- class bayspec.util.param.Par(val, prior=None, post=None, comment=None, scale='linear', unit=None, frozen=False)[source]¶
Bases:
objectModel parameter carrying value, prior, posterior, and metadata.
Parinstances can be linked to share value, prior, and posterior across several models; setting any of those on one mate propagates the change to the others. A version counter is bumped on every value change so downstream caches can invalidate.- Variables:
val – Current numerical value.
prior – Optional prior distribution.
post – Optional posterior sample container.
comment – Free-form description.
scale –
'linear'or'log'– determines howvalueis built.unit – Optional unit attached to
val.frozen – If
True, the parameter is held fixed during inference.mates – Set of other
Parinstances kept in sync vialink.
- property val¶
- property version¶
Monotonic counter bumped on every value change.
Downstream code uses this as a cheap cache key.
- property prior¶
- property prior_info¶
Short description of the prior, or
Nonewhen unset.
- property post¶
- property post_info¶
Summary of the posterior, or
Nonewhen unset.
- link(other)[source]¶
Link this parameter with
otherto keep them synchronized.After linking, setting
val/prior/poston either side propagates to every mate in the group.- Parameters:
other – Another
Parinstance to link with.- Raises:
ValueError – If
otheris the same instance asself.
- property value¶
Physical value derived from
val,scale, andunit.For
scale='linear'this returnsval(optionally times the unit); forscale='log'it returns10 ** val.- Raises:
ValueError – If
scaleis neither'linear'nor'log'.
- property range¶
Plausible range for the parameter.
Returns a collapsed point if the parameter is frozen, the full uniform support for uniform priors, or the central 95% interval otherwise.
- property info¶
Print each field of
todictone per line and return an empty string.The empty return lets
infobe used transparently as a property in an interactive session where the print output is the point.
- class bayspec.util.param.Cfg(val, prior=None, post=None, comment=None, scale='linear', unit=None, frozen=False)[source]¶
Bases:
ParConfiguration parameter: a
Parpermanently frozen with no prior.Cfgrepresents values that configure a model (e.g. sample redshift or selected channel) rather than quantities that inference should estimate. They accept the same constructor signature asParbutpriorandpostare forced toNoneandfrozentoTrue.
bayspec.util.plot module¶
High-level plotting helpers for spectra, responses, fits, and posteriors.
Plot dispatches per-object figures (spectrum, response, dataunit, fit
comparison, corner), ModelPlot composes multi-model comparisons, and
Figure wraps the returned figure with notebook display plus
filename-aware saving (HTML/PDF/JSON).
Every renderer accepts ploter='plotly' or ploter='matplotlib' and
returns a Figure.
- class bayspec.util.plot.Plot[source]¶
Bases:
objectStatic factory for single-object figures over bayspec data types.
Every method takes a concrete bayspec object (
Spectrum,Response,DataUnit,Data,Pair,Infer,Posterior/Bootstrap) and returns aFigure. Plotly is the default backend;matplotlibis available for static output.- colors = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52', '#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD', '#8C564B', '#E377C2', '#7F7F7F', '#BCBD22', '#17BECF', '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#0099C6', '#DD4477', '#66AA00', '#B82E2E', '#316395', '#4C78A8', '#F58518', '#E45756', '#72B7B2', '#54A24B', '#EECA3B', '#B279A2', '#FF9DA6', '#9D755D', '#BAB0AC', '#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1C8356', '#16FF32', '#F7E1A0', '#E2E2E2', '#1CBE4F', '#C4451C', '#DEA0FD', '#FE00FA', '#325A9B', '#FEAF16', '#F8A19F', '#90AD1C', '#F6222E', '#1CFFCE', '#2ED9FF', '#B10DA1', '#C075A6', '#FC1CBF', '#B00068', '#FBE426', '#FA0087']¶
- static get_rgb(color, opacity=1.0)[source]¶
Convert a matplotlib color plus opacity into a Plotly
rgbastring.
- static spectrum(cls, ploter='plotly')[source]¶
Plot counts vs. channel for a
Spectrum.- Parameters:
cls –
Spectrumwhose counts and errors are drawn.ploter – Backend –
'plotly'or'matplotlib'.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aSpectrum.
- static response(cls, ploter='plotly', ch_range=None, ph_range=None)[source]¶
Plot the 2D detector response matrix as a contour.
- Parameters:
cls –
Response(non-Auxiliary) to visualize.ploter – Backend –
'plotly'or'matplotlib'.ch_range – Optional
(min, max)channel-energy window.ph_range – Optional
(min, max)photon-energy window.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aResponseor isAuxiliary.
- static response_photon(cls, ploter='plotly', ph_range=None)[source]¶
Plot effective area vs. photon energy.
- Parameters:
cls –
ResponseorAuxiliary.ploter – Backend –
'plotly'or'matplotlib'.ph_range – Optional
(min, max)photon-energy window.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aResponse.
- static response_channel(cls, ploter='plotly', ch_range=None)[source]¶
Plot the channel-summed response vs. channel energy.
- Parameters:
cls –
Response(non-Auxiliary).ploter – Backend –
'plotly'or'matplotlib'.ch_range – Optional
(min, max)channel-energy window.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aResponseor isAuxiliary.
- static dataunit(cls, ploter='plotly', style='CE')[source]¶
Plot a single
DataUnit’s observed spectrum.- Parameters:
cls –
DataUnitto plot; must be complete.ploter – Backend –
'plotly'or'matplotlib'.style – Display style – e.g.
'CC'counts/channel,'CE'counts/keV,'NE'photon flux density.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aDataUnit.AttributeError – If the
DataUnitfails its completeness check.
- static data(cls, ploter='plotly', style='CE')[source]¶
Plot every
DataUnitin aDatacontainer on one figure.- Parameters:
cls –
Datawhose units are drawn together.ploter – Backend –
'plotly'or'matplotlib'.style – Display style (see
dataunit()).
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aData.
- static model(ploter='plotly', style='NE', post=False, yrange=None)[source]¶
Create an empty
ModelPlotfor accumulating model traces.- Parameters:
ploter – Backend –
'plotly'or'matplotlib'.style – Spectrum style –
'NE'/'Fv'/'ENE'/'vFv'/'EENE'for additive models,'NoU'for multiplicative/mathematical models.post – If
True, also draw the posterior credible band.yrange – Optional
(ymin, ymax)tuple for the y-axis.
- Returns:
A fresh
ModelPlotready foradd_modelcalls.
- static pair(cls, ploter='plotly', style='CE')[source]¶
Plot data and model together for a
Pair, with residual panel.The top panel shows observed and model spectra for every data unit; the bottom panel shows residuals in units of sigma.
- Parameters:
cls –
Pairwhose data and model are drawn.ploter – Backend –
'plotly'or'matplotlib'.style – Display style –
'CC','CE','NE','Fv'/'ENE', or'vFv'/'EENE'.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aPair.ValueError – If
styleis not recognized.
- static emcee_walker(cls)[source]¶
Plot per-parameter emcee walker trajectories.
- Parameters:
cls –
BayesInferorPosteriorexposingposterior_sampleandfree_nparams.- Returns:
A
Figurewrapping the matplotlib walker plot.- Raises:
TypeError – If
clsis not aBayesInferorPosterior.
- static infer(cls, ploter='plotly', style='CE', rebin=True, at_par=None)[source]¶
Plot data vs. inferred model (with residuals) from an
Infer.- Parameters:
cls –
Inferor one of its subclasses (Posterior,Bootstrap) to visualize.ploter – Backend –
'plotly'or'matplotlib'.style – Display style (see
pair()).rebin – Draw with re-binned channels when
True.at_par – Which parameter point to evaluate the model at –
'best','best-ci','median','mean', or'truth'. Defaults to'best'forPosteriorand'truth'forBootstrap.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not anInfer.ValueError – If
at_parorstyleis not recognized, or ifat_par='truth'but some parameters lack a truth value.
- static post_corner(cls, ploter='plotly', at_par=None)[source]¶
Corner plot of a
PosteriororBootstrapsample.- Parameters:
cls –
PosteriororBootstrapwhose parameter samples are visualized.ploter – Backend –
'plotly','getdist', or'cornerpy'.at_par – Reference point overlaid on the plot –
'best','best-ci','median','mean', or'truth'. Defaults to'best'forPosteriorand'truth'forBootstrap.
- Returns:
A
Figurewrapping the plot.- Raises:
TypeError – If
clsis not aPosteriororBootstrap.ValueError – If
at_paris not recognized, ifat_par='truth'but some parameters lack a truth value, or ifploteris not one of the supported backends.
- class bayspec.util.plot.ModelPlot(ploter='plotly', style='NE', post=False, yrange=None)[source]¶
Bases:
objectAccumulating figure that overlays multiple
Modelspectra.Build one via
Plot.model(), then calladd_model()for each model to compare, and finish withget_fig(). The y-axis label and which model spectra are valid depend onstyle.- Variables:
ploter – Active backend (
'plotly'or'matplotlib').style – Spectrum style (see
Plot.model()).post – Whether posterior credible bands are drawn alongside lines.
yrange – Optional y-axis range.
fig – Underlying figure object from the chosen backend.
fig_data – Raw plotted arrays keyed by model expression.
model_index – Running count of models added; used for color cycling.
- colors = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52', '#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD', '#8C564B', '#E377C2', '#7F7F7F', '#BCBD22', '#17BECF', '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#0099C6', '#DD4477', '#66AA00', '#B82E2E', '#316395', '#4C78A8', '#F58518', '#E45756', '#72B7B2', '#54A24B', '#EECA3B', '#B279A2', '#FF9DA6', '#9D755D', '#BAB0AC', '#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1C8356', '#16FF32', '#F7E1A0', '#E2E2E2', '#1CBE4F', '#C4451C', '#DEA0FD', '#FE00FA', '#325A9B', '#FEAF16', '#F8A19F', '#90AD1C', '#F6222E', '#1CFFCE', '#2ED9FF', '#B10DA1', '#C075A6', '#FC1CBF', '#B00068', '#FBE426', '#FA0087']¶
- static get_rgb(color, opacity=1.0)[source]¶
Convert a matplotlib color plus opacity into a Plotly
rgbastring.
- add_model(model, E, T=None, post=None, at_par=None)[source]¶
Draw
modelat energiesEonto the accumulating figure.The required model spectrum method is selected from
styleandat_par. WhenpostisTruethe one-sigma credible band is added alongside the point estimate.- Parameters:
model –
Modelinstance compatible with the currentstyle.E – Energy grid (keV) at which to evaluate the model.
T – Optional time argument forwarded to time-dependent models.
post – Overrides the instance-level
postflag for this call.at_par – Which parameter point to evaluate at –
'best','best-ci','median','mean', or'truth'. Defaults to'best'when any truth value is missing, otherwise'truth'.
- Raises:
TypeError – If
modelis not aModel.AttributeError – If the model type is incompatible with
style.ValueError – If
at_parorstyleis not recognized, or ifat_par='truth'but some parameters lack a truth value.
- class bayspec.util.plot.Figure(fig, fig_data, plotter)[source]¶
Bases:
objectBackend-agnostic figure wrapper with notebook auto-display and saving.
Shows plotly figures immediately when running in an IPython kernel and supports saving to HTML, PDF, or JSON depending on the backend.
- Variables:
fig – Underlying figure object.
fig_data – Raw plotted arrays, saved alongside the figure as JSON.
plotter – Backend tag –
'plotly','matplotlib','cornerpy', or'getdist'.
- save(fname)[source]¶
Persist the figure (plus raw data) to disk using
fnameas stem.The extension is picked per backend:
.htmlfor plotly,.pdffor matplotlib and cornerpy, and a getdist-native export otherwise. Rawfig_datais additionally dumped as<fname>.json.- Parameters:
fname – Target file path without extension.
- Raises:
ValueError – If
plotteris not recognized.
bayspec.util.post module¶
Container for posterior samples of a single parameter.
- class bayspec.util.post.Post(sample, logprob=None)[source]¶
Bases:
objectPosterior sample and its summary statistics for one parameter.
Holds a 1D array of posterior draws together with an optional matching array of log-probabilities, and exposes common point estimates and credible intervals.
- Variables:
sample – 1D array of posterior draws.
logprob – Matching log-probability for each draw, or
None.
- property sample¶
- property logprob¶
- property nsample¶
Number of posterior draws.
- property mean¶
Sample mean of the posterior draws.
- property median¶
Sample median of the posterior draws.
- property best¶
Draw with the highest log-probability, or
Noneif unavailable.
- property best_ci¶
- property truth¶
- quantile(q)[source]¶
Return the
q-quantile of the sample.- Parameters:
q – Probability (or array of probabilities) in
[0, 1].- Returns:
The corresponding sample quantile.
- interval(q)[source]¶
Return the central credible interval containing probability
q.- Parameters:
q – Requested central probability mass, between 0 and 1.
- Returns:
[low, high]bounding the central interval.
- property Isigma¶
One-sigma (68.27%) central credible interval.
- property IIsigma¶
Two-sigma (95.45%) central credible interval.
- property IIIsigma¶
Three-sigma (99.73%) central credible interval.
- property ninety_percent¶
90% central credible interval.
- error(par, q=0.6827)[source]¶
Return the asymmetric errors of
paragainst theq-interval.- Parameters:
par – Reference point estimate (e.g. best fit or median).
q – Central credible level. Defaults to one sigma.
- Returns:
[lower_error, upper_error]– signed differences betweenparand the interval endpoints.
- property info¶
Dictionary of mean, median, best, and one-sigma interval.
bayspec.util.prior module¶
Prior distributions used as parameter priors in Bayesian inference.
Wraps scipy.stats frozen distributions behind a uniform interface so
that the inference layer can query pdf, cdf, quantiles, and moments
without caring about the underlying distribution family.
Example
from bayspec.util.prior import unif, norm p = unif(0.0, 1.0) p.pdf(0.5)
- class bayspec.util.prior.unif(min, max)[source]¶
Bases:
PriorUniform prior on the closed interval
[min, max].
- class bayspec.util.prior.logunif(min, max, loc=0, scale=1)[source]¶
Bases:
PriorLog-uniform (reciprocal) prior on
[min, max].
- class bayspec.util.prior.truncnorm(a, b, loc, scale)[source]¶
Bases:
PriorTruncated Gaussian prior.
bayspec.util.significance module¶
Significance calculators for count detections against a noisy background.
Adapted from gv_significance (Giacomo Vianello, 2018, BSD 3-Clause,
https://github.com/giacomov/gv_significance) and the corresponding
Vianello 2018 ApJS (https://doi.org/10.3847/1538-4365/aab780) and Li &
Ma (1983) formulations. pgsig treats the background as Gaussian;
ppsig dispatches to Li & Ma, Vianello eq. 7, or Vianello eq. 9
based on the systematic-uncertainty inputs.
- bayspec.util.significance.pgsig(n, b, sigma)¶
Compute the Gaussian-background detection significance.
Treats the background estimate
bas a Gaussian with standard deviationsigma, maximizes the likelihood under the null hypothesis, and returns the signed square-root of the likelihood ratio.- Parameters:
n – Observed counts; scalar or array.
b – Background expectation; same shape as
n.sigma – Background uncertainty; broadcasts against
n.
- Returns:
Signed significance (
zscore); negative whenn < b.
- bayspec.util.significance.ppsig(n, b, alpha, sigma=0, k=0)¶
Compute the Poisson-background detection significance.
Dispatches per-element among three formulations:
Both
sigma == 0andk == 0: classic Li & Ma (1983).k > 0: Vianello 2018 eq. 7, treatingkas an upper bound on the fractional systematic uncertainty (sigmais ignored).sigma > 0: Vianello 2018 eq. 9, assuming a Gaussian systematic with standard deviationsigma(kis ignored).
- Parameters:
n – Observed counts; scalar or array.
b – Expected background counts under the null; same shape as
n.alpha – Ratio of source to background observation efficiencies; scalar or same shape as
n.sigma – Gaussian systematic standard deviation; scalar or matching
n.k – Upper bound on fractional systematic uncertainty; scalar or matching
n.
- Returns:
Signed significance (
zscore) for each element; negative whenn < alpha * b.
- bayspec.util.significance.size_one_or_n(value, other_array, name)¶
Broadcast a scalar or length-
narray to matchother_array.- Parameters:
value – Scalar or 1D array.
other_array – Reference array whose length defines
n.name – Label used in the assertion message.
- Returns:
A 1D float array of the same length as
other_array.- Raises:
AssertionError – If
valueis neither length 1 nor lengthn.
- bayspec.util.significance.xlogy(x, y)¶
Return
x * log(y), evaluating to 0 whenxis 0.Avoids the
0 * -inf = nantrap that naive multiplication hits.- Parameters:
x – Scalar multiplier.
y – Scalar argument to the logarithm; must be positive when
xis non-zero.
- Returns:
0.0ifx == 0; otherwisex * log(y).
bayspec.util.tools module¶
Small utilities shared across the package.
Hosts the numpy-aware JSON encoder, the index-plus-key dictionary, the dependency-aware memoization decorators, and the numba-accelerated 1D/2D trapezoidal integrators used in model evaluation.
- class bayspec.util.tools.JsonEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶
Bases:
JSONEncoderJSON encoder that understands numpy, set, datetime, and
todict-ables.Falls back to the default encoder for anything else, so
TypeErroris still raised on unsupported objects.
- bayspec.util.tools.json_dump(data, filepath, indent=4, ensure_ascii=False)[source]¶
Write
datatofilepathas JSON usingJsonEncoder.Creates missing parent directories. Uses UTF-8 and leaves non-ASCII characters intact by default.
- Parameters:
data – Serializable payload; may contain numpy and datetime values.
filepath – Target path; parents are created if absent.
indent – Indentation width for pretty-printing.
ensure_ascii – When
True, escape non-ASCII characters.
- class bayspec.util.tools.SuperDict[source]¶
Bases:
OrderedDictOrderedDictthat also supports 1-based positional indexing.Integer keys are interpreted as ordinal positions; every other key type falls through to the underlying dictionary.
- bayspec.util.tools.get_fingerprint(x)[source]¶
Recursively build a hashable fingerprint of
x.Used as cache-key material for
memoized(). The output is a nested tuple containing only hashable leaves, so it can be used directly as adictkey.- Handling by type:
np.ndarray:(tag, shape, dtype, blake2b(content)). Content hashing means identical buffers hit the cache and in-place modifications correctly invalidate it.list/tuple: recursed element-wise; the container type is preserved in the tag so a list and a tuple with the same items produce different fingerprints.dict: recursed value-wise and sorted by key, so key insertion order does not affect the fingerprint.Anything else: returned as-is. The caller is responsible for ensuring it is hashable; unhashable values will raise when the fingerprint is used as a key.
- Parameters:
x – Any object to fingerprint.
- Returns:
A hashable (possibly nested) structure uniquely identifying
xfor caching purposes.
- bayspec.util.tools.memoized(dep_getter=None, *, cache_size=None, verbose=False)[source]¶
Method-memoization decorator keyed on arguments and a dependency value.
Each decorated method gets a per-instance bounded LRU cache keyed on a fingerprint of
dep_getter(self), the positional arguments, and the keyword arguments. Numpy arrays are fingerprinted by content hash (BLAKE2b) along with shape and dtype, so identical contents hit the cache and in-place modifications correctly invalidate it.- Parameters:
dep_getter – Callable mapping
selfto the dependency value. WhenNone, dependencies are ignored.cache_size – Max entries per instance.
Noneuses the global default (_DEFAULT_CACHE_SIZE).verbose – When
True, print one line on every hit or miss.
- Returns:
A decorator that wraps a method with memoization.
- bayspec.util.tools.clear_memoized(obj, *names)[source]¶
Drop
memoized()caches fromobj.- Parameters:
obj – Instance whose caches should be cleared.
*names – Method names to clear; clears every memoized method when empty.
- bayspec.util.tools.cached_property(dep_getter=None, *, verbose=False)[source]¶
Per-instance cached-property decorator with optional dependency tracking.
On each access,
dep_getter(self)is reduced to a fingerprint viaget_fingerprint()(numpy arrays are content-hashed by BLAKE2b along with shape and dtype). When the fingerprint differs from the last observed one, the cache is invalidated and the method is re-run.Cache state lives on the instance as
_cached_<name>and_cached_dep_<name>; drop it withclear_cached_property().- Parameters:
dep_getter – Callable mapping
selfto the dependency value. WhenNone, the property caches forever after the first access.verbose – When
True, print one line on every hit or miss.
- Returns:
A
propertywhose getter memoizes the underlying method.
- bayspec.util.tools.clear_cached_property(obj, *names)[source]¶
Drop
cached_property()caches fromobj.- Parameters:
obj – Instance whose caches should be cleared.
*names – Property names to clear; clears every cached property when empty.
- bayspec.util.tools.trapz_1d(y, x)[source]¶
Integrate
yoverxwith the trapezoidal rule (numba-accelerated).- Parameters:
y – 1D array of integrand values.
x – 1D array of sample points; must match
yin length.
- Returns:
The trapezoidal integral of
yoverx.
- bayspec.util.tools.trapz_2d(y, x)[source]¶
Row-wise trapezoidal integration of a 2D array (numba-accelerated).
- Parameters:
y – 2D array; integration runs along columns for each row.
x – 2D array of matching shape holding the sample points.
- Returns:
1D array of row integrals, length equal to
y.shape[0].
Module contents¶
Shared utilities: priors, parameters, posteriors, tables, and plotting.