binference 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. {binference-0.2.0 → binference-0.3.0}/.gitignore +3 -0
  2. {binference-0.2.0 → binference-0.3.0}/CHANGELOG.md +80 -2
  3. {binference-0.2.0 → binference-0.3.0}/CITATION.cff +10 -5
  4. {binference-0.2.0 → binference-0.3.0}/PKG-INFO +47 -44
  5. binference-0.3.0/README.md +72 -0
  6. {binference-0.2.0 → binference-0.3.0}/pyproject.toml +2 -2
  7. {binference-0.2.0 → binference-0.3.0}/src/binference/_utils.py +3 -1
  8. binference-0.3.0/src/binference/_values.py +235 -0
  9. binference-0.3.0/src/binference/_version.py +1 -0
  10. {binference-0.2.0 → binference-0.3.0}/src/binference/basis.py +23 -21
  11. {binference-0.2.0 → binference-0.3.0}/src/binference/bins.py +8 -6
  12. {binference-0.2.0 → binference-0.3.0}/src/binference/diagnostics.py +3 -1
  13. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/base.py +3 -1
  14. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/bootstrap.py +2 -1
  15. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/gibbs.py +2 -2
  16. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/nuts.py +24 -25
  17. {binference-0.2.0 → binference-0.3.0}/src/binference/estimator.py +1 -1
  18. {binference-0.2.0 → binference-0.3.0}/src/binference/inference.py +18 -13
  19. {binference-0.2.0 → binference-0.3.0}/src/binference/likelihoods.py +106 -17
  20. {binference-0.2.0 → binference-0.3.0}/src/binference/model.py +8 -6
  21. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/base.py +15 -0
  22. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/dirichlet.py +82 -12
  23. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/logistic.py +73 -31
  24. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/rates.py +15 -1
  25. {binference-0.2.0 → binference-0.3.0}/src/binference/response.py +2 -1
  26. {binference-0.2.0 → binference-0.3.0}/src/binference/results.py +74 -257
  27. {binference-0.2.0 → binference-0.3.0}/src/binference/selection.py +35 -24
  28. {binference-0.2.0 → binference-0.3.0}/src/binference/simulate.py +33 -33
  29. {binference-0.2.0 → binference-0.3.0}/src/binference/validation.py +2 -1
  30. {binference-0.2.0 → binference-0.3.0}/tests/conftest.py +48 -0
  31. binference-0.3.0/tests/data/golden/empirikos.json +1 -0
  32. binference-0.3.0/tests/data/golden/make_empirikos.jl +43 -0
  33. binference-0.3.0/tests/data/golden/make_mixsqp.R +44 -0
  34. binference-0.3.0/tests/data/golden/mixsqp.json +1 -0
  35. {binference-0.2.0 → binference-0.3.0}/tests/test_api.py +130 -2
  36. {binference-0.2.0 → binference-0.3.0}/tests/test_auto.py +19 -8
  37. {binference-0.2.0 → binference-0.3.0}/tests/test_basis.py +21 -19
  38. {binference-0.2.0 → binference-0.3.0}/tests/test_best_loo.py +2 -2
  39. {binference-0.2.0 → binference-0.3.0}/tests/test_binning_bias.py +4 -4
  40. {binference-0.2.0 → binference-0.3.0}/tests/test_bins.py +4 -0
  41. {binference-0.2.0 → binference-0.3.0}/tests/test_constructors.py +10 -10
  42. {binference-0.2.0 → binference-0.3.0}/tests/test_correlated.py +3 -3
  43. {binference-0.2.0 → binference-0.3.0}/tests/test_derived_rates.py +1 -1
  44. {binference-0.2.0 → binference-0.3.0}/tests/test_diagnostics.py +17 -0
  45. {binference-0.2.0 → binference-0.3.0}/tests/test_engines.py +640 -15
  46. {binference-0.2.0 → binference-0.3.0}/tests/test_explainers.py +37 -2
  47. binference-0.3.0/tests/test_golden.py +63 -0
  48. {binference-0.2.0 → binference-0.3.0}/tests/test_hygiene.py +19 -10
  49. {binference-0.2.0 → binference-0.3.0}/tests/test_injections.py +45 -9
  50. binference-0.3.0/tests/test_io.py +219 -0
  51. {binference-0.2.0 → binference-0.3.0}/tests/test_joint_response.py +2 -2
  52. {binference-0.2.0 → binference-0.3.0}/tests/test_likelihoods.py +59 -10
  53. {binference-0.2.0 → binference-0.3.0}/tests/test_measures_masks.py +4 -4
  54. {binference-0.2.0 → binference-0.3.0}/tests/test_model.py +141 -1
  55. binference-0.2.0/tests/test_plotting_io.py → binference-0.3.0/tests/test_plotting.py +13 -64
  56. {binference-0.2.0 → binference-0.3.0}/tests/test_priors.py +349 -10
  57. {binference-0.2.0 → binference-0.3.0}/tests/test_response.py +17 -0
  58. binference-0.3.0/tests/test_results.py +583 -0
  59. {binference-0.2.0 → binference-0.3.0}/tests/test_samples.py +84 -2
  60. {binference-0.2.0 → binference-0.3.0}/tests/test_simulate_validation.py +29 -6
  61. {binference-0.2.0 → binference-0.3.0}/tests/test_values.py +68 -21
  62. binference-0.2.0/README.md +0 -69
  63. binference-0.2.0/src/binference/_version.py +0 -1
  64. binference-0.2.0/tests/test_gibbs_fixes.py +0 -107
  65. binference-0.2.0/tests/test_map_fixes.py +0 -180
  66. binference-0.2.0/tests/test_model_fixes.py +0 -205
  67. binference-0.2.0/tests/test_nuts_fixes.py +0 -167
  68. binference-0.2.0/tests/test_prior_fixes.py +0 -259
  69. binference-0.2.0/tests/test_results.py +0 -260
  70. binference-0.2.0/tests/test_results_audit.py +0 -510
  71. binference-0.2.0/tests/test_review_regressions.py +0 -343
  72. {binference-0.2.0 → binference-0.3.0}/LICENSE +0 -0
  73. {binference-0.2.0 → binference-0.3.0}/src/binference/__init__.py +0 -0
  74. {binference-0.2.0 → binference-0.3.0}/src/binference/_kernels.py +0 -0
  75. {binference-0.2.0 → binference-0.3.0}/src/binference/_quadrature.py +0 -0
  76. {binference-0.2.0 → binference-0.3.0}/src/binference/_simplex.py +0 -0
  77. {binference-0.2.0 → binference-0.3.0}/src/binference/density.py +0 -0
  78. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/__init__.py +0 -0
  79. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/_curvature.py +0 -0
  80. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/_nuts_core.py +0 -0
  81. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/laplace.py +0 -0
  82. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/optimize.py +0 -0
  83. {binference-0.2.0 → binference-0.3.0}/src/binference/engines/vb.py +0 -0
  84. {binference-0.2.0 → binference-0.3.0}/src/binference/io.py +0 -0
  85. {binference-0.2.0 → binference-0.3.0}/src/binference/measure.py +0 -0
  86. {binference-0.2.0 → binference-0.3.0}/src/binference/plotting.py +2 -2
  87. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/__init__.py +0 -0
  88. {binference-0.2.0 → binference-0.3.0}/src/binference/priors/hyper.py +0 -0
  89. {binference-0.2.0 → binference-0.3.0}/src/binference/warnings.py +0 -0
  90. {binference-0.2.0 → binference-0.3.0}/tests/__init__.py +0 -0
  91. {binference-0.2.0 → binference-0.3.0}/tests/data/matrix_reference.json +0 -0
  92. {binference-0.2.0 → binference-0.3.0}/tests/test_api_docs.py +0 -0
  93. {binference-0.2.0 → binference-0.3.0}/tests/test_benchmark_matrix.py +0 -0
  94. {binference-0.2.0 → binference-0.3.0}/tests/test_density.py +0 -0
  95. {binference-0.2.0 → binference-0.3.0}/tests/test_matrix_regression.py +0 -0
  96. {binference-0.2.0 → binference-0.3.0}/tests/test_quadrature_peaks.py +0 -0
  97. {binference-0.2.0 → binference-0.3.0}/tests/test_results_outputs.py +0 -0
  98. {binference-0.2.0 → binference-0.3.0}/tests/test_sbc_cases.py +0 -0
  99. {binference-0.2.0 → binference-0.3.0}/tests/test_selection.py +0 -0
  100. {binference-0.2.0 → binference-0.3.0}/tests/test_simplex.py +0 -0
  101. {binference-0.2.0 → binference-0.3.0}/tests/test_slow.py +0 -0
