seed

Contents

seed#

class brainstate.random.seed(seed_or_key=None)#

Set the global random seed for both JAX and NumPy.

This function initializes the global random state with a new seed, affecting both JAX and NumPy random number generators. It ensures reproducible random number generation across the entire BrainState ecosystem.

Parameters:

seed_or_key (int | Array | ndarray) – The seed or key to set. Can be: - None: Generates a random seed automatically - int: An integer seed (0 to 2^32-1) - JAX PRNG key: A JAX random key array If None, a random seed is generated using NumPy’s random generator.

Raises:

ValueError – If seed_or_key is not a valid seed format (not an integer, valid JAX key, or None).

Example

Set a specific seed for reproducible results:

>>> import brainstate
>>> brainstate.random.seed(42)
>>> values1 = brainstate.random.rand(3)
>>> brainstate.random.seed(42)  # Reset to same seed
>>> values2 = brainstate.random.rand(3)
>>> assert np.allclose(values1, values2)  # Same values

Use automatic random seeding:

>>> brainstate.random.seed()  # Uses random seed
>>> # Each call will produce different sequences

Use with JAX keys:

>>> import jax
>>> key = jax.random.key(123)
>>> brainstate.random.seed(key)
>>> # Now both JAX and NumPy use consistent seeds

Ensure reproducibility in scientific experiments:

>>> def experiment():
...     brainstate.random.seed(12345)  # Fixed seed for reproducibility
...     data = brainstate.random.normal(size=(100, 10))
...     return data.mean()
>>> result1 = experiment()
>>> result2 = experiment()
>>> assert result1 == result2  # Always same result

Note

  • This function affects the global random state used by all BrainState random functions and NumPy’s global random state.

  • When using automatic seeding (seed_or_key=None), NumPy’s seed is not set to maintain its current state.

  • JAX compilation is handled automatically with compile-time evaluation.

  • For JAX keys, only the first element is used to seed NumPy to maintain compatibility between the two random systems.

See also