
    ukit             	         d dl mZ d dlmZmZ d dlmZ d dlZd dlm	Z	 d dl
Z
d dl
mZ d dlZd dlZd dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZ d dl m!Z! d dl m"Z" d dl m#Z# d dl$m%Z& d dl$m'Z' d dl$m(Z) d dl*m+Z, d dl*m-Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4 d dlm5Z5 d dl6m7Z7m8Z8m9Z9m:Z: d dl;m<Z< e8Z=e8Z>e:Z?e:Z@e:ZAeeB   ZCej                  ZDej                  ZEddZFdd 	 	 	 dd!ZGd" ZHdd$ZId% ZJ G d& d'      ZKeeLeKeDef   ZMdd(ZN	 	 	 	 dd)ZOdd*	 	 	 dd+ZPdd*	 	 	 dd,ZQdd-ZRdDdd.ZSdDdd/ZTdd0ZUdd1ZVdd2ZWdd3ZXdd4ZYdd*	 dd5ZZdd6Z[d7 Z\	 	 ddd8	 	 	 	 	 dd9Z]d: Z^	 	 	 	 ddd8	 	 	 	 	 	 	 	 	 dd;Z_ ed<=      dd>       Z`dd?Za	 ddd8	 	 	 	 	 	 	 	 	 dd@Zb ed<=      ddA       Zc	 	 ddd8	 	 	 	 	 	 	 ddBZddC Ze edD=      ddE       Zf	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddHZg	 	 ddd8	 	 	 	 	 ddIZh edJ=      ddK       Zi edJ=      ddL       Zj	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddMZk edN=      ddO       Zl	 	 ddd8	 	 	 	 	 	 	 	 	 ddPZm ed<=      ddQ       Zn	 	 	 ddd8	 	 	 	 	 	 	 ddRZo ed#dGgS      ddT       Zp	 	 d	 	 	 	 	 	 	 	 	 ddUZqddVZr	 	 d	 	 	 	 	 ddWZs edJ=      ddX       Zt	 	 d	 	 	 	 	 	 	 ddYZu edZ=      dd[       Zv	 	 d	 	 	 	 	 dd\Zw edJ=      dd]       Zxdd^Zyd_ Zzdd`daZ{db Z| ej                  dc      Z~e~j                  e{       dd Ze~j                  e        e!j                  e~dde         e#j                  e~ e#j                   ee{dF`      df              e#j                  e~ e#j                   ee{dF`      df      dgh       e|e"j
                  e~<   	 	 d	 	 	 	 	 	 	 ddiZ	 	 d	 	 	 	 	 	 	 ddjZ edkS      dddl       Z edm=      ddn       Z edm=      ddo       Z edZ=      ddp       Z	 	 d	 	 	 	 	 	 	 ddqZ	 	 	 ddd8	 	 	 	 	 	 	 ddrZ eds=      ddt       Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dduZ	 	 d	 	 	 	 	 ddvZ edJ=      ddw       Z	 	 d	 	 	 	 	 ddxZ edJ=      dy        Z	 	 d	 	 	 	 	 	 	 ddzZ edZ=      dd{       Z	 	 d	 	 	 	 	 	 	 dd|Z edZ=      dd}       Z	 	 d	 	 	 	 	 	 	 dd~Z edZ=      dd       Z	 	 d	 	 	 	 	 	 	 	 	 ddZ ed<=      dd       Z	 	 d	 	 	 	 	 ddZ edJ=      dd       Z	 	 d	 	 	 	 	 ddZ edJ=      dd       Z	 	 d	 	 	 	 	 	 	 	 	 ddZ ed<=      dd       Z	 	 d	 	 	 	 	 	 	 	 	 ddZ ed<=      dd       Z	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 ddZ edZ=      dd       Z	 	 d	 	 	 	 	 	 	 ddZ edZ=      dd       Z	 	 d	 	 	 	 	 	 	 ddZ edZ=      dd       Z	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ eddF      dd       Z ej^                  d      ddf	 	 	 	 	 	 	 ddZ edZdF      dd       Zd Z edNdF      d        Z edNdF      d        Z ed<dF      dd       Z	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ ej                  d      Z ejp                  e       ej                  d         e"jr                  e        e#j                  ed        dddd	 	 	 	 	 	 	 	 	 	 	 ddZd Zd Zy)    )annotations)HashableSequence)partialN)index)Union)config)core)dispatch)dtypes)numpy)prng)
xla_bridge)get_abstract_mesh)NamedShardingPartitionSpec)jitvmap)ad)batching)mlir)control_flow)lax)special)einsum)linalg)
_arraylikecheck_arraylikepromote_dtypes_inexact)	auto_axes)canonicalize_sharding)Array	ArrayLikeDType	DTypeLike)canonicalize_axisc                .    t        j                  | |       S N)r   nexs    J/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/random.py_isnanr-   D   s    	1    Fallow_batchedc                   t        |t              r4t        j                  |j                  t        j
                        r|}d}nt        |      rt        j                  |t                     }d}t        j                  j                  t        j                  j                  k(  rt        d      t        j                  j                  t        j                  j                   k(  rt#        j$                  dd       nLt        j&                  j                  r2t#        j$                  dt(               nt+        dt-        |             |s0|j.                  r$t        |  d	t1        j2                  |       d
      ||fS )NFimplTzLegacy uint32 key array passed as key to jax.random function. Please create keys using jax.random.key(). If use of a raw key array was intended, set jax_legacy_prng_key="allow".   )
stacklevelzjRaw arrays as random keys to jax.random functions are deprecated. Assuming valid threefry2x32 key for now.zunexpected PRNG key type z: accepts a single key, but was given a key array of shape " != (). Use jax.vmap for batching.)
isinstancer"   r   
issubdtypedtypeprng_keyr   r   random_wrapdefault_prng_implr	   legacy_prng_keyvalueLegacyPrngKeyStateERROR
ValueErrorWARNwarningswarnenable_custom_prngFutureWarning	TypeErrortypendimnpshape)namekeyr0   wrapped_keywrappeds        r,   _check_prng_keyrP   H   s<   U 1 1#))V__ MKG#""3->-@AKG##v'@'@'F'FF	9: : 
			%	%)B)B)G)G	Gmm	9EFH 
	"	"	(	(mm5

 /S	{;
<<
[--
v !xx}o-OQ R R 
g	r.   c                    t        j                  |j                  t         j                        sJ t        j
                  j                  r|S | rt        j                  |      S |S r(   )	r   r8   r9   r:   r	   rE   r>   r   random_unwrap)was_wrappedrM   s     r,   _return_prng_keysrT   k   sL    			399foo	66	6$$J&14c":s:r.   rK   c                    t        j                  | j                  t         j                        sJ t	        j
                  | ||      S )N	bit_widthrK   )r   r8   r9   r:   r   random_bits)rM   rW   rK   s      r,   _random_bitsrY   t   s5    			399foo	66	6			#%	@@r.   c                     t         j                  j                  } | t        j                  v sJ |        t        j                  |    S )zGet the default PRNG implementation.

  The default implementation is determined by ``config.jax_default_prng_impl``,
  which specifies it by name.
  )r	   r<   r>   r   prngs)	impl_names    r,   r<   r<   {   s;     &&,,)	djj	 +)+	 	I	r.   c                  H    e Zd ZU dZdgZded<   d Zd
dZd
dZddZ	ddZ
y	)PRNGSpecz$Specifies a PRNG key implementation._implPRNGImplc                    || _         y r(   )r_   )selfr3   s     r,   __init__zPRNGSpec.__init__   s	    DJr.   c                6    d| j                   j                  dS )Nz	PRNGSpec())r_   rL   rb   s    r,   __repr__zPRNGSpec.__repr__   s    tzz)++r.   c                ,    t        | j                        S r(   )strr_   rf   s    r,   __str__zPRNGSpec.__str__   s    tzz?r.   c                ,    t        | j                        S r(   )hashr_   rf   s    r,   __hash__zPRNGSpec.__hash__   s    

r.   c                X    t        |t              xr | j                  |j                  k(  S r(   )r7   r^   r_   )rb   others     r,   __eq__zPRNGSpec.__eq__   s!    eX&D4::+DDr.   N)returnri   )rq   int)rq   bool)__name__
__module____qualname____doc__	__slots____annotations__rc   rg   rj   rm   rp    r.   r,   r^   r^      s+    ,i)	/,Er.   r^   c                   | 
t               S t        |       t        u r| S t        |       t        u r| j                  S t        |       t
        u rk| t        j                  v rt        j                  |    S dj                  d t        j                  j                         D              }t        d|  d| d      t        |       }t        d| d      )Nz, c              3  (   K   | ]
  }d | d   yw)"Nrz   ).0ss     r,   	<genexpr>z$resolve_prng_impl.<locals>.<genexpr>   s     =a1QCq=s   z"unrecognized PRNG implementation "z". Did you mean one of: ?zunrecognized type z$ for specifying PRNG implementation.)r<   rH   r`   r^   r_   ri   r   r[   joinkeysrA   rG   )	impl_speckeys_fmtts      r,   resolve_prng_implr      s    	)_ 
 	)_ ??	)_DJJZZ	""yy=4::??+<==H
9) E--5Ja9 : : 9o!&qc)MNOOr.   c                H   t        |      }t        |d      r<t        j                  |j                  t        j
                        rt        |  d      t        j                  |      r$t        |  dt        j                  |       d      t        j                  ||      S )Nr9   z1 accepts a scalar seed, but was given a PRNG key.z8 accepts a scalar seed, but was given an array of shape z! != (). Use jax.vmap for batchingr2   )r   hasattrr   r8   r9   r:   rG   rJ   rI   rK   r   random_seed)	ctor_nameseedr   r3   s       r,   _keyr      s    	9	%$T7 1 1$**foo N
+FGI IWWT]
+ $  A	CD D 
		$T	**r.   r2   c                   t        d| |      S )ai  Create a pseudo-random number generator (PRNG) key given an integer seed.

  The result is a scalar array containing a key, whose dtype indicates
  the default PRNG implementation, as determined by the optional
  ``impl`` argument or, otherwise, by the ``jax_default_prng_impl``
  config flag at the time when this function is called.

  Args:
    seed: a 64- or 32-bit integer used as the value of the key.
    impl: optional string specifying the PRNG implementation (e.g.
      ``'threefry2x32'``)

  Returns:
    A scalar PRNG key array, consumable by random functions as well as ``split``
    and ``fold_in``.
  rM   )r   r   r3   s     r,   rM   rM      s    $ 
eT4	  r.   c               0    t        dt        d| |            S )a  Create a legacy PRNG key given an integer seed.

  This function produces old-style legacy PRNG keys, which are arrays
  of dtype ``uint32``. For more, see the note in the `PRNG keys
  <https://docs.jax.dev/en/latest/jax.random.html#prng-keys>`_
  section. When possible, :func:`jax.random.key` is recommended for
  use instead.

  The resulting key does not carry a PRNG implementation. The returned
  key matches the implementation given by the optional ``impl``
  argument or, otherwise, determined by the ``jax_default_prng_impl``
  config flag. Callers must ensure that same implementation is set as
  the default when passing this key as an argument to other functions
  (such as ``jax.random.split`` and ``jax.random.normal``).

  Args:
    seed: a 64- or 32-bit integer used as the value of the key.
    impl: optional string specifying the PRNG implementation (e.g.
      ``'threefry2x32'``)

  Returns:
    A PRNG key, consumable by random functions as well as ``split``
    and ``fold_in``.
  TPRNGKey)rT   r   r   s     r,   r   r      s    4 
4it!<	==r.   c                    t        d|       \  } }t        j                  |      r"t        dt        j                  |       d      t        j                  | t        j                  |d            }t        ||      S )ac  Folds in data to a PRNG key to form a new PRNG key.

  Args:
    key: a PRNG key (from ``key``, ``split``, ``fold_in``).
    data: a 32-bit integer representing data to be folded into the key.

  Returns:
    A new PRNG key that is a deterministic function of the inputs and is
    statistically safe for producing a stream of new pseudo-random values.
  fold_inz9fold_in accepts a scalar, but was given an array ofshape r6   uint32r9   )
rP   rJ   rI   rG   rK   r   random_fold_injnpasarrayrT   )rM   datarO   key_outs       r,   r   r      st     !C0,#wWWT]
 XXd^,,NP Q QS[[X%FG'	7G	,,r.   c                   t        j                  | j                  t         j                        sJ | j                  rt        d| j                   d      t        |t              rt        |      n|f}t        j                  | |      S )Nz?split accepts a single key, but was given a key array of shape r6   rK   )r   r8   r9   r:   rI   rG   rK   r7   r   tupler   random_split)rM   numrK   s      r,   _splitr     sx     
		399foo	66	6XX
  YYK'IK L L"31%*v%			3e	,,r.   c                L    t        d|       \  }}t        |t        ||            S )aK  Splits a PRNG key into `num` new keys by adding a leading axis.

  Args:
    key: a PRNG key (from ``key``, ``split``, ``fold_in``).
    num: optional, a positive integer (or tuple of integers) indicating
      the number (or shape) of keys to produce. Defaults to 2.

  Returns:
    An array-like object of `num` new PRNG keys.
  split)rP   rT   r   )rM   r   	typed_keyrO   s       r,   r   r     s)     'w4)W	7F9c$:	;;r.   c                    t        j                  | j                  t         j                        sJ t	        j
                  t        j                  | j                        }|j                  S r(   )	r   r8   r9   r:   typingcastr   KeyTyr_   )r   
