
    vh             	         d dl mZ d dl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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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,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3m4Z4m5Z5 d dl6m7Z7 e4Z8e4Z9e5Z:e5Z;e5Z<ee=   Z>ej~                  Z?ej                  Z@e%j                  ZBddZCdd	 	 	 ddZDd ZEdd ZFd! ZG G d" d#      ZHe
eIeHe?f   ZJdd$ZK	 	 	 	 dd%ZLdd&	 	 	 dd'ZMdd&	 	 	 dd(ZNdd)ZOdBdd+ZPdBdd,ZQdd-ZRdd.ZSdd/ZTdd0ZUdd1ZVdd&	 dd2ZWdd3ZXd4 ZY	 	 ddd6	 	 	 	 	 dd7ZZd5e[d8d9fdd6	 	 	 	 	 	 	 	 	 dd:Z\ eed;<      dd=       Z]e=fdd6	 	 	 	 	 	 	 	 	 dd>Z^ eed;<      dd?       Z_	 	 ddd6	 	 	 	 	 	 	 dd@Z`dA Za eedB<      ddC       Zb	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddFZcd5e[fdd6	 	 	 	 	 ddGZd eedH<      ddI       Ze eedH<      ddJ       Zf	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddKZg eedL<      ddM       Zhde[fdd6	 	 	 	 	 	 	 	 	 ddNZi eed;<      ddO       Zj ej                  dP      ddQf	 	 	 	 	 	 	 ddRZl eeddEgS      ddT       Zmde[f	 	 	 	 	 	 	 	 	 ddUZnddVZod5e[f	 	 	 	 	 ddWZp eedH<      ddX       Zqde[f	 	 	 	 	 	 	 ddYZr eedZ<      dd[       Zsd5e[f	 	 	 	 	 dd\Zt eedH<      dd]       Zudd^Zvd_ Zwdd`daZxdb Zy ej                  dc      Z{e{j                  ex       e{j                  dd         e!j                  e{dde         e#j                  e{ e#j                    eexdD`      df              e#j                  e{ e#j                    eexdD`      df      dgh       eye"j                  e{<   de[f	 	 	 	 	 	 	 ddiZde[f	 	 	 	 	 	 	 ddjZ eedkS      dddl       Z eedm<      ddn       Z eedm<      ddo       Z eedZ<      ddp       Zde=f	 	 	 	 	 	 	 ddqZd5e[df	 	 	 	 	 	 	 ddrZ eeds<      ddt       Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dduZd5e[f	 	 	 	 	 ddvZ eedH<      ddw       Zd5e[f	 	 	 	 	 ddxZ eedH<      dy        Zde[f	 	 	 	 	 	 	 ddzZ eedZ<      dd{       Zd5e[f	 	 	 	 	 	 	 dd|Z eedZ<      dd}       Zde[f	 	 	 	 	 	 	 dd~Z eedZ<      dd       Zde[f	 	 	 	 	 	 	 	 	 ddZ eed;<      dd       Zd5e=f	 	 	 	 	 ddZ eedH<      dd       Zd5e[f	 	 	 	 	 ddZ eedH<      dd       Zd5e[f	 	 	 	 	 	 	 	 	 ddZ eed;<      dd       Zd5e[f	 	 	 	 	 	 	 	 	 ddZ eed;<      dd       Zd5e[df	 	 	 	 	 	 	 	 	 	 	 ddZd5e[f	 	 	 	 	 	 	 	 	 ddZd*d5e[f	 	 	 	 	 	 	 	 	 ddZde[f	 	 	 	 	 	 	 ddZ eedZ<      dd       Zde[f	 	 	 	 	 	 	 ddZ eedZ<      dd       Zde=f	 	 	 	 	 	 	 ddZ eedZ<      dd       Zde[f	 	 	 	 	 	 	 	 	 	 	 ddZ eeddD      dd       Z ej                  d      de[f	 	 	 	 	 	 	 ddZ eedZdD      dd       Zd Z eedLdD      d        Z eedLdD      d        Z eed;dD      dd       Zde[f	 	 	 	 	 	 	 	 	 	 	 ddZ ej                  d      Z ejf                  e       ej                  d         e"jh                  e        e#j                  ed        de[dd	 	 	 	 	 	 	 	 	 	 	 ddZd Zy)    )annotations)Sequence)partialN)index)Union)lax)choleskysvdeigh)config)core)dispatch)dtypes)prng)
xla_bridge)jitvmap)ad)batching)mlir)softmax)_convert_and_clip_integer)
_arraylikecheck_arraylikepromote_dtypes_inexact)	auto_axes)canonicalize_sharding)Array	ArrayLike	DTypeLike)canonicalize_axisc                .    t        j                  | |       S N)r   nexs    J/opt/face_recognition/venv/lib/python3.12/site-packages/jax/_src/random.py_isnanr(   E   s    	1    Fallow_batchedc                  t        |t              r3t        j                  |j                  t        j
                        r|}d}nt        |      rt        j                  |t                     }d}t        j                  j                  dk(  rt        d      t        j                  j                  dk(  rt        j                  dd       nLt        j                   j                  r2t        j                  d	t"               nt%        d
t'        |             |s0|j(                  r$t        |  dt+        j,                  |       d      ||fS )NFimplTerrorzLegacy 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".warn   )
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
ValueErrorwarningsr0   enable_custom_prngFutureWarning	TypeErrortypendimnpshape)namekeyr+   wrapped_keywrappeds        r'   _check_prng_keyrI   I   s$   U 1 1#))V__ MKG#""3->-@AKG##w.	9: : 
			%	%	/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#   )
jnpr5   r6   r   r7   r   r>   r;   r   random_unwrap)was_wrappedrF   s     r'   _return_prng_keysrN   l   sJ    			6??	33	3$$J&14c":s:r)   rD   c                    t        j                  | j                  t        j                        sJ t        j                  | ||      S )N	bit_widthrD   )rK   r5   r6   r   r7   r   random_bits)rF   rQ   rD   s      r'   _random_bitsrS   u   s3    			6??	33	3			#%	@@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   r9   r;   r   prngs)	impl_names    r'   r9   r9   |   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#   )rY   )selfr.   s     r'   __init__zPRNGSpec.__init__   s	    DJr)   c                6    d| j                   j                  dS )Nz	PRNGSpec())rY   rE   r\   s    r'   __repr__zPRNGSpec.__repr__   s    tzz)++r)   c                ,    t        | j                        S r#   )strrY   r`   s    r'   __str__zPRNGSpec.__str__   s    tzz?r)   c                ,    t        | j                        S r#   )hashrY   r`   s    r'   __hash__zPRNGSpec.__hash__   s    

