Reference / Changelog
Changelog¶
All notable changes to binference are recorded here. The format follows Keep a Changelog, and versions follow Semantic Versioning as the contributing guide’s “Breaking changes” section sets out.
[0.3.0] - 2026-11-16¶
Added¶
Likelihoods.from_samplestakeskind="likelihood"for samples drawn from a likelihood, asfrom_tableandfrom_densitydo.Likelihoods.from_samples(..., smooth="kde", bandwidth=...)spreads each sample over the bins by a Gaussian kernel in the measure coordinate (1-D bins). It helps on bins much narrower than the posteriors, widens each posterior by the bandwidth, and blurs posteriors with several peaks.GeneralizedDirichlet.from_base_measure(concentration, base, order)sets each stick’s Beta so that the prior mean is the base measure’s bin masses, with the same concentrationa + bon every stick.A
Dirichletwith one concentration for every bin (a scalaralpha, the default, orDirichlet.reference()) raises anInputWarningon bins of unequal width in the measure coordinate, where its prior mean is not a flat density, and points toDirichlet.from_base_measure.GammaRateswith oneshapefor every bin warns there too.check()warns when bins with fewer than 20 recovered injections hold more than a tenth of the population, for a selection from injections inferred orfixed(), and names the bins that need more injections.
Changed¶
Breaking: renames, each to the spelling its siblings use:
Likelihoods.from_gaussian(mean, sigma, bins)→(mean, bins, sigma), withbinsrequired.Auto(gibbs_max_missing=, nnz_limit=)→max_gibbs_missing=,max_nnz=.Selection.from_function(function=)→func=.Basis.masses(grid)andaxis_masses(grid)→bins.Selection.draw,Response.drawandPopulationModel.draw_total→sample,sample_total.simulate.mock_1d(n_samples=)→samples_per_object=.check(predictive_draws=)→n_predictive=.simulate.mock_unfolding(n_true=, n_reco=)→n_truth=,n_measured=, and itsmeasurements["reco_counts"]→"measured_counts".selection.as_selectionis now private.
Breaking: options after a method’s primary arguments are keyword-only, so a positional call means the same on sibling methods (
check(True)setstricton one result type andkkt_maxon the other). This covers the result and per-object methods (realized_countstakes only keywords),PointEstimate.laplace,Likelihoods.with_weightsandstack,PopulationModel’s methods,exact_posterior,SBCResult.passed,simulate.population,plot_individual,plot_sbc,LogisticRandomWalk,LogisticGP,LogisticNormalaftercov, andBins(mask=); andrngeverywhere a user passes it. Passing one of these by position raises aTypeError; pass it by name.Breaking:
LogisticRandomWalktakes its differences at the bin centres in the measure coordinate, in units of their mean spacing, and its unpenalised trends are polynomials in that coordinate. On bins of equal width in the measure coordinate (Bins.linear,Bins.log) nothing changes; on unequal bins a step over a wider gap may be larger. Results saved on unequal bins by 0.2 attach under the new prior. No argument restores the index steps; use 0.2 to reproduce such a fit.Breaking:
LogisticGPwithn_basis=Nonegives each axis as many sines as its narrowest bin fits across the axis, at most four per bin; on bins of equal width this is one per bin, as before. To keep 0.2’s basis on unequal bins, passn_basiswith the number of bins on each axis.Breaking:
Selection.from_injectionstakes Jeffreys’ prior,prior=(0.5, 0.5), on each bin’s detection probability by default; it was(1, 1). With few recoveries it reduced the low bias of derived totals from 12% to 9% in simulations of the injections tutorial’s setup. Passprior=(1, 1)for the old default.NUTS uses a dense metric for logistic priors up to 500 dimensions (from 200), and starts it from the curvature at every chain’s position. With
LogisticGP’s default basis, two chains and one thread each, this cut the time per fit by two to five times on a 16 × 16 grid, about three on 20 × 20 and five on 22 × 22. Above 500 dimensions,metric="auto"is diagonal and starts from the identity. The low E-BFMI ofLogisticGPfits on large grids remains; the engines page documents it.PolyaTree’s error for a base measure with an empty bin reads asDirichlet’s.
Fixed¶
NUTSrefuses a NaNn_warmuporjitterand a fractionaln_warmup, which it truncated.infernames an option that no engine takes as unknown, rather than suggestingmethod=;checkrefuses ann_predictivethat is not a positive integer.
[0.2.0] - 2026-11-07¶
Added¶
PopulationResult.selection_draws()andresponse_draws()return the posterior draws of a jointly inferred selection,(n_draws, K), or tallied response,(n_draws, J, K).infer(method=)also takes anEnginesubclass, so a user-written engine runs throughinferwith the samerng,progressand options as a named one.The Release workflow also creates the GitHub release, with the version’s CHANGELOG section as notes and the wheel and sdist attached.
describe(bins, counts=None)onDirichletand the tree priors draws the tree as text: each branch’s concentration, mean share and mean mass, or the posterior given counts.DirichletTreetakes named groups (nested dicts, with bin labels on categorical bins), andalphaas a dict from group names, and bins as the tree writes them, to the concentration of the branch into each.BoundPrior.long_log_tails(): whether a bin without data has a long tail in the unconstrained coordinates NUTS samples.Selection.from_functionandSelection.combinedtakemax_depth, the most refinements of their adaptive quadrature; the default, 20, allows the halvings a jump inside a bin needs.Likelihoods.from_density,Density.from_functionandDensity.coercetakebounded=: the bin averages of a bounded density, such as a box, and offrom_density’s interim prior given as a function, are checked for jumps near bin edges as a selection function’s are, at 13/8 the points per cell in 1-D.Densitycompares by value and is hashable: flat densities by coordinate, arrays by their values and reading, frozen SciPy distributions by family and parameters, functions by identity.
Changed¶
When
check()reports a low E-BFMI forLogisticGPon a grid, its hint suggestsn_basis=10.Breaking:
Likelihoods.basisand thebasisof a result are neverNone. Plain bins are the identity basisBasis(bins)(order 0, resolution 1), which categories now also take, so testbasis.is_identitywherebasis is Nonewas tested. An explicitBasis(bins)now behaves as its plain bins, except thatSelection.from_injectionsstill refuses anyBasis. Saved files keep their layout and files from 0.1.0 still load: a file without basis metadata is on the identity basis.inferchecks the inputs of every fit, not only NUTS and Gibbs: the Monte Carlo noise of sample likelihoods for every engine and, where the result has draws, binned counts the response does not describe.PointEstimate.checkincludes the noise check.A raw array whose rows all sum to 1 raises an
InputWarning, since it may hold posteriors, which an array is not read as.Breaking: an explicit
n_samplesundermethod="auto"is a minimum. A Gibbs run may be extended past it until it mixes, and Gibbs is left out when it would need more thanmax_gibbs_draws; before,n_samplesfixed the length and kept Gibbs at any projected length, so passing it for speed gave a fit that did not mix.Autotakes its extension and probe settings as arguments,extend_target,extend_max_factor,extend_min_factor,probe_proposals,probe_drawsandprobe_ess_share, at the values of the constants they replace.Breaking:
GeneralizedDirichleton a grid of two or more dimensions needsorder. Its stick used to break in row-major order, which depends on how the grid is flattened.Breaking:
SBCResult.passedrequires both the chi-square and the ECDF test by default (method="both"), each atalpha / (2 n_quantities). Passmethod="chisquare"for the old behaviour.A tree prior stores a thin branch membership as a sparse matrix: an EM step with a
PolyaTreeon 1024 bins takes half the time, and small trees are unchanged.Breaking:
binference.samplersis renamedbinference.engines, since it also holds MAP and VB, which do not sample. There is no alias, sofrom binference.samplers import NUTSbecomesfrom binference.engines import NUTS; the API pages’ URLs change with it.The
testextra installs scikit-learn 1.6 or later, so the test ofPopulationEstimatorwith scikit-learn’s model selection runs.Selection.at_mean()is renamedSelection.fixed(), the name the same operation has onResponse.A selection function’s bin averages are also checked against Lobatto’s 5-point rule read just inside each cell’s ends, so a jump near a cell’s edge is refined to
tolinstead of being missed without a warning.Likelihoods.from_samplesrefuses NaN and infinite samples, which counted as samples outside the bins.Likelihoods.from_densityevaluates frozen SciPy distributions of one family in one call, for their exact bin masses and for their densities; the densities’ check for one family never matched, so each distribution was evaluated separately.plot(stack=...)takes the stack asLikelihoods.stackreturns it, and on a fit with aBasisshares its component weights among the bins, soresult.plot(stack=lk.stack())works on every fit; it failed with more components than bins and, with as many, drew the component weights as bin fractions. A stack mapped to the bins first, asLikelihoods.stack’s docstring advised, is now refused when the numbers of components and bins differ and mapped twice when they agree. Atruthorstackof the wrong length is refused by name.PopulationResultandPointEstimatekeep read-only copies of every array they are given (draws, total,value,x, labels, and the arrays ininfo), freeze what they cache, and stay read-only through pickling: writing intosamples,chains,component_draws,total,selected,data_supportor a column ofsummary()raises,diagnosticsis a read-only mapping, and changing the array passed in no longer changes the result.check()flags Markov chains that give no R-hat or ESS, shorter than 8 draws (MIXING_MIN_DRAWS) or constant; they passed with no message.PointEstimaterefuses rates with the same message asPopulationResult.Measureobjects are immutable, asBinsare; renaming the sharedMeasure.log()broke the saving of bins.Bins,Selection,ResponseandMeasurealso refusedelof an attribute, after which it could be set again.PopulationModel.log_likelihoodrefuses a value that is not finite and non-negative, or is all zero; a negative fraction gave a finite log-likelihood.sbcranks the log-likelihood of a model that infers its selection or response in one pass over the draws: the same values, about 11 times faster.method="auto"records first ininfo["auto_reason"]why a rule left Gibbs out, and keeps an extended Gibbs result rather than rebuilding it.binference.ioandbinference.plottingare imported with the package and listed bydir(); they stay out of__all__.The partial-centring weights of the logistic priors’ bound form are named
gamma(waslam), also inwith_centeringandrecentre;info["centring"]is unchanged.Tree priors take their EM weights from the concentrations, and binding no longer builds a slot-by-node matrix: a
PolyaTreeon 2048 bins binds in 0.06 s (was 0.64 s) (#166).BoundPriordocuments the interface a new prior implements.method="auto"builds every engine it may run when it is made, so a bad engine option, or options that no engine takes, raise before any fit (#174).Breaking:
initis fractions or rates of shape (K,) formethod="auto"andNUTS, as for Gibbs and MAP; NUTS converts it withPopulationModel.from_valueto one point that each chain jitters. Starts in NUTS’s unconstrained coordinates, shape (dim,) or (n_chains, dim), are passed asinit_x. Before,NUTS(init=)read a point in its unconstrained coordinates, and auto refused a fraction for NUTS’s start and read a rate as a log-rate. Such a point passed asinitis now refused by its shape, or, when it is positive and of length K (log-rates above 0, or a logistic prior whose dimension is K), read as fractions or rates without an error (#174, #190).A jittered NUTS start from
initorinit_xwith zero density is drawn again at a tenth of the jitter, then taken without jitter, as the start from the mode already was.Above 200 dimensions, NUTS takes a logistic prior’s hyperparameter curvature at one chain, like the rest of its warm-up curvature.
The defaults page lists NUTS’s divergence threshold,
_MAX_ENERGY_ERROR.
Removed¶
PopulationModel.prior_transform,BoundPrior.prior_transform(on the Dirichlet, tree andGammaRatespriors) andBoundPrior.has_prior_transform: the unit-cube map for nested samplers, which nothing in binference used.Engine.nameandEngine.approximate, which nothing read.Response.measured_fractions, which only a test used and which ignored the posterior means of a tallied response.binference.diagnostics.kkt_gapandbinference.diagnostics.missing_information: usePopulationModel.kkt_gapandPopulationModel.missing_information, orPointEstimate.kkt_gap.simulate.Truth.extra, which nothing set or read.Bins.widths, which nothing used; per-axis widths arenp.diff(bins.edges[d]).Dirichlet("reference")and theKargument ofDirichlet.reference(), which takesKfrom the bins.PopulationPrior.kindandGammaRates.kind; the bound prior’skindremains.The lazy
binference.__getattr__.
Fixed¶
Adaptive bin averages no longer lose a narrow feature that a coarse cell read. On one bin a Gaussian with σ = 1e-3 centred on the split point read as nothing, with no warning, and half of one above a flat background read 0.5 against 1. A point value that a cell reads and its children do not is now followed until a cell confirms it or
max_depthwarns. Errors are measured against the row’s current estimate rather than the largest value ever read, so an overshooting first reading no longer loosenstol(σ = 1e-2 read 1.032). This affectsfrom_density,Density.masses, selection functions and 2-D likelihoods, and a box narrow compared with its bin can now warn at the defaultmax_depth, since its error is judged against its own bin’s average.NUTS’s starting metric gives flat or negatively curved directions the largest variance seen, as documented, rather than 1e6 times the smallest. On
LogisticGP()with 4 bins and 10 objects, 20 fits took 16.6 s in all against 114.1 s, with none over 5 s.missing_information(include_prior=True)includes a tree prior’s curvature, so MAP’s EM message states the right rate forGeneralizedDirichletand the Dirichlet trees.Docstrings, error messages, attribute comments on the API pages and this changelog no longer cite design records, which the site does not include.
The NUTS tree-depth hint of
check()names long log tails only for priors that have them where NUTS samples, such as a tree with a branch concentration below one; it no longer blames trees whose concentrations are all at least one, such asGeneralizedDirichlet(1, 1)or the defaultPolyaTree()on 4 bins, and suggestsmethod="gibbs"only when Gibbs can fit the model.A tree prior with a branch whose exponent on the simplex is exactly zero no longer counts as unbounded through rounding, so MAP keeps it on the simplex.
The sdist no longer includes walkthrough notes, and its tests skip the checks that need
docs/orbenchmarks/, which it does not ship.plot_individualon a fit with aBasisdrew the object’s likelihood over the components as if they were bins, or failed when there were more components than bins; it is now shared among the bins as the hierarchical posterior is.The stack overlay of
plot(which="selected")is no longer reweighted by the selection: an average over the observed objects, it already estimates the selected population.plot_sbcalways shows the joint log-likelihood; with 12 or more other quantities it was left out. Amax_panelsbelow one is refused by name.A list or array of colours is accepted for the bars of categories only, one per category; the other plots failed with a matplotlib error and now raise one naming the argument, and
plot_sbc, which coloured its rank bars from a list, refuses it too.A truth overlay on
which="selected"of a fit with aBasisis drawn as given without a selection and refused with one, unless the basis is the bins; it failed with a broadcasting error or, with as many components as bins, drew a wrong overlay.MAPchecksinit’s shape and sign, and that it is not all zero, when the engine is made; a wrong shape failed inside NumPy. EM raises zeros in its start to 1e-12 of the largest value, so a zero, frominitor from mix-SQP’s hand-off to EM, no longer leaves a wrong mode with only a convergence warning.NUTSchecksmodel, and the shape and finiteness ofinit_x, when it is made.The start for rates with a selection is near the mode for broad likelihoods too.
Gibbs refuses a negative
n_warmup;Laplace.runwith fewer than 3 samples draws 5 importance proposals rather than failing in Pareto smoothing; the engines that can infer a selection are each named once in the refusal of those that cannot.Response(matrix, efficiency=...)divides a migration column that sums to one withinMIGRATION_ATOLby its sum, so the efficiency given is exact.Boolean category labels reload as booleans; they came back as 0 and 1.
Errors name the input at fault: a single distribution passed to
from_density; objects in a measured bin whose response row is zero (the error suggesteddrop_empty); a truth bin whose response column sums to zero (the error spoke of selection values), and any selection value that is zero or not finite;Response.from_countswith more counts than generated events;Response.from_simulationwithopen_endedand categorical measured bins (anAttributeError); labelled scores that are not finite.Selection.combinedchecksscalebefore evaluating its functions.Adaptive bin averages refine a row whose 5-point estimates are all zero where a check rule reads something, until its cells are below
tolof their bin, and warn where the function is still unread there; such a row was read as zero, so a selection function, or a bounded density, that is non-zero only within 4.7% of a bin edge was missed without a warning.check()computes and checks the tail ESS of a selection or response inferred with the population (ess_tail_selection,ess_tail_response); it looked for these keys, which were never computed.mock_1ddraws posterior samples flat in u within each bin when the interim prior is omitted or known only per bin (masses or “flat”), asLikelihoods.from_samplesreads them; without an interim,mock.interimholdsDensity.flat()’s masses. On log bins the likelihoods built from these samples were biased; linear bins are unchanged.summary(level=),coverage(levels=)andplot(levels=)refuse levels outside (0, 1) by name, asintervaldoes.rhatof a constant chain is NaN without NumPy’s “All-NaN” warning.exact_posteriorrefuses apriorgiven with aPopulationModel, which ignored it.psisrefuses +inf log weights; it gave them zero weight.autocorr_timeandautocorr_functionreturn NaN for a constant chain; they gave 1, or the chain’s length when its mean was off by round-off.mock_categoricalchecks thatprevalenceandtrain_priorhaven_classesnon-negative entries with a positive sum, naming them.The ECDF p-value is documented as the Bonferroni bound below 1e-12, and Pareto smoothing as needing at least 21 weights; with fewer, k̂ = inf and the weights are not smoothed.
Unpickled
Bins, and copies of grids with a non-linear measure, had writeable edges.Bins.linear,Bins.logandBins.coarsenrefuse a count or factor that is not a positive integer, naming it; they truncated it, andcoarsen(1.5)returned the bins unchanged.Bins.categories(2.0)raises a TypeError naminglabels.PopulationModel.expected_countsraises, naming the objects of zero likelihood, and checksvalue; it returned zeros for them.missing_information(include_prior=True)adds aGammaRatesprior’s pseudo-counts as the MAP EM does: 0.49 instead of 0.89 forGammaRates(200, 1), which corrects the missing information reported when the rates EM does not converge. It is NaN where shapes below one outweigh the data.A distribution with
cdfandsfbut nologsfkeeps its upper tail.Likelihoods.from_samplesnames the measure when a sample falls where aMeasure.transformhas no finite slope, andMeasure.log_jacobianno longer emits NumPy warnings there.The docs of
tol, ofPopulationModel(bins=)and ofkkt_gap(include_prior=)say what the code does.A prior’s fingerprint, which
attachcompares afterload, includes the values of its base measure: priors with different base arrays of the same length no longer pass for each other, and a named function as base matches in another process.MAP with a tree prior one of whose branches has exponent zero, such as
PolyaTree(c=K/2), converges when that branch’s bins are empty: the KKT gap is checked on the tree’s branch probabilities, where it keeps its precision; EM warned that it had not converged (at K = 32 also in 0.1.0).A value that is not numbers, such as
Dirichlet("reference"), raises an error naming the argument rather than NumPy’s cast error.inferandAuto.runrefuse ann_samplesthat is not a positive integer, by name;0under auto ran at the automatic length.Dirichlet.from_countsrefuses a negativestrengthorbase, naming them; a negative strength subtracted the reference sample.auto reported “the only engine that takes these options” when Gibbs took them but a rule left it out.
amplitude,scaleandlength_scale(andlength_scale[d]) are named in their errors.The docs say which priors have unbounded densities, give
GeneralizedDirichlet’s defaultb_k = (K - k) a, and the length scale below whichLogisticGPwarns.Docs: the Laplace Student-t’s (−H)⁻¹ is its scale matrix, not its covariance; also
_HESSIAN_MAX_DIM’s description, bootstrap’stol, MAP’smax_iter(which covers mix-SQP) and the engines’ notation.
[0.1.0] - 2026-10-29¶
First release.
Changed (landing on main)¶
Renamed from
pastrytobinference(package, import and PyPI name). The warning base class isBinferenceWarningand the environment variables start withBINFERENCE_.Python ≥ 3.13, NumPy ≥ 2.1, SciPy ≥ 1.14.1, matplotlib ≥ 3.9.2.
CI runs the pre-commit hooks, the fast suite on three systems with Python 3.13 and 3.14, minimum dependencies, the README and user-guide code, the docs build and a clean-wheel import; pushes to
mainpublish the docs to GitHub Pages.Releases: a tag
vX.Y.Zonmainpublishes to PyPI by trusted publishing.Development process: issue and pull-request templates and the rules in
CLAUDE.mdandCONTRIBUTING.md.The prior base class is now
binference.priors.PopulationPrior(wasPrior).On log bins, the default base measures of
Dirichlet.from_base_measureandPolyaTree, the default mean of the logistic priors and the “flat” interim prior are flat in log z (they were flat in z).Results (audit O-1–O-21): a result keeps its selection through
save,loadandattach, which refuses other bins or another selection;result_to_dictis whatsavewrites (metaplus arrays,label_drawsapart from the bin labels);check()also flags tail ESS, E-BFMI, one-chain R-hat and unconverged optimisers and raisesDiagnosticsErrorwhen strict;summaryreports the mixing of the quantity it summarises;which=takes"fraction(s)"/"rate(s)"everywhere, includingfunctional,rebin,cov,corr,plot_cornerandplot_trace;method="em"runs EM on the simplex, and an explicitMAP(algorithm=)raises where it cannot run instead of falling back to L-BFGS (#100);sample_assignments,sample_valuesandrealized_countsdefault to 500 draws;binference.plottingandbinference.ioload on first use;result.plot_individual;PopulationEstimatorworks with scikit-learn model selection (Likelihoods.shape); the xarray export uses ArviZ’s statistic names, numeric bin centres and hyperparameter draws.inferdefaults tomethod="auto"(was"nuts"): Gibbs for joint conjugate models and for conjugate priors with at most 0.98 missing information (run long enough for a bulk ESS of about 400), else Laplace when its importance check passes with an ESS of at least 400, else NUTS. The choice and reason are inresult.info["auto_method"]and["auto_reason"]. The rules are one engine,binference.inference.Auto, whose thresholds (target_ess,gibbs_max_missing,nnz_limit) are options;PopulationEstimatordefaults to it too. Passmethod="nuts"for the previous behaviour. Withoutn_samples, a Gibbs run chosen by auto is extended until its ESS and R-hat pass, or gives way to the next engine beyondmax_gibbs_draws. Laplace draws that auto keeps without passing its check (on very large inputs, or as the last candidate) are flaggedapproximate.Laplacefinds its mode and curvature once per engine (andstep), not on everyrun.PopulationResult.log_predictiveworks through the objectschunkat a time (a newchunkargument, 4096 by default, aspredict_probaandassignment_probabilitiesalready did), so its memory no longer grows with the number of objects times the number of draws.Names:
sbcandcoveragetakeprogress=(wasprogress_bar=);CoverageResult.coverage_rates()(wasrates());Likelihoods.with_weights( fractional_weights=)(wasfractional=);simulate.mock_unfolding(n_objects=)(wasn_events=). Plots label rateslambda[k], as SBC names them (wasrate[k]). The"se"kernel alias and the rename hints for the old selection modes are gone.GibbsandMeanFieldVBraiseValueError(wasTypeError) for a model they cannot run, with the reasonEngine.unsupported(model)gives.PopulationModel.stack()is removed;likelihoods.stack()is the one stacking.Engines declare
Engine.markov(draws are Markov chains, checked by R-hat and ESS) andEngine.unsupported(model);PopulationResult(kind=)defaults to the model’s kind;diagnostics.importance_ess(weights)is Kish’s effective sample size.The chunked kernels work through 4096 dense rows at a time (was 65,536): Gibbs drew labels as fast at either size (N = 2·10⁴ to 2·10⁵, K = 20 to 80) with 16 times less memory per block. Sparse rows are sampled all at once, since slicing CSR rows per chunk cost time (0.030 s per label draw, from 0.035 s, at N = 2·10⁵, K = 200, 2% filled).
Faster: Laplace’s importance step evaluates its proposals in blocks (5.3 s, from 28.4 s, for 8000 proposals at N = 10⁵, K = 50, one thread); EM computes
L·ρonce per point; leave-one-out smooths all objects’ weights together (3.1 s, from 7.4 s, at N = 2·10⁴ with 2000 draws); Gibbs draws labels in place (35 ms, from 47 ms, per draw at N = 10⁵, K = 50).method="auto"keeps the MAP it computed asresult.bestwhen that raised no warning.Plot colours follow the active matplotlib style instead of fixed hex colours; new
sample_colorargument onplot_populationandplot_individual;colordefaults to the style and is added toplot_individualandplot_sbc; 2-D maps and the corner plot’s 2-D histograms are drawn on ramps to the population colour (relative uncertainty to the text colour) instead of viridis, magma and Blues;POSTERIOR_COLOR,STACK_COLORandINKare removed.
Fixed (phase-wide review)¶
PSIS compared weights with the cut as
log(exp(cut)), so a weight tied with the cut could enter the tail with no exceedance; with duplicated draws (resampled Laplace) the fit divided by zero. The cut is compared in logs, as ArviZ does; k-hat changes slightly where the old comparison included the cut weight.A degenerate generalised-Pareto fit gives k-hat = inf in
diagnostics.psis(was NaN, which compared False with any threshold), so leave-one-out flags such objects.Bootstrap and other resampling of a model with an inferred response kept each row’s measured bin from before rows were dropped.
attachclears everything computed from the previous likelihoods (the total, the missing information); a model with another prior than the fit’s no longer stands in for it inbestandbinning_bias(compared by a digest of the prior’s arguments, saved with the result, since its repr shortens arrays); a saved selection on a basis re-attaches after load.savekeeps the unconstrained draws, soprior_information_ratiois the same afterload.PopulationResult.from_samplesrefuses a model that infers its selection or response unless their draws are given.Diagnostics of a jointly inferred response are named
*_response(were*_selection).Posterior-sample mocks on unequal bins weighted every grid step alike, whatever its width (with bins [0, 0.1, 3], half the samples fell in the narrow bin). Their grid is now 50 equal steps per bin in the bins’ measure (in log z on log bins; was in z).
Selection.drawfloors its Beta draws as Gibbs does, so none underflows to zero.Pickling likelihoods whose within-bin data cannot be pickled warns (they were dropped silently).
Added¶
benchmarks/matrix.py: the benchmark matrix of scenario × prior × engine against long reference runs, with its results inbenchmarks/results/.Results:
result.selected(the selected population, alsowhich="selected"),realized_counts(full=True)(with the missed objects),data_supportand thesupportsummary column,prior_information_ratio()(Efron’s ratio),check(support_min=), andPointEstimate.check()for the KKT gap.Binning-bias check:
result.binning_bias()refits the data on linear B-spline components over the same bins (Gaussian inputs rebuild themselves; others takebuild) and reports each bin’s shift in posterior s.d. and, for flagged bins,n_crit, the number of objects at which the binning bias equals the statistical error.Best fit and leave-one-out: every result has
result.best(the MAP estimate, computed on first use) and per-object outputs at it with a_bestsuffix;assignment_probabilities_loogives leave-one-out posteriors by Pareto-smoothed importance sampling, with the Pareto k-hat per object.Value draws from within-bin information:
sample_valuesresamples the samples offrom_samplesinside the drawn bin (keep_samples=), evaluatesfrom_densitydensities inside 1-D bins (interim divided out for posteriors), and draws correlated Gaussians jointly by Gibbs sweeps (n_sweeps=); tables, binned inputs, compressed rows, densities on grids or without a pdf, samples not kept and density functions that could not be pickled fall back to flat within the bin, with a warning naming the source.Measures: each grid axis has a
Measure, the coordinateu = T(z)in which the population is flat within a bin: linear, log, a transform with its inverse, or the cumulative integral of a positive density.Bins.loguses the log measure; bin centres are midpoints inu;Bins.from_centerstakes midpoints inu(positive edges for log-spaced centres, I-16). Geometric hand-built edges warn.Selection from injections:
Selection.from_injectionsgives a completeness with Beta posteriors per bin, inferred jointly with the population by Gibbs, NUTS, Laplace andMAP(space="unconstrained")(logit S as extra coordinates);smooth=τties neighbouring bins by a random walk on logit S;at_mean()fixes it for VB and the bootstrap.Responses inferred with the population: a response tallied from events (
Response.from_counts,from_simulation,from_labelled) has a Dirichlet posterior per column (prior=β, default 1 per cell) and is inferred jointly by Gibbs, NUTS, Laplace and unconstrained MAP;response.fixed()takes it as known.Totals and rates from fractions: every fractions result has
total(draws of Λ ~ Gamma(W, S·ρ), exact under a scale-free prior) andrates(Λρ), with an absolute or no selection; point estimates give W/(S·ρ̂).Mixture basis and internal resolution:
binference.Basis(bins, order=0|1, resolution=r)fits components on the bins refinedrtimes, flat (order=0) or linear B-spline hats (order=1), and reports in the bins. Every constructor takes aBasisforbins(Likelihoods.on_basisfor per-bin likelihoods); callable selections are averaged with each component as the weight. Results report per bin and keepcomponent_draws; save and load keep the basis.Bins.refineis the counterpart ofcoarsen.sample_valueson non-linear measures now draws flat inuwithin a bin (it ignoredT'(z)).from_samplesstores likelihoods sparsely below 10% non-zero entries (was 30%).Masked grids:
mask=onBins,Bins.grid,Bins.linearandBins.log; masked cells leave the support and the model. Saved and loaded with results.Binswith edges-0.0and0.0now hash alike (I-12);Bins.indexrefuses multi-column values for 1-D bins (I-22).Density: one fixed density over the bin coordinate for interim priors, the Dirichlet base measure and simulation truth.Density.flat()is flat in the measure coordinate. An array interim prior on unequal bins needsinterim_representation, so every constructor reads it the same way (I-1); a callable on categories receives the labels (I-17).Likelihoods.stack()uses the interim prior the likelihoods were built with (I-5) and raises on rows with no support under it (I-6).Constructors by input form:
Likelihoods.from_tableandLikelihoods.from_densityreplacefrom_posteriors,from_functionandfrom_distributions; each needskind="likelihood"orinterim=.interim_prioris nowinterim(also instack()andsimulate.mock_1d).Adaptive quadrature: bin averages of functions and distributions are refined to
tol(default 1e-3), in the measure coordinate for likelihoods;from_gaussianaverages in u on non-linear axes. Far tails no longer underflow to empty rows (I-2, I-3).Samples: one estimator for every interim prior (per-sample weights T’(z)/π(z); a per-bin prior is flat in u within bins), an opt-in Dirichlet
floorin pseudo-samples,n_effinside the bins with a warning on the share of noisy objects (I-23),Likelihoods.sample_varianceand a Monte Carlo variance check inresult.check();Measure.log_jacobian.Binned measurements:
binference.Responseholds P(measured bin, observed | true bin) with real truth bins, from a matrix, tallies (Response.from_counts), simulated events (Response.from_simulation) or a labelled validation set (Response.from_labelled: open-ended score bins or a confusion matrix).Likelihoods.from_binnedreplacesfrom_response;from_classifieris removed (route A isfrom_tableon categories, route C isfrom_binnedwith a labelled response).summary()names the inputs, andresult.check()runs a posterior predictive test of the measured counts (Response.predictive_pvalue) that flags label shift.check()raisesInputWarningfor problems with the inputs (this test and the samples’ Monte Carlo variance) andConvergenceWarningfor sampler problems.simulate.mock_categoricalgainstemperatureand a labelledmock.response;simulate.mock_unfoldingreturnsmock.response.Selection: the modes are
"on_truth"and"on_measurement"(the old names raise an error naming the new ones);Selection.combined(on_truth, on_measurement)selects on both; a selection may be a function of the true value, averaged over each bin (Selection.from_function, or a callableselection=); values are detection probabilities in (0, 1] unless declaredscale="exposure"or"relative", and rates refuse a relative selection (audit G-4); an array that changes by more than a factor of two between neighbouring bins raises anInputWarning(aSelectionobject or a callable is taken as averaged within bins).simulate.mock_1d(measured_range=...)simulates selection on the measurement, alone or withselection=(combined).sbc/coveragename rateslambda[k](G-10).Model:
PopulationModel.log_probandlog_prob_and_gradare renamedlog_density_unconstrainedandlog_density_unconstrained_and_grad; the theory page explains the two densities and their modes.kkt_gapis infinite where an object is impossible and, for rates, relative to the exposure (audit M-3, M-4);missing_informationis correct with a selection function and on the support, withinclude_prior=for the MAP EM (M-2). Bootstrap replicates drop zero-weight objects in every engine, so EM no longer resets to the prior’s mode or collapses rates to zero (M-1); EM stops with a warning where an object becomes impossible. The rates starting point is W ρ / S (M-7).LogisticGP()works on two bins (M-14).PopulationResult.log_probis nowlog_density_unconstrained(old files still load);MAP.runno longer takesweights=.MAP:
tol(default 1e-8, was 1e-10 on the objective) is the tolerance on the KKT gap for every simplex algorithm and on the largest gradient overmax(1, W)for L-BFGS (mix-SQP bounds the gap of the problem it solves), and EM is converged only when the gap is below it, or below1e3 * tolonce the objective stops improving (M-6, M-9).GammaRateswith shapes of at least one use mix-SQP, with the total rate profiled out (M-6).PointEstimate.log_posteriorismodel.log_posterior(value)for every algorithm (NaN for priors without a closed-form density); L-BFGS addsinfo["log_density_unconstrained"](M-8). mix-SQP drops its SVD and starts after 10 EM steps instead of 50, 2–3 times faster on large dense inputs (M-5); a failed quadratic step hands over to EM instead of raising (M-13); Dirichlet priors mixing concentrations of one and above one no longer warn (T-4). The rates KKT gap is one-sided, so a rate EM drives towards zero no longer reads as a violation.Priors:
LogisticRandomWalk(trend_scale=3.0)is the standard deviation of each unpenalised mode’s root-mean-square size across the grid, so its meaning no longer depends on K (was 10 in basis units, which tightened as 1/√K; P-6). Arguments are checked when a prior is made:DirichletTreeper-node alphas of different lengths now work (P-4),LogisticNormal(cov=)must be a positive variance or a matrix positive semi-definite on zero-sum vectors (P-8),LogisticGPn_basisandboundary_factorare checked andlength_scaletakes an array (P-10, P-11),PolyaTreeneeds two bins and a non-negative power (P-9),GeneralizedDirichleta,bandorderare checked (P-22). Reprs show every argument (P-14); tree VB draws have no exact zeros (P-12);GammaRateshas aprior_transform(P-15).GeneralizedDirichletandPolyaTreeare no longer subclasses ofDirichletTree(P-13).LogisticRandomWalk(2).bindat K = 1000 and 20,000 GP draws are about twice as fast (P-20).GP prior:
LogisticGPis stationary in the measure coordinate (log z onBins.log; length scales are in that coordinate; P-1). Defaults:boundary_factor=3(was 1.5; P-3),n_basisone per bin up to 1024 modes in all (was at most 48 per axis), and a length-scale prior whose lower 1% quantile is the shortest length scale that basis resolves (P-2), orLogNormal(log(range/2), 1)on coarse grids (P-7). Partially centred GP densities and gradients agree where scales underflow (P-5).NUTS and Laplace: NUTS results (
x,log_density_unconstrained,model) and the positionssample()yields are in the model’s own coordinates, not the partly centred sampling ones (info["centring"]holds the weights; N-1, N-2).diagnostics.psis_threshold(n)gives the k̂ threshold for n importance weights. Parallel workers receive the model once, reuse one pool per run, never raise a BLAS thread limit already set, respect CPU affinity, and errors from the model are raised instead of triggering a serial rerun (N-3, N-7, N-13).max_depth,n_warmup,jitterandinitare checked (N-5); Laplace returns every draw asked for without importance resampling (N-4) and judges k̂ against min(1 − 1/log10 S, 0.7) (N-6). Dense momentum draws use a precomputed triangular factor (N-9).Validation, Gibbs, bootstrap: SBC p-values and bands use the expected count per rank bin (G-1) and
sbcwarns when the ESS is belown_draws(G-9);exact_posteriorintegrates by stick-breaking Gauss–Legendre quadrature that resolves the simplex boundary, also for concentrations below one, addslog_density, and bounds its memory, with a defaultn_gridof 200 (G-3, G-5); weighted Gibbs on sparse likelihoods draws counts over each row’s nonzeros only (G-2); Gibbs checkschunk,store_labelsandinit, and chains start apart, from counts that include missed objects (G-6, G-7); SBC rejectsn_binsaboven_draws + 1;Bootstrap(kind=)is nowscheme=, non-converged replicates are counted and the base fit warns (G-8).Correlated Gaussians:
from_gaussian(..., cov=)takes full per-object covariances, averaged over N-D bins by adaptive cubature in log space.weightsare integer multiplicities; non-integer weights needfractional_weights=Trueand warn that the result is a pseudo-likelihood. Stored arrays are read-only (I-14);compress()keeps sparse storage and is fast on it (I-7, I-19); warnings point at the caller’s line; clearer errors for badrtol, Gaussian shapes, zero objects and 2-D arrays passed toBins.grid(I-8, I-10, I-11, I-20); broad Gaussians keep full precision near the mean (I-15).Each object’s likelihood mass outside the bins is recorded in
meta["outside_fraction"], with a warning when many objects lose most of it.Inputs.
Bins(linear, log, from centres, N-D grids, categories) andLikelihoodswith constructors for:likelihood matrices (density or mass representation, dense or sparse, log-space input);
Gaussian measurements;
per-object posteriors with their interim prior;
posterior samples;
SciPy distributions and arbitrary likelihood functions;
response matrices (unfolding) and classifier scores or labels (quantification), as binned measurements with a
Response.
Selection.
Selectionfunctions with explicit"on_measurement"and"on_truth"modes, attached to the data or passed to the model.Model.
PopulationModelfor bin fractions or Poisson rates, with log-density and gradient in unconstrained coordinates, expected counts, responsibilities, an optimality (KKT) gap and the missing-information fraction.Priors.
Simplex:
Dirichlet(with reference, count-based and base-measure constructors),GeneralizedDirichlet,DirichletTree,PolyaTree.Smoothness:
LogisticNormal,LogisticRandomWalkandLogisticGP(Hilbert-space GP) on N-D grids, with inferred hyperparameters.Rates:
GammaRates.
Engines.
NUTS: multinomial NUTS with windowed metric adaptation. Smoothness priors get partial non-centring (where the data constrain their scales) and a curvature-based dense metric. Chains are resumable and can run in parallel processes, which share the cores’ BLAS threads (viathreadpoolctl) rather than oversubscribing them.Data-augmentation
Gibbsfor conjugate priors, with selection augmentation.MAPwith an optimality certificate: mix-SQP for Dirichlet priors with concentrations of at least one (under a fixed selection onlyDirichlet(1), which gives maximum likelihood) and forGammaRateswith shapes of at least one; SQUAREM-accelerated EM for the other conjugate priors whose density is bounded; L-BFGS otherwise.Laplacewith PSIS importance correction.MeanFieldVB(flagged as approximate) andBootstrap(nonparametric or Bayesian, over objects, with variable totals for rate models).
Interfaces.
binference.inferand the scikit-learn-stylePopulationEstimator.Results.
PopulationResultandPointEstimateprovide:summaries, intervals (central and HDI), functionals and rebinning;
per-object assignment probabilities, values and realised counts;
posterior predictive scores, diagnostics and checks with hints;
plots, save/load and xarray
DataTreeexport.
Diagnostics. Rank-normalised split R-hat, bulk and tail ESS, autocorrelation time, MCSE and PSIS.
Validation. Exact quadrature posteriors (K <= 3), simulation-based calibration and coverage studies. Mock catalogues in 1-D and 2-D, plus categorical, unfolding and prior-predictive mocks.
Design documents, tests, docs.
Specification, test plan, implementation plan, and a survey of related software, including an audit of the
frankenzsamplers.A fast and a slow (statistical) test suite.
Sphinx documentation with tutorials.