keys_dtypes     r,   	_key_implr   (  sD    			4::v	77	7{{4::tzz2*			r.   c                ~    t        |       }|j                  t        j                  v r|j                  S t	        |      S r(   )r   rL   r   r[   r^   )r   r3   s     r,   	_key_specr   -  s-    	4$ii4::-A8D>Ar.   c                :    t        d| d      \  }}t        |      S )Nkey_implTr/   )rP   r   )r   
typed_keys_s      r,   r   r   1  s    !*d$G-*a	:	r.   c                    t        j                  | j                  t         j                        sJ t	        j
                  |       S r(   )r   r8   r9   r:   r   rR   )r   s    r,   	_key_datar   6  s1    			4::v	77	7			D	!!r.   c                :    t        d| d      \  } }t        |       S )z9Recover the bits of key data underlying a PRNG key array.key_dataTr/   )rP   r   )r   r   s     r,   r   r   :  s    JDA'$	4r.   c               F    t        |      }t        j                  | |      S )a  Wrap an array of key data bits into a PRNG key array.

  Args:
    key_bits_array: a ``uint32`` array with trailing shape corresponding to
      the key shape of the PRNG implementation specified by ``impl``.
    impl: optional, specifies a PRNG implementation, as in ``random.key``.

  Returns:
    A PRNG key array, whose dtype is a subdtype of ``jax.dtypes.prng_key``
      corresponding to ``impl``, and whose shape equals the leading shape
      of ``key_bits_array.shape`` up to the key bit dimensions.
  r2   )r   r   r;   )key_bits_arrayr3   impl_objs      r,   wrap_key_datar   @  s!     t$(			.x	88r.   c                |    |r:t        j                  |g| }||k7  rd}t        |j                  | ||            y y )Nz{} parameter shapes must be broadcast-compatible with shape argument, and the result of broadcasting the shapes must equal the shape argument, but got result {} for shape argument {}.)r   broadcast_shapesrA   format)rL   rK   param_shapesshape_msgs        r,   _check_shaper   U  sM    !!%7,7FLc szz$677	  r.   c                f    t        | fi |}||S t        |||j                  j                        S )N)out_shardingaxes)r   r    meshexplicit_axes)fr   hoist_kwargsf_s       r,   maybe_auto_axesr   _  s<    q!L!"IRl&++99; ;r.   )r   c               p   t        d|       \  } }|t        j                         }nt        j                  |      }t        j                  |t
        j                        st        d|       t        j                  |      }t        |d|      }|j                  dz  } t        t        |||      |       S )a  Sample uniform bits in the form of unsigned integers.

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ``()``.
    dtype: optional, an unsigned integer dtype for the returned values (default
      ``uint64`` if ``jax_enable_x64`` is true, otherwise ``uint32``).

  Returns:
    A random array with the specified shape and dtype.
  bitsz<dtype argument to `bits` must be an unsigned int dtype, got    rV   )rP   r   default_uint_dtype!check_and_canonicalize_user_dtyper8   rJ   unsignedintegerrA   r
   canonicalize_shape"canonicalize_sharding_for_samplersitemsizer   rY   )rM   rK   r9   r   r   rW   s         r,   r   r   h  s    " 63'&#q
]%%'E44U;E			5""4"4	5
 !7$ % %

!
!%
(%3L&%P,nnq )
;|#,E
;;>
@ @r.   c                z    t        | |      } t               }|j                  r| |st        |t	                     } | S r(   )r!   r   are_all_axes_explicitr   P)r   rL   rK   cur_meshs       r,   r   r     s:    &|T:, (##(<U 13/L	r.   c               8   t        d|       \  } }t        j                  |t        n|      }t	        j
                  |      }t        |d|      }t        j                  |t        j                        st        d|        t        t        |||      | ||      S )a  Sample uniform random values in [minval, maxval) with given shape/dtype.

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).
    minval: optional, a minimum (inclusive) value broadcast-compatible with shape for the range (default 0).
    maxval: optional, a maximum (exclusive) value broadcast-compatible with shape for the range (default 1).

  Returns:
    A random array with the specified shape and dtype.
  uniformz7dtype argument to `uniform` must be a float dtype, got rK   r9   )rP   r   r   floatr
   r   r   r8   rJ   floatingrA   r   _uniform)rM   rK   r9   minvalmaxvalr   r   s          r,   r   r     s    * 9c*&#q

2
2}e%)%

!
!%
(%3L)US,			5"++	.
 !7$ % %
3<$E
336
H Hr.   )      )static_argnumsc           	        t        d|       t        j                  |t        j                        st        d      t        j                  ||      }t        j                  ||      }t        j                  |t        |            }t        j                  |t        |            }t        j                  |      }|j                  |j                  }}|dvrt        d| d      |}|dk  rd}t        | ||      }	t        |   }
||k7  rt        j                  |	|
      }	t        j                  |	t!        j"                  ||z
  |
            }t        j$                  |t!        j&                  t        j"                  d|      j)                  |j*                        |j*                              }t        j,                  ||      t!        j"                  d|      z
  }t        j.                  |t        j0                  |||z
  z  |z   |            S )	Nr   z+uniform only accepts floating point dtypes.r          @   z7uniform only accepts 8-, 16-, 32-, or 64-bit dtypesgot .r         ?r   )r   r   r8   rJ   r   rG   r   convert_element_typebroadcast_to_ranklenfinfor   nmantrY   UINT_DTYPESshift_right_logicalr   array
bitwise_orr   viewr9   bitcast_convert_typemaxreshape)rM   r   r   rK   r9   r   nbitsr   rng_bitsr   
uint_dtype
float_bitsfloatss                r,   r   r     s   y% 			5"++	.
A
BB##FE2&##FE2&  U4&  U4&
,,u
%U[[%
/!

A%J  (
QYH	c8U	+$5!*##D*5D &&
CIIh&
35*~~ 
kk"((3&++J,<,<="((*+* ##J62u9MM&		kk&FVO,v5u=
? ?r.   c           	        t        | t              sJ t        j                  |t        j
                        r.t        j                  | j                  t        j
                        st        d      t        j                  | t        t        j                  |      j                  t        j                  | j                        j                              }t        j                  | t        t        j                  |      j                  t        j                  | j                        j                              }t        j                  | ||      j                  |      S )a  
  Convert integer-typed val to specified integer dtype, clipping to dtype
  range rather than wrapping.

  Args:
    val: value to be converted
    dtype: dtype of output

  Returns:
    equivalent of val in new dtype

  Examples
  --------
  Normal integer type conversion will wrap:

  >>> val = jnp.uint32(0xFFFFFFFF)
  >>> val.astype('int32')
  Array(-1, dtype=int32)

  This function clips to the values representable in the new type:

  >>> _convert_and_clip_integer(val, 'int32')
  Array(2147483647, dtype=int32)
  z6_convert_and_clip_integer only accepts integer dtypes.)r7   r"   r   r8   rJ   integerr9   rG   r   _constr   iinfominr   clipastype)valr9   min_valmax_vals       r,   _convert_and_clip_integerr    s    2 
C		


E2::
.63D3DSYYPRPZPZ3[
L
MMJJsCU 3 7 7 &SYY 7 ; ;= >'JJsCU 3 7 7!'cii!8!<!<> ?'	#w	(	/	/	66r.   c                  t        d|       \  } }t        j                  |t        n|      }t	        j
                  |      }t        |d|      }t        j                  |t        j                        st        d|       t        j                  j                  rt        j                  |      }|}|j                  dk  rt        j                   d      }t#        j$                  |      j'                  d      j)                  t        |j*                        t        |j,                              }t#        j$                  |      j'                  d      j)                  t        |j*                        t        |j,                        dz         } t/        t0        |||      | ||      j'                  |      S  t/        t0        |||      | ||      S )a  Sample uniform random values in [minval, maxval) with given shape/dtype.

  Args:
    key: a PRNG key used as the random key.
    shape: a tuple of nonnegative integers representing the shape.
    minval: int or array of ints broadcast-compatible with ``shape``, a minimum
      (inclusive) value for the range.
    maxval: int or array of ints broadcast-compatible with ``shape``, a maximum
      (exclusive) value for the range.
    dtype: optional, an int dtype for the returned values (default int64 if
      jax_enable_x64 is true, otherwise int32).

  Returns:
    A random array with the specified shape and dtype.

  .. note::

     :func:`randint` uses a modulus-based computation that is known to produce
     slightly biased values in some cases. The magnitude of the bias scales as
     ``(maxval - minval) * ((2 ** nbits ) % (maxval - minval)) / 2 ** nbits``:
     in words, the bias goes to zero when ``(maxval - minval)`` is a power of 2,
     and otherwise the bias will be small whenever ``(maxval - minval)`` is
     small compared to the range of the sampled type.

     To reduce this bias, 8-bit and 16-bit values will always be sampled at 32-bit and
     then cast to the requested type. If you find yourself sampling values for which
     this bias may be problematic, a possible alternative is to sample via uniform::

       def randint_via_uniform(key, shape, minval, maxval, dtype):
         u = jax.random.uniform(key, shape, minval=minval - 0.5, maxval=maxval - 0.5)
         return u.round().astype(dtype)

     But keep in mind this method has its own biases due to floating point rounding
     errors, and in particular there may be some integers in the range
     ``[minval, maxval)`` that are impossible to produce with this approach.
  randint)randint only accepts integer dtypes, got r   int32   r   )rP   r   r   rr   r
   r   r   r8   rJ   r   rG   r	   safer_randintr>   r   r   r9   r   r   r   r   r   r   r   _randint)	rM   rK   r   r   r9   r   r   infodtype_for_samplings	            r,   r  r    ss   V 9c*&#q

2
2]c'%

!
!%
(%3L)US,			5"**	-
?wG
HH <<Dyy2~88G,{{6"))'277DHHs488}Uf{{6"))'277DHHs488}WXGXYfY?8\FXYVV#VE]+ 
K<uE	J	66
 r.   c           
     Z   t        dt        j                  |      t        j                  |             t        j                  |t        j
                        st        d|       t        d||       t        j                  |      }t        j                  |      }t        j                  |j                  t        j
                        s|j                  t              }t        j                  |j                  t        j
                        s|j                  t              }t        j                  |t        t        j                   t        j"                  |      j$                  |      |j                              }t        ||      }t        ||      }t        j&                  |t)                    }t        j&                  |t)                    }t        j"                  |      j*                  dvrt        d|       t-        |       \  }}fd} ||       ||      }
}	t.           }t        j0                  ||z
  |      }t        j2                  ||k  t        j4                  |d      |      }t        j2                  |||kD  z  t        j6                  |t        j8                  |d            |      }t        j:                  t        j8                  |ddz  z        |      }t        j:                  t        j<                  ||      |      }t        j6                  t        j<                  t        j:                  |	|      |      t        j:                  |
|            }t        j:                  ||      }t        j6                  |t        j0                  ||            S )Nr  r  r   z9randint only accepts 8-, 16-, 32-, or 64-bit dtypes, got c                    t        |       S r(   )rY   )rM   r   rK   s    r,   <lambda>z_randint.<locals>.<lambda>y  s    l3u5 r.   r  r4   )r   rJ   rK   r   r8   r   rG   r   r   r   r9   r   rr   r   gtr  r   r   r   r   r   r   r   r   r   select	full_likeaddr   remmul)rM   r   r   rK   r9   maxval_out_of_rangek1k2rbitshigher_bits
lower_bitsunsigned_dtypespan
multiplierrandom_offsetr   s      `           @r,   r
  r
  H  s   & y%&!1288F3CD			5"**	-
?wG
HH)VV,;;v&;;v&			6<<	4]]3F			6<<	4]]3F 
%ciiU0C0G0G&OQWQ]Q]^` %VU3&$VU3&  U4&  U4&
,,u

"
"%
/!
OPUwW
XX
 #;&"b
5%!"IuRyz+u%.		!	!&6/>	B$ 
Ff$cmmD!&<d	C$
 
6F?+GGD#**T1%&

$ wwszz$eqj(9:DA*wwswwz:6=*''#''#''+t"<jI''*d35-''-.-	11-G	HHr.   c                  t        d|       \  } }t        d|       t        t        j                  |      xs d      t        |d      }t        j                  |      sst        j                  t        j                  |      t        j                        st        d      t        j                  t        |d       t        fd|      |       S  t        t        ||      | |      S )a  Returns a randomly permuted array or range.

  Args:
    key: a PRNG key used as the random key.
    x: int or array. If x is an integer, randomly shuffle np.arange(x).
      If x is an array, randomly shuffle its elements.
    axis: int, optional. The axis which x is shuffled along. Default is 0.
    independent: bool, optional. If set to True, each individual vector along
      the given axis is shuffled independently. Default is False.

  Returns:
    A shuffled version of x or array range
  permutationr  z.x must be an integer or at least 1-dimensionalz&argument x of jax.random.permutation()c                D    t        | t        j                              S r(   )_shuffler   arange)rM   axisrs    r,   r  zpermutation.<locals>.<lambda>  s    xSZZ]D'I r.   )r%  independent)rP   r   r&   rJ   rI   r!   r8   r   r9   r   rG   r
   concrete_or_errorrr   r   _permutation)rM   r+   r%  r'  r   r   r&  s     `   @r,   r!  r!    s    & =#.&#q-#	4q	1$&|]C,	==1rzz2FGGsA'OPA)?I')),. .
