API reference

Everything a typical analysis needs is importable from the top-level binference namespace; priors, engines and helpers live in sub-modules. The names are grouped by what you are doing.

Inferring a population

infer fits a population in one call; the estimator wraps the same fit for scikit-learn, and the model holds the inputs of a fit for reuse.

infer

Infer a population distribution from per-object likelihoods in one call.

PopulationEstimator

Population inference with the scikit-learn estimator conventions.

PopulationModel

Likelihoods + prior (+ selection): the object every inference engine works on.

Inputs and bins

The bins, how volume is measured in them, and the per-object likelihoods and response that a fit takes.

Bins

The bins (or categories) over which populations and likelihoods are defined.

Basis

Components of the population model over reporting bins.

Measure

A strictly increasing map u = T(z) of one bin axis.

Density

A fixed probability density over the bin coordinate.

Likelihoods

Bin-averaged per-object likelihoods \(L_{ik} \propto p(d_i \mid z_i \in B_k)\).

Response

The probability of each measured bin, and of being observed, given the true bin.

Priors

Priors on the population fractions or rates; pass one to infer as prior=.

Dirichlet

Dirichlet prior \(\rho \sim \mathrm{Dir}(\alpha)\) on bin fractions.

GeneralizedDirichlet

Generalised Dirichlet (Connor & Mosimann 1969) via stick-breaking Betas.

DirichletTree

Dirichlet-tree prior: independent Dirichlet splits along a tree of bins.

PolyaTree

Finite Polya-tree prior on an ordered 1-D grid (a balanced binary Dirichlet-tree).

LogisticNormal

Logistic-normal prior on the population fractions.

LogisticRandomWalk

Random-walk (intrinsic GMRF) smoothness prior on log-fractions over a grid.

LogisticGP

Gaussian-process prior on log-fractions over a 1-D or N-D grid.

GammaRates

Independent Gamma priors on per-bin rates, \(\lambda_k \sim \mathrm{Gamma}(a_k, b_k)\).

Hyperpriors for the hyperparameters of the logistic priors are parametrised on the log scale internally; pass a plain number to fix a hyperparameter.

HalfNormal

Half-normal prior with scale scale on a positive hyperparameter.

LogNormal

Log-normal prior: log(theta) ~ Normal(mu, sigma).

InverseGamma

Inverse-gamma prior with shape a and scale b.

Gamma

Gamma prior with shape a and rate b.

Fixed

A hyperparameter held fixed at value (not inferred).

A new prior subclasses one of these base classes; bind returns its numerical form.

PopulationPrior

Base class for priors on population fractions or rates.

BoundPrior

Numerical interface of a prior bound to specific bins (internal).

Hyperprior

Base class for priors on a positive scalar hyperparameter.

Selection

Which objects enter the sample, given their true or measured values; pass a Selection to infer as selection=.

Selection

Per-bin detection probability (fractions) or exposure (rates), with its mode.

as_selection

Normalise user input: None, a Selection, a callable or an array plus mode.

SELECTION_MODES

The values of Selection.mode: how objects are selected.

SELECTION_SCALES

The values of Selection.scale: what the selection values measure.

Engines

infer(..., method=...) builds one of these for you; use them directly for fine control, generator-style sampling or resuming a run.

NUTS

No-U-Turn Sampler on the exact posterior, for every prior.

Gibbs

Data-augmentation Gibbs sampler (the "hierarchical" sampler).

MAP

Maximum a posteriori (or maximum-likelihood) estimate of the population.

Laplace

Gaussian (Laplace) approximation in unconstrained coordinates.

MeanFieldVB

Mean-field variational Bayes: \(q(\rho)\prod_i q(z_i)\).

Bootstrap

Bootstrap over objects of the MAP / maximum-likelihood estimator.

Engine

Base class of all inference engines.

method="auto", the default, is an engine that picks one of the others; METHODS maps each method= name to its engine.

Auto

Picks Gibbs, Laplace or NUTS from rules set by a benchmark of the engines.

METHODS