@@ -107,3 +107,6 @@ venv.bak/
107
107
  docs/reference/api/generated/
108
108
  docs/jupyter_execute/
109
109
  .jupyter_cache/
110
+
111
+ # Personal Claude Code instructions
112
+ CLAUDE.local.md
@@ -2,8 +2,86 @@
2
2
 
3
3
  All notable changes to binference are recorded here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
- [Semantic Versioning](https://semver.org/) (with the usual 0.x caveat that minor
6
- releases may break the API).
5
+ [Semantic Versioning](https://semver.org/) as the contributing guide's "Breaking
6
+ changes" section sets out.
7
+
8
+ ## [0.3.0] - 2026-11-27
9
+
10
+ ### Added
11
+
12
+ - The posterior-input guide shows how to turn a `qp` histogram ensemble into bin
13
+ masses and supply the interim prior used by the photometric-redshift fit.
14
+ - `Likelihoods.from_samples` takes `kind="likelihood"` for samples drawn from a
15
+ likelihood, as `from_table` and `from_density` do.
16
+ - `Likelihoods.from_samples(..., smooth="kde", bandwidth=...)` spreads each sample over
17
+ the bins by a Gaussian kernel in the measure coordinate (1-D bins). It helps on bins much
18
+ narrower than the posteriors, widens each posterior by the bandwidth, and blurs
19
+ posteriors with several peaks.
20
+ - `GeneralizedDirichlet.from_base_measure(concentration, base, order)` sets each stick's
21
+ Beta so that the prior mean is the base measure's bin masses, with the same
22
+ concentration `a + b` on every stick.
23
+ - A `Dirichlet` with one concentration for every bin (a scalar `alpha`, the default, or
24
+ `Dirichlet.reference()`) raises an `InputWarning` on bins of unequal width in the measure
25
+ coordinate, where its prior mean is not a flat density, and points to
26
+ `Dirichlet.from_base_measure`. `GammaRates` with one `shape` for every bin warns there too.
27
+ - `check()` warns when bins with fewer than 20 recovered injections hold more than a tenth
28
+ of the population, for a selection from injections inferred or `fixed()`, and names the
29
+ bins that need more injections.
30
+
31
+ ### Changed
32
+
33
+ - binference enters beta. The compatibility policy in `CONTRIBUTING.md` covers
34
+ API changes and loading results saved by the previous minor release.
35
+ - **Breaking:** renames, each to the spelling its siblings use:
36
+ - `Likelihoods.from_gaussian(mean, sigma, bins)` → `(mean, bins, sigma)`, with `bins`
37
+ required.
38
+ - `Auto(gibbs_max_missing=, nnz_limit=)` → `max_gibbs_missing=`, `max_nnz=`.
39
+ - `Selection.from_function(function=)` → `func=`.
40
+ - `Basis.masses(grid)` and `axis_masses(grid)` → `bins`.
41
+ - `Selection.draw`, `Response.draw` and `PopulationModel.draw_total` → `sample`,
42
+ `sample_total`.
43
+ - `simulate.mock_1d(n_samples=)` → `samples_per_object=`.
44
+ - `check(predictive_draws=)` → `n_predictive=`.
45
+ - `simulate.mock_unfolding(n_true=, n_reco=)` → `n_truth=`, `n_measured=`, and its
46
+ `measurements["reco_counts"]` → `"measured_counts"`.
47
+ - `selection.as_selection` is now private.
48
+ - **Breaking:** options after a method's primary arguments are keyword-only, so a
49
+ positional call means the same on sibling methods (`check(True)` set `strict` on one
50
+ result type and `kkt_max` on the other). This covers the result and per-object methods
51
+ (`realized_counts` takes only keywords), `PointEstimate.laplace`,
52
+ `Likelihoods.with_weights` and `stack`, `PopulationModel`'s methods, `exact_posterior`,
53
+ `SBCResult.passed`, `simulate.population`, `plot_individual`, `plot_sbc`,
54
+ `LogisticRandomWalk`, `LogisticGP`, `LogisticNormal` after `cov`, and `Bins(mask=)`;
55
+ and `rng` everywhere a user passes it. Passing one of these by position raises a
56
+ `TypeError`; pass it by name.
57
+ - **Breaking:** `LogisticRandomWalk` takes its differences at the bin centres in the
58
+ measure coordinate, in units of their mean spacing, and its unpenalised trends are
59
+ polynomials in that coordinate. On bins of equal width in the measure coordinate
60
+ (`Bins.linear`, `Bins.log`) nothing changes; on unequal bins a step over a wider gap may
61
+ be larger. Results saved on unequal bins by 0.2 attach under the new prior. No argument
62
+ restores the index steps; use 0.2 to reproduce such a fit.
63
+ - **Breaking:** `LogisticGP` with `n_basis=None` gives each axis as many sines as its
64
+ narrowest bin fits across the axis, at most four per bin; on bins of equal width this is
65
+ one per bin, as before. To keep 0.2's basis on unequal bins, pass `n_basis` with the
66
+ number of bins on each axis.
67
+ - **Breaking:** `Selection.from_injections` takes Jeffreys' prior, `prior=(0.5, 0.5)`, on
68
+ each bin's detection probability by default; it was `(1, 1)`. With few recoveries it
69
+ reduced the low bias of derived totals from 12% to 9% in simulations of the injections
70
+ tutorial's setup. Pass `prior=(1, 1)` for the old default.
71
+ - NUTS uses a dense metric for logistic priors up to 500 dimensions (from 200), and
72
+ starts it from the curvature at every chain's position. With `LogisticGP`'s default
73
+ basis, two chains and one thread each, this cut the time per fit by two to five times
74
+ on a 16 × 16 grid, about three on 20 × 20 and five on 22 × 22. Above 500 dimensions,
75
+ `metric="auto"` is diagonal and starts from the identity. The low E-BFMI of `LogisticGP`
76
+ fits on large grids remains; the engines page documents it.
77
+ - `PolyaTree`'s error for a base measure with an empty bin reads as `Dirichlet`'s.
78
+
79
+ ### Fixed
80
+
81
+ - `NUTS` refuses a NaN `n_warmup` or `jitter` and a fractional `n_warmup`, which it
82
+ truncated.
83
+ - `infer` names an option that no engine takes as unknown, rather than suggesting `method=`;
84
+ `check` refuses an `n_predictive` that is not a positive integer.
7
85
 
8
86
  ## [0.2.0] - 2026-11-07
9
87
 
@@ -3,15 +3,20 @@ message: "If you use binference, please cite it as below, together with the meth
3
3
  title: "binference: population and hierarchical inference with PDFs"
4
4
  abstract: >-
5
5
  binference infers population distributions over bins, and the posteriors of
6
- individual objects, from heteroscedastic per-object likelihoods, posteriors
7
- or posterior samples, using an exact hierarchical Bayesian model with
8
- smoothness priors, selection effects and built-in validation.
6
+ individual objects, from per-object likelihoods, posteriors, posterior
7
+ samples, binned measurements or classifier outputs, using an exact
8
+ hierarchical Bayesian model with smoothness priors, selection effects and
9
+ built-in validation.
9
10
  type: software
10
11
  authors:
11
12
  - family-names: Speagle
12
13
  given-names: Joshua S.
13
- version: 0.2.0
14
- date-released: 2026-11-07
14
+ version: 0.3.0
15
+ date-released: 2026-11-27
16
+ identifiers:
17
+ - type: doi
18
+ value: "10.5281/zenodo.23752879"
19
+ description: "Zenodo concept DOI for all archived binference versions."
15
20
  license: MIT
16
21
  repository-code: "https://github.com/joshspeagle/binference"
17
22
  keywords:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: binference
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Population and hierarchical inference with PDFs: honest population distributions from noisy per-object PDFs over bins.
5
5
  Project-URL: Homepage, https://github.com/joshspeagle/binference
6
6
  Project-URL: Source, https://github.com/joshspeagle/binference
@@ -10,7 +10,7 @@ Author: Joshua S. Speagle
10
10
  License-Expression: MIT
11
11
  License-File: LICENSE
12
12
  Keywords: bayesian,deconvolution,dirichlet,hierarchical,mcmc,photometric redshifts,population inference,quantification,unfolding
13
- Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Development Status :: 4 - Beta
14
14
  Classifier: Intended Audience :: Science/Research
15
15
  Classifier: Operating System :: OS Independent
16
16
  Classifier: Programming Language :: Python :: 3
@@ -61,23 +61,24 @@ Provides-Extra: xarray
61
61
  Requires-Dist: xarray>=2024.10; extra == 'xarray'
62
62
  Description-Content-Type: text/markdown
63
63
 
64
- # binference
64
+ <h1>
65
+ <picture>
66
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_themes/binference/static/brand/lockup-large-dark.svg">
67
+ <img alt="binference" width="300" src="https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_themes/binference/static/brand/lockup-large-light.svg">
68
+ </picture>
69
+ </h1>
65
70
 
66
- **Population and hierarchical inference with PDFs.**
71
+ [![PyPI version][pypi-badge]][pypi]
72
+ [![Supported Python versions][python-badge]][pypi]
73
+ [![CI status on main][ci-badge]][ci]
74
+ [![Documentation][docs-badge]][docs]
67
75
 
68
- Many objects are each measured with noise: galaxies, merger events, patients,
69
- classified documents. binference reads each object's likelihood, posterior, samples,
70
- binned measurement or classifier output. From these it infers the population the objects
71
- come from, with calibrated uncertainty, and each object's posterior under that
72
- population.
76
+ **Population inference from noisy measurements.** binference combines per-object
77
+ likelihoods, posteriors, samples, binned counts, or classifier outputs. Fit the
78
+ population distribution, quantify its uncertainty, and use it to update each
79
+ object's posterior.
73
80
 
74
- ![Population posteriors for a mock catalogue][figure]
75
-
76
- [figure]: https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_static/quickstart.png
77
-
78
- *The population inferred from 2000 simulated objects, under the default Dirichlet prior
79
- (top) and a Gaussian-process prior (bottom). Each panel shows the posterior median, its
80
- 68% and 95% intervals, the true density (dashed) and the stacked estimate (dotted).*
81
+ [Quick start][quickstart] · [Choose an input][inputs] · [Tutorials][tutorials] · [API reference][api]
81
82
 
82
83
  ## Install
83
84
 
@@ -85,48 +86,50 @@ population.
85
86
  pip install "binference[plot]"
86
87
  ```
87
88
 
88
- The [installation page](https://joshspeagle.github.io/binference/start/install.html)
89
- lists the extras and the supported Python versions.
89
+ See the [installation guide][install] for supported Python versions and extras.
90
+
91
+ ## Fit a population
90
92
 
91
- ## Example
93
+ This example estimates a redshift distribution from measured values and their
94
+ Gaussian errors. Replace the simulated arrays with your own.
92
95
 
93
96
  ```python
94
97
  import binference
95
98
 
96
99
  bins = binference.Bins.linear(0.0, 3.0, 15)
97
-
98
- # a simulated stand-in for your arrays: measured values and their Gaussian errors
99
100
  mock = binference.simulate.mock_1d(2000, bins, rng=42)
100
101
  z_obs, z_err = mock.measurements["mean"], mock.measurements["sigma"]
101
102
 
102
- lk = binference.Likelihoods.from_gaussian(z_obs, z_err, bins)
103
- result = binference.infer(lk, rng=1) # method="auto" chooses the engine
103
+ lk = binference.Likelihoods.from_gaussian(z_obs, bins, z_err)
104
+ result = binference.infer(lk, rng=1)
104
105
  print(result.summary())
105
106
  ```
106
107
 
107
- ## Documentation
108
-
109
- - [Quick start][quickstart]
110
- - [Is binference right for my data?][is-it-right]
111
- - [Tutorials][tutorials]
112
- - [Full documentation][docs]
113
-
114
- [quickstart]: https://joshspeagle.github.io/binference/start/quickstart.html
115
- [is-it-right]: https://joshspeagle.github.io/binference/start/is-it-right.html
116
- [tutorials]: https://joshspeagle.github.io/binference/tutorials/index.html
117
- [docs]: https://joshspeagle.github.io/binference/
118
-
119
- To contribute, see [`CONTRIBUTING.md`][contributing].
108
+ ![Population posteriors for a mock catalogue][figure]
120
109
 
121
- [contributing]: https://github.com/joshspeagle/binference/blob/main/CONTRIBUTING.md
110
+ *Population posteriors for 2,000 simulated objects under a Dirichlet prior (top)
111
+ and a Gaussian-process prior (bottom). Each panel shows the posterior median,
112
+ 68% and 95% intervals, the true density (dashed), and the stacked estimate (dotted).*
122
113
 
123
- ## Status and citing
114
+ ## Status, citation, and contributions
124
115
 
125
- binference is alpha software, and its API may change before 1.0. If you use it, please
126
- cite it as described on the [citing page][citing].
116
+ Version 0.3.0 is the first beta. The API may change before 1.0. If you use
117
+ binference in your work, see [how to cite it][citing]. Contributions follow the
118
+ [contributor guide][contributing]. binference is released under the [MIT License][license].
127
119
 
120
+ [pypi-badge]: https://img.shields.io/pypi/v/binference
121
+ [python-badge]: https://img.shields.io/pypi/pyversions/binference
122
+ [ci-badge]: https://github.com/joshspeagle/binference/actions/workflows/ci.yml/badge.svg?branch=main
123
+ [docs-badge]: https://img.shields.io/badge/docs-online-4A4FC4
124
+ [pypi]: https://pypi.org/project/binference/
125
+ [ci]: https://github.com/joshspeagle/binference/actions/workflows/ci.yml
126
+ [docs]: https://joshspeagle.github.io/binference/
127
+ [quickstart]: https://joshspeagle.github.io/binference/start/quickstart.html
128
+ [inputs]: https://joshspeagle.github.io/binference/guides/inputs/index.html
129
+ [tutorials]: https://joshspeagle.github.io/binference/tutorials/index.html
130
+ [api]: https://joshspeagle.github.io/binference/reference/api/index.html
131
+ [install]: https://joshspeagle.github.io/binference/start/install.html
132
+ [figure]: https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_static/quickstart.png
128
133
  [citing]: https://joshspeagle.github.io/binference/reference/citing.html
129
-
130
- ## License
131
-
132
- MIT; see [LICENSE](https://github.com/joshspeagle/binference/blob/main/LICENSE).
134
+ [contributing]: https://github.com/joshspeagle/binference/blob/main/CONTRIBUTING.md
135
+ [license]: https://github.com/joshspeagle/binference/blob/main/LICENSE
@@ -0,0 +1,72 @@
1
+ <h1>
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_themes/binference/static/brand/lockup-large-dark.svg">
4
+ <img alt="binference" width="300" src="https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_themes/binference/static/brand/lockup-large-light.svg">
5
+ </picture>
6
+ </h1>
7
+
8
+ [![PyPI version][pypi-badge]][pypi]
9
+ [![Supported Python versions][python-badge]][pypi]
10
+ [![CI status on main][ci-badge]][ci]
11
+ [![Documentation][docs-badge]][docs]
12
+
13
+ **Population inference from noisy measurements.** binference combines per-object
14
+ likelihoods, posteriors, samples, binned counts, or classifier outputs. Fit the
15
+ population distribution, quantify its uncertainty, and use it to update each
16
+ object's posterior.
17
+
18
+ [Quick start][quickstart] · [Choose an input][inputs] · [Tutorials][tutorials] · [API reference][api]
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install "binference[plot]"
24
+ ```
25
+
26
+ See the [installation guide][install] for supported Python versions and extras.
27
+
28
+ ## Fit a population
29
+
30
+ This example estimates a redshift distribution from measured values and their
31
+ Gaussian errors. Replace the simulated arrays with your own.
32
+
33
+ ```python
34
+ import binference
35
+
36
+ bins = binference.Bins.linear(0.0, 3.0, 15)
37
+ mock = binference.simulate.mock_1d(2000, bins, rng=42)
38
+ z_obs, z_err = mock.measurements["mean"], mock.measurements["sigma"]
39
+
40
+ lk = binference.Likelihoods.from_gaussian(z_obs, bins, z_err)
41
+ result = binference.infer(lk, rng=1)
42
+ print(result.summary())
43
+ ```
44
+
45
+ ![Population posteriors for a mock catalogue][figure]
46
+
47
+ *Population posteriors for 2,000 simulated objects under a Dirichlet prior (top)
48
+ and a Gaussian-process prior (bottom). Each panel shows the posterior median,
49
+ 68% and 95% intervals, the true density (dashed), and the stacked estimate (dotted).*
50
+
51
+ ## Status, citation, and contributions
52
+
53
+ Version 0.3.0 is the first beta. The API may change before 1.0. If you use
54
+ binference in your work, see [how to cite it][citing]. Contributions follow the
55
+ [contributor guide][contributing]. binference is released under the [MIT License][license].
56
+
57
+ [pypi-badge]: https://img.shields.io/pypi/v/binference
58
+ [python-badge]: https://img.shields.io/pypi/pyversions/binference
59
+ [ci-badge]: https://github.com/joshspeagle/binference/actions/workflows/ci.yml/badge.svg?branch=main
60
+ [docs-badge]: https://img.shields.io/badge/docs-online-4A4FC4
61
+ [pypi]: https://pypi.org/project/binference/
62
+ [ci]: https://github.com/joshspeagle/binference/actions/workflows/ci.yml
63
+ [docs]: https://joshspeagle.github.io/binference/
64
+ [quickstart]: https://joshspeagle.github.io/binference/start/quickstart.html
65
+ [inputs]: https://joshspeagle.github.io/binference/guides/inputs/index.html
66
+ [tutorials]: https://joshspeagle.github.io/binference/tutorials/index.html
67
+ [api]: https://joshspeagle.github.io/binference/reference/api/index.html
68
+ [install]: https://joshspeagle.github.io/binference/start/install.html
69
+ [figure]: https://raw.githubusercontent.com/joshspeagle/binference/main/docs/_static/quickstart.png
70
+ [citing]: https://joshspeagle.github.io/binference/reference/citing.html
71
+ [contributing]: https://github.com/joshspeagle/binference/blob/main/CONTRIBUTING.md
72
+ [license]: https://github.com/joshspeagle/binference/blob/main/LICENSE
@@ -24,7 +24,7 @@ keywords = [
24
24
  "mcmc",
25
25
  ]
26
26
  classifiers = [
27
- "Development Status :: 3 - Alpha",
27
+ "Development Status :: 4 - Beta",
28
28
  "Intended Audience :: Science/Research",
29
29
  "Operating System :: OS Independent",
30
30
  "Programming Language :: Python :: 3",
@@ -93,7 +93,7 @@ exclude_also = ["if TYPE_CHECKING:", "raise NotImplementedError", "@overload"]
93
93
  [tool.ruff]
94
94
  line-length = 99
95
95
  src = ["src", "tests"]
96
- extend-exclude = ["docs/_build", "research_notes", "reports", "notes", "*.md"]
96
+ extend-exclude = ["docs/_build", "notes", "*.md"]
97
97
 
98
98
  [tool.ruff.lint]
99
99
  select = ["E", "F", "W", "I", "B", "UP", "NPY", "RUF", "SIM", "C4", "PT", "PIE", "PERF"]
@@ -129,8 +129,10 @@ def check_nonnegative(value: Any, name: str) -> np.ndarray:
129
129
 
130
130
 
131
131
  def _check_sign(value: Any, name: str, positive: bool) -> np.ndarray:
132
+ got = ""
132
133
  try:
133
134
  raw = np.asarray(value)
135
+ got = f"; got {value!r}" if raw.ndim == 0 else ""
134
136
  a = np.asarray(raw, dtype=float)
135
137
  ok = (
136
138
  raw.dtype.kind != "b"
@@ -141,7 +143,7 @@ def _check_sign(value: Any, name: str, positive: bool) -> np.ndarray:
141
143
  ok = False
142
144
  if not ok:
143
145
  what = "strictly positive" if positive else "non-negative"
144
- raise ValueError(f"{name} must be finite and {what}.")
146
+ raise ValueError(f"{name} must be finite and {what}{got}.")
145
147
  return a
146
148
 
147
149
 
@@ -0,0 +1,235 @@
1
+ """Values drawn inside bins from each input's own within-bin information.
2
+
3
+ ``sample_values``, on a ``PopulationResult`` or a ``PointEstimate``, draws a value for each
4
+ object inside the bin it is assigned to; :func:`_value_drawer` chooses how from what the
5
+ likelihoods kept: the per-object arrays of ``Likelihoods.meta``
6
+ (``_PER_OBJECT_KEYS`` and ``_WithinBin`` in ``likelihoods``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from functools import partial
13
+
14
+ import numpy as np
15
+ from scipy import special
16
+
17
+ from . import _kernels as kern
18
+ from .density import _log_nonneg
19
+ from .likelihoods import _log_interim, _rows_logpdf
20
+ from .measure import Measure
21
+
22
+ #: Most values a density function returns per call when values are drawn (2**24 floats
23
+ #: are 128 MB).
24
+ EVAL_BUDGET = 2**24
25
+
26
+
27
+ def _value_drawer(model, loglike, n_sub: int, n_sweeps: int) -> tuple[Callable, bool]:
28
+ """``draw(objects, labels, lo, hi, gen, height) -> (z, keep)``: values in the boxes
29
+ ``[lo, hi]`` (in ``u``, ``(n, ndim)``) from the input's own likelihood times the
30
+ population, flat in ``u`` times the hat's ``height(labels, d, u)`` per axis (``None``
31
+ when flat); and whether the input has within-bin information."""
32
+ # DECISIONS #50
33
+ meta = model.likelihoods.meta
34
+ measures = model.bins.measures
35
+ flat = partial(_draw_subpoints, measures, n_sub, None)
36
+ if loglike is not None:
37
+ return partial(_draw_subpoints, measures, n_sub, _per_object(loglike)), True
38
+ if "gaussian_mean" in meta:
39
+ return partial(_draw_gauss, measures, n_sub, n_sweeps, meta), True
40
+ within = meta.get("within")
41
+ if within is None or within.data is None or "value_row" not in meta:
42
+ return flat, False # e.g. rows merged by compress, which drops value_row
43
+ kind, *data = within.data
44
+ row = np.asarray(meta["value_row"])
45
+ if kind == "samples":
46
+ # labels are the bins the samples are in
47
+ direct = model.likelihoods.basis.is_identity and data[0] == model.K
48
+ return partial(_draw_samples, measures, flat, direct, row, *data), True
49
+ if kind == "dists": # one family's parameters are packed once, not per call
50
+ dists, interim = data
51
+ evaluate = partial(_dists_logl, row, _rows_logpdf(dists, 1), interim)
52
+ else:
53
+ evaluate = partial(_rows_logl, row, *data)
54
+ return partial(_draw_subpoints, measures, n_sub, evaluate), True
55
+
56
+
57
+ def _dists_logl(row, logpdf, interim, objects, labels, zz):
58
+ # distributions of from_density: one vectorised call for the rows' own points
59
+ with np.errstate(invalid="ignore"): # -inf - -inf where the interim vanishes: NaN
60
+ return logpdf(zz, row[objects]) - _log_interim(interim, zz)
61
+
62
+
63
+ def _rows_logl(row, n_in, fn, log, interim, objects, labels, zz):
64
+ # a density function of from_density returns every input row at common points: it
65
+ # is called on the sub-points of a few bins at a time, at most EVAL_BUDGET values
66
+ out = np.empty(zz.shape)
67
+ _, first, inverse = np.unique(labels, return_index=True, return_inverse=True)
68
+ inverse = inverse.ravel()
69
+ per = max(1, EVAL_BUDGET // (n_in * zz.shape[1]))
70
+ for c in range(0, len(first), per):
71
+ at = np.flatnonzero((inverse >= c) & (inverse < c + per))
72
+ pts = zz[first[c : c + per]]
73
+ v = fn(pts.ravel())
74
+ v = np.asarray(v if log else _log_nonneg(v), dtype=float).reshape(n_in, *pts.shape)
75
+ out[at] = v[row[objects[at]], inverse[at] - c]
76
+ with np.errstate(invalid="ignore"): # -inf - -inf where the interim vanishes: NaN
77
+ return out - _log_interim(interim, zz)
78
+
79
+
80
+ def _per_object(loglike: Callable[[np.ndarray, int], np.ndarray]) -> Callable:
81
+ """An evaluator ``(objects, labels, zz) -> log-likelihoods`` calling ``loglike(z, i)``
82
+ once per object, at the sub-points of all its bins."""
83
+
84
+ def evaluate(objects, labels, zz):
85
+ key = objects.astype(np.int64) * (int(labels.max()) + 1) + labels # by object
86
+ _, first, inverse = np.unique(key, return_index=True, return_inverse=True)
87
+ vals = np.empty((len(first), zz.shape[1]))
88
+ ids, starts = np.unique(objects[first], return_index=True)
89
+ for i, a, b in zip(ids, starts, [*starts[1:], len(first)], strict=True):
90
+ pts = zz[first[a:b]]
91
+ vals[a:b] = np.asarray(loglike(pts.ravel(), int(i)), dtype=float).reshape(pts.shape)
92
+ return vals[inverse.ravel()]
93
+
94
+ return evaluate
95
+
96
+
97
+ def _subpoints(zlo, zhi, n_sub):
98
+ # midpoints of n_sub equal cells in z of each box, (n, n_sub)
99
+ return zlo[:, None] + (zhi - zlo)[:, None] * ((np.arange(n_sub) + 0.5) / n_sub)
100
+
101
+
102
+ def _subpoint_draw(zz, width, logw, gen, objects) -> np.ndarray:
103
+ """One value per row by inverse-CDF sampling on the sub-points ``zz`` (cells of
104
+ ``width / n_sub``) with log-weights ``logw``."""
105
+ n, n_sub = logw.shape
106
+ logw = np.where(np.isnan(logw), -np.inf, logw) # e.g. a posterior over a zero prior
107
+ empty = ~np.isfinite(logw).any(axis=1)
108
+ if empty.any(): # it drew from the box's first sub-point before (audit O-11)
109
+ raise ValueError(
110
+ f"The likelihood is zero at all {n_sub} sub-points of a bin with posterior "
111
+ f"mass (object {int(objects[empty][0])}); raise n_sub or check loglike."
112
+ )
113
+ cell = kern._sample_labels_dense(np.exp(logw - logw.max(axis=1, keepdims=True)), 1.0, gen)
114
+ return zz[np.arange(n), cell] + width / n_sub * (gen.random(n) - 0.5)
115
+
116
+
117
+ def _base_logw(m, zz, labels, d, height):
118
+ # flat in u (the Jacobian in z) times the hat's height along axis d
119
+ with np.errstate(divide="ignore"):
120
+ return m.log_jacobian(zz) + (
121
+ 0.0 if height is None else np.log(height(labels, d, m.forward(zz)))
122
+ )
123
+
124
+
125
+ def _draw_subpoints(measures, n_sub, evaluate, objects, labels, lo, hi, gen, height):
126
+ # each axis on n_sub sub-points: the population, times evaluate(objects, labels, zz)
127
+ z = np.empty(lo.shape)
128
+ for d, m in enumerate(measures):
129
+ zlo, zhi = m.inverse(lo[:, d]), m.inverse(hi[:, d])
130
+ zz = _subpoints(zlo, zhi, n_sub)
131
+ logw = _base_logw(m, zz, labels, d, height)
132
+ if evaluate is not None:
133
+ logw = logw + evaluate(objects, labels, zz)
134
+ z[:, d] = _subpoint_draw(zz, zhi - zlo, logw, gen, objects)
135
+ return z, np.ones(len(z), dtype=bool)
136
+
137
+
138
+ def _truncnorm(a, b, gen) -> np.ndarray:
139
+ """Standard normal draws truncated to ``[a, b]``, by the inverse CDF in log space
140
+ (intervals above zero are reflected, so tails keep their precision)."""
141
+ flip = a > 0
142
+ lo, hi = np.where(flip, -b, a), np.where(flip, -a, b)
143
+ la, lb = special.log_ndtr(lo), special.log_ndtr(hi)
144
+ u = gen.random(np.shape(lo))
145
+ with np.errstate(divide="ignore"): # u = 0 at a lower bound of -inf
146
+ x = special.ndtri_exp(lb + np.log(u + (1 - u) * np.exp(la - lb)))
147
+ x = np.clip(x, lo, hi)
148
+ return np.where(flip, -x, x)
149
+
150
+
151
+ def _draw_gauss(measures, n_sub, n_sweeps, meta, objects, labels, lo, hi, gen, height):
152
+ """Gaussian likelihoods: exact truncated draws per axis on linear axes (the hat's
153
+ height as an acceptance test), sub-points elsewhere; with a covariance, ``n_sweeps``
154
+ Gibbs sweeps over the axes' conditionals from that start (sub-points inside hats)."""
155
+ n, nd = lo.shape
156
+ mu = np.asarray(meta["gaussian_mean"])[objects]
157
+ P = None
158
+ if "gaussian_cov" in meta:
159
+ ids, inverse = np.unique(objects, return_inverse=True) # one inverse per object
160
+ C = np.asarray(meta["gaussian_cov"])[ids]
161
+ P = np.linalg.inv(C)[inverse]
162
+ sig = np.sqrt(np.diagonal(C, axis1=1, axis2=2))[inverse]
163
+ else:
164
+ sig = np.asarray(meta["gaussian_sigma"])[objects]
165
+ zlo = np.stack([m.inverse(lo[:, d]) for d, m in enumerate(measures)], axis=1)
166
+ zhi = np.stack([m.inverse(hi[:, d]) for d, m in enumerate(measures)], axis=1)
167
+ keep = np.ones(n, dtype=bool)
168
+
169
+ def axis(d, m, mu_d, sig_d, reject):
170
+ if m == Measure.linear() and (height is None or reject):
171
+ x = mu_d + sig_d * _truncnorm(
172
+ (zlo[:, d] - mu_d) / sig_d, (zhi[:, d] - mu_d) / sig_d, gen
173
+ )
174
+ if height is not None:
175
+ keep[:] &= gen.random(n) < height(labels, d, m.forward(x))
176
+ return x
177
+ zz = _subpoints(zlo[:, d], zhi[:, d], n_sub)
178
+ logw = (
179
+ _base_logw(m, zz, labels, d, height)
180
+ - 0.5 * ((zz - mu_d[:, None]) / sig_d[:, None]) ** 2
181
+ )
182
+ return _subpoint_draw(zz, zhi[:, d] - zlo[:, d], logw, gen, objects)
183
+
184
+ z = np.empty((n, nd))
185
+ for d, m in enumerate(measures):
186
+ z[:, d] = axis(d, m, mu[:, d], sig[:, d], reject=P is None)
187
+ for _ in range(n_sweeps if P is not None else 0):
188
+ for d, m in enumerate(measures):
189
+ s2 = 1.0 / P[:, d, d]
190
+ rest = np.einsum("nj,nj->n", P[:, d], z - mu) - P[:, d, d] * (z[:, d] - mu[:, d])
191
+ z[:, d] = axis(d, m, mu[:, d] - s2 * rest, np.sqrt(s2), reject=False)
192
+ return z, keep
193
+
194
+
195
+ def _draw_samples(
196
+ measures, flat, direct, row, K, key, zs, G, objects, labels, lo, hi, gen, height
197
+ ):
198
+ """An object's kept samples inside the box, drawn with their weights (``G`` their
199
+ cumulative sum, each row's summing to one; ``key`` = row * K + bin, sorted); in
200
+ a box no sample reached, flat in ``u`` as the ``floor`` is."""
201
+ n, nd = lo.shape
202
+ z, keep = np.empty((n, nd)), np.ones(n, dtype=bool)
203
+ r = row[objects]
204
+ G0 = np.concatenate(([0.0], G))
205
+ if direct: # the label is the bin each sample was counted in: one segment each
206
+ s0 = np.searchsorted(key, r * K + labels, side="left")
207
+ s1 = np.searchsorted(key, r * K + labels, side="right")
208
+ a, b = G0[s0], G0[s1]
209
+ hit = b > a # samples with weight in the bin
210
+ u = a[hit] + (1.0 - gen.random(hit.sum())) * (b - a)[hit]
211
+ z[hit] = zs[np.clip(np.searchsorted(G, u, side="left"), s0[hit], s1[hit] - 1)]
212
+ else: # components: the samples of the row inside the box, times the hat's height
213
+ hit = np.zeros(n, dtype=bool)
214
+ s0 = np.searchsorted(key, r * K, side="left")
215
+ s1 = np.searchsorted(key, (r + 1) * K, side="left")
216
+ order = np.lexsort((labels, objects))
217
+ cut = np.flatnonzero(np.diff(objects[order]) | np.diff(labels[order])) + 1
218
+ last = -1
219
+ for at in np.split(order, cut): # the draws of one object in one box
220
+ i = at[0]
221
+ seg = slice(s0[i], s1[i])
222
+ if objects[i] != last: # the object's samples in u, once for all its boxes
223
+ us = np.stack([m.forward(zs[seg, d]) for d, m in enumerate(measures)], axis=1)
224
+ last = objects[i]
225
+ w = np.diff(G0[s0[i] : s1[i] + 1]) * np.all((us >= lo[i]) & (us <= hi[i]), axis=1)
226
+ for d in range(nd if height is not None else 0):
227
+ w = w * height(labels[i], d, us[:, d])
228
+ c = np.cumsum(w)
229
+ if c.size and c[-1] > 0:
230
+ z[at] = zs[seg][np.searchsorted(c, (1.0 - gen.random(at.size)) * c[-1])]
231
+ hit[at] = True
232
+ miss = ~hit
233
+ if miss.any():
234
+ z[miss], keep[miss] = flat(objects[miss], labels[miss], lo[miss], hi[miss], gen, height)
235
+ return z, keep
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"