r)   c                X    t        |t              xr | j                  |j                  k(  S r#   )r4   rX   rY   )r\   others     r'   __eq__zPRNGSpec.__eq__   s!    eX&D4::+DDr)   N)returnrc   )rk   int)rk   bool)__name__
__module____qualname____doc__	__slots____annotations__r]   ra   rd   rg   rj    r)   r'   rX   rX      s+    ,i)	/,Er)   rX   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)"Nrt   ).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.)r9   rA   rZ   rX   rY   rc   r   rU   joinkeysr<   r@   )	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 )Nr6   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 batchingr-   )r   hasattrrK   r5   r6   r   r7   r@   rC   rB   rD   r   random_seed)	ctor_nameseedr~   r.   s       r'   _keyr      s    	9	%$T7tzz6?? K
+FGI IWWT]
+ $  A	CD D 
		$T	**r)   r-   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``.
  rF   )r   r   r.   s     r'   rF   rF      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)rN   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                  |            }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 r3   )
rI   rC   rB   r@   rD   r   random_fold_inrK   uint32rN   )rF   datarH   key_outs       r'   r   r      sr     !C0,#wWWT]
 XXd^,,NP Q QSZZ%56'	7G	,,r)   r1   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 r3   rD   )rK   r5   r6   r   r7   rB   r@   rD   r4   r   tupler   random_split)rF   numrD   s      r'   _splitr     sv     
		6??	33	3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)rI   rN   r   )rF   r   	typed_keyrH   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#   )
rK   r5   r6   r   r7   typingcastr   KeyTyrY   )r}   
keys_dtypes     r'   	_key_implr   )  sB    	

FOO	44	4{{4::tzz2*			r)   c                ~    t        |       }|j                  t        j                  v r|j                  S t	        |      S r#   )r   rE   r   rU   rX   )r}   r.   s     r'   	_key_specr   .  s-    	4$ii4::-A8D>Ar)   c                :    t        d| d      \  }}t        |      S )Nkey_implTr*   )rI   r   )r}   
typed_keys_s      r'   r   r   2  s    !*d$G-*a	:	r)   c                    t        j                  | j                  t        j                        sJ t        j                  |       S r#   )rK   r5   r6   r   r7   r   rL   )r}   s    r'   	_key_datar   7  s/    	

FOO	44	4			D	!!r)   c                :    t        d| d      \  } }t        |       S )z9Recover the bits of key data underlying a PRNG key array.key_dataTr*   )rI   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.
  r-   )r   r   r8   )key_bits_arrayr.   impl_objs      r'   wrap_key_datar   A  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_shapesr<   format)rE   rD   param_shapesshape_msgs        r'   _check_shaper   V  sM    !!%7,7FLc szz$677	  r)   c                <    t        | fi |}||S t        ||      S )Nout_sharding)r   r   )fr   hoist_kwargsf_s       r'   maybe_auto_axesr   `  s)    q!L!"IRl33r)   rt   r   c                  t        d|       \  } }|$t        j                  t        j                        }nt        j
                  |       t        j                  |t        j                        st        d|       t        j                  |      }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    rP   )rI   r   canonicalize_dtyperK   uintcheck_user_dtype_supportedr5   rC   unsignedintegerr<   r   canonicalize_shaper   itemsizer   rS   )rF   rD   r6   r   r   rQ   s         r'   r   r   h  s    " 63'&#q
]%%chh/E
%%e,			5""4"4	5
 !7$ % %

#
#E
*%

!
!%
(%&|V<,nnq )
;|#,E
;;>
@ @r)                 ?c               P   t        d|       \  } }t        j                  |       t        j                  |      }t        |d      }t        j                  |t        j                        st        d|       t        j                  |      } 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 rD   r6   )rI   r   r   r   r   r   r5   rC   floatingr<   r   r   _uniform)rF   rD   r6   minvalmaxvalr   r   s          r'   r   r     s    * 9c*&#q##E*

!
!%
(%&|Y?,			5"++	.
 !7$ % %

#
#E
*%
2<$5
225vv
G G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                   |	t        j"                  ||z
  |
            t        j"                  d|      j%                  |
            }t        j&                  ||      t        j"                  d|      z
  }t        j(                  |t        j*                  |||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   rK   r5   rC   r   r@   r   convert_element_typebroadcast_to_ranklenfinfor   nmantrS   UINT_DTYPES
bitwise_orshift_right_logicalarrayviewbitcast_convert_typemaxreshape)rF   r   r   rD   r6   r   nbitsr   rng_bitsr   
uint_dtype
float_bitsfloatss                r'   r   r     s   y% 	r{{	+
A
BB##FE2&##FE2&  U4&  U4&
))E
%U[[%
/!

A%J  (
QYH	c8U	+$5!*##D*5D ~~	dBHHX-=z$JKhhsE
+* ##J6"e9LL&		kk&FVO,v5u=
? ?r)   c                   t        d|       \  } }t        j                  |       t        j                  |      }t	        j
                  |      }t        |d      } t        t        |||      | ||      S )ap  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.
  randintr   )	rI   r   r   r   r   r   r   r   _randint)rF   rD   r   r   r6   r   r   s          r'   r   r     so    , 9c*&#q##E*

#
#E
*%

!
!%
(%&|Y?,	J<uE	J	66
 r)   c           
     2   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        j.                  ||z
  |      }t        j0                  ||k  t        j2                  |d      |      }t        j0                  |||kD  z  t        j4                  |t7        |d            |      }t        j8                  t7        |ddz  z        |      }t        j8                  t        j:                  ||      |      }t        j4                  t        j:                  t        j8                  |	|      |      t        j8                  |
