brainstate 0.1.10__py2.py3-none-any.whl → 0.2.1__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. brainstate/__init__.py +169 -58
  2. brainstate/_compatible_import.py +340 -148
  3. brainstate/_compatible_import_test.py +681 -0
  4. brainstate/_deprecation.py +210 -0
  5. brainstate/_deprecation_test.py +2319 -0
  6. brainstate/{util/error.py → _error.py} +45 -55
  7. brainstate/_state.py +1652 -1605
  8. brainstate/_state_test.py +52 -52
  9. brainstate/_utils.py +47 -47
  10. brainstate/environ.py +1495 -563
  11. brainstate/environ_test.py +1223 -62
  12. brainstate/graph/__init__.py +22 -29
  13. brainstate/graph/_node.py +240 -0
  14. brainstate/graph/_node_test.py +589 -0
  15. brainstate/graph/{_graph_operation.py → _operation.py} +1624 -1738
  16. brainstate/graph/_operation_test.py +1147 -0
  17. brainstate/mixin.py +1433 -365
  18. brainstate/mixin_test.py +1017 -77
  19. brainstate/nn/__init__.py +137 -135
  20. brainstate/nn/_activations.py +1100 -808
  21. brainstate/nn/_activations_test.py +354 -331
  22. brainstate/nn/_collective_ops.py +633 -514
  23. brainstate/nn/_collective_ops_test.py +774 -43
  24. brainstate/nn/_common.py +226 -178
  25. brainstate/nn/_common_test.py +154 -0
  26. brainstate/nn/_conv.py +2010 -501
  27. brainstate/nn/_conv_test.py +849 -238
  28. brainstate/nn/_delay.py +575 -588
  29. brainstate/nn/_delay_test.py +243 -238
  30. brainstate/nn/_dropout.py +618 -426
  31. brainstate/nn/_dropout_test.py +477 -100
  32. brainstate/nn/_dynamics.py +1267 -1343
  33. brainstate/nn/_dynamics_test.py +67 -78
  34. brainstate/nn/_elementwise.py +1298 -1119
  35. brainstate/nn/_elementwise_test.py +830 -169
  36. brainstate/nn/_embedding.py +408 -58
  37. brainstate/nn/_embedding_test.py +156 -0
  38. brainstate/nn/{_fixedprob.py → _event_fixedprob.py} +233 -239
  39. brainstate/nn/{_fixedprob_test.py → _event_fixedprob_test.py} +115 -114
  40. brainstate/nn/{_linear_mv.py → _event_linear.py} +83 -83
  41. brainstate/nn/{_linear_mv_test.py → _event_linear_test.py} +121 -120
  42. brainstate/nn/_exp_euler.py +254 -92
  43. brainstate/nn/_exp_euler_test.py +377 -35
  44. brainstate/nn/_linear.py +744 -424
  45. brainstate/nn/_linear_test.py +475 -107
  46. brainstate/nn/_metrics.py +1070 -0
  47. brainstate/nn/_metrics_test.py +611 -0
  48. brainstate/nn/_module.py +384 -377
  49. brainstate/nn/_module_test.py +40 -40
  50. brainstate/nn/_normalizations.py +1334 -975
  51. brainstate/nn/_normalizations_test.py +699 -73
  52. brainstate/nn/_paddings.py +1020 -0
  53. brainstate/nn/_paddings_test.py +723 -0
  54. brainstate/nn/_poolings.py +2239 -1177
  55. brainstate/nn/_poolings_test.py +953 -217
  56. brainstate/nn/{_rate_rnns.py → _rnns.py} +946 -554
  57. brainstate/nn/_rnns_test.py +593 -0
  58. brainstate/nn/_utils.py +216 -89
  59. brainstate/nn/_utils_test.py +402 -0
  60. brainstate/{init/_random_inits.py → nn/init.py} +809 -553
  61. brainstate/{init/_random_inits_test.py → nn/init_test.py} +180 -149
  62. brainstate/random/__init__.py +270 -24
  63. brainstate/random/_rand_funs.py +3938 -3616
  64. brainstate/random/_rand_funs_test.py +640 -567
  65. brainstate/random/_rand_seed.py +675 -210
  66. brainstate/random/_rand_seed_test.py +48 -48
  67. brainstate/random/_rand_state.py +1617 -1409
  68. brainstate/random/_rand_state_test.py +551 -0
  69. brainstate/transform/__init__.py +59 -0
  70. brainstate/transform/_ad_checkpoint.py +176 -0
  71. brainstate/{compile → transform}/_ad_checkpoint_test.py +49 -49
  72. brainstate/{augment → transform}/_autograd.py +1025 -778
  73. brainstate/{augment → transform}/_autograd_test.py +1289 -1289
  74. brainstate/transform/_conditions.py +316 -0
  75. brainstate/{compile → transform}/_conditions_test.py +220 -220
  76. brainstate/{compile → transform}/_error_if.py +94 -92
  77. brainstate/{compile → transform}/_error_if_test.py +52 -52
  78. brainstate/transform/_eval_shape.py +145 -0
  79. brainstate/{augment → transform}/_eval_shape_test.py +38 -38
  80. brainstate/{compile → transform}/_jit.py +399 -346
  81. brainstate/{compile → transform}/_jit_test.py +143 -143
  82. brainstate/{compile → transform}/_loop_collect_return.py +675 -536
  83. brainstate/{compile → transform}/_loop_collect_return_test.py +58 -58
  84. brainstate/{compile → transform}/_loop_no_collection.py +283 -184
  85. brainstate/{compile → transform}/_loop_no_collection_test.py +50 -50
  86. brainstate/transform/_make_jaxpr.py +2016 -0
  87. brainstate/transform/_make_jaxpr_test.py +1510 -0
  88. brainstate/transform/_mapping.py +529 -0
  89. brainstate/transform/_mapping_test.py +194 -0
  90. brainstate/{compile → transform}/_progress_bar.py +255 -202
  91. brainstate/{augment → transform}/_random.py +171 -151
  92. brainstate/{compile → transform}/_unvmap.py +256 -159
  93. brainstate/transform/_util.py +286 -0
  94. brainstate/typing.py +837 -304
  95. brainstate/typing_test.py +780 -0
  96. brainstate/util/__init__.py +27 -50
  97. brainstate/util/_others.py +1025 -0
  98. brainstate/util/_others_test.py +962 -0
  99. brainstate/util/_pretty_pytree.py +1301 -0
  100. brainstate/util/_pretty_pytree_test.py +675 -0
  101. brainstate/util/{pretty_repr.py → _pretty_repr.py} +462 -328
  102. brainstate/util/_pretty_repr_test.py +696 -0
  103. brainstate/util/filter.py +945 -469
  104. brainstate/util/filter_test.py +912 -0
  105. brainstate/util/struct.py +910 -523
  106. brainstate/util/struct_test.py +602 -0
  107. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/METADATA +108 -91
  108. brainstate-0.2.1.dist-info/RECORD +111 -0
  109. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/licenses/LICENSE +202 -202
  110. brainstate/augment/__init__.py +0 -30
  111. brainstate/augment/_eval_shape.py +0 -99
  112. brainstate/augment/_mapping.py +0 -1060
  113. brainstate/augment/_mapping_test.py +0 -597
  114. brainstate/compile/__init__.py +0 -38
  115. brainstate/compile/_ad_checkpoint.py +0 -204
  116. brainstate/compile/_conditions.py +0 -256
  117. brainstate/compile/_make_jaxpr.py +0 -888
  118. brainstate/compile/_make_jaxpr_test.py +0 -156
  119. brainstate/compile/_util.py +0 -147
  120. brainstate/functional/__init__.py +0 -27
  121. brainstate/graph/_graph_node.py +0 -244
  122. brainstate/graph/_graph_node_test.py +0 -73
  123. brainstate/graph/_graph_operation_test.py +0 -563
  124. brainstate/init/__init__.py +0 -26
  125. brainstate/init/_base.py +0 -52
  126. brainstate/init/_generic.py +0 -244
  127. brainstate/init/_regular_inits.py +0 -105
  128. brainstate/init/_regular_inits_test.py +0 -50
  129. brainstate/nn/_inputs.py +0 -608
  130. brainstate/nn/_ltp.py +0 -28
  131. brainstate/nn/_neuron.py +0 -705
  132. brainstate/nn/_neuron_test.py +0 -161
  133. brainstate/nn/_others.py +0 -46
  134. brainstate/nn/_projection.py +0 -486
  135. brainstate/nn/_rate_rnns_test.py +0 -63
  136. brainstate/nn/_readout.py +0 -209
  137. brainstate/nn/_readout_test.py +0 -53
  138. brainstate/nn/_stp.py +0 -236
  139. brainstate/nn/_synapse.py +0 -505
  140. brainstate/nn/_synapse_test.py +0 -131
  141. brainstate/nn/_synaptic_projection.py +0 -423
  142. brainstate/nn/_synouts.py +0 -162
  143. brainstate/nn/_synouts_test.py +0 -57
  144. brainstate/nn/metrics.py +0 -388
  145. brainstate/optim/__init__.py +0 -38
  146. brainstate/optim/_base.py +0 -64
  147. brainstate/optim/_lr_scheduler.py +0 -448
  148. brainstate/optim/_lr_scheduler_test.py +0 -50
  149. brainstate/optim/_optax_optimizer.py +0 -152
  150. brainstate/optim/_optax_optimizer_test.py +0 -53
  151. brainstate/optim/_sgd_optimizer.py +0 -1104
  152. brainstate/random/_random_for_unit.py +0 -52
  153. brainstate/surrogate.py +0 -1957
  154. brainstate/transform.py +0 -23
  155. brainstate/util/caller.py +0 -98
  156. brainstate/util/others.py +0 -540
  157. brainstate/util/pretty_pytree.py +0 -945
  158. brainstate/util/pretty_pytree_test.py +0 -159
  159. brainstate/util/pretty_table.py +0 -2954
  160. brainstate/util/scaling.py +0 -258
  161. brainstate-0.1.10.dist-info/RECORD +0 -130
  162. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/WHEEL +0 -0
  163. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/top_level.txt +0 -0