FLt
FFI1
N Nr.   c                    |st        j                  |      dk(  rt        | ||      S t        | t        j                  |j
                  |         d      }t        j                  |||d      S )Nr  r   T)unique_indices)rJ   rI   r#  r   r$  rK   take)rM   r+   r%  r'  inds        r,   r)  r)    sV    BGGAJ!OCD!!cjj/3#	!S$t	44r.   r4   c                ,   d}t        j                  t        j                        j                  }t        j                  |j                        st        d|j                         t        t        j                  |t        j                  t	        d|j                              z  t        j                  |      z              }t        |      D ]A  }t        |       \  } }t        |d|j                        }t!        j"                  |||      \  }}C |S )Nr   zSshape polymorphism for `permutation` or `shuffle` for arrays of non-constant size: r  r   )r   r   rJ   r   r   r
   is_constant_dimsizeNotImplementedErrorrr   ceillogranger   rY   rK   r   sort_key_val)	rM   r+   r%  exponent	uint32max
num_roundsr   subkey	sort_keyss	            r,   r#  r#    s      (ll299%)))			aff	%
	--.VVH	67 7 2778bffSAFF^&<<rvvi?PPQR* 0a+KCVR1IIq$/DAq0
 
(r.   Tmodec                   t        d|       \  } }t        |t              st        d|       t	        d|       t        j                  |      }|j                  dk(  rt        j                  t        |d      }	n%t        ||j                        }|j                  |   }	t        j                  |      }
|
dk(  r!t        j                  ||j                         S |	dk  rt#        d      |s|
|	kD  rt#        d|
 d|	 d	      |y|r8t%        | |d|	      }|j                  dk(  r|nt        j&                  |||      }nkt)        d
      f|z  t)        |
      fz   }t+        | |j                  dk(  r|	n||      |   }n,t	        d|       t-        |      \  }|j                  |	fk7  rt#        d|j                   d|	 d      |r`t        j.                  |      }|d   dt1        | ||j                         z
  z  }t        j2                  ||      j5                  t              }n]t7        | |	f|j                   |      t        j8                  |      z   }t;        j<                  ||
      d   j5                  t              }|j                  dk(  r|nt        j&                  |||      }|j?                  |j                  dk(  r|      S |j                  d| tA        |      z   |j                  |dz   d
 z         S )aS  Generates a random sample from a given array.

  .. warning::
    If ``p`` has fewer non-zero elements than the requested number of samples,
    as specified in ``shape``, and ``replace=False``, the output of this
    function is ill-defined. Please make sure to use appropriate inputs.

  Args:
    key: a PRNG key used as the random key.
    a : array or int. If an ndarray, a random sample is generated from
      its elements. If an int, the random sample is generated as if a were
      arange(a).
    shape : tuple of ints, optional. Output shape.  If the given shape is,
      e.g., ``(m, n)``, then ``m * n`` samples are drawn.  Default is (),
      in which case a single value is returned.
    replace : boolean.  Whether the sample is with or without replacement.
      Default is True.
    p : 1-D array-like, The probabilities associated with each entry in a.
      If not given the sample assumes a uniform distribution over all
      entries in a.
    axis: int, optional. The axis along which the selection is performed.
      The default, 0, selects by row.
    mode: optional, "high" or "low" for how many bits to use in the gumbel sampler
      when `p is None` and `replace = False`. The default is determined by the
      ``use_high_dynamic_range_gumbel`` config, which defaults to "low". With mode="low",
      in float32 sampling will be biased for choices with probability less than about
      1E-7; with mode="high" this limit is pushed down to about 1E-14. mode="high"
      approximately doubles the cost of sampling.

  Returns:
    An array of shape `shape` containing samples from `a`.
  choicez<shape argument of jax.random.choice must be a sequence, got r   z)The error occurred in jax.random.choice()r   z4a must be greater than 0 unless no samples are takenz"Cannot take a larger sample (size z) than population (size z) when 'replace=False'NzOp must be None or a 1D vector with the same size as a.shape[axis]. p has shape z and a.shape[axis] is r   r  )r9   r<  )k)!rP   r7   r   rG   r   r   r   rI   r
   r(  rr   r&   rK   mathprodzerosr9   rA   r  r,  slicer!  r   cumsumr   searchsortedr   gumbelr4  r   top_kr   r   )rM   arK   replacepr%  r<  r   arrn_inputsn_drawsr-  resultslicesp_arrp_cumlr&  gs                     r,   r>  r>    s   N 8S)&#q	E8	$
  '# $ $(AA#XX]%%c1.YZHT388,DyyHIIe'\99U#)),,]
K
LL	Wx'

,WI 6$:%;	=> > YC8,chh!ms#sD)Afd~$g'88f3CHHMsDI&QfHa #A&FE{{xk!%;H:QHI I zz% f
*GCfllCC
DaVQ'..s3c xk4
@3775>
QaIIa7#A&--c2cHHMSsxxS$'?F	Q 
O O		!D)E%L8399T!VW;MM
O Or.   c               4   t        d|       \  } }t        j                  |      }t        |d|      }t	        j
                  |t        n|      }t	        j                  |t        j                        st        d|        t        t        |||      |       S )aY  Sample standard normal random values with given shape and float dtype.

  The values are returned according to the probability density function:

  .. math::
     f(x) = \frac{1}{\sqrt{2\pi}}e^{-x^2/2}

  on the domain :math:`-\infty < x < \infty`

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  normalzAdtype argument to `normal` must be a float or complex dtype, got r   )rP   r
   r   r   r   r   r   r8   rJ   inexactrA   r   _normal)rM   rK   r9   r   r   s        r,   rU  rU  7  s    0 8S)&#q

!
!%
(%3L(ER,

2
2}e%)%			5"**	-
 !7$ % %	I,e5	I#	NNr.   )r  r4   c                   t        j                  |t        j                        rt        j                  t        j
                  d      |      }t        |       \  }}t        j                  d|      j                  j                  }t        |||      j                  |      }t        |||      j                  |      }|d|z  z   |z  S t        | ||      S )Nr4   r   y              ?)r   r8   rJ   complexfloatingr   sqrtr   realr9   _normal_realr   )	rM   rK   r9   sqrt2key_rekey_im
real_dtype_re_ims	            r,   rW  rW  Y  s    ub001HHRWWQZ'EC[NFF!U#((..J
vuj
1
8
8
?C
vuj
1
8
8
?C"s(Ne##UE**r.   c                   t        d|       t        j                  t        j                  d|      t        j                  d|      |      }t        j                  d|      }t	        | ||||      }t        j                  t        j                  t        j                  d      |      t        j                  |            S )NrU                r   r   r4   )
r   rJ   	nextafterr   r   r   r  rZ  lax_specialerf_inv)rM   rK   r9   lohius         r,   r\  r\  f  s    x	||BHHS%("((2u*=UK"	xxE"c5%R(!	"''!*e,k.A.A!.D	EEr.   c                V   t        d|       \  } }t        ||      \  }}|dvrt        d      ||j                  }nt	        j
                  |      }t	        j                  |t        j                        st        d|       |t        j                  |      }t        | |||||      S )a0  Sample multivariate normal random values with given mean and covariance.

  The values are returned according to the probability density function:

  .. math::
     f(x;\mu, \Sigma) = (2\pi)^{-k/2} \det(\Sigma)^{-1}e^{-\frac{1}{2}(x - \mu)^T \Sigma^{-1} (x - \mu)}

  where :math:`k` is the dimension, :math:`\mu` is the mean (given by ``mean``) and
  :math:`\Sigma` is the covariance matrix (given by ``cov``).

  Args:
    key: a PRNG key used as the random key.
    mean: a mean vector of shape ``(..., n)``.
    cov: a positive definite covariance matrix of shape ``(..., n, n)``. The
      batch shape ``...`` must be broadcast-compatible with that of ``mean``.
    shape: optional, a tuple of nonnegative integers specifying the result
      batch shape; that is, the prefix of the result shape excluding the last
      axis. Must be broadcast-compatible with ``mean.shape[:-1]`` and
      ``cov.shape[:-2]``. The default (None) produces a result batch shape by
      broadcasting together the batch shapes of ``mean`` and ``cov``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).
    method: optional, a method to compute the factor of ``cov``.
      Must be one of 'svd', 'eigh', and 'cholesky'. Default 'cholesky'. For
      singular covariance matrices, use 'svd' or 'eigh'.
  Returns:
    A random array with the specified dtype and shape given by
    ``shape + mean.shape[-1:]`` if ``shape`` is not None, or else
    ``broadcast_shapes(mean.shape[:-1], cov.shape[:-2]) + mean.shape[-1:]``.
  multivariate_normal>   svdeighcholeskyz1method must be one of {'svd', 'eigh', 'cholesky'}zCdtype argument to `multivariate_normal` must be a float dtype, got )rP   r   rA   r9   r   r   r8   rJ   r   r
   r   _multivariate_normal)rM   meancovrK   r9   methodr   s          r,   rm  rm  o  s    H 0#6&#q$T3/)$..
H
II
]JJE44U;E			5"++	.
 ##('+ , ,
##E*E	c4eUF	CCr.   )r   r      c                z   t        j                  |      dk\  s/d}t        |j                  t        j                  |                  t        j                  |      dk\  s/d}t        |j                  t        j                  |                  |j                  d   }t        j                  |      dd  ||fk7  r1d}t        |j                  |t        j                  |                  |1t        j                  |j                  d d |j                  d d       }n(t        d	||j                  d d |j                  d d        |d
k(  r:t        j                  |      \  }}	}
|t        j                  |	dd d d f         z  }nS|dk(  r9t        j                  |      \  }}|t        j                  |dd d d f         z  }nt        j                  |      }t        | ||j                  dd  z   |      }t        j                   d      5  |t#        j$                  d||      z   }d d d        |S # 1 sw Y   S xY w)Nr  z@multivariate_normal requires mean.ndim >= 1, got mean.ndim == {}r4   z>multivariate_normal requires cov.ndim >= 2, got cov.ndim == {}r?  z^multivariate_normal requires cov.shape == (..., n, n) for n={n}, but got cov.shape == {shape}.)nrK   rU  rn  .ro  allowz...ij,...j->...i)rJ   rI   rA   r   rK   r   r   r   
jnp_linalgrn  r   rZ  ro  rp  rU  r	   numpy_rank_promotion
jnp_einsumr   )rM   rr  rs  rK   r9   rt  r   rx  rk  r   r   factorwvnormal_samplesrO  s                   r,   rq  rq    s   	!	
LC
SZZ.
//		
JC
SZZ-
..
jjn!XXc]23Aq6!+C
SZZ!288C=Z9
::
]  CR#))CR.AE5$**Sb/399Sb>Bu_s#IQ1!CqL/**F__S!FQ!CqL/**F  %F#utzz"#6>.""7+ RJ%%&8&.QQFR	-R	-s   H00H:c               :   |t        j                  |      }t        d|       \  } }t        |d      }t	        j
                  |t        n|      }t	        j                  |t        j                        st        d|        t        t        |||      | ||      S )a  Sample truncated standard normal random values with given shape and dtype.

  The values are returned according to the probability density function:

  .. math::
     f(x) \propto e^{-x^2/2}

  on the domain :math:`\rm{lower} < x < \rm{upper}`.

  Args:
    key: a PRNG key used as the random key.
    lower: a float or array of floats representing the lower bound for
      truncation. Must be broadcast-compatible with ``upper``.
    upper: a float or array of floats representing the  upper bound for
      truncation. Must be broadcast-compatible with ``lower``.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``lower`` and ``upper``. The
      default (None) produces a result shape by broadcasting ``lower`` and
      ``upper``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and shape given by ``shape`` if
    ``shape`` is not None, or else by broadcasting ``lower`` and ``upper``.
    Returns values in the open interval ``(lower, upper)``.
  truncated_normalz@dtype argument to `truncated_normal` must be a float dtype, got r   )r
   r   rP   r!   r   r   r   r8   rJ   r   rA   r   _truncated_normal)rM   lowerupperrK   r9   r   r   s          r,   r  r    s    B ##E*E-s3&#q&|5GH,

2
2}e%)%			5"++	.
 ##('+ , ,
3*L$E
336u
F Fr.   c                   |=t        j                  t        j                  |      t        j                  |            }n4t	        d|t        j                  |      t        j                  |             t        j
                  t        j                  d      |      }t        j                  ||      }t        j                  ||      }t        j                  ||z        }t        j                  ||z        }t        j                  |t        j                        st        d      t        | ||||      }|t        j                  |      z  }	t!        j"                  |	t        j$                  t        j&                  |      t        j
                  t        j(                  |            t        j$                  t        j&                  |      t        j
                  t        j(                   |                  S )Nr  r4   z4truncated_normal only accepts floating point dtypes.r   r   r   )r   r   rJ   rK   r   r   rZ  r   rg  erfr   r8   r   rG   r   rh  r   r   rf  stop_gradientinf)