|            }t        j8                  ||      }t        j4                  |t        j.                  ||            S )Nr   z)randint only accepts integer dtypes, got r   z9randint only accepts 8-, 16-, 32-, or 64-bit dtypes, got c                    t        |       S r#   )rS   )rF   r   rD   s    r'   <lambda>z_randint.<locals>.<lambda>  s    l3u5 r)      r1   )r   rC   rD   rK   r5   integerr@   r   asarrayr6   astyperl   r   gtr   r   iinfor   r   r   r   r   r   r   select	full_likeadd
_lax_constremmul)rF   r   r   rD   r6   maxval_out_of_rangek1k2rbitshigher_bits
lower_bitsunsigned_dtypespan
multiplierrandom_offsetr   s      `           @r'   r   r     s   y%&!1288F3CD	rzz	*
?wG
HH)VV,;;v&;;v&	bjj	1]]3F	bjj	1]]3F 
%cii		%0@0D0De&Lfll[] %VU3&$VU3&  U4&  U4&
))E


%
/!
OPUwW
XX
 #;&"b
5%!"IuRyz+u%.		!	!&6/>	B$ 
Ff$cmmD!&<d	C$
 
6F?+GGD*T1%&

$ wwz$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#   )_shufflerK   arange)rF   axisrs    r'   r   zpermutation.<locals>.<lambda>K  s    xSZZ]D'I r)   )r  independent)rI   r   r!   rC   rB   r   r5   r   r6   r   r@   r   concrete_or_errorrl   r   _permutation)rF   r&   r  r  r   r   r  s     `   @r'   r  r  0  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)rC   rB   r	  rK   r
  rD   take)rF   r&   r  r  inds        r'   r  r  P  sV    BGGAJ!OCD!!cjj/3#	!S$t	44r)   r1   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   )rK   r   rC   r   r   r   is_constant_dimsizeNotImplementedErrorrl   ceillogranger   rS   rD   r   sort_key_val)	rF   r&   r  exponent	uint32max
num_roundsr   subkey	sort_keyss	            r'   r	  r	  W  s      (ii		"&&)			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()r6   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   )r6   r"  )k)!rI   r4   r   r@   r   rK   r   rB   r   r  rl   r!   rD   mathprodzerosr6   r<   r   r  slicer  r   cumsumr   searchsortedr   gumbelr  r   top_kr   r   )rF   arD   replacepr  r"  r   arrn_inputsn_drawsr  resultslicesp_arrp_cumlr  gs                     r'   r$  r$  w  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               L   t        d|       \  } }t        j                  |      }t        |d      }t	        j
                  |       t	        j                  |t        j                        st        d|       t	        j                  |      } 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   )rI   r   r   r   r   r   r5   rC   inexactr<   r   r   _normal)rF   rD   r6   r   r   s        r'   r<  r<    s    0 8S)&#q

!
!%
(%&|X>,##E*			5"**	-
 !7$ % %

#
#E
*%	I,e5	I#	NNr)   )r   r1   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 )Nr1   r   y              ?)r   r5   rC   complexfloatingr   sqrtr   realr6   _normal_realr   )	rF   rD   r6   sqrt2key_rekey_im
real_dtype_re_ims	            r'   r>  r>    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 )Nr<        r   r%  r   r1   )	r   rC   	nextafterr   r   r   r   rA  erf_inv)rF   rD   r6   lohius         r'   rC  rC    s    x	||BHHS%("((2u*=UK"	xxE"c5%R(!	"''!*e,ckk!n	==r)   c                T   t        d|       \  } }t        j                  |       t        ||      \  }}|dvrt	        d      ||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>   r
   r   r	   z1method must be one of {'svd', 'eigh', 'cholesky'}zCdtype argument to `multivariate_normal` must be a float dtype, got )rI   r   r   r   r<   r6   r5   rC   r   r   r   _multivariate_normal)rF   meancovrD   r6   methodr   s          r'   rR  rR    s    H 0#6&#q##E*$T3/)$..
H
II
]JJE			5"++	.
 ##('+ , ,
##E*E	c4eUF	CCr)   )r   r      c                >   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(  r0t        |      \  }}	}
|t        j                  |	dd d d f         z  }n?|dk(  r/t        |      \  }}|t        j                  |dd d d f         z  }nt        |      }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 == {}r1   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}.)nrD   r<  r
   .r   allowz...ij,...j->...i)rC   rB   r<   r   rD   r   r   r   r
   rK   rA  r   r	   r<  r   numpy_rank_promotioneinsum)rF   rT  rU  rD   r6   rV  r   rZ  rP  ry   r   factorwvnormal_samplesr6  s                   r'   rS  rS  9  s   	!	
LC
SZZ.
//		
JC
SZZ-
..
jjn!XXc]23Aq6!+C
SZZ!288C=Z9
::
]  CR#))CR.AE5$**Sb/399Sb>Bu_CIQ1!CqL/**F#YFQ!CqL/**Fc]F#utzz"#6>.""7+ KCJJ16>JJFK	-K	-s   -HHc               T   |t        j                  |      }t        d|       \  } }t        |d      }t	        j
                  |       t	        j                  |t        j                        st        d|       t	        j                  |      } 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   rI   r   r   r   r5   rC   r   r<   r   r   _truncated_normal)rF   lowerupperrD   r6   r   r   s          r'   rc  rc  Z  s    B ##E*E-s3&#q&|5GH,##E*			5"++	.
 ##('+ , ,