Registry of inference methods accepted by infer().

Results and summaries

What a fit returns: posterior draws or a point estimate, and their summary table.

PopulationResult

Posterior draws of a population (fractions and, for rate models, rates).

PointEstimate

A MAP / maximum-likelihood estimate of the population.

Summary

A small per-bin summary table with a readable repr.

Diagnostics and validation

Checks of a single fit: convergence of draws, importance sampling for approximations, and optimality of a point estimate.

rhat

Rank-normalised split R-hat (maximum of bulk and folded/tail versions).

ess

Effective sample size of a scalar quantity.

mcse

Monte Carlo standard error of the mean of a scalar quantity.

autocorr_time

Integrated autocorrelation time with Sokal's adaptive window.

autocorr_function

Normalised autocorrelation function of a 1-D chain (or average over chains).

psis

Pareto-smoothed importance sampling.

psis_threshold

The Pareto k_hat below which PSIS with n weights is reliable.

importance_ess

Kish's effective sample size of importance weights, \((\sum_s w_s)^2 / \sum_s w_s^2\) (normalised or not).

kkt_gap

First-order optimality violation of a point estimate.

missing_information

Largest fraction of missing information.

Checks of a method: exact posteriors for small problems, simulation-based calibration and coverage.

exact_posterior

Quadrature posterior of the fractions for K = 2 or K = 3 bins.

sbc

Simulation-based calibration.

coverage

Empirical coverage of central credible intervals over simulated data sets.

ExactPosterior

Posterior on quadrature nodes over the simplex (K <= 3).

SBCResult

Ranks from simulation-based calibration.

CoverageResult

Empirical coverage of central credible intervals.

Simulation

Mock data sets with a known truth, for trying a method before it meets real data.

mock_1d

A 1-D mock catalogue with heteroscedastic Gaussian measurement errors.

mock_2d

A 2-D mock catalogue (e.g. a colour-magnitude-like ridge) with Gaussian errors.

mock_categorical

A quantification problem: classifier outputs over unordered classes.

mock_unfolding

An unfolding problem: an exponential spectrum smeared by a detector.

prior_predictive

A simulator simulate(rng) -> (likelihoods, truth) drawing populations from a prior.

population

Population fractions per bin from a density name, Density, callable or masses.

Mock

A mock catalogue: bins, likelihoods, truth and alternative input forms.

Truth

The true population and objects behind a mock catalogue.

Plotting

Figures of a population, its draws, the per-object posteriors and calibration.

plot_population

Plot a population posterior: bands for 1-D bins, images for 2-D grids, bars for categories.

plot_corner

Corner plot of the fractions (or which="rates", ...) in selected bins.

plot_trace

Trace plots of the fractions (or which="rates", ...) in selected bins, one line per chain.

plot_individual

Compare object i's own likelihood (flat-prior posterior) with its shrunk posterior.

plot_sbc

Rank histograms from binference.validation.sbc() with a 99% uniformity band.

SAMPLE_COLOR

The coral of single objects and samples in the binference docs (their brand sample colour), to pass as sample_color; docs/_scripts/brand.py --check keeps the two equal.

Saving and loading

Write a result to disk, read it back, or convert it to an xarray DataTree for ArviZ.

save_result

Save a result to a compressed .npz file (versioned schema; result_to_dict()).

load_result

Load a result saved with save_result() (.npz may be left off path).

result_to_dict

Arrays and metadata of a result as a plain dictionary: what save_result() writes, with "meta" the JSON-compatible metadata and every other entry an array.

to_datatree

Convert to an xarray.DataTree with posterior and sample_stats groups.

Warnings

The warnings binference emits, and the error a strict convergence check raises.

BinferenceWarning

Base class for all binference warnings.

InputWarning

Inputs look inconsistent with the declared conventions.

ConvergenceWarning

A sampler or optimiser shows signs of non-convergence.

ApproximationWarning

A result comes from an approximation with known failure modes.

DiagnosticsError

result.check(strict=True) found problems (the messages its warnings carry).