rM   r  r  rK   r9   r]  rI  brk  outs
             r,   r  r    sY   
]  %"((5/BE#UBHHUORXXe_M
((2771:u
%%

"
"5%
0%

"
"5%
0%ooeem$!ooeem$!			5"++	.
J
KKc5%!4!##A&&# 
		mmC%%e,bhhrvvU.KL	mmC%%e,bhhwe.LM
O Or.   c                  |t        j                  |      }|dvrt        d|d      t        d|       \  } }t	        |d      }t        j                  |      }t        j                  |t        j                        sd}t        |j                  |            t        j                  ||      } t        t        |||      | |      S )aT  Sample Bernoulli random values with given shape and mean.

  The values are distributed according to the probability mass function:

  .. math::
     f(k; p) = p^k(1 - p)^{1 - k}

  where :math:`k \in \{0, 1\}` and :math:`0 \le p \le 1`.

  Args:
    key: a PRNG key used as the random key.
    p: optional, a float or array of floats for the mean of the random
      variables. Must be broadcast-compatible with ``shape``. Default 0.5.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Must be broadcast-compatible with ``p.shape``. The default (None)
      produces a result shape equal to ``p.shape``.
    mode: optional, "high" or "low" for how many bits to use when sampling.
      default='low'. Set to "high" for correct sampling at small values of
      `p`. When sampling in float32, bernoulli samples with mode='low' produce
      incorrect results for p < ~1E-7. mode="high" approximately doubles the
      cost of sampling.

  Returns:
    A random array with boolean dtype and shape given by ``shape`` if ``shape``
    is not None, or else ``p.shape``.
  highlowz	got mode=z, expected 'high' or 'low'	bernoulliz=bernoulli probability `p` must have a floating dtype, got {}.)rK   r<  )r
   r   rA   rP   r!   r   r9   r   r8   rJ   r   rG   r   r   r   
_bernoulli)rM   rK  rK   r<  r   r   r9   r   s           r,   r  r    s    > ##E*E	 
zD7"<=
>>;,&#q&|[A,
))A,%			5"++	.
IC
CJJu%
&&	q%(!
1\$4
114a
9 9r.   )static_argnamesc                p   |t        j                  |      }n t        d|t        j                  |             t        j                  |      }|dk(  rBt        | dg||      \  }}|dt        j                  |      j                   z  z  }|||z
  k  S t        | |t        j                  |            |k  S )Nr  r  r4   )	rJ   rK   r   r   r9   r   r   r   r   )rM   rK  rK   r<  r9   u1u2s          r,   r  r  6  s    
]HHQKEeRXXa[1
))A,%	V^S1+u+u-FB!U#)))
))BB;3syy|,q00r.   c                
   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | ||||      S )a
  Sample Beta random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x;a,b) \propto x^{a - 1}(1 - x)^{b - 1}

  on the domain :math:`0 \le x \le 1`.

  Args:
    key: a PRNG key used as the random key.
    a: a float or array of floats broadcast-compatible with ``shape``
      representing the first parameter "alpha".
    b: a float or array of floats broadcast-compatible with ``shape``
      representing the second parameter "beta".
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``a`` and ``b``. The default
      (None) produces a result shape by broadcasting ``a`` and ``b``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and shape given by ``shape`` if
    ``shape`` is not None, or else by broadcasting ``a`` and ``b``.
  betaz4dtype argument to `beta` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _beta)rM   rI  r  rK   r9   r   s         r,   r  r  H  s    < 63'&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	sAq%	''r.   c                   |=t        j                  t        j                  |      t        j                  |            }n4t	        d|t        j                  |      t        j                  |             t        d| ||      \  } \  }}t        j                  ||      }t        j                  ||      }t        |       \  }}t        j                  ||      }t        j                  ||      }t        ||||      }t        ||||      }t        j                  ||      }	t        j                  ||	z
        }
t        j                  ||	z
        }|
|
|z   z  S )Nr  zjax.random.beta)r   r   rJ   rK   r   random_insert_pvaryr   r   r   broadcast_tologgammar   exp)rM   rI  r  rK   r9   key_akey_blog_gamma_alog_gamma_blog_maxgamma_a_scaledgamma_b_scaleds               r,   r  r  q  s   
]  !bhhqk:ERXXa[9#$5sAqA+#v1	q%(!	q%(!,%	q% !	q% !5%0+5%0+GGK-'77;01.77;01.	>N:	;;r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||      S )aK  Sample Cauchy random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x) \propto \frac{1}{x^2 + 1}

  on the domain :math:`-\infty < x < \infty`

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  cauchyz6dtype argument to `cauchy` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _cauchyrM   rK   r9   r   s       r,   r  r    s|    , 8S)&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	eU	##r.   c                ^   t        d|       t        | ||t        j                  |      j                  d      }t        j                  |t        j                        }t        j                  t        j                  |t        j                  |t        j                  |d                        S )Nr  r   r        ?)r   r   r   r   epsr   r   rJ   pitanr  sub)rM   rK   r9   rk  r  s        r,   r  r    sq    xc5%U(;(?(?K!
zz!RUU"	SWWQ

1c(:;<	==r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a  Sample Dirichlet random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(\{x_i\}; \{\alpha_i\}) \propto \prod_{i=1}^k x_i^{\alpha_i - 1}

  Where :math:`k` is the dimension, and :math:`\{x_i\}` satisfies

  .. math::
     \sum_{i=1}^k x_i = 1

  and :math:`0 \le x_i \le 1` for all :math:`x_i`.

  Args:
    key: a PRNG key used as the random key.
    alpha: an array of shape ``(..., n)`` used as the concentration
      parameter of the random variables.
    shape: optional, a tuple of nonnegative integers specifying the result
      batch shape; that is, the prefix of the result shape excluding the last
      element of value ``n``. Must be broadcast-compatible with
      ``alpha.shape[:-1]``. The default (None) produces a result shape equal to
      ``alpha.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and shape given by
    ``shape + (alpha.shape[-1],)`` if ``shape`` is not None, or else
    ``alpha.shape``.
  	dirichletz9dtype argument to `dirichlet` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   
_dirichlet)rM   alpharK   r9   r   s        r,   r  r    s    F ;,&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	Cu	--r.   )r4   r   c                   ddl m} t        j                  |      dk\  s/d}t	        |j                  t        j                  |                  |t        j                  |      d d }n#t        d|t        j                  |      d d        t        j                  ||      }t        | ||t        j                  |      dd  z   |      } ||d      S )Nr   )softmaxr  z8dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}r?  r  )jax._src.nn.functionsr  rJ   rI   rA   r   rK   r   r   r   r  )rM   r  rK   r9   r  r   log_gamma_sampless          r,   r  r    s    +	1	
DC
SZZ/
00
]HHUOCR EeRXXe_Sb%9:

"
"5%
0% sE5288E?233G+GO	"B	''r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||      S )a<  Sample Exponential random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x) = e^{-x}

  on the domain :math:`0 \le x < \infty`.

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  exponentialz;dtype argument to `exponential` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _exponentialr  s       r,   r  r    s|    , =#.&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	c5%	((r.   c                    t        d|       t        | ||      }t        j                  t        j                  t        j                  |                  S )Nr  )r   r   r   neglog1prM   rK   r9   rk  s       r,   r  r    s:    }e$c5% !	3771:&	''r.   c                6   t        j                  |d      t        j                  |d      t        j                  |d      }t        j                  |d      t        j                  |d      t        j                  |d      }t        j                  |d      t        j                  |      t        j                  t        t        j                  |      j                              t        j                  t        t        j                  |      j                              t        j                  t        t        j                  |      j                              t        j                  |t        t        j                  |      j                              }t        j                  |      }|}t        j                  ||t        j                  |            }t        j                  ||      t        j                  |t        j                              fd}fd	}t        |       \  } }	t        j                   ||| |f      \  }
}
}}
|rt        j"                  t%        |	d
            }t        j                  ||dk(  z  t        j&                  |t        j                  |                  }t        j                  t        j                  t        j(                        t        j(                  |            |      S dt+        |	d
      z
  }t        j                  |t        j,                  |t        j                  |                  }t        j&                  t        j&                  |      |      S )Nr   r  r4   r?  r  gUUUUUU?gm{?c                   | \  }}}}t        j                  t        j                  |t        j                  t        j                  	t        j                  ||                        t        j                  t        j
                  |      t        j                  t        j                  |      t        j                  t        j                  t        j                  |      t        j
                  |                                    }|S r(   )r   bitwise_andger  r  r4  r  )
kXVUr   XVUconddoneone_over_twosqueeze_consts
         r,   _cond_fnz_gamma_one.<locals>._cond_fn8  s    JAq!Q ??q#''#sww}cggamDEFswwqz3773771l#;#&771cggcggc1o69ggaj/B $CD 	EFD
 Kr.   c                &   fd}| d   }t        |d      \  }}}t        j                  fd||f      \  }}}t        j                  ||      }t        j                  t        j                  ||      |      }	t        |d      }
|||	|
fS )Nc                    | d   }t        |      \  }}t        |d      }t        j                  t        j                  |            }|||fS )Nr   rz   r   )r   rU  r   r  r  )kxvrM   r:  r+   r  cr9   r  s        r,   	_next_kxvz/_gamma_one.<locals>._body_fn.<locals>._next_kxvE  sM    Fc3Kkc6
5
)a
''#swwq!}
%a!QYr.   r   r   c                6    t        j                  | d         S )Nr4   )r   le)r  zeros    r,   r  z._gamma_one.<locals>._body_fn.<locals>.<lambda>N  s    cffSVT6J r.   rz   r   )r   lax_control_flow
while_loopr   r  r   )r  r  rM   x_keyU_keyr   r+   r  r  r  r  r  r9   	minus_oner  r  s              r,   _body_fnz_gamma_one.<locals>._body_fnD  s     q'CsAC))*J*3eT95MOGAq!1A1q!Ar'A1a<r.   rz   r   )r   r   r9   r
   pvaryr   typeofvmar  r  r  r  divrZ  r   r  r  r  r  r  r4  r   pow)rM   r  	log_spacetwoone_over_three
boost_mask
alpha_origr  r  r:  r   r  log_samples	log_boostsamplesboostr  r  r9   r  r  r  r  r  s                   @@@@@@@@r,   
_gamma_oner    s    
E1	$

5!#

5!#jj#)E3',::eW-.**UF+-
))E
%	D%E 2 6 67	8$

3dkk%04456#jjE$++e*<*@*@$AB)

3dkk%04456# vveS!**
**Zs(;
<%	gge^$!	ggnchhqk*!
 $ s+#v**3c3/1*!Q1''+fb>?K

:)9:D77;Z0HIKI773773771:swwqz2I>>'&"E22GJJz3wwwZ(@ACE773771a=%((r.   c                  t        j                  | d      }t        j                  |d      }|rt        j                  |      }t        j                  | d      }t        j
                  |t        j                  |j                        j                        }t        j                  t        j                  ||      ||      }d nt        j                  t        j                         j                   dk(  rt#        j$                  fd||f      }n t'              ||      }|j                  t)        j*                  |            S )Nr?  r   c                4    t        j                  | |      |z  S r(   )rg  random_gamma_grad)r  samples     r,   r  z_gamma_grad.<locals>.<lambda>p  s    %%eV4v= r.   cpuc                     |  S r(   rz   )args
gamma_grads    r,   r  z_gamma_grad.<locals>.<lambda>u  s    j$.? r.   )r   r   r   r  r   r  r   r   r9   tinyr  eqrg  r  r   get_backendplatformr  mapr   rJ   rK   )	r  rI  r  r  alphasr  r  gradsr  s	           @r,   _gamma_gradr  e  s    KK#';;q"& gggG::fa D==&,,w}}"="B"BCDjj.g>G?J ..J&&%/  !?&'ARSEDVW-E	rxx{	##r.   )use_vmapc                  t        j                  |      }t        j                  || j                  d        }| j                         } t        t        d      ||      }|j                         }|j                         }|r=t        |       t        j                  u r" t        t        t                    ||      }nt        j                  fd||f      }t        j                   ||      S )N)r   N)in_axesr  c                    t        | diS )Nr  )r  )r  r  s    r,   r  z_gamma_impl.<locals>.<lambda>  s    Z;; r.   )rJ   rK   rA  rB  rI   flattenr   r   r   r   threefry_prng_implr   r  r  r  r   r   )	rM   rI  r  r  a_shapesplit_countr   r  r  s	     `      r,   _gamma_implr  z  s    HHQK'		'#((),-+	$	(fi	({	;$	$99;&)C.D$;$;;<d7:;<T6JG"";dF^MG 
Wg	&&r.   c                   | \  }}|\  }}t        d t        | |      D              }t        j                  |||      }t        j                  |||      }t        j                  |||      dfS )Nc              3  F   K   | ]  \  }}|	|j                   |     y wr(   r   )r~   r   is      r,   r   z'_gamma_batching_rule.<locals>.<genexpr>  s'      MQamaggajMs   
!!r  r   )nextzipr   bdim_at_frontrandom_gamma_pbind)batched_args
batch_dimsr  r@  rI  bkbar1  s           r,   _gamma_batching_ruler    sz    	$!Q&"b	 M z:M 
M$QD)!QD)!			QY		7	::r.   random_gammac                4    t        j                  d| |       |S )Nr  )r
   standard_vma_rule)rM   rI  r   s      r,   _random_gamma_abstract_evalr    s    a0	