#
#E
*%
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 )Nrc  r1   z4truncated_normal only accepts floating point dtypes.r   r   r%  )r   r   rC   rD   r   r   rA  r   erfrK   r5   r   r@   r   rM  cliprL  stop_gradientinf)
rF   re  rf  rD   r6   rD  r0  brP  outs
             r'   rd  rd    sT   
]  %"((5/BE#UBHHUORXXe_M
((2771:u
%%

"
"5%
0%

"
"5%
0%	ggeem!	ggeem!	r{{	+
J
KKc5%!4!A# 
		mmC%%e,bhhrvvU.KL	mmC%%e,bhhwe.LM
O Or)         ?lowc                   |t        j                  |      }|dvrt        d|d      t        d|       \  } }t	        j
                  t        j                  |            }t        j                  |t        j                        sd}t        |j                  |            t        j                  ||      }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``.
  highrp  z	got mode=z, expected 'high' or 'low'	bernoulliz=bernoulli probability `p` must have a floating dtype, got {}.r"  )r   r   r<   rI   r   r   r   r6   rK   r5   rC   r   r@   r   r   
_bernoulli)rF   r2  rD   r"  r   r6   r   s          r'   rt  rt    s    < ##E*E	 
zD7"<=
>>;,&#q

#
#CIIaL
1%	r{{	+
IC
CJJu%
&&	q%(!	CE	--r)   )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 )Nrt  rs  r1   )	rC   rD   r   r   r6   r   r   r   r   )rF   r2  rD   r"  r6   u1u2s          r'   rv  rv    s    
]HHQKEeRXXa[1
))A,%	V^S1+u+u-FB!U#)))
))BB;3syy|,q00r)   c                $   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   _beta)rF   r0  rm  rD   r6   r   s         r'   r|  r|    s    < 63'&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	sAq%	''r)   c                   |=t        j                  t        j                  |      t        j                  |            }n4t	        d|t        j                  |      t        j                  |             t        j
                  ||      }t        j
                  ||      }t        |       \  }}t        j                  ||      }t        j                  ||      }t        ||||      }t        ||||      }t        j                  ||      }	t        j                  ||	z
        }
t        j                  ||	z
        }|
|
|z   z  S )Nr|  )r   r   rC   rD   r   r   r   rK   broadcast_tologgammar   exp)rF   r0  rm  rD   r6   key_akey_blog_gamma_alog_gamma_blog_maxgamma_a_scaledgamma_b_scaleds               r'   r}  r}    s   
]  !bhhqk:ERXXa[9	q%(!	q%(!,%	q% !	q% !5%0+5%0+GGK-'77;01.77;01.	>N:	;;r)   c                   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _cauchyrF   rD   r6   r   s       r'   r  r    s    , 8S)&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	eU	##r)   c                6   t        d|       t        | ||t        j                  |      j                  d      }t        |t        j                        }t        j                  t        j                  |t        j                  |t        |d                        S )Nr  r   rh  ro  )r   r   rK   r   epsr   rC   pir   tanr   sub)rF   rD   r6   rP  r  s        r'   r  r  8  si    xc5%		%(8(<(<RH!!RUU"	SWWQ
1c(:;<	==r)   c                "   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   
_dirichlet)rF   alpharD   r6   r   s        r'   r  r  @  s    F ;,&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	Cu	--r)   )r1   r   c                   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   |      }t        |d      S )Nr   z8dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}r&  r  )
rC   rB   r<   r   rD   r   r   r   r  r   )rF   r  rD   r6   r   log_gamma_sampless         r'   r  r  m  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        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _exponentialr  s       r'   r  r    s    , =#.&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	c5%	((r)   c                    t        d|       t        | ||      }t        j                  t        j                  t        j                  |                  S )Nr  )r   r   r   neglog1prF   rD   r6   rP  s       r'   r  r    s:    }e$c5% !	3771:&	''r)   c                   t        |d      t        |d      t        |d      t        |d      t        |d      }t        |d      t        j                  |      t        j                  |      }|}t        j                  ||t        j
                  |            }t        j                  ||      t        j                  |t        j                              fd}fd}t        |       \  } }t        j                  ||| t        |d	      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   r&  ro  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   r  r   )
kXVUr   XVUconddoneone_over_twosqueeze_consts
         r'   _cond_fnz_gamma_one.<locals>._cond_fn  s    JAq!Q ??366!SWWS#''-QRTU2W%XY66#''!*cggcgga6N69ggaQTVWILQRBU 7V/W XY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   rt   r%  )r   r<  r   r   r   )kxvrF   r   r&   r`  cr6   r  s        r'   	_next_kxvz/_gamma_one.<locals>._body_fn.<locals>._next_kxv  sM    Fc3Kkc6
