util_random.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. """Helpers for random number generators."""
  3. import numpy as np
  4. def ensure_rng(rng=None):
  5. """Coerces input into a random number generator.
  6. If the input is None, then a global random state is returned.
  7. If the input is a numeric value, then that is used as a seed to construct a
  8. random state. Otherwise the input is returned as-is.
  9. Adapted from [1]_.
  10. Args:
  11. rng (int | numpy.random.RandomState | None):
  12. if None, then defaults to the global rng. Otherwise this can be an
  13. integer or a RandomState class
  14. Returns:
  15. (numpy.random.RandomState) : rng -
  16. a numpy random number generator
  17. References:
  18. .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501
  19. """
  20. if rng is None:
  21. rng = np.random.mtrand._rand
  22. elif isinstance(rng, int):
  23. rng = np.random.RandomState(rng)
  24. else:
  25. rng = rng
  26. return rng