(r.   c                "    | t        ||fi |z  S r(   )r  )tangentansrM   rI  kwdss        r,   r  r    s    ;sA3N3N)N r.   )multiple_resultsr  )r  c                
   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a  Sample Gamma random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x;a) \propto x^{a - 1} e^{-x}

  on the domain :math:`0 \le x < \infty`, with :math:`a > 0`.

  This is the standard gamma density, with a unit scale/rate parameter.
  Dividing the sample output by the rate is equivalent to sampling from
  *gamma(a, rate)*, and multiplying the sample output by the scale is equivalent
  to sampling from *gamma(a, scale)*.

  Args:
    key: a PRNG key used as the random key.
    a: a float or array of floats broadcast-compatible with ``shape``
      representing the parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``a``. The default (None)
      produces a result shape equal to ``a.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``a.shape``.

  See Also:
    loggamma : sample gamma values in log-space, which can provide improved
      accuracy for small values of ``a``.
  gamma5dtype argument to `gamma` must be a float dtype, got r   rP   r   r   r   r8   rJ   r   rA   r
   r   _gammarM   rI  rK   r9   r   s        r,   r  r    s    H 7C(&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	Qe5	11r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||d      S )aV  Sample log-gamma random values with given shape and float dtype.

  This function is implemented such that the following will hold for a
  dtype-appropriate tolerance::

    np.testing.assert_allclose(jnp.exp(loggamma(*args)), gamma(*args), rtol=rtol)

  The benefit of log-gamma is that for samples very close to zero (which occur frequently
  when `a << 1`) sampling in log space provides better precision.

  Args:
    key: a PRNG key used as the random key.
    a: a float or array of floats broadcast-compatible with ``shape``
      representing the parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``a``. The default (None)
      produces a result shape equal to ``a.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``a.shape``.

  See Also:
    gamma : standard gamma sampler.
  r  r  TrK   r9   r  r  r  s        r,   r  r    s    > :s+&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	Qe5D	AAr.   r!  c                N   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        j                  |      |k7  rt        j                  ||      }t        d| |      \  } \  }t        j                  | ||      S )Nr  r  )
rJ   rK   r   r   r   r   r  r  r
  r  )rM   rI  rK   r9   r  s        r,   r  r     s    
]HHQKE%!-	q%(!XXa[EE"A!'32)#t			S!y		99r.   )r4   r   r   c                    fd}fd}t        j                  d|      }t        j                  dt        j                        }t	        j
                  ||d|| |f      d   }	|	dz
  j                  |      S )Nc                    | \  }}}}t        |      \  }}t        j                  | kD  |dz   |      }t        |t        j
                        }|dz   |||t        j                  |      z   fS Nr  )r   r   r  r   rJ   float32r   r4  )	carryr  r@  rnglog_prodr:  rk  lamrK   s	          r,   body_fnz_poisson_knuth.<locals>.body_fn  sl    Aq#x+KC

8sd?AE1-Arzz*Aq5!S(SWWQZ///r.   c                L    | d   | d   }}| kD  j                         |k  z  S )Nr   r   any)r'  r  r)  r*  	max_iterss      r,   cond_fnz_poisson_knuth.<locals>.cond_fn  s2    (E!HxAtO  "a)m44r.   r   r  )r   r  rJ   r&  r  r  r   )
rM   r*  rK   r9   r/  r+  r0  k_initlog_rate_initr@  s
    `` `     r,   _poisson_knuthr3    sq    05 ==a.&--Q

E:-!!'7Q]4STUVW!
a%	r.   c                  
 t        j                        ddt        j                        z  z   ddz  z   
dddz
  z  z   dd	d
z
  z  z
  
fd}fd}t        j                  dj                        }t        j                  dt        j                  d            }t        j                  ||d||| f      d   }	|	j                  |      S )Ngn?=
ףp=@gh|?5g[	m?g$~?gr?g333333@gr鷯?gB>٬@r4   c                (   | \  }}}}t        |d      \  }}}t        |j                        dz
  }t        |j                        }dt        |      z
  }	t	        j
                  dz  |	z  z   |z  z   dz         }
t	        j                  |z  |	|	z  z  z   z        } |
z  z   t        j                  |
dz         z
  }|	dk\  |k  z  }|
dk  |	dk  ||	kD  z  z  }||k  }|| |z  z  }t	        j                  ||
|      }||z  }|dz   |||fS )	Nr   r  r4   gQ?r  Q?r   g9v?)
r   r   r9   absr   floorr4  rg  lgammar  )r'  r  k_outacceptedrM   subkey_0subkey_1rk  r  	u_shiftedr@  r   r   accept1rejectaccept2acceptrI  r  	inv_alphar*  log_lamrK   v_rs                    r,   r+  z#_poisson_rejection.<locals>.body_fn0  sF   #Auh$S!nC8%+c1A%+Ac!fI		1q59$q(A-3d:;AIi)&;!<q!@ABA	q7{[//A66AD Q#X.G!eU*q9}=>F1fG')*FJJvq%(EHq5%3&&r.   c                @    | \  }}}}| j                         |k  z  S r(   r-  )r'  r  r;  r<  rM   r/  s        r,   r0  z#_poisson_rejection.<locals>.cond_fnF  s)    #AuhI??I..r.   r?  Frs   r   r  )	r   r4  rZ  r  r9   rJ   r  r  r   )rM   r*  rK   r9   r/  r+  r0  r1  r<  r@  rI  r  rD  rE  rF  s    `` `     @@@@@r,   _poisson_rejectionrH  %  s    
 GGCL'dSXXc]""!w{!vS)))1q5!!#' ',/ ==b#))U3&]]3rxx'7?(!!'7Q#4NOPQR!	
%r.   c                   t        |      |dk  z  }t        j                  ||t        j                  |d            }t        j                  |t        j                  |d      |      }|j	                  t        j                  |      j                        }t        j                  |t        | ||||      t        | ||||            }t        j                  |dk(  t        j                  |      |      S )N
   re  g     j@r   )r-   r   r  r  rH   r   r   r   r3  rH  r   
zeros_like)	rM   r*  rK   r9   	use_knuth	lam_knuthlam_rejectionr/  rO  s	            r,   _poissonrO  P  s     SkS2X&)jjCsC)@A) **Yc3(?E-jje,001)::3	5%;sM5%C&
 
C1HcnnV4f	==r.   c                   t        d|       \  } }t        j                  |t        n|      }t	        j
                  t        j                  | j                        }|j                  }|t        j                  urt        d|       |t        j                  |      }nt        j                  |      }t!        j"                  ||      }t%        j&                  |t        j(                        }t+        | |||      S )a\  Sample Poisson random values with given shape and integer dtype.

  The values are distributed according to the probability mass function:

  .. math::
     f(k; \lambda) = \frac{\lambda^k e^{-\lambda}}{k!}

  Where `k` is a non-negative integer and :math:`\lambda > 0`.

  Args:
    key: a PRNG key used as the random key.
    lam: rate parameter (mean of the distribution), must be >= 0. Must be broadcast-compatible with ``shape``
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default (None) produces a result shape equal to ``lam.shape``.
    dtype: optional, a integer dtype for the returned values (default int64 if
      jax_enable_x64 is true, otherwise int32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape is not None, or else by ``lam.shape``.
  poissonz<`poisson` is only implemented for the threefry2x32 RNG, not )rP   r   r   rr   r   r   r   r   r9   r_   r   r2  r
   r   rJ   rK   r   r  r   r   r&  rO  )rM   r*  rK   r9   r   r   r   s          r,   rQ  rQ  e  s    2 9c*&#q

2
2]c'% {{4::syy1*(T,,,
	j	  ##E*EHHSMEe$#  bjj1#	#sE5	))r.   c                  t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }|t        j                  j                  rdnd}|dvrt        d|z        t        |d|      } t        t        ||||      |       S )a  Sample Gumbel random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x) = e^{-(x + e^{-x})}

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).
    mode: optional, "high" or "low" for how many bits to use when sampling.
      The default is determined by the ``use_high_dynamic_range_gumbel`` config,
      which defaults to "low". When drawing float32 samples, with mode="low" the
      uniform resolution is such that the largest possible gumbel logit is ~16;
      with mode="high" this is increased to ~32, at approximately double the
      computational cost.

  Returns:
    A random array with the specified shape and dtype.
  rG  z6dtype argument to `gumbel` must be a float dtype, got r  r  r  z*Must provide valid mode for gumbel got: %s)rK   r9   r<  )rP   r   r   r   r8   rJ   r   rA   r
   r   r	   use_high_dynamic_range_gumbelr>   r   r   _gumbel)rM   rK   r9   r<  r   r   s         r,   rG  rG    s    : 8S)&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	\99??6UD	 
ADH
II3L(ER,
$,e5"
$$'
) )r.   )r  r4   r   c                   t        d|       t        j                  |      }|dk(  r|t        | ddd|z   |      \  }}t	        j
                  |dk\  ||d|j                   z  |z  z   |j                  z         }t	        j                  t	        j                  |               S t	        j                  t	        j                  t        | |j                  d||                    S )	NrG  r  re  r   r.  )r   r   rK   r9   r  r4   )
r   r   r   r   r   wherer   r  r4  r  )rM   rK   r9   r<  r  r  r  r+   s           r,   rT  rT    s    x	e	$	V^R#e|5:ID# 			$#+tqdjjM!C''$))3	5AGGSYYr]N###GGSWWTYYreLN N O O Or.   c                   t        d|       \  } }t        d|       t        j                  |      }t	        t        j                  |j                  |            }||}n"t        j                  |      }t        d||       |dt        |      t        |      z
   }	|r|dk\  r|t        |j                        z  }t        |t        |      t        |      z
  d       }
|
j                  |t        |j                        z  |j                  |          t        j                  t        | g |	|
|j                   |      t#        j$                  |t	        t'        t        |	                        z   |      S |t        | |j                  |j                   |      z  }t)        j*                  |	      }||j                  |   kD  rt-        d| d|j                  |    d      t#        j.                  t        j0                  ||d	      |      \  }}|j                  ||fz   k(  sJ ||	|z   k(  sJ |j2                  d
z
  gt'        |j2                  d
z
        }t#        j4                  |||      }|j                  |k(  sJ |S )a  Sample random values from categorical distributions.

  Sampling with replacement uses the Gumbel max trick. Sampling without replacement uses
  the Gumbel top-k trick. See [1] for reference.

  Args:
    key: a PRNG key used as the random key.
    logits: Unnormalized log probabilities of the categorical distribution(s) to sample from,
      so that `softmax(logits, axis)` gives the corresponding probabilities.
    axis: Axis along which logits belong to the same categorical distribution.
    shape: Optional, a tuple of nonnegative integers representing the result shape.
      Must be broadcast-compatible with ``np.delete(logits.shape, axis)``.
      The default (None) produces a result shape equal to ``np.delete(logits.shape, axis)``.
    replace: If True (default), perform sampling with replacement. If False, perform
      sampling without replacement.
    mode: optional, "high" or "low" for how many bits to use in the gumbel sampler.
      The default is determined by the ``use_high_dynamic_range_gumbel`` config,
      which defaults to "low". With mode="low", in float32 sampling will be biased
      for events with probability less than about 1E-7; with mode="high" this limit
      is pushed down to about 1E-14. mode="high" approximately doubles the cost of
      sampling.

  Returns:
    A random array with int dtype and shape given by ``shape`` if ``shape``
    is not None, or else ``np.delete(logits.shape, axis)``.

  References:
    .. [1] Wouter Kool, Herke van Hoof, Max Welling. "Stochastic Beams and Where to Find
      Them: The Gumbel-Top-k Trick for Sampling Sequences Without Replacement".
      Proceedings of the 36th International Conference on Machine Learning, PMLR
      97:3499-3508, 2019. https://proceedings.mlr.press/v97/kool19a.html.
  categoricalNr   )r<  r%  z'Number of samples without replacement (z&) cannot exceed number of categories (z).r?  r  )rP   r   r   r   r   rJ   deleterK   r
   r   r   r   listinsertargmaxrG  r9   r   expand_dimsr5  rA  rB  rA   rH  moveaxisrI   r   )rM   logitsr%  rK   rJ  r<  r   
logits_arrbatch_shapeshape_prefixlogits_shaper@  indices
dimensionss                 r,   rX  rX    sZ   P =#.&#q-({{6"*bii
 0 0$78+
]E##E*E{33E
3{#334,qy
c*""##dc%j3{+;;<=>Ls:#3#344j6F6Ft6LM::s2l2\2J4D4D4P
E%L0A*B$CD	E 
 &j..
0@0@tLLJ		,A:D!!
1! 5!''-.b	2 
 3<<
D"=qAJAw==K1$....L;....,,"=U7<<!+;%<=Jkk'5*5G==E!!!Nr.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||      S )a  Sample Laplace random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
    f(x) = \frac{1}{2}e^{-|x|}

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  laplacez7dtype argument to `laplace` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _laplacer  s       r,   rh  rh    s|    ( 9c*&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	#ue	$$r.   c           
     >   t        d|       t        | ||dt        j                  |      j                  z   d      }t        j                  t        j                  |      t        j                  t        j                  t        j                  |                        S )Nrh  rd  r   r  )r   r   r   r   epsnegr   r  signr  r  r8  r  s       r,   ri  ri  <  si    y% 	5%fll5&9&@&@ @M!	!cii
(;<	==r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||      S )a%  Sample logistic random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x) = \frac{e^{-x}}{(1 + e^{-x})^2}

  Args:
    key: a PRNG key used as the random key.
    shape: optional, a tuple of nonnegative integers representing the result
      shape. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  logisticz8dtype argument to `logistic` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   	_logisticr  s       r,   rn  rn  D  s|    ( :s+&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	3u	%%r.   c                   t        d|       t        | ||t        j                  |      j                  d      }t        j                  t        j                  |      t        j                  t        j                  |                  S )Nrn  r   r  )