5
)a
''#swwq!}
%a!QYr)   r   r   c                6    t        j                  | d         S )Nr1   )r   le)r  zeros    r'   r   z._gamma_one.<locals>._body_fn.<locals>.<lambda>  s    A)= r)   rt   r%  )r   r   
while_loopr   r   )r  r  rF   x_keyU_keyr   r&   r`  r  r  r  r  r6   	minus_oner  r  s              r'   _body_fnz_gamma_one.<locals>._body_fn  s     q'CsACnn=y5RVXaJbcGAq!1A1q!Ar'A1a<r)   r1   rt   r%  )r   r   r6   r  r   r   r  divrA  r   r  r  r  r   r  r   pow)rF   r  	log_spaceone_over_three
boost_mask
alpha_origr  r  r   r   r  log_samples	log_boostsamplesboostr  r  r6   r  r  r  r  r  s                  @@@@@@@@r'   
_gamma_oner    s    
E1	$5!##)E3',eW-.UF+-
))E
% vveS!**
**Zs(;
<%	gge^$!	ggnchhqk*!	 " s+#v~~h3c:eUVCW2XY*!Q1''+fb>?K

:)9:D#''+WZW^W^_bdnWoBpqI773773771:swwqz2I>>'&"E22GJJz3j9Q(RSE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#   )r   random_gamma_grad)r  samples     r'   r   z_gamma_grad.<locals>.<lambda>  s    s'<'<UF'Kf'T r)   cpuc                     |  S r#   rt   )args
gamma_grads    r'   r   z_gamma_grad.<locals>.<lambda>  s    T!2 r)   )rK   r   r   r  lax_internal_constr   r   r6   tinyr   eqr  r   get_backendplatformmapr   rC   rD   )	r  r0  r  r  alphasr  r  gradsr  s	           @r'   _gamma_gradr    s    KK#';;q"& gggGvq)D==#))GMM":"?"?@Djj.g>GTJ&&J&&%/GG2VW4EFE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)   )rK   rD   r(  r)  rB   flattenr   r   r   r   threefry_prng_implr   r  r   r  r   )	rF   r0  r  r  a_shapesplit_countr}   r  r  s	     `      r'   _gamma_implr    s    IIaL'		'#((),-+	$	(fi	({	;$	$99;&)C.D$;$;;<d7:;<T6JGgg;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   )rx   r   is      r'   rz   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'  r0  bkbar  s           r'   _gamma_batching_ruler    sz    	$!Q&"b	 M z:M 
M$QD)!QD)!			QY		7	::r)   random_gammac                    |S r#   rt   )rF   r0  r   s      r'   r   r     s    Q r)   c                "    | t        ||fi |z  S r#   )r  )tangentansrF   r0  kwdss        r'   r   r     s    ;sA3N3N)N r)   )multiple_resultsr  )r  c                $   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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   rI   r   r   r5   rC   r   r<   r   r   r   _gammarF   r0  rD   r6   r   s        r'   r  r  &  s    H 7C(&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	Qe5	11r)   c                &   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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rD   r6   r  r  r  s        r'   r  r  U  s    > :s+&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	Qe5D	AAr)   r  c                *   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        j                  |      |k7  rt        j                  ||      }t        j                  | ||      S )Nr  r  )	rC   rD   r   r   r   rK   r  r  r  )rF   r0  rD   r6   r  s        r'   r  r    st    
]HHQKE%!-	q%(!XXa[EE"A			S!y		99r)   )r1   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   rC   float32rK   r  )	carryr  r'  rnglog_prodr   rP  lamrD   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   rC   r  r  r   )
rF   r  rD   r6   r
  r  r  k_initlog_rate_initr'  s
    `` `     r'   _poisson_knuthr    sn    05 ==a.&--Q

E:-	nnWg63'FGJ!
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                        }t        j                  ||d||| f      d   }	|	j                  |      S )Ngn?=
ףp=@gh|?5g[	m?g$~?gr?g333333@gr鷯?gB>٬@r1   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   ro  r1   gQ?r   Q?r   g9v?)	r   r   r6   absr   floorr  lgammar   )r  r  k_outacceptedrF   subkey_0subkey_1rP  r`  	u_shiftedr'  ry   r   accept1rejectaccept2acceptr0  rm  	inv_alphar  log_lamrD   v_rs                    r'   r  z#_poisson_rejection.<locals>.body_fn  sD   #Auh$S!nC8%+c1A%+Ac!fI		1q59$q(A-3d:;AIi)&;!<q!@ABA	q7{SZZA..A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  rF   r
  s        r'   r  z#_poisson_rejection.<locals>.cond_fn  s)    #AuhI??I..r)   r&  Fr   r   )	r   r  rA  r   r6   rK   bool_r  r   )rF   r  rD   r6   r
  r  r  r  r  r'  r0  rm  r  r   r!  s    `` `     @@@@@r'   _poisson_rejectionr$    s    
 GGCL'dSXXc]""!w{!vS)))1q5!!#' ',/ ==b#))U3&]]3syy%8(	nnWg68S'AB1E!	
%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
   r   g     j@r   )r(   r   r   r   rA   rK   r   r   r  r$  
zeros_like)	rF   r  rD   r6   	use_knuth	lam_knuthlam_rejectionr
  r6  s	            r'   _poissonr+    s     SkS2X&)jjCsC)@A) **Yc3(?E-jj5)--.)::3	5%;sM5%C&
 
C1HcnnV4f	==r)   c                   t        d|       \  } }t        j                  |       t        j                  t
        j                  | j                        }|j                  }|t
        j                  urt        d|       t        j                  |      }|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 )rI   r   r   r   r   r   r   r6   rY   r  r  r   r   r   rC   rD   rK   r  r   r   r  r+  )rF   r  rD   r6   r   r   r   s          r'   r-  r-    s    2 9c*&#q##E* {{4::syy1*(T,,,
	j	  
#
#E
*%
##E*EHHSMEe$#  bjj1#	#sE5	))r)   c                   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }t        j                  |      }|t        j                  j                  rdnd}|dvrt        d|z        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.
  r.  z6dtype argument to `gumbel` must be a float dtype, got rs  rp  rr  z*Must provide valid mode for gumbel got: %s)rI   r   r   r5   rC   r   r<   r   r   r   r   use_high_dynamic_range_gumbelr;   _gumbel)rF   rD   r6   r"  r   s        r'   r.  r.    s    6 8S)&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	\99??6UD	 
ADH
II	eUD	))r)   )r   r1   r   c                   t        d|       |dk(  rt        | ddd|z   |      \  }}t        j                  |dk\  ||dt        j                  |      j
                   z  |z  z   t        j                  |      j                  z         }t        j                  t        j                  |               S t        j                  t        j                  t        | t        j                  |      j                  d||                    S )	Nr.  rs  r   r   r  )r   r   rD   r6   ro  r1   )	r   r   rK   wherer   r   r  r  r  )rF   rD   r6   r"  rs  rp  r&   s          r'   r0  r0  8  s    x	V^R#e|5:ID# 			$#+tqcii&,,--33cii6F6K6KK	MAGGSYYr]N###GGSWWSYYu-222E	+, , - - -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   ru  r  z'Number of samples without replacement (z&) cannot exceed number of categories (z).r&  r   )rI   r   rK   r   r   rC   deleterD   r   r   r   r   listinsertargmaxr.  r6   r   expand_dimsr  r(  r)  r<   r/  moveaxisrB   r   )rF   logitsr  rD   r1  r"  r   
logits_arrbatch_shapeshape_prefixlogits_shaper'  indices
dimensionss                 r'   r4  r4  I  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        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _laplacer  s       r'   rD  rD    s    ( 9c*&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	#ue	$$r)   c           
     >   t        d|       t        | ||dt        j                  |      j                  z   d      }t        j                  t        j                  |      t        j                  t        j                  t        j                  |                        S )NrD  rK  r   rh  )r   r   rK   r   epsnegr   r   signr  r  r  r  s       r'   rE  rE    si    y% 	5%cii&6&=&= =bJ!	!cii
