Random number generation
Random number generation in bilby uses a global numpy Generator
object in bilby.core.utils.random. The recommended usage is
>>> from bilby.core.utils import random
>>> x = random.rng.uniform()
where rng is a numpy random generator. For more details about
numpy random generators, see the
numpy documentation.
Warning
The rng object should not be imported directly as it will not be seeded
by calls to bilby.core.utils.random.seed().
The random number generation can be seeded using the
bilby.core.utils.random.seed() function:
>>> from bilby.core.utils import random
>>> random.seed(1234)
For more fine-grained control, every function/method that relies on random number
generation supports a random_state argument that can be used to specify
the random number generator to use for that function/method.
Seeding samplers
The different samplers in bilby have different ways of seeding the random number
generator that depend on each sampler’s implementation. As such, seeding the bilby
random number generator with bilby.core.utils.random.seed() does not guarantee that the
sampler will be seeded.
If the interface for a sampler supports seeding, then specifying either the specific
keyword argument or an equivalent argument (seed, sampling_seed or random_seed
will be automatically translated to the appropriate keyword argument)
when calling run_sampler() will seed the sampler’s random number generator.
For example:
>>> import bilby
>>> likelihood = ...
>>> prior = ...
>>> bilby.run_sampler(
likelihood=likelihood,
prior=prior,
sampler="dynesty",
seed=1234,
)
Note
Some sampler interfaces do not support seeding.
Random number generation and non-NumpPy backends
To support random number generation with non-NumPy array backends,
any bilby function or method that supports random number generation and accepts a
random_state argument.
This argument should be one of the following types:
None(the default): the function will use thebilbyglobalnumpyrandom number generator (set usingbilby.core.random.seed).numpy.random.Generator: the function will use the provided generator.orng.RandomGenerator: the function will use the providedorngrandom number generator.int: the function will create a newnumpyrandom number generator seeded with the provided integer and use it for random number generation.jax.random.key: the function will create a neworngrandom number generator with the “jax” backend seeded with the provided key and use it for random number generation.
For example,
>>> import orng
>>> rng = orng.RandomGenerator("jax", seed=1234)
>>> x = rng.uniform()
>>> priors.sample(xp=jnp, rng=rng)