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