(;<	==r)   c                   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   	_logisticr  s       r'   rJ  rJ    s    ( :s+&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	3u	%%r)   c                   t        d|       t        | ||t        j                  |      j                  d      }t        j                  t        j                  |t        j                  t        |d      |                  S )NrJ  r   rh  r   )
r   r   rK   r   r  r   r  r  r  r   )rF   rD   r6   r&   s       r'   rK  rK    sY    z5!c5%		%(8(<(<RH!	CGGJq!$4a89	::r)   c                "   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   _pareto)rF   rm  rD   r6   r   s        r'   rN  rN    s    6 8S)&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	a	&&r)   c                    |t        j                  |      }nt        d|       t        j                  ||      }t        | ||      }t        j                  ||z        S )NrN  )rC   rD   r   r   r   r  r  )rF   rm  rD   r6   es        r'   rO  rO    sP    
]HHQKE5!	q%(!#ue$!	Qr)   c                   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _trF   dfrD   r6   r   s        r'   r   r     s    6 3$&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	CUE	""r)   c                j   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        |       \  }}t        |||      }t        |d      }t        j                  ||      }t        ||||      }	|t        j                  ||	z        z  S )Nr   r1   )rC   rD   r   r   r   r   r<  r   r  r  rK   rA  )
rF   rU  rD   r6   key_nkey_grZ  twohalf_dfr:  s
             r'   rS  rS  7  s    
]HHRLEeRXXb\*
E*",%UE5!!1a#GGB'E7E5)!	
SXXgk"	""r)   c                "   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   
_chisquarerT  s        r'   r\  r\  G  s    8 ;,&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	CUE	**r)   c                V   |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        |d      }t        j                  ||      }t        | |||      }t        j                  t        j                  |      |      }|S )Nr\  r1   )r0  rD   r6   )rC   rD   r   r   r   r   r  r  r   rK   r  )rF   rU  rD   r6   rY  rZ  log_gchi2s           r'   r]  r]  m  s    
]HHRLEeRXXb\2
E*"2q#GGB'
3'e
<%		%$	+r)   c                $   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   _f)rF   dfnumdfdenrD   r6   r   s         r'   r   r   {  s    D 3$&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##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   rC   rD   r   r   r   r\  rK   r  r  )rF   rc  rd  rD   r6   key_dfdkey_dfnchi2_dfnchi2_dfdr   denr   s               r'   rb  rb    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        j                  |      }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)rI   r   r   r   r   r   _rademacherr  s       r'   rl  rl    sQ    , <-&#q##E*

#
#E
*%

!
!%
(%	S%	''r)   c                j    t        | d|      j                  |      }d|z  dz
  j                  |      S )Nro  )rF   r2  rD   r1   r   )rt  r   )rF   rD   r6   bernoulli_sampless       r'   rm  rm    s8    C3e<CCEJ

!
#	+	+E	22r)   c                   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _maxwellr  s       r'   rq  rq    s    . 9c*&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	#ue	$$r)   c                j    |dz   }t        | ||      }t        j                  j                  |d      S )N)r   )rF   rD   r6   r&  r5  )r<  rK   linalgnorm)rF   rD   r6   norm_rvss       r'   rr  rr    s0    
$,%56(		++r)   c                    t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _double_sided_maxwell)rF   locscalerD   r6   r   s         r'   rx  rx    s    4 137&#q##E*			5"++	.
 $$)7, - -

#
#E
*%

!
!%
(%	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   rC   rD   r   rq  rl  )
rF   rz  r{  rD   r6   params_shapesmaxwell_keyrademacher_keymaxwell_rvsrandom_signs
             r'   ry  ry  *  s    &&rxx}bhhuoF-	E
-
% &s+~5>+>eD+			k//	//	/	{	"U	*S	00r)   c                    t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }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 )rI   r   r   r5   rC   r   r<   r   r   r   _weibull_min)rF   r{  concentrationrD   r6   r   s         r'   r  r  :  s    4 =#.&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%

!
!%
(%	c5-	>>r)   c                    t        | |dd|      }t        j                  t        j                  |        d|z        |z  S )Nr   r   )rF   rD   r   r   r6   r   )r   rK   powerr  )rF   r{  r  rD   r6   random_uniforms         r'   r  r  ^  sB    
U1Qe=. 
CII~o..M0A	BU	JJr)   c                V   ||}n|}t        j                  |      }t        d|       \  } }t        j                  |       t        d|       t        j                  t        |d      }t        j                  t        |d      }t        | g |t        ||      t        ||      |      }t        j                  j                  |      \  }}	t        j                  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()rY  )r   r   rI   r   r   r   r  r   r<  r   minrK   rt  qrdiagonalr:  rH  mT)rF   rZ  rD   r6   m_mr   zqr  r  r&   s               r'   r  r  g  s    D Y	
B	
B

!
!%
(%<-&#q##E*|U#
UA'VW!eR)XY"S2E23q":2s1bz2E:!	q	$!Q	jj!!#//#((1+r
**!V44KHr)   c                    t        j                  |      }t        d|       \  } }t        j                  |       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   rI   r   r   r   r   r  rl  )rF   r2  rD   r6   r   r}   r:  r  s           r'   r  r    s    4 
!
!%
(%/5&#q##E*#U+	s$DGQqS%'!a%'!	
Q1q5\	r)   c                   t        j                  |      }t        d|       \  } }t        j                  |       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   rI   r   r   r   r  r   r   r  r  rK   r  sum)
rF   r  r2  rD   r6   r   r   r   r:  rQ  s
             r'   r  r    s    , 
