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.percentile when weights is None.

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 q is outside [0, 1], or if weights has a different length than x.

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: object

Tabular 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 None values become the literal string 'None'.

classmethod from_dict(data_dict)[source]

Build an Info from a column-major dictionary.

Raises:

TypeError – If data_dict is not a dict.

classmethod from_list(data_list)[source]

Build an Info from a header-plus-rows list.

Raises:

TypeError – If data_list is not a list.

classmethod from_list_dict(list_dict)[source]

Build an Info from a list of row dictionaries.

Raises:

TypeError – If list_dict is not a non-empty list of dicts.

static dict_to_list(data_dict)[source]

Convert a column-major dict into a header-plus-rows list.

static dict_to_list_dict(data_dict)[source]

Convert a column-major dict into a list of row dictionaries.

static list_to_dict(data_list)[source]

Convert a header-plus-rows list into a column-major dict.

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_table for notebook rendering.

property html_table

HTML rendering of the table tagged with the my-table class.

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: object

Model parameter carrying value, prior, posterior, and metadata.

Par instances 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 how value is built.

  • unit – Optional unit attached to val.

  • frozen – If True, the parameter is held fixed during inference.

  • mates – Set of other Par instances kept in sync via link.

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 None when unset.

property post
property post_info

Summary of the posterior, or None when unset.

Link this parameter with other to keep them synchronized.

After linking, setting val/prior/post on either side propagates to every mate in the group.

Parameters:

other – Another Par instance to link with.

Raises:

ValueError – If other is the same instance as self.

Break the link between this parameter and other.

frozen_at(new_val)[source]

Set the value to new_val and freeze the parameter.

property value

Physical value derived from val, scale, and unit.

For scale='linear' this returns val (optionally times the unit); for scale='log' it returns 10 ** val.

Raises:

ValueError – If scale is 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.

todict()[source]

Serialize the parameter into a plain-dict representation.

property info

Print each field of todict one per line and return an empty string.

The empty return lets info be 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: Par

Configuration parameter: a Par permanently frozen with no prior.

Cfg represents 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 as Par but prior and post are forced to None and frozen to True.

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: object

Static 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 a Figure. Plotly is the default backend; matplotlib is 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 rgba string.

static spectrum(cls, ploter='plotly')[source]

Plot counts vs. channel for a Spectrum.

Parameters:
  • clsSpectrum whose counts and errors are drawn.

  • ploter – Backend – 'plotly' or 'matplotlib'.

Returns:

A Figure wrapping the plot.

Raises:

TypeError – If cls is not a Spectrum.

static response(cls, ploter='plotly', ch_range=None, ph_range=None)[source]

Plot the 2D detector response matrix as a contour.