@@ -1,1409 +1,1617 @@
1
- # Copyright 2024 BDP Ecosystem Limited. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
- # -*- coding: utf-8 -*-
17
-
18
- from functools import partial
19
- from operator import index
20
- from typing import Optional
21
-
22
- import brainunit as u
23
- import jax
24
- import jax.numpy as jnp
25
- import jax.random as jr
26
- import numpy as np
27
- from jax import jit, vmap
28
- from jax import lax, core, dtypes
29
-
30
- from brainstate import environ
31
- from brainstate._state import State
32
- from brainstate.compile._error_if import jit_error_if
33
- from brainstate.typing import DTypeLike, Size, SeedOrKey
34
- from ._random_for_unit import uniform_for_unit, permutation_for_unit
35
-
36
- __all__ = ['RandomState', 'DEFAULT', ]
37
-
38
- use_prng_key = True
39
-
40
-
41
- class RandomState(State):
42
- """RandomState that track the random generator state. """
43
-
44
- # __slots__ = ('_backup', '_value')
45
-
46
- def __init__(self, seed_or_key: Optional[SeedOrKey] = None):
47
- """RandomState constructor.
48
-
49
- Parameters
50
- ----------
51
- seed_or_key: int, Array, optional
52
- It can be an integer for initial seed of the random number generator,
53
- or it can be a JAX's PRNKey, which is an array with two elements and `uint32` dtype.
54
- """
55
- with jax.ensure_compile_time_eval():
56
- if seed_or_key is None:
57
- seed_or_key = np.random.randint(0, 100000, 2, dtype=np.uint32)
58
- if isinstance(seed_or_key, int):
59
- key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
60
- else:
61
- if jnp.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
62
- key = seed_or_key
63
- else:
64
- if len(seed_or_key) != 2 and seed_or_key.dtype != np.uint32:
65
- raise ValueError('key must be an array with dtype uint32. '
66
- f'But we got {seed_or_key}')
67
- key = seed_or_key
68
- super().__init__(key)
69
-
70
- self._backup = None
71
-
72
- def __repr__(self):
73
- return f'{self.__class__.__name__}({self.value})'
74
-
75
- def check_if_deleted(self):
76
- if not use_prng_key and isinstance(self._value, np.ndarray):
77
- self._value = jr.key(np.random.randint(0, 10000))
78
-
79
- if (
80
- isinstance(self._value, jax.Array) and
81
- not isinstance(self._value, jax.core.Tracer) and
82
- self._value.is_deleted()
83
- ):
84
- self.seed()
85
-
86
- # ------------------- #
87
- # seed and random key #
88
- # ------------------- #
89
-
90
- def backup_key(self):
91
- if self._backup is not None:
92
- raise ValueError('The random key has been backed up, and has not been restored.')
93
- self._backup = self.value
94
-
95
- def restore_key(self):
96
- if self._backup is None:
97
- raise ValueError('The random key has not been backed up.')
98
- self.value = self._backup
99
- self._backup = None
100
-
101
- def clone(self):
102
- return type(self)(self.split_key())
103
-
104
- def set_key(self, key: SeedOrKey):
105
- self.value = key
106
-
107
- def seed(self, seed_or_key: Optional[SeedOrKey] = None):
108
- """Sets a new random seed.
109
-
110
- Parameters
111
- ----------
112
- seed_or_key: int, ArrayLike, optional
113
- It can be an integer for initial seed of the random number generator,
114
- or it can be a JAX's PRNKey, which is an array with two elements and `uint32` dtype.
115
- """
116
- with jax.ensure_compile_time_eval():
117
- if seed_or_key is None:
118
- seed_or_key = np.random.randint(0, 100000, 2, dtype=np.uint32)
119
- if np.size(seed_or_key) == 1:
120
- if isinstance(seed_or_key, int):
121
- key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
122
- elif jnp.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
123
- key = seed_or_key
124
- elif isinstance(seed_or_key, (jnp.ndarray, np.ndarray)) and jnp.issubdtype(seed_or_key.dtype, jnp.integer):
125
- key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
126
- else:
127
- raise ValueError(f'Invalid seed_or_key: {seed_or_key}')
128
- else:
129
- if len(seed_or_key) == 2 and seed_or_key.dtype == np.uint32:
130
- key = seed_or_key
131
- else:
132
- raise ValueError(f'Invalid seed_or_key: {seed_or_key}')
133
- self.value = key
134
-
135
- def split_key(self, n: Optional[int] = None, backup: bool = False) -> SeedOrKey:
136
- """
137
- Create a new seed from the current seed.
138
-
139
- Parameters
140
- ----------
141
- n: int, optional
142
- The number of seeds to generate.
143
- backup : bool, optional
144
- Whether to backup the current key.
145
-
146
- Returns
147
- -------
148
- key : SeedOrKey
149
- The new seed or a tuple of JAX random keys.
150
- """
151
- if n is not None:
152
- assert isinstance(n, int) and n >= 1, f'n should be an integer greater than 1, but we got {n}'
153
-
154
- if not isinstance(self.value, jax.Array):
155
- self.value = jnp.asarray(self.value, dtype=jnp.uint32)
156
- keys = jr.split(self.value, num=2 if n is None else n + 1)
157
- self.value = keys[0]
158
- if backup:
159
- self.backup_key()
160
- if n is None:
161
- return keys[1]
162
- else:
163
- return keys[1:]
164
-
165
- def self_assign_multi_keys(self, n: int, backup: bool = True):
166
- """
167
- Self-assign multiple keys to the current random state.
168
- """
169
- if backup:
170
- keys = jr.split(self.value, n + 1)
171
- self.value = keys[0]
172
- self.backup_key()
173
- self.value = keys[1:]
174
- else:
175
- self.value = jr.split(self.value, n)
176
-
177
- # ---------------- #
178
- # random functions #
179
- # ---------------- #
180
-
181
- def rand(self, *dn, key: Optional[SeedOrKey] = None, dtype: DTypeLike = None):
182
- key = self.split_key() if key is None else _formalize_key(key)
183
- dtype = dtype or environ.dftype()
184
- r = uniform_for_unit(key, shape=dn, minval=0., maxval=1., dtype=dtype)
185
- return r
186
-
187
- def randint(
188
- self,
189
- low,
190
- high=None,
191
- size: Optional[Size] = None,
192
- dtype: DTypeLike = None,
193
- key: Optional[SeedOrKey] = None
194
- ):
195
- if high is None:
196
- high = low
197
- low = 0
198
- high = _check_py_seq(high)
199
- low = _check_py_seq(low)
200
- if size is None:
201
- size = lax.broadcast_shapes(jnp.shape(low),
202
- jnp.shape(high))
203
- key = self.split_key() if key is None else _formalize_key(key)
204
- dtype = dtype or environ.ditype()
205
- r = jr.randint(key,
206
- shape=_size2shape(size),
207
- minval=low, maxval=high, dtype=dtype)
208
- return r
209
-
210
- def random_integers(
211
- self,
212
- low,
213
- high=None,
214
- size: Optional[Size] = None,
215
- key: Optional[SeedOrKey] = None,
216
- dtype: DTypeLike = None,
217
- ):
218
- low = _check_py_seq(low)
219
- high = _check_py_seq(high)
220
- if high is None:
221
- high = low
222
- low = 1
223
- high += 1
224
- if size is None:
225
- size = lax.broadcast_shapes(jnp.shape(low), jnp.shape(high))
226
- key = self.split_key() if key is None else _formalize_key(key)
227
- dtype = dtype or environ.ditype()
228
- r = jr.randint(key,
229
- shape=_size2shape(size),
230
- minval=low,
231
- maxval=high,
232
- dtype=dtype)
233
- return r
234
-
235
- def randn(self, *dn, key: Optional[SeedOrKey] = None, dtype: DTypeLike = None):
236
- key = self.split_key() if key is None else _formalize_key(key)
237
- dtype = dtype or environ.dftype()
238
- r = jr.normal(key, shape=dn, dtype=dtype)
239
- return r
240
-
241
- def random(self,
242
- size: Optional[Size] = None,
243
- key: Optional[SeedOrKey] = None,
244
- dtype: DTypeLike = None):
245
- dtype = dtype or environ.dftype()
246
- key = self.split_key() if key is None else _formalize_key(key)
247
- r = uniform_for_unit(key, shape=_size2shape(size), minval=0., maxval=1., dtype=dtype)
248
- return r
249
-
250
- def random_sample(self,
251
- size: Optional[Size] = None,
252
- key: Optional[SeedOrKey] = None,
253
- dtype: DTypeLike = None):
254
- r = self.random(size=size, key=key, dtype=dtype)
255
- return r
256
-
257
- def ranf(self,
258
- size: Optional[Size] = None,
259
- key: Optional[SeedOrKey] = None,
260
- dtype: DTypeLike = None):
261
- r = self.random(size=size, key=key, dtype=dtype)
262
- return r
263
-
264
- def sample(self,
265
- size: Optional[Size] = None,
266
- key: Optional[SeedOrKey] = None,
267
- dtype: DTypeLike = None):
268
- r = self.random(size=size, key=key, dtype=dtype)
269
- return r
270
-
271
- def choice(self,
272
- a,
273
- size: Optional[Size] = None,
274
- replace=True,
275
- p=None,
276
- key: Optional[SeedOrKey] = None):
277
- a = _check_py_seq(a)
278
- p = _check_py_seq(p)
279
- key = self.split_key() if key is None else _formalize_key(key)
280
- r = jr.choice(key, a=a, shape=_size2shape(size), replace=replace, p=p)
281
- return r
282
-
283
- def permutation(self,
284
- x,
285
- axis: int = 0,
286
- independent: bool = False,
287
- key: Optional[SeedOrKey] = None):
288
- x = _check_py_seq(x)
289
- key = self.split_key() if key is None else _formalize_key(key)
290
- r = permutation_for_unit(key, x, axis=axis, independent=independent)
291
- return r
292
-
293
- def shuffle(self,
294
- x,
295
- axis=0,
296
- key: Optional[SeedOrKey] = None):
297
- key = self.split_key() if key is None else _formalize_key(key)
298
- x = permutation_for_unit(key, x, axis=axis)
299
- return x
300
-
301
- def beta(self,
302
- a,
303
- b,
304
- size: Optional[Size] = None,
305
- key: Optional[SeedOrKey] = None,
306
- dtype: DTypeLike = None):
307
- a = _check_py_seq(a)
308
- b = _check_py_seq(b)
309
- if size is None:
310
- size = lax.broadcast_shapes(jnp.shape(a), jnp.shape(b))
311
- key = self.split_key() if key is None else _formalize_key(key)
312
- dtype = dtype or environ.dftype()
313
- r = jr.beta(key, a=a, b=b, shape=_size2shape(size), dtype=dtype)
314
- return r
315
-
316
- def exponential(self,
317
- scale=None,
318
- size: Optional[Size] = None,
319
- key: Optional[SeedOrKey] = None,
320
- dtype: DTypeLike = None):
321
- if size is None:
322
- size = jnp.shape(scale)
323
- key = self.split_key() if key is None else _formalize_key(key)
324
- dtype = dtype or environ.dftype()
325
- scale = jnp.asarray(scale, dtype=dtype)
326
- r = jr.exponential(key, shape=_size2shape(size), dtype=dtype)
327
- if scale is not None:
328
- r = r / scale
329
- return r
330
-
331
- def gamma(self,
332
- shape,
333
- scale=None,
334
- size: Optional[Size] = None,
335
- key: Optional[SeedOrKey] = None,
336
- dtype: DTypeLike = None):
337
- shape = _check_py_seq(shape)
338
- scale = _check_py_seq(scale)
339
- if size is None:
340
- size = lax.broadcast_shapes(jnp.shape(shape), jnp.shape(scale))
341
- key = self.split_key() if key is None else _formalize_key(key)
342
- dtype = dtype or environ.dftype()
343
- r = jr.gamma(key, a=shape, shape=_size2shape(size), dtype=dtype)
344
- if scale is not None:
345
- r = r * scale
346
- return r
347
-
348
- def gumbel(self,
349
- loc=None,
350
- scale=None,
351
- size: Optional[Size] = None,
352
- key: Optional[SeedOrKey] = None,
353
- dtype: DTypeLike = None):
354
- loc = _check_py_seq(loc)
355
- scale = _check_py_seq(scale)
356
- if size is None:
357
- size = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))
358
- key = self.split_key() if key is None else _formalize_key(key)
359
- dtype = dtype or environ.dftype()
360
- r = _loc_scale(loc, scale, jr.gumbel(key, shape=_size2shape(size), dtype=dtype))
361
- return r
362
-
363
- def laplace(self,
364
- loc=None,
365
- scale=None,
366
- size: Optional[Size] = None,
367
- key: Optional[SeedOrKey] = None,
368
- dtype: DTypeLike = None):
369
- loc = _check_py_seq(loc)
370
- scale = _check_py_seq(scale)
371
- if size is None:
372
- size = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))
373
- key = self.split_key() if key is None else _formalize_key(key)
374
- dtype = dtype or environ.dftype()
375
- r = _loc_scale(loc, scale, jr.laplace(key, shape=_size2shape(size), dtype=dtype))
376
- return r
377
-
378
- def logistic(self,
379
- loc=None,
380
- scale=None,
381
- size: Optional[Size] = None,
382
- key: Optional[SeedOrKey] = None,
383
- dtype: DTypeLike = None):
384
- loc = _check_py_seq(loc)
385
- scale = _check_py_seq(scale)
386
- if size is None:
387
- size = lax.broadcast_shapes(
388
- jnp.shape(loc) if loc is not None else (),
389
- jnp.shape(scale) if scale is not None else ()
390
- )
391
- key = self.split_key() if key is None else _formalize_key(key)
392
- dtype = dtype or environ.dftype()
393
- r = _loc_scale(loc, scale, jr.logistic(key, shape=_size2shape(size), dtype=dtype))
394
- return r
395
-
396
- def normal(self,
397
- loc=None,
398
- scale=None,
399
- size: Optional[Size] = None,
400
- key: Optional[SeedOrKey] = None,
401
- dtype: DTypeLike = None):
402
- loc = _check_py_seq(loc)
403
- scale = _check_py_seq(scale)
404
- if size is None:
405
- size = lax.broadcast_shapes(
406
- jnp.shape(scale) if scale is not None else (),
407
- jnp.shape(loc) if loc is not None else ()
408
- )
409
- key = self.split_key() if key is None else _formalize_key(key)
410
- dtype = dtype or environ.dftype()
411
- r = _loc_scale(loc, scale, jr.normal(key, shape=_size2shape(size), dtype=dtype))
412
- return r
413
-
414
- def pareto(self,
415
- a,
416
- size: Optional[Size] = None,
417
- key: Optional[SeedOrKey] = None,
418
- dtype: DTypeLike = None):
419
- if size is None:
420
- size = jnp.shape(a)
421
- key = self.split_key() if key is None else _formalize_key(key)
422
- dtype = dtype or environ.dftype()
423
- a = jnp.asarray(a, dtype=dtype)
424
- r = jr.pareto(key, b=a, shape=_size2shape(size), dtype=dtype)
425
- return r
426
-
427
- def poisson(self,
428
- lam=1.0,
429
- size: Optional[Size] = None,
430
- key: Optional[SeedOrKey] = None,
431
- dtype: DTypeLike = None):
432
- lam = _check_py_seq(lam)
433
- if size is None:
434
- size = jnp.shape(lam)
435
- key = self.split_key() if key is None else _formalize_key(key)
436
- dtype = dtype or environ.ditype()
437
- r = jr.poisson(key, lam=lam, shape=_size2shape(size), dtype=dtype)
438
- return r
439
-
440
- def standard_cauchy(self,
441
- size: Optional[Size] = None,
442
- key: Optional[SeedOrKey] = None,
443
- dtype: DTypeLike = None):
444
- key = self.split_key() if key is None else _formalize_key(key)
445
- dtype = dtype or environ.dftype()
446
- r = jr.cauchy(key, shape=_size2shape(size), dtype=dtype)
447
- return r
448
-
449
- def standard_exponential(self,
450
- size: Optional[Size] = None,
451
- key: Optional[SeedOrKey] = None,
452
- dtype: DTypeLike = None):
453
- key = self.split_key() if key is None else _formalize_key(key)
454
- dtype = dtype or environ.dftype()
455
- r = jr.exponential(key, shape=_size2shape(size), dtype=dtype)
456
- return r
457
-
458
- def standard_gamma(self,
459
- shape,
460
- size: Optional[Size] = None,
461
- key: Optional[SeedOrKey] = None,
462
- dtype: DTypeLike = None):
463
- shape = _check_py_seq(shape)
464
- if size is None:
465
- size = jnp.shape(shape) if shape is not None else ()
466
- key = self.split_key() if key is None else _formalize_key(key)
467
- dtype = dtype or environ.dftype()
468
- r = jr.gamma(key, a=shape, shape=_size2shape(size), dtype=dtype)
469
- return r
470
-
471
- def standard_normal(self,
472
- size: Optional[Size] = None,
473
- key: Optional[SeedOrKey] = None,
474
- dtype: DTypeLike = None):
475
- key = self.split_key() if key is None else _formalize_key(key)
476
- dtype = dtype or environ.dftype()
477
- r = jr.normal(key, shape=_size2shape(size), dtype=dtype)
478
- return r
479
-
480
- def standard_t(self, df,
481
- size: Optional[Size] = None,
482
- key: Optional[SeedOrKey] = None,
483
- dtype: DTypeLike = None):
484
- df = _check_py_seq(df)
485
- if size is None:
486
- size = jnp.shape(size) if size is not None else ()
487
- key = self.split_key() if key is None else _formalize_key(key)
488
- dtype = dtype or environ.dftype()
489
- r = jr.t(key, df=df, shape=_size2shape(size), dtype=dtype)
490
- return r
491
-
492
- def uniform(self,
493
- low=0.0,
494
- high=1.0,
495
- size: Optional[Size] = None,
496
- key: Optional[SeedOrKey] = None,
497
- dtype: DTypeLike = None):
498
- low = _check_py_seq(low)
499
- high = _check_py_seq(high)
500
- if size is None:
501
- size = lax.broadcast_shapes(jnp.shape(low), jnp.shape(high))
502
- key = self.split_key() if key is None else _formalize_key(key)
503
- dtype = dtype or environ.dftype()
504
- r = uniform_for_unit(key, shape=_size2shape(size), minval=low, maxval=high, dtype=dtype)
505
- return r
506
-
507
- def __norm_cdf(self, x, sqrt2, dtype):
508
- # Computes standard normal cumulative distribution function
509
- return (np.asarray(1., dtype) + lax.erf(x / sqrt2)) / np.asarray(2., dtype)
510
-
511
- def truncated_normal(
512
- self,
513
- lower,
514
- upper,
515
- size: Optional[Size] = None,
516
- loc=0.,
517
- scale=1.,
518
- key: Optional[SeedOrKey] = None,
519
- dtype: DTypeLike = None
520
- ):
521
- lower = _check_py_seq(lower)
522
- upper = _check_py_seq(upper)
523
- loc = _check_py_seq(loc)
524
- scale = _check_py_seq(scale)
525
- dtype = dtype or environ.dftype()
526
-
527
- lower = u.math.asarray(lower, dtype=dtype)
528
- upper = u.math.asarray(upper, dtype=dtype)
529
- loc = u.math.asarray(loc, dtype=dtype)
530
- scale = u.math.asarray(scale, dtype=dtype)
531
- unit = u.get_unit(lower)
532
- lower, upper, loc, scale = (
533
- lower.mantissa if isinstance(lower, u.Quantity) else lower,
534
- u.Quantity(upper).in_unit(unit).mantissa,
535
- u.Quantity(loc).in_unit(unit).mantissa,
536
- u.Quantity(scale).in_unit(unit).mantissa
537
- )
538
-
539
- jit_error_if(
540
- u.math.any(u.math.logical_or(loc < lower - 2 * scale, loc > upper + 2 * scale)),
541
- "mean is more than 2 std from [lower, upper] in truncated_normal. "
542
- "The distribution of values may be incorrect."
543
- )
544
-
545
- if size is None:
546
- size = u.math.broadcast_shapes(jnp.shape(lower),
547
- jnp.shape(upper),
548
- jnp.shape(loc),
549
- jnp.shape(scale))
550
-
551
- # Values are generated by using a truncated uniform distribution and
552
- # then using the inverse CDF for the normal distribution.
553
- # Get upper and lower cdf values
554
- sqrt2 = np.array(np.sqrt(2), dtype=dtype)
555
- l = self.__norm_cdf((lower - loc) / scale, sqrt2, dtype)
556
- u_ = self.__norm_cdf((upper - loc) / scale, sqrt2, dtype)
557
-
558
- # Uniformly fill tensor with values from [l, u], then translate to
559
- # [2l-1, 2u-1].
560
- key = self.split_key() if key is None else _formalize_key(key)
561
- out = uniform_for_unit(
562
- key, size, dtype,
563
- minval=lax.nextafter(2 * l - 1, np.array(np.inf, dtype=dtype)),
564
- maxval=lax.nextafter(2 * u_ - 1, np.array(-np.inf, dtype=dtype))
565
- )
566
-
567
- # Use inverse cdf transform for normal distribution to get truncated
568
- # standard normal
569
- out = lax.erf_inv(out)
570
-
571
- # Transform to proper mean, std
572
- out = out * scale * sqrt2 + loc
573
-
574
- # Clamp to ensure it's in the proper range
575
- out = jnp.clip(
576
- out,
577
- lax.nextafter(lax.stop_gradient(lower), np.array(np.inf, dtype=dtype)),
578
- lax.nextafter(lax.stop_gradient(upper), np.array(-np.inf, dtype=dtype))
579
- )
580
- return out if unit.is_unitless else u.Quantity(out, unit=unit)
581
-
582
- def _check_p(self, *args, **kwargs):
583
- raise ValueError('Parameter p should be within [0, 1], but we got {p}')
584
-
585
- def bernoulli(self,
586
- p,
587
- size: Optional[Size] = None,
588
- key: Optional[SeedOrKey] = None):
589
- p = _check_py_seq(p)
590
- jit_error_if(jnp.any(jnp.logical_or(p < 0, p > 1)), self._check_p, p=p)
591
- if size is None:
592
- size = jnp.shape(p)
593
- key = self.split_key() if key is None else _formalize_key(key)
594
- r = jr.bernoulli(key, p=p, shape=_size2shape(size))
595
- return r
596
-
597
- def lognormal(
598
- self,
599
- mean=None,
600
- sigma=None,
601
- size: Optional[Size] = None,
602
- key: Optional[SeedOrKey] = None,
603
- dtype: DTypeLike = None
604
- ):
605
- mean = _check_py_seq(mean)
606
- sigma = _check_py_seq(sigma)
607
- mean = u.math.asarray(mean, dtype=dtype)
608
- sigma = u.math.asarray(sigma, dtype=dtype)
609
- unit = mean.unit if isinstance(mean, u.Quantity) else u.Unit()
610
- mean = mean.mantissa if isinstance(mean, u.Quantity) else mean
611
- sigma = sigma.in_unit(unit).mantissa if isinstance(sigma, u.Quantity) else sigma
612
-
613
- if size is None:
614
- size = jnp.broadcast_shapes(
615
- jnp.shape(mean) if mean is not None else (),
616
- jnp.shape(sigma) if sigma is not None else ()
617
- )
618
- key = self.split_key() if key is None else _formalize_key(key)
619
- dtype = dtype or environ.dftype()
620
- samples = jr.normal(key, shape=_size2shape(size), dtype=dtype)
621
- samples = _loc_scale(mean, sigma, samples)
622
- samples = jnp.exp(samples)
623
- return samples if unit.is_unitless else u.Quantity(samples, unit=unit)
624
-
625
- def binomial(
626
- self,
627
- n,
628
- p,
629
- size: Optional[Size] = None,
630
- key: Optional[SeedOrKey] = None,
631
- dtype: DTypeLike = None,
632
- check_valid: bool = True,
633
- ):
634
- n = _check_py_seq(n)
635
- p = _check_py_seq(p)
636
- if check_valid:
637
- jit_error_if(
638
- jnp.any(jnp.logical_or(p < 0, p > 1)),
639
- 'Parameter p should be within [0, 1], but we got {p}',
640
- p=p
641
- )
642
- if size is None:
643
- size = jnp.broadcast_shapes(jnp.shape(n), jnp.shape(p))
644
- key = self.split_key() if key is None else _formalize_key(key)
645
- r = jr.binomial(key, n, p, shape=_size2shape(size))
646
- dtype = dtype or environ.ditype()
647
- return jnp.asarray(r, dtype=dtype)
648
-
649
- def chisquare(self,
650
- df,
651
- size: Optional[Size] = None,
652
- key: Optional[SeedOrKey] = None,
653
- dtype: DTypeLike = None):
654
- df = _check_py_seq(df)
655
- key = self.split_key() if key is None else _formalize_key(key)
656
- dtype = dtype or environ.dftype()
657
- if size is None:
658
- if jnp.ndim(df) == 0:
659
- dist = jr.normal(key, (df,), dtype=dtype) ** 2
660
- dist = dist.sum()
661
- else:
662
- raise NotImplementedError('Do not support non-scale "df" when "size" is None')
663
- else:
664
- dist = jr.normal(key, (df,) + _size2shape(size), dtype=dtype) ** 2
665
- dist = dist.sum(axis=0)
666
- return dist
667
-
668
- def dirichlet(self,
669
- alpha,
670
- size: Optional[Size] = None,
671
- key: Optional[SeedOrKey] = None,
672
- dtype: DTypeLike = None):
673
- key = self.split_key() if key is None else _formalize_key(key)
674
- alpha = _check_py_seq(alpha)
675
- dtype = dtype or environ.dftype()
676
- r = jr.dirichlet(key, alpha=alpha, shape=_size2shape(size), dtype=dtype)
677
- return r
678
-
679
- def geometric(self,
680
- p,
681
- size: Optional[Size] = None,
682
- key: Optional[SeedOrKey] = None,
683
- dtype: DTypeLike = None):
684
- p = _check_py_seq(p)
685
- if size is None:
686
- size = jnp.shape(p)
687
- key = self.split_key() if key is None else _formalize_key(key)
688
- dtype = dtype or environ.dftype()
689
- u_ = uniform_for_unit(key, size, dtype=dtype)
690
- r = jnp.floor(jnp.log1p(-u_) / jnp.log1p(-p))
691
- return r
692
-
693
- def _check_p2(self, p):
694
- raise ValueError(f'We require `sum(pvals[:-1]) <= 1`. But we got {p}')
695
-
696
- def multinomial(self,
697
- n,
698
- pvals,
699
- size: Optional[Size] = None,
700
- key: Optional[SeedOrKey] = None,
701
- dtype: DTypeLike = None):
702
- key = self.split_key() if key is None else _formalize_key(key)
703
- n = _check_py_seq(n)
704
- pvals = _check_py_seq(pvals)
705
- jit_error_if(jnp.sum(pvals[:-1]) > 1., self._check_p2, pvals)
706
- if isinstance(n, jax.core.Tracer):
707
- raise ValueError("The total count parameter `n` should not be a jax abstract array.")
708
- size = _size2shape(size)
709
- n_max = int(np.max(jax.device_get(n)))
710
- batch_shape = lax.broadcast_shapes(jnp.shape(pvals)[:-1], jnp.shape(n))
711
- r = _multinomial(key, pvals, n, n_max, batch_shape + size)
712
- dtype = dtype or environ.ditype()
713
- return jnp.asarray(r, dtype=dtype)
714
-
715
- def multivariate_normal(
716
- self,
717
- mean,
718
- cov,
719
- size: Optional[Size] = None,
720
- method: str = 'cholesky',
721
- key: Optional[SeedOrKey] = None,
722
- dtype: DTypeLike = None
723
- ):
724
- if method not in {'svd', 'eigh', 'cholesky'}:
725
- raise ValueError("method must be one of {'svd', 'eigh', 'cholesky'}")
726
- dtype = dtype or environ.dftype()
727
- mean = u.math.asarray(_check_py_seq(mean), dtype=dtype)
728
- cov = u.math.asarray(_check_py_seq(cov), dtype=dtype)
729
- if isinstance(mean, u.Quantity):
730
- assert isinstance(cov, u.Quantity)
731
- assert mean.unit ** 2 == cov.unit
732
- mean = mean.mantissa if isinstance(mean, u.Quantity) else mean
733
- cov = cov.mantissa if isinstance(cov, u.Quantity) else cov
734
- unit = mean.unit if isinstance(mean, u.Quantity) else u.Unit()
735
-
736
- key = self.split_key() if key is None else _formalize_key(key)
737
- if not jnp.ndim(mean) >= 1:
738
- raise ValueError(f"multivariate_normal requires mean.ndim >= 1, got mean.ndim == {jnp.ndim(mean)}")
739
- if not jnp.ndim(cov) >= 2:
740
- raise ValueError(f"multivariate_normal requires cov.ndim >= 2, got cov.ndim == {jnp.ndim(cov)}")
741
- n = mean.shape[-1]
742
- if jnp.shape(cov)[-2:] != (n, n):
743
- raise ValueError(f"multivariate_normal requires cov.shape == (..., n, n) for n={n}, "
744
- f"but got cov.shape == {jnp.shape(cov)}.")
745
- if size is None:
746
- size = lax.broadcast_shapes(mean.shape[:-1], cov.shape[:-2])
747
- else:
748
- size = _size2shape(size)
749
- _check_shape("normal", size, mean.shape[:-1], cov.shape[:-2])
750
-
751
- if method == 'svd':
752
- (u_, s, _) = jnp.linalg.svd(cov)
753
- factor = u_ * jnp.sqrt(s[..., None, :])
754
- elif method == 'eigh':
755
- (w, v) = jnp.linalg.eigh(cov)
756
- factor = v * jnp.sqrt(w[..., None, :])
757
- else: # 'cholesky'
758
- factor = jnp.linalg.cholesky(cov)
759
- normal_samples = jr.normal(key, size + mean.shape[-1:], dtype=dtype)
760
- r = mean + jnp.einsum('...ij,...j->...i', factor, normal_samples)
761
- return r if unit.is_unitless else u.Quantity(r, unit=unit)
762
-
763
- def rayleigh(self,
764
- scale=1.0,
765
- size: Optional[Size] = None,
766
- key: Optional[SeedOrKey] = None,
767
- dtype: DTypeLike = None):
768
- scale = _check_py_seq(scale)
769
- if size is None:
770
- size = jnp.shape(scale)
771
- key = self.split_key() if key is None else _formalize_key(key)
772
- dtype = dtype or environ.dftype()
773
- x = jnp.sqrt(-2. * jnp.log(uniform_for_unit(key, shape=_size2shape(size), minval=0, maxval=1, dtype=dtype)))
774
- r = x * scale
775
- return r
776
-
777
- def triangular(self,
778
- size: Optional[Size] = None,
779
- key: Optional[SeedOrKey] = None):
780
- key = self.split_key() if key is None else _formalize_key(key)
781
- bernoulli_samples = jr.bernoulli(key, p=0.5, shape=_size2shape(size))
782
- r = 2 * bernoulli_samples - 1
783
- return r
784
-
785
- def vonmises(self,
786
- mu,
787
- kappa,
788
- size: Optional[Size] = None,
789
- key: Optional[SeedOrKey] = None,
790
- dtype: DTypeLike = None):
791
- key = self.split_key() if key is None else _formalize_key(key)
792
- dtype = dtype or environ.dftype()
793
- mu = jnp.asarray(_check_py_seq(mu), dtype=dtype)
794
- kappa = jnp.asarray(_check_py_seq(kappa), dtype=dtype)
795
- if size is None:
796
- size = lax.broadcast_shapes(jnp.shape(mu), jnp.shape(kappa))
797
- size = _size2shape(size)
798
- samples = _von_mises_centered(key, kappa, size, dtype=dtype)
799
- samples = samples + mu
800
- samples = (samples + jnp.pi) % (2.0 * jnp.pi) - jnp.pi
801
- return samples
802
-
803
- def weibull(self,
804
- a,
805
- size: Optional[Size] = None,
806
- key: Optional[SeedOrKey] = None,
807
- dtype: DTypeLike = None):
808
- key = self.split_key() if key is None else _formalize_key(key)
809
- a = _check_py_seq(a)
810
- if size is None:
811
- size = jnp.shape(a)
812
- else:
813
- if jnp.size(a) > 1:
814
- raise ValueError(f'"a" should be a scalar when "size" is provided. But we got {a}')
815
- size = _size2shape(size)
816
- dtype = dtype or environ.dftype()
817
- random_uniform = uniform_for_unit(key=key, shape=size, minval=0, maxval=1, dtype=dtype)
818
- r = jnp.power(-jnp.log1p(-random_uniform), 1.0 / a)
819
- return r
820
-
821
- def weibull_min(self,
822
- a,
823
- scale=None,
824
- size: Optional[Size] = None,
825
- key: Optional[SeedOrKey] = None,
826
- dtype: DTypeLike = None):
827
- key = self.split_key() if key is None else _formalize_key(key)
828
- a = _check_py_seq(a)
829
- scale = _check_py_seq(scale)
830
- if size is None:
831
- size = jnp.broadcast_shapes(jnp.shape(a), jnp.shape(scale) if scale is not None else ())
832
- else:
833
- if jnp.size(a) > 1:
834
- raise ValueError(f'"a" should be a scalar when "size" is provided. But we got {a}')
835
- size = _size2shape(size)
836
- dtype = dtype or environ.dftype()
837
- random_uniform = uniform_for_unit(key=key, shape=size, minval=0, maxval=1, dtype=dtype)
838
- r = jnp.power(-jnp.log1p(-random_uniform), 1.0 / a)
839
- if scale is not None:
840
- r /= scale
841
- return r
842
-
843
- def maxwell(self,
844
- size: Optional[Size] = None,
845
- key: Optional[SeedOrKey] = None,
846
- dtype: DTypeLike = None):
847
- key = self.split_key() if key is None else _formalize_key(key)
848
- shape = _size2shape(size) + (3,)
849
- dtype = dtype or environ.dftype()
850
- norm_rvs = jr.normal(key=key, shape=shape, dtype=dtype)
851
- r = jnp.linalg.norm(norm_rvs, axis=-1)
852
- return r
853
-
854
- def negative_binomial(self,
855
- n,
856
- p,
857
- size: Optional[Size] = None,
858
- key: Optional[SeedOrKey] = None,
859
- dtype: DTypeLike = None):
860
- n = _check_py_seq(n)
861
- p = _check_py_seq(p)
862
- if size is None:
863
- size = lax.broadcast_shapes(jnp.shape(n), jnp.shape(p))
864
- size = _size2shape(size)
865
- logits = jnp.log(p) - jnp.log1p(-p)
866
- if key is None:
867
- keys = self.split_key(2)
868
- else:
869
- keys = jr.split(_formalize_key(key), 2)
870
- rate = self.gamma(shape=n, scale=jnp.exp(-logits), size=size, key=keys[0], dtype=environ.dftype())
871
- r = self.poisson(lam=rate, key=keys[1], dtype=dtype or environ.ditype())
872
- return r
873
-
874
- def wald(self,
875
- mean,
876
- scale,
877
- size: Optional[Size] = None,
878
- key: Optional[SeedOrKey] = None,
879
- dtype: DTypeLike = None):
880
- dtype = dtype or environ.dftype()
881
- key = self.split_key() if key is None else _formalize_key(key)
882
- mean = jnp.asarray(_check_py_seq(mean), dtype=dtype)
883
- scale = jnp.asarray(_check_py_seq(scale), dtype=dtype)
884
- if size is None:
885
- size = lax.broadcast_shapes(jnp.shape(mean), jnp.shape(scale))
886
- size = _size2shape(size)
887
- sampled_chi2 = jnp.square(self.randn(*size))
888
- sampled_uniform = self.uniform(size=size, key=key, dtype=dtype)
889
- # Wikipedia defines an intermediate x with the formula
890
- # x = loc + loc ** 2 * y / (2 * conc) - loc / (2 * conc) * sqrt(4 * loc * conc * y + loc ** 2 * y ** 2)
891
- # where y ~ N(0, 1)**2 (sampled_chi2 above) and conc is the concentration.
892
- # Let us write
893
- # w = loc * y / (2 * conc)
894
- # Then we can extract the common factor in the last two terms to obtain
895
- # x = loc + loc * w * (1 - sqrt(2 / w + 1))
896
- # Now we see that the Wikipedia formula suffers from catastrphic
897
- # cancellation for large w (e.g., if conc << loc).
898
- #
899
- # Fortunately, we can fix this by multiplying both sides
900
- # by 1 + sqrt(2 / w + 1). We get
901
- # x * (1 + sqrt(2 / w + 1)) =
902
- # = loc * (1 + sqrt(2 / w + 1)) + loc * w * (1 - (2 / w + 1))
903
- # = loc * (sqrt(2 / w + 1) - 1)
904
- # The term sqrt(2 / w + 1) + 1 no longer presents numerical
905
- # difficulties for large w, and sqrt(2 / w + 1) - 1 is just
906
- # sqrt1pm1(2 / w), which we know how to compute accurately.
907
- # This just leaves the matter of small w, where 2 / w may
908
- # overflow. In the limit a w -> 0, x -> loc, so we just mask
909
- # that case.
910
- sqrt1pm1_arg = 4 * scale / (mean * sampled_chi2) # 2 / w above
911
- safe_sqrt1pm1_arg = jnp.where(sqrt1pm1_arg < np.inf, sqrt1pm1_arg, 1.0)
912
- denominator = 1.0 + jnp.sqrt(safe_sqrt1pm1_arg + 1.0)
913
- ratio = jnp.expm1(0.5 * jnp.log1p(safe_sqrt1pm1_arg)) / denominator
914
- sampled = mean * jnp.where(sqrt1pm1_arg < np.inf, ratio, 1.0) # x above
915
- res = jnp.where(sampled_uniform <= mean / (mean + sampled),
916
- sampled,
917
- jnp.square(mean) / sampled)
918
- return res
919
-
920
- def t(self,
921
- df,
922
- size: Optional[Size] = None,
923
- key: Optional[SeedOrKey] = None,
924
- dtype: DTypeLike = None):
925
- dtype = dtype or environ.dftype()
926
- df = jnp.asarray(_check_py_seq(df), dtype=dtype)
927
- if size is None:
928
- size = np.shape(df)
929
- else:
930
- size = _size2shape(size)
931
- _check_shape("t", size, np.shape(df))
932
- if key is None:
933
- keys = self.split_key(2)
934
- else:
935
- keys = jr.split(_formalize_key(key), 2)
936
- n = jr.normal(keys[0], size, dtype=dtype)
937
- two = _const(n, 2)
938
- half_df = lax.div(df, two)
939
- g = jr.gamma(keys[1], half_df, size, dtype=dtype)
940
- r = n * jnp.sqrt(half_df / g)
941
- return r
942
-
943
- def orthogonal(self,
944
- n: int,
945
- size: Optional[Size] = None,
946
- key: Optional[SeedOrKey] = None,
947
- dtype: DTypeLike = None):
948
- dtype = dtype or environ.dftype()
949
- key = self.split_key() if key is None else _formalize_key(key)
950
- size = _size2shape(size)
951
- _check_shape("orthogonal", size)
952
- n = core.concrete_or_error(index, n, "The error occurred in jax.random.orthogonal()")
953
- z = jr.normal(key, size + (n, n), dtype=dtype)
954
- q, r = jnp.linalg.qr(z)
955
- d = jnp.diagonal(r, 0, -2, -1)
956
- r = q * jnp.expand_dims(d / abs(d), -2)
957
- return r
958
-
959
- def noncentral_chisquare(self,
960
- df,
961
- nonc,
962
- size: Optional[Size] = None,
963
- key: Optional[SeedOrKey] = None,
964
- dtype: DTypeLike = None):
965
- dtype = dtype or environ.dftype()
966
- df = jnp.asarray(_check_py_seq(df), dtype=dtype)
967
- nonc = jnp.asarray(_check_py_seq(nonc), dtype=dtype)
968
- if size is None:
969
- size = lax.broadcast_shapes(jnp.shape(df), jnp.shape(nonc))
970
- size = _size2shape(size)
971
- if key is None:
972
- keys = self.split_key(3)
973
- else:
974
- keys = jr.split(_formalize_key(key), 3)
975
- i = jr.poisson(keys[0], 0.5 * nonc, shape=size, dtype=environ.ditype())
976
- n = jr.normal(keys[1], shape=size, dtype=dtype) + jnp.sqrt(nonc)
977
- cond = jnp.greater(df, 1.0)
978
- df2 = jnp.where(cond, df - 1.0, df + 2.0 * i)
979
- chi2 = 2.0 * jr.gamma(keys[2], 0.5 * df2, shape=size, dtype=dtype)
980
- r = jnp.where(cond, chi2 + n * n, chi2)
981
- return r
982
-
983
- def loggamma(self,
984
- a,
985
- size: Optional[Size] = None,
986
- key: Optional[SeedOrKey] = None,
987
- dtype: DTypeLike = None):
988
- dtype = dtype or environ.dftype()
989
- key = self.split_key() if key is None else _formalize_key(key)
990
- a = _check_py_seq(a)
991
- if size is None:
992
- size = jnp.shape(a)
993
- r = jr.loggamma(key, a, shape=_size2shape(size), dtype=dtype)
994
- return r
995
-
996
- def categorical(self,
997
- logits,
998
- axis: int = -1,
999
- size: Optional[Size] = None,
1000
- key: Optional[SeedOrKey] = None):
1001
- key = self.split_key() if key is None else _formalize_key(key)
1002
- logits = _check_py_seq(logits)
1003
- if size is None:
1004
- size = list(jnp.shape(logits))
1005
- size.pop(axis)
1006
- r = jr.categorical(key, logits, axis=axis, shape=_size2shape(size))
1007
- return r
1008
-
1009
- def zipf(self,
1010
- a,
1011
- size: Optional[Size] = None,
1012
- key: Optional[SeedOrKey] = None,
1013
- dtype: DTypeLike = None):
1014
- a = _check_py_seq(a)
1015
- if size is None:
1016
- size = jnp.shape(a)
1017
- dtype = dtype or environ.ditype()
1018
- r = jax.pure_callback(lambda x: np.random.zipf(x, size).astype(dtype),
1019
- jax.ShapeDtypeStruct(size, dtype),
1020
- a)
1021
- return r
1022
-
1023
- def power(self,
1024
- a,
1025
- size: Optional[Size] = None,
1026
- key: Optional[SeedOrKey] = None,
1027
- dtype: DTypeLike = None):
1028
- a = _check_py_seq(a)
1029
- if size is None:
1030
- size = jnp.shape(a)
1031
- size = _size2shape(size)
1032
- dtype = dtype or environ.dftype()
1033
- r = jax.pure_callback(lambda a: np.random.power(a=a, size=size).astype(dtype),
1034
- jax.ShapeDtypeStruct(size, dtype),
1035
- a)
1036
- return r
1037
-
1038
- def f(self,
1039
- dfnum,
1040
- dfden,
1041
- size: Optional[Size] = None,
1042
- key: Optional[SeedOrKey] = None,
1043
- dtype: DTypeLike = None):
1044
- dfnum = _check_py_seq(dfnum)
1045
- dfden = _check_py_seq(dfden)
1046
- if size is None:
1047
- size = jnp.broadcast_shapes(jnp.shape(dfnum), jnp.shape(dfden))
1048
- size = _size2shape(size)
1049
- d = {'dfnum': dfnum, 'dfden': dfden}
1050
- dtype = dtype or environ.dftype()
1051
- r = jax.pure_callback(lambda dfnum_, dfden_: np.random.f(dfnum=dfnum_,
1052
- dfden=dfden_,
1053
- size=size).astype(dtype),
1054
- jax.ShapeDtypeStruct(size, dtype),
1055
- dfnum, dfden)
1056
- return r
1057
-
1058
- def hypergeometric(
1059
- self,
1060
- ngood,
1061
- nbad,
1062
- nsample,
1063
- size: Optional[Size] = None,
1064
- key: Optional[SeedOrKey] = None,
1065
- dtype: DTypeLike = None
1066
- ):
1067
- ngood = _check_py_seq(ngood)
1068
- nbad = _check_py_seq(nbad)
1069
- nsample = _check_py_seq(nsample)
1070
-
1071
- if size is None:
1072
- size = lax.broadcast_shapes(jnp.shape(ngood),
1073
- jnp.shape(nbad),
1074
- jnp.shape(nsample))
1075
- size = _size2shape(size)
1076
- dtype = dtype or environ.ditype()
1077
- d = {'ngood': ngood, 'nbad': nbad, 'nsample': nsample}
1078
- r = jax.pure_callback(lambda d: np.random.hypergeometric(ngood=d['ngood'],
1079
- nbad=d['nbad'],
1080
- nsample=d['nsample'],
1081
- size=size).astype(dtype),
1082
- jax.ShapeDtypeStruct(size, dtype),
1083
- d)
1084
- return r
1085
-
1086
- def logseries(self,
1087
- p,
1088
- size: Optional[Size] = None,
1089
- key: Optional[SeedOrKey] = None,
1090
- dtype: DTypeLike = None):
1091
- p = _check_py_seq(p)
1092
- if size is None:
1093
- size = jnp.shape(p)
1094
- size = _size2shape(size)
1095
- dtype = dtype or environ.ditype()
1096
- r = jax.pure_callback(lambda p: np.random.logseries(p=p, size=size).astype(dtype),
1097
- jax.ShapeDtypeStruct(size, dtype),
1098
- p)
1099
- return r
1100
-
1101
- def noncentral_f(self,
1102
- dfnum,
1103
- dfden,
1104
- nonc,
1105
- size: Optional[Size] = None,
1106
- key: Optional[SeedOrKey] = None,
1107
- dtype: DTypeLike = None):
1108
- dfnum = _check_py_seq(dfnum)
1109
- dfden = _check_py_seq(dfden)
1110
- nonc = _check_py_seq(nonc)
1111
- if size is None:
1112
- size = lax.broadcast_shapes(jnp.shape(dfnum),
1113
- jnp.shape(dfden),
1114
- jnp.shape(nonc))
1115
- size = _size2shape(size)
1116
- d = {'dfnum': dfnum, 'dfden': dfden, 'nonc': nonc}
1117
- dtype = dtype or environ.dftype()
1118
- r = jax.pure_callback(lambda x: np.random.noncentral_f(dfnum=x['dfnum'],
1119
- dfden=x['dfden'],
1120
- nonc=x['nonc'],
1121
- size=size).astype(dtype),
1122
- jax.ShapeDtypeStruct(size, dtype),
1123
- d)
1124
- return r
1125
-
1126
- # PyTorch compatibility #
1127
- # --------------------- #
1128
-
1129
- def rand_like(self, input, *, dtype=None, key: Optional[SeedOrKey] = None):
1130
- """Returns a tensor with the same size as input that is filled with random
1131
- numbers from a uniform distribution on the interval ``[0, 1)``.
1132
-
1133
- Args:
1134
- input: the ``size`` of input will determine size of the output tensor.
1135
- dtype: the desired data type of returned Tensor. Default: if ``None``, defaults to the dtype of input.
1136
- key: the seed or key for the random.
1137
-
1138
- Returns:
1139
- The random data.
1140
- """
1141
- return self.random(jnp.shape(input), key=key).astype(dtype)
1142
-
1143
- def randn_like(self, input, *, dtype=None, key: Optional[SeedOrKey] = None):
1144
- """Returns a tensor with the same size as ``input`` that is filled with
1145
- random numbers from a normal distribution with mean 0 and variance 1.
1146
-
1147
- Args:
1148
- input: the ``size`` of input will determine size of the output tensor.
1149
- dtype: the desired data type of returned Tensor. Default: if ``None``, defaults to the dtype of input.
1150
- key: the seed or key for the random.
1151
-
1152
- Returns:
1153
- The random data.
1154
- """
1155
- return self.randn(*jnp.shape(input), key=key).astype(dtype)
1156
-
1157
- def randint_like(self, input, low=0, high=None, *, dtype=None, key: Optional[SeedOrKey] = None):
1158
- if high is None:
1159
- high = max(input)
1160
- return self.randint(low, high=high, size=jnp.shape(input), dtype=dtype, key=key)
1161
-
1162
-
1163
- # default random generator
1164
- DEFAULT = RandomState(np.random.randint(0, 10000, size=2, dtype=np.uint32))
1165
-
1166
-
1167
- # ---------------------------------------------------------------------------------------------------------------
1168
-
1169
-
1170
- def _formalize_key(key):
1171
- if isinstance(key, int):
1172
- return jr.PRNGKey(key) if use_prng_key else jr.key(key)
1173
- elif isinstance(key, (jax.Array, np.ndarray)):
1174
- if jnp.issubdtype(key.dtype, jax.dtypes.prng_key):
1175
- return key
1176
- if key.size == 1 and jnp.issubdtype(key.dtype, jnp.integer):
1177
- return jr.PRNGKey(key) if use_prng_key else jr.key(key)
1178
-
1179
- if key.dtype != jnp.uint32:
1180
- raise TypeError('key must be a int or an array with two uint32.')
1181
- if key.size != 2:
1182
- raise TypeError('key must be a int or an array with two uint32.')
1183
- return jnp.asarray(key, dtype=jnp.uint32)
1184
- else:
1185
- raise TypeError('key must be a int or an array with two uint32.')
1186
-
1187
-
1188
- def _size2shape(size):
1189
- if size is None:
1190
- return ()
1191
- elif isinstance(size, (tuple, list)):
1192
- return tuple(size)
1193
- else:
1194
- return (size,)
1195
-
1196
-
1197
- def _check_shape(name, shape, *param_shapes):
1198
- if param_shapes:
1199
- shape_ = lax.broadcast_shapes(shape, *param_shapes)
1200
- if shape != shape_:
1201
- msg = ("{} parameter shapes must be broadcast-compatible with shape "
1202
- "argument, and the result of broadcasting the shapes must equal "
1203
- "the shape argument, but got result {} for shape argument {}.")
1204
- raise ValueError(msg.format(name, shape_, shape))
1205
-
1206
-
1207
- def _is_python_scalar(x):
1208
- if hasattr(x, 'aval'):
1209
- return x.aval.weak_type
1210
- elif np.ndim(x) == 0:
1211
- return True
1212
- elif isinstance(x, (bool, int, float, complex)):
1213
- return True
1214
- else:
1215
- return False
1216
-
1217
-
1218
- python_scalar_dtypes = {
1219
- bool: np.dtype('bool'),
1220
- int: np.dtype('int64'),
1221
- float: np.dtype('float64'),
1222
- complex: np.dtype('complex128'),
1223
- }
1224
-
1225
-
1226
- def _dtype(x, *, canonicalize: bool = False):
1227
- """Return the dtype object for a value or type, optionally canonicalized based on X64 mode."""
1228
- if x is None:
1229
- raise ValueError(f"Invalid argument to dtype: {x}.")
1230
- elif isinstance(x, type) and x in python_scalar_dtypes:
1231
- dt = python_scalar_dtypes[x]
1232
- elif type(x) in python_scalar_dtypes:
1233
- dt = python_scalar_dtypes[type(x)]
1234
- elif hasattr(x, 'dtype'):
1235
- dt = x.dtype
1236
- else:
1237
- dt = np.result_type(x)
1238
- return dtypes.canonicalize_dtype(dt) if canonicalize else dt
1239
-
1240
-
1241
- def _const(example, val):
1242
- if _is_python_scalar(example):
1243
- dtype = dtypes.canonicalize_dtype(type(example))
1244
- val = dtypes.scalar_type_of(example)(val)
1245
- return val if dtype == _dtype(val, canonicalize=True) else np.array(val, dtype)
1246
- else:
1247
- dtype = dtypes.canonicalize_dtype(example.dtype)
1248
- return np.array(val, dtype)
1249
-
1250
-
1251
- @partial(jit, static_argnums=(2,))
1252
- def _categorical(key, p, shape):
1253
- # this implementation is fast when event shape is small, and slow otherwise
1254
- # Ref: https://stackoverflow.com/a/34190035
1255
- shape = shape or p.shape[:-1]
1256
- s = jnp.cumsum(p, axis=-1)
1257
- r = jr.uniform(key, shape=shape + (1,))
1258
- return jnp.sum(s < r, axis=-1)
1259
-
1260
-
1261
- def _scatter_add_one(operand, indices, updates):
1262
- return lax.scatter_add(
1263
- operand,
1264
- indices,
1265
- updates,
1266
- lax.ScatterDimensionNumbers(
1267
- update_window_dims=(),
1268
- inserted_window_dims=(0,),
1269
- scatter_dims_to_operand_dims=(0,),
1270
- ),
1271
- )
1272
-
1273
-
1274
- def _reshape(x, shape):
1275
- if isinstance(x, (int, float, np.ndarray, np.generic)):
1276
- return np.reshape(x, shape)
1277
- else:
1278
- return jnp.reshape(x, shape)
1279
-
1280
-
1281
- def _promote_shapes(*args, shape=()):
1282
- # adapted from lax.lax_numpy
1283
- if len(args) < 2 and not shape:
1284
- return args
1285
- else:
1286
- shapes = [jnp.shape(arg) for arg in args]
1287
- num_dims = len(lax.broadcast_shapes(shape, *shapes))
1288
- return [
1289
- _reshape(arg, (1,) * (num_dims - len(s)) + s) if len(s) < num_dims else arg
1290
- for arg, s in zip(args, shapes)
1291
- ]
1292
-
1293
-
1294
- @partial(jit, static_argnums=(3, 4))
1295
- def _multinomial(key, p, n, n_max, shape=()):
1296
- if jnp.shape(n) != jnp.shape(p)[:-1]:
1297
- broadcast_shape = lax.broadcast_shapes(jnp.shape(n), jnp.shape(p)[:-1])
1298
- n = jnp.broadcast_to(n, broadcast_shape)
1299
- p = jnp.broadcast_to(p, broadcast_shape + jnp.shape(p)[-1:])
1300
- shape = shape or p.shape[:-1]
1301
- if n_max == 0:
1302
- return jnp.zeros(shape + p.shape[-1:], dtype=jnp.result_type(int))
1303
- # get indices from categorical distribution then gather the result
1304
- indices = _categorical(key, p, (n_max,) + shape)
1305
- # mask out values when counts is heterogeneous
1306
- if jnp.ndim(n) > 0:
1307
- mask = _promote_shapes(jnp.arange(n_max) < jnp.expand_dims(n, -1), shape=shape + (n_max,))[0]
1308
- mask = jnp.moveaxis(mask, -1, 0).astype(indices.dtype)
1309
- excess = jnp.concatenate([jnp.expand_dims(n_max - n, -1),
1310
- jnp.zeros(jnp.shape(n) + (p.shape[-1] - 1,))],
1311
- -1)
1312
- else:
1313
- mask = 1
1314
- excess = 0
1315
- # NB: we transpose to move batch shape to the front
1316
- indices_2D = (jnp.reshape(indices * mask, (n_max, -1))).T
1317
- samples_2D = vmap(_scatter_add_one)(jnp.zeros((indices_2D.shape[0], p.shape[-1]), dtype=indices.dtype),
1318
- jnp.expand_dims(indices_2D, axis=-1),
1319
- jnp.ones(indices_2D.shape, dtype=indices.dtype))
1320
- return jnp.reshape(samples_2D, shape + p.shape[-1:]) - excess
1321
-
1322
-
1323
- @partial(jit, static_argnums=(2, 3), static_argnames=['shape', 'dtype'])
1324
- def _von_mises_centered(key, concentration, shape, dtype=None):
1325
- """Compute centered von Mises samples using rejection sampling from [1]_ with wrapped Cauchy proposal.
1326
-
1327
- Returns
1328
- -------
1329
- out: array_like
1330
- centered samples from von Mises
1331
-
1332
- References
1333
- ----------
1334
- .. [1] Luc Devroye "Non-Uniform Random Variate Generation", Springer-Verlag, 1986;
1335
- Chapter 9, p. 473-476. http://www.nrbook.com/devroye/Devroye_files/chapter_nine.pdf
1336
-
1337
- """
1338
- shape = shape or jnp.shape(concentration)
1339
- dtype = dtype or environ.dftype()
1340
- concentration = lax.convert_element_type(concentration, dtype)
1341
- concentration = jnp.broadcast_to(concentration, shape)
1342
-
1343
- if dtype == jnp.float16:
1344
- s_cutoff = 1.8e-1
1345
- elif dtype == jnp.float32:
1346
- s_cutoff = 2e-2
1347
- elif dtype == jnp.float64:
1348
- s_cutoff = 1.2e-4
1349
- else:
1350
- raise ValueError(f"Unsupported dtype: {dtype}")
1351
-
1352
- r = 1.0 + jnp.sqrt(1.0 + 4.0 * concentration ** 2)
1353
- rho = (r - jnp.sqrt(2.0 * r)) / (2.0 * concentration)
1354
- s_exact = (1.0 + rho ** 2) / (2.0 * rho)
1355
-
1356
- s_approximate = 1.0 / concentration
1357
-
1358
- s = jnp.where(concentration > s_cutoff, s_exact, s_approximate)
1359
-
1360
- def cond_fn(*args):
1361
- """check if all are done or reached max number of iterations"""
1362
- i, _, done, _, _ = args[0]
1363
- return jnp.bitwise_and(i < 100, jnp.logical_not(jnp.all(done)))
1364
-
1365
- def body_fn(*args):
1366
- i, key, done, _, w = args[0]
1367
- uni_ukey, uni_vkey, key = jr.split(key, 3)
1368
- u = jr.uniform(
1369
- key=uni_ukey,
1370
- shape=shape,
1371
- dtype=concentration.dtype,
1372
- minval=-1.0,
1373
- maxval=1.0,
1374
- )
1375
- z = jnp.cos(jnp.pi * u)
1376
- w = jnp.where(done, w, (1.0 + s * z) / (s + z)) # Update where not done
1377
- y = concentration * (s - w)
1378
- v = jr.uniform(key=uni_vkey, shape=shape, dtype=concentration.dtype)
1379
- accept = (y * (2.0 - y) >= v) | (jnp.log(y / v) + 1.0 >= y)
1380
- return i + 1, key, accept | done, u, w
1381
-
1382
- init_done = jnp.zeros(shape, dtype=bool)
1383
- init_u = jnp.zeros(shape)
1384
- init_w = jnp.zeros(shape)
1385
-
1386
- _, _, done, u, w = lax.while_loop(
1387
- cond_fun=cond_fn,
1388
- body_fun=body_fn,
1389
- init_val=(jnp.array(0), key, init_done, init_u, init_w),
1390
- )
1391
-
1392
- return jnp.sign(u) * jnp.arccos(w)
1393
-
1394
-
1395
- def _loc_scale(loc, scale, value):
1396
- if loc is None:
1397
- if scale is None:
1398
- return value
1399
- else:
1400
- return value * scale
1401
- else:
1402
- if scale is None:
1403
- return value + loc
1404
- else:
1405
- return value * scale + loc
1406
-
1407
-
1408
- def _check_py_seq(seq):
1409
- return jnp.asarray(seq) if isinstance(seq, (tuple, list)) else seq
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ # -*- coding: utf-8 -*-
17
+
18
+ from functools import partial
19
+ from operator import index
20
+ from typing import Optional
21
+
22
+ import brainunit as u
23
+ import jax
24
+ import jax.numpy as jnp
25
+ import jax.random as jr
26
+ import numpy as np
27
+ from jax import jit, vmap
28
+ from jax import lax, core, dtypes
29
+
30
+ from brainstate import environ
31
+ from brainstate._state import State
32
+ from brainstate.typing import DTypeLike, Size, SeedOrKey
33
+
34
+ __all__ = [
35
+ 'RandomState',
36
+ 'DEFAULT',
37
+ ]
38
+
39
+ use_prng_key = True
40
+
41
+
42
+ class RandomState(State):
43
+ """RandomState that track the random generator state. """
44
+
45
+ # __slots__ = ('_backup', '_value')
46
+
47
+ def __init__(
48
+ self,
49
+ seed_or_key: Optional[SeedOrKey] = None
50
+ ):
51
+ """RandomState constructor.
52
+
53
+ Parameters
54
+ ----------
55
+ seed_or_key: int, Array, optional
56
+ It can be an integer for initial seed of the random number generator,
57
+ or it can be a JAX's PRNKey, which is an array with two elements and `uint32` dtype.
58
+ """
59
+ with jax.ensure_compile_time_eval():
60
+ if seed_or_key is None:
61
+ seed_or_key = np.random.randint(0, 100000, 2, dtype=np.uint32)
62
+ if isinstance(seed_or_key, int):
63
+ key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
64
+ else:
65
+ if jnp.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
66
+ key = seed_or_key
67
+ else:
68
+ if len(seed_or_key) != 2 and seed_or_key.dtype != np.uint32:
69
+ raise ValueError('key must be an array with dtype uint32. '
70
+ f'But we got {seed_or_key}')
71
+ key = seed_or_key
72
+ super().__init__(key)
73
+
74
+ self._backup = None
75
+
76
+ def __repr__(
77
+ self
78
+ ):
79
+ return f'{self.__class__.__name__}({self.value})'
80
+
81
+ def check_if_deleted(
82
+ self
83
+ ):
84
+ if not use_prng_key and isinstance(self._value, np.ndarray):
85
+ self._value = jr.key(np.random.randint(0, 10000))
86
+
87
+ if (
88
+ isinstance(self._value, jax.Array) and
89
+ not isinstance(self._value, jax.core.Tracer) and
90
+ self._value.is_deleted()
91
+ ):
92
+ self.seed()
93
+
94
+ # ------------------- #
95
+ # seed and random key #
96
+ # ------------------- #
97
+
98
+ def backup_key(self):
99
+ if self._backup is not None:
100
+ raise ValueError('The random key has been backed up, and has not been restored.')
101
+ self._backup = self.value
102
+
103
+ def restore_key(self):
104
+ if self._backup is None:
105
+ raise ValueError('The random key has not been backed up.')
106
+ self.value = self._backup
107
+ self._backup = None
108
+
109
+ def clone(self):
110
+ return type(self)(self.split_key())
111
+
112
+ def set_key(self, key: SeedOrKey):
113
+ self.value = key
114
+
115
+ def seed(
116
+ self,
117
+ seed_or_key: Optional[SeedOrKey] = None
118
+ ):
119
+ """Sets a new random seed.
120
+
121
+ Parameters
122
+ ----------
123
+ seed_or_key: int, ArrayLike, optional
124
+ It can be an integer for initial seed of the random number generator,
125
+ or it can be a JAX's PRNKey, which is an array with two elements and `uint32` dtype.
126
+ """
127
+ with jax.ensure_compile_time_eval():
128
+ if seed_or_key is None:
129
+ seed_or_key = np.random.randint(0, 100000, 2, dtype=np.uint32)
130
+ if np.size(seed_or_key) == 1:
131
+ if isinstance(seed_or_key, int):
132
+ key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
133
+ elif jnp.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
134
+ key = seed_or_key
135
+ elif isinstance(seed_or_key, (jnp.ndarray, np.ndarray)) and jnp.issubdtype(seed_or_key.dtype, jnp.integer):
136
+ key = jr.PRNGKey(seed_or_key) if use_prng_key else jr.key(seed_or_key)
137
+ else:
138
+ raise ValueError(f'Invalid seed_or_key: {seed_or_key}')
139
+ else:
140
+ if len(seed_or_key) == 2 and seed_or_key.dtype == np.uint32:
141
+ key = seed_or_key
142
+ else:
143
+ raise ValueError(f'Invalid seed_or_key: {seed_or_key}')
144
+ self.value = key
145
+
146
+ def split_key(
147
+ self,
148
+ n: Optional[int] = None,
149
+ backup: bool = False
150
+ ) -> SeedOrKey:
151
+ """
152
+ Create a new seed from the current seed.
153
+
154
+ Parameters
155
+ ----------
156
+ n: int, optional
157
+ The number of seeds to generate.
158
+ backup : bool, optional
159
+ Whether to backup the current key.
160
+
161
+ Returns
162
+ -------
163
+ key : SeedOrKey
164
+ The new seed or a tuple of JAX random keys.
165
+ """
166
+ if n is not None:
167
+ assert isinstance(n, int) and n >= 1, f'n should be an integer greater than 1, but we got {n}'
168
+
169
+ if not isinstance(self.value, jax.Array):
170
+ self.value = u.math.asarray(self.value, dtype=jnp.uint32)
171
+ keys = jr.split(self.value, num=2 if n is None else n + 1)
172
+ self.value = keys[0]
173
+ if backup:
174
+ self.backup_key()
175
+ if n is None:
176
+ return keys[1]
177
+ else:
178
+ return keys[1:]
179
+
180
+ def self_assign_multi_keys(
181
+ self,
182
+ n: int,
183
+ backup: bool = True
184
+ ):
185
+ """
186
+ Self-assign multiple keys to the current random state.
187
+ """
188
+ if backup:
189
+ keys = jr.split(self.value, n + 1)
190
+ self.value = keys[0]
191
+ self.backup_key()
192
+ self.value = keys[1:]
193
+ else:
194
+ self.value = jr.split(self.value, n)
195
+
196
+ # ---------------- #
197
+ # random functions #
198
+ # ---------------- #
199
+
200
+ def rand(
201
+ self,
202
+ *dn,
203
+ key: Optional[SeedOrKey] = None,
204
+ dtype: DTypeLike = None
205
+ ):
206
+ key = self.split_key() if key is None else _formalize_key(key)
207
+ dtype = dtype or environ.dftype()
208
+ r = jr.uniform(key, dn, dtype)
209
+ return r
210
+
211
+ def randint(
212
+ self,
213
+ low,
214
+ high=None,
215
+ size: Optional[Size] = None,
216
+ dtype: DTypeLike = None,
217
+ key: Optional[SeedOrKey] = None
218
+ ):
219
+ if high is None:
220
+ high = low
221
+ low = 0
222
+ high = _check_py_seq(high)
223
+ low = _check_py_seq(low)
224
+ if size is None:
225
+ size = lax.broadcast_shapes(u.math.shape(low),
226
+ u.math.shape(high))
227
+ key = self.split_key() if key is None else _formalize_key(key)
228
+ dtype = dtype or environ.ditype()
229
+ r = jr.randint(key,
230
+ shape=_size2shape(size),
231
+ minval=low, maxval=high, dtype=dtype)
232
+ return r
233
+
234
+ def random_integers(
235
+ self,
236
+ low,
237
+ high=None,
238
+ size: Optional[Size] = None,
239
+ key: Optional[SeedOrKey] = None,
240
+ dtype: DTypeLike = None
241
+ ):
242
+ low = _check_py_seq(low)
243
+ high = _check_py_seq(high)
244
+ if high is None:
245
+ high = low
246
+ low = 1
247
+ high += 1
248
+ if size is None:
249
+ size = lax.broadcast_shapes(u.math.shape(low), u.math.shape(high))
250
+ key = self.split_key() if key is None else _formalize_key(key)
251
+ dtype = dtype or environ.ditype()
252
+ r = jr.randint(key,
253
+ shape=_size2shape(size),
254
+ minval=low,
255
+ maxval=high,
256
+ dtype=dtype)
257
+ return r
258
+
259
+ def randn(
260
+ self,
261
+ *dn,
262
+ key: Optional[SeedOrKey] = None,
263
+ dtype: DTypeLike = None
264
+ ):
265
+ key = self.split_key() if key is None else _formalize_key(key)
266
+ dtype = dtype or environ.dftype()
267
+ r = jr.normal(key, shape=dn, dtype=dtype)
268
+ return r
269
+
270
+ def random(
271
+ self,
272
+ size: Optional[Size] = None,
273
+ key: Optional[SeedOrKey] = None,
274
+ dtype: DTypeLike = None
275
+ ):
276
+ dtype = dtype or environ.dftype()
277
+ key = self.split_key() if key is None else _formalize_key(key)
278
+ r = jr.uniform(key, _size2shape(size), dtype)
279
+ return r
280
+
281
+ def random_sample(
282
+ self,
283
+ size: Optional[Size] = None,
284
+ key: Optional[SeedOrKey] = None,
285
+ dtype: DTypeLike = None
286
+ ):
287
+ r = self.random(size=size, key=key, dtype=dtype)
288
+ return r
289
+
290
+ def ranf(
291
+ self,
292
+ size: Optional[Size] = None,
293
+ key: Optional[SeedOrKey] = None,
294
+ dtype: DTypeLike = None
295
+ ):
296
+ r = self.random(size=size, key=key, dtype=dtype)
297
+ return r
298
+
299
+ def sample(
300
+ self,
301
+ size: Optional[Size] = None,
302
+ key: Optional[SeedOrKey] = None,
303
+ dtype: DTypeLike = None
304
+ ):
305
+ r = self.random(size=size, key=key, dtype=dtype)
306
+ return r
307
+
308
+ def choice(
309
+ self,
310
+ a,
311
+ size: Optional[Size] = None,
312
+ replace=True,
313
+ p=None,
314
+ key: Optional[SeedOrKey] = None
315
+ ):
316
+ a = _check_py_seq(a)
317
+ a, unit = u.split_mantissa_unit(a)
318
+ p = _check_py_seq(p)
319
+ key = self.split_key() if key is None else _formalize_key(key)
320
+ r = jr.choice(key, a=a, shape=_size2shape(size), replace=replace, p=p)
321
+ return u.maybe_decimal(r * unit)
322
+
323
+ def permutation(
324
+ self,
325
+ x,
326
+ axis: int = 0,
327
+ independent: bool = False,
328
+ key: Optional[SeedOrKey] = None
329
+ ):
330
+ x = _check_py_seq(x)
331
+ x, unit = u.split_mantissa_unit(x)
332
+ key = self.split_key() if key is None else _formalize_key(key)
333
+ r = jr.permutation(key, x, axis, independent=independent)
334
+ return u.maybe_decimal(r * unit)
335
+
336
+ def shuffle(
337
+ self,
338
+ x,
339
+ axis=0,
340
+ key: Optional[SeedOrKey] = None
341
+ ):
342
+ return self.permutation(x, axis=axis, key=key, independent=False)
343
+
344
+ def beta(
345
+ self,
346
+ a,
347
+ b,
348
+ size: Optional[Size] = None,
349
+ key: Optional[SeedOrKey] = None,
350
+ dtype: DTypeLike = None
351
+ ):
352
+ a = _check_py_seq(a)
353
+ b = _check_py_seq(b)
354
+ if size is None:
355
+ size = lax.broadcast_shapes(u.math.shape(a), u.math.shape(b))
356
+ key = self.split_key() if key is None else _formalize_key(key)
357
+ dtype = dtype or environ.dftype()
358
+ r = jr.beta(key, a=a, b=b, shape=_size2shape(size), dtype=dtype)
359
+ return r
360
+
361
+ def exponential(
362
+ self,
363
+ scale=None,
364
+ size: Optional[Size] = None,
365
+ key: Optional[SeedOrKey] = None,
366
+ dtype: DTypeLike = None
367
+ ):
368
+ if size is None:
369
+ size = u.math.shape(scale)
370
+ key = self.split_key() if key is None else _formalize_key(key)
371
+ dtype = dtype or environ.dftype()
372
+ r = jr.exponential(key, shape=_size2shape(size), dtype=dtype)
373
+ if scale is not None:
374
+ scale = u.math.asarray(scale, dtype=dtype)
375
+ r = r / scale
376
+ return r
377
+
378
+ def gamma(
379
+ self,
380
+ shape,
381
+ scale=None,
382
+ size: Optional[Size] = None,
383
+ key: Optional[SeedOrKey] = None,
384
+ dtype: DTypeLike = None
385
+ ):
386
+ shape = _check_py_seq(shape)
387
+ scale = _check_py_seq(scale)
388
+ if size is None:
389
+ size = lax.broadcast_shapes(u.math.shape(shape), u.math.shape(scale))
390
+ key = self.split_key() if key is None else _formalize_key(key)
391
+ dtype = dtype or environ.dftype()
392
+ r = jr.gamma(key, a=shape, shape=_size2shape(size), dtype=dtype)
393
+ if scale is not None:
394
+ r = r * scale
395
+ return r
396
+
397
+ def gumbel(
398
+ self,
399
+ loc=None,
400
+ scale=None,
401
+ size: Optional[Size] = None,
402
+ key: Optional[SeedOrKey] = None,
403
+ dtype: DTypeLike = None
404
+ ):
405
+ loc = _check_py_seq(loc)
406
+ scale = _check_py_seq(scale)
407
+ if size is None:
408
+ size = lax.broadcast_shapes(u.math.shape(loc), u.math.shape(scale))
409
+ key = self.split_key() if key is None else _formalize_key(key)
410
+ dtype = dtype or environ.dftype()
411
+ r = _loc_scale(loc, scale, jr.gumbel(key, shape=_size2shape(size), dtype=dtype))
412
+ return r
413
+
414
+ def laplace(
415
+ self,
416
+ loc=None,
417
+ scale=None,
418
+ size: Optional[Size] = None,
419
+ key: Optional[SeedOrKey] = None,
420
+ dtype: DTypeLike = None
421
+ ):
422
+ loc = _check_py_seq(loc)
423
+ scale = _check_py_seq(scale)
424
+ if size is None:
425
+ size = lax.broadcast_shapes(u.math.shape(loc), u.math.shape(scale))
426
+ key = self.split_key() if key is None else _formalize_key(key)
427
+ dtype = dtype or environ.dftype()
428
+ r = _loc_scale(loc, scale, jr.laplace(key, shape=_size2shape(size), dtype=dtype))
429
+ return r
430
+
431
+ def logistic(
432
+ self,
433
+ loc=None,
434
+ scale=None,
435
+ size: Optional[Size] = None,
436
+ key: Optional[SeedOrKey] = None,
437
+ dtype: DTypeLike = None
438
+ ):
439
+ loc = _check_py_seq(loc)
440
+ scale = _check_py_seq(scale)
441
+ if size is None:
442
+ size = lax.broadcast_shapes(
443
+ u.math.shape(loc) if loc is not None else (),
444
+ u.math.shape(scale) if scale is not None else ()
445
+ )
446
+ key = self.split_key() if key is None else _formalize_key(key)
447
+ dtype = dtype or environ.dftype()
448
+ r = _loc_scale(loc, scale, jr.logistic(key, shape=_size2shape(size), dtype=dtype))
449
+ return r
450
+
451
+ def normal(
452
+ self,
453
+ loc=None,
454
+ scale=None,
455
+ size: Optional[Size] = None,
456
+ key: Optional[SeedOrKey] = None,
457
+ dtype: DTypeLike = None
458
+ ):
459
+ loc = _check_py_seq(loc)
460
+ scale = _check_py_seq(scale)
461
+ if size is None:
462
+ size = lax.broadcast_shapes(
463
+ u.math.shape(scale) if scale is not None else (),
464
+ u.math.shape(loc) if loc is not None else ()
465
+ )
466
+ key = self.split_key() if key is None else _formalize_key(key)
467
+ dtype = dtype or environ.dftype()
468
+ r = _loc_scale(loc, scale, jr.normal(key, shape=_size2shape(size), dtype=dtype))
469
+ return r
470
+
471
+ def pareto(
472
+ self,
473
+ a,
474
+ size: Optional[Size] = None,
475
+ key: Optional[SeedOrKey] = None,
476
+ dtype: DTypeLike = None
477
+ ):
478
+ if size is None:
479
+ size = u.math.shape(a)
480
+ key = self.split_key() if key is None else _formalize_key(key)
481
+ dtype = dtype or environ.dftype()
482
+ a = u.math.asarray(a, dtype=dtype)
483
+ r = jr.pareto(key, b=a, shape=_size2shape(size), dtype=dtype)
484
+ return r
485
+
486
+ def poisson(
487
+ self,
488
+ lam=1.0,
489
+ size: Optional[Size] = None,
490
+ key: Optional[SeedOrKey] = None,
491
+ dtype: DTypeLike = None
492
+ ):
493
+ lam = _check_py_seq(lam)
494
+ if size is None:
495
+ size = u.math.shape(lam)
496
+ key = self.split_key() if key is None else _formalize_key(key)
497
+ dtype = dtype or environ.ditype()
498
+ r = jr.poisson(key, lam=lam, shape=_size2shape(size), dtype=dtype)
499
+ return r
500
+
501
+ def standard_cauchy(
502
+ self,
503
+ size: Optional[Size] = None,
504
+ key: Optional[SeedOrKey] = None,
505
+ dtype: DTypeLike = None
506
+ ):
507
+ key = self.split_key() if key is None else _formalize_key(key)
508
+ dtype = dtype or environ.dftype()
509
+ r = jr.cauchy(key, shape=_size2shape(size), dtype=dtype)
510
+ return r
511
+
512
+ def standard_exponential(
513
+ self,
514
+ size: Optional[Size] = None,
515
+ key: Optional[SeedOrKey] = None,
516
+ dtype: DTypeLike = None
517
+ ):
518
+ key = self.split_key() if key is None else _formalize_key(key)
519
+ dtype = dtype or environ.dftype()
520
+ r = jr.exponential(key, shape=_size2shape(size), dtype=dtype)
521
+ return r
522
+
523
+ def standard_gamma(
524
+ self,
525
+ shape,
526
+ size: Optional[Size] = None,
527
+ key: Optional[SeedOrKey] = None,
528
+ dtype: DTypeLike = None
529
+ ):
530
+ shape = _check_py_seq(shape)
531
+ if size is None:
532
+ size = u.math.shape(shape) if shape is not None else ()
533
+ key = self.split_key() if key is None else _formalize_key(key)
534
+ dtype = dtype or environ.dftype()
535
+ r = jr.gamma(key, a=shape, shape=_size2shape(size), dtype=dtype)
536
+ return r
537
+
538
+ def standard_normal(
539
+ self,
540
+ size: Optional[Size] = None,
541
+ key: Optional[SeedOrKey] = None,
542
+ dtype: DTypeLike = None
543
+ ):
544
+ key = self.split_key() if key is None else _formalize_key(key)
545
+ dtype = dtype or environ.dftype()
546
+ r = jr.normal(key, shape=_size2shape(size), dtype=dtype)
547
+ return r
548
+
549
+ def standard_t(
550
+ self,
551
+ df,
552
+ size: Optional[Size] = None,
553
+ key: Optional[SeedOrKey] = None,
554
+ dtype: DTypeLike = None
555
+ ):
556
+ df = _check_py_seq(df)
557
+ if size is None:
558
+ size = u.math.shape(size) if size is not None else ()
559
+ key = self.split_key() if key is None else _formalize_key(key)
560
+ dtype = dtype or environ.dftype()
561
+ r = jr.t(key, df=df, shape=_size2shape(size), dtype=dtype)
562
+ return r
563
+
564
+ def uniform(
565
+ self,
566
+ low=0.0,
567
+ high=1.0,
568
+ size: Optional[Size] = None,
569
+ key: Optional[SeedOrKey] = None,
570
+ dtype: DTypeLike = None
571
+ ):
572
+ low, unit = u.split_mantissa_unit(_check_py_seq(low))
573
+ high = u.Quantity(_check_py_seq(high)).to(unit).mantissa
574
+ if size is None:
575
+ size = lax.broadcast_shapes(u.math.shape(low), u.math.shape(high))
576
+ key = self.split_key() if key is None else _formalize_key(key)
577
+ dtype = dtype or environ.dftype()
578
+ r = jr.uniform(key, _size2shape(size), dtype=dtype, minval=low, maxval=high)
579
+ return u.maybe_decimal(r * unit)
580
+
581
+ def __norm_cdf(
582
+ self,
583
+ x,
584
+ sqrt2,
585
+ dtype
586
+ ):
587
+ # Computes standard normal cumulative distribution function
588
+ return (np.asarray(1., dtype) + lax.erf(x / sqrt2)) / np.asarray(2., dtype)
589
+
590
+ def truncated_normal(
591
+ self,
592
+ lower,
593
+ upper,
594
+ size: Optional[Size] = None,
595
+ loc=0.0,
596
+ scale=1.0,
597
+ key: Optional[SeedOrKey] = None,
598
+ dtype: DTypeLike = None,
599
+ check_valid: bool = True
600
+ ):
601
+ lower = _check_py_seq(lower)
602
+ upper = _check_py_seq(upper)
603
+ loc = _check_py_seq(loc)
604
+ scale = _check_py_seq(scale)
605
+ dtype = dtype or environ.dftype()
606
+
607
+ lower, unit = u.split_mantissa_unit(u.math.asarray(lower, dtype=dtype))
608
+ upper = u.math.asarray(upper, dtype=dtype)
609
+ loc = u.math.asarray(loc, dtype=dtype)
610
+ scale = u.math.asarray(scale, dtype=dtype)
611
+ upper, loc, scale = (
612
+ u.Quantity(upper).in_unit(unit).mantissa,
613
+ u.Quantity(loc).in_unit(unit).mantissa,
614
+ u.Quantity(scale).in_unit(unit).mantissa
615
+ )
616
+
617
+ if check_valid:
618
+ from brainstate.transform._error_if import jit_error_if
619
+ jit_error_if(
620
+ u.math.any(u.math.logical_or(loc < lower - 2 * scale, loc > upper + 2 * scale)),
621
+ "mean is more than 2 std from [lower, upper] in truncated_normal. "
622
+ "The distribution of values may be incorrect."
623
+ )
624
+
625
+ if size is None:
626
+ size = u.math.broadcast_shapes(
627
+ u.math.shape(lower),
628
+ u.math.shape(upper),
629
+ u.math.shape(loc),
630
+ u.math.shape(scale)
631
+ )
632
+
633
+ # Values are generated by using a truncated uniform distribution and
634
+ # then using the inverse CDF for the normal distribution.
635
+ # Get upper and lower cdf values
636
+ sqrt2 = np.array(np.sqrt(2), dtype=dtype)
637
+ l = self.__norm_cdf((lower - loc) / scale, sqrt2, dtype)
638
+ u_ = self.__norm_cdf((upper - loc) / scale, sqrt2, dtype)
639
+
640
+ # Uniformly fill tensor with values from [l, u], then translate to
641
+ # [2l-1, 2u-1].
642
+ key = self.split_key() if key is None else _formalize_key(key)
643
+ out = jr.uniform(
644
+ key, size, dtype,
645
+ minval=lax.nextafter(2 * l - 1, np.array(np.inf, dtype=dtype)),
646
+ maxval=lax.nextafter(2 * u_ - 1, np.array(-np.inf, dtype=dtype))
647
+ )
648
+
649
+ # Use inverse cdf transform for normal distribution to get truncated
650
+ # standard normal
651
+ out = lax.erf_inv(out)
652
+
653
+ # Transform to proper mean, std
654
+ out = out * scale * sqrt2 + loc
655
+
656
+ # Clamp to ensure it's in the proper range
657
+ out = jnp.clip(
658
+ out,
659
+ lax.nextafter(lax.stop_gradient(lower), np.array(np.inf, dtype=dtype)),
660
+ lax.nextafter(lax.stop_gradient(upper), np.array(-np.inf, dtype=dtype))
661
+ )
662
+ return u.maybe_decimal(out * unit)
663
+
664
+ def _check_p(self, *args, **kwargs):
665
+ raise ValueError('Parameter p should be within [0, 1], but we got {p}')
666
+
667
+ def bernoulli(
668
+ self,
669
+ p,
670
+ size: Optional[Size] = None,
671
+ key: Optional[SeedOrKey] = None,
672
+ check_valid: bool = True
673
+ ):
674
+ p = _check_py_seq(p)
675
+ if check_valid:
676
+ from brainstate.transform._error_if import jit_error_if
677
+ jit_error_if(jnp.any(jnp.logical_or(p < 0, p > 1)), self._check_p, p=p)
678
+ if size is None:
679
+ size = u.math.shape(p)
680
+ key = self.split_key() if key is None else _formalize_key(key)
681
+ r = jr.bernoulli(key, p=p, shape=_size2shape(size))
682
+ return r
683
+
684
+ def lognormal(
685
+ self,
686
+ mean=None,
687
+ sigma=None,
688
+ size: Optional[Size] = None,
689
+ key: Optional[SeedOrKey] = None,
690
+ dtype: DTypeLike = None
691
+ ):
692
+ mean = _check_py_seq(mean)
693
+ sigma = _check_py_seq(sigma)
694
+ mean = u.math.asarray(mean, dtype=dtype)
695
+ sigma = u.math.asarray(sigma, dtype=dtype)
696
+ unit = mean.unit if isinstance(mean, u.Quantity) else u.UNITLESS
697
+ mean = mean.mantissa if isinstance(mean, u.Quantity) else mean
698
+ sigma = sigma.in_unit(unit).mantissa if isinstance(sigma, u.Quantity) else sigma
699
+
700
+ if size is None:
701
+ size = jnp.broadcast_shapes(
702
+ u.math.shape(mean) if mean is not None else (),
703
+ u.math.shape(sigma) if sigma is not None else ()
704
+ )
705
+ key = self.split_key() if key is None else _formalize_key(key)
706
+ dtype = dtype or environ.dftype()
707
+ samples = jr.normal(key, shape=_size2shape(size), dtype=dtype)
708
+ samples = _loc_scale(mean, sigma, samples)
709
+ samples = jnp.exp(samples)
710
+ return u.maybe_decimal(samples * unit)
711
+
712
+ def binomial(
713
+ self,
714
+ n,
715
+ p,
716
+ size: Optional[Size] = None,
717
+ key: Optional[SeedOrKey] = None,
718
+ dtype: DTypeLike = None,
719
+ check_valid: bool = True
720
+ ):
721
+ n = _check_py_seq(n)
722
+ p = _check_py_seq(p)
723
+ if check_valid:
724
+ from brainstate.transform._error_if import jit_error_if
725
+ jit_error_if(
726
+ jnp.any(jnp.logical_or(p < 0, p > 1)),
727
+ 'Parameter p should be within [0, 1], but we got {p}',
728
+ p=p
729
+ )
730
+ if size is None:
731
+ size = jnp.broadcast_shapes(u.math.shape(n), u.math.shape(p))
732
+ key = self.split_key() if key is None else _formalize_key(key)
733
+ r = jr.binomial(key, n, p, shape=_size2shape(size))
734
+ dtype = dtype or environ.ditype()
735
+ return u.math.asarray(r, dtype=dtype)
736
+
737
+ def chisquare(
738
+ self,
739
+ df,
740
+ size: Optional[Size] = None,
741
+ key: Optional[SeedOrKey] = None,
742
+ dtype: DTypeLike = None
743
+ ):
744
+ df = _check_py_seq(df)
745
+ key = self.split_key() if key is None else _formalize_key(key)
746
+ dtype = dtype or environ.dftype()
747
+ if size is None:
748
+ if jnp.ndim(df) == 0:
749
+ dist = jr.normal(key, (df,), dtype=dtype) ** 2
750
+ dist = dist.sum()
751
+ else:
752
+ raise NotImplementedError('Do not support non-scale "df" when "size" is None')
753
+ else:
754
+ dist = jr.normal(key, (df,) + _size2shape(size), dtype=dtype) ** 2
755
+ dist = dist.sum(axis=0)
756
+ return dist
757
+
758
+ def dirichlet(
759
+ self,
760
+ alpha,
761
+ size: Optional[Size] = None,
762
+ key: Optional[SeedOrKey] = None,
763
+ dtype: DTypeLike = None
764
+ ):
765
+ key = self.split_key() if key is None else _formalize_key(key)
766
+ alpha = _check_py_seq(alpha)
767
+ dtype = dtype or environ.dftype()
768
+ r = jr.dirichlet(key, alpha=alpha, shape=_size2shape(size), dtype=dtype)
769
+ return r
770
+
771
+ def geometric(
772
+ self,
773
+ p,
774
+ size: Optional[Size] = None,
775
+ key: Optional[SeedOrKey] = None,
776
+ dtype: DTypeLike = None
777
+ ):
778
+ p = _check_py_seq(p)
779
+ if size is None:
780
+ size = u.math.shape(p)
781
+ key = self.split_key() if key is None else _formalize_key(key)
782
+ dtype = dtype or environ.dftype()
783
+ u_ = jr.uniform(key, size, dtype)
784
+ r = jnp.floor(jnp.log1p(-u_) / jnp.log1p(-p))
785
+ return r
786
+
787
+ def _check_p2(self, p):
788
+ raise ValueError(f'We require `sum(pvals[:-1]) <= 1`. But we got {p}')
789
+
790
+ def multinomial(
791
+ self,
792
+ n,
793
+ pvals,
794
+ size: Optional[Size] = None,
795
+ key: Optional[SeedOrKey] = None,
796
+ dtype: DTypeLike = None,
797
+ check_valid: bool = True
798
+ ):
799
+ key = self.split_key() if key is None else _formalize_key(key)
800
+ n = _check_py_seq(n)
801
+ pvals = _check_py_seq(pvals)
802
+ if check_valid:
803
+ from brainstate.transform._error_if import jit_error_if
804
+ jit_error_if(jnp.sum(pvals[:-1]) > 1., self._check_p2, pvals)
805
+ if isinstance(n, jax.core.Tracer):
806
+ raise ValueError("The total count parameter `n` should not be a jax abstract array.")
807
+ size = _size2shape(size)
808
+ n_max = int(np.max(jax.device_get(n)))
809
+ batch_shape = lax.broadcast_shapes(u.math.shape(pvals)[:-1], u.math.shape(n))
810
+ r = _multinomial(key, pvals, n, n_max, batch_shape + size)
811
+ dtype = dtype or environ.ditype()
812
+ return u.math.asarray(r, dtype=dtype)
813
+
814
+ def multivariate_normal(
815
+ self,
816
+ mean,
817
+ cov,
818
+ size: Optional[Size] = None,
819
+ method: str = 'cholesky',
820
+ key: Optional[SeedOrKey] = None,
821
+ dtype: DTypeLike = None
822
+ ):
823
+ if method not in {'svd', 'eigh', 'cholesky'}:
824
+ raise ValueError("method must be one of {'svd', 'eigh', 'cholesky'}")
825
+ dtype = dtype or environ.dftype()
826
+ mean = u.math.asarray(_check_py_seq(mean), dtype=dtype)
827
+ cov = u.math.asarray(_check_py_seq(cov), dtype=dtype)
828
+ if isinstance(mean, u.Quantity):
829
+ assert isinstance(cov, u.Quantity)
830
+ assert mean.unit ** 2 == cov.unit
831
+ mean = mean.mantissa if isinstance(mean, u.Quantity) else mean
832
+ cov = cov.mantissa if isinstance(cov, u.Quantity) else cov
833
+ unit = mean.unit if isinstance(mean, u.Quantity) else u.Unit()
834
+
835
+ key = self.split_key() if key is None else _formalize_key(key)
836
+ if not jnp.ndim(mean) >= 1:
837
+ raise ValueError(f"multivariate_normal requires mean.ndim >= 1, got mean.ndim == {jnp.ndim(mean)}")
838
+ if not jnp.ndim(cov) >= 2:
839
+ raise ValueError(f"multivariate_normal requires cov.ndim >= 2, got cov.ndim == {jnp.ndim(cov)}")
840
+ n = mean.shape[-1]
841
+ if u.math.shape(cov)[-2:] != (n, n):
842
+ raise ValueError(f"multivariate_normal requires cov.shape == (..., n, n) for n={n}, "
843
+ f"but got cov.shape == {u.math.shape(cov)}.")
844
+ if size is None:
845
+ size = lax.broadcast_shapes(mean.shape[:-1], cov.shape[:-2])
846
+ else:
847
+ size = _size2shape(size)
848
+ _check_shape("normal", size, mean.shape[:-1], cov.shape[:-2])
849
+
850
+ if method == 'svd':
851
+ (u_, s, _) = jnp.linalg.svd(cov)
852
+ factor = u_ * jnp.sqrt(s[..., None, :])
853
+ elif method == 'eigh':
854
+ (w, v) = jnp.linalg.eigh(cov)
855
+ factor = v * jnp.sqrt(w[..., None, :])
856
+ else: # 'cholesky'
857
+ factor = jnp.linalg.cholesky(cov)
858
+ normal_samples = jr.normal(key, size + mean.shape[-1:], dtype=dtype)
859
+ r = mean + jnp.einsum('...ij,...j->...i', factor, normal_samples)
860
+ return u.maybe_decimal(r * unit)
861
+
862
+ def rayleigh(
863
+ self,
864
+ scale=1.0,
865
+ size: Optional[Size] = None,
866
+ key: Optional[SeedOrKey] = None,
867
+ dtype: DTypeLike = None
868
+ ):
869
+ scale = _check_py_seq(scale)
870
+ if size is None:
871
+ size = u.math.shape(scale)
872
+ key = self.split_key() if key is None else _formalize_key(key)
873
+ dtype = dtype or environ.dftype()
874
+ x = jnp.sqrt(-2. * jnp.log(jr.uniform(key, shape=_size2shape(size), dtype=dtype)))
875
+ r = x * scale
876
+ return r
877
+
878
+ def triangular(
879
+ self,
880
+ size: Optional[Size] = None,
881
+ key: Optional[SeedOrKey] = None
882
+ ):
883
+ key = self.split_key() if key is None else _formalize_key(key)
884
+ bernoulli_samples = jr.bernoulli(key, p=0.5, shape=_size2shape(size))
885
+ r = 2 * bernoulli_samples - 1
886
+ return r
887
+
888
+ def vonmises(
889
+ self,
890
+ mu,
891
+ kappa,
892
+ size: Optional[Size] = None,
893
+ key: Optional[SeedOrKey] = None,
894
+ dtype: DTypeLike = None
895
+ ):
896
+ key = self.split_key() if key is None else _formalize_key(key)
897
+ dtype = dtype or environ.dftype()
898
+ mu = u.math.asarray(_check_py_seq(mu), dtype=dtype)
899
+ kappa = u.math.asarray(_check_py_seq(kappa), dtype=dtype)
900
+ if size is None:
901
+ size = lax.broadcast_shapes(u.math.shape(mu), u.math.shape(kappa))
902
+ size = _size2shape(size)
903
+ samples = _von_mises_centered(key, kappa, size, dtype=dtype)
904
+ samples = samples + mu
905
+ samples = (samples + jnp.pi) % (2.0 * jnp.pi) - jnp.pi
906
+ return samples
907
+
908
+ def weibull(
909
+ self,
910
+ a,
911
+ size: Optional[Size] = None,
912
+ key: Optional[SeedOrKey] = None,
913
+ dtype: DTypeLike = None
914
+ ):
915
+ key = self.split_key() if key is None else _formalize_key(key)
916
+ a = _check_py_seq(a)
917
+ if size is None:
918
+ size = u.math.shape(a)
919
+ else:
920
+ if jnp.size(a) > 1:
921
+ raise ValueError(f'"a" should be a scalar when "size" is provided. But we got {a}')
922
+ size = _size2shape(size)
923
+ dtype = dtype or environ.dftype()
924
+ random_uniform = jr.uniform(key=key, shape=size, dtype=dtype)
925
+ r = jnp.power(-jnp.log1p(-random_uniform), 1.0 / a)
926
+ return r
927
+
928
+ def weibull_min(
929
+ self,
930
+ a,
931
+ scale=None,
932
+ size: Optional[Size] = None,
933
+ key: Optional[SeedOrKey] = None,
934
+ dtype: DTypeLike = None
935
+ ):
936
+ key = self.split_key() if key is None else _formalize_key(key)
937
+ a = _check_py_seq(a)
938
+ scale = _check_py_seq(scale)
939
+ if size is None:
940
+ size = jnp.broadcast_shapes(u.math.shape(a), u.math.shape(scale) if scale is not None else ())
941
+ else:
942
+ if jnp.size(a) > 1:
943
+ raise ValueError(f'"a" should be a scalar when "size" is provided. But we got {a}')
944
+ size = _size2shape(size)
945
+ dtype = dtype or environ.dftype()
946
+ random_uniform = jr.uniform(key=key, shape=size, dtype=dtype)
947
+ r = jnp.power(-jnp.log1p(-random_uniform), 1.0 / a)
948
+ if scale is not None:
949
+ r /= scale
950
+ return r
951
+
952
+ def maxwell(
953
+ self,
954
+ size: Optional[Size] = None,
955
+ key: Optional[SeedOrKey] = None,
956
+ dtype: DTypeLike = None
957
+ ):
958
+ key = self.split_key() if key is None else _formalize_key(key)
959
+ shape = _size2shape(size) + (3,)
960
+ dtype = dtype or environ.dftype()
961
+ norm_rvs = jr.normal(key=key, shape=shape, dtype=dtype)
962
+ r = jnp.linalg.norm(norm_rvs, axis=-1)
963
+ return r
964
+
965
+ def negative_binomial(
966
+ self,
967
+ n,
968
+ p,
969
+ size: Optional[Size] = None,
970
+ key: Optional[SeedOrKey] = None,
971
+ dtype: DTypeLike = None
972
+ ):
973
+ n = _check_py_seq(n)
974
+ p = _check_py_seq(p)
975
+ if size is None:
976
+ size = lax.broadcast_shapes(u.math.shape(n), u.math.shape(p))
977
+ size = _size2shape(size)
978
+ logits = jnp.log(p) - jnp.log1p(-p)
979
+ if key is None:
980
+ keys = self.split_key(2)
981
+ else:
982
+ keys = jr.split(_formalize_key(key), 2)
983
+ rate = self.gamma(shape=n, scale=jnp.exp(-logits), size=size, key=keys[0], dtype=environ.dftype())
984
+ r = self.poisson(lam=rate, key=keys[1], dtype=dtype or environ.ditype())
985
+ return r
986
+
987
+ def wald(
988
+ self,
989
+ mean,
990
+ scale,
991
+ size: Optional[Size] = None,
992
+ key: Optional[SeedOrKey] = None,
993
+ dtype: DTypeLike = None
994
+ ):
995
+ dtype = dtype or environ.dftype()
996
+ key = self.split_key() if key is None else _formalize_key(key)
997
+ mean = u.math.asarray(_check_py_seq(mean), dtype=dtype)
998
+ scale = u.math.asarray(_check_py_seq(scale), dtype=dtype)
999
+ if size is None:
1000
+ size = lax.broadcast_shapes(u.math.shape(mean), u.math.shape(scale))
1001
+ size = _size2shape(size)
1002
+ sampled_chi2 = jnp.square(self.randn(*size))
1003
+ sampled_uniform = self.uniform(size=size, key=key, dtype=dtype)
1004
+ # Wikipedia defines an intermediate x with the formula
1005
+ # x = loc + loc ** 2 * y / (2 * conc) - loc / (2 * conc) * sqrt(4 * loc * conc * y + loc ** 2 * y ** 2)
1006
+ # where y ~ N(0, 1)**2 (sampled_chi2 above) and conc is the concentration.
1007
+ # Let us write
1008
+ # w = loc * y / (2 * conc)
1009
+ # Then we can extract the common factor in the last two terms to obtain
1010
+ # x = loc + loc * w * (1 - sqrt(2 / w + 1))
1011
+ # Now we see that the Wikipedia formula suffers from catastrphic
1012
+ # cancellation for large w (e.g., if conc << loc).
1013
+ #
1014
+ # Fortunately, we can fix this by multiplying both sides
1015
+ # by 1 + sqrt(2 / w + 1). We get
1016
+ # x * (1 + sqrt(2 / w + 1)) =
1017
+ # = loc * (1 + sqrt(2 / w + 1)) + loc * w * (1 - (2 / w + 1))
1018
+ # = loc * (sqrt(2 / w + 1) - 1)
1019
+ # The term sqrt(2 / w + 1) + 1 no longer presents numerical
1020
+ # difficulties for large w, and sqrt(2 / w + 1) - 1 is just
1021
+ # sqrt1pm1(2 / w), which we know how to compute accurately.
1022
+ # This just leaves the matter of small w, where 2 / w may
1023
+ # overflow. In the limit a w -> 0, x -> loc, so we just mask
1024
+ # that case.
1025
+ sqrt1pm1_arg = 4 * scale / (mean * sampled_chi2) # 2 / w above
1026
+ safe_sqrt1pm1_arg = jnp.where(sqrt1pm1_arg < np.inf, sqrt1pm1_arg, 1.0)
1027
+ denominator = 1.0 + jnp.sqrt(safe_sqrt1pm1_arg + 1.0)
1028
+ ratio = jnp.expm1(0.5 * jnp.log1p(safe_sqrt1pm1_arg)) / denominator
1029
+ sampled = mean * jnp.where(sqrt1pm1_arg < np.inf, ratio, 1.0) # x above
1030
+ res = jnp.where(sampled_uniform <= mean / (mean + sampled),
1031
+ sampled,
1032
+ jnp.square(mean) / sampled)
1033
+ return res
1034
+
1035
+ def t(
1036
+ self,
1037
+ df,
1038
+ size: Optional[Size] = None,
1039
+ key: Optional[SeedOrKey] = None,
1040
+ dtype: DTypeLike = None
1041
+ ):
1042
+ dtype = dtype or environ.dftype()
1043
+ df = u.math.asarray(_check_py_seq(df), dtype=dtype)
1044
+ if size is None:
1045
+ size = np.shape(df)
1046
+ else:
1047
+ size = _size2shape(size)
1048
+ _check_shape("t", size, np.shape(df))
1049
+ if key is None:
1050
+ keys = self.split_key(2)
1051
+ else:
1052
+ keys = jr.split(_formalize_key(key), 2)
1053
+ n = jr.normal(keys[0], size, dtype=dtype)
1054
+ two = _const(n, 2)
1055
+ half_df = lax.div(df, two)
1056
+ g = jr.gamma(keys[1], half_df, size, dtype=dtype)
1057
+ r = n * jnp.sqrt(half_df / g)
1058
+ return r
1059
+
1060
+ def orthogonal(
1061
+ self,
1062
+ n: int,
1063
+ size: Optional[Size] = None,
1064
+ key: Optional[SeedOrKey] = None,
1065
+ dtype: DTypeLike = None
1066
+ ):
1067
+ dtype = dtype or environ.dftype()
1068
+ key = self.split_key() if key is None else _formalize_key(key)
1069
+ size = _size2shape(size)
1070
+ _check_shape("orthogonal", size)
1071
+ n = core.concrete_or_error(index, n, "The error occurred in jax.random.orthogonal()")
1072
+ z = jr.normal(key, size + (n, n), dtype=dtype)
1073
+ q, r = jnp.linalg.qr(z)
1074
+ d = jnp.diagonal(r, 0, -2, -1)
1075
+ r = q * jnp.expand_dims(d / abs(d), -2)
1076
+ return r
1077
+
1078
+ def noncentral_chisquare(
1079
+ self,
1080
+ df,
1081
+ nonc,
1082
+ size: Optional[Size] = None,
1083
+ key: Optional[SeedOrKey] = None,
1084
+ dtype: DTypeLike = None
1085
+ ):
1086
+ dtype = dtype or environ.dftype()
1087
+ df = u.math.asarray(_check_py_seq(df), dtype=dtype)
1088
+ nonc = u.math.asarray(_check_py_seq(nonc), dtype=dtype)
1089
+ if size is None:
1090
+ size = lax.broadcast_shapes(u.math.shape(df), u.math.shape(nonc))
1091
+ size = _size2shape(size)
1092
+ if key is None:
1093
+ keys = self.split_key(3)
1094
+ else:
1095
+ keys = jr.split(_formalize_key(key), 3)
1096
+ i = jr.poisson(keys[0], 0.5 * nonc, shape=size, dtype=environ.ditype())
1097
+ n = jr.normal(keys[1], shape=size, dtype=dtype) + jnp.sqrt(nonc)
1098
+ cond = jnp.greater(df, 1.0)
1099
+ df2 = jnp.where(cond, df - 1.0, df + 2.0 * i)
1100
+ chi2 = 2.0 * jr.gamma(keys[2], 0.5 * df2, shape=size, dtype=dtype)
1101
+ r = jnp.where(cond, chi2 + n * n, chi2)
1102
+ return r
1103
+
1104
+ def loggamma(
1105
+ self,
1106
+ a,
1107
+ size: Optional[Size] = None,
1108
+ key: Optional[SeedOrKey] = None,
1109
+ dtype: DTypeLike = None
1110
+ ):
1111
+ dtype = dtype or environ.dftype()
1112
+ key = self.split_key() if key is None else _formalize_key(key)
1113
+ a = _check_py_seq(a)
1114
+ if size is None:
1115
+ size = u.math.shape(a)
1116
+ r = jr.loggamma(key, a, shape=_size2shape(size), dtype=dtype)
1117
+ return r
1118
+
1119
+ def categorical(
1120
+ self,
1121
+ logits,
1122
+ axis: int = -1,
1123
+ size: Optional[Size] = None,
1124
+ key: Optional[SeedOrKey] = None
1125
+ ):
1126
+ key = self.split_key() if key is None else _formalize_key(key)
1127
+ logits = _check_py_seq(logits)
1128
+ if size is None:
1129
+ size = list(u.math.shape(logits))
1130
+ size.pop(axis)
1131
+ r = jr.categorical(key, logits, axis=axis, shape=_size2shape(size))
1132
+ return r
1133
+
1134
+ def zipf(
1135
+ self,
1136
+ a,
1137
+ size: Optional[Size] = None,
1138
+ key: Optional[SeedOrKey] = None,
1139
+ dtype: DTypeLike = None
1140
+ ):
1141
+ a = _check_py_seq(a)
1142
+ if size is None:
1143
+ size = u.math.shape(a)
1144
+ dtype = dtype or environ.ditype()
1145
+ r = jax.pure_callback(lambda x: np.random.zipf(x, size).astype(dtype),
1146
+ jax.ShapeDtypeStruct(size, dtype),
1147
+ a)
1148
+ return r
1149
+
1150
+ def power(
1151
+ self,
1152
+ a,
1153
+ size: Optional[Size] = None,
1154
+ key: Optional[SeedOrKey] = None,
1155
+ dtype: DTypeLike = None
1156
+ ):
1157
+ a = _check_py_seq(a)
1158
+ if size is None:
1159
+ size = u.math.shape(a)
1160
+ size = _size2shape(size)
1161
+ dtype = dtype or environ.dftype()
1162
+ r = jax.pure_callback(lambda a: np.random.power(a=a, size=size).astype(dtype),
1163
+ jax.ShapeDtypeStruct(size, dtype),
1164
+ a)
1165
+ return r
1166
+
1167
+ def f(
1168
+ self,
1169
+ dfnum,
1170
+ dfden,
1171
+ size: Optional[Size] = None,
1172
+ key: Optional[SeedOrKey] = None,
1173
+ dtype: DTypeLike = None
1174
+ ):
1175
+ dfnum = _check_py_seq(dfnum)
1176
+ dfden = _check_py_seq(dfden)
1177
+ if size is None:
1178
+ size = jnp.broadcast_shapes(u.math.shape(dfnum), u.math.shape(dfden))
1179
+ size = _size2shape(size)
1180
+ d = {'dfnum': dfnum, 'dfden': dfden}
1181
+ dtype = dtype or environ.dftype()
1182
+ r = jax.pure_callback(
1183
+ lambda dfnum_, dfden_: np.random.f(dfnum=dfnum_,
1184
+ dfden=dfden_,
1185
+ size=size).astype(dtype),
1186
+ jax.ShapeDtypeStruct(size, dtype),
1187
+ dfnum, dfden
1188
+ )
1189
+ return r
1190
+
1191
+ def hypergeometric(
1192
+ self,
1193
+ ngood,
1194
+ nbad,
1195
+ nsample,
1196
+ size: Optional[Size] = None,
1197
+ key: Optional[SeedOrKey] = None,
1198
+ dtype: DTypeLike = None
1199
+ ):
1200
+ ngood = _check_py_seq(ngood)
1201
+ nbad = _check_py_seq(nbad)
1202
+ nsample = _check_py_seq(nsample)
1203
+
1204
+ if size is None:
1205
+ size = lax.broadcast_shapes(u.math.shape(ngood),
1206
+ u.math.shape(nbad),
1207
+ u.math.shape(nsample))
1208
+ size = _size2shape(size)
1209
+ dtype = dtype or environ.ditype()
1210
+ d = {'ngood': ngood, 'nbad': nbad, 'nsample': nsample}
1211
+ r = jax.pure_callback(
1212
+ lambda d: np.random.hypergeometric(
1213
+ ngood=d['ngood'],
1214
+ nbad=d['nbad'],
1215
+ nsample=d['nsample'],
1216
+ size=size
1217
+ ).astype(dtype),
1218
+ jax.ShapeDtypeStruct(size, dtype),
1219
+ d
1220
+ )
1221
+ return r
1222
+
1223
+ def logseries(
1224
+ self,
1225
+ p,
1226
+ size: Optional[Size] = None,
1227
+ key: Optional[SeedOrKey] = None,
1228
+ dtype: DTypeLike = None
1229
+ ):
1230
+ p = _check_py_seq(p)
1231
+ if size is None:
1232
+ size = u.math.shape(p)
1233
+ size = _size2shape(size)
1234
+ dtype = dtype or environ.ditype()
1235
+ r = jax.pure_callback(
1236
+ lambda p: np.random.logseries(p=p, size=size).astype(dtype),
1237
+ jax.ShapeDtypeStruct(size, dtype),
1238
+ p
1239
+ )
1240
+ return r
1241
+
1242
+ def noncentral_f(
1243
+ self,
1244
+ dfnum,
1245
+ dfden,
1246
+ nonc,
1247
+ size: Optional[Size] = None,
1248
+ key: Optional[SeedOrKey] = None,
1249
+ dtype: DTypeLike = None
1250
+ ):
1251
+ dfnum = _check_py_seq(dfnum)
1252
+ dfden = _check_py_seq(dfden)
1253
+ nonc = _check_py_seq(nonc)
1254
+ if size is None:
1255
+ size = lax.broadcast_shapes(u.math.shape(dfnum),
1256
+ u.math.shape(dfden),
1257
+ u.math.shape(nonc))
1258
+ size = _size2shape(size)
1259
+ d = {'dfnum': dfnum, 'dfden': dfden, 'nonc': nonc}
1260
+ dtype = dtype or environ.dftype()
1261
+ r = jax.pure_callback(
1262
+ lambda x: np.random.noncentral_f(dfnum=x['dfnum'],
1263
+ dfden=x['dfden'],
1264
+ nonc=x['nonc'],
1265
+ size=size).astype(dtype),
1266
+ jax.ShapeDtypeStruct(size, dtype),
1267
+ d
1268
+ )
1269
+ return r
1270
+
1271
+ # PyTorch compatibility #
1272
+ # --------------------- #
1273
+
1274
+ def rand_like(
1275
+ self,
1276
+ input,
1277
+ *,
1278
+ dtype=None,
1279
+ key: Optional[SeedOrKey] = None
1280
+ ):
1281
+ """Returns a tensor with the same size as input that is filled with random
1282
+ numbers from a uniform distribution on the interval ``[0, 1)``.
1283
+
1284
+ Args:
1285
+ input: the ``size`` of input will determine size of the output tensor.
1286
+ dtype: the desired data type of returned Tensor. Default: if ``None``, defaults to the dtype of input.
1287
+ key: the seed or key for the random.
1288
+
1289
+ Returns:
1290
+ The random data.
1291
+ """
1292
+ return self.random(u.math.shape(input), key=key).astype(dtype)
1293
+
1294
+ def randn_like(
1295
+ self,
1296
+ input,
1297
+ *,
1298
+ dtype=None,
1299
+ key: Optional[SeedOrKey] = None
1300
+ ):
1301
+ """Returns a tensor with the same size as ``input`` that is filled with
1302
+ random numbers from a normal distribution with mean 0 and variance 1.
1303
+
1304
+ Args:
1305
+ input: the ``size`` of input will determine size of the output tensor.
1306
+ dtype: the desired data type of returned Tensor. Default: if ``None``, defaults to the dtype of input.
1307
+ key: the seed or key for the random.
1308
+
1309
+ Returns:
1310
+ The random data.
1311
+ """
1312
+ return self.randn(*u.math.shape(input), key=key).astype(dtype)
1313
+
1314
+ def randint_like(
1315
+ self,
1316
+ input,
1317
+ low=0,
1318
+ high=None,
1319
+ *,
1320
+ dtype=None,
1321
+ key: Optional[SeedOrKey] = None
1322
+ ):
1323
+ if high is None:
1324
+ high = max(input)
1325
+ return self.randint(low, high=high, size=u.math.shape(input), dtype=dtype, key=key)
1326
+
1327
+
1328
+ # default random generator
1329
+ DEFAULT = RandomState(np.random.randint(0, 10000, size=2, dtype=np.uint32))
1330
+
1331
+
1332
+ # ---------------------------------------------------------------------------------------------------------------
1333
+
1334
+
1335
+ def _formalize_key(key):
1336
+ if isinstance(key, int):
1337
+ return jr.PRNGKey(key) if use_prng_key else jr.key(key)
1338
+ elif isinstance(key, (jax.Array, np.ndarray)):
1339
+ if jnp.issubdtype(key.dtype, jax.dtypes.prng_key):
1340
+ return key
1341
+ if key.size == 1 and jnp.issubdtype(key.dtype, jnp.integer):
1342
+ return jr.PRNGKey(key) if use_prng_key else jr.key(key)
1343
+
1344
+ if key.dtype != jnp.uint32:
1345
+ raise TypeError('key must be a int or an array with two uint32.')
1346
+ if key.size != 2:
1347
+ raise TypeError('key must be a int or an array with two uint32.')
1348
+ return u.math.asarray(key, dtype=jnp.uint32)
1349
+ else:
1350
+ raise TypeError('key must be a int or an array with two uint32.')
1351
+
1352
+
1353
+ def _size2shape(size):
1354
+ if size is None:
1355
+ return ()
1356
+ elif isinstance(size, (tuple, list)):
1357
+ return tuple(size)
1358
+ else:
1359
+ return (size,)
1360
+
1361
+
1362
+ def _check_shape(
1363
+ name,
1364
+ shape,
1365
+ *param_shapes
1366
+ ):
1367
+ if param_shapes:
1368
+ shape_ = lax.broadcast_shapes(shape, *param_shapes)
1369
+ if shape != shape_:
1370
+ msg = ("{} parameter shapes must be broadcast-compatible with shape "
1371
+ "argument, and the result of broadcasting the shapes must equal "
1372
+ "the shape argument, but got result {} for shape argument {}.")
1373
+ raise ValueError(msg.format(name, shape_, shape))
1374
+
1375
+
1376
+ def _is_python_scalar(x):
1377
+ if hasattr(x, 'aval'):
1378
+ return x.aval.weak_type
1379
+ elif np.ndim(x) == 0:
1380
+ return True
1381
+ elif isinstance(x, (bool, int, float, complex)):
1382
+ return True
1383
+ else:
1384
+ return False
1385
+
1386
+
1387
+ python_scalar_dtypes = {
1388
+ bool: np.dtype('bool'),
1389
+ int: np.dtype('int64'),
1390
+ float: np.dtype('float64'),
1391
+ complex: np.dtype('complex128'),
1392
+ }
1393
+
1394
+
1395
+ def _dtype(
1396
+ x,
1397
+ *,
1398
+ canonicalize: bool = False
1399
+ ):
1400
+ """Return the dtype object for a value or type, optionally canonicalized based on X64 mode."""
1401
+ if x is None:
1402
+ raise ValueError(f"Invalid argument to dtype: {x}.")
1403
+ elif isinstance(x, type) and x in python_scalar_dtypes:
1404
+ dt = python_scalar_dtypes[x]
1405
+ elif type(x) in python_scalar_dtypes:
1406
+ dt = python_scalar_dtypes[type(x)]
1407
+ elif hasattr(x, 'dtype'):
1408
+ dt = x.dtype
1409
+ else:
1410
+ dt = np.result_type(x)
1411
+ return dtypes.canonicalize_dtype(dt) if canonicalize else dt
1412
+
1413
+
1414
+ def _const(
1415
+ example,
1416
+ val
1417
+ ):
1418
+ if _is_python_scalar(example):
1419
+ dtype = dtypes.canonicalize_dtype(type(example))
1420
+ val = dtypes.scalar_type_of(example)(val)
1421
+ return val if dtype == _dtype(val, canonicalize=True) else np.array(val, dtype)
1422
+ else:
1423
+ dtype = dtypes.canonicalize_dtype(example.dtype)
1424
+ return np.array(val, dtype)
1425
+
1426
+
1427
+ @partial(jit, static_argnums=(2,))
1428
+ def _categorical(
1429
+ key,
1430
+ p,
1431
+ shape
1432
+ ):
1433
+ # this implementation is fast when event shape is small, and slow otherwise
1434
+ # Ref: https://stackoverflow.com/a/34190035
1435
+ shape = shape or p.shape[:-1]
1436
+ s = jnp.cumsum(p, axis=-1)
1437
+ r = jr.uniform(key, shape=shape + (1,))
1438
+ return jnp.sum(s < r, axis=-1)
1439
+
1440
+
1441
+ def _scatter_add_one(
1442
+ operand,
1443
+ indices,
1444
+ updates
1445
+ ):
1446
+ return lax.scatter_add(
1447
+ operand,
1448
+ indices,
1449
+ updates,
1450
+ lax.ScatterDimensionNumbers(
1451
+ update_window_dims=(),
1452
+ inserted_window_dims=(0,),
1453
+ scatter_dims_to_operand_dims=(0,),
1454
+ ),
1455
+ )
1456
+
1457
+
1458
+ def _reshape(x, shape):
1459
+ if isinstance(x, (int, float, np.ndarray, np.generic)):
1460
+ return np.reshape(x, shape)
1461
+ else:
1462
+ return jnp.reshape(x, shape)
1463
+
1464
+
1465
+ def _promote_shapes(
1466
+ *args,
1467
+ shape=()
1468
+ ):
1469
+ # adapted from lax.lax_numpy
1470
+ if len(args) < 2 and not shape:
1471
+ return args
1472
+ else:
1473
+ shapes = [u.math.shape(arg) for arg in args]
1474
+ num_dims = len(lax.broadcast_shapes(shape, *shapes))
1475
+ return [
1476
+ _reshape(arg, (1,) * (num_dims - len(s)) + s) if len(s) < num_dims else arg
1477
+ for arg, s in zip(args, shapes)
1478
+ ]
1479
+
1480
+
1481
+ @partial(jit, static_argnums=(3, 4))
1482
+ def _multinomial(
1483
+ key,
1484
+ p,
1485
+ n,
1486
+ n_max,
1487
+ shape=()
1488
+ ):
1489
+ if u.math.shape(n) != u.math.shape(p)[:-1]:
1490
+ broadcast_shape = lax.broadcast_shapes(u.math.shape(n), u.math.shape(p)[:-1])
1491
+ n = jnp.broadcast_to(n, broadcast_shape)
1492
+ p = jnp.broadcast_to(p, broadcast_shape + u.math.shape(p)[-1:])
1493
+ shape = shape or p.shape[:-1]
1494
+ if n_max == 0:
1495
+ return jnp.zeros(shape + p.shape[-1:], dtype=jnp.result_type(int))
1496
+ # get indices from categorical distribution then gather the result
1497
+ indices = _categorical(key, p, (n_max,) + shape)
1498
+ # mask out values when counts is heterogeneous
1499
+ if jnp.ndim(n) > 0:
1500
+ mask = _promote_shapes(jnp.arange(n_max) < jnp.expand_dims(n, -1), shape=shape + (n_max,))[0]
1501
+ mask = jnp.moveaxis(mask, -1, 0).astype(indices.dtype)
1502
+ excess = jnp.concatenate([jnp.expand_dims(n_max - n, -1),
1503
+ jnp.zeros(u.math.shape(n) + (p.shape[-1] - 1,))],
1504
+ -1)
1505
+ else:
1506
+ mask = 1
1507
+ excess = 0
1508
+ # NB: we transpose to move batch shape to the front
1509
+ indices_2D = (jnp.reshape(indices * mask, (n_max, -1))).T
1510
+ samples_2D = vmap(_scatter_add_one)(
1511
+ jnp.zeros((indices_2D.shape[0], p.shape[-1]), dtype=indices.dtype),
1512
+ jnp.expand_dims(indices_2D, axis=-1),
1513
+ jnp.ones(indices_2D.shape, dtype=indices.dtype)
1514
+ )
1515
+ return jnp.reshape(samples_2D, shape + p.shape[-1:]) - excess
1516
+
1517
+
1518
+ @partial(jit, static_argnums=(2, 3), static_argnames=['shape', 'dtype'])
1519
+ def _von_mises_centered(
1520
+ key,
1521
+ concentration,
1522
+ shape,
1523
+ dtype=None
1524
+ ):
1525
+ """Compute centered von Mises samples using rejection sampling from [1]_ with wrapped Cauchy proposal.
1526
+
1527
+ Returns
1528
+ -------
1529
+ out: array_like
1530
+ centered samples from von Mises
1531
+
1532
+ References
1533
+ ----------
1534
+ .. [1] Luc Devroye "Non-Uniform Random Variate Generation", Springer-Verlag, 1986;
1535
+ Chapter 9, p. 473-476. http://www.nrbook.com/devroye/Devroye_files/chapter_nine.pdf
1536
+
1537
+ """
1538
+ shape = shape or u.math.shape(concentration)
1539
+ dtype = dtype or environ.dftype()
1540
+ concentration = lax.convert_element_type(concentration, dtype)
1541
+ concentration = jnp.broadcast_to(concentration, shape)
1542
+
1543
+ if dtype == jnp.float16:
1544
+ s_cutoff = 1.8e-1
1545
+ elif dtype == jnp.float32:
1546
+ s_cutoff = 2e-2
1547
+ elif dtype == jnp.float64:
1548
+ s_cutoff = 1.2e-4
1549
+ else:
1550
+ raise ValueError(f"Unsupported dtype: {dtype}")
1551
+
1552
+ r = 1.0 + jnp.sqrt(1.0 + 4.0 * concentration ** 2)
1553
+ rho = (r - jnp.sqrt(2.0 * r)) / (2.0 * concentration)
1554
+ s_exact = (1.0 + rho ** 2) / (2.0 * rho)
1555
+
1556
+ s_approximate = 1.0 / concentration
1557
+
1558
+ s = jnp.where(concentration > s_cutoff, s_exact, s_approximate)
1559
+
1560
+ def cond_fn(
1561
+ *args
1562
+ ):
1563
+ """check if all are done or reached max number of iterations"""
1564
+ i, _, done, _, _ = args[0]
1565
+ return jnp.bitwise_and(i < 100, jnp.logical_not(jnp.all(done)))
1566
+
1567
+ def body_fn(
1568
+ *args
1569
+ ):
1570
+ i, key, done, _, w = args[0]
1571
+ uni_ukey, uni_vkey, key = jr.split(key, 3)
1572
+ u_ = jr.uniform(
1573
+ key=uni_ukey,
1574
+ shape=shape,
1575
+ dtype=concentration.dtype,
1576
+ minval=-1.0,
1577
+ maxval=1.0,
1578
+ )
1579
+ z = jnp.cos(jnp.pi * u_)
1580
+ w = jnp.where(done, w, (1.0 + s * z) / (s + z)) # Update where not done
1581
+ y = concentration * (s - w)
1582
+ v = jr.uniform(key=uni_vkey, shape=shape, dtype=concentration.dtype)
1583
+ accept = (y * (2.0 - y) >= v) | (jnp.log(y / v) + 1.0 >= y)
1584
+ return i + 1, key, accept | done, u_, w
1585
+
1586
+ init_done = jnp.zeros(shape, dtype=bool)
1587
+ init_u = jnp.zeros(shape)
1588
+ init_w = jnp.zeros(shape)
1589
+
1590
+ _, _, done, uu, w = lax.while_loop(
1591
+ cond_fun=cond_fn,
1592
+ body_fun=body_fn,
1593
+ init_val=(jnp.array(0), key, init_done, init_u, init_w),
1594
+ )
1595
+
1596
+ return jnp.sign(uu) * jnp.arccos(w)
1597
+
1598
+
1599
+ def _loc_scale(
1600
+ loc,
1601
+ scale,
1602
+ value
1603
+ ):
1604
+ if loc is None:
1605
+ if scale is None:
1606
+ return value
1607
+ else:
1608
+ return value * scale
1609
+ else:
1610
+ if scale is None:
1611
+ return value + loc
1612
+ else:
1613
+ return value * scale + loc
1614
+
1615
+
1616
+ def _check_py_seq(seq):
1617
+ return u.math.asarray(seq) if isinstance(seq, (tuple, list)) else seq