!
!%
(%63'&#q##E*vu
UA'PQ!:&"bQ%U3!"eU#!	

a$$R(1,!a%8)D	DDr)   c                "   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   	_rayleigh)rF   r{  rD   r6   r   s        r'   r  r    s    8 :s+&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	3ue	,,r)   c                   |t        j                  |      }n t        d|t        j                  |             t        | ||      }|j	                  |      }t        j                  ||      }t        j                  |      }t        |d      }t        j                  t        j                  ||            }t        j                  ||      }|S )Nr  rY  )rC   rD   r   r   r   rK   r  r   r  r   rA  r   )	rF   r{  rD   r6   rP  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        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   _wald)rF   rT  rD   r6   r   s        r'   r  r  	  s    : 63'&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##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  r1   r   )rC   rD   r   r   r   rK   r  r<  r   r   integer_powrA  r   r  )rF   rT  rD   r6   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        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   
_geometric)rF   r2  rD   r6   r   s        r'   r  r  Q	  s    6 ;,&#q##E*			5"**	-
 ##('+ , ,

#
#E
*%
##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   )rC   rD   r   r   r   r   r6   r   r  r  rK   r  r  r  r   )rF   r2  rD   r6   rP  r  log_one_minus_pr:  s           r'   r  r  v	  s    
]XXa[EeRXXa[1+q!a "!c5!''"!
''!*%IIqbM/$$_e</	ii/014!	
%r)   c                &   t        d|       \  } }t        j                  |       t        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r   r<   r   r   r   _triangular)rF   leftr"  rightrD   r6   r   s          r'   r  r  	  s    H <-&#q##E*			5"++	.
 ##('+ , ,

#
#E
*%
##E*E	S$eUE	::r)   )r   rW  )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   rC   rD   r   rK   r  r   rA  r   )rF   r  r"  r  rD   r6   fcrP  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        j                  |t        j
                        st        d|       t        j                  |      }|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 )rI   r   r   r5   rC   r=  r<   r   r   r   
_lognormal)rF   sigmarD   r6   r   s        r'   r  r  	  s    2 ;,&#q##E*			5"**	-
 !7$ % %

#
#E
*%
##E*E	Cu	--r)   c                    |t        j                  |      }n t        d|t        j                  |             t        j                  ||      }t        | ||      |z  }t        j                  |      S )Nr  )rC   rD   r   rK   r  r<  r   r  )rF   r  rD   r6   scaled_norms        r'   r  r  	  s\    
]XXe_Eubhhuo6


5%
(%sE5)E1+		r)   c                j   t        j                  g d| j                        }| dk  }t        j                  t        | d      | t        | d            } | dz   | dz   z  }ddd	|z  z
  |z  z
  | dz   z  }t        j                  |       } t        j                  ||t        j                  |          |      S )
N)
gW
ڼq?g;>*?g&W?gxb&J?g?QN?g{k?g^J.aM]?g?0{^R?gb?gCL?r%  	   r   g      "@r   gUUUUUU?gllf?gJ?)	rK   r   r6   r   clampr   r  r   int32)r'  stirling_tail_valsuse_tail_valueskp1sqapproxs        r'   _stirling_approx_tailr  	  s    yy GG F/	ii
1c"Az!S'9:!q5QU
%	J$66%??AEJ&	iil!	O%7		!%Ev	NNr)   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   r6   rK   r  r  )r  r  num_geomgeom_sumrF   r   num_geom_outrP  geomcountlog1minusprobprobrD   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   r1   r  )r  r  r  r  r
  s      r'   r  z$_binomial_inversion.<locals>.cond_fn
  s1    (E!HxA""$I66r)   r   r   )r   enable_checksr;   rK   r5   r6   r   r  r   r   r  r   )rF   r  r  rD   r6   r
  r  r  num_geom_initgeom_sum_initr  r'  r  s    ``` `      @r'   _binomial_inversionr  
  s    >>$**cll333))TE"-.7 --aU;---aU;-m]C
0%	nnWgu-a0!
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         j                        | f}
t        j                  |||
      d   j                  |      S )Nr   gffffff?r  gEJYga+e?{Gz?ro  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   ro  r  r1   r   r   )
