cosmulator 0.0.35__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 (35) hide show
  1. cosmulator-0.0.35/LICENSE +21 -0
  2. cosmulator-0.0.35/PKG-INFO +70 -0
  3. cosmulator-0.0.35/README.rst +25 -0
  4. cosmulator-0.0.35/cosmulator/__init__.py +54 -0
  5. cosmulator-0.0.35/cosmulator/_version.py +1 -0
  6. cosmulator-0.0.35/cosmulator/config.py +63 -0
  7. cosmulator-0.0.35/cosmulator/diagnostics.py +429 -0
  8. cosmulator-0.0.35/cosmulator/ensemble.py +400 -0
  9. cosmulator-0.0.35/cosmulator/fetch.py +295 -0
  10. cosmulator-0.0.35/cosmulator/hpo.py +211 -0
  11. cosmulator-0.0.35/cosmulator/maf.py +561 -0
  12. cosmulator-0.0.35/cosmulator/manifest.py +262 -0
  13. cosmulator-0.0.35/cosmulator/parameters.py +108 -0
  14. cosmulator-0.0.35/cosmulator/publish.py +386 -0
  15. cosmulator-0.0.35/cosmulator/store.py +218 -0
  16. cosmulator-0.0.35/cosmulator/validation.py +497 -0
  17. cosmulator-0.0.35/cosmulator.egg-info/PKG-INFO +70 -0
  18. cosmulator-0.0.35/cosmulator.egg-info/SOURCES.txt +33 -0
  19. cosmulator-0.0.35/cosmulator.egg-info/dependency_links.txt +1 -0
  20. cosmulator-0.0.35/cosmulator.egg-info/requires.txt +25 -0
  21. cosmulator-0.0.35/cosmulator.egg-info/top_level.txt +1 -0
  22. cosmulator-0.0.35/pyproject.toml +63 -0
  23. cosmulator-0.0.35/setup.cfg +4 -0
  24. cosmulator-0.0.35/tests/test_diagnostics.py +288 -0
  25. cosmulator-0.0.35/tests/test_ensemble.py +112 -0
  26. cosmulator-0.0.35/tests/test_fetch.py +229 -0
  27. cosmulator-0.0.35/tests/test_hpo.py +77 -0
  28. cosmulator-0.0.35/tests/test_init.py +41 -0
  29. cosmulator-0.0.35/tests/test_maf.py +170 -0
  30. cosmulator-0.0.35/tests/test_manifest.py +133 -0
  31. cosmulator-0.0.35/tests/test_packaging.py +108 -0
  32. cosmulator-0.0.35/tests/test_parameters.py +87 -0
  33. cosmulator-0.0.35/tests/test_publish.py +263 -0
  34. cosmulator-0.0.35/tests/test_store.py +178 -0
  35. cosmulator-0.0.35/tests/test_validation.py +215 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dily Duan Yi Ong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: cosmulator
