Skip to content

rnd_utils

Random number utilities for seeding, sampling, and random string generation.

This module provides functions to compute deterministic seeds from arbitrary values, seed numpy/random jointly, weighted random choices, shuffling, uniform jittering, and cryptographically-random string generation.

compute_seed(seed)

Compute a deterministic 32-bit CRC seed from an arbitrary value.

Parameters:

Name Type Description Default
seed

An int, float, bytes, str, or other hashable value.

required

Returns:

Type Description

A 32-bit unsigned integer seed derived via CRC32.

Example
rnd_utils.compute_seed(42) == rnd_utils.compute_seed(42)  # True
isinstance(rnd_utils.compute_seed('hello'), int)  # True
Source code in py_misc_utils/rnd_utils.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def compute_seed(seed):
  """Compute a deterministic 32-bit CRC seed from an arbitrary value.

  Args:
    seed: An int, float, bytes, str, or other hashable value.

  Returns:
    A 32-bit unsigned integer seed derived via CRC32.

  Example:
    rnd_utils.compute_seed(42) == rnd_utils.compute_seed(42)  # True
    isinstance(rnd_utils.compute_seed('hello'), int)  # True
  """
  if isinstance(seed, int):
    seed = binascii.crc32(struct.pack('=q', seed))
  elif isinstance(seed, float):
    seed = binascii.crc32(struct.pack('=d', seed))
  elif isinstance(seed, bytes):
    seed = binascii.crc32(seed)
  elif isinstance(seed, str):
    seed = binascii.crc32(seed.encode())
  else:
    seed = binascii.crc32(struct.pack('=Q', hash(seed) & 0xFFFFFFFFFFFFFFFF))

  return seed

manual_seed(seed)

Seed both numpy and random with a deterministic seed derived from seed.

Parameters:

Name Type Description Default
seed

An int, float, bytes, str, or other hashable value.

required

Returns:

Type Description

The computed 32-bit seed actually used.

Example
rnd_utils.manual_seed('abc')  # Seeds np.random and random, returns the seed.
Source code in py_misc_utils/rnd_utils.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def manual_seed(seed):
  """Seed both numpy and random with a deterministic seed derived from seed.

  Args:
    seed: An int, float, bytes, str, or other hashable value.

  Returns:
    The computed 32-bit seed actually used.

  Example:
    rnd_utils.manual_seed('abc')  # Seeds np.random and random, returns the seed.
  """
  cseed = compute_seed(seed)

  np.random.seed(cseed)
  random.seed(cseed)

  return cseed

choices(weights, n)

Randomly select n indices weighted by the given weights.

Parameters:

Name Type Description Default
weights

A list of relative weights, one per index.

required
n

The number of selections to make.

required

Returns:

Type Description

A list of n selected indices.

Example
rnd_utils.manual_seed(0)
rnd_utils.choices([1, 2, 3], 5)  # e.g. [2, 2, 0, 2, 2]
Source code in py_misc_utils/rnd_utils.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def choices(weights, n):
  """Randomly select n indices weighted by the given weights.

  Args:
    weights: A list of relative weights, one per index.
    n: The number of selections to make.

  Returns:
    A list of n selected indices.

  Example:
    rnd_utils.manual_seed(0)
    rnd_utils.choices([1, 2, 3], 5)  # e.g. [2, 2, 0, 2, 2]
  """
  return random.choices(range(len(weights)), weights=weights, k=n)

shuffle(args)

Return a new shuffled copy of args using random.sample.

Parameters:

Name Type Description Default
args

A sequence of items to shuffle.

required

Returns:

Type Description

A new list with the same items in random order.

Example
rnd_utils.manual_seed(7)
rnd_utils.shuffle([1, 2, 3, 4, 5])  # e.g. [3, 5, 2, 1, 4]
Source code in py_misc_utils/rnd_utils.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def shuffle(args):
  """Return a new shuffled copy of args using random.sample.

  Args:
    args: A sequence of items to shuffle.

  Returns:
    A new list with the same items in random order.

  Example:
    rnd_utils.manual_seed(7)
    rnd_utils.shuffle([1, 2, 3, 4, 5])  # e.g. [3, 5, 2, 1, 4]
  """
  return random.sample(args, k=len(args))

uniform(center, delta=None, pct=None)

Generate a random float uniformly distributed around center.

Exactly one of delta or pct must be provided.

Parameters:

Name Type Description Default
center

The center value of the distribution.

required
delta

Absolute half-width of the distribution.

None
pct

Percentage of center used as delta (overrides delta if given).

None

Returns:

Type Description

A random float in [center - delta, center + delta].

Raises:

Type Description
AssertionError

When neither delta nor pct is provided.

Example
rnd_utils.uniform(10, delta=2)  # A float in [8.0, 12.0].
rnd_utils.uniform(10, pct=0.1)  # A float in [9.0, 11.0].
Source code in py_misc_utils/rnd_utils.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def uniform(center, delta=None, pct=None):
  """Generate a random float uniformly distributed around center.

  Exactly one of delta or pct must be provided.

  Args:
    center: The center value of the distribution.
    delta: Absolute half-width of the distribution.
    pct: Percentage of center used as delta (overrides delta if given).

  Returns:
    A random float in [center - delta, center + delta].

  Raises:
    AssertionError: When neither delta nor pct is provided.

  Example:
    rnd_utils.uniform(10, delta=2)  # A float in [8.0, 12.0].
    rnd_utils.uniform(10, pct=0.1)  # A float in [9.0, 11.0].
  """
  if pct is not None:
    delta = abs(center * pct)

  tas.check_is_not_none(delta, msg='Either delta or pct must be provided')

  return random.uniform(center - delta, center + delta)

rand_string(n)

Generate a cryptographically-random alphanumeric string.

Parameters:

Name Type Description Default
n

The length of the string to generate.

required

Returns:

Type Description

A string of n lowercase letters and digits.

Example
len(rnd_utils.rand_string(8))  # 8
Source code in py_misc_utils/rnd_utils.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def rand_string(n):
  """Generate a cryptographically-random alphanumeric string.

  Args:
    n: The length of the string to generate.

  Returns:
    A string of n lowercase letters and digits.

  Example:
    len(rnd_utils.rand_string(8))  # 8
  """
  rng = random.SystemRandom()

  return ''.join(rng.choices(string.ascii_lowercase + string.digits, k=n))