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