Coverage for gemlib/abc/abc_rejection_sampler.py: 100%
16 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 19:54 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 19:54 +0000
1from collections.abc import Callable
2from typing import TypeVar
4import jax
5import tensorflow_probability.substrates.jax as tfp
7tfd = tfp.distributions
8Array = jax.Array
9PyTree = TypeVar("PyTree")
11__all__ = ["abc_rejection_sampler"]
14def abc_rejection_sampler(
15 accept_fn: Callable[[PyTree], Array],
16 num_samples: int,
17 model: tfd.JointDistribution,
18 key: Array,
19) -> tuple[PyTree, float]:
20 """Approximate Bayesian Computation rejection sampler
22 Args:
23 accept_fn: Python callable which takes a batch of samples from `model`
24 and returns a boolean array of shape `num_samples` to keep.
25 Any tolerance/threshold logic is responsibility of `accept_fn`.
26 num_samples: total number of samples
27 model: a `tfd.JointDistribution` to draw proposal from
28 key: a PRNG key
30 Returns:
31 A tuple of (posterior, acceptance_rate).
32 """
34 @jax.jit
35 def fn(key):
36 samples = model.sample(sample_shape=num_samples, seed=key)
37 keep = accept_fn(samples)
39 return samples, keep
41 samples, accept = fn(key)
43 return jax.tree.map(lambda x: x[accept], samples), accept.mean()