3
+ Version: 0.0.35
4
+ Summary: Train, validate and serve machine-learning emulators of posterior distributions
5
+ Author-email: Dily Duan Yi Ong <dlo26@cam.ac.uk>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/DilyOng/cosmulator
8
+ Project-URL: Bug Tracker, https://github.com/DilyOng/cosmulator/issues
9
+ Project-URL: Documentation, https://cosmulator.readthedocs.io
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Topic :: Scientific/Engineering
17
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy
24
+ Requires-Dist: scipy
25
+ Requires-Dist: requests
26
+ Provides-Extra: train
27
+ Requires-Dist: jax; extra == "train"
28
+ Requires-Dist: optax; extra == "train"
29
+ Requires-Dist: flowjax; extra == "train"
30
+ Requires-Dist: equinox; extra == "train"
31
+ Provides-Extra: hpo
32
+ Requires-Dist: optuna; extra == "hpo"
33
+ Provides-Extra: docs
34
+ Requires-Dist: sphinx; extra == "docs"
35
+ Requires-Dist: sphinx_rtd_theme; extra == "docs"
36
+ Requires-Dist: numpydoc; extra == "docs"
37
+ Provides-Extra: test
38
+ Requires-Dist: pytest; extra == "test"
39
+ Requires-Dist: pytest-cov; extra == "test"
40
+ Requires-Dist: flake8; extra == "test"
41
+ Requires-Dist: pydocstyle; extra == "test"
42
+ Requires-Dist: packaging; extra == "test"
43
+ Requires-Dist: pre-commit; extra == "test"
44
+ Dynamic: license-file
45
+
46
+ =============================================================================================
47
+ cosmulator: accelerating cosmological inference with JAX machine-learning emulators on GPU
48
+ =============================================================================================
49
+
50
+ :Author: Dily Duan Yi Ong
51
+ :License: MIT
52
+ :Homepage: https://github.com/DilyOng/cosmulator
53
+
54
+ ``cosmulator`` trains JAX normalising-flow emulators of nested-sampling
55
+ posteriors on GPU, so a distribution can be resampled instantly for fast
56
+ marginalisation and Bayesian evidence, and manages the resulting emulators
57
+ (training, validation, storage and serving) across a grid of cosmological
58
+ models and surveys.
59
+
60
+ Developed under a UKRI-funded high performance computing (DiRAC) project.
61
+
62
+ Installation
63
+ ------------
64
+
65
+ .. code:: bash
66
+
67
+ pip install cosmulator # inspect and use emulators (numpy only)
68
+ pip install "cosmulator[train]" # adds the JAX training stack
69
+
70
+ Requires Python 3.11 or later.
@@ -0,0 +1,25 @@
1
+ =============================================================================================
2
+ cosmulator: accelerating cosmological inference with JAX machine-learning emulators on GPU
3
+ =============================================================================================
4
+
5
+ :Author: Dily Duan Yi Ong
6
+ :License: MIT
7
+ :Homepage: https://github.com/DilyOng/cosmulator
8
+
9
+ ``cosmulator`` trains JAX normalising-flow emulators of nested-sampling
10
+ posteriors on GPU, so a distribution can be resampled instantly for fast
11
+ marginalisation and Bayesian evidence, and manages the resulting emulators
12
+ (training, validation, storage and serving) across a grid of cosmological
13
+ models and surveys.
14
+
15
+ Developed under a UKRI-funded high performance computing (DiRAC) project.
16
+
17
+ Installation
18
+ ------------
19
+
20
+ .. code:: bash
21
+
22
+ pip install cosmulator # inspect and use emulators (numpy only)
23
+ pip install "cosmulator[train]" # adds the JAX training stack
24
+
25
+ Requires Python 3.11 or later.
@@ -0,0 +1,54 @@
1
+ """cosmulator: emulators of expensive posterior distributions.
2
+
3
+ Nested sampling and MCMC produce posterior samples at great computational
4
+ expense. ``cosmulator`` trains normalising-flow emulators of those posteriors so
5
+ that the distribution can be resampled instantly afterwards, and manages the
6
+ resulting emulators as durable, shareable artefacts.
7
+
8
+ The package is deliberately split so that using an emulator is cheap while
9
+ training one is not: the training stack is an optional extra, and nothing in the
10
+ core import path requires it.
11
+ """
12
+
13
+ from cosmulator._version import __version__
14
+ from cosmulator.diagnostics import (
15
+ effective_sample_size,
16
+ forward_kl,
17
+ moment_error,
18
+ self_consistency,
19
+ )
20
+ from cosmulator.fetch import EmulatorArchive, fetch
21
+ from cosmulator.manifest import Hyperparameters, Manifest, Provenance, Quality, Training
22
+ from cosmulator.parameters import (
23
+ BASE,
24
+ COSMO_SAMPLED,
25
+ cosmological_parameters,
26
+ parameter_names,
27
+ )
28
+ from cosmulator.store import Emulator, EmulatorStore
29
+ from cosmulator.validation import certify, marginal_gof, mmd, out_of_bounds
30
+
31
+ __all__ = [
32
+ "__version__",
33
+ "BASE",
34
+ "COSMO_SAMPLED",
35
+ "Emulator",
36
+ "EmulatorArchive",
37
+ "EmulatorStore",
38
+ "Hyperparameters",
39
+ "Manifest",
40
+ "Provenance",
41
+ "Quality",
42
+ "Training",
43
+ "certify",
44
+ "cosmological_parameters",
45
+ "effective_sample_size",
46
+ "fetch",
47
+ "forward_kl",
48
+ "marginal_gof",
49
+ "mmd",
50
+ "moment_error",
51
+ "out_of_bounds",
52
+ "parameter_names",
53
+ "self_consistency",
54
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.0.35"
@@ -0,0 +1,63 @@
1
+ """Where cosmulator looks for things on the current machine.
2
+
3
+ Paths differ between a laptop, a shared cluster and a continuous-integration
4
+ runner, and a library that hardcodes any of them can only ever run in one
5
+ place. Every location is therefore resolved here, from the environment, with a
6
+ documented default.
7
+
8
+ No credential is read here or anywhere else in the package. Tokens are passed
9
+ explicitly to the one class that needs them; see :mod:`cosmulator.publish`.
10
+ """
11
+
12
+ import os
13
+ from pathlib import Path
14
+
15
+ #: Environment variable naming the local emulator store.
16
+ STORE_ENV = "COSMULATOR_STORE"
17
+
18
+ #: Environment variable naming the download cache.
19
+ CACHE_ENV = "COSMULATOR_CACHE"
20
+
21
+ #: Environment variable naming the root of a local chain grid.
22
+ CHAINS_ENV = "COSMULATOR_CHAINS"
23
+
24
+
25
+ def store_root():
26
+ """Return the directory holding locally trained emulators.
27
+
28
+ Returns
29
+ -------
30
+ pathlib.Path
31
+ ``$COSMULATOR_STORE`` if set, otherwise ``~/.cosmulator/store``.
32
+ """
33
+ return Path(os.environ.get(STORE_ENV, Path.home() / ".cosmulator" / "store"))
34
+
35
+
36
+ def cache_root():
37
+ """Return the directory downloaded emulators are cached in.
38
+
39
+ Downloads are cached so that repeated use of an emulator costs one network
40
+ round trip rather than one per call.
41
+
42
+ Returns
43
+ -------
44
+ pathlib.Path
45
+ ``$COSMULATOR_CACHE`` if set, otherwise ``~/.cosmulator/cache``.
46
+ """
47
+ return Path(os.environ.get(CACHE_ENV, Path.home() / ".cosmulator" / "cache"))
48
+
49
+
50
+ def chains_root():
51
+ """Return the root of a local grid of posterior chains, if configured.
52
+
53
+ Only training needs this; consuming a published emulator does not, which is
54
+ why there is no default. A machine that has never trained anything should
55
+ not be asked to invent a plausible path.
56
+
57
+ Returns
58
+ -------
59
+ pathlib.Path or None
60
+ ``$COSMULATOR_CHAINS`` if set, otherwise None.
61
+ """
62
+ value = os.environ.get(CHAINS_ENV)
63
+ return Path(value) if value else None
@@ -0,0 +1,429 @@
1
+ """Measures of how faithfully an emulator reproduces its target.
2
+
3
+ A trained flow always produces samples. Whether those samples are the posterior
4
+ is a separate question, and one that is easy not to ask: an emulator that is
5
+ subtly over-dispersed looks entirely healthy until its output is used for
6
+ inference. These diagnostics exist so that every emulator carries evidence of
7
+ its own fidelity, and so that a bad one can be identified automatically rather
8
+ than by eye.
9
+
10
+ The functions here operate on plain arrays of samples. They neither train nor
11
+ load models, and so require no JAX; given samples from an emulator and samples
12
+ from its target, any of them can be computed on a laptop.
13
+ """
14
+
15
+ import numpy as np
16
+
17
+
18
+ def _normalised_weights(weights, size):
19
+ """Return finite, normalised weights, defaulting to uniform.
20
+
21
+ Parameters
22
+ ----------
23
+ weights : array_like or None
24
+ Per-sample weights, or None for uniform weighting.
25
+ size : int
26
+ Number of samples the weights must cover.
27
+
28
+ Returns
29
+ -------
30
+ numpy.ndarray
31
+ Weights summing to one.
32
+
33
+ Raises
34
+ ------
35
+ ValueError
36
+ If the weights do not match the samples, or sum to zero.
37
+ """
38
+ if weights is None:
39
+ return np.full(size, 1.0 / size)
40
+ weights = np.asarray(weights, dtype=float)
41
+ if weights.shape != (size,):
42
+ raise ValueError(f"weights have shape {weights.shape}, expected ({size},)")
43
+ total = weights.sum()
44
+ if not np.isfinite(total) or total <= 0:
45
+ raise ValueError("weights must be finite and sum to a positive value")
46
+ return weights / total
47
+
48
+
49
+ def self_consistency(log_prob_at_target, log_prob_at_emulated, weights=None):
50
+ r"""Compare the emulator's density at its own samples and at the target's.
51
+
52
+ For a flow :math:`q` approximating a posterior :math:`P`, the quantity
53
+
54
+ .. math::
55
+ \Delta\log p = E_q[\log q] - E_P[\log q]
56
+
57
+ vanishes when the two distributions agree. It is cheap, needs only the
58
+ flow's own density, and is signed: a negative value indicates the emulator
59
+ spreads probability more widely than the target, which is the failure mode
60
+ that flatters an emulator by making it look conservative.
61
+
62
+ Parameters
63
+ ----------
64
+ log_prob_at_target : array_like
65
+ The emulator's log density evaluated at samples from the target.
66
+ log_prob_at_emulated : array_like
67
+ The emulator's log density evaluated at its own samples.
68
+ weights : array_like, optional
69
+ Weights for the target samples. Nested sampling output is weighted, and
70
+ ignoring that biases the comparison.
71
+
72
+ Returns
73
+ -------
74
+ dict
75
+ ``dlogp`` and its absolute value, plus the two expectations that formed
76
+ it, so that a surprising result can be diagnosed without recomputing.
77
+
78
+ Notes
79
+ -----
80
+ Non-finite densities are dropped before averaging. A flow evaluated far
81
+ into the tails can legitimately return ``-inf``, and discarding those
82
+ points is preferable to propagating a NaN through the whole metric.
83
+ """
84
+ at_target = np.asarray(log_prob_at_target, dtype=float)
85
+ at_emulated = np.asarray(log_prob_at_emulated, dtype=float)
86
+
87
+ w = _normalised_weights(weights, at_target.size)
88
+ finite = np.isfinite(at_target)
89
+ if not finite.any():
90
+ raise ValueError("no finite log densities at the target samples")
91
+ e_target = float(np.sum(w[finite] * at_target[finite]) / np.sum(w[finite]))
92
+
93
+ finite_emulated = np.isfinite(at_emulated)
94
+ if not finite_emulated.any():
95
+ raise ValueError("no finite log densities at the emulated samples")
96
+ e_emulated = float(np.mean(at_emulated[finite_emulated]))
97
+
98
+ dlogp = e_emulated - e_target
99
+ return {
100
+ "dlogp": dlogp,
101
+ "abs_dlogp": abs(dlogp),
102
+ "E_q_logq": e_emulated,
103
+ "E_P_logq": e_target,
104
+ }
105
+
106
+
107
+ def forward_kl(log_prob_at_target, target_samples, weights=None):
108
+ r"""Forward Kullback--Leibler divergence from the target to the emulator.
109
+
110
+ For a target posterior :math:`P` and an emulator :math:`q`,
111
+
112
+ .. math::
113
+ D_{\mathrm{KL}}(P\,\|\,q) = -H(P) - E_P[\log q]
114
+ = H(P, q) - H(P),
115
+
116
+ reported in nats. Unlike :func:`self_consistency`, this is a genuine
117
+ divergence: it is non-negative, zero only when the emulator equals the
118
+ target, and it *cannot* be made small by over-dispersion. That makes it the
119
+ metric to minimise when tuning an emulator; the signed self-consistency
120
+ :math:`\Delta\log p` can be driven towards zero by an over-broad flow, and
121
+ so rewards the very failure it is meant to catch.
122
+
123
+ The cross-entropy :math:`H(P, q) = -E_P[\log q]` is computed exactly from
124
+ the flow's own density at the target samples. The entropy :math:`H(P)` is
125
+ not available for a nuisance-marginalised posterior, so it is estimated by
126
+ the Gaussian entropy of the target's covariance,
127
+ :math:`\tfrac12\ln[(2\pi e)^d \det\Sigma]`. Because a Gaussian has the
128
+ largest entropy of any distribution with a given covariance, this
129
+ *overestimates* :math:`H(P)`, so **when the emulator has finite density at
130
+ every target sample** the returned value is a **lower bound** on the true
131
+ forward KL --- tight when the target is close to Gaussian, as marginal
132
+ cosmological posteriors usually are. Where the emulator's density underflows
133
+ at some target samples those points are floored (see Notes) rather than
134
+ dropped, and the fraction of target weight affected is returned as
135
+ ``missed_mass_frac`` so the failure is visible without distorting the score.
136
+
137
+ Parameters
138
+ ----------
139
+ log_prob_at_target : array_like, shape (n,)
140
+ The emulator's log density evaluated at the ``n`` target samples.
141
+ target_samples : array_like, shape (n, d)
142
+ The target samples themselves, used for the covariance in :math:`H(P)`.
143
+ weights : array_like, optional
144
+ Weights for the target samples. Nested sampling output is weighted, and
145
+ ignoring that biases both the cross-entropy and the covariance.
146
+
147
+ Returns
148
+ -------
149
+ dict
150
+ ``forward_kl`` (the lower bound, in nats), the ``cross_entropy`` and
151
+ ``entropy_gaussian`` terms that formed it, and ``missed_mass_frac`` --
152
+ the fraction of target weight at which the emulator's density
153
+ underflowed -- so a value can be diagnosed without recomputing.
154
+
155
+ Raises
156
+ ------
157
+ ValueError
158
+ If the densities and samples disagree in length, the target covariance
159
+ is not positive definite, or no target sample has finite density.
160
+
161
+ Notes
162
+ -----
163
+ Non-finite densities are **floored, not dropped, and not given an unphysical
164
+ penalty**. A normalising flow with a Gaussian base has infinite support and
165
+ never assigns true-zero density, so a ``-inf`` at a target sample is
166
+ numerical underflow in the far tail, not a genuinely missed mode. Dropping
167
+ such points, as :func:`self_consistency` does for its symmetric quantity,
168
+ would flatter a mode-collapsed flow; but assigning a huge fixed penalty
169
+ (e.g. ``-1e6``) is equally wrong -- a fraction of a percent of tail weight
170
+ then contributes hundreds of nats and swamps the real signal, leaving the
171
+ score flat and useless for optimisation. Instead each underflowed density is
172
+ floored 50 nats below the *median* finite log density. The median tracks the
173
+ bulk scale (so the floor adapts to dimension) and, unlike the raw minimum, is
174
+ immune to numerical-outlier finite values -- a flow on a degenerate posterior
175
+ can return finite garbage such as ``-1e33`` at an outlier, and flooring at the
176
+ minimum would adopt it and inflate the divergence to ``~1e30``. Any such
177
+ absurd finite value is clipped to the floor as well. The floor is bounded, so
178
+ a benign tail underflow (tiny weight) is negligible, while a genuinely missed
179
+ mode (high weight underflowing) is still penalised in proportion to its
180
+ weight -- and ``missed_mass_frac`` reports the fraction regardless, so mode
181
+ collapse is never hidden.
182
+ """
183
+ at_target = np.asarray(log_prob_at_target, dtype=float)
184
+ samples = np.atleast_2d(np.asarray(target_samples, dtype=float))
185
+ n, d = samples.shape
186
+ if at_target.shape != (n,):
187
+ raise ValueError(
188
+ f"log densities have shape {at_target.shape}, expected ({n},) "
189
+ f"to match the target samples"
190
+ )
191
+
192
+ w = _normalised_weights(weights, n)
193
+ # Floor, rather than drop, a non-finite log density, so a genuinely missed mode
194
+ # is still penalised in proportion to its weight, but a flow with infinite
195
+ # support (whose -inf is mere numerical underflow in the far tail) is not
196
+ # assigned an unphysical, signal-swamping penalty. The floor is the least-likely
197
+ # *finite* density the emulator can evaluate here; a benign tail underflow then
198
+ # carries negligible weight, while a high-weight miss carries a large one. The
199
+ # fraction of target weight that underflowed is returned as ``missed_mass_frac``.
200
+ finite = np.isfinite(at_target)
201
+ if not finite.any():
202
+ raise ValueError("no finite log densities at the target samples")
203
+ # Floor 50 nats below the MEDIAN finite log density. The median tracks the bulk
204
+ # density scale (so the floor adapts to dimension) and, unlike the raw minimum,
205
+ # is immune to numerical-outlier finite values -- a flow on a degenerate
206
+ # posterior can return finite garbage (e.g. -1e33) at an outlier, and flooring
207
+ # at the minimum would adopt it and blow the divergence up to ~1e30. Clip both
208
+ # non-finite densities and any absurdly-negative finite value to this floor.
209
+ floor = float(np.median(at_target[finite]) - 50.0)
210
+ floored = np.where(finite & (at_target > floor), at_target, floor)
211
+ missed_mass = float(w[~finite].sum())
212
+ cross_entropy = -float(np.sum(w * floored))
213
+
214
+ mean = w @ samples
215
+ centred = samples - mean
216
+ cov = (centred * w[:, None]).T @ centred
217
+ sign, logdet = np.linalg.slogdet(cov)
218
+ if sign <= 0:
219
+ raise ValueError("target covariance is not positive definite")
220
+ entropy_gaussian = 0.5 * (d * (1.0 + np.log(2.0 * np.pi)) + logdet)
221
+
222
+ return {
223
+ "forward_kl": float(cross_entropy - entropy_gaussian),
224
+ "cross_entropy": float(cross_entropy),
225
+ "entropy_gaussian": float(entropy_gaussian),
226
+ "missed_mass_frac": missed_mass,
227
+ }
228
+
229
+
230
+ def moment_error(target_samples, emulated_samples, weights=None):
231
+ """Compare the first two moments of the target and the emulator.
232
+
233
+ Reported per parameter and averaged. Where
234
+ :func:`self_consistency` gives one number for the whole distribution, this
235
+ says which parameters are wrong and in what way, which is what a user needs
236
+ in order to act on a poor score.
237
+
238
+ Parameters
239
+ ----------
240
+ target_samples : array_like, shape (n, d)
241
+ Samples from the target distribution.
242
+ emulated_samples : array_like, shape (m, d)
243
+ Samples drawn from the emulator. Need not match ``n``.
244
+ weights : array_like, optional
245
+ Weights for the target samples.
246
+
247
+ Returns
248
+ -------
249
+ dict
250
+ Per-parameter ``bias_sigma`` and ``width_error_pct`` arrays, and their
251
+ mean absolute values. Bias is expressed in units of the target's own
252
+ standard deviation so that parameters with different scales can be
253
+ compared and a single tolerance applied across them.
254
+
255
+ Raises
256
+ ------
257
+ ValueError
258
+ If the two sample sets have different dimensionality, or a target
259
+ parameter has zero spread.
260
+ """
261
+ target = np.atleast_2d(np.asarray(target_samples, dtype=float))
262
+ emulated = np.atleast_2d(np.asarray(emulated_samples, dtype=float))
263
+ if target.shape[1] != emulated.shape[1]:
264
+ raise ValueError(
265
+ f"dimension mismatch: target has {target.shape[1]} parameters, "
266
+ f"emulated has {emulated.shape[1]}"
267
+ )
268
+
269
+ w = _normalised_weights(weights, target.shape[0])
270
+ target_mean = w @ target
271
+ target_std = np.sqrt(w @ (target - target_mean) ** 2)
272
+ # A constant parameter yields a standard deviation of order machine epsilon
273
+ # rather than exactly zero, so an absolute test against zero passes and the
274
+ # bias below divides by ~1e-16. Compare against the parameter's own scale.
275
+ scale = np.maximum(np.abs(target_mean), 1.0)
276
+ if not np.all(target_std > 1e-12 * scale):
277
+ raise ValueError(
278
+ "a target parameter has zero spread; cannot express bias in "
279
+ "units of its standard deviation"
280
+ )
281
+
282
+ bias = (emulated.mean(axis=0) - target_mean) / target_std
283
+ width = 100.0 * (emulated.std(axis=0) - target_std) / target_std
284
+ return {
285
+ "bias_sigma": bias.tolist(),
286
+ "width_error_pct": width.tolist(),
287
+ "mean_abs_bias_sigma": float(np.mean(np.abs(bias))),
288
+ "mean_abs_width_err_pct": float(np.mean(np.abs(width))),
289
+ }
290
+
291
+
292
+ def equal_weight_resample(samples, weights, size=None, seed=0):
293
+ """Systematic (low-variance) resample of a weighted set to equal weights.
294
+
295
+ The k-NN KL estimator wants unit-weight draws from the posterior, not the
296
+ weighted nested-sampling points. Systematic resampling picks one point per
297
+ equal-mass stratum of the CDF, so it reproduces the weighted distribution
298
+ with far less noise than i.i.d. multinomial resampling.
299
+
300
+ Parameters
301
+ ----------
302
+ samples : array_like, shape (n, d)
303
+ Weighted samples.
304
+ weights : array_like, shape (n,)
305
+ Non-negative weights (need not be normalised).
306
+ size : int, optional
307
+ Number of equal-weight samples to return. Defaults to the effective
308
+ sample size (rounded), which is the honest amount of independent
309
+ information the weighted set carries.
310
+ seed : int
311
+ Seed for the single random offset.
312
+
313
+ Returns
314
+ -------
315
+ numpy.ndarray, shape (size, d)
316
+ Unit-weight samples.
317
+ """
318
+ samples = np.atleast_2d(np.asarray(samples, dtype=float))
319
+ w = np.asarray(weights, dtype=float)
320
+ w = np.where(np.isfinite(w) & (w > 0), w, 0.0)
321
+ cdf = np.cumsum(w)
322
+ cdf /= cdf[-1]
323
+ if size is None:
324
+ size = int(round(effective_sample_size(w)))
325
+ size = max(int(size), 1)
326
+ u = (np.random.default_rng(seed).random() + np.arange(size)) / size
327
+ idx = np.searchsorted(cdf, u)
328
+ idx = np.clip(idx, 0, len(samples) - 1)
329
+ return samples[idx]
330
+
331
+
332
+ def knn_kl_divergence(p_samples, q_samples, k=5, standardise=True, eps=1e-12):
333
+ r"""k-nearest-neighbour estimate of ``D_KL(P || Q)`` from two sample sets.
334
+
335
+ This is the honest headline measure of emulator accuracy: the divergence
336
+ between the *true* marginal posterior samples ``P`` and the *emulated*
337
+ samples ``Q``, computed directly in the parameter space of interest (e.g. the
338
+ six cosmological parameters), with no nuisances and no prior-volume term. It
339
+ is the two-sample Wang--Kulkarni--Verdu / Perez-Cruz estimator
340
+
341
+ .. math::
342
+ \hat D_{KL}(P\|Q) = \frac{d}{n}\sum_{i=1}^{n}
343
+ \log\frac{\nu_k(i)}{\rho_k(i)} + \log\frac{m}{n-1},
344
+
345
+ where ``rho_k(i)`` is the distance from ``P_i`` to its ``k``-th neighbour
346
+ within ``P`` (excluding itself) and ``nu_k(i)`` the distance to its ``k``-th
347
+ neighbour in ``Q``. The two hard-boundary biases that wreck a
348
+ single-sample entropy estimate cancel here, because ``P`` and ``Q`` share the
349
+ same bounded support. A perfect emulator gives an estimate near zero (small
350
+ negative values are ordinary estimator noise when ``P`` and ``Q`` match).
351
+
352
+ Unlike anesthetic's nested-sampling ``D_KL`` (the thermodynamic information
353
+ gain against the prior over *all* sampled dimensions, nuisances included),
354
+ this does not conflate the model's information content with the emulator's
355
+ fidelity.
356
+
357
+ Parameters
358
+ ----------
359
+ p_samples : array_like, shape (n, d)
360
+ Equal-weight samples from the true distribution ``P`` (see
361
+ :func:`equal_weight_resample`).
362
+ q_samples : array_like, shape (m, d)
363
+ Equal-weight samples from the emulator ``Q``.
364
+ k : int
365
+ Neighbour rank. Larger ``k`` lowers variance at some bias cost; the
366
+ bias-correction terms cancel between the two sets for a shared ``k``.
367
+ standardise : bool
368
+ Standardise both sets by ``P``'s mean and standard deviation before the
369
+ neighbour search. KL is invariant under this shared affine map, but the
370
+ estimator is better behaved when distances are isotropic.
371
+ eps : float
372
+ Floor on neighbour distances, to avoid ``log 0`` from duplicate points.
373
+
374
+ Returns
375
+ -------
376
+ float
377
+ The estimated ``D_KL(P || Q)`` in nats.
378
+ """
379
+ from scipy.spatial import cKDTree
380
+
381
+ P = np.atleast_2d(np.asarray(p_samples, dtype=float))
382
+ Q = np.atleast_2d(np.asarray(q_samples, dtype=float))
383
+ n, d = P.shape
384
+ m, dq = Q.shape
385
+ if d != dq:
386
+ raise ValueError(f"dimensionality mismatch: P has {d}, Q has {dq}")
387
+ if n <= k or m < k:
388
+ raise ValueError(f"need more than k={k} samples in each set (n={n}, m={m})")
389
+
390
+ if standardise:
391
+ mu = P.mean(axis=0)
392
+ sd = P.std(axis=0)
393
+ sd = np.where(sd > 0, sd, 1.0)
394
+ P = (P - mu) / sd
395
+ Q = (Q - mu) / sd
396
+
397
+ # rho: k-th neighbour within P (query k+1, drop the self match at rank 0)
398
+ rho = cKDTree(P).query(P, k=k + 1)[0][:, k]
399
+ # nu: k-th neighbour of each P_i in Q
400
+ nu = cKDTree(Q).query(P, k=k)[0]
401
+ nu = nu[:, k - 1] if k > 1 else nu
402
+ rho = np.maximum(rho, eps)
403
+ nu = np.maximum(nu, eps)
404
+ return float(d * np.mean(np.log(nu / rho)) + np.log(m / (n - 1.0)))
405
+
406
+
407
+ def effective_sample_size(weights):
408
+ r"""Return the effective number of independent samples in a weighted set.
409
+
410
+ Nested sampling chains carry many points of negligible weight, so the
411
+ nominal length of a chain badly overstates how much the flow can learn
412
+ from it. This is the number that matters when deciding whether a chain is
413
+ worth training on.
414
+
415
+ Parameters
416
+ ----------
417
+ weights : array_like
418
+ Per-sample weights. Need not be normalised.
419
+
420
+ Returns
421
+ -------
422
+ float
423
+ Kish's effective sample size, :math:`(\sum w)^2 / \sum w^2`.
424
+ """
425
+ w = np.asarray(weights, dtype=float)
426
+ w = w[np.isfinite(w) & (w > 0)]
427
+ if w.size == 0:
428
+ return 0.0
429
+ return float(w.sum() ** 2 / np.square(w).sum())