Parameters:
  • clsResponse (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 Figure wrapping the plot.

Raises:

TypeError – If cls is not a Response or is Auxiliary.

static response_photon(cls, ploter='plotly', ph_range=None)[source]

Plot effective area vs. photon energy.

Parameters:
  • clsResponse or Auxiliary.

  • ploter – Backend – 'plotly' or 'matplotlib'.

  • ph_range – Optional (min, max) photon-energy window.

Returns:

A Figure wrapping the plot.

Raises:

TypeError – If cls is not a Response.

static response_channel(cls, ploter='plotly', ch_range=None)[source]

Plot the channel-summed response vs. channel energy.

Parameters:
  • clsResponse (non-Auxiliary).

  • ploter – Backend – 'plotly' or 'matplotlib'.

  • ch_range – Optional (min, max) channel-energy window.

Returns:

A Figure wrapping the plot.

Raises:

TypeError – If cls is not a Response or is Auxiliary.

static dataunit(cls, ploter='plotly', style='CE')[source]

Plot a single DataUnit’s observed spectrum.

Parameters:
  • clsDataUnit to 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 Figure wrapping the plot.

Raises:
  • TypeError – If cls is not a DataUnit.

  • AttributeError – If the DataUnit fails its completeness check.

static data(cls, ploter='plotly', style='CE')[source]

Plot every DataUnit in a Data container on one figure.

Parameters:
  • clsData whose units are drawn together.

  • ploter – Backend – 'plotly' or 'matplotlib'.

  • style – Display style (see dataunit()).

Returns:

A Figure wrapping the plot.

Raises:

TypeError – If cls is not a Data.

static model(ploter='plotly', style='NE', post=False, yrange=None)[source]

Create an empty ModelPlot for 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 ModelPlot ready for add_model calls.

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:
  • clsPair whose data and model are drawn.

  • ploter – Backend – 'plotly' or 'matplotlib'.

  • style – Display style – 'CC', 'CE', 'NE', 'Fv'/ 'ENE', or 'vFv'/'EENE'.

Returns:

A Figure wrapping the plot.

Raises:
  • TypeError – If cls is not a Pair.

  • ValueError – If style is not recognized.

static emcee_walker(cls)[source]

Plot per-parameter emcee walker trajectories.

Parameters:

clsBayesInfer or Posterior exposing posterior_sample and free_nparams.

Returns:

A Figure wrapping the matplotlib walker plot.

Raises:

TypeError – If cls is not a BayesInfer or Posterior.

static infer(cls, ploter='plotly', style='CE', rebin=True, at_par=None)[source]

Plot data vs. inferred model (with residuals) from an Infer.

Parameters:
  • clsInfer or 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' for Posterior and 'truth' for Bootstrap.

Returns:

A Figure wrapping the plot.

Raises:
  • TypeError – If cls is not an Infer.

  • ValueError – If at_par or style is not recognized, or if at_par='truth' but some parameters lack a truth value.

static post_corner(cls, ploter='plotly', at_par=None)[source]

Corner plot of a Posterior or Bootstrap sample.

Parameters:
  • clsPosterior or Bootstrap whose 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' for Posterior and 'truth' for Bootstrap.

Returns:

A Figure wrapping the plot.

Raises:
  • TypeError – If cls is not a Posterior or Bootstrap.

  • ValueError – If at_par is not recognized, if at_par='truth' but some parameters lack a truth value, or if ploter is not one of the supported backends.

class bayspec.util.plot.ModelPlot(ploter='plotly', style='NE', post=False, yrange=None)[source]

Bases: object

Accumulating figure that overlays multiple Model spectra.

Build one via Plot.model(), then call add_model() for each model to compare, and finish with get_fig(). The y-axis label and which model spectra are valid depend on style.

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

add_model(model, E, T=None, post=None, at_par=None)[source]

Draw model at energies E onto the accumulating figure.

The required model spectrum method is selected from style and at_par. When post is True the one-sigma credible band is added alongside the point estimate.

Parameters:
  • modelModel instance compatible with the current style.

  • E – Energy grid (keV) at which to evaluate the model.

  • T – Optional time argument forwarded to time-dependent models.

  • post – Overrides the instance-level post flag 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 model is not a Model.

  • AttributeError – If the model type is incompatible with style.

  • ValueError – If at_par or style is not recognized, or if at_par='truth' but some parameters lack a truth value.

get_fig()[source]

Wrap the accumulated plot in a Figure for display or saving.

class bayspec.util.plot.Figure(fig, fig_data, plotter)[source]

Bases: object

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

static is_notebook()[source]

Return True when running inside an IPython kernel.

save(fname)[source]

Persist the figure (plus raw data) to disk using fname as stem.

The extension is picked per backend: .html for plotly, .pdf for matplotlib and cornerpy, and a getdist-native export otherwise. Raw fig_data is additionally dumped as <fname>.json.

Parameters:

fname – Target file path without extension.

Raises:

ValueError – If plotter is not recognized.

bayspec.util.post module

Container for posterior samples of a single parameter.

class bayspec.util.post.Post(sample, logprob=None)[source]

Bases: object

Posterior 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 None if 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 par against the q-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 between par and 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: Prior

Uniform prior on the closed interval [min, max].

class bayspec.util.prior.logunif(min, max, loc=0, scale=1)[source]

Bases: Prior

Log-uniform (reciprocal) prior on [min, max].

class bayspec.util.prior.norm(loc, scale)[source]

Bases: Prior

Gaussian prior.

class bayspec.util.prior.lognorm(s, loc, scale)[source]

Bases: Prior

Log-normal prior.

class bayspec.util.prior.truncnorm(a, b, loc, scale)[source]

Bases: Prior

Truncated Gaussian prior.

class bayspec.util.prior.cauchy(loc, scale)[source]

Bases: Prior

Cauchy (Lorentzian) prior.

class bayspec.util.prior.cosine(loc, scale)[source]

Bases: Prior

Cosine-shaped prior on a bounded interval.

class bayspec.util.prior.beta(a, b, loc, scale)[source]

Bases: Prior

Beta prior.

class bayspec.util.prior.gamma(a, loc, scale)[source]

Bases: Prior

Gamma prior.

class bayspec.util.prior.expon(loc, scale)[source]

Bases: Prior

Exponential prior.

class bayspec.util.prior.plaw(a, loc, scale)[source]

Bases: Prior

Power-law prior.

bayspec.util.prior.list_priors()[source]

Return the names of every prior subclass registered in this module.

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 b as a Gaussian with standard deviation sigma, 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 (z score); negative when n < 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 == 0 and k == 0: classic Li & Ma (1983).

  • k > 0: Vianello 2018 eq. 7, treating k as an upper bound on the fractional systematic uncertainty (sigma is ignored).

  • sigma > 0: Vianello 2018 eq. 9, assuming a Gaussian systematic with standard deviation sigma (k is 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 (z score) for each element; negative when n < alpha * b.

bayspec.util.significance.size_one_or_n(value, other_array, name)

Broadcast a scalar or length-n array to match other_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 value is neither length 1 nor length n.

bayspec.util.significance.xlogy(x, y)

Return x * log(y), evaluating to 0 when x is 0.

Avoids the 0 * -inf = nan trap that naive multiplication hits.

Parameters:
  • x – Scalar multiplier.

  • y – Scalar argument to the logarithm; must be positive when x is non-zero.

Returns:

0.0 if x == 0; otherwise x * log(y).

bayspec.util.significance.xlogyv(x, y)

Vectorized xlogy() that returns 0 where x is 0.

Parameters:
  • x – Scalar or array multiplier.

  • y – Array argument to the logarithm; must be positive wherever x is non-zero.

Returns:

Squeezed array of x * log(y) with 0 in place of 0 * log(0).

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: JSONEncoder

JSON encoder that understands numpy, set, datetime, and todict-ables.

Falls back to the default encoder for anything else, so TypeError is still raised on unsupported objects.

default(obj)[source]

Serialize numpy scalars/arrays, sets, dates, todict-ables, and BytesIO.

bayspec.util.tools.json_dump(data, filepath, indent=4, ensure_ascii=False)[source]

Write data to filepath as JSON using JsonEncoder.

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: OrderedDict

OrderedDict that 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 a dict key.

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 x for 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 self to the dependency value. When None, dependencies are ignored.

  • cache_size – Max entries per instance. None uses 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 from obj.

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 via get_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 with clear_cached_property().

Parameters:
  • dep_getter – Callable mapping self to the dependency value. When None, the property caches forever after the first access.

  • verbose – When True, print one line on every hit or miss.

Returns:

A property whose getter memoizes the underlying method.

bayspec.util.tools.clear_cached_property(obj, *names)[source]

Drop cached_property() caches from obj.

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 y over x with the trapezoidal rule (numba-accelerated).

Parameters:
  • y – 1D array of integrand values.

  • x – 1D array of sample points; must match y in length.

Returns:

The trapezoidal integral of y over x.

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.