r   r   r   r   r  r   r  r4  r  r  )rM   rK   r9   r+   s       r,   ro  ro  a  sW    z5!c5%U(;(@(@L!	SYYswwqz2	33r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a~  Sample Pareto random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x; b) = b / x^{b + 1}

  on the domain :math:`1 \le x < \infty` with :math:`b > 0`

  Args:
    key: a PRNG key used as the random key.
    b: a float or array of floats broadcast-compatible with ``shape``
      representing the parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``b``. The default (None)
      produces a result shape equal to ``b.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``b.shape``.
  paretoz6dtype argument to `pareto` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _pareto)rM   r  rK   r9   r   s        r,   rr  rr  h  s    6 8S)&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	a	&&r.   c                    |t        j                  |      }nt        d|       t        j                  ||      }t        | ||      }t        j                  ||z        S )Nrr  )rJ   rK   r   r   r   r  r  )rM   r  rK   r9   es        r,   rs  rs    sP    
]HHQKE5!	q%(!#ue$!	Qr.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | |||      S )a  Sample Student's t random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(t; \nu) \propto \left(1 + \frac{t^2}{\nu}\right)^{-(\nu + 1)/2}

  Where :math:`\nu > 0` is the degrees of freedom, given by the parameter ``df``.

  Args:
    key: a PRNG key used as the random key.
    df: a float or array of floats broadcast-compatible with ``shape``
      representing the degrees of freedom parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``df``. The default (None)
      produces a result shape equal to ``df.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``df.shape``.
  r   z1dtype argument to `t` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _trM   dfrK   r9   r   s        r,   r   r     s~    6 3$&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	CUE	""r.   c                ~   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        |       \  }}t        |||      }t        j                  |d      }t        j                  ||      }t        ||||      }	|t        j                  ||	z        z  S )Nr   r4   )rJ   rK   r   r   r   r   rU  r   r  r  r   rZ  )
rM   ry  rK   r9   key_nkey_grx  r  half_dfrS  s
             r,   rw  rw    s    
]HHRLEeRXXb\*
E*",%UE5!!

1a#GGB'E7E5)!	
SXXgk"	""r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a  Sample Chisquare random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x; \nu) \propto x^{\nu/2 - 1}e^{-x/2}

  on the domain :math:`0 < x < \infty`, where :math:`\nu > 0` represents the
  degrees of freedom, given by the parameter ``df``.

  Args:
    key: a PRNG key used as the random key.
    df: a float or array of floats broadcast-compatible with ``shape``
      representing the parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``df``. The default (None)
      produces a result shape equal to ``df.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``df.shape``.
  	chisquarez9dtype argument to `chisquare` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   
_chisquarerx  s        r,   r  r    s    8 ;,&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	CUE	**r.   c                j   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        j
                  |d      }t        j                  ||      }t        | |||      }t        j                  t        j                  |      |      }|S )Nr  r4   )rI  rK   r9   )rJ   rK   r   r   r   r   r  r  r  r   r  )rM   ry  rK   r9   r  r}  log_gchi2s           r,   r  r    s    
]HHRLEeRXXb\2
E*"

2q#GGB'
3'e
<%		%$	+r.   c                
   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | ||||      S )a-  Sample F-distribution random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
     f(x; \nu_1, \nu_2) \propto x^{\nu_1/2 - 1}\left(1 + \frac{\nu_1}{\nu_2}x\right)^{
      -(\nu_1 + \nu_2) / 2}

  on the domain :math:`0 < x < \infty`. Here :math:`\nu_1` is the degrees of
  freedom of the numerator (``dfnum``), and :math:`\nu_2` is the degrees of
  freedom of the denominator (``dfden``).

  Args:
    key: a PRNG key used as the random key.
    dfnum: a float or array of floats broadcast-compatible with ``shape``
      representing the numerator's ``df`` of the distribution.
    dfden: a float or array of floats broadcast-compatible with ``shape``
      representing the denominator's ``df`` of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``dfnum`` and ``dfden``.
      The default (None) produces a result shape equal to ``dfnum.shape``,
      and ``dfden.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``df.shape``.
  r   z1dtype argument to `f` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _f)rM   dfnumdfdenrK   r9   r   s         r,   r   r     s    D 3$&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	Cue	,,r.   c                t   |=t        j                  t        j                  |      t        j                  |            }n4t	        d|t        j                  |      t        j                  |             t        j
                  ||      }t        j
                  ||      }t        |       \  }}t        ||||      }t        ||||      }t        j                  ||      }t        j                  ||      }t        j                  ||      }	t        j                  ||      }
t        j                  |	|
      }|S )Nr   )r   r   rJ   rK   r   r   r   r  r   r  r  )rM   r  r  rK   r9   key_dfdkey_dfnchi2_dfnchi2_dfdr   denr   s               r,   r  r  -  s    
]!!"((5/288E?CEeRXXe_bhhuo>

"
"5%
0%

"
"5%
0%C['7wue4(wue4(


5%
(%


5%
(%% #% #	ggc3!	
(r.   c                    t        d|       \  } }t        j                  |t        n|      }t	        j
                  |      }t        | ||      S )a  Sample from a Rademacher distribution.

  The values are distributed according to the probability mass function:

  .. math::
     f(k) = \frac{1}{2}(\delta(k - 1) + \delta(k + 1))

  on the domain :math:`k \in \{-1, 1\}`, where :math:`\delta(x)` is the dirac delta function.

  Args:
    key: a PRNG key.
    shape: The shape of the returned samples. Default ().
    dtype: The type used for samples.

  Returns:
    A jnp.array of samples, of shape `shape`. Each element in the output has
    a 50% change of being 1 or -1.

  
rademacher)rP   r   r   rr   r
   r   _rademacherr  s       r,   r  r  A  sL    , <-&#q

2
2]c'%

!
!%
(%	S%	''r.   c                j    t        | d|      j                  |      }d|z  dz
  j                  |      S )Nr  )rM   rK  rK   r4   r  )r  r   )rM   rK   r9   bernoulli_sampless       r,   r  r  ^  s8    C3e<CCEJ

!
#	+	+E	22r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||      S )a  Sample from a one sided Maxwell distribution.

  The values are distributed according to the probability density function:

  .. math::
     f(x) \propto x^2 e^{-x^2 / 2}

  on the domain :math:`0 \le x < \infty`.

  Args:
    key: a PRNG key.
    shape: The shape of the returned samples.
    dtype: The type used for samples.

  Returns:
    A jnp.array of samples, of shape `shape`.

  maxwellz7dtype argument to `maxwell` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _maxwellr  s       r,   r  r  d  s|    . 9c*&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	#ue	$$r.   c                V    |dz   }t        | ||      }t        j                  |d      S )N)r   )rM   rK   r9   r?  rY  )rU  rz  norm)rM   rK   r9   norm_rvss       r,   r  r    s*    
$,%56(		++r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||||      S )ar  Sample from a double sided Maxwell distribution.

  The values are distributed according to the probability density function:

  .. math::
     f(x;\mu,\sigma) \propto z^2 e^{-z^2 / 2}

  where :math:`z = (x - \mu) / \sigma`, with the center :math:`\mu` specified by
  ``loc`` and the scale :math:`\sigma` specified by ``scale``.

  Args:
    key: a PRNG key.
    loc: The location parameter of the distribution.
    scale: The scale parameter of the distribution.
    shape: The shape added to the parameters loc and scale broadcastable shape.
    dtype: The type used for samples.

  Returns:
    A jnp.array of samples.

  double_sided_maxwellzDdtype argument to `double_sided_maxwell` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _double_sided_maxwell)rM   locscalerK   r9   r   s         r,   r  r    s    4 137&#q

2
2}e%)%			5"++	.
 $$)7, - -

!
!%
(%	sCu	==r.   c                ,   t        j                  t        j                  |      t        j                  |            }|s|}||z   }t	        |       \  }}t        |||      }t        |||      }	|	j                  |j                  k(  sJ |	|z  |z  |z   S )Nr   )r   r   rJ   rK   r   r  r  )
rM   r  r  rK   r9   params_shapesmaxwell_keyrademacher_keymaxwell_rvsrandom_signs
             r,   r  r    s    &&rxx}bhhuoF-	E
-
% &s+~5>+>eD+			k//	//	/	{	"U	*S	00r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       t        j                  |      }t        | ||||      S )a~  Sample from a Weibull distribution.

  The values are distributed according to the probability density function:

  .. math::
     f(x;\sigma,c) \propto x^{c - 1} \exp(-(x / \sigma)^c)

  on the domain :math:`0 < x < \infty`, where :math:`c > 0` is the concentration
  parameter, and :math:`\sigma > 0` is the scale parameter.

  Args:
    key: a PRNG key.
    scale: The scale parameter of the distribution.
    concentration: The concentration parameter of the distribution.
    shape: The shape added to the parameters loc and scale broadcastable shape.
    dtype: The type used for samples.

  Returns:
    A jnp.array of samples.

  weibull_minz;dtype argument to `weibull_min` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _weibull_min)rM   r  concentrationrK   r9   r   s         r,   r  r    s    4 =#.&#q

2
2}e%)%			5"++	.
 ##('+ , ,

!
!%
(%	c5-	>>r.   c                    t        | |dd|      }t        j                  t        j                  |        d|z        |z  S )Nr   r  )rM   rK   r   r   r9   r   )r   r   powerr  )rM   r  r  rK   r9   random_uniforms         r,   r  r    sB    
U1Qe=. 
CII~o..M0A	BU	JJr.   c                >   ||}n|}t        j                  |      }t        d|       \  } }t        j                  |t
        n|      }t        d|       t        j                  t        |d      }t        j                  t        |d      }t        | g |t        ||      t        ||      |      }t        j                  |      \  }}	t        j                  |	      }
|t        j                   t        j"                  |
      d      z  }||k  r|j$                  S |S )a  Sample uniformly from the orthogonal group O(n).

  If the dtype is complex, sample uniformly from the unitary group U(n).

  For unequal rows and columns, this samples a semi-orthogonal matrix instead.
  That is, if :math:`A` is the resulting matrix and :math:`A^*` is its conjugate
  transpose, then:

  - If :math:`n \leq m`, the rows are mutually orthonormal: :math:`A A^* = I_n`.
  - If :math:`m \leq n`, the columns are mutually orthonormal: :math:`A^* A = I_m`.

  Args:
    key: a PRNG key used as the random key.
    n: an integer indicating the number of rows.
    shape: optional, the batch dimensions of the result. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).
    m: an integer indicating the number of columns. Defaults to `n`.

  Returns:
    A random array of shape `(*shape, n, m)` and specified dtype.

  References:
    .. [1] Mezzadri, Francesco. (2007). "How to generate random matrices from
           the classical compact groups". Notices of the American Mathematical
           Society, 54(5), 592-604. https://arxiv.org/abs/math-ph/0609050.
  
orthogonalz-The error occurred in jax.random.orthogonal()rw  )r
   r   rP   r   r   r   r   r(  r   rU  r   r   rz  qrdiagonalr   r^  rl  mT)rM   rx  rK   r9   m_mr   zqr&  r  r+   s               r,   r  r    s    D Y	
B	
B

!
!%
(%<-&#q

2
2}e%)%|U#
UA'VW!eR)XY"S2E23q":2s1bz2E:!	q	$!Q!!#//#((1+r
**!V44KHr.   c                   t        j                  |      }t        d|       \  } }t        j                  |t
        n|      }t        d|       t        |       }t        |d   d|z  ||      }t        |d   ||      }||d|z  z  z  S )au  Sample from the generalized normal distribution.

  The values are returned according to the probability density function:

  .. math::
     f(x;p) \propto e^{-|x|^p}

  on the domain :math:`-\infty < x < \infty`, where :math:`p > 0` is the
  shape parameter.

  Args:
    key: a PRNG key used as the random key.
    p: a float representing the shape parameter.
    shape: optional, the batch dimensions of the result. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified shape and dtype.
  generalized_normalr   r  )
r
   r   rP   r   r   r   r   r   r  r  )rM   rK  rK   r9   r   r   rS  r&  s           r,   r  r  %	  s    4 
!
!%
(%/5&#q

2
2}e%)%#U+	s$DGQqS%'!a%'!	
Q1q5\	r.   c                   t        j                  |      }t        d|       \  } }t        j                  |t
        n|      }t        d|       t        j                  t        |d      }t        |       \  }}t        ||g |||      }t        |||      }	|t        j                  |      |z  j                  d      |	z   d|z  z  d   z  S )a$  Sample uniformly from the unit Lp ball.

  Reference: https://arxiv.org/abs/math/0503650.

  Args:
    key: a PRNG key used as the random key.
    d: a nonnegative int representing the dimensionality of the ball.
    p: a float representing the p parameter of the Lp norm.
    shape: optional, the batch dimensions of the result. Default ().
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array of shape `(*shape, d)` and specified dtype.
  ballz'The error occurred in jax.random.ball()r?  r  ).N)r
   r   rP   r   r   r   r   r(  r   r   r  r  r   r8  sum)
rM   r  rK  rK   r9   r   r  r  rS  ru  s
             r,   r  r  I	  s    , 
!
!%
(%63'&#q

2
2}e%)%vu
UA'PQ!:&"bQ%U3!"eU#!	