r   r   r6   rK   r  r  r  r  r   r   )r  r  r  r  rF   r  r  rP  r`  usr  r'  r  ubr  r  r0  r  rm  r  r  r  r  r  rD   r!  s                   r'   r  z_btrs.<locals>.body_fn4
  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'   r  z_btrs.<locals>.cond_fnN
  s,    (E!HxAI??I..r)   r&  r   F)
rK   rA  r  r   r   r6   fullr#  r  r   )rF   r  r  rD   r6   r
  stddevr  r  r  r  r0  r  rm  r  r  r  r!  s    ``` `     @@@@@@@r'   _btrsr  '
  s    88EDLAH-.&
TF]!
TD[(!dlS!sQw#
a$h!#'>V
#%	iid"#!' '4/ ==r4::u5&fchhueSYY7
=%	%	0	3	:	:5	AAr)   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binomialro  r   r   r  g      $@g     @)rK   r   rD   r   rC   r   r   r   r6   r  r   r(   isinfr   r  rA   r   r   r  r  nanrl  r   )rF   r  r  rD   r6   	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  W
  sy    ]  5!1399T?CE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5)--.)JJY5%C	#z65%;' X 00'JJMM'377E*' JJ'MM'377E*' JJ  8+i7	LL'!'
 
.r)   c                >   t        d|       \  } }t        d||       t        j                  |       t        j                  |t
        j                        st        d|       t        j                  |      }|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 )rI   r   r   r   r5   rC   r   r<   r   r   r   r  )rF   rZ  r2  rD   r6   r   s         r'   r  r  
  s    D :s+&#q*a###E*			5"++	.

B5'J  
#
#E
*%
##E*E	31eU	++r)   random_clonec                    | S r#   rt   r%   s    r'   r   r   
  s    1 r)   c                    |gS r#   rt   )r   r'  s     r'   r   r   
  s    QC r)   )rD   r6   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  rj  r6   )	remainder	ratio_keyratiorF   r  s        r'   r   zmultinomial.<locals>.f
  s:    JE3S)UZZ1%5Y__MEue##r)   r   T)reverser   )r  )rI   r   r   rD   rK   r  r;  r   r,  r2  r   scanr   )rF   rZ  r2  rD   r6   r  r   r   remaining_probsratiosr}   r  countss                r'   r  r  
  s   D =#.&#q-A&	1	%$!Q
]GGE	q%*%!	q% !$
 
ll1b!!JJq!T2/syyA-q/BB&	sFLLO	$$hhq!fd^FC)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  )rF   s    r'   cloner    s     
		S	!!r)   )r&   r   rk   r   )rE   rc   rF   r   r+   rm   rk   ztuple[Array, bool])rF   r   rQ   rl   rD   Shaperk   r   )r~   PRNGSpecDesc | Nonerk   rZ   )r   rc   r   int | ArrayLiker~   r  rk   r   )r   r  r.   r  rk   r   )rF   r   r   IntegerArrayrk   r   )rF   r   r   int | tuple[int, ...]rk   r   )rF   r   r   r  rk   r   )r}   r   rk   rZ   )r}   r   rk   str | PRNGSpec)r}   r   rk   r  )r}   r   rk   r   )r}   r   rk   r   )r   r   r.   r  )rE   rc   rD   r  rk   None)rt   N)rF   r   rD   r  r6   zDTypeLikeUInt | Nonerk   r   )rF   r   rD   r  r6   DTypeLikeFloatr   	RealArrayr   r
  rk   r   )rk   r   )rF   r   rD   r  r   r  r   r  r6   DTypeLikeIntrk   r   )r   F)
rF   r   r&   r  r  rl   r  rm   rk   r   )rt   TNr   N)rF   r   r0  r  rD   r  r1  rm   r2  zRealArray | Noner  rl   r"  
str | Nonerk   r   )rF   r   rD   r  r6   r	  rk   r   )NNr	   )rF   r   rT  r
  rU  r
  rD   Shape | Noner6   zDTypeLikeFloat | NonerV  rc   rk   r   )rF   r   re  r
  rf  r
  rD   r  r6   r	  rk   r   )
rF   r   r2  r
  rD   r  r"  rc   rk   r   )
rF   r   r2  r   rD   r  r"  rc   rk   r   )rF   r   r0  r
  rm  r
  rD   r  r6   r	  rk   r   )
rF   r   r  r
  rD   r  r6   r	  rk   r   )rF   r   rk   r   )
rF   r   r0  r
  rD   r  r6   r	  rk   r   )F)
rF   r   r  r
  rD   r  r6   r  rk   r   )
rF   r   rD   r  r6   r	  r"  r  rk   r   )r&  NTN)rF   r   r<  r
  r  rl   rD   r  r1  rm   r"  r  rk   r   )
rF   r   rm  r
  rD   r  r6   r	  rk   r   )
rF   r   rU  r
  rD   r  r6   r	  rk   r   )
rF   r   rU  r
  rD   r  r6   r	  rk   r   )rF   r   rc  r
  rd  r
  rD   r  r6   r	  rk   r   )rF   r   rD   r  r6   r  rk   r   )rF   r   rz  r
  r{  r
  rD   r  r6   r	  rk   r   )rF   r   r{  r
  r  r
  rD   r  r6   r	  rk   r   )rF   r   rZ  rl   rD   r  r6   r	  r  z
int | Nonerk   r   )
rF   r   r2  floatrD   r  r6   r	  rk   r   )
rF   r   r  rl   r2  r  rD   r  r6   r	  )
rF   r   r{  r
  rD   r  r6   r	  rk   r   )
rF   r   rT  r
  rD   r  r6   r	  rk   r   )
rF   r   r2  r
  rD   r  r6   r  rk   r   )rF   r   r  r
  r"  r
  r  r
  rD   r  r6   r	  rk   r   )
rF   r   r  r
  rD   r  r6   r	  rk   r   )rF   r   rZ  r
  r2  r
  rD   r  r6   r	  rk   r   )rF   r   rZ  r
  r2  r
  rD   r  r6   r	  r  z
int | bool)
__future__r   collections.abcr   	functoolsr   r(  operatorr   r   r   r=   numpyrC   	jax.numpyrK   jaxr   jax.numpy.linalgr	   r
   r   jax._srcr   r   r   r   r   r   jax._src.apir   r   jax._src.interpretersr   r   r   jax._src.laxr  jax._src.nn.functionsr   jax._src.numpy.lax_numpyr   jax._src.numpy.utilr   r   r   jax._src.pjitr   jax._src.sharding_implsr   jax._src.typingr   r   r    jax._src.utilr!   r
  r  r  DTypeLikeUIntr	  rl   r  rZ   r   r  r   r(   rI   rN   rS   r9   rX   rc   PRNGSpecDescr   r   rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r  r  r	  r$  r<  r>  rC  rR  rS  rc  rd  r  rt  rv  r|  r}  r  r  r  r  r  r  r  r  r  r  	Primitiver  def_impldef_abstract_evaldefjvp2register_lowering	lower_funprimitive_batchersr  r  r  r  r$  r+  r-  r.  r0  r4  rD  rE  rJ  rK  rN  rO  r   rS  r\  r]  r   rb  rl  rm  rq  rr  rx  ry  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  rt   r)   r'   <module>r-     sH   # $          0 0       " $ * & , ) > S S # 9 7 7 + 	 ==
   

 +0 #' 4F F;A"E E0 S(H,-P.
+'
+,1
+ %)!!!-2!* )->%>16>:-&	-<
B
" /39+9*84 '+@ 	@@$@  %	@D $) " "	G GG!G G 	G #(GB 	V$%? %%?X #&	   !  	 #(< 	V$;I %;I@ $)N
 "N"NN "N
 ',N@5 	T" #B !%"UOUOUO UO 	UO
 UO UO (-UOr #( O 	 O O  O "'	 OD 	V$
+ %
+ 	V$> %> /37;&00D'0D&0D  ,0D  5	0D
 !$0D
 6;0Dd 	Y' (F ,0-2	+F
 &*+F%+F%+F )+F +	+F
 /4+FZ 	V$O %O0 (RZZ_$((.(.!(. (. %*(.V 	w/01 11(  $!&	&(&(&( &( 	&( ,1	&(R<* #($$ $-2$> 	V$> %> %)&++.+.!+. $+. 16+.Z 	V$( %($  "(-))%)27)> 	V$( %(A)H$( 05 '";  /    $     !6 7 


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