a$$R(1,!a%8)D	DDr.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a  Sample Rayleigh random values with given shape and float dtype.

  The values are returned according to the probability density function:

  .. math::
     f(x;\sigma) \propto xe^{-x^2/(2\sigma^2)}

  on the domain :math:`-\infty < x < \infty`, and where :math:`\sigma > 0` is the scale
  parameter of the distribution.

  Args:
    key: a PRNG key used as the random key.
    scale: a float or array of floats broadcast-compatible with ``shape``
      representing the parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``scale``. The default (None)
      produces a result shape equal to ``scale.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``scale.shape``.
  rayleighz8dtype argument to `rayleigh` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   	_rayleigh)rM   r  rK   r9   r   s        r,   r  r  k	  s    8 :s+&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	3ue	,,r.   c                   |t        j                  |      }n t        d|t        j                  |             t        | ||      }|j	                  |      }t        j                  ||      }t        j                  |      }t        j                  |d      }t        j                  t        j                  ||            }t        j                  ||      }|S )Nr  rw  )rJ   rK   r   r   r   r   r  r   r4  r   rZ  r  )	rM   r  rK   r9   rk  log_un_twosqrt_urays	            r,   r  r  	  s    
]HHUOEUBHHUO4c5% !
,,u
%


5%
(%
''!*%
**UB
%88CGGE5)*&v#	*r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )a  Sample Wald random values with given shape and float dtype.

  The values are returned according to the probability density function:

  .. math::
     f(x;\mu) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{(x - \mu)^2}{2\mu^2 x}\right)

  on the domain :math:`-\infty < x < \infty`, and where :math:`\mu > 0` is the location
  parameter of the distribution.


  Args:
    key: a PRNG key used as the random key.
    mean: a float or array of floats broadcast-compatible with ``shape``
      representing the mean parameter of the distribution.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``mean``. The default
      (None) produces a result shape equal to ``np.shape(mean)``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``mean.shape``.
  waldz4dtype argument to `wald` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _wald)rM   rr  rK   r9   r   s        r,   r  r  	  s    : 63'&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	sD%	''r.   c                l   |t        j                  |      }n t        d|t        j                  |             t        | d      \  }}|j	                  |      }t        j                  ||      }t        |||      }t        |||      }t        j                  |d      }t        j                  |d      }	t        j                  |d      }
t        j                  d|z  |z  |
|	z  z         }||
|z  dz  z   |dz  |z  z
  }t        j                  t        j                  ||||z   z        ||
|z        }|S )Nr  r4   r   )rJ   rK   r   r   r   r   r  rU  r   r   integer_powrZ  r  r  )rM   rr  rK   r9   r  r  r  r  yy_sqmean_sq	sqrt_termr+   r~  s                 r,   r  r  	  s   
]XXd^E/#q>&"b	U	$			$	&$R!b%!	ooa!	A	$OOD!$'hhq4x!|gn45)
Wq[1_tax)33!	jjDD1H-.7Q;?!	
(r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )ao  Sample Geometric random values with given shape and float dtype.

  The values are returned according to the probability mass function:

  .. math::
      f(k;p) = p(1-p)^{k-1}

  on the domain :math:`0 < p < 1`.

  Args:
    key: a PRNG key used as the random key.
    p: a float or array of floats broadcast-compatible with ``shape``
      representing the probability of success of an individual trial.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``p``. The default
      (None) produces a result shape equal to ``np.shape(p)``.
    dtype: optional, a int dtype for the returned values (default int64 if
      jax_enable_x64 is true, otherwise int32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``p.shape``.
  	geometricz8dtype argument to `geometric` must be an int dtype, got )rP   r   r   rr   r8   rJ   r   rA   r
   r   
_geometric)rM   rK  rK   r9   r   s        r,   r  r  	  s    6 ;,&#q

2
2]c'%			5"**	-
 ##('+ , ,
##E*E	CE5	))r.   c                   |t        j                  |      }n t        d|t        j                  |             t        d|       t	        |      \  }t        | ||j                        }t        j                  |      }t        j                  |       }t        j                  ||      }t        j                  t        j                  ||            dz   }|j                  |      S )Nr  r  )rJ   rK   r   r   r   r   r9   r   r4  r  r   r  r9  r  r   )rM   rK  rK   r9   rk  r  log_one_minus_prS  s           r,   r  r  	  s    
]XXa[EeRXXa[1+q!a "!c5!''"!
''!*%IIqbM/$$_e</	ii/014!	
%r.   c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||||      S )a  Sample Triangular random values with given shape and float dtype.

  The values are returned according to the probability density function:

  .. math::
      f(x; a, b, c) = \frac{2}{c-a} \left\{ \begin{array}{ll} \frac{x-a}{b-a} & a \leq x \leq b \\ \frac{c-x}{c-b} & b \leq x \leq c \end{array} \right.

  on the domain :math:`a \leq x \leq c`.

  Args:
    key: a PRNG key used as the random key.
    left: a float or array of floats broadcast-compatible with ``shape``
      representing the lower limit parameter of the distribution.
    mode: a float or array of floats broadcast-compatible with ``shape``
      representing the peak value parameter of the distribution, value must
      fulfill the condition ``left <= mode <= right``.
    right: a float or array of floats broadcast-compatible with ``shape``
      representing the upper limit parameter of the distribution, must be
      larger than ``left``.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``left``,``mode`` and ``right``.
      The default (None) produces a result shape equal to ``left.shape``, ``mode.shape``
      and ``right.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape`` if
    ``shape`` is not None, or else by ``left.shape``, ``mode.shape`` and ``right.shape``.
  
triangularz:dtype argument to `triangular` must be a float dtype, got )rP   r   r   r   r8   rJ   r   rA   r
   r   _triangular)rM   leftr<  rightrK   r9   r   s          r,   r  r  
  s    H <-&#q

2
2}e%)%			5"++	.
 ##('+ , ,
##E*E	S$eUE	::r.   )r   ru  )r   inlinec           	        |Qt        j                  t        j                  |      t        j                  |      t        j                  |            }nHt	        d|t        j                  |      t        j                  |      t        j                  |             t        j                  ||      }t        j                  ||      }t        j                  ||      }||z
  ||z
  z  }t        | ||      }|t        j                  |||z
  z  ||z
  z        z   }|t        j                  d|z
  ||z
  z  ||z
  z        z
  }	t        j                  ||k  ||	      }
|
S )Nr  r  )
r   r   rJ   rK   r   r   r  r   rZ  r  )rM   r  r<  r  rK   r9   fcrk  out1out2tris              r,   r  r  =
  s    ]!!"((4."((4."((5/REubhhtnbhhtnbhhuoV			$	&$			$	&$


5%
(%t%"c5% !	edl+td{;<	<$	1q5UT\2edlCD	D$

1r64&#	*r.   r  c                   t        d|       \  } }t        j                  |t        n|      }t        j                  |t
        j                        st        d|       |t        j                  |      }t        | |||      S )ac   Sample lognormal random values with given shape and float dtype.

  The values are distributed according to the probability density function:

  .. math::
      f(x) = \frac{1}{x\sqrt{2\pi\sigma^2}}\exp\left(-\frac{(\log x)^2}{2\sigma^2}\right)

  on the domain :math:`x > 0`.

  Args:
    key: a PRNG key used as the random key.
    sigma: a float or array of floats broadcast-compatible with ``shape`` representing
      the standard deviation of the underlying normal distribution. Default 1.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. The default (None) produces a result shape equal to ``()``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by ``shape``.
  	lognormalzDdtype argument to `lognormal` must be a float or complex dtype, got )rP   r   r   r   r8   rJ   rV  rA   r
   r   
_lognormal)rM   sigmarK   r9   r   s        r,   r  r  O
  s    2 ;,&#q

2
2}e%)%			5"**	-
 !7$ % %
##E*E	Cu	--r.   c                    |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        | ||      |z  }t        j                  |      S )Nr  )rJ   rK   r   r   r  rU  r   r  )rM   r  rK   r9   scaled_norms        r,   r  r  r
  s\    
]XXe_Eubhhuo6


5%
(%sE5)E1+		r.   c                   t        j                  g d| j                        }| dk  }t        j                  t        j
                  | d      | t        j
                  | d            } | dz   | dz   z  }ddd	|z  z
  |z  z
  | dz   z  }t        j                  |       } t        j                  ||t        j                  | d
         |      S )N)
gW
ڼq?g;>*?g&W?gxb&J?g?QN?g{k?g^J.aM]?g?0{^R?gb?gCL?r   	   re  g      "@r  gUUUUUU?gllf?gJ?r  )	r   r   r9   r   clampr   r9  r  r   )r@  stirling_tail_valsuse_tail_valueskp1sqapproxs        r,   _stirling_approx_tailr  }
  s    yy GG F/	ii

1c"Aszz!S'9:!q5QU
%	J$66%??AEJ&	iil!	)#++aw*GH&
R Rr.   c                   t         j                  j                  r0t        j                  j
                  t        j                        sJ t        j                         fd}fd}t        j                  dj
                        }t        j                  dj
                        }	d||	| f}
t        j                  |||
      d   }|dz
  j                  |      S )Nc                   | \  }}}}t        |      \  }}t        j                  |	k  |dz   |      }t        |j                        }t        j                  t        j                  |      
z        }||z   }|dz   |||fS r%  )r   r   r  r   r9   r   r3  r4  )r'  r  num_geomgeom_sumrM   r:  num_geom_outrk  geomcountlog1minusprobprobrK   s            r,   r+  z$_binomial_inversion.<locals>.body_fn
  s    !&Ax3*KFC::h%/AxHLtzz*A88CGGAJ./D$Hq5,#--r.   c                J    | d   | d   }}|k  j                         |k  z  S Nr   r4   r-  )r'  r  r  r  r/  s      r,   r0  z$_binomial_inversion.<locals>.cond_fn
  s1    (E!HxA""$I66r.   r   r  )r	   enable_checksr>   r   r8   r9   rJ   r   r   r  r   r  r  r  r   )rM   r  r  rK   r9   r/  r+  r0  num_geom_initgeom_sum_initr'  r@  r  s    ``` `      @r,   _binomial_inversionr  
  s    TZZ555))TE"-.7 --aU;---aU;-m]C
0%!!'7E:1=!
a%	r.   c           
        t        j                  z  dz
  z        }dd|z  z   ddz  z   dz  z   z  dz   dd	z  z
  dz
  z  d
dz  z   |z  t        j                  dz   z        f
d}fd}t        j                  dj
                        }	d|	t        j                  dt              | f}
t        j                  |||
      d   j                  |      S )Nr  gffffff?r5  gEJYga+e?{Gz?r  gq=
ףp?g@gp=
ף@gffffff@c                V  
 | \  }}}}t        |d      \  }}}t        |j                        }t        |j                        }|dz
  }dt        j                  |      z
  }	|	dk\  |k  z  }
t        j
                  dz  |	z  z   |z  z         }|dk  |kD  z  }t        j                  |z  |	|	z  z  z   z        }dz   t        j                  dz   z
  dz   z  z        z  dz   t        j                  z
  dz   |z
  dz   z        z  z   |dz   t        j                  |z
  dz   z  |dz   z        z  z   t              z   t        z
        z   t        |      z
  t        |z
        z
  }||k  }|
| |z  z  }t        j                  |||      }||z  }|dz   |||fS )Nr   r  r7  r4   r   r  )
r   r   r9   r   r8  r9  r4  r  r   r  )r'  r  r;  r<  rM   r=  r>  rk  r  usr@  r@  rA  ubrB  rC  rI  r  r  r  r  r  r  r&  rK   rF  s                   r,   r+  z_btrs.<locals>.body_fn
  s   #Auh#CmC8%,A%,A	CA	swwqz	BTza3h'G		1q52:>Q&*+A!eE	"FE	Q"r']Q./0A3w#''1q5Q%!)a-%89::	cgguqy1}Q?@@A	
SCGGAQ/1q59::; 	a ! 	eai(	)
 	a ! 	eai()  2gG')*FJJvq%(EHq5%3&&r.   c                F    | d   | d   }}| j                         |k  z  S r  r-  )r'  r  r<  r/  s      r,   r0  z_btrs.<locals>.cond_fn
  s,    (E!HxAI??I..r.   r?  r   F)r   rZ  r9  r   r  r9   fullrs   r  r  r   )rM   r  r  rK   r9   r/  stddevr+  r0  r1  r'  rI  r  r  r  r  r&  rF  s    ``` `     @@@@@@@r,   _btrsr  
  s    88EDLAH-.&
TF]!
TD[(!dlS!sQw#
a$h!#'>V
#%	iid"#!' '4/ ==r4::u5&fchhueT2C
8%		$	$Wgu	=a	@	G	G	NNr.   c                   |=t        j                  t        j                  |      t        j                  |            }n4t	        d|t        j                  |      t        j                  |             t        |      \  }t        j                  ||j                        }t        j                  ||      }t        j                  ||      }|dk  }t        j                  ||d|z
        }t        |      |dk  z  }t        j                  |      }t        |      }	|dk  }
t        j                  |	|
z  t        j                  |d      |      }|||z  dk  z  }t        j                  |      }t        j                  ||t        j                  |d            }t        j                  |t        j                  |d      |      }t        j                  |t        j                  |d      |      }|j                  t!        j"                  |      j$                        }t        j                  |t'        | |||||      t)        | |||||            }|
|	z  |z  }t        j                  |t        j                  |t        j*                  |      |      }t        j                  || z  t        j                  |t        j,                  |      |      }t        j                  ||z  |	z  |z  ||j/                  |      |z
        }|S )Nbinomialr  r   re  r  g      $@g     @)r   r   rJ   rK   r   r   r   r   r9   r  r  r-   isinfr  r9  rH   r   r   r   r  r  nanr  r   )rM   r  r  rK   r9   	p_lt_halfr  count_nan_or_neg	count_infq_is_nanq_l_0use_inversion	count_inv
count_btrsq_btrsr/  r  invalids                     r,   	_binomialr  
  sx    ]  %"((4.AEUBHHUORXXd^D"4('4

"
"5$**
5%


5%
(%			$	&$Sj)	jjD#*-!E]eck2ii)AY(
c'%	jjE!3==D#91=!"eai4&78- ))E
%jjs}}UC/HI)zz-uc)BEJ*::mS]]1c%:A>&jje,001)JJY5%C	#z65%;' X 00'JJMM'2665)' JJ'MM'2665)' JJ  8+i7	LL'!'
 
.r.   c                $   t        d|       \  } }t        d||       t        j                  |t        n|      }t        j
                  |t        j                        st        d|       |t        j                  |      }t        | ||||      S )a  Sample Binomial random values with given shape and float dtype.

  The values are returned according to the probability mass function:

  .. math::
      f(k;n,p) = \binom{n}{k}p^k(1-p)^{n-k}

  on the domain :math:`0 < p < 1`, and where :math:`n` is a nonnegative integer
  representing the number of trials and :math:`p` is a float representing the
  probability of success of an individual trial.

  Args:
    key: a PRNG key used as the random key.
    n: a float or array of floats broadcast-compatible with ``shape``
      representing the number of trials.
    p: a float or array of floats broadcast-compatible with ``shape``
      representing the probability of success of an individual trial.
    shape: optional, a tuple of nonnegative integers specifying the result
      shape. Must be broadcast-compatible with ``n`` and ``p``.
      The default (None) produces a result shape equal to ``np.broadcast(n, p).shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).

  Returns:
    A random array with the specified dtype and with shape given by
    ``np.broadcast(n, p).shape``.
  r  z8dtype argument to `binomial` must be a float dtype, got )rP   r   r   r   r   r8   rJ   r   rA   r
   r   r  )rM   rx  rK  rK   r9   r   s         r,   r  r    s    D :s+&#q*a#

2
2}e%)%			5"++	.

B5'J  ##E*E	31eU	++r.   random_clonec                    | S r(   rz   r*   s    r,   r  r  N  s    1 r.   c                    |gS r(   rz   )r   r@  s     r,   r  r  P  s    QC r.   )rK   r9   unrollc               *   t        d|       \  } }t        d||       t        ||      \  }}||j                  }t	        j
                  ||dd       }t	        j
                  ||      }d }t	        j                  |dd      }t        j                  |dd      }|t	        j                  |dk(  d|      z  }	t        | |	j                  d         }
t        j                  |||	|
f|	      \  }}t	        j                  |dd      j                  |      S )
a  Sample from a multinomial distribution.

  The probability mass function is

  .. math::
      f(x;n,p) = \frac{n!}{x_1! \ldots x_k!} p_1^{x_1} \ldots p_k^{x_k}

  Args:
    key: PRNG key.
    n: number of trials. Should have shape broadcastable to ``p.shape[:-1]``.
    p: probability of each outcome, with outcomes along the last axis.
    shape: optional, a tuple of nonnegative integers specifying the result batch
      shape, that is, the prefix of the result shape excluding the last axis.
      Must be broadcast-compatible with ``p.shape[:-1]``. The default (None)
      produces a result shape equal to ``p.shape``.
    dtype: optional, a float dtype for the returned values (default float64 if
      jax_enable_x64 is true, otherwise float32).
    unroll: optional, unroll parameter passed to :func:`jax.lax.scan` inside the
      implementation of this function.

  Returns:
    An array of counts for each outcome with the specified dtype and with shape
      ``p.shape`` if ``shape`` is None, otherwise ``shape + (p.shape[-1],)``.
  multinomialNr?  c                l    |\  }}t        || |j                  dd      | j                        }| |z
  |fS )Nr   r  r   )r  r   r9   )	remainder	ratio_keyratiorM   r  s        r,   r   zmultinomial.<locals>.f~  s:    JE3S)UZZ1%5Y__MEue##r.   r   T)reverser  )r  )rP   r   r   rK   r   r  r_  r  rE  rV  r   scanr   )rM   rx  rK  rK   r9   r  r   r   remaining_probsratiosr   r  countss                r,   r  r  S  s   D =#.&#q-A&	1	%$!Q
]GGE	q%*%!	q% !$
 
ll1b!!$++Aq$?/syyA-q/BB&	sFLLO	$$&++Aq64.P)V 
fa	$	+	+E	22r.   c                ,    t         j                  |       S )a}  Clone a key for reuse

  Outside the context of key reuse checking (see :mod:`jax.experimental.key_reuse`)
  this function operates as an identity.

  Examples:

    >>> import jax
    >>> key = jax.random.key(0)
    >>> data = jax.random.uniform(key)
    >>> cloned_key = jax.random.clone(key)
    >>> same_data = jax.random.uniform(cloned_key)
    >>> assert data == same_data
  )random_clone_pr  )rM   s    r,   cloner!    s     
		S	!!r.   c           
     b   t         j                  j                  s||fS |s||fS t        j                  |      j
                  }g }|D ]  }t        t        j                  |      x}t        j                        r|j
                  n	t               |z
  r(t        j                  |t        fd|D                    }|t        j                  |      j
                  k7  r:t        |  dt        j                  |       dt        j                  |       d      |j                  |        ||fS )Nc              3  ,   K   | ]  }|vs|  y wr(   rz   )r~   r@  arg_vmas     r,   r   z&random_insert_pvary.<locals>.<genexpr>  s     EAAW4DaEs   	z= requires all arguments to have matching type. Got key type: z vs arg type: z. Use jax.lax.pcast(..., to='varying') to make them match. If your key is less varying than arg, watch out for key-reuse problems.)r	   
_check_vmar>   r
   r  r  r7   ShapedArray	frozensetr  r   rG   append)rL   rM   r  key_vmar  rI  avalr$  s          @r,   r  r    s   				 	 9	9KK  '
# a%dkk!n&<dd>N>NOtxxK  
**QEEE
Fa$++a.$$$F kk#~dkk!n-= >FFG G
 JJqM  
c/r.   )r+   r#   rq   r"   )rL   ri   rM   r#   r0   rs   rq   ztuple[Array, bool])rM   r"   rW   rr   rK   Shaperq   r"   )r   PRNGSpecDesc | Nonerq   r`   )r   ri   r   int | ArrayLiker   r,  rq   r"   )r   r-  r3   r,  rq   r"   )rM   r#   r   IntegerArrayrq   r"   )rM   r"   r   int | tuple[int, ...]rq   r"   )rM   r#   r   r/  rq   r"   )r   r"   rq   r`   )r   r"   rq   str | PRNGSpec)r   r#   rq   r0  )r   r"   rq   r"   )r   r#   rq   r"   )r   r"   r3   r,  )rL   ri   rK   r+  rq   None)rz   N)rM   r#   rK   r+  r9   zDTypeLikeUInt | Nonerq   r"   )rz   Nre  r   )rM   r#   rK   r+  r9   DTypeLikeFloat | Noner   	RealArrayr   r3  rq   r"   )rq   r"   )r   r"   r9   r$   rq   r"   r(   )rM   r#   rK   r+  r   r.  r   r.  r9   DTypeLikeInt | Nonerq   r"   )r   F)
rM   r#   r+   r-  r%  rr   r'  rs   rq   r"   )rz   TNr   N)rM   r#   rI  r-  rK   r+  rJ  rs   rK  zRealArray | Noner%  rr   r<  
str | Nonerq   r"   )rM   r#   rK   r+  r9   r2  rq   r"   )NNrp  )rM   r#   rr  r3  rs  r3  rK   Shape | Noner9   r2  rt  ri   rq   r"   )NN)rM   r#   r  r3  r  r3  rK   r6  r9   r2  rq   r"   )r  Nr  )
rM   r#   rK  r3  rK   r6  r<  ri   rq   r"   )
rM   r"   rK  r"   rK   r6  r<  ri   rq   r"   )rM   r#   rI  r3  r  r3  rK   r6  r9   r2  rq   r"   )
rM   r#   r  r3  rK   r6  r9   r2  rq   r"   )rM   r"   rq   r"   )
rM   r#   rI  r3  rK   r6  r9   r2  rq   r"   )F)
rM   r#   r*  r3  rK   r6  r9   r4  rq   r"   )rz   NN)
rM   r#   rK   r+  r9   r2  r<  r5  rq   r"   )r?  NTN)rM   r#   r`  r3  r%  rr   rK   r6  rJ  rs   r<  r5  rq   r"   )
rM   r#   r  r3  rK   r6  r9   r2  rq   r"   )
rM   r#   ry  r3  rK   r+  r9   r2  rq   r"   )
rM   r#   ry  r3  rK   r6  r9   r2  rq   r"   )rM   r#   r  r3  r  r3  rK   r6  r9   r2  rq   r"   )rM   r#   rK   r+  r9   r4  rq   r"   )rM   r#   r  r3  r  r3  rK   r+  r9   r2  rq   r"   )rM   r#   r  r3  r  r3  rK   r+  r9   r2  rq   r"   )rM   r#   rx  rr   rK   r+  r9   r2  r  z
int | Nonerq   r"   )
rM   r#   rK  r   rK   r+  r9   r2  rq   r"   )r4   rz   N)
rM   r#   r  rr   rK  r   rK   r+  r9   r2  )
rM   r#   r  r3  rK   r6  r9   r2  rq   r"   )
rM   r#   rr  r3  rK   r6  r9   r2  rq   r"   )
rM   r#   rK  r3  rK   r6  r9   r4  rq   r"   )rM   r#   r  r3  r<  r3  r  r3  rK   r6  r9   r2  rq   r"   )
rM   r#   r  r3  rK   r6  r9   r2  rq   r"   )rM   r"   rx  r3  rK  r3  rK   r6  r9   r2  rq   r"   )rM   r"   rx  r3  rK  r3  rK   r6  r9   r2  r  z
int | bool)
__future__r   collections.abcr   r   	functoolsr   rA  operatorr   r   r   rC   r   rJ   jax._srcr	   r
   r   r   r   r   r   jax._src.meshr   jax._src.sharding_implsr   r   r   jax._src.apir   r   jax._src.interpretersr   r   r   jax._src.laxr   r  r   r   rg  jax._src.numpyr   r|  r   rz  jax._src.numpy.utilr   r   r   jax._src.pjitr    r!   jax._src.typingr"   r#   r$   r%   jax._src.utilr&   r3  r.  DTypeLikeIntDTypeLikeUIntDTypeLikeFloatrr   r+  r`   r   r-   rP   rT   rY   r<   r^   ri   PRNGSpecDescr   r   rM   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r
  r!  r)  r#  r>  rU  rW  r\  rm  rq  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  	Primitiver
  def_implr  def_abstract_evaldefjvp2register_lowering	lower_funprimitive_batchersr  r  r  r3  rH  rO  rQ  rG  rT  rX  rh  ri  rn  ro  rr  rs  r   rw  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  r  r  r  r  r  r  r  r   simple_impldefvectorizedr  r!  r  rz   r.   r,   <module>rS     s,   # .            !   + E " $ * & 9  / / / S S # 9 > > + 	 ==

 +0 #' 4F F;A"E E0 S(Hh67P.
+'
+,1
+ %)!!!-2!* )->%>16>:-&	-<
B
" /39+9*8; '+@ 	@@$@  %	@@ +/ " "	H HH(H H 	H #(HB F*? *?Z!7P *.	B BB B !B '	B #(BH FLI LIb $)N
 "N"NN "N
 ',N@5 D B !%"UOUOUO UO 	UO
 UO UO (-UOr *. O 	 O O' O "'	 OD F
+ 
+ FF F /37;&01D'1D&1D  ,1D  5	1D
 !$1D
 6;1Df I F ,048	+F
 &*+F%+F%+F )+F 2	+F
 /4+FZ FO O0 !$(+9 #	+9+9!+9 +9 (-	+9\ gv&'1 (1(  $(,	&(&(&( &( &	&( 27	&(R<. *.$$'$38$> F> > %)-1+.+.!+. ++. 7<+.Z F( ((  "/3)),)8=)> F( (L)^$* 05 '";  /    $     !< = 


DNP   ~~t~~K$'(    ~~t~~K$'(&+- /C  N + !%)-,2,2,2 ',2 38,2b $(,0'B'B 'B *'B 6;'BT 45
: 6
: I , I' 'T F> >, #')-****** '** 38**\ *."*)
 *)*)'*) *)
 "'*)X IO O& MM
M 	M 
	M
 M 	M Mb +/%%(%49%: F> > ,0&&)&5:&: F4 4 "&*.#'#'#' (#' 49#'J F  %)"#
"#"# #"# /4"#H F# #" %)-1$+$+!$+ +$+ 7<$+L F
 
  !%)	*-*-*- *- #	*- /4	*-X F ( !,0(()(5:(: F3 3 +/%%(%49%B F, , )+8<	!>'!> )!> !&!> !6	!> BG	!>H F1 1$  "/3	!? !?(!? !? -	!? 9>	!?H FK K !%666 
6 
	6
 6 6v !%	""
" 
" 
	"
 "N !%EEE E 
	E
 
EH $(,0$-$- $- *$- 6;$-L F    $(,%(%(%( &%( 27%(N F ( %)+/#*#*!#* )#* 5:#*J F & &*.2,;,;,;  ,; #	,;
 ,,;
 8=,;\ F4( )$ ",A$(-1!.!.!!. +!. 7<!.F F4( )R2 Id+ ,4 Id+,O ,,O^ F4(7 )7| #',,	,,,, ,, 	,,
 !,, ,,`  /   ^ $      -   ~ &   ~'7 8 #'93	9393 93
 93 !93 93x"$r.   