
    Vpf0                   ?   U d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 ddl
Z
ddlZddlZddlZddlmZmZmZmZmZmZmZ ddlmZ ddlZddlZddlZddlZddlmZ dd	lmZ dd
lm Z  ddl!m"Z"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(m0Z0 ddl(m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z= dd
l>m Z? ddl@mAZB ddlCmDZD ddlCmEZE ddlCmFZF ddlGmHZH ddlImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZTmUZUmVZVmWZWmXZXmYZZm[Z[ d D ]$Z\	  e
j]        e\ d!          Z^ n# e_$ r dZ^Y !w xY wdZ` ed"          ZadԐdd*Zbd+Zcd,Zdeje        Zeejf        Zfejg        Zgejh        Zheji        Ziejj        Zjejk        Zkejl        Zldd/Zmejn        xZnZoejp        xZpZqejr        Zrdd1Zs G d2 d3et          Zud4 Zveve)jw        eu<   dd7Zx exejy                  Zye0jz         exe0jz                  Zz exe0j{                  Z{ exej|                  Z| exej}                  Z} exej~                  Z~ exej                  Ze0j         exe0j                  Z exe0j                  Z exej                  Z exej                  Z exej                  Z exej                  Z exe0j                  Z exe0j                  Z exe0j                  Z exe0j                  Z exe0j                  Z exe0j                  Z exej                  Z exej                  xZZ exej                  xZZ exej                  xZZ exej                  xZZe0j        ej        k    reneZe0j        ej~        k    re~neZe0j        ej        k    reneZd%ed8<   e0j        ej        k    reneZej        Zej        Zej        Zej        Zej        Zej        Zej        Zej        Zej        Zej        Zej        Ze0j        Ze0j        Zej        Ze0j        Ze0j        Ze[Zej        Zej        Zej        Zej        Z eFj        ej                  d9d9d:dd?            ZeeyeeeeeeiZd@edA<   e?j        ZddFZ eFj        ej        d9G          ddJ            Z eFj        ej        dKL          eddO                        Z eFj        ej        dKL          eddP                        Z eFj        ej                  ddT            Z eFj        ej                  ddV            Zej        Z eFj        ej                  ddW            Z eFj        ej        dKL          eddX                        ZdYZ e	eg dZ[          	 dddb            Z e	edc[          ddddeddh            Z e	edc[          ddddeddj            Z eFj        ej                  	 	 	 dddq            Z eFj        ej                  	 	 	 	 dddv            Z eFj        ej                  	 	 	 	 dddz            Z eFj        ej                  	 	 	 	 ddd}            Zd~ZɐdddZ eFj         eedd                    dd            Z̐ddZ eFj        ej        eɬ           e	ed[          ddd                        ZΐdddZ e	ed[          ddd            ZАddZѐddZedd            Zedd            Z e	edg[          ddd            Z eFj        ej                   e	ed[          	 	 	 ddd                        ZdZ eFj        ej        e׬          e	 	 ddd                        Z eFj        ej        dg           e	ed[          ddddd                        ZِddZ	 d eL            dddZ e	edd          ddd            Z	 dddZݐd dĄZ eFj        ej                   e	edŬ[          ddǄ                        ZߐdddȄZ e	edd          ddɄ            Zdd˄Z e	edd          ddτ            Zdd҄Z e	edd          ddԄ            Z e	edլ[          	 	 dd	d܄            Z	 	 	 d
ddZ eFj        ej         ed                    	 	 	 d
dd            Ze	 	 dddddd            Zeddddd            Ze	 	 dddddd            ZdddddZ eFj        ej                  	 ddd            Z	 	 dddddZedd            Zedd            Z eFj         eedd                    d             Z eFj        ej        d           dd            Z eFj        ej        d           dd            Z	 dddZ eFj        ej        eɬ          	 ddd	            ZddZ edd          Z edd          Z edd          Z eFj        ej                  	 ddd            Z e.j        d           e	 	 	 d
 eL             eL             eL            ddd            Z eFj        ej        dg           e	ed[          ddd                        ZeZeZ eFj        ej        dg          eddd                         Z eFj        ej                  e	 	 	 ddd%                        Z e	edլ[          	 	 dd	d&            Zdddd d'Zdddd!d(Z eFj        ej                    e	ed[          dddeez  fd"d+                        Z eeaeea         eeea                  f         Zeeeaeaf         d,f         Z G d- d.e          Zd#d4Zd$d7Zd%d;Zd&d<Zd'd>Z	d&d?Z
d(dBZd)dFZd&dGZd*dJZ e	edKL          d+dO            Z eFj        ej        dP          	 d,d-dT            Z eFj        ej        dg          	 d.d/dW            Z eFj         eedXd                     e	ed[          ddd0dY                        Z eFj        ej                  d1d]            Z	 dd2d^Z eFj        ej                  	 dd3d_            Z eFj         eed`d                    ddd4da            Z eFj        ej                  	 dd5dc            Z eFj        ej                  	 dd5dd            Z eFj        ej                  	 dd5de            Z eFj        ej                  d6df            Z eFj        ej        dg          	 d7d8dh            Zd9diZd:dlZ eFj        ej                  ed;dm                        Zed<dn            Zeddo            Zed=dq            Z eFj        ej        d9eɐr          ed>ds                        Zed<dt            Z eddu            Z ed=dv            Z  eFj        ej         d9eɐr          ed>dw                        Z ed<dx            Z!eddy            Z!ed=dz            Z! eFj        ej!        d9eɐr          ed>d{                        Z!d| Z"d}Z# e.j        d~            eFj        ej$        e#d          	 	 d?ddd@d            Z$dAdZ%dBdZ& e.j        d           d9dddCdZ' eFj        ej(        e#d          dddddDd            Z( eFj        ej)        e#          ddEd            Z)	 	 ddddFdZ*	 	 ddddFdZ+	 	 ddddGdZ,dAdZ-	 ddddHdZ.	 	 ddddIdZ/ddddJdZ0ddddJdZ1ddddJdZ2dKdZ3ddLdZ4dMdZ5 eFj        ej6                  eddfdNd            Z6d Z7d Z8 eFj         eedd          d          ddddOd            Z9 eFj        ej:                  eddPd            Z: eFj        ej;                  edfdQd            Z;	 	 	 dRdddSdZ<	 	 	 dRdTdZ=ddUdZ>	 	 d
dddVdZ?	 	 d
dWdZ@dXdZAe	 	 	 	 dYdddZdȄ            ZBe	 	 dddd[dʄ            ZBe	 	 d\dddd˜d[d̄            ZBe	 	 	 	 dYddd]d΄            ZB eFj        ejB        dϦ          	 	 	 	 dYddd]dЄ            ZB e	edѬ[          	 	 	 	 dYddd]d҄            ZC eFj        ejD                  	 	 	 d^d_dՄ            ZD e	ed֬[          	 	 	 d^d_dׄ            ZE eFj        ejF                  	 	 d`dad؄            ZF e	ed֬[          	 	 d`dadل            ZG eFj        ejH        eɬ          dd9dڐdۜdbd߄            ZHe- eFj        ejI                  edd                                    ZIeIjJ        d             ZKdcdZLe	 	 ddded            ZMeddfd            ZMe	 	 dddgd            ZM eFj        ejM                  	 	 dddgd            ZMddddhdZN eFj         eed eedd                               e	ed[          	 	 didjd                        ZOdRdkdZP e	ed[          ddld            ZQ e	ed[          ddld            ZR eFj        ejS        dg           e	ed[          	 	 dmdnd                        ZSd ZT eTejU                  ZUd ZVddodZWddodZXddpdZYddpdZZddddqd Z[ eFj        ej\                  dddrd            Z\ eFj        ej]                  dsd            Z] eFj        ej^        eɬ           e	ed[          	 	 dtdud                        Z^ eFj        ej_        eɬ          ddvd            Z_ e	ed[          d             Z`dZa eFj        ejb        ea          ddvd	            Zb eFj        ejc                  dwd            ZcdwdZd e	ed[          	 ddxd            Ze	 dd9ddydZf eFj        ejg                  	 ddzd            Zg eFj        ejh                  d{d            Zh eFj        eji                  d|d            Zi e	eded          ddded}d            Zj e	eded          ddded}d            Zk e	eded          ddded}d            Zlddddd~dZm	 dddddeddZn G d  d!ejo        jp                  Zqedd"dde jr        d#dd)            Zsedd"dde jr        d#dd,            Zsdd"dde jr        d#dd-Zsi Ztd. Zued,d/dd3            Zved,d/dd4            Zvd5d/dd6Zvd7 Zwe jr        fdd;Zx e	eded          dddedd=            Zy eFj        ejz        dg           e	ed>          ddd?                        Zz eFj        ej{                   e	ed@[          	 	 dddD                        Z{ eFj        ej|                  eddE                        Z| eFj        ej}                   e	edF[          	 ddddH                        Z}dddddIZ~ eFj        ej        dg          	 	 d
ddK            Z e	edLd          ddddM            Z eFj        ej        dg          	 	 d
ddN            Z e	edLd          ddddO            ZdPZ eFj        ej        e                    d          dgQ          	 	 	 d
ddR            Z e	edL[          ddddS            Z eFj        ej        e                    d          dgQ          	 	 	 d
ddT            Z e	edL[          ddddU            Z e	edV[          	 ddddd9dWdd[            Z eFj        ej                  edd\                        Z eFj        ej                   e	ed[          ddd_                        Z e	edV[          	 ddddd9dWdd`            Z e	edadg[          dddb            Z e	edadg[          dddc            Z e	eddL          ddf            Z e	edgL          ddh            Z eFj        ej                  	 dddj            Z e	edk[          dddl            Z eFj        ej                   e	edm[          	 dddp                        Z eFj        ej                   e	edq[          	 	 	 dddr                        Z	 	 	 	 	 	 dddvZ e	edw[          	 	 dddx            Zdy Z e	edz[          	 	 ddd|            Zdd~ZddZd Zd ZddZ	 	 ddZd Z G d de          Zd Zd Zd Z	 dddZd Zd Zd Zd Zd Zd Zd Zd ZddZddZ eFj        ej                  dd            Z eFj        ej                  dd            Z eFj        ej                  dd            Z eFj        ej                  dd            Z eFj        ej                  dd            ZddZddZ eFj        ej        dKL          edܐd                        Z eFj        ej        dKL          edܐd                        ZdddddZdddddddZ eFj        ej                   e	ed[          	 	 	 	 ddd                        Z eFj        ej                   e	ed[          ddd                        Z e	eHh d          dd            ZddZddZ e	ed[          	 	 ddddd            Z eFj        ej                   e	ed¬[          dddÄ                        ZdĐZ eFj        ej        e          ddȄ            Z e	edg[          dd̈́            ZÐdd΄ZddddфZ	 dddddӄZdS (  a  
Implements the NumPy API, using the primitives in :mod:`jax.lax`.

NumPy operations are implemented in Python in terms of the primitive operations
in :mod:`jax.lax`. Since NumPy operations are not primitive and instead are
implemented in terms of :mod:`jax.lax` operations, we do not need to define
transformation rules such as gradient or batching rules. Instead,
transformations for NumPy primitives can be derived from the transformation
rules for the underlying :code:`lax` primitives.
    )annotationsN)CallableSequence)partial)overloadAnyLiteral
NamedTupleProtocolTypeVarUnion)dedent)jit)errors)lax)ShardingSingleDeviceSharding)tree_leavestree_flattentree_map)api_util)config)core)
custom_jvp)deprecations)dispatch)dtypes)
xla_bridge)_ensure_index_tuple)	ArrayImpl)ShapedArrayConcreteArray)_array_copy_sort_lt_comparator_sort_le_comparatorPrecisionLike)
xla_client)
reductions)ufuncs)util)	vectorize)	Array	ArrayLikeDeprecatedArgDimSizeDuckTypedArrayDType	DTypeLikeShapeStaticScalar)unzip2subvalssafe_zipceil_of_ratiopartition_listcanonicalize_axisNumpyComplexWarning)jax_cuda12_pluginz
jax.jaxlibz.cuda_plugin_extensionT shaper   contextstrreturn
core.Shapec                    t          | t          t          f          s>t          | dd           dk    st	          |           dk    rt          j        | f|          S t          j        | |          S )Nndimr   )
isinstancetuplelistgetattrrE   r   canonicalize_shape)r?   r@   s     X/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/numpy/lax_numpy.pyrJ   rJ   _   sg    
UUDM
*
* 3ufd##q((DKK1,<,<"E8W555"5'222    a  In addition to the original NumPy arguments listed below, also supports
``precision`` for extra control over matrix-multiplication precision
on supported devices. ``precision`` may be set to ``None``, which means
default precision for the backend, a :class:`~jax.lax.Precision` enum value
(``Precision.DEFAULT``, ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple
of two :class:`~jax.lax.Precision` enums indicating separate precision for each argument.
z	jax.numpyxboolc                    | dS 	 | j         j        }n)# t          $ r t          |           j         j        }Y nw xY wt	          |t
                    S )a  Check if the input is a complex number or an array containing complex elements.

  JAX implementation of :func:`numpy.iscomplexobj`.

  The function evaluates based on input type rather than value.
  Inputs with zero imaginary parts are still considered complex.

  Args:
    x: input object to check.

  Returns:
    True if ``x`` is a complex number or an array containing at least one complex element,
    False otherwise.

  See Also:
    - :func:`jax.numpy.isrealobj`
    - :func:`jax.numpy.iscomplex`

  Examples:
    >>> jnp.iscomplexobj(True)
    False
    >>> jnp.iscomplexobj(0)
    False
    >>> jnp.iscomplexobj(jnp.array([1, 2]))
    False
    >>> jnp.iscomplexobj(1+2j)
    True
    >>> jnp.iscomplexobj(jnp.array([0, 1+2j]))
    True
  NF)dtypetypeAttributeErrorasarray
issubdtypecomplexfloating)rM   typs     rK   iscomplexobjrW      s^    > Y5 
',CC	      
!**

CCC 	C	)	))s    #99r1   c                .    t          j        | d          S )NT)canonicalize)r   rP   rM   s    rK   _dtyper[      s    	ad	+	+	++rL   c                  B    e Zd ZU ded<   ddZdd	Zdd
ZddZddZdS )_ScalarMetaznp.dtyperP   rB   intc                4    t          | j        j                  S N)hashrP   rQ   )selfs    rK   __hash__z_ScalarMeta.__hash__   s    
   rL   otherr   rN   c                b    t          |           t          |          k    p| j        j        |k    S r`   )idrP   rQ   rb   rd   s     rK   __eq__z_ScalarMeta.__eq__   s'    d88r%yy <DJOu$<<rL   c                    | |k     S r`    rg   s     rK   __ne__z_ScalarMeta.__ne__   s    rL   rM   r,   c                .    t          || j                  S NrP   )rS   rP   )rb   rM   s     rK   __call__z_ScalarMeta.__call__   s    1DJ''''rL   instancec                6    t          || j        j                  S r`   )rF   rP   rQ   )rb   rp   s     rK   __instancecheck__z_ScalarMeta.__instancecheck__   s    h
000rL   N)rB   r^   )rd   r   rB   rN   )rM   r   rB   r,   )rp   r   rB   rN   )	__name__
__module____qualname____annotations__rc   rh   rk   ro   rr   rj   rL   rK   r]   r]      s         ///! ! ! != = = =   ( ( ( (1 1 1 1 1 1rL   r]   c                (    t          d|  d          )NzJAX scalar type z& cannot be interpreted as a JAX array.)	TypeErrorrZ   s    rK   _abstractify_scalar_metary      s    NQNNNOOOrL   np_scalar_typerQ   c                ~    t          | j        t          fdt          j        |           i          }t
          |_        |S )NrP   )r]   rs   objectnprP   _PUBLIC_MODULE_NAMErt   )rz   metas     rK   _make_scalar_typer      s8    	^,virx778
: 
:$'$/	+rL   float_FaligncopyobjDTypeLike | Noner   r   c                   t          j        | t           j                  r| S | t           j        } n0t	          | t
                    r| t           j        v rt          |          } t          j	        | ||          S )z5Similar to np.dtype, but respects JAX dtype defaults.Nr   )
r   rT   extendedr   rF   rQ   python_scalar_dtypes_DEFAULT_TYPEMAPr}   rP   )r   r   r   s      rK   
_jnp_dtyper     sn     sFO,, J[
-CC#t  (C!C!C
3
C	#U	.	.	..rL   zdict[type, _ScalarMeta]r   valr-   rP   r,   c           	        t          | t                    r| nt          |           } t          j        |          }t          |t                    rt          | j        t                    st          d          t          j        | j                  }|| j        k    r	 t          | t          t          |          j        t          |          j                            }t          | t          t          |          j
        t          |          j
                            }t          | ||                              |          S )a  
  Convert integer-typed val to specified integer dtype, clipping to dtype
  range rather than wrapping.

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

  Returns:
    equivalent of val in new dtype

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

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

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

  >>> _convert_and_clip_integer(val, 'int32')
  Array(2147483647, dtype=int32)
  z6_convert_and_clip_integer only accepts integer dtypes.)rF   r,   rS   r   canonicalize_dtyperT   integerrP   rx   
_lax_constmaxiinfominclipastype)r   rP   	val_dtypemin_valmax_vals        rK   _convert_and_clip_integerr   &  s   2 #u%%773<<#

#E
*
*%
UG
$
$ NCIw)G)G N
L
M
MM'	22)#) 	sCe 0%	2B2B2FGGHH'sCe 0%	2B2B2FGGHH'	c7G	$	$	+	+E	2	22rL   
update_docargskwargsc                     t          j        | i |}t          |t           j                  rM|j        dk    r|                    t                    }	 t          |          }n# t          t          f$ r Y nw xY w|S )NV2)
r}   loadrF   ndarrayrP   viewbfloat16rS   rx   AssertionError)r   r   outs      rK   r   r   O  s     	   #RZ   
yDHHXcCLLcc~&   
d	*s   A" "A65A6numpy)modulex1x2c                t    t          t          j        | |          t          j        |          z  | |          S r`   )wherer)   lessisnanr   r   s     rK   fminr   `  s1     
v{2r""V\"%5%55r2	>	>>rL   c                t    t          t          j        | |          t          j        |          z  | |          S r`   )r   r)   greaterr   r   s     rK   fmaxr   e  s1     
v~b"%%R(8(88"b	A	AArL   arg1r2   arg2c                ,    t          j        | |          S r`   )r   rT   )r   r   s     rK   rT   rT   j  s    		4	&	&&rL   elementc                    t          | d          r|                                 } t          j        |           pt	          j        |           S N__jax_array__)hasattrr   r   is_python_scalarr}   isscalar)r   s    rK   r   r   n  sE    Wo&& &##%%G		 	)	)	AR[-A-AArL   c                     t          j        |  S r`   )r   result_typer   s    rK   r   r   v  s    		T	""rL   c           	     N   t          j        d|            t          j        t          j        |           d          rt          j        |           S t          t          j	        | t          | d                    t          j        |           t          j        |                     S )Ntrunc)integralrN   r   )r*   check_arrayliker   isdtyperP   lax_internalrS   r   r   ltr   r)   ceilfloorrZ   s    rK   r   r   {  s}     w"""^FLOO%9:: #"""	svaAq))**FKNNFLOO	L	LLrL   a  
preferred_element_type : dtype, optional
    If specified, accumulate results and return a result of the given data type.
    If not specified, the function instead follows the numpy convention of always
    accumulating results and returning an inexact dtype.
modeop	precisionpreferred_element_typestatic_argnamesyr   r   r   r&   r   c                   t          |           dk    st          |          dk    rt          | d          |t          j        | |          \  } }nt          j        | |          \  } }t          |           dk    st          |          dk    r"t          | d| j         d|j         d          t          d           }|dk    rJt          j	        |          }t          |           t          |          k     r|| }} t          d d d          }n9|d	k    r3t          |           t          |          k     r|| }} t          |          }|d
k    rdg}np|dk    r3|j        d         dz  |j        d         |j        d         dz  z
  dz
  fg}n7|dk    r"|j        d         dz
  |j        d         dz
  fg}nt          d          t          j        | d d d d f         |d d d d f         d|||          }|dd|f         S )N   z%() only support 1-dimensional inputs.r   z%: inputs cannot be empty, got shapes  and .	correlateconvolvevalidr   r   same   fullz-mode must be one of ['full', 'same', 'valid']r   r   r   )rE   
ValueErrorr*   promote_dtypes_inexactpromote_dtypeslenr?   slicer)   conjflipr   conv_general_dilated)	rM   r   r   r   r   r   	out_orderpaddingresults	            rK   _convr     s    
!WW\\T!WW\\
AAA
B
BB#&q!,,DAqq q!$$DAqVVq[[CFFaKK
YYYYqwYYY
Z
ZZDkk);AA
1vvAadB''i	Z
1vvAaQA	W__hGGv~~
aagajAo!=!ABCGGv~~
Q
Q/0GG
D
E
EE#AdD!!!m$4adAAA6F$+y;QS S S& 
1i	  rL   )r   r   r   r   r   avc                   t          j        d| |           t          t          |           t          |          |d||          S )a  Convolution of two one dimensional arrays.

  JAX implementation of :func:`numpy.convolve`.

  Convolution of one dimensional arrays is defined as:

  .. math::

     c_k = \sum_j a_{k - j} v_j

  Args:
    a: left-hand input to the convolution. Must have ``a.ndim == 1``.
    v: right-hand input to the convolution. Must have ``v.ndim == 1``.
    mode: controls the size of the output. Available operations are:

      * ``"full"``: (default) output the full convolution of the inputs.
      * ``"same"``: return a centered portion of the ``"full"`` output which
        is the same size as ``a``.
      * ``"valid"``: return the portion of the ``"full"`` output which do not
        depend on padding at the array edges.

    precision: Specify the precision of the computation. Refer to
      :class:`jax.lax.Precision` for a description of available values.

    preferred_element_type: A datatype, indicating to accumulate results to and
      return a result with that datatype. Default is ``None``, which means the
      default accumulation type for the input types.

  Returns:
    Array containing the convolved result.

  See Also:
    - :func:`jax.scipy.signal.convolve`: ND convolution
    - :func:`jax.numpy.correlate`: 1D correlation

  Examples:
    A few 1D convolution examples:

    >>> x = jnp.array([1, 2, 3, 2, 1])
    >>> y = jnp.array([4, 1, 2])

    ``jax.numpy.convolve``, by default, returns full convolution using implicit
    zero-padding at the edges:

    >>> jnp.convolve(x, y)
    Array([ 4.,  9., 16., 15., 12.,  5.,  2.], dtype=float32)

    Specifying ``mode = 'same'`` returns a centered convolution the same size
    as the first input:

    >>> jnp.convolve(x, y, mode='same')
    Array([ 9., 16., 15., 12.,  5.], dtype=float32)

    Specifying ``mode = 'valid'`` returns only the portion where the two arrays
    fully overlap:

    >>> jnp.convolve(x, y, mode='valid')
    Array([16., 15., 12.], dtype=float32)

    For complex-valued inputs:

    >>> x1 = jnp.array([3+1j, 2, 4-3j])
    >>> y1 = jnp.array([1, 2-3j, 4+5j])
    >>> jnp.convolve(x1, y1)
    Array([ 3. +1.j, 11. -7.j, 15.+10.j,  7. -8.j, 31. +8.j], dtype=complex64)
  r   r   r*   r   r   rS   r   r   r   r   r   s        rK   r   r     sO    L z1a(((	wqzz71::DZ";Q
S 
S 
S SrL   r   c                   t          j        d| |           t          t          |           t          |          |d||          S )a
  Correlation of two one dimensional arrays.

  JAX implementation of :func:`numpy.correlate`.

  Correlation of one dimensional arrays is defined as:

  .. math::

     c_k = \sum_j a_{k + j} \overline{v_j}

  where :math:`\overline{v_j}` is the complex conjugate of :math:`v_j`.

  Args:
    a: left-hand input to the correlation. Must have ``a.ndim == 1``.
    v: right-hand input to the correlation. Must have ``v.ndim == 1``.
    mode: controls the size of the output. Available operations are:

      * ``"full"``: output the full correlation of the inputs.
      * ``"same"``: return a centered portion of the ``"full"`` output which
        is the same size as ``a``.
      * ``"valid"``: (default) return the portion of the ``"full"`` output which do not
        depend on padding at the array edges.

    precision: Specify the precision of the computation. Refer to
      :class:`jax.lax.Precision` for a description of available values.

    preferred_element_type: A datatype, indicating to accumulate results to and
      return a result with that datatype. Default is ``None``, which means the
      default accumulation type for the input types.

  Returns:
    Array containing the cross-correlation result.

  See Also:
    - :func:`jax.scipy.signal.correlate`: ND correlation
    - :func:`jax.numpy.convolve`: 1D convolution

  Examples:
    >>> x = jnp.array([1, 2, 3, 2, 1])
    >>> y = jnp.array([4, 5, 6])

    Since default ``mode = 'valid'``, ``jax.numpy.correlate`` returns only the
    portion of correlation where the two arrays fully overlap:

    >>> jnp.correlate(x, y)
    Array([32., 35., 28.], dtype=float32)

    Specifying ``mode = 'full'`` returns full correlation using implicit
    zero-padding at the edges.

    >>> jnp.correlate(x, y, mode='full')
    Array([ 6., 17., 32., 35., 28., 13.,  4.], dtype=float32)

    Specifying ``mode = 'same'`` returns a centered correlation the same size
    as the first input:

    >>> jnp.correlate(x, y, mode='same')
    Array([17., 32., 35., 28., 13.], dtype=float32)

    If both the inputs arrays are real-valued and symmetric then the result will
    also be symmetric and will be equal to the result of ``jax.numpy.convolve``.

    >>> x1 = jnp.array([1, 2, 3, 2, 1])
    >>> y1 = jnp.array([4, 5, 4])
    >>> jnp.correlate(x1, y1, mode='full')
    Array([ 4., 13., 26., 31., 26., 13.,  4.], dtype=float32)
    >>> jnp.convolve(x1, y1, mode='full')
    Array([ 4., 13., 26., 31., 26., 13.,  4.], dtype=float32)

    For complex-valued inputs:

    >>> x2 = jnp.array([3+1j, 2, 2-3j])
    >>> y2 = jnp.array([4, 2-5j, 1])
    >>> jnp.correlate(x2, y2, mode='full')
    Array([ 3. +1.j,  3.+17.j, 18.+11.j, 27. +4.j,  8.-12.j], dtype=complex64)
  r   r   r   r   s        rK   r   r     sO    ` {Aq)))	wqzz71::D[";Q
S 
S 
S SrL   
   binsrange"None | Array | Sequence[ArrayLike]weightsArrayLike | Nonec                4   ~t          |t                    rt          d          t          j        d| |           t          |           }t          j        |j                  }t          |          dk    rt          ||          S t          j        t          j        |d          }|(|                                |                                g}t          ||          }t!          |          dk    rt#          d|           t%          t'          j        |          dk    |d         d	z
  |d                   t%          t'          j        |          dk    |d         d	z   |d                   f}|J t+          |d         |d         |dz   |          S )
Nz)string values for `bins` not implemented.histogram_bin_edgesr   rn   z$bins argument of histogram_bin_edgesr   z:`range` must be either None or a sequence of scalars, got r         ?)rF   rA   NotImplementedErrorr*   r   rS   r   to_inexact_dtyperP   _ndimr   concrete_or_erroroperatorindexr   r   r?   r   r   r(   ptplinspace)r   r   r   r   arrrP   bins_ints          rK   r   r   S  s    c K
I
J
JJ,a666

#

!#)
,
,%
4[[A4u%%%%#HND$JL L(
]WWYY		"E
%u
%
%
%%
5\\T
YRWYY
Z
ZZ&&!+U1X^U1XFF&&!+U1X^U1XFFH%					%(E!Hhl%	@	@	@@rL   Sequence[ArrayLike] | Nonedensitybool | Nonetuple[Array, Array]c                   |<t          j        d| |           t          j        |           \  } t          |           }n^t          j        d| ||           t	          |           t	          |          k    rt          d          t          j        | |          \  } }t          | |||          }t          || d          }t          | |d         k    t          |          dz
  |          }t          t          |          |j                  j        |                             |          dd          }|r)t          |          }||z  |                                z  }||fS )N	histogramz(weights should have the same shape as a.rightsider   r   )r*   r   r   	ones_liker?   r   r   searchsortedr   r   zerosrP   atadddiffsum)	r   r   r   r   r  	bin_edgesbin_idxcounts
bin_widthss	            rK   r
  r
  m  sG   
 _a...		$Q	'	'BAllGGaw777Qxx5>>!!ABBB,Q88JAw!!T5'::)AG444'!y}$c)nnq&8'BB'Y//27;??HHL& 0iJj 6::<</F		rL   ArrayLike | list[ArrayLike]3Sequence[None | Array | Sequence[ArrayLike]] | Nonetuple[Array, Array, Array]c                @   t          j        d| |           	 t          |          }n# t          $ r d}Y nw xY w|dk    r|dk    rt	          |          x}}||g}t          t	          | |g                    }	t          |	||||          \  }
}|
|d         |d         fS )Nhistogram2dr   r   r   )r*   r   r   rx   rS   	transposehistogramdd)rM   r   r   r   r   r  Nx_edgesy_edgessamplehistedgess               rK   r  r    s    
 }a+++
D		AA	 
 
 
	AAA
 !VVQ%GgWDWaV__%%&FD%'BB+$	uQxq	!!s   ( 77r#  tuple[Array, list[Array]]c                   |,t          j        d|            t          j        |           \  } net          j        d| |           t          |          t          |           d d         k    rt	          d          t          j        | |          \  } }t          |           \  }}|Ft          |          |k    st          d |D                       rt	          d||f d| d|          	 t          |          }||k    rt	          d          t          |          }n# t          $ r	 ||gz  }Y nw xY wg }	g }
t          j
        |          D ]}|d n||         }t          | d d |f         ||         ||          }t          || d d |f         d	
          }t          | d d |f         |d         k    |dz
  |          }|	                    |           |
                    |           t          d |
D                       }d |
D             }t!          t          |	          |d          }t#          ||t%          j        |                    }t)          ||          }|t+          dd          fz  }||         }|rB|                    | j                  }||                                z  }t3          | D ]}||z  }||
fS )Nr  r   z'should have one weight for each sample.c              3  P   K   | ]!}|d uot          |          d         dk    V  "d S )Nr   r   r?   ).0rs     rK   	<genexpr>zhistogramdd.<locals>.<genexpr>  s:      OOAQd]?uQxx{a/?OOOOOOrL   zFor sample.shape=z, range must be a sequence of z pairs or Nones; got range=z#should be a bin for each dimension.r  r  r   c              3  :   K   | ]}t          |          d z   V  dS r   Nr   r*  r  s     rK   r,  zhistogramdd.<locals>.<genexpr>  s-      EEyI"EEEEEErL   c                ,    g | ]}t          |          S rj   )r  r0  s     rK   
<listcomp>zhistogramdd.<locals>.<listcomp>  s    >>>	DOO>>>rL   r   r   length)r*   r   r   r?   r   r   anyrH   rx   builtinsr   r   r  r   appendrG   ravel_multi_indexbincountmathprodreshaper   r   rP   r  ix_)r#  r   r   r   r  r   Dnum_binsbins_per_dimensionbin_idx_by_dimbin_edges_by_dimirange_ir  r  nbinsdedgesxyr$  r   norms                        rK   r  r    s2   
 _///)&11GFF888W~~vrr***@AAA1&'BBOFG	v$!Q
	%jjAooOOOOOOOo
 <!Q < << <38< < = = =$4yyH
 1}}<===d 
 5 5 5*+tf*5 !#."$>! ' 'amddqG#F111a4L2DQ2GRYZZI9fQQQTlAAAGF111a4LIbM17Q;HHG'"""I&&&&
EE4DEEE
E
E%>>-=>>>&~..FCCC"	"gdi&6&6	7	7	7$	u		$	
E!RLL?	$	d$ ;;v|$$DDHHJJDV  
dldd		s   /D# #D65D6zc
The JAX version of this function may in some cases return a copy rather than a
view of the input.
axesSequence[int] | Nonec                     t          j        d            |2t          t          t	                               ddd                   n|} fd|D             }t          j         |          S )aS	  Return a transposed version of an N-dimensional array.

  JAX implementation of :func:`numpy.transpose`, implemented in terms of
  :func:`jax.lax.transpose`.

  Args:
    a: input array
    axes: optionally specify the permutation using a length-`a.ndim` sequence of integers
      ``i`` satisfying ``0 <= i < a.ndim``. Defaults to ``range(a.ndim)[::-1]``, i.e.
      reverses the order of all axes.

  Returns:
    transposed copy of the array.

  See Also:
    - :func:`jax.Array.transpose`: equivalent function via an :class:`~jax.Array` method.
    - :attr:`jax.Array.T`: equivalent function via an :class:`~jax.Array`  property.
    - :func:`jax.numpy.matrix_transpose`: transpose the last two axes of an array. This is
      suitable for working with batched 2D matrices.
    - :func:`jax.numpy.swapaxes`: swap any two axes in an array.
    - :func:`jax.numpy.moveaxis`: move an axis to another position in the array.

  Note:
    Unlike :func:`numpy.transpose`, :func:`jax.numpy.transpose` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize-away
    such copies when possible, so this doesn't have performance impacts in practice.

  Examples:
    For a 1D array, the transpose is the identity:

    >>> x = jnp.array([1, 2, 3, 4])
    >>> jnp.transpose(x)
    Array([1, 2, 3, 4], dtype=int32)

    For a 2D array, the transpose is a matrix transpose:

    >>> x = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> jnp.transpose(x)
    Array([[1, 3],
           [2, 4]], dtype=int32)

    For an N-dimensional array, the transpose reverses the order of the axes:

    >>> x = jnp.zeros(shape=(3, 4, 5))
    >>> jnp.transpose(x).shape
    (5, 4, 3)

    The ``axes`` argument can be specified to change this default behavior:

    >>> jnp.transpose(x, (0, 2, 1)).shape
    (3, 5, 4)

    Since swapping the last two axes is a common operation, it can be done
    via its own API, :func:`jax.numpy.matrix_transpose`:

    >>> jnp.matrix_transpose(x).shape
    (3, 5, 4)

    For convenience, transposes may also be performed using the :meth:`jax.Array.transpose`
    method or the :attr:`jax.Array.T` property:

    >>> x = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> x.transpose()
    Array([[1, 3],
           [2, 4]], dtype=int32)
    >>> x.T
    Array([[1, 3],
           [2, 4]], dtype=int32)
  r  Nr   c                J    g | ]}t          |t                               S rj   _canonicalize_axisrE   r*  rD  r   s     rK   r2  ztranspose.<locals>.<listcomp>"  s*    
9
9
9aaa))
9
9
9rL   )r*   r   rH   r   rE   r   r  )r   rJ  axes_s   `  rK   r  r    sq    P {A&&&(,$uT!WW~~ddd#
$
$
$$%
9
9
9
95
9
9
9%	q%	 	  rL   permute_dimstuple[int, ...]c               V    t          j        d|            t          j        | |          S )NrR  )r*   r   r   r  )r   rJ  s     rK   rR  rR  &  s'    ~q)))	q$		rL   c                   t          j        d|            t          j        |           }|dk     rt	          d|          g t          |dz
            |dz
  |dz
  R }t          j        | |          S )a&  Transpose the last two dimensions of an array.

  JAX implementation of :func:`numpy.matrix_transpose`, implemented in terms of
  :func:`jax.lax.transpose`.

  Args:
    x: input array, Must have ``x.ndim >= 2``

  Returns:
    matrix-transposed copy of the array.

  See Also:
    - :attr:`jax.Array.mT`: same operation accessed via an :func:`~jax.Array` property.
    - :func:`jax.numpy.transpose`: general multi-axis transpose

  Note:
    Unlike :func:`numpy.matrix_transpose`, :func:`jax.numpy.matrix_transpose` will return a
    copy rather than a view of the input array. However, under JIT, the compiler will
    optimize-away such copies when possible, so this doesn't have performance impacts in practice.

  Examples:
    Here is a 2x2x2 matrix representing a batched 2x2 matrix:

    >>> x = jnp.array([[[1, 2],
    ...                 [3, 4]],
    ...                [[5, 6],
    ...                 [7, 8]]])
    >>> jnp.matrix_transpose(x)
    Array([[[1, 3],
            [2, 4]],
    <BLANKLINE>
           [[5, 7],
            [6, 8]]], dtype=int32)

    For convenience, you can perform the same transpose via the :attr:`~jax.Array.mT`
    property of :class:`jax.Array`:

    >>> x.mT
    Array([[[1, 3],
            [2, 4]],
    <BLANKLINE>
           [[5, 7],
            [6, 8]]], dtype=int32)
  matrix_transposer   zBx must be at least two-dimensional for matrix_transpose; got ndim=r   )r*   r   r}   rE   r   r   r   r  )rM   rE   rJ  s      rK   rV  rV  ,  s    Z )1---	$	AXX
\UY\\
]
]]	/5??	/D1H	/dQh	/	/$	q$		rL   )lax_description)krJ  r   r   r   mrX  r^   tuple[int, int]c                   t          j        d|            t          j        |           dk     r9t	          dt          j        |            dt          j        |                      |\  }}t          |t          |                     }t          |t          |                     }||k    rt	          d          |dz  }|dk    rt          |           S |dk    rt          t          | |          |          S t          t          t          |                               }||         ||         c||<   ||<   |dk    rt          t          | |          |          S t          t          | |          |          S )	Nrot90r   z]rot90 requires its first argument to have ndim at least two, but got first argument of shape z, which has ndim zAxes must be different   r   r   )r*   r   r}   rE   r   r?   rO  rS   r   rH   r   r  )rZ  rX  rJ  ax1ax2perms         rK   r]  r]  a  se    w"""WQZZ!^^
 4=?Xa[[4 4')wqzz4 4 5 5 5 (#s3Q((#3Q((#CZZ
-
.
..!e!!VV1::AvvQc"""d1ggD9d3iDItCyAvvtAs||T***)At$$c***rL   axisint | Sequence[int] | Nonec                    t          j        d|            t          t          |           t	          j        |                    S )a  Reverse the order of elements of an array along the given axis.

  JAX implementation of :func:`numpy.flip`.

  Args:
    m: Array.
    axis: integer or sequence of integers. Specifies along which axis or axes
      should the array elements be reversed. Default is ``None``, which flips
      along all axes.

  Returns:
    An array with the elements in reverse order along ``axis``.

  See Also:
    - :func:`jax.numpy.fliplr`: reverse the order along axis 1 (left/right)
    - :func:`jax.numpy.flipud`: reverse the order along axis 0 (up/down)

  Examples:
    >>> x1 = jnp.array([[1, 2],
    ...                 [3, 4]])
    >>> jnp.flip(x1)
    Array([[4, 3],
           [2, 1]], dtype=int32)

    If ``axis`` is specified with an integer, then ``jax.numpy.flip`` reverses
    the array along that particular axis only.

    >>> jnp.flip(x1, axis=1)
    Array([[2, 1],
           [4, 3]], dtype=int32)

    >>> x2 = jnp.arange(1, 9).reshape(2, 2, 2)
    >>> x2
    Array([[[1, 2],
            [3, 4]],
    <BLANKLINE>
           [[5, 6],
            [7, 8]]], dtype=int32)
    >>> jnp.flip(x2)
    Array([[[8, 7],
            [6, 5]],
    <BLANKLINE>
           [[4, 3],
            [2, 1]]], dtype=int32)

    When ``axis`` is specified with a sequence of integers, then
    ``jax.numpy.flip`` reverses the array along the specified axes.

    >>> jnp.flip(x2, axis=[1, 2])
    Array([[[4, 3],
            [2, 1]],
    <BLANKLINE>
           [[8, 7],
            [6, 5]]], dtype=int32)
  r   )r*   r   _fliprS   r(   _ensure_optional_axesrZ  rb  s     rK   r   r   |  s9    p vq!!!	wqzz:;DAA	B	BBrL   rb  int | tuple[int, ...] | Nonec                     |It          j         t          t          t	          t                                                             S t          |          }t          j          fd|D                       S )Nc                J    g | ]}t          |t                               S rj   rN  )r*  axrZ  s     rK   r2  z_flip.<locals>.<listcomp>  s*    DDD'DGG44DDDrL   )r   revrH   r   r   r?   r   rg  s   ` rK   re  re    sj    	\71d5U1XX//00111	T	"	"$	DDDDtDDD	E	EErL   c                f    t          j        d|            t          t          |           d          S )a  Reverse the order of elements of an array along axis 1.

  JAX implementation of :func:`numpy.fliplr`.

  Args:
    m: Array with at least two dimensions.

  Returns:
    An array with the elements in reverse order along axis 1.

  See Also:
    - :func:`jax.numpy.flip`: reverse the order along the given axis
    - :func:`jax.numpy.flipud`: reverse the order along axis 0

  Examples:
    >>> x = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> jnp.fliplr(x)
    Array([[2, 1],
           [4, 3]], dtype=int32)
  fliplrr   r*   r   re  rS   rZ  s    rK   ro  ro    -    , x###	wqzz1		rL   c                f    t          j        d|            t          t          |           d          S )a  Reverse the order of elements of an array along axis 0.

  JAX implementation of :func:`numpy.flipud`.

  Args:
    m: Array with at least one dimension.

  Returns:
    An array with the elements in reverse order along axis 0.

  See Also:
    - :func:`jax.numpy.flip`: reverse the order along the given axis
    - :func:`jax.numpy.fliplr`: reverse the order along axis 1

  Examples:
    >>> x = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> jnp.flipud(x)
    Array([[3, 4],
           [1, 2]], dtype=int32)
  flipudr   rp  rq  s    rK   rt  rt    rr  rL   c                p    t          j        |           }t          j        |t	          |d                    S )a  Return boolean array showing where the input is complex.

  JAX implementation of :func:`numpy.iscomplex`.

  Args:
    x: Input array to check.

  Returns:
    A new array containing boolean values indicating complex elements.

  See Also:
    - :func:`jax.numpy.iscomplexobj`
    - :func:`jax.numpy.isrealobj`

  Examples:
    >>> jnp.iscomplex(jnp.array([True, 0, 1, 2j, 1+2j]))
    Array([False, False, False, True, True], dtype=bool)
  r   )r)   imagr   ner   rM   rD  s     rK   	iscomplexry    -    ( k!nn!	:a##	$	$$rL   c                p    t          j        |           }t          j        |t	          |d                    S )a  Return boolean array showing where the input is real.

  JAX implementation of :func:`numpy.isreal`.

  Args:
    x: input array to check.

  Returns:
    A new array containing boolean values indicating real elements.

  See Also:
    - :func:`jax.numpy.iscomplex`
    - :func:`jax.numpy.isrealobj`

  Examples:
    >>> jnp.isreal(jnp.array([False, 0j, 1, 2.1, 1+2j]))
    Array([ True,  True,  True,  True, False], dtype=bool)
  r   )r)   rv  r   eqr   rx  s     rK   isrealr}  	  rz  rL   degzc                   t          j        |           }t          j        |           }t          |          }t	          |t
                    r5t	          t          |           t                    rVt          |           dk    rCt          j	        t                    }t          j        ||          }t          j        ||          }t          j        ||          }|rt          j        |          n|S )a  Return the angle of a complex valued number or array.

  JAX implementation of :func:`numpy.angle`.

  Args:
    z: A complex number or an array of complex numbers.
    deg: Boolean. If ``True``, returns the result in degrees else returns
      in radians. Default is ``False``.

  Returns:
    An array of counterclockwise angle of each element of ``z``, with the same
    shape as ``z`` of dtype float.

  Examples:

    If ``z`` is a number

    >>> z1 = 2+3j
    >>> jnp.angle(z1)
    Array(0.98279375, dtype=float32, weak_type=True)

    If ``z`` is an array

    >>> z2 = jnp.array([[1+3j, 2-5j],
    ...                 [4-3j, 3+2j]])
    >>> with jnp.printoptions(precision=2, suppress=True):
    ...     print(jnp.angle(z2))
    [[ 1.25 -1.19]
     [-0.64  0.59]]

    If ``deg=True``.

    >>> with jnp.printoptions(precision=2, suppress=True):
    ...     print(jnp.angle(z2, deg=True))
    [[ 71.57 -68.2 ]
     [-36.87  33.69]]
  r   )r)   realrv  r[   rT   inexactfloatingrE   r   r   r   r   convert_element_typeatan2degrees)r  r~  reimrP   r   s         rK   angler  !  s    N {1~~"{1~~"
**%	E7	#	# -H%%-*.q''Q,,%f--E		!"e	,	,B		!"e	,	,B9R&#&	2			F2rL   )nrb  r   r  prependr8  c                d   t          j        d|            t          |           }t          j        t
          j        |d          }t          j        t
          j        |d          }|dk    r|S |dk     rt          d|           |j        dk    rt          d|            |j        }t          ||          }g }||t          j        d|           t          |          s6t          |j                  }d||<   t          |t          |                    }|                    t          |                     |                    |           ||t          j        d|           t          |          s6t          |j                  }d||<   t          |t          |                    }|                    t          |                     t          |          dk    rt!          ||          }t#          d           g|z  }	t#          d           g|z  }
t#          dd           |	|<   t#          d d          |
|<   t          |	          }t          |
          }|j        t&          j        k    rt*          j        nt*          j        }t1          |          D ]} |||         ||                   }|S )	Nr  z'n' argument of jnp.diffz'axis' argument of jnp.diffr   z#order must be non-negative but got z:diff requires input that is at least one dimensional; got r   r   )r*   r   rS   r   r   r   r   r   rE   rO  rH   r?   broadcast_torG   r8  r   concatenater   rP   r}   bool_r)   	not_equalsubtractr   )r   r  rb  r  r8  r  ndcombinedr?   slice1slice2slice1_tupleslice2_tupler   _s                  rK   r  r  T  st   
 vq!!!

#
X^Q0JKK!		6S	T	T$!VVJUU
>1>>
?
??X]]
URSUU
V
VV
x"	D"	%	%$()))== 439ooeeDkWeEll33gOOGG$$%%%
//#(((<< 239ooeeDkFE%LL11fOOGFOO$$$]]Q
h
%
%C$KK=2&$KK=2&q$&,tR&,v,v,900vfo"88 3 3a
"SL 1
2
2CC	*rL   zUnlike NumPy's implementation of ediff1d, :py:func:`jax.numpy.ediff1d` will not
issue an error if casting ``to_end`` or ``to_begin`` to the type of ``ary``
loses precision.
aryto_endto_beginc           	        t          j        d|            t          |           }t          j        |dd          |d d                   }|Gt          j        d|           t          t          t          ||j                            |f          }|Gt          j        d|           t          |t          t          ||j                            f          }|S )Nediff1dr   r   rn   )r*   r   ravelr   subr  rS   rP   )r  r  r  r  r   s        rK   r  r    s     y#&&&c

#73qrr7CH%%&H---%	 B B BCCVLMMFF+++&%ci(H(H(H"I"IJKKF	-rL   
edge_order)skip_params)rb  r  fvarargs
int | NoneArray | list[Array]c               f  	 |t          d          t          j        | g|R  ^}d 	|"t          t	          j                            n(t          fdt          |          D                       t                    dk    rg S t          fdt          j
                  D                       dk     rt          d          t          |          dk    rdgt                    z  }nt          |          d	k    r t          |          t                    z  }nRt          |          t                    k    rt          |          }n"t          d
t          |           d|           	fdt          |          D             }t                    d	k    r|d         n|S )Nz;The 'edge_order' argument to jnp.gradient is not supported.c                   t          t          j        | |          } |dd           |dd          z
  } |dd            |dd          z
  }t          |          dk    r+ |dd            |d d          z
  dz  |z  }||z  }||z  }nZt          |          dk    r7t	          |          | j        |         k    rt          d          dg| j        z  }t	          |          ||<   |                    |          }t          t          j        ||          }| |dd           |dd          z
  z  }| |dd            |dd          z
  z  } |dd           |dd          z
  }	 |dd            |dd          z
  }
|
 |	|	|
z   z  z  } |
|	z
  |	|
z  z  }|	|
|	|
z   z  z  }|  |dd          z  | |dd          z  z   | |dd           z  z   }nt          d	          t          |||f|          S )
Nrh  r   r   r   r   r   zaSpacing arrays must have the same length as the dimension along which the gradient is calculated.z,Spacing arrays must be 1D arrays or scalars.)	r   r   slice_in_dimrE   r   r?   r   r=  r  )r   hrb  sliced
upper_edge
lower_edgeinnerh_shapesliced_xdx1dx2bcs                rK   gradient_along_axisz%gradient.<locals>.gradient_along_axis  sQ   S%qt444F1q!,JD!!FF2rNN2JAww!||vab!1!11S81<eAojAojj	aA	Q174=	 	 @
 
 	
 afg!ffgdm
))G

a)14888hHHQNNXXa^^33jHHR&&"b)9)999jHQOOhhq"oo-cHQB/c&C39%
&a9s
#a
c	"
#a&&B--!ffQmm"33a&&D//6IIeeEFFF
E:6TBBBBrL   c              3  B   K   | ]}t          |j                  V  d S r`   rN  rP  s     rK   r,  zgradient.<locals>.<genexpr>  s0      XX)!QV44XXXXXXrL   r   c              3  *   K   | ]\  }}|v 	|V  d S r`   rj   )r*  rD  s
axis_tuples      rK   r,  zgradient.<locals>.<genexpr>  s+      ==tq!Q*______==rL   r   z]Shape of array too small to calculate a numerical gradient, at least 2 elements are required.      ?r   z$Invalid number of spacing arguments z
 for axis=c                0    g | ]\  }} ||          S rj   rj   )r*  rl  r  r   r  s      rK   r2  zgradient.<locals>.<listcomp>  s-    KKKeb!1b))KKKrL   )r   r*   r   rG   r   rE   r   r   r   	enumerater?   r   rH   rx   zip)
r  rb  r  r  spacingdxa_gradr   r  r  s
          @@@rK   gradientr    s    
E   +A8888+!g C  C  CD 
\uQV}}%%JJXXXX>QRV>W>WXXXXXJ__I====y))=====AA
 9 : : : 	\\Q"ec*oo5BB
7||q	gZ	(BB
7||s:&&	gBBOS\\OOOOPPPKKKKKs:r7J7JKKK&*oo**6rL   c                "    t          |            S )a  Check if the input is not a complex number or an array containing complex elements.

  JAX implementation of :func:`numpy.isrealobj`.

  The function evaluates based on input type rather than value.
  Inputs with zero imaginary parts are still considered complex.

  Args:
    x: input object to check.

  Returns:
    False if ``x`` is a complex number or an array containing at least one complex element,
    True otherwise.

  See Also:
    - :func:`jax.numpy.iscomplexobj`
    - :func:`jax.numpy.isreal`

  Examples:
    >>> jnp.isrealobj(0)
    True
    >>> jnp.isrealobj(1.2)
    True
    >>> jnp.isrealobj(jnp.array([1, 2]))
    True
    >>> jnp.isrealobj(1+2j)
    False
    >>> jnp.isrealobj(jnp.array([0, 1+2j]))
    False
  )rW   rZ   s    rK   	isrealobjr    s    > !__	rL   C)newshapeDimSize | Shape | Noneorderr  DimSize | Shape | DeprecatedArgc               v   d}t          j        d|            t          |t                    s1|t	          d          t          j        dt          d           |}~n|t          d          	 | 	                    ||	          S # t          $ r Y nw xY wt          |           	                    ||	          S )
a0	  Return a reshaped copy of an array.

  JAX implementation of :func:`numpy.reshape`, implemented in terms of
  :func:`jax.lax.reshape`.

  Args:
    a: input array to reshape
    shape: integer or sequence of integers giving the new shape, which must match the
      size of the input array. If any single dimension is given size ``-1``, it will be
      replaced with a value such that the output has the correct size.
    order: ``'F'`` or ``'C'``, specifies whether the reshape should apply column-major
      (fortran-style, ``"F"``) or row-major (C-style, ``"C"``) order; default is ``"C"``.
      JAX does not support ``order="A"``.

  Returns:
    reshaped copy of input array with the specified shape.

  Notes:
    Unlike :func:`numpy.reshape`, :func:`jax.numpy.reshape` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize-away
    such copies when possible, so this doesn't have performance impacts in practice.

  See Also:
    - :meth:`jax.Array.reshape`: equivalent functionality via an array method.
    - :func:`jax.numpy.ravel`: flatten an array into a 1D shape.
    - :func:`jax.numpy.squeeze`: remove one or more length-1 axes from an array's shape.

  Examples:
    >>> x = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> jnp.reshape(x, 6)
    Array([1, 2, 3, 4, 5, 6], dtype=int32)
    >>> jnp.reshape(x, (3, 2))
    Array([[1, 2],
           [3, 4],
           [5, 6]], dtype=int32)

    You can use ``-1`` to automatically compute a shape that is consistent with
    the input size:

    >>> jnp.reshape(x, -1)  # -1 is inferred to be 6
    Array([1, 2, 3, 4, 5, 6], dtype=int32)
    >>> jnp.reshape(x, (-1, 2))  # -1 is inferred to be 3
    Array([[1, 2],
           [3, 4],
           [5, 6]], dtype=int32)

    The default ordering of axes in the reshape is C-style row-major ordering.
    To use Fortran-style column-major ordering, specify ``order='F'``:

    >>> jnp.reshape(x, 6, order='F')
    Array([1, 4, 2, 5, 3, 6], dtype=int32)
    >>> jnp.reshape(x, (3, 2), order='F')
    Array([[1, 5],
           [4, 3],
           [2, 6]], dtype=int32)

    For convenience, this functionality is also available via the
    :meth:`jax.Array.reshape` method:

    >>> x.reshape(3, 2)
    Array([[1, 2],
           [3, 4],
           [5, 6]], dtype=int32)
  Tr=  Nzjnp.reshape received both `shape` and `newshape` arguments. Note that using `newshape` is deprecated, please only use `shape` instead.zThe newshape argument of jax.numpy.reshape is deprecated and setting it will soon raise an error. To avoid an error in the future, and to suppress this warning, please use the shape argument instead.r   
stacklevelzBjnp.shape requires passing a `shape` argument, but none was given.r  )r*   r   rF   r.   r   warningswarnDeprecationWarningrx   r=  rR   rS   )r   r?   r  r  __tracebackhide__s        rK   r=  r=  
  s    H y!$$$ 
Hm	,	, 	K   MF Q	( ( ( (
 E}
J  	99U%9(((	 	 	 	D				E		/	//s   0B 
BBr  T)r   inlinec                    t          j        d|            |dk    rt          d          t          | t	          |           f|          S )a  Flatten array into a 1-dimensional shape.

  JAX implementation of :func:`numpy.ravel`, implemented in terms of
  :func:`jax.lax.reshape`.

  ``ravel(arr, order=order)`` is equivalent to ``reshape(arr, -1, order=order)``.

  Args:
    a: array to be flattened.
    order: ``'F'`` or ``'C'``, specifies whether the reshape should apply column-major
      (fortran-style, ``"F"``) or row-major (C-style, ``"C"``) order; default is ``"C"``.
      JAX does not support `order="A"` or `order="K"`.

  Returns:
    flattened copy of input array.

  Notes:
    Unlike :func:`numpy.ravel`, :func:`jax.numpy.ravel` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize-away
    such copies when possible, so this doesn't have performance impacts in practice.

  See Also:
    - :meth:`jax.Array.ravel`: equivalent functionality via an array method.
    - :func:`jax.numpy.reshape`: general array reshape.

  Examples:
    >>> x = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])

    By default, ravel in C-style, row-major order

    >>> jnp.ravel(x)
    Array([1, 2, 3, 4, 5, 6], dtype=int32)

    Optionally ravel in Fortran-style, column-major:

    >>> jnp.ravel(x, order='F')
    Array([1, 4, 2, 5, 3, 6], dtype=int32)

    For convenience, the same functionality is available via the :meth:`jax.Array.ravel`
    method:

    >>> x.ravel()
    Array([1, 2, 3, 4, 5, 6], dtype=int32)
  r  Kz$Ravel not implemented for order='K'.)r*   r   r   r=  sizer   r  s     rK   r  r  k  sJ    ^ w"""
c\\
D
E
EE	T!WWJ	&	&&rL   raisemulti_indexSequence[ArrayLike]dimsSequence[int]c                   t          |           t          |          k    s*J dt          |            dt          |                       t          d |D                       }t          j        dg| R   d | D             }|D ]T}|dk    rt	          j        t          |d           t          t          |          t                    st          d          U|dk    r7t          d	 t          ||          D                       rt          d
          nU|dk    rd t          ||          D             }n4|dk    rd t          ||          D             }nt          d|d          |dk    r t          j        d|dd         z             }nK|dk    r2t          j        d|dd         ddd         z             ddd         }nt          d|d          t          d|r|d         j        nt#          j        t&                              }t          ||          D ]\  }}	||t)          |	          z  z   }|S )a  Convert multi-dimensional indices into flat indices.

  JAX implementation of :func:`numpy.ravel_multi_index`

  Args:
    multi_index: sequence of integer arrays containing indices in each dimension.
    dims: sequence of integer sizes; must have ``len(dims) == len(multi_index)``
    mode: how to handle out-of bound indices. Options are

      - ``"raise"`` (default): raise a ValueError. This mode is incompatible
        with :func:`~jax.jit` or other JAX transformations.
      - ``"clip"``: clip out-of-bound indices to valid range.
      - ``"wrap"``: wrap out-of-bound indices to valid range.

    order: ``"C"`` (default) or ``"F"``, specify whether to assume C-style
      row-major order or Fortran-style column-major order.

  Returns:
    array of flattened indices

  See also:
    :func:`jax.numpy.unravel_index`: inverse of this function.

  Examples:
    Define a 2-dimensional array and a sequence of indices of even values:

    >>> x = jnp.array([[2., 3., 4.],
    ...                [5., 6., 7.]])
    >>> indices = jnp.where(x % 2 == 0)
    >>> indices
    (Array([0, 0, 1], dtype=int32), Array([0, 2, 1], dtype=int32))
    >>> x[indices]
    Array([2., 4., 6.], dtype=float32)

    Compute the flattened indices:

    >>> indices_flat = jnp.ravel_multi_index(indices, x.shape)
    >>> indices_flat
    Array([0, 2, 4], dtype=int32)

    These flattened indices can be used to extract the same values from the
    flattened ``x`` array:

    >>> x_flat = x.ravel()
    >>> x_flat
    Array([2., 3., 4., 5., 6., 7.], dtype=float32)
    >>> x_flat[indices_flat]
    Array([2., 4., 6.], dtype=float32)

    The original indices can be recovered with :func:`~jax.numpy.unravel_index`:

    >>> jnp.unravel_index(indices_flat, x.shape)
    (Array([0, 0, 1], dtype=int32), Array([0, 2, 1], dtype=int32))
  zlen(multi_index)=z != len(dims)=c              3  V   K   | ]$}t          j        t          j        |d           V  %dS )z*in `dims` argument of ravel_multi_index().Nr   r   r   r   r*  ds     rK   r,  z$ravel_multi_index.<locals>.<genexpr>  s5      uuklt%hna9effuuuuuurL   r9  c                ,    g | ]}t          |          S rj   rS   r*  rD  s     rK   r2  z%ravel_multi_index.<locals>.<listcomp>  s    555AWQZZ555rL   r  zxThe error occurred because ravel_multi_index was jit-compiled with mode='raise'. Use mode='wrap' or mode='clip' instead.zonly int indices permittedc              3  Z   K   | ]&\  }}t          j        |d k     ||k    z            V  'dS r   Nr(   r6  r*  rD  r  s      rK   r,  z$ravel_multi_index.<locals>.<genexpr>  s=      
U
U$!Q:>1q5Q!V,--
U
U
U
U
U
UrL   z"invalid entry in coordinates arrayr   c                <    g | ]\  }}t          |d |dz
            S rY  )r   r  s      rK   r2  z%ravel_multi_index.<locals>.<listcomp>  s,    PPPTQtAq!a%((PPPrL   wrapc                    g | ]
\  }}||z  S rj   rj   r  s      rK   r2  z%ravel_multi_index.<locals>.<listcomp>  s     DDDAq1uDDDrL   zinvalid mode=z%. Expected 'raise', 'wrap', or 'clip'Fr   Nr   r  r   zinvalid order=z. Expected 'C' or 'F'r   rn   )r   rG   r*   r   r   r   arrayrT   r[   r   rx   r6  r  r   r}   cumprodrP   r   r   int_r^   )
r  r  r   r  multi_index_arrr   stridesr   rD  r  s
             rK   r9  r9    s   p 
[		SYY	&	&	&(gC<L<L(g(g\_`d\e\e(g(g	&	&	&	uuptuuu	u	u$*9[999955555/ 4 4ew
UE	FG G G fUmmW-- 423334	W__

U
U#ot:T:T
U
U
UUU =;<<<=v~~PPS$5O5OPPPOOv~~DD_d)C)CDDDOO
RTRRR
S
SS
c\\jSbS	)**GG||jQRR2.//"5GG
DeDDD
E
EE @?1-33 & 9$ ? ?B B B&/7++ ! !daa#a&&j FF	-rL   indicesr3   tuple[Array, ...]c                   t          j        d|            t          |           }	 t          |          }n# t          $ r |g}Y nw xY wt          d |D                       rt          d          dgt          |          z  }t          t          t          |                              D ] \  }}t          j        ||          \  }||<   !|dk    |dk     t          fdt          ||          D                       S )a  Convert flat indices into multi-dimensional indices.

  JAX implementation of :func:`numpy.unravel_index`. The JAX version differs in
  its treatment of out-of-bound indices: unlike NumPy, negative indices are
  supported, and out-of-bound indices are clipped to the nearest valid value.

  Args:
    indices: integer array of flat indices
    shape: shape of multidimensional array to index into

  Returns:
    Tuple of unraveled indices

  See also:
    :func:`jax.numpy.ravel_multi_index`: Inverse of this function.

  Examples:
    Start with a 1D array values and indices:

    >>> x = jnp.array([2., 3., 4., 5., 6., 7.])
    >>> indices = jnp.array([1, 3, 5])
    >>> print(x[indices])
    [3. 5. 7.]

    Now if ``x`` is reshaped, ``unravel_indices`` can be used to convert
    the flat indices into a tuple of indices that access the same entries:

    >>> shape = (2, 3)
    >>> x_2D = x.reshape(shape)
    >>> indices_2D = jnp.unravel_index(indices, shape)
    >>> indices_2D
    (Array([0, 1, 1], dtype=int32), Array([1, 0, 2], dtype=int32))
    >>> print(x_2D[indices_2D])
    [3. 5. 7.]

    The inverse function, ``ravel_multi_index``, can be used to obtain the
    original indices:

    >>> jnp.ravel_multi_index(indices_2D, shape)
    Array([1, 3, 5], dtype=int32)
  unravel_indexc              3  <   K   | ]}t          |          d k    V  dS r  rE   )r*  r  s     rK   r,  z unravel_index.<locals>.<genexpr>/  s,      %%!aA%%%%%%rL   z7unravel_index: shape should be a scalar or 1D sequence.r   r   c           
   3  d   K   | ]*\  }}t          |d z
  t          d|                    V  +dS )r   r   Nr   )r*  r  rD  oob_negoob_poss      rK   r,  z unravel_index.<locals>.<genexpr>6  sW       9 91a Wa!eU7Aq%9%9:: 9 9 9 9 9 9rL   )r*   r   rS   rH   rx   r6  r   r   reversedr  r)   divmodrG   r7   )r  r?   indices_arrout_indicesrD  r  r  r  s         @@rK   r  r    sG   T 000  +KKEE	    GEEE 	%%u%%%%% P
N
O
OO"#s5zz!1+tIe,,--.. @ @da"(-Q"?"?KQ!O'"'	 9 9 9 9 9#E;779 9 9 
9 
9 9s   8 AA)	new_shaper  c                   t          j        d|            t          |          }t          d |D                       rt	          d          t          |           }t          j        |          }|j        dk    s|dk    rt          ||          S t          ||j                  }t          ||          d |         }t          ||          S )Nresizec              3  "   K   | ]
}|d k     V  dS r  rj   )r*  
dim_lengths     rK   r,  zresize.<locals>.<genexpr>?  s&      44Ja444444rL   z0all elements of `new_shape` must be non-negativer   r)  )r*   r   r   r6  r   r  r;  r<  r  
zeros_liker8   tiler=  )r   r  r  new_sizerepeatss        rK   r   r   9  s     x###!),,)44)44444 I
G
H
HHa#Yy!!(X]]h!mmc++++(CH--'S'9H9%#	i	 	  rL   c                    t          j        d|            t          t          |           |t	          |          nd          S )a>  Remove one or more length-1 axes from array

  JAX implementation of :func:`numpy.sqeeze`, implemented via :func:`jax.lax.squeeze`.

  Args:
    a: input array
    axis: integer or sequence of integers specifying axes to remove. If any specified
      axis does not have a length of 1, an error is raised. If not specified, squeeze
      all length-1 axes in ``a``.

  Returns:
    copy of ``a`` with length-1 axes removed.

  Notes:
    Unlike :func:`numpy.squeeze`, :func:`jax.numpy.squeeze` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize-away
    such copies when possible, so this doesn't have performance impacts in practice.

  See Also:
    - :func:`jax.numpy.expand_dims`: the inverse of ``squeeze``: add dimensions of length 1.
    - :meth:`jax.Array.squeeze`: equivalent functionality via an array method.
    - :func:`jax.lax.squeeze`: equivalent XLA API.
    - :func:`jax.numpy.ravel`: flatten an array into a 1D shape.
    - :func:`jax.numpy.reshape`: general array reshape.

  Examples:
    >>> x = jnp.array([[[0]], [[1]], [[2]]])
    >>> x.shape
    (3, 1, 1)

    Squeeze all length-1 dimensions:

    >>> jnp.squeeze(x)
    Array([0, 1, 2], dtype=int32)
    >>> _.shape
    (3,)

    Equivalent while specifying the axes explicitly:

    >>> jnp.squeeze(x, axis=(1, 2))
    Array([0, 1, 2], dtype=int32)

    Attempting to squeeze a non-unit axis results in an error:

    >>> jnp.squeeze(x, axis=0)  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    ValueError: cannot select an axis to squeeze out which has size not equal to one, got shape=(3, 1, 1) and dimensions=(0,)

    For convenience, this functionality is also available via the
    :meth:`jax.Array.squeeze` method:

    >>> x.squeeze()
    Array([0, 1, 2], dtype=int32)
  squeezeN)r*   r   _squeezerS   r   r   rb  s     rK   r  r  N  sB    p y!$$$	'!**4;K1$777QU	V	VVrL   c                    |Xt          |           }t          j        |          st          d          t	          d t          |          D                       }t          j        | |          S )NzCjnp.squeeze with axis=None is not supported with shape polymorphismc              3  ,   K   | ]\  }}|d k    |V  dS r.  rj   r  s      rK   r,  z_squeeze.<locals>.<genexpr>  s*      <<tq!Q!VVVVVV<<rL   )r?   r   is_constant_shaper   rG   r  r   r  )r   rb  a_shapes      rK   r	  r	    sk    	\AhhG!'** ^\]]]<<y11<<<<<D	Q		rL   int | Sequence[int]c                t    t          j        d|            t          |          }t          j        | |          S )a  Insert dimensions of length 1 into array

  JAX implementation of :func:`numpy.expand_dims`, implemented via
  :func:`jax.lax.expand_dims`.

  Args:
    a: input array
    axis: integer or sequence of integers specifying positions of axes to add.

  Returns:
    Copy of ``a`` with added dimensions.

  Notes:
    Unlike :func:`numpy.expand_dims`, :func:`jax.numpy.expand_dims` will return a copy
    rather than a view of the input array. However, under JIT, the compiler will optimize
    away such copies when possible, so this doesn't have performance impacts in practice.

  See Also:
    - :func:`jax.numpy.squeeze`: inverse of this operation, i.e. remove length-1 dimensions.
    - :func:`jax.lax.expand_dims`: XLA version of this functionality.

  Examples:
    >>> x = jnp.array([1, 2, 3])
    >>> x.shape
    (3,)

    Expand the leading dimension:

    >>> jnp.expand_dims(x, 0)
    Array([[1, 2, 3]], dtype=int32)
    >>> _.shape
    (1, 3)

    Expand the trailing dimension:

    >>> jnp.expand_dims(x, 1)
    Array([[1],
           [2],
           [3]], dtype=int32)
    >>> _.shape
    (3, 1)

    Expand multiple dimensions:

    >>> jnp.expand_dims(x, (0, 1, 3))
    Array([[[[1],
             [2],
             [3]]]], dtype=int32)
    >>> _.shape
    (1, 1, 3, 1)

    Dimensions can also be expanded more succinctly by indexing with ``None``:

    >>> x[None]  # equivalent to jnp.expand_dims(x, 0)
    Array([[1, 2, 3]], dtype=int32)
    >>> x[:, None]  # equivalent to jnp.expand_dims(x, 1)
    Array([[1],
           [2],
           [3]], dtype=int32)
    >>> x[None, None, :, None]  # equivalent to jnp.expand_dims(x, (0, 1, 3))
    Array([[[[1],
             [2],
             [3]]]], dtype=int32)
  expand_dims)r*   r   r   r   r  r
  s     rK   r  r    s7    B }a(((	T	"	"$	D	!	!!rL   )axis1axis2r  r  c                    t          j        d|            t          j        t	          |                     }||         ||         c||<   ||<   t          j        | t          |                    S )a  Swap two axes of an array.

  JAX implementation of :func:`numpy.swapaxes`, implemented in terms of
  :func:`jax.lax.transpose`.

  Args:
    a: input array
    axis1: index of first axis
    axis2: index of second axis

  Returns:
    Copy of ``a`` with specified axes swapped.

  Notes:
    Unlike :func:`numpy.swapaxes`, :func:`jax.numpy.swapaxes` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize away
    such copies when possible, so this doesn't have performance impacts in practice.

  See Also:
    - :func:`jax.numpy.moveaxis`: move a single axis of an array.
    - :func:`jax.numpy.rollaxis`: older API for ``moveaxis``.
    - :func:`jax.lax.transpose`: more general axes permutations.
    - :meth:`jax.Array.swapaxes`: same functionality via an array method.

  Examples:
    >>> a = jnp.ones((2, 3, 4, 5))
    >>> jnp.swapaxes(a, 1, 3).shape
    (2, 5, 4, 3)

    Equivalent output via the ``swapaxes`` array method:

    >>> a.swapaxes(1, 3).shape
    (2, 5, 4, 3)

    Equivalent output via :func:`~jax.numpy.transpose`:

    >>> a.transpose(0, 3, 2, 1).shape
    (2, 5, 4, 3)
  swapaxes)r*   r   r}   arangerE   r   r  rH   )r   r  r  ra  s       rK   r  r    sa    R z1%%%	477		$!%[$u+$u+tE{	q$t**	%	%%rL   sourcedestinationc                    t          j        d|            t          t          |           t	          |          t	          |                    S )a  Move an array axis to a new position

  JAX implementation of :func:`numpy.moveaxis`, implemented in terms of
  :func:`jax.lax.transpose`.

  Args:
    a: input array
    source: index or indices of the axes to move.
    destination: index or indices of the axes destinations

  Returns:
    Copy of ``a`` with axes moved from ``source`` to ``destination``.

  Notes:
    Unlike :func:`numpy.moveaxis`, :func:`jax.numpy.moveaxis` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize away
    such copies when possible, so this doesn't have performance impacts in practice.

  See also:
    - :func:`jax.numpy.swapaxes`: swap two axes.
    - :func:`jax.numpy.rollaxis`: older API for moving an axis.
    - :func:`jax.numpy.transpose`: general axes permutation.

  Examples:
    >>> a = jnp.ones((2, 3, 4, 5))

    Move axis ``1`` to the end of the array:

    >>> jnp.moveaxis(a, 1, -1).shape
    (2, 4, 5, 3)

    Move the last axis to position 1:

    >>> jnp.moveaxis(a, -1, 1).shape
    (2, 5, 3, 4)

    Move multiple axes:

    >>> jnp.moveaxis(a, (0, 1), (-1, -2)).shape
    (4, 5, 3, 2)

    This can also be accomplished via :func:`~jax.numpy.transpose`:

    >>> a.transpose(2, 3, 1, 0).shape
    (4, 5, 3, 2)
  moveaxis)r*   r   	_moveaxisrS   r   )r   r  r  s      rK   r  r  	  sH    ` z1%%%	71::26::&{33
5 
5 5rL   )r  r  c                    t           fdD                       t           fd|D                       }t                    t          |          k    r=t          d                    t                    t          |                              fdt	          t                               D             }t          t          |                    D ]\  }}|                    ||           t          j
         |          S )Nc              3  R   K   | ]!}t          |t                              V  "d S r`   rN  rP  s     rK   r,  z_moveaxis.<locals>.<genexpr>?  s4      @@A#AtAww//@@@@@@rL   c              3  R   K   | ]!}t          |t                              V  "d S r`   rN  rP  s     rK   r,  z_moveaxis.<locals>.<genexpr>@  s4      JJ(DGG44JJJJJJrL   z)Inconsistent number of elements: {} vs {}c                    g | ]}|v|	S rj   rj   )r*  rD  r  s     rK   r2  z_moveaxis.<locals>.<listcomp>D  s    	7	7	7q!rL   )rG   r   r   formatr   rE   sortedr  insertr   r  )r   r  r  ra  destsrcs   ``    rK   r  r  =  s   @@@@@@@@@&JJJJkJJJJJ+[[C$$$$
@fS[[#k*:*:;;= = =	7	7	7	7U477^^	7	7	7$#k62233  idCKKc	q$		rL   )	equal_nanh㈵>:0yE>r  rtolatolr%  c                (   t          j        d| |          \  } }t          |           }t          j        |t          j                  rt          j        | |          S t          j        d| |          \  } }t          |           }t	          |t                    r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        ||          }
t#          j        |t#          j        |	                    }t          j        | |          }t#          j        |
|          }t#          j        ||          }t#          j        |           }t#          j        |          }t#          j        ||          }t#          j        |t#          j        |                    }|r*t#          j        ||          }t#          j        ||          }|S )a(  Check if the elements of two arrays are approximately equal within a tolerance.

  JAX implementation of :func:`numpy.allclose`.

  Essentially this function evaluates the following condition:

  .. math::

     |a - b| \le \mathtt{atol} + \mathtt{rtol} * |b|

  ``jnp.inf`` in ``a`` will be considered equal to ``jnp.inf`` in ``b``.

  Args:
    a: first input array to compare.
    b: second input array to compare.
    rtol: relative tolerance used for approximate equality. Default = 1e-05.
    atol: absolute tolerance used for approximate equality. Default = 1e-08.
    equal_nan: Boolean. If ``True``, NaNs in ``a`` will be considered
      equal to NaNs in ``b``. Default is ``False``.

  Returns:
    A new array containing boolean values indicating whether the input arrays
    are element-wise approximately equal within the specified tolerances.

  See Also:
    - :func:`jax.numpy.allclose`
    - :func:`jax.numpy.equal`

  Examples:
    >>> jnp.isclose(jnp.array([1e6, 2e6, jnp.inf]), jnp.array([1e6, 2e7, jnp.inf]))
    Array([ True, False,  True], dtype=bool)
    >>> jnp.isclose(jnp.array([1e6, 2e6, 3e6]),
    ...              jnp.array([1.00008e6, 2.00008e7, 3.00008e8]), rtol=1e3)
    Array([ True,  True,  True], dtype=bool)
    >>> jnp.isclose(jnp.array([1e6, 2e6, 3e6]),
    ...              jnp.array([1.00001e6, 2.00002e6, 3.00009e6]), atol=1e3)
    Array([ True,  True,  True], dtype=bool)
    >>> jnp.isclose(jnp.array([jnp.nan, 1, 2]),
    ...              jnp.array([jnp.nan, 1, 2]), equal_nan=True)
    Array([ True,  True,  True], dtype=bool)
  isclose)r*   promote_argsr[   r   rT   r   r   r|  promote_args_inexactrU   _complex_elem_typer  leabsr  r  mulr)   isinf
logical_orlogical_andlogical_notr   )r   r  r(  r)  r%  rP   r   a_infb_infany_infboth_inf
same_valuesame_infa_nanb_nanany_nanboth_nans                    rK   r+  r+  J  s   X 
	9a	+	+$!Q
))%ufo.. 6!Q<<		"9a	3	3$!Q
))%'' +#E**E		!$	.	.$		!$	.	.$GCGAqMMGD#'$

++,,	. 	.# ,q//%
,q//%eU++'u--(3 27 ; ;<<#va||**55(#x((# ,q//%
,q//%eU++'3 27 ; ;<<# +!%//H

C
*
*C	*rL   xpfpleftArrayLike | str | Noner  periodc                r   t          j        d| ||           t          |          t          |          k    st          |          dk    rt	          d          t          j        | |          \  }}t          j        |          \  }~ ~~t          |t                    r|dk    rt	          d|          d}	nd}	t          |t                    r|dk    rt	          d|          d}
nd}
t          j	        |j
        t          j                  rt	          d	          |t          |          d
k    rt	          d|           t          j        |          }||z  }||z  }t          j        ||          \  }}t#          |dd          |z
  ||d d         |z   g          }t#          |dd          ||d d         g          }t%          t'          ||d          dt)          |          dz
            }||         ||dz
           z
  }||         ||dz
           z
  }|||dz
           z
  }t          j        t          j        |j
                  j                  }t          j        |          |k    }t1          |||dz
           ||dz
           |t1          |d|          z  |z  z             }|	s@t          |t                    rJ ||d
         n|}|t1          ||d
         k     ||          }|
s@t          |t                    rJ ||d         n|}|t1          ||d         k    ||          }|S )Ninterpr   z6xp and fp must be one-dimensional arrays of equal sizeextrapolatezAthe only valid string value of `left` is 'extrapolate', but got: TFzBthe only valid string value of `right` is 'extrapolate', but got: z+jnp.interp: complex x values not supported.r   zperiod must be a scalar; got r   r  r  )r*   r   r?   rE   r   r   rF   rA   r   rT   rP   r}   rU   r)   r0  r   sort_key_valr  r   r  r   r  finfoepsr   )rM   r@  rA  rB  r  rD  x_arrxp_arrfp_arrextrapolate_leftextrapolate_rightrD  dfr  deltaepsilondx0r  left_arr	right_arrs                       rK   _interprV    st    xB+++
2YY%))tBxx1}}
M
N
NN-a44-%'++'&Rc } ;26; ; < < <s  <27< < = = =u{B$677 D
B
C
CCF||q?v??@@@ZFFNEf_F%ff55NFF&+.rr
V8KLMMF&+vvbqbz:;;F
<G444aVqII!ay6!a%= "ay6!a%= "
&Q-
%Jrx--122'w#CAq1usAr9J9J1Jb0P PQQ!	 0$$$$$$'+|&))H~
q	!8Q
/
/a	 2%%%%%%).6"::EI~
r
"Iq
1
1a	
(rL   z
    In addition to constant interpolation supported by NumPy, jnp.interp also
    supports left='extrapolate' and right='extrapolate' to indicate linear
    extrapolation instead.c                0   g }t          |t                    s||                    d           t          |t                    s||                    d           ||                    d           t          t          |          } || |||||          S )NrB  r  rD  r   )rF   rA   r8  r   rV  )rM   r@  rA  rB  r  rD  r   jitted_interps           rK   rF  rF    s     /c #dl6"""s $u}7###^8$$$g???-	q"b$v	6	66rL   r  
fill_value	conditionLiteral[None]r  rZ  (None | ArrayLike | tuple[ArrayLike, ...]c                  d S r`   rj   r[  rM   r   r  rZ  s        rK   r   r     s	     #&#rL   c                  d S r`   rj   r_  s        rK   r   r     s	     crL   Array | tuple[Array, ...]c                  d S r`   rj   r_  s        rK   r   r     s	     +.#rL   c                 |)|'t          j        d|            t          | ||          S t          j        d| ||           ||t          d          ||t          d| d| d          t          j        | ||          S )a	  Select elements from two arrays based on a condition.

  JAX implementation of :func:`numpy.where`.

  .. note::
     when only ``condition`` is provided, ``jnp.where(condition)`` is equivalent
     to ``jnp.nonzero(condition)``. For that case, refer to the documentation of
     :func:`jax.numpy.nonzero`. The docstring below focuses on the case where
     ``x`` and ``y`` are specified.

  The three-term version of ``jnp.where`` lowers to :func:`jax.lax.select`.

  Args:
    condition: boolean array. Must be broadcast-compatible with ``x`` and ``y`` when
      they are specified.
    x: arraylike. Should be broadcast-compatible with ``condition`` and ``y``, and
      typecast-compatible with ``y``.
    y: arraylike. Should be broadcast-compatible with ``condition`` and ``x``, and
      typecast-compatible with ``x``.
    size: integer, only referenced when ``x`` and ``y`` are ``None``. For details,
      see :func:`jax.numpy.nonzero`.
    fill_value: only referenced when ``x`` and ``y`` are ``None``. For details,
      see :func:`jax.numpy.nonzero`.

  Returns:
    An array of dtype ``jnp.result_type(x, y)`` with values drawn from ``x`` where ``condition``
    is True, and from ``y`` where condition is ``False. If ``x`` and ``y`` are ``None``, the
    function behaves differently; see `:func:`jax.numpy.nonzero` for a description of the return
    type.

  See Also:
    - :func:`jax.numpy.nonzero`
    - :func:`jax.numpy.argwhere`
    - :func:`jax.lax.select`

  Notes:
    Special care is needed when the ``x`` or ``y`` input to :func:`jax.numpy.where` could
    have a value of NaN. Specifically, when a gradient is taken with :func:`jax.grad`
    (reverse-mode differentiation), a NaN in either ``x`` or ``y`` will propagate into the
    gradient, regardless of the value of ``condition``.  More information on this behavior
    and workarounds is available in the `JAX FAQ
    <https://jax.readthedocs.io/en/latest/faq.html#gradients-contain-nan-where-using-where>`_.

  Examples:
    When ``x`` and ``y`` are not provided, ``where`` behaves equivalently to
    :func:`jax.numpy.nonzero`:

    >>> x = jnp.arange(10)
    >>> jnp.where(x > 4)
    (Array([5, 6, 7, 8, 9], dtype=int32),)
    >>> jnp.nonzero(x > 4)
    (Array([5, 6, 7, 8, 9], dtype=int32),)

    When ``x`` and ``y`` are provided, ``where`` selects between them based on
    the specified condition:

    >>> jnp.where(x > 4, x, 0)
    Array([0, 0, 0, 0, 0, 5, 6, 7, 8, 9], dtype=int32)
  Nr   rY  zJsize and fill_value arguments cannot be used in three-term where function.z[Either both or neither of the x and y arguments should be provided to jax.numpy.where, got r   r   )r*   r   nonzeror   _wherer_  s        rK   r   r     s    x Y19),,,94J????)Q222:1 4 5 5 5yAI '' '"#' ' ' ( ( ( ;y!Q'''rL   condlist
choicelistdefaultc                   t          |           t          |          k    r?d}t          |                    t          |           t          |                              t          |           dk    rt          d          t          j        |g|R  }t          t          dg| R            }t          |                    t                    d          }t          j        t          |g|R   S )Nz8condlist must have length equal to choicelist ({} vs {})r   zcondlist must be non-emptyFrh  )r   r   r   r*   r   stackbroadcast_arraysargmaxr   rN   r   select_n)rf  rg  rh  msg
conditionsidxs         rK   selectrq  L  s     	]]c*oo%%
DC
SZZHs:??
@
@@]]a
1
2
22 "78Z888*%e7h77788*z  &&Q///#	'9j999	::rL   r4  	minlengthr5  c               6   t          j        d|            t          t          |           t                    st          dt          |                      t          |           dk    rt          d          t          j	        t          j        |d          }|Ut          j	        t          | d          }t          ||j        o#t          |                                          dz             }nt          j        |d          }|t#          j        dt&          	          }n/t)          |           t)          |          k    rt          d
          t+          |t          |                    j        t/          | d                                       |          S )an  Count the number of occurrences of each value in an integer array.

  JAX implementation of :func:`numpy.bincount`.

  For an array of positive integers ``x``, this function returns an array ``counts``
  of size ``x.max() + 1``, such that ``counts[i]`` contains the number of occurrences
  of the value ``i`` in ``x``.

  The JAX version has a few differences from the NumPy version:

  - In NumPy, passing an array ``x`` with negative entries will result in an error.
    In JAX, negative values are clipped to zero.
  - JAX adds an optional ``length`` parameter which can be used to statically specify
    the length of the output array so that this function can be used with transformations
    like :func:`jax.jit`. In this case, items larger than `length + 1` will be dropped.

  Args:
    x : N-dimensional array of positive integers
    weights: optional array of weights associated with ``x``. If not specified, the
      weight for each entry will be ``1``.
    minlength: the minimum length of the output counts array.
    length: the length of the output counts array. Must be specified statically for
      ``bincount`` to be used with :func:`jax.jit` and other JAX transformations.

  Returns:
    An array of counts or summed weights reflecting the number of occurrences of values
    in ``x``.

  See Also:
    - :func:`jax.numpy.histogram`
    - :func:`jax.numpy.digitize`
    - :func:`jax.numpy.unique_counts`

  Examples:
    Basic bincount:

    >>> x = jnp.array([1, 1, 2, 3, 3, 3])
    >>> jnp.bincount(x)
    Array([0, 2, 1, 3], dtype=int32)

    Weighted bincount:

    >>> weights = jnp.array([1, 2, 3, 4, 5, 6])
    >>> jnp.bincount(x, weights)
    Array([ 0,  3,  3, 15], dtype=int32)

    Specifying a static ``length`` makes this jit-compatible:

    >>> jit_bincount = jax.jit(jnp.bincount, static_argnames=['length'])
    >>> jit_bincount(x, length=5)
    Array([0, 2, 1, 3, 0], dtype=int32)

    Any negative numbers are clipped to the first bin, and numbers beyond the
    specified ``length`` are dropped:

    >>> x = jnp.array([-1, -1, 1, 3, 10])
    >>> jnp.bincount(x, length=5)
    Array([2, 1, 0, 1, 0], dtype=int32)
  r:  z6x argument to bincount must have an integer type; got r   z#only 1-dimensional input supported.zCThe error occurred because of argument 'minlength' of jnp.bincount.NzqThe error occurred because of argument 'x' of jnp.bincount. To avoid this error, pass a static `length` argument.z@The error occurred because of argument 'length' of jnp.bincount.rn   z'shape of weights must match shape of x.r   )r*   r   rT   r[   r   rx   rE   r   r   r   r   r   rS   r   r  r^   concrete_dim_or_errorr}   r  r  r?   r  r  r   r  )rM   r   rr  r5  rK  s        rK   r:  r:  _  sg   | z1%%%	F1IIw	'	' Z
XVTUYYXX
Y
YY	!WW\\
:
;
;;$X^YKM M)^"7A>? ?E EJ?3uyy{{+;+;a+?@@FF'JL LF_hq%%%GGQxx5>>!!
>
?
??	vvg	'	'	*41::	6	:	:7	C	CCrL   shapesc                     d S r`   rj   ru  s    rK   broadcast_shapesrx    s    ADrL   Sequence[int | core.Tracer]tuple[int | core.Tracer, ...]c                     d S r`   rj   rw  s    rK   rx  rx    s    9<rL   rx  c                 >    | sdS d | D             } t          j        |  S )Nrj   c                b    g | ],}t          j        |          d k    r|fnt          |          -S r   )r}   rE   rG   )r*  r?   s     rK   r2  z$broadcast_shapes.<locals>.<listcomp>  s6    RRR%!++UHHuRRRrL   )r   rx  rw  s    rK   rx  rx    s0    	 2RR6RRR&		v	&&rL   zAThe JAX version does not necessarily return a view of the input.
list[Array]c                     t          j        |  S r`   )r*   _broadcast_arraysr   s    rK   rk  rk    s     
		&&rL   r  DimSize | Shapec                ,    t          j        | |          S r`   )r*   _broadcast_to)r  r?   s     rK   r  r    s     
	E5	)	))rL   indices_or_sectionsint | Sequence[int] | ArrayLikec                   	
 t          j                    t                    t          j        t
          j        d  d          j                 }t          |t          t          f          s,t          |t          j        t          f          r1|j        dk    r& fd|D             }dgt          |          z   |gz   }nt          j        |          rt!          d  d          t          j        t"          |d  d          }t%          ||          \  	

dk    r	fdt'          |d	z             D             }nW d
k    r?	fdt'          
d	z             D             	
fdt'          |
z
            D             z   }nt!          d
           d |D             }dgt                    z  t                    cd fdt)          |d d         |d	d                    D             S )Nin jax.numpy.z argument `axis`r   c                B    g | ]}t          j        |d  d          S )r   argument 1)r   rt  )r*  i_sr   s     rK   r2  z_split.<locals>.<listcomp>  sB     ( ( ( 	"3(G(G(G(GHH( ( (rL   z
jax.numpy.z4 with a symbolic number of sections is not supportedr  c                    g | ]}|z  S rj   rj   r*  rD  	part_sizes     rK   r2  z_split.<locals>.<listcomp>  s-     9 9 9 9} 9 9 9rL   r   array_splitc                     g | ]
}|d z   z  S r   rj   r  s     rK   r2  z_split.<locals>.<listcomp>  s"    333i!m	333rL   c                8    g | ]}|z  d z   d z   z  d z
  z   S r   rj   )r*  rD  r  r+  s     rK   r2  z_split.<locals>.<listcomp>  sD     	+ 	+ 	+ 
Y1q5Y]3a7	8 	+ 	+ 	+rL   z:array split does not result in an equal division: rest is c                b    g | ],}t          j        |          r|nt          j        |          -S rj   )r   is_symbolic_dimr}   int64r  s     rK   r2  z_split.<locals>.<listcomp>  sD     + + + ,Q//@11RXa[[ + + +rL   c                (    t          | ||fg          S r`   )r6   )rM   rD  r   s      rK   <lambda>z_split.<locals>.<lambda>  s    GAAx00 rL   c                n    g | ]1\  }}t          j         |           |                    2S rj   )r   r   )r*  startend_subvalr  rb  endsstartss      rK   r2  z_split.<locals>.<listcomp>  s]     
H 
H 
HeS )Cu55wwtT37O7O
P
P 
H 
H 
HrL   r   )r*   r   rS   r   r   r   r   r?   rF   rG   rH   r}   r   r,   rE   r  r   r^   r  r   r  )r   r  r  rb  r  split_indicesnum_sectionsr  r  r  r+  r  s   `` `   @@@@@rK   _splitr    s    r3#		6Zb6Z6Z6Z	[	[$	4$$udm44 Y$rz5&9::Y""( ( ( (&( ( ( C$2333tf<MM/00 ( 'B ' ' ' ( ( (.s4G/Nr/N/N/NP PL$--LIqAvv9 9 9 9 %lQ&6 7 79 9 9mm	}		3333eAEll333	+ 	+ 	+ 	+ 	+q())	+ 	+ 	+	+ m
 WTUWWXXX+ +)+ + +-tCyy%**,&$00'
H 
H 
H 
H 
H 
H 
H 
Hcrc 2M!""4EFF
H 
H 
H HrL   c                (    t          d| ||          S )Nsplitrh  r  r  r  rb  s      rK   r  r    s     
1	=	=	==rL   3Callable[[ArrayLike, int | ArrayLike], list[Array]]c                v     t          j        t          t                     d          d
 fd	            }|S )NFr   r  r-   r  r  rB   r  c                    t          j        |            t          |           }dk    rt          |j                  dk    rdt          | |          S )Nr   r   rh  )r*   r   rS   r   r?   r  )r  r  r   rb  r   s      rK   r  z_split_on_axis.<locals>.f  s[     	S!!!AqyyS\\Q&&d"c.T::::rL   )r  r-   r  r  rB   r  )r*   
implementsrI   r}   )r   rb  r  s   `` rK   _split_on_axisr    sP    ?72r??u555; ; ; ; ; ; 65; 
(rL   vsplithsplitdsplitr   c                (    t          d| ||          S )Nr  rh  r  r  s      rK   r  r  
	  s     
s$7d	C	C	CCrL   jax-numpy-clip-complex)r   a_mina_maxr   r   r  ArrayLike | DeprecatedArgr   ArrayLike | None | DeprecatedArgr  c              4   t          |t                    s|n| } | t          d          t          |t                    s|n|}t          |t                    s|n|}t          d |||fD                       rt	          j        dt          d           t          j        d|            t          d | ||fD                       rt          j        d	d
d           |t          j        ||           } |t          j        ||           } t          |           S )ap  Clip array values to a specified range.

  JAX implementation of :func:`numpy.clip`.

  Args:
    arr: N-dimensional array to be clipped.
    min: optional minimum value of the clipped range; if ``None`` (default) then
      result will not be clipped to any minimum value. If specified, it should be
      broadcast-compatible with ``arr`` and ``max``.
    max: optional maximum value of the clipped range; if ``None`` (default) then
      result will not be clipped to any maximum value. If specified, it should be
      broadcast-compatible with ``arr`` and ``min``.
    a: deprecated alias of the ``arr`` argument.  Will result in a
      :class:`DeprecationWarning` if used.
    a_min: deprecated alias of the ``min`` argument. Will result in a
      :class:`DeprecationWarning` if used.
    a_max: deprecated alias of the ``max`` argument. Will result in a
      :class:`DeprecationWarning` if used.

  Returns:
    An array containing values from ``arr``, with values smaller than ``min`` set
    to ``min``, and values larger than ``max`` set to ``max``.

  See also:
    - :func:`jax.numpy.minimum`: Compute the element-wise minimum value of two arrays.
    - :func:`jax.numpy.maximum`: Compute the element-wise maximum value of two arrays.

  Examples:
    >>> arr = jnp.array([0, 1, 2, 3, 4, 5, 6, 7])
    >>> jnp.clip(arr, 2, 5)
    Array([2, 2, 2, 3, 4, 5, 5, 5], dtype=int32)
  Nz+No input was provided to the clip function.c              3  B   K   | ]}t          |t                     V  d S r`   )rF   r.   r*  ts     rK   r,  zclip.<locals>.<genexpr>B	  s/      EEaZ=))	)EEEEEErL   zPassing arguments 'a', 'a_min' or 'a_max' to jax.numpy.clip is deprecated. Please use 'arr', 'min' or 'max' respectively instead.r   r  r   c              3  T   K   | ]#}t           j                            |          V  $d S r`   )jaxr   rW   r  s     rK   r,  zclip.<locals>.<genexpr>K	  s2      <<q			"	"<<<<<<rL   r  aX  Clip received a complex value either through the input or the min/max keywords. Complex values have no ordering and cannot be clipped. Attempting to clip using complex numbers is deprecated and will soon raise a ValueError. Please convert to a real value or array by taking the real or imaginary components via jax.numpy.real/imag respectively.)rF   r.   r   r6  r  r  r  r*   r   r   r)   maximumminimumrS   )r  r   r   r   r  r  s         rK   r   r   	  sH   X A}--63#[
B
C
CC}55>3#}55>3#EEAue3DEEEEE MK	    vs###<<S#sO<<<<< 	O
     	_
.c
"
"C_
.c
"
"C	rL   r   )decimalsr  Nonec                   t          j        d|            t          j        t          j        d          |t          d          t          |           t          t                    r$dk     rt          d          t          |           S dfd
}t          t                    rKt          j         |t          j        |                      |t          j        |                               S  ||           S )Nroundz 'decimals' argument of jnp.roundz1The 'out' argument to jnp.round is not supported.r   z1integer np.round not implemented for decimals < 0rM   r-   rB   r,   c                   dk    r$t          j        | t           j        j                  S t          j        k    rt          j        | t          j                  n| } t          | dz            }t          j	        t          j        t          j
        | |          t           j        j                  |          }t          j        k    rt          j        |          n|S )Nr   r   )r   r  RoundingMethodTO_NEAREST_EVENr}   float16r  float32r   divr1  )rM   factorr   r  rP   s      rK   _round_floatzround.<locals>._round_floati	  s    1}}Yq#,<=== 49BJ3F3F BJ///AA2>**F
'#)CGAv...>@ @AGI IC38BJ3F3F3#C///COrL   rM   r-   rB   r,   )r*   r   r   r   r   r   r   r[   rT   r   rS   rU   r   complexr  rv  )r   r  r   r  rP   s    `  @rK   r  r  [	  s    w"""#HNH>`aa(_
Q
R
RR
))%w !||;= = =1::P P P P P P P '' ;||CHQKK00,,sx{{2K2KLLL<??rL   c                    t          j        d|            |t          d          t          | d          }t	          t          j        | |          t          j        |           t          j	        |                     S )Nfixz/The 'out' argument to jnp.fix is not supported.r   )
r*   r   r   r   r   r   ger)   r   r   )rM   r   zeros      rK   r  r  	  sf     ua   _
O
P
PP	Aq		$	svaQQ	@	@@rL           nanposinfneginfc           	        ~t          j        d|            t          |           }t          |t                    st          |           S t          |t                    r[t          j        t          t          j
        |           |||          t          t          j        |           |||                    S t          t          j        |                    }||j        n|}||j        n|}t#          t%          j        |           t          ||          |           }t#          t%          j        |          t          ||          |          }t#          t%          j        |          t          ||          |          }|S )N
nan_to_num)r  r  r  rn   )r*   r   r[   rT   r  rS   rU   r   r  r  r  rv  rI  r   r   r   r   r   r)   r   isposinfisneginf)rM   r   r  r  r  rP   infor   s           rK   r  r  	  sX   
 |Q'''
))%	E7	#	# 1::'' F;!#fVDDD!#fVDDDF F F 
v(//	0	0$~4886&~4886&fl1oows%888!<<#foc""GF%$@$@$@#FF#foc""GF%$@$@$@#FF#	*rL   c           	     x    t          j        d| |           t          j        t	          | ||||                    S )a  Check if two arrays are element-wise approximately equal within a tolerance.

  JAX implementation of :func:`numpy.allclose`.

  Essentially this function evaluates the following condition:

  .. math::

     |a - b| \le \mathtt{atol} + \mathtt{rtol} * |b|

  ``jnp.inf`` in ``a`` will be considered equal to ``jnp.inf`` in ``b``.

  Args:
    a: first input array to compare.
    b: second input array to compare.
    rtol: relative tolerance used for approximate equality. Default = 1e-05.
    atol: absolute tolerance used for approximate equality. Default = 1e-08.
    equal_nan: Boolean. If ``True``, NaNs in ``a`` will be considered
      equal to NaNs in ``b``. Default is ``False``.

  Returns:
    Boolean scalar array indicating whether the input arrays are element-wise
    approximately equal within the specified tolerances.

  See Also:
    - :func:`jax.numpy.isclose`
    - :func:`jax.numpy.equal`

  Examples:
    >>> jnp.allclose(jnp.array([1e6, 2e6, 3e6]), jnp.array([1e6, 2e6, 3e7]))
    Array(False, dtype=bool)
    >>> jnp.allclose(jnp.array([1e6, 2e6, 3e6]),
    ...              jnp.array([1.00008e6, 2.00008e7, 3.00008e8]), rtol=1e3)
    Array(True, dtype=bool)
    >>> jnp.allclose(jnp.array([1e6, 2e6, 3e6]),
    ...              jnp.array([1.00001e6, 2.00002e6, 3.00009e6]), atol=1e3)
    Array(True, dtype=bool)
    >>> jnp.allclose(jnp.array([jnp.nan, 1, 2]),
    ...              jnp.array([jnp.nan, 1, 2]), equal_nan=True)
    Array(True, dtype=bool)
  allclose)r*   r   r(   allr+  )r   r  r(  r)  r%  s        rK   r  r  	  s:    X z1a(((	1dD)<<	=	==rL   c               ,  	
 t          j        d|            t          |           }~ t          |          dk    rt	          d          |j        t          k    r|n|dk    }||                                n|}t          j	        |d          	|j
        dk    s	dk    r t          	fd|j        D                       S t          j        t          t          j        |          	                    t!          j        |j        ddd                   ddd         |j        z                      t&                    }t          fd	t)          ||j                  D                       }|t+          |t                    r|n
|j        |fz  }t-          d
 |D                       rt	          d|j         d|           t/          	          |                                k    
t          
fdt1          ||          D                       }|S )a  Return indices of nonzero elements of an array.

  JAX implementation of :func:`numpy.nonzero`.

  Because the size of the output of ``nonzero`` is data-dependent, the function
  is not compatible with JIT and other transformations. The JAX version adds
  the optional ``size`` argument which must be specified statically for
  ``jnp.nonzero`` to be used within JAX's transformations.

  Args:
    a: N-dimensional array.
    size: optional static integer specifying the number of nonzero entries to
      return. If there are more nonzero elements than the specified ``size``,
      then indices will be truncated at the end. If there are fewer nonzero
      elements than the specified size, then indices will be padded with
      ``fill_value``, which defaults to zero.
    fill_value: optional padding value when ``size`` is specified. Defaults to 0.

  Returns:
    Tuple of JAX Arrays of length ``a.ndim``, containing the indices of each
    nonzero value.

  See also:
    - :func:`jax.numpy.flatnonzero`
    - :func:`jax.numpy.where`

  Examples:

    One-dimensional array returns a length-1 tuple of indices:

    >>> x = jnp.array([0, 5, 0, 6, 0, 7])
    >>> jnp.nonzero(x)
    (Array([1, 3, 5], dtype=int32),)

    Two-dimensional array returns a length-2 tuple of indices:

    >>> x = jnp.array([[0, 5, 0],
    ...                [6, 0, 7]])
    >>> jnp.nonzero(x)
    (Array([0, 1, 1], dtype=int32), Array([1, 0, 2], dtype=int32))

    In either case, the resulting tuple of indices can be used directly to extract
    the nonzero values:

    >>> indices = jnp.nonzero(x)
    >>> x[indices]
    Array([5, 6, 7], dtype=int32)

    The output of ``nonzero`` has a dynamic shape, because the number of returned
    indices depends on the contents of the input array. As such, it is incompatible
    with JIT and other JAX transformations:

    >>> x = jnp.array([0, 5, 0, 6, 0, 7])
    >>> jax.jit(jnp.nonzero)(x)  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected: traced array with shape int32[].
    The size argument of jnp.nonzero must be statically specified to use jnp.nonzero within JAX transformations.

    This can be addressed by passing a static ``size`` parameter to specify the
    desired output shape:

    >>> nonzero_jit = jax.jit(jnp.nonzero, static_argnames='size')
    >>> nonzero_jit(x, size=3)
    (Array([1, 3, 5], dtype=int32),)

    If ``size`` does not match the true size, the result will be either truncated or padded:

    >>> nonzero_jit(x, size=2)  # size < 3: indices are truncated
    (Array([1, 3], dtype=int32),)
    >>> nonzero_jit(x, size=5)  # size > 3: indices are padded with zeros.
    (Array([1, 3, 5, 0, 0], dtype=int32),)

    You can specify a custom fill value for the padding using the ``fill_value`` argument:

    >>> nonzero_jit(x, size=5, fill_value=len(x))
    (Array([1, 3, 5, 6, 6], dtype=int32),)
  rd  r   zZCalling nonzero on 0d arrays is not allowed. Use jnp.atleast_1d(scalar).nonzero() instead.NzlThe size argument of jnp.nonzero must be statically specified to use jnp.nonzero within JAX transformations.c              3  B   K   | ]}t          t                    V  d S r`   )r  r^   )r*  dimcalculated_sizes     rK   r,  znonzero.<locals>.<genexpr>-
  s-      BB,,BBBBBBrL   r4  r   c              3  .   K   | ]\  }}|z  |z  V  d S r`   rj   )r*  strider  flat_indicess      rK   r,  znonzero.<locals>.<genexpr>1
  s1      ZZ,&$|v%-ZZZZZZrL   c              3  <   K   | ]}t          |          d k    V  dS )rj   N)_shape)r*  r   s     rK   r,  znonzero.<locals>.<genexpr>4
  s-      
7
76#;;"
7
7
7
7
7
7rL   z1fill_value must be a scalar or a tuple of length ; got c              3  @   K   | ]\  }}t          ||          V  d S r`   r  )r*  fvalentry	fill_masks      rK   r,  znonzero.<locals>.<genexpr>7
  s3      __+$iu--______rL   )r*   r   rS   rE   r   rP   rN   r  r   rt  r  rG   r?   r(   cumsumr:  r}   r  r   r  r  rF   r6  r  r7   )r   r  rZ  r  maskcalculated_size_r  r   fill_value_tupr  r  r  s            @@@rK   rd  rd  	  s(   b y!$$$

#	#YY!^^
 E F F F	T!!q$#'<TXXZZZT34D56 6/ 	X]]o**BBBB	BBBBBB"z &&???A A,CIdddO44TTrT:ciGOOPTUU'ZZZZ#gsyBYBYZZZZZ##-j%#@#@^ZZchR\Q^F^N

7
7
7
7
777 ig38gg[egghhh''488::5I
____.Z]A^A^___
_
_C	*rL   c               L    t          t          |           ||          d         S )aC  Return indices of nonzero elements in a flattened array

  JAX implementation of :func:`numpy.flatnonzero`.

  ``jnp.flatnonzero(x)`` is equivalent to ``nonzero(ravel(a))[0]``. For a full
  discussion of the parameters to this function, refer to :func:`jax.numpy.nonzero`.

  Args:
    a: N-dimensional array.
    size: optional static integer specifying the number of nonzero entries to
      return. See :func:`jax.numpy.nonzero` for more discussion of this parameter.
    fill_value: optional padding value when ``size`` is specified. Defaults to 0.
      See :func:`jax.numpy.nonzero` for more discussion of this parameter.

  Returns:
    Array containing the indices of each nonzero value in the flattened array.

  See Also:
    - :func:`jax.numpy.nonzero`
    - :func:`jax.numpy.where`

  Examples:
    >>> x = jnp.array([[0, 5, 0],
    ...                [6, 0, 8]])
    >>> jnp.flatnonzero(x)
    Array([1, 3, 5], dtype=int32)

    This is equivalent to calling :func:`~jax.numpy.nonzero` on the flattened
    array, and extracting the first entry in the resulting tuple:

    >>> jnp.nonzero(x.ravel())[0]
    Array([1, 3, 5], dtype=int32)

    The returned indices can be used to extract nonzero entries from the
    flattened array:

    >>> indices = jnp.flatnonzero(x)
    >>> x.ravel()[indices]
    Array([5, 6, 8], dtype=int32)
  rY  r   )rd  r  )r   r  rZ  s      rK   flatnonzeror  ;
  s%    T 
q	<	<	<Q	??rL   pdiscontc           	        t          j        d|            t          |           } t          | j        t
          j                  rt          d          | j        |         dk    rt          j	        |           d         S ||dz  }|dz  }t          | |          }t          j        ||z   |          |z
  }t          || k    |dk    z  ||          }t          t          j        |          |k     d||z
            }t          t!          j        | dd|          t!          j        | dd |          t%          j        ||          z   f|          }|S )Nunwrapz+jnp.unwrap does not support complex inputs.r   r   rh  r   )r*   r   rS   rT   rP   r}   rU   r   r?   r   r  r)   modr   r0  r  r   r  r(   r  )	r  r  rb  rD  intervalddddmod
ph_correctups	            rK   r  r  h
  s_    x###ajj!+,, D
B
C
CCWT]a&q))!,,_qjGaZ(AD"
*R(]F
+
+h
6%
8)#Q/5
A
A%VZ^^g-q%"*==*Q14(((Q4d+++j.?
QU.V.V.VV   "
 
)rL   .c                      e Zd ZdddddZdS )PadStatFuncNFrb  keepdimsr  r-   rb  r  r  rN   rB   r,   c                  d S r`   rj   )rb   r  rb  r  s       rK   ro   zPadStatFunc.__call__
  s    14rL   )r  r-   rb  r  r  rN   rB   r,   )rs   rt   ru   ro   rj   rL   rK   r  r  
  s8        "& %5 5 5 5 5 5 5 5rL   r  nvalsPadValueLiker  namePadValuec                    	 t          j        t          fd                      n:# t          $ r-}dt	          |          v rt          d d            | d }~ww xY w fd j        |dfk    rt          fd D                       S  j        dk    rJ  d	                     d
                   ft          fdt          |          D                       S  j        dk    rJ  d                     d                   ft          fdt          |          D                       S  j        dk    r9  d                   t          fdt          |          D                       S  j        dk    r>  j	        d                   t          fdt          |          D                       S t          d d|d j         d| d	          )Nc                8    t          j        d |  d          S )Nz argument of jnp.padr@   )r   r   )rM   r  s    rK   r  z%_broadcast_to_pairs.<locals>.<lambda>
  s"    &tQ48U8U8UVVV rL   z array has an inhomogeneous shape`"` entries must be the same shape: c                    t          j        |           st          j        |           s| S t	          d d           )Nr  r  )r   is_dimr}   r?   rx   )r   r  r  s    rK   as_scalar_dimz*_broadcast_to_pairs.<locals>.as_scalar_dim
  sH    {1~~ KRXa[[ KhI$II%IIJJJrL   r   c              3  \   K   | ]&} |d                     |d                   fV  'dS r   r   Nrj   )r*  nvalr  s     rK   r,  z&_broadcast_to_pairs.<locals>.<genexpr>
  sD      TTd--Q((--Q*@*@ATTTTTTrL   r   r   r   rY  c              3     K   | ]}V  d S r`   rj   r*  rD  v1_2s     rK   r,  z&_broadcast_to_pairs.<locals>.<genexpr>
  #      ))!))))))rL   r   r   r   c              3     K   | ]}V  d S r`   rj   r  s     rK   r,  z&_broadcast_to_pairs.<locals>.<genexpr>
  r  rL   r   c              3      K   | ]}fV  	d S r`   rj   r*  rD  r   s     rK   r,  z&_broadcast_to_pairs.<locals>.<genexpr>
  '      ++A!Q++++++rL   rj   c              3      K   | ]}fV  	d S r`   rj   r  s     rK   r,  z&_broadcast_to_pairs.<locals>.<genexpr>
  r  rL   z	jnp.pad: z	 with nd=z has unsupported shape z. Valid shapes are (z , 2), (1, 2), (2,), (1,), or ().)
r}   rS   r   r   rA   rx   r?   rG   r   flat)r  r  r  er  r   r  s   ` ` @@@rK   _broadcast_to_pairsr  
  s   
JxVVVV   EE 
 
 
 
)SVV33I$II%IIJJPQQ		
K K K K K K [RGTTTTeTTTTTT{f=t%%}}U4['A'AAD))))uRyy)))))){d=q""MM%($;$;;D))))uRyy)))))){deAhA++++r++++++{bejm$$A++++r++++++
 O O OR O O O O*,O O O P P Ps   %- 
A$(AA$axis_paddingtuple[Any, Any]c                ~    | d         dk    s| d         dk    r$d}t          |                    |                    d S )Nr   r   z'Cannot apply '{}' padding to empty axis)r   r   )r  r   rn  s      rK   _check_no_paddingr  
  sF    1o\!_q00
3C
SZZ%%
&
&& 10rL   	pad_widthPadValue[int]constant_valuesc                   t          |           }t          ||df          }t          j        || j        t          j        |                     }t          |          D ]l}dg|z  }||         d         ddf||<   t          j	        | ||df         |          } d||         d         df||<   t          j	        | ||df         |          } m| S )Nr   r   r   r   r   r   )
rE   r  r   _convert_element_typerP   r   is_weakly_typedr   r   pad)r  r  r  r  rD  widthss         rK   _pad_constantr$  
  s    E{{" 2q'::/ 6u{F$:5$A$AC C/99 : :a[2F1a!Q'F1IGE?1a40&99EIaLOQ'F1IGE?1a40&99EE	,rL   c                
   t          t          |                     D ]}| j        |         dk    rt          ||         d           *| j        |         }t	          ||         d         |          \  }}t	          ||         d         |          \  }}||z   dz   }g }	|dk    r|	t          j        | ||z
  ||          gz  }	|	|| gz  z  }	|dk    r|	t          j        | d||          gz  }	t          j        |	|          } | S )Nr   r  r   rh  	dimension)r   rE   r?   r  r  r   r  r  )
r  r  rD  r  left_repeatsleft_remainderright_repeatsright_remaindertotal_repeatspartss
             rK   	_pad_wrapr.  
  s'   e 0 0a{1~	!f---;q>D#))A,q/4#@#@ L.%+IaLOT%B%B"M? =014ME ~(=t!LLLMMe	]eW$$E ?CCCDDeOEQ///EE	,rL   reflect_typec                F   dv sJ dv sJ t          t          |                     D ]s| j                 dk    rt          |                    *| j                 fd} || |         d         d          }  || |         d         d          } t| S )	N	symmetricreflect)evenoddr   c                d   rt          j        | dd          }nt          j        | dd           }fd}	 dk    rdk    rdnd}t          j        f           }|r&dk    r	|z
  k    st	           |                      n/# t          j        $ r}t	           |                      |d }~ww xY wdk    rt          |z
            }|z  |rdk    sJ r|}	||z   }
n||z    }	dk    sdk    rd nd}
t          j        | |	|
          }t          |          }dk    rAd	|z  |z
  }dk    r3rt          j        |dd          }nt          j        |dd           }rt          j        || g
          } nt          j        | |g
          } dk    | S )Nr   r   rh  r   c            	     *    d  d drdnd d d	S )NzShape polymorphism is supported for jnp.pad with 'reflect' or 'symmetric' padding mode only when it is possible to determine at lowering time that the axis size (= zB) is larger than 1 and larger or equal than the padding length (= z). Error while handling rB  r  z padding on axis r   rj   )	axis_sizebeforerD  r   s   rK   r  zB_pad_symmetric_or_reflect.<locals>.build_padding.<locals>.<lambda>
  sb    W4=W W =DW W -3"?&&	W W ST	W W W rL   r3  r2  r5  r   r&  )	r   r  r   r  r   InconclusiveDimensionOperationr   r   r  )r  r   r9  edgeshape_poly_error_msgoffsethas_poly_dimr  curr_padr  stoprM   r8  rD  r   r/  s    ``         rK   build_paddingz0_pad_symmetric_or_reflect.<locals>.build_padding
  sh   	 9q!!444r4a888X X X X X X X8y((Y]]19g2FGGG 	3Q9v3E3P3P//1122
20 8 8 8--//00a78 aKKw	F 2338,1 	I%("$$v%&%+--ab$UE4a888OOO5  $hl!]] ;%aAA666dd%aT:::d 	;/1e*:::%%/5!*:::%5 aKK6 ls    AB B<B77B<T)r9  r   F)r   rE   r?   r  )r  r  r   r/  rA  r8  rD  s     `` @@rK   _pad_symmetric_or_reflectrB  
  s    	)	)	)	)	)		(	(	(	(e <@ <@a{1~	!d+++AI2 2 2 2 2 2 2 2h M%1a>>>EM%1a???EE	,rL   c                   t          |           }t          |          D ]}| j        |         dk    rt          ||         d           *| j        |         }||         \  }}t	          j        | dd|          }t          |||          }t	          j        | |dz
  ||          }	t          |	||          }
t	          j        || |
g|          } | S )Nr   r;  r   rh  r&  )rE   r   r?   r  r   r  repeatr  )r  r  r  rD  r  npad_before
npad_afteredge_before
pad_before
edge_after	pad_afters              rK   	_pad_edgerK  #  s    E{{"99 I Ia{1~	!f---AA'lK"5!QQ777K[q999J!%1aa888Jz:A666IOZ	:aHHHEE	,rL   
end_valuesPadValue[ArrayLike]c           	        t          t          |                     D ]6}t          j        | dd|          }t          j        | dd |          }t	          ||         d         |                    |          ||         d         d| j        |          }t          j        |t          j
        |                     }t	          ||         d         |                    |          ||         d         d| j        |          }t          j        |t          j
        |                     }t          ||          }t          j        || |g|          } 8| S )	Nr   r   rh  r   Fr  r@  numendpointrP   rb  )	weak_typer&  )r   rE   r   r  r  r  rP   r   r   r   r!  r   r  )r  r  rL  rb  rG  rI  ramp_before
ramp_afters           rK   _pad_linear_ramprU  7  sj   DKK   N Nd"5!QT:::K!%T===Jq!  &&dOAk  K 4v5e<<> > >Kq!%%dOAk  J 3f4U;;= = =J j$''JO[%<MMMEE	,rL   stat_lengthPadValue[int] | None	stat_funcc                z   t          |           }t          |          D ]}| || |d          }|}n| j        |         }||         \  }	}
|	dk    s|
dk    rt          d          t	          |	|          }	t	          |
|          }
t          j        | d|	|          }t          j        | |
 d |          } |||d          } |||d          }t          j        | j	        t          j
                  rt          |          }t          |          }t          j        || j	        t          j        |                     }t          j        || j	        t          j        |                     }||         \  }}t!          |||          }t!          |||          }t          j        || |g|          } | S )NTr  r   z,stat_length of 0 yields no value for paddingrh  r&  )rE   r   r?   r   r   r   r  r}   rT   rP   r   r  r   r   r   r!  rD  r  )r  r  rV  rX  r  rD  stat_before
stat_afterarray_lengthlength_beforelength_afterslice_beforeslice_afterrE  rF  rH  rJ  s                    rK   
_pad_statsra  X  s    E{{"99  I  IaIe!d;;;kjj[^l$/N!m\	!		|q00GHHH -66m|44l%eQAFFFl$U\M4aHHHkIlTBBBk9[q4@@@j	}U["*-- %+&&k$$j4U[&"8"?"?A AK3EK!7!>!>@ @J (lK[q999Jz:A666IOZ	:aHHHEE	,rL   c                   t          t          |                     D ]}| j        d |         ||         d         fz   | j        |dz   d          z   }t          | |          }| j        d |         ||         d         fz   | j        |dz   d          z   }t          | |          }t	          j        || |g|          } | S )Nr   r   r)  r&  )r   rE   r?   
empty_liker   r  )r  r  rD  shape_beforerH  shape_afterrJ  s          rK   
_pad_emptyrf    s    e I Ia;rr?il1o%77%+a!eff:MMLE666J+bqb/Yq\!_$66QUVV9LLK5444IOZ	:aHHHEE	,rL   funcCallable[..., Any]c           	         t          |t          |           d          }t          | |t          d                    }t	          t          |                    D ]}t          |||||         ||          }|S )Nr  r   )r  rE   r$  rS   r   apply_along_axis)r  r  rg  r   paddedrb  s         rK   	_pad_funcrl    sq    !)T%[[+FF)	71::66&DLL!! Q QddD&)D/4PPFF	-rL   )r   r   r^        )static_argnumsPadValueLike[int]PadValueLike[ArrayLike]c           	        t          |           } t          |           }|dk    r| S t          j        t          j        t          j        t          j        d}t          ||d          }t          j	        |          }	|	j
        |dfk    rt          d|df d|	j
         d          t          j        |	dk               rt          d          |d	k    rt          | |t          |                    S |d
k    rt          | |          S |dv rt          | |t!          |          |          S |dk    rt#          | |          S |dk    r"t          ||d          }t%          | ||          S ||v r8|t          ||d          }t'          | |||t!          |                             S |dk    rt)          | |          S J d            )Nr   )r  r  meanmedianr  r   z!Expected pad_width to have shape r  r   z#index can't contain negative valuesconstantr  r1  r;  linear_ramprL  rV  emptyFzTShould not be reached since pad already handled unsupported andnot implemented modes)rS   rE   r(   amaxaminrs  rt  r  r}   r  r?   r   r6  r$  r.  rB  rA   rK  rU  ra  rf  )
r  r  r   r  rV  rL  r/  r  
stat_funcspad_width_arrs
             rK   _padr|    s    %..%E{{"1WWL o!	( (* ")R==)(9%%-RG##
^"a^^H[^^^
_
__VMA <
:
;
;;	Z	7?+C+CDDDv~~UI&&&'''$UIs4yy,OOOv~~UI&&&}$Z\BBJE9j999z'RGGkeYZD		5JKKKweY''', + , , ,rL   zUnlike numpy, JAX "function" mode's argument (which is another function) should return
the modified array. This is because Jax arrays are immutable.
(In numpy, "function" mode's argument should modify a rank 1 array in-place.)
ru  &PadValueLike[int | Array | np.ndarray]str | Callable[..., Any]c                   t          j        d|            t          |t          |           d          }|r(t	          d |D                       st          d          t          |          rt          t          |           ||fi |S g g g dgdgdgdgdgdgdgdgd	}	 t          |          t          ||                   z
  }n2# t          $ r% d
}t          |                    |                    w xY w|r#t          d                    ||                    |                    dd          }|                    dd           }|                    dd          }	|                    dd          }
t          | |||||	|
          S )Nr"  r  c              3  ~   K   | ]8}t          j        |d                    ot          j        |d                   V  9dS r  r   r  )r*  r  s     rK   r,  zpad.<locals>.<genexpr>  sW       / /   ;qt,,BQqT1B1B / / / / / /rL   z%`pad_width` must be of integral type.r  rL  rV  r/  )rw  r;  r  ru  rv  r  rs  rt  r  r3  r2  z+Unimplemented padding mode '{}' for np.pad.z/unsupported keyword arguments for mode '{}': {}r   r4  )r*   r   r  rE   r  rx   callablerl  rS   setKeyErrorr   r   r   getr|  )r  r  r   r   allowed_kwargsunsupported_kwargsrn  r  rV  rL  r/  s              rK   r"  r"    s    ue$$$!)T%[[+FF) =s / /$-/ / / / / =
;
<
<<d^^ @WU^^Y????? 2r$%"^o !"#
 
.0Vs>$+?'@'@@	 0 0 0
7C
cjj..
/
//0  8
FfT#5668 8 8 JJ0!44/

=$//+zz,***NF33,	eYo{JP\	]	]]s    %C /C5arrays(np.ndarray | Array | Sequence[ArrayLike]c                \   t          |           st          d          |t          d          t          | t          j        t          f          r8t          || j                  }t          t          | |dz             ||          S t          j        dg| R   t          | d                   }t          |t          |          dz             }g }| D ]G}t          |          |k    rt          d          |                    t          ||                     Ht          |||          S )Nz!Need at least one array to stack.z1The 'out' argument to jnp.stack is not supported.r   rb  rP   rj  r   z*All input arrays must have the same shape.)r   r   r   rF   r}   r   r,   rO  rE   r  r  r*   r   r?   r8  )r  rb  r   rP   shape0
new_arraysr   s          rK   rj  rj    s/    
V :
8
9
99_
Q
R
RRU+,, ;dFK00D{64!8444uMMMM*6****6!9FdCKK!O44DJ . .	qV		EFFFAt,,----zE::::rL   unstackc                  t          j        d|            t          |           } | j        dk    rt	          d          t          t          | |d                    S )Nr  r   zIUnstack requires arrays with rank > 0, however a scalar array was passed.)r*   r   rS   rE   r   rG   r  )rM   rb  s     rK   r  r    s`     y!$$$ajj!Vq[[
   
x4##	$	$$rL   ArepsDimSize | Sequence[DimSize]c           	     R   t          j        d|            	 t          |           t          |          }n# t          $ r |f}Y nw xY wt          d |D                       }dt          |          t          |           z
  z  t          |           z   }dt          |          t          |          z
  z  |z   }t          t          | d |D                       d t          ||          D                       }t          |t          t          j        ||                              S )Nr  c              3  j   K   | ].}t          j        |          rt          j        |          n|V  /d S r`   )r   is_constant_dimr   r   )r*  reps     rK   r,  ztile.<locals>.<genexpr>"  sU       ( ( +/*>s*C*CL8>#&&& ( ( ( ( ( (rL   r   c                     g | ]}d |fD ]}|S r   rj   )r*  rD  js      rK   r2  ztile.<locals>.<listcomp>&  s)    #G#G#G!A#G#G1A#G#G#G#GrL   c                    g | ]	}|D ]}|
S rj   rj   )r*  pairrX  s      rK   r2  ztile.<locals>.<listcomp>'  s%    LLLttLL!LLLLrL   )r*   r   iterrG   rx   r   rE   r?   r  r=  r  r}   multiply)r  r  reps_tupA_shaper   s        rK   r  r    s:   vq!!!JJJ T{{HH 
 , , ,%)GHHH,  ( (&( ( ( ( ((CMMDGG+,uQxx7'S\\CMM12X=(#G#Gw#G#G#GHHLLs8W'='=LLLN N&	r{7H==>>	?	??s   6 AAc                ,   t          | |          } | j        dk    s| j        d         dk    rt          d          |t	          j        | | j        f          S | j        dk    rt          d          t          || j        dz
            }| j        d|dz            | j        d         | j        |dz            z  fz   | j        |dz   d          z   }g t          d|dz             dt          |dz   | j                  }t	          j        | ||          S )Nrn   r   'Need at least one array to concatenate.r   /Zero-dimensional arrays cannot be concatenated.r   )	rS   rE   r?   r   r   r=  r  rO  r   )r  rb  rP   r?   
dimensionss        rK   _concatenate_arrayr  *  s    	5!!!#X]]cila''
>
?
??	\;sSXK(((X]]
F
G
GG	D#(Q,	/	/$
)AdQhJ
39Q<#)D1H2E#E"G
G#)TX[\T\T]T]J^
^%Cq$(##CQCtax)B)BC*	S%	,	,,rL   c                   t          | t          j        t          f          rt	          |           S t          j        dg| R   t          |           st          d          t          d | D             d          S t          | d                   dk    rt          d          t          t          | d                             t          j        |  nfd| D             d	t                    d
k    r?fdt          dt                              D             t                    d
k    ?d         S )Nrn   r  r  c                ,    g | ]}t          |          S rj   )r  r*  r   s     rK   r2  zconcatenate.<locals>.<listcomp>B  s    111Qa111rL   r   r  r  c                2    g | ]}t          |           S rn   r  )r*  r  rP   s     rK   r2  zconcatenate.<locals>.<listcomp>I  s&    >>>'#U+++>>>rL      r   c                P    g | ]"}t          j        ||z                      #S rj   )r   r  )r*  rD  
arrays_outrb  rX  s     rK   r2  zconcatenate.<locals>.<listcomp>O  sB     9 9 9 /*QqsU"3T:: 9 9 9rL   )rF   r}   r   r,   r  r*   r   r   r   r  rE   rO  r   r   )r  rb  rP   r  rX  s    ``@@rK   r  r  9  s{    U+,, 9fd%8888}.v....	V @
>
?
??	\11&111GGGG	&)__
F
G
GG	D$vay//	2	2$
]$f-JJ>>>>v>>>J 	!J!9 9 9 9 9 9 C
OOQ779 9 9J 	J! 
ArL   concatc              h    t          j        dg| R   t          j                            | |          S )Nr  rh  )r*   r   r  r   r  )r  rb  s     rK   r  r  T  s6    x)&))))			vD		1	11rL   tupc                    t          | t          j        t          f          r# t	          j        t                    |           }n!t          j        dg| R ddi d | D             }t          |d|          S )Nvstackemit_warningTc                ,    g | ]}t          |          S rj   )
atleast_2dr*  rZ  s     rK   r2  zvstack.<locals>.<listcomp>c      '''aJqMM'''rL   r   r  )
rF   r}   r   r,   r  vmapr  r*   r   r  r  rP   arrss      rK   r  r  Z       bj%()) (38J$$DD 	;C;;;d;;;''3'''D	T	/	/	//rL   c                .   t          | t          j        t          f          r- t	          j        t                    |           }|j        dz
  }n.t          j	        dg| R ddi d | D             }|d         j        }t          ||dk    rdnd|          S )Nr   hstackr  Tc                ,    g | ]}t          |          S rj   )
atleast_1dr  s     rK   r2  zhstack.<locals>.<listcomp>q  r  rL   r   r  )rF   r}   r   r,   r  r  r  rE   r*   r   r  )r  rP   r  	arr0_ndims       rK   r  r  g  s     bj%()) 38J$$D	AII 	;C;;;d;;;''3'''DQI	TY!^^%	H	H	HHrL   c                    t          | t          j        t          f          r# t	          j        t                    |           }n!t          j        dg| R ddi d | D             }t          |d|          S )Ndstackr  Tc                ,    g | ]}t          |          S rj   
atleast_3dr  s     rK   r2  zdstack.<locals>.<listcomp>  r  rL   r   r  )
rF   r}   r   r,   r  r  r  r*   r   r  r  s      rK   r  r  v  r  rL   c                $   t          | t          j        t          f          r,| j        dk     r t          j        d           |           n| }n4t          j        dg| R ddi d t          t          |           D             }t          |d          S )N   c                *    t          |           j        S r`   )r  r=   rZ   s    rK   r  zcolumn_stack.<locals>.<lambda>  s    jmmo rL   column_stackr  Tc                P    g | ]#}|j         d k     rt          |          j        n|$S r   )rE   r  r=   r*  r  s     rK   r2  z column_stack.<locals>.<listcomp>  s0    TTT3AJsOO3TTTrL   r   )rF   r}   r   r,   rE   r  r  r*   r   maprS   r  )r  r  s     rK   r  r    s     bj%()) U7:x!||.38--..s333DD 	A#AAADAAATT#gsBSBSTTTD	T1		rL   choicesc                p   |t          d          t          j        d| g|R   t          t	          |           t
                    st          d          t          |          }|dk    rJt          j	        t          | d          }t          j        |dk     ||k    z            rt          d          nG|dk    rt          |           |z  }n.|d	k    rt          | d|d
z
            }nt          d|d          t          |g|R  ^}}t          |          |ft!          |j        d          z            S )Nz2The 'out' argument to jnp.choose is not supported.choosez`a` array must be integer typedr  zqThe error occurred because jnp.choose was jit-compiled with mode='raise'. Use mode='wrap' or mode='clip' instead.r   zinvalid entry in choice arrayr  r   r   zmode=z3 not understood. Must be 'raise', 'wrap', or 'clip'T)sparse)r   r*   r   rT   r[   r   r   r   r   r   rS   r(   r6  r   rk  r  r  r?   )r   r  r   r   r   r  s         rK   r  r    sU    	_
R
S
SSx-W----	F1IIw	'	' 8
6
7
77	'll!	W__'DE EC ~sQw3!8,-- 867778v~~
!**q.CCv~~
q!QU

CC
XTXXX
Y
YY"31111-#	w4!@!@!@@	AArL   c                    t          |           }||k     rt          j        | d||z
  z            nt          |           S )Nr   )rE   r   	broadcastrS   )rM   r  rZ  s      rK   _atleast_ndr    s:    
1gg!-.UUq$!a%.	)	)	)

BrL   xstuple[Array, int]c                v   t          | t                    r"t          d                    |                     t          | t                    rt          |           dk    rt          d          t          d | D                       \  }t          fddd          D                       rt          d          t          d         t          d |D                                 t          fd	|D                       }t          |d          
          d         dz   fS t          |           dfS )Nz-jax.numpy.block does not allow tuples, got {}r   z3jax.numpy.block does not allow empty list argumentsc                ,    g | ]}t          |          S rj   _blockr*  rM   s     rK   r2  z_block.<locals>.<listcomp>  s    3331VAYY333rL   c              3  0   K   | ]}|d          k    V  dS r  rj   )r*  r  depthss     rK   r,  z_block.<locals>.<genexpr>  s+      
.
.a1q	>
.
.
.
.
.
.rL   r   z)Mismatched list depths in jax.numpy.blockc              3  4   K   | ]}t          |          V  d S r`   r  r  s     rK   r,  z_block.<locals>.<genexpr>  s(      66!d1gg666666rL   c              3  8   K   | ]}t          |          V  d S r`   )r  )r*  rM   ranks     rK   r,  z_block.<locals>.<genexpr>  s-      88A;q$''888888rL   rh  )rF   rG   r   r   rH   r   r5   r6  r   r  rS   )r  xs_tupr  r  s     @@rK   r  r    sE   E 
DfRjj" " ""d 

2ww!||LMMM3333344NFF

.
.
.
.6!"":
.
.
... DBCCCvay#66v6666677D888888888FvVAYJ///Q>>2;;>rL   c                *    t          |           \  }}|S r`   r  )r  r   r  s      rK   blockr    s     &>>&#q	*rL   c                     d S r`   rj   rj   rL   rK   r  r        #rL   c                   d S r`   rj   rZ   s    rK   r  r    r  rL   arysc                   d S r`   rj   rM   r   r  s      rK   r  r    r  rL   )r   rW  c                     t          j        dg| R ddi t          |           dk    rt          | d         dd          S d | D             S )	Nr  r  Tr   r   Fr   ndminc                2    g | ]}t          |d d          S )Fr   r  r  r  s     rK   r2  zatleast_1d.<locals>.<listcomp>  '    <<<E#E+++<<<rL   r*   r   r   r  r  s    rK   r  r    a     |>d>>>>>>YY!^^auA....<<t<<<<rL   c                     d S r`   rj   rj   rL   rK   r  r    r  rL   c                   d S r`   rj   rZ   s    rK   r  r    r  rL   c                   d S r`   rj   r  s      rK   r  r    r  rL   c                     t          j        dg| R ddi t          |           dk    rt          | d         dd          S d	 | D             S )
Nr  r  Tr   r   Fr   r  c                2    g | ]}t          |d d          S )Fr   r  r  r  s     rK   r2  zatleast_2d.<locals>.<listcomp>  r  rL   r  r  s    rK   r  r    r  rL   c                     d S r`   rj   rj   rL   rK   r  r    r  rL   c                   d S r`   rj   rZ   s    rK   r  r    r  rL   c                   d S r`   rj   r  s      rK   r  r    r  rL   c                 b   t          j        dg| R ddi t          |           dk    r|t          | d                   }|j        dk    rt          j        |d          }nC|j        dk    rt          j        |d          }n!|j        d	k    rt          j        |d
          }|S d | D             S )Nr  r  Tr   r   )r   r   r   r  )r   r   r   r   c                ,    g | ]}t          |          S rj   r  r  s     rK   r2  zatleast_3d.<locals>.<listcomp>  s    ,,,JsOO,,,rL   )r*   r   r   rS   rE   r   r  )r  r  s     rK   r  r    s     |>d>>>>>>YY!^^
$q'

C
x1}}OCI666cc	QOCF333cc	QOCD111cJ,,t,,,,rL   c                H    	 t          |           }dS # t          $ r Y dS w xY w)NTF)
memoryviewrx   )r   r   s     rK   _supports_buffer_protocolr    s=    c??D 4 
   55s    
!!a  
This function will create arrays on JAX's default device. For control of the
device placement of data, see :func:`jax.device_put`. More information is
available in the JAX FAQ at :ref:`faq-data-placement` (full FAQ at
https://jax.readthedocs.io/en/latest/faq.html).
jax-numpy-array-nonez|
device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
  to which the created array will be committed.
)rW  extra_paramsr  devicer|   
str | Noner  r  xc.Device | Sharding | Nonec          	        ||dk    rt          d          t          j        d           d u ot          j        |           }t	          |          }|sHt          | t          j                  r.| j        k    r!|| j	        k    r|t          j        |           S t          | t          t          t          t          f          rt          j        |           }nt          | t"                    st%          | d          r|                                 } n}t%          | d          rm| j        }	t+          j        d          }
t.          d }n&t.                              |	d         d                   }t2          j                            |	|
|	          } t9          d
 |           } t;          | d           }t=          d |D                       rNt?          j         d          rtC          d          tE          j#        dtH          d           t;          |           }T	 |rt          j%        | d         nt          j&        n0# tB          $ r# d |D             }t          j%        | d         Y nw xY w|st          j'        d          tQ          d |D                       rt          j)        |           }nt          | t"                    r| j*        J |rtW          |           n| }nt          | tX          tZ          f          r5| rt]          fd| D                       }nt          j/        g           }nhta          |           r:tc          |           } |rt          j/        |           nt          j)        |           }ntC          dte          |                      tg          j4        |||          }|t          |          k    r2tk          j6        |to          |t          |          z
                      }|S )Nr  zOnly implemented for order='K'r  r   __cuda_array_interface__cudadatar   )caigpu_backend	device_idc                N    t          | d          r|                                 n| S r   )r   r   )leafs    rK   r  zarray.<locals>.<lambda>S  s.    t_55"@!3!3!5!5!5;? rL   c                
    | d u S r`   rj   rZ   s    rK   r  zarray.<locals>.<lambda>U  s
    d rL   )is_leafc              3     K   | ]}|d u V  	d S r`   rj   r*  r  s     rK   r,  zarray.<locals>.<genexpr>V  s&      ))$))))))rL   r  z'None is not a valid value for jnp.arrayznNone encountered in jnp.array(); this is currently treated as NaN. In the future this will result in an error.r   r  c                ,    g | ]}t          |          S rj   ) _convert_to_array_if_dtype_failsr  s     rK   r2  zarray.<locals>.<listcomp>g  s!    JJJ4066JJJrL   Tallow_extended_dtypec              3  B   K   | ]}t          |t                     V  d S r`   )rF   r,   r  s     rK   r,  zarray.<locals>.<genexpr>o  s/      88Ze$$	$888888rL   rn   c                2    g | ]}t          |           S r  r  )r*  eltrP   s     rK   r2  zarray.<locals>.<listcomp>z  s&    ???73e,,,???rL   z!Unexpected input type for array: )rR  sharding)8r   r   check_user_dtype_supportedr!  canonicalize_device_to_shardingrF   r}   r   rP   rE   r  
device_putrN   r^   floatr  coerce_to_arrayr,   r   r   r  r   get_backendcuda_plugin_extensionget_device_ordinalxc_xlacuda_array_interface_to_bufferr   r   r6  r   is_acceleratedrx   r  r  FutureWarning_lattice_result_typer   r   r  rS   avalr#   rH   rG   rj  r  r  r  rQ   r   r   r   r  r   )r|   rP   r   r  r  r  rR  r  r  r  backendr
  leavesr   	out_arrays    `             rK   r  r    sT    5C<<
>
?
?? 	#E7333 tm> 6v > >),V44(  ":fbj11 "}--EV[4H4Hn>&!!! sE7344 =vu--AAfe$$ = v'' 
=##%%ff	3	4	4 =+c&v..g		&		)<<S[^LL	w55w) 6 = =f  @ @AGI I&v':':;;;&))&))))) !"#9:: A?@@@M4# # # #   F
]69?Rf)62155V]ee 6 6 6 KJ6JJJf)6215eee	6 
 H%e$GGGE 	8888888 H
 *V5
)
)
)CC&%   H;"""!%
1+f


6CC&4-(( 
H &???????@@ccHRu%%%cc (( HF"
:"(6



6(:(:CC
FVFF
G
GG!7	5I: : :)
T)__	5i1H+I+IJJI	s   !"I *I10I1Sharding | Nonec                X    t          | t          j                  rt          |           S | S r`   rF   r!  Devicer   r   s    rK   r  r    s)    	"" ('''	-rL   c                x    	 t          j        |            | S # t          $ r t          j        |           cY S w xY wr`   )r   rP   rx   r}   rS   rZ   s    rK   r  r    sL    
LOOO H 
   :a==s    99 jax-numpy-astype-complex-to-real)r   r  c                 t          j        d|            t          |           }|t          j        t
                    }t          j        |d           t          |j        t                    r^t          j
        |d          rt          j        ddd           n1t          j        |          t          k    r|t          |d          k    }t!          j                    5  t!          j        d	t&                     t)          j        ||t-          |          
          }ddd           n# 1 swxY w Y   |rt/          |          n|S )aS  Convert an array to a specified dtype.

  JAX imlementation of :func:`numpy.astype`.

  This is implemented via :func:`jax.lax.convert_element_type`, which may
  have slightly different behavior than :func:`numpy.astype` in some cases.
  In particular, the details of float-to-int and int-to-float casts are
  implementation dependent.

  Args:
    x: input array to convert
    dtype: output dtype
    copy: if True, then always return a copy. If False (default) then only
      return a copy if necessary.
    device: optionally specify the device to which the output will be committed.

  Returns:
    An array with the same shape as ``x``, containing values of the specified
    dtype.

  See Also:
    - :func:`jax.lax.convert_element_type`: lower-level function for XLA-style
      dtype conversions.

  Examples:
    >>> x = jnp.array([0, 1, 2, 3])
    >>> x
    Array([0, 1, 2, 3], dtype=int32)
    >>> x.astype('float32')
    Array([0.0, 1.0, 2.0, 3.0], dtype=float32)

    >>> y = jnp.array([0.0, 0.5, 1.0])
    >>> y.astype(int)  # truncates fractional values
    Array([0, 0, 1], dtype=int32)
  r   N)r   zreal floatingr0  zCasting from complex to real dtypes will soon raise a ValueError. Please first use jnp.real or jnp.imag to take the real/imaginary component of your input.r   r  r   ignorer  )r*   r   rS   r   r   r   r  rT   rP   rU   r   r   r  r}   rN   r   r  catch_warningssimplefilterComplexWarningr   r   _normalize_to_shardingr#   )rM   rP   r   r  rK  r   s         rK   r   r     s   L x###
!**%
]%f--E#E8444_-- 
.~e:;; 	.*	#      
%D	 	 
5!,,,e    = =(N333/U3F;;= = =F= = = = = = = = = = = = = = = !%	0V			&0s    ?D++D/2D/c                  |du rot          | t                    sZt          j                    dk    rCt	          |           r4t          dt          |            dt          j                    d          t          j        |d           |t          j	        |d          }t          | |t          |          ||	          S )
NFcpuz+jnp.asarray: cannot convert object of type z to JAX Array on backend=z@ with copy=False. Consider using copy=None or copy=True instead.rS   Tr  )rP   r   r  r  )rF   r,   r  default_backendr  r   rQ   r   r  r   r  rN   )r   rP   r  r   r  s        rK   rS   rS     s     emmJq%00m



5
(
(
#A
&
& )
 G477 G G#&#6#8#8G G G H H H 	#E9555
%e$GGGE	qDJJeF	K	K	KKrL   c                P    t          j        d|            t          | d|          S )Nr   T)r   r  )r*   r   r  r  s     rK   r   r     s*    vq!!!	qt5	)	)	))rL   ArrayLike | DuckTypedArrayc          	        t          | d          rt          | d          st          j        d|            t          j        |d           |t          |          }t          j        | d||t          |                    S )a  Create an array full of zeros with the same shape and dtype as an array.

  JAX implementation of :func:`numpy.zeros_like`.

  Args:
    a: Array-like object with ``shape`` and ``dtype`` attributes.
    shape: optionally override the shape of the created array.
    dtype: optionally override the dtype of the created array.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.zeros`
    - :func:`jax.numpy.empty_like`
    - :func:`jax.numpy.ones_like`
    - :func:`jax.numpy.full_like`

  Examples:
    >>> x = jnp.arange(4)
    >>> jnp.zeros_like(x)
    Array([0, 0, 0, 0], dtype=int32)
    >>> jnp.zeros_like(x, dtype=bool)
    Array([False, False, False, False], dtype=bool)
    >>> jnp.zeros_like(x, shape=(2, 3))
    Array([[0, 0, 0],
           [0, 0, 0]], dtype=int32)
  rP   r?   r  Nr   r3  	r   r*   r   r   r  rJ   r   	full_liker7  r   rP   r?   r  s       rK   r  r    s    D !W

 *'!W"5"5 *q)))#E<888
u%%E	q!UE4J64R4R	S	S	SSrL   c          	        t          | d          rt          | d          st          j        d|            t          j        |d           |t          |          }t          j        | d||t          |                    S )a  Create an array of ones with the same shape and dtype as an array.

  JAX implementation of :func:`numpy.ones_like`.

  Args:
    a: Array-like object with ``shape`` and ``dtype`` attributes.
    shape: optionally override the shape of the created array.
    dtype: optionally override the dtype of the created array.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.empty`
    - :func:`jax.numpy.zeros_like`
    - :func:`jax.numpy.ones_like`
    - :func:`jax.numpy.full_like`

  Examples:
    >>> x = jnp.arange(4)
    >>> jnp.ones_like(x)
    Array([1, 1, 1, 1], dtype=int32)
    >>> jnp.ones_like(x, dtype=bool)
    Array([ True,  True,  True,  True], dtype=bool)
    >>> jnp.ones_like(x, shape=(2, 3))
    Array([[1, 1, 1],
           [1, 1, 1]], dtype=int32)
  rP   r?   r  Nr   r3  r>  r@  s       rK   r  r  #  s    D !W

 )'!W"5"5 )a(((#E;777
u%%E	q!UE4J64R4R	S	S	SSrL   	prototypec                   t          | d          rt          | d          st          j        d|            t          j        |d           t          | |||          S )aN  Create an empty array with the same shape and dtype as an array.

  JAX implementation of :func:`numpy.empty_like`. Because XLA cannot create
  an un-initialized array, :func:`jax.numpy.empty` will always return an
  array full of zeros.

  Args:
    a: Array-like object with ``shape`` and ``dtype`` attributes.
    shape: optionally override the shape of the created array.
    dtype: optionally override the dtype of the created array.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.empty`
    - :func:`jax.numpy.zeros_like`
    - :func:`jax.numpy.ones_like`
    - :func:`jax.numpy.full_like`

  Examples:
    >>> x = jnp.arange(4)
    >>> jnp.empty_like(x)
    Array([0, 0, 0, 0], dtype=int32)
    >>> jnp.empty_like(x, dtype=bool)
    Array([False, False, False, False], dtype=bool)
    >>> jnp.empty_like(x, shape=(2, 3))
    Array([[0, 0, 0],
           [0, 0, 0]], dtype=int32)
  rP   r?   rc  )rP   r?   r  )r   r*   r   r   r  r  )rB  rP   r?   r  s       rK   rc  rc  M  se    H )W
%
% 2')W*E*E 2y111#E<888	IU%	G	G	GGrL   c                X    t          | t          j                  rt          |           S | S r`   r-  r   s    rK   r7  r7  w  s)    	"" '''MrL   c               H   t          j        |d           t          j        d|           t	          |          dk    r4t          |           } t          j        | ||t          |                    S t          j
        t          t          ||          |           |          S )aT  Create an array full of a specified value.

  JAX implementation of :func:`numpy.full`.

  Args:
    shape: int or sequence of ints specifying the shape of the created array.
    fill_value: scalar or array with which to fill the created array.
    dtype: optional dtype for the created array; defaults to the dtype of the
      fill value.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.full_like`
    - :func:`jax.numpy.empty`
    - :func:`jax.numpy.zeros`
    - :func:`jax.numpy.ones`

  Examples:
    >>> jnp.full(4, 2, dtype=float)
    Array([2., 2., 2., 2.], dtype=float32)
    >>> jnp.full((2, 3), 0, dtype=bool)
    Array([[False, False, False],
           [False, False, False]], dtype=bool)

    `fill_value` may also be an array that is broadcast to the specified shape:

    >>> jnp.full((2, 3), fill_value=jnp.arange(3))
    Array([[0, 1, 2],
           [0, 1, 2]], dtype=int32)
  r   r   r3  rn   )r   r  r*   r   rE   rJ   r   r   r7  r  r  r  rS   )r?   rZ  rP   r  s       rK   r   r   ~  s    J 	#E6222vz***	*u%%E8E:u7Mf7U7UVVVV>WZu555u==vG G GrL   c          	        t          | d          r't          | d          rt          j        dd|           nt          j        d| |           t          j        |d           |t          |          }t          |          dk    r&t          j        | |||t          |                    S |t          j        |           n|}|t          |           n|}t          j        t          t!          ||          |          |          S )a  Create an array full of a specified value with the same shape and dtype as an array.

  JAX implementation of :func:`numpy.full_like`.

  Args:
    a: Array-like object with ``shape`` and ``dtype`` attributes.
    fill_value: scalar or array with which to fill the created array.
    shape: optionally override the shape of the created array.
    dtype: optionally override the dtype of the created array.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.full`
    - :func:`jax.numpy.empty_like`
    - :func:`jax.numpy.zeros_like`
    - :func:`jax.numpy.ones_like`

  Examples:
    >>> x = jnp.arange(4.0)
    >>> jnp.full_like(x, 2)
    Array([2., 2., 2., 2.], dtype=float32)
    >>> jnp.full_like(x, 0, shape=(2, 3))
    Array([[0., 0., 0.],
           [0., 0., 0.]], dtype=float32)

    `fill_value` may also be an array that is broadcast to the specified shape:

    >>> x = jnp.arange(6).reshape(2, 3)
    >>> jnp.full_like(x, fill_value=jnp.array([[1], [2]]))
    Array([[1, 1, 1],
           [2, 2, 2]], dtype=int32)
  rP   r?   r?  r   Nr3  rn   )r   r*   r   r   r  rJ   rE   r   r?  r7  r}   r?   r   r  r  r  rS   )r   rZ  rP   r?   r  s        rK   r?  r?    s   P Q 5WQ00 5a4444a444#E;777
u%%E	*=Ju?UV\?]?]^^^^ =BHQKKKeE#mKNNNE>WZu555u==vG G GrL   c               D   t          | t          j                  rt          d          t	          d| |          x}rt          |          t          j        |d           t          |           } t          j	        | dt          |          t          |                    S )a   Create an array full of zeros.

  JAX implementation of :func:`numpy.zeros`.

  Args:
    shape: int or sequence of ints specifying the shape of the created array.
    dtype: optional dtype for the created array; defaults to floating point.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.zeros_like`
    - :func:`jax.numpy.empty`
    - :func:`jax.numpy.ones`
    - :func:`jax.numpy.full`

  Examples:
    >>> jnp.zeros(4)
    Array([0., 0., 0., 0.], dtype=float32)
    >>> jnp.zeros((2, 3), dtype=bool)
    Array([[False, False, False],
           [False, False, False]], dtype=bool)
  :expected sequence object with len >= 0 or a single integerr  r   r3  )rF   typesGeneratorTyperx   _check_forgot_shape_tupler   r  rJ   r   r   r   r7  r?   rP   r  rZ  s       rK   r  r    s    8 u*++ R
P
Q
QQ$WeU;;;aPIaLL>P#E7333
U
#
#%	%Ju--8Nv8V8V	W	W	WWrL   c               D   t          | t          j                  rt          d          t	          d| |          x}rt          |          t          |           } t          j        |d           t          j	        | dt          |          t          |                    S )a  Create an array full of ones.

  JAX implementation of :func:`numpy.ones`.

  Args:
    shape: int or sequence of ints specifying the shape of the created array.
    dtype: optional dtype for the created array; defaults to floating point.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.ones_like`
    - :func:`jax.numpy.empty`
    - :func:`jax.numpy.zeros`
    - :func:`jax.numpy.full`

  Examples:
    >>> jnp.ones(4)
    Array([1., 1., 1., 1.], dtype=float32)
    >>> jnp.ones((2, 3), dtype=bool)
    Array([[ True,  True,  True],
           [ True,  True,  True]], dtype=bool)
  rH  onesr   r3  )rF   rI  rJ  rx   rK  rJ   r   r  r   r   r   r7  rL  s       rK   rN  rN  
  s    8 u*++ R
P
Q
QQ$VUE:::aO9Q<<=O
U
#
#%#E6222	%Ju--8Nv8V8V	W	W	WWrL   c                   t          d| |          x}rt          |          t          j        |d           t	          | ||          S )a  Create an empty array.

  JAX implementation of :func:`numpy.empty`. Because XLA cannot create an
  un-initialized array, :func:`jax.numpy.empty` will always return an array
  full of zeros.

  Args:
    shape: int or sequence of ints specifying the shape of the created array.
    dtype: optional dtype for the created array; defaults to floating point.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of the specified shape and dtype, on the specified device if specified.

  See also:
    - :func:`jax.numpy.empty_like`
    - :func:`jax.numpy.zeros`
    - :func:`jax.numpy.ones`
    - :func:`jax.numpy.full`

  Examples:
    >>> jnp.empty(4)
    Array([0., 0., 0., 0.], dtype=float32)
    >>> jnp.empty((2, 3), dtype=bool)
    Array([[False, False, False],
           [False, False, False]], dtype=bool)
  rw  r   )rK  rx   r   r  r  rL  s       rK   rw  rw  .  sN    < %WeU;;;aPIaLL>P#E7333	ueF	+	+	++rL   c                    t          |t                    r-t          |t                    rd| d|  d| d| d|  d| d| dS d S d S )NzCannot interpret 'z9' as a data type.

Did you accidentally write `jax.numpy.(, z)` when you meant `jax.numpy.z((z5))`, i.e. with a single tuple argument for the shape?rF   r^   )r  r?   rP   s      rK   rK  rK  P  s    s ;
5# 6 6 ;: : :: :!&: :*/: : *.: : 27: : ;@: : : ;; ; ; ;rL   a1a2c           	        t          |           t          |          }} t          |           t          |          k    rt          d          S t          | |k              }|rLt          j        |t          j        t          j        |           t          j        |                              }t          j        |          S )a@  Check if two arrays are element-wise equal.

  JAX implementation of :func:`numpy.array_equal`.

  Args:
    a1: first input array to compare.
    a2: second input array to compare.
    equal_nan: Boolean. If ``True``, NaNs in ``a1`` will be considered
      equal to NaNs in ``a2``. Default is ``False``.

  Returns:
    Boolean scalar array indicating whether the input arrays are element-wise equal.

  See Also:
    - :func:`jax.numpy.allclose`
    - :func:`jax.numpy.array_equiv`

  Examples:
    >>> jnp.array_equal(jnp.array([1, 2, 3]), jnp.array([1, 2, 3]))
    Array(True, dtype=bool)
    >>> jnp.array_equal(jnp.array([1, 2, 3]), jnp.array([1, 2]))
    Array(False, dtype=bool)
    >>> jnp.array_equal(jnp.array([1, 2, 3]), jnp.array([1, 2, 4]))
    Array(False, dtype=bool)
    >>> jnp.array_equal(jnp.array([1, 2, float('nan')]),
    ...                 jnp.array([1, 2, float('nan')]))
    Array(False, dtype=bool)
    >>> jnp.array_equal(jnp.array([1, 2, float('nan')]),
    ...                 jnp.array([1, 2, float('nan')]), equal_nan=True)
    Array(True, dtype=bool)
  F)	rS   r?   r  r)   r3  r4  r   r(   r  )rT  rU  r%  r|  s       rK   array_equalrW  Y  s    @ 2;;b"
2YY%))<<rRx" W		2v1&,r2B2BFLQSDTDTUU	V	VB			rL   c                    t          |           t          |          }} 	 t          j        | |          }n# t          $ r t	          d          cY S w xY wt          j        |          S )a;  Check if two arrays are element-wise equal.

  JAX implementation of :func:`numpy.array_equiv`.

  This function will return ``False`` if the input arrays cannot be broadcasted
  to the same shape.

  Args:
    a1: first input array to compare.
    a2: second input array to compare.

  Returns:
    Boolean scalar array indicating whether the input arrays are
    element-wise equal after broadcasting.

  See Also:
    - :func:`jax.numpy.allclose`
    - :func:`jax.numpy.array_equal`

  Examples:
    >>> jnp.array_equiv(jnp.array([1, 2, 3]), jnp.array([1, 2, 3]))
    Array(True, dtype=bool)
    >>> jnp.array_equiv(jnp.array([1, 2, 3]), jnp.array([1, 2, 4]))
    Array(False, dtype=bool)
    >>> jnp.array_equiv(jnp.array([[1, 2, 3], [1, 2, 3]]),
    ...                 jnp.array([1, 2, 3]))
    Array(True, dtype=bool)
  F)rS   r)   equalr   r  r(   r  )rT  rU  r|  s      rK   array_equivrZ    sp    : 2;;b"	b"		BB	   << 
		s   6 AAbufferbytes | Anycountr=  c                L    t          t          j        | |||                    S )Nr[  rP   r]  r=  )rS   r}   
frombufferr_  s       rK   r`  r`    s%     
fEvVVV	W	WWrL   c                      t          d          )a/  Unimplemented JAX wrapper for jnp.fromfile.

  This function is left deliberately unimplemented because it may be non-pure and thus
  unsafe for use with JIT and other JAX transformations. Consider using
  ``jnp.asarray(np.fromfile(...))`` instead, although care should be taken if ``np.fromfile``
  is used within jax transformations because of its potential side-effect of consuming the
  file object; for more information see `Common Gotchas: Pure Functions
  <https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functions>`_.
  a  jnp.fromfile() is not implemented because it may be non-pure and thus unsafe for use with JIT and other JAX transformations. Consider using jnp.asarray(np.fromfile(...)) instead, although care should be taken if np.fromfile is used within a jax transformations because of its potential side-effect of consuming the file object; for more information see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functionsr   r   r   s     rK   fromfilerd         	_	` 	` `rL   c                      t          d          )a3  Unimplemented JAX wrapper for jnp.fromiter.

  This function is left deliberately unimplemented because it may be non-pure and thus
  unsafe for use with JIT and other JAX transformations. Consider using
  ``jnp.asarray(np.fromiter(...))`` instead, although care should be taken if ``np.fromiter``
  is used within jax transformations because of its potential side-effect of consuming the
  iterable object; for more information see `Common Gotchas: Pure Functions
  <https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functions>`_.
  a  jnp.fromiter() is not implemented because it may be non-pure and thus unsafe for use with JIT and other JAX transformations. Consider using jnp.asarray(np.fromiter(...)) instead, although care should be taken if np.fromiter is used within a jax transformations because of its potential side-effect of consuming the iterable object; for more information see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functionsrb  rc  s     rK   fromiterrg    re  rL   from_dlpacka_  
.. note::

   While JAX arrays are always immutable, dlpack buffers cannot be marked as
   immutable, and it is possible for processes external to JAX to mutate them
   in-place. If a jax Array is constructed from a dlpack buffer and the buffer
   is later modified in-place, it may lead to undefined behavior when using
   the associated JAX array.
r  r   c              *    ddl m}  || ||          S )Nr   )rh  ri  )
jax.dlpackrh  )rM   r  r   rh  s       rK   rh  rh    s-     %$$$$$	QvD	1	1	11rL   rn   functionCallable[..., Array]c          
     @   t          j        |d          }t          t          |                    D ]Vfdt          t          |                    D             }t	          j        | t          |d d d                             } W | fd|D             i |S )Nz$shape argument of jnp.fromfunction()r  c                $    g | ]}|k    rd ndS r  rj   )r*  r  rD  s     rK   r2  z fromfunction.<locals>.<listcomp>  s%    @@@AFFqq@@@rL   r   in_axesc              3  :   K   | ]}t          |           V  dS )rn   N)r  )r*  r  rP   s     rK   r,  zfromfunction.<locals>.<genexpr>  s0      ::qF1E***::::::rL   )r   rJ   r   r   r  r  rG   )rl  r?   rP   r   rq  rD  s     `  @rK   fromfunctionrs    s     
!%1W
X
X
X%U @ @a@@@@eCJJ.?.?@@@Gx%"*>*>???HH	::::E:::	Ef	E	EErL   stringsepc               L    t          t          j        | |||                    S )Nrt  rP   r]  ru  )rS   r}   
fromstringrw  s       rK   rx  rx    s#    	fECPPP	Q	QQrL   r   r/   MDimSize | Noneint | ArrayLikec               \    t          | |||          }|t          j        ||          S |S )a  Create a square or rectangular identity matrix

  JAX implementation of :func:`numpy.eye`.

  Args:
    N: integer specifying the first dimension of the array.
    M: optional integer specifying the second dimension of the array;
      defaults to the same value as ``N``.
    k: optional integer specifying the offset of the diagonal. Use positive
      values for upper diagonals, and negative values for lower diagonals.
      Default is zero.
    dtype: optional dtype; defaults to floating point.
    device: optional :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Identity array of shape ``(N, M)``, or ``(N, N)`` if ``M`` is not specified.

  See also:
    :func:`jax.numpy.identity`: Simpler API for generating square identity matrices.

  Examples:
    A simple 3x3 identity matrix:

    >>> jnp.eye(3)
    Array([[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]], dtype=float32)

    Integer identity matrices with offset diagonals:

    >>> jnp.eye(3, k=1, dtype=int)
    Array([[0, 1, 0],
           [0, 0, 1],
           [0, 0, 0]], dtype=int32)
    >>> jnp.eye(3, k=-1, dtype=int)
    Array([[0, 0, 0],
           [1, 0, 0],
           [0, 1, 0]], dtype=int32)

    Non-square identity matrix:

    >>> jnp.eye(3, 5, k=1)
    Array([[0., 1., 0., 0., 0.],
           [0., 0., 1., 0., 0.],
           [0., 0., 0., 1., 0.]], dtype=float32)
  )ry  rX  rP   Nr   )_eyer  r  )r   ry  rX  rP   r  outputs         rK   eyer    s;    j Q!5)))&>&0000	-rL   c                   t          j        |d           t          |t                    rt	          j        |t          j                  }t          j	        d|           t          |          }|j        dk    r$t          j        |j        t          j                  st          d|           t!          j        | d          }||nt!          j        |d          }|dk     s|dk     rt          d|  d|           t%          j        |j        ||fd          }t%          j        |j        ||fd	          }||z   |k                        |          S )
Nr  rj   z k must be a scalar integer; got z'N' argument of jnp.eye()z'M' argument of jnp.eye()r   z)negative dimensions are not allowed, got r   r   )r   r  rF   r^   r   _clip_int_to_valid_ranger}   int32r*   r   rS   r?   rT   rP   r   r   r   canonicalize_dimr   broadcasted_iotar   )	r   ry  rX  rP   r=  N_intM_intrD  r  s	            rK   r}  r}  +  sC    	#E51113 ;-a::Aua   1::&
,"

!26<!L!L

;;;
<
<<

#>
?
?%9%%$"7;V"W"W%
QYY%!))
LLLLL
M
MM	6<%;;!	6<%;;!
f*/	!	!%	(	((rL   c                N    t          j        |d           t          | |          S )av  Create a square identity matrix

  JAX implementation of :func:`numpy.identity`.

  Args:
    n: integer specifying the size of each array dimension.
    dtype: optional dtype; defaults to floating point.

  Returns:
    Identity array of shape ``(n, n)``.

  See also:
    :func:`jax.numpy.eye`: non-square and/or offset identity matrices.

  Examples:
    A simple 3x3 identity matrix:

    >>> jnp.identity(3)
    Array([[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]], dtype=float32)

    A 2x2 integer identity matrix:

    >>> jnp.identity(2, dtype=int)
    Array([[1, 0],
           [0, 1]], dtype=int32)
  identityrn   )r   r  r  )r  rP   s     rK   r  r  >  s*    : 	#E:666	Qe			rL   r  ArrayLike | DimSizer@  ArrayLike | DimSize | Nonestepc               \    t          | |||          }|t          j        ||          S |S )a	  Create an array of evenly-spaced values.

  JAX implementation of :func:`numpy.arange`, implemented in terms of
  :func:`jax.lax.iota`.

  Similar to Python's :func:`range` function, this can be called with a few
  different positional signatures:

  - ``jnp.arange(stop)``: generate values from 0 to ``stop``, stepping by 1.
  - ``jnp.arange(start, stop)``: generate values from ``start`` to ``stop``,
    stepping by 1.
  - ``jnp.arange(start, stop, step)``: generate values from ``start`` to ``stop``,
    stepping by ``step``.

  Like with Python's :func:`range` function, the starting value is inclusive,
  and the stop value is exclusive.

  Args:
    start: start of the interval, inclusive.
    stop: optional end of the interval, exclusive. If not specified, then
      ``(start, stop) = (0, start)``
    step: optional step size for the interval. Default = 1.
    dtype: optional dtype for the returned array; if not specified it will
      be determined via type promotion of `start`, `stop`, and `step`.
    device: (optional) :class:`~jax.Device` or :class:`~jax.sharding.Sharding`
      to which the created array will be committed.

  Returns:
    Array of evenly-spaced values from ``start`` to ``stop``, separated by ``step``.

  Note:
    Using ``arange`` with a floating-point ``step`` argument can lead to unexpected
    results due to accumulation of floating-point errors, especially with
    lower-precision data types like ``float8_*`` and ``bfloat16``.
    To avoid precision errors, consider generating a range of integers, and scaling
    it to the desired range. For example, instead of this::

       jnp.arange(-1, 1, 0.01, dtype='bfloat16')

    it can be more accurate to generate a sequence of integers, and scale them::

       (jnp.arange(-100, 100) * 0.01).astype('bfloat16')

  Examples:
    Single-argument version specifies only the ``stop`` value:

    >>> jnp.arange(4)
    Array([0, 1, 2, 3], dtype=int32)

    Passing a floating-point ``stop`` value leads to a floating-point result:

    >>> jnp.arange(4.0)
    Array([0., 1., 2., 3.], dtype=float32)

    Two-argument version specifies ``start`` and ``stop``, with ``step=1``:

    >>> jnp.arange(1, 6)
    Array([1, 2, 3, 4, 5], dtype=int32)

    Three-argument version specifies ``start``, ``stop``, and ``step``:

    >>> jnp.arange(0, 2, 0.5)
    Array([0. , 0.5, 1. , 1.5], dtype=float32)

  See Also:
    - :func:`jax.numpy.linspace`: generate a fixed number of evenly-spaced values.
    - :func:`jax.lax.iota`: directly generate integer sequences in XLA.
  r@  r  rP   Nr   )_aranger  r  )r  r@  r  rP   r  r~  s         rK   r  r  _  s;    R 5t$e<<<&>&0000	-rL   c                P   t          j        |d           t          j        j        sFt          j        d|            ||t          j        d | d          } nt          j        d | d          } t          j	        dd ||           t          j        d |d          }t          j        d |d          }||dnd}|| fd|fd|ffD ]4\  }}|-t          j        |          dk    rt          d	| d
|           5t          d | ||fD                       rA|	|| }d} d}n||d}t          | |||pt          j        t          j                            S |t#          | gd ||fD             R  }t%          |          }||t'          |           }t          j        |t          j                  stt          j        |t           j                  sUt/          | t          j                  rt2          j        nt          j        } ||                               t8                    } t;          j        ||           S |G| dk    rA|?t;          j        |t          j        |                              t8                              S t?          t          j         | |||                    S )Nr  z*It arose in the jnp.arange argument 'stop'z+It arose in the jnp.arange argument 'start'z*It arose in the jnp.arange argument 'step'r@  r  r  r   z1jax.numpy.arange: arguments must be scalars; got =c              3  >   K   | ]}t          j        |          V  d S r`   )r   r  r*  r   s     rK   r,  z_arange.<locals>.<genexpr>  s-      >>Q	a	 	 >>>>>>rL   r   c              3     K   | ]}||V  	d S r`   rj   r  s     rK   r,  z_arange.<locals>.<genexpr>  s"       J JqAMMMMM J JrL   r  )!r   r  r   dynamic_shapesvaluer*   r   r   r   check_arraylike_or_noner}   rE   r   r6  _arange_dynamicr   r  r   r   r[   rT   r   r   rF   Tracerr)   r   r   r^   r   iotar  r  )	r  r@  r  rP   
start_namer  r   start_dtypeceil_s	            rK   r  r    s   #E8444			$ a5)))|$T52^__ee$T52_``extT:::		d,X	Y	Y$		d,X	Y	Y$$,vvG*'&$&$H Y YidC
273<<1,,W4WWRUWWXXX>>5$*=>>>>> \|dedd		dld5$e.Zv7PQSQY7Z7Z[[[
]K J JT4L J J JKKKE
U

%	\dl--Kk2:66 'k6?;;''t{;;HfkkeeEll!!#&&e8E5!!!|

t'7XeRWT]]11#667775t$eDDDEEErL   c                   t          d | ||fD                       rt          d|  d| d|           	 |dk    rt          d          |dk    }n5# t          j        $ r#}t          j        d| dd	| z             d }~ww xY w|r|n| }|r|| z
  n| |z
  }t          j        d||z   d
z
            |z  }t          | |          t          ||          t          j        ||          z  z   S )Nc              3  @   K   | ]}t          j        |           V  d S r`   r  r  s     rK   r,  z"_arange_dynamic.<locals>.<genexpr>  s-      99T[^^	999999rL   z{In arange with non-constant arguments all of start, stop, and step must be either dimension expressions or integers: start=z, stop=z, step=r   zarange has step == 0z0In arange with non-constant arguments the step () must 5be resolved statically if it is > 0 or < 0.
Details: r   rn   )r6  r   r   r:  max_dimr  r   r  )	r  r@  r  rP   	step_gt_0r  gapdistancer  s	            rK   r  r    sp    	99eT4%899999 %
	$CH	$ 	$	$ 	$!	$ 	$% % %
Fqyy-...II		, F F F

-H4HHHDDD	EF F FF %v#(<dUllut|(	aC!+	,	,	3$
U
#
#
#
E
"
"
"SXeT%:%:
:; <s   A B!A??B2   rP  rQ  retstepLiteral[False]c                   d S r`   rj   r  r@  rP  rQ  r  rP   rb  r  s           rK   r  r    s    
 GJcrL   Literal[True]c                   d S r`   rj   r  s           rK   r  r    s    
 UXTWrL   )rP   rb  r  c                   d S r`   rj   r  s           rK   r  r    s    
 RUQTrL   Array | tuple[Array, Array]c                   d S r`   rj   r  s           rK   r  r     s    
 ]`\_rL   )r  c          
         t          j        |d          }t          j        t          j        |d          }t          | |||||||          S )Nz'num' argument of jnp.linspacez'axis' argument of jnp.linspacer   )r   rt  r   r   r   	_linspacer  s           rK   r  r    sM     	"3(HII#		6W	X	X$	5$XwtF	S	S	SSrL   )rP  rQ  r  rP   rb  r  c                  t          j        |d           |dk     rt          d| d          t          j        d| |           |"t          j        t          | |                    }t          |          }t          j        |          }t          | |          } t          ||          }t          t          j        t          |           t          |                              }	t          | |	          }
t          ||	          }|dk     rt          |	          |z   dz   n|}|	                    |d           |r|dz
  n|}|dk    r
t          j        || z
  |          t#          ||          z  }dgt          |	          z  }|||<   t%          |          j        }t)          t          j        ||          |          t#          ||          z  }|                    |          }t)          |
|	          d|z
  z  t)          ||	          |z  z   }|r>t          j        |t          j        ||f          gt3          ||j                            }n|dk    r.t          |rt6          n|| z
  |          }t)          |
|	          }nt          t          j        t          |           t          |                              }|                    |d           t          t6          |          }t)          t#          g |          |          }t9          |t:                    r.t9          |j        t:                    st          j        |          }t?          |          }tA          j!        |||          }|r||fn|S )	zAImplementation of linspace differentiable in start and stop args.r  r   zNumber of samples, z, must be non-negative.Nrn   r   r3  )"r   r  r   r*   r   r   r   r   rS   rH   r   rx  r?   r  r   r"  r  r  rI  rP   r=  r  r   r  r  rO  rE   r  rT   r   r   r  r   r   )r  r@  rP  rQ  r  rP   rb  r  computation_dtypebounds_shapebroadcast_startbroadcast_stopr  rQ  
iota_shape
real_dtyper  r   empty_shaper  r   s                        rK   r  r    se    	#E:6661WW
G3GGG
H
HHz5$///
]#Kt$<$<==E
U

%-e44
%0
1
1
1%	.	/	/	/$c*5<<tEEFF, 55/l33.)-\		T	!A	%	%t$dA&q3#1WW+D5L:KLLuUX`qOrOrOrrEL)))JJt ())/J38J,,j99E#z<R<RRD;;())D?L11QX>nl++d23C  @OS#/.4'"J"JK.tSX>>@ @c axx85CC=NOOOE
/<
0
0CCs+E%LL%++FFGGKtQC0111E
%%(((+
6
6Cw 
39g(F(F 
)C..C,V44(-c58LLL&#	/&%/rL         $@basec           	         t          j        t          j        |d          }t          j        t          j        |d          }t	          | ||||||          S )Nz'num' argument of jnp.logspacez'axis' argument of jnp.logspace)r   r   r   r   	_logspace)r  r@  rP  rQ  r  rP   rb  s          rK   logspacer  M  sL     	x~s4TUU#		6W	X	X$	5$XtUD	A	AArL   )rP  rQ  rP   rb  c           	        t          j        |d           |"t          j        t          | |                    }t	          |          }t          j        |          }t          j        d| |           t          | |          } t          ||          }t          | |||dd|          }t          j
        t          j        ||          |          S )zAImplementation of logspace differentiable in start and stop args.r  Nrn   F)rQ  r  rP   rb  )r   r  r   r   r   r*   r   rS   r  r   r  r)   power)	r  r@  rP  rQ  r  rP   rb  r  lins	            rK   r  r  U  s    
 	#E:666
]#Kt$<$<==E
U

%-e44z5$///
%0
1
1
1%	.	/	/	/$c"ED	J 	J 	J#		!&,tS"9"95	A	AArL   c                    t          j        t          j        |d          }t          j        t          j        |d          }t	          | |||||          S )Nz'num' argument of jnp.geomspacez 'axis' argument of jnp.geomspace)r   r   r   r   
_geomspacerO  s         rK   	geomspacer  g  sJ     	x~s4UVV#		6X	Y	Y$	E4ht	<	<<rL   c           
     0   t          j        |d           |"t          j        t          | |                    }t	          |          }t          j        |          }t          j        d| |           t          | |          } t          ||          }t          j	        |           }|t          t          j        | |z            t          j        ||z            ||d|d          z  }|dk    rt          |d|          }t          j        ||          S )zBImplementation of geomspace differentiable in start and stop args.r  Nrn   r  r   )rQ  r  rP   rb  )r   r  r   r   r   r*   r   rS   r)   signr  log10r  r   r  )	r  r@  rP  rQ  rP   rb  r  r  ress	            rK   r  r  n  s    	#E;777
]#Kt$<$<==E
U

%-e44{E4000
%0
1
1
1%	.	/	/	/$	U		$xUT\22FL4M4MhT/a9 9 9 	9# 
QYY
34
 
 C		!#u	-	--rL   rH  )r   r  indexingxir  r  c                   t          j        dg|R   d |D             }| st          d          |dvrt          d|           t          d |D                       rt          dd |D                        |d	k    r*t	          |          d
k    r|d         |d         c|d<   |d<   fd|D             fdfdt          |          D             }|d	k    r*t	          |          d
k    r|d         |d         c|d<   |d<   |S )Nmeshgridc                ,    g | ]}t          |          S rj   r  r  s     rK   r2  zmeshgrid.<locals>.<listcomp>  s    	!	!	!'!**	!	!	!rL   z*jax.numpy.meshgrid only supports copy=True)rH  ijz1Valid values for indexing are 'xy' and 'ij', got c              3  ,   K   | ]}|j         d k    V  dS r.  r  r  s     rK   r,  zmeshgrid.<locals>.<genexpr>  s(      ##1######rL   z7Arguments to jax.numpy.meshgrid must be 1D, got shapes c                    g | ]	}|j         
S rj   r)  r  s     rK   r2  zmeshgrid.<locals>.<listcomp>  s    ///Q///rL   rH  r   r   r   c                2    g | ]}rd n|j         d         S r   r   r)  )r*  r   r  s     rK   r2  zmeshgrid.<locals>.<listcomp>  s(    
5
5
51&11AGAJ
5
5
5rL   c                X    r&g d |          |j         d         | dz   d          nS )Nr   r   r)  )rD  r   r?   r  s     rK   r  zmeshgrid.<locals>.<lambda>  s<    fWBE"1"IBqwqzBE!a%&&MBBRW rL   c           	     X    g | ]&\  }}t          j        | ||          |f          'S rj   )r   broadcast_in_dim)r*  rD  r   _a_shapes      rK   r2  zmeshgrid.<locals>.<listcomp>  s8    WWWeaC HHQNNQD99WWWrL   )r*   r   r   r6  r   r  )r   r  r  r  r   r~  r  r?   s    `    @@rK   r  r    sw    z'B''''	!	!b	!	!	!$	 C
A
B
BB\!!
SSS
T
TT##d##### 3
 2//$///2 2 3 3 3#d))q..AwQDGT!W
5
5
5
5
5
5
5%WWWWW(WWWWyQUWWW&#d))q..!!9fQiF1Ivay	-rL   c                F   t          j        d|           \  }t          |j        t          j                  st          dt          |                      t          j	        |          }t          j
        t          j        |          t          j        |                    S )Ni0z(Unsupported input type to jax.numpy.i0: )r*   r-  rT   rP   r}   r  r   r[   r   r0  r1  exp
bessel_i0e)rM   rK  s     rK   r  r    s}     $T1--&%	EK	-	- M
Kq		KK
L
LL
'%..%	!6!6	7	77rL   c                    t          j        t          j        | |          \  }}|t	          | d         dk    d|          fS )Nr   r  )r  jvpr  funr   )primalstangents
primal_outtangent_outs       rK   _i0_jvpr    s;    GBFGX>>*k	U71:?C==	==rL   c            
        t          j        dg| R   t          |           }g }t          |           D ]\  }}t	          |          }t          |j                  dk    r)d}t          |                    |j                            t          |          t          k    rt          d          dg|z  }|j        d         ||<   |j        dk    rF|                    t          j        |t          j        dt          j                                       |                    t          j        |||f                     t'          |          S )av  Return a multi-dimensional grid (open mesh) from N one-dimensional sequences.

  JAX implementation of :func:`numpy.ix_`.

  Args:
    *args: N one-dimensional arrays

  Returns:
    Tuple of Jax arrays forming an open mesh, each with N dimensions.

  See Also:
    - :obj:`jax.numpy.ogrid`
    - :obj:`jax.numpy.mgrid`
    - :func:`jax.numpy.meshgrid`

  Examples:
    >>> rows = jnp.array([0, 2])
    >>> cols = jnp.array([1, 3])
    >>> open_mesh = jnp.ix_(rows, cols)
    >>> open_mesh
    (Array([[0],
          [2]], dtype=int32), Array([[1, 3]], dtype=int32))
    >>> [grid.shape for grid in open_mesh]
    [(2, 1), (1, 2)]
    >>> x = jnp.array([[10, 20, 30, 40],
    ...                [50, 60, 70, 80],
    ...                [90, 100, 110, 120],
    ...                [130, 140, 150, 160]])
    >>> x[open_mesh]
    Array([[ 20,  40],
           [100, 120]], dtype=int32)
  ixr   z>Arguments to jax.numpy.ix_ must be 1-dimensional, got shape {}z6Boolean arguments to jax.numpy.ix_ are not implementedr   rj   )r*   r   r   r  rS   r?   r   r   r[   r  r   r  r8  r   r   r}   r  intpr  rG   )r   r  r~  rD  r   rn  r?   s          rK   r>  r>    s5   B t#d####	$ii!&oo : :da

A
17||qLcszz!'**+++ayyE@B B BC!GEwqzE!Hv{{mmCHUBHR$9$9::;;;;mmC(EA4889999	vrL   r  c                    d S r`   rj   r  rP   r  s      rK   r  r    s    69crL   c                   d S r`   rj   r  s      rK   r  r    s    <?CrL   c                    d S r`   rj   r  s      rK   r  r    s    @CrL   c                   t          j        |d           |pt          j        t                    }t	          d | D                       } t          |           }g }| }t          |           D ][\  }}t          j        ||          }|rd|z  |fz   d||z
  dz
  z  z   }|	                    t          j
        |||f                     \|rt	          |          S |rt          |d          nt          g |          S )Nr  c              3  V   K   | ]$}t          j        t          j        |d           V  %dS )z"dimensions argument of jnp.indicesNr  r  s     rK   r,  zindices.<locals>.<genexpr>  sH        
 X^Q0TUU     rL   r   r   r   rn   )r   r  r   r  rG   r   r  r   r  r8  r  rj  r  )	r  rP   r  r   r~  r  rD  r  rp  s	            rK   r  r    s$    	#E9555

26,T22%      * 
*oo!&!*%% 6 6fa
(5#

C -
q&C6/D!a%!),
,a
MM#&sAt445555 ==#	?vq			r)?)?)??rL   )total_repeat_lengthr  r  c          
        t          j        d|            t          j        |          pt          j        d|           |t	          |           } d}nt          |           } t          j        t          j        |d          }t          |t                    sJ t          j        |          r|t          d|d|d          |t          j        d|d          }t          j        |          dk    rt          |           dk    rt          |           }t!          |t#          |                    }|d	z   t%          |          }|                    t          j        |          rt          j        |          n|           t+          j        | |fd
t/          t#          |                    D                       } t%          |          }||xx         |z  cc<   t1          | |          S t          j        |          }t          |           dk    r)t          j        |t          |           |         g          }t          j        |          }nFt	          |          }t          |           dk    r$t3          |t          |           |         g          }t          |           dk    r3t          |          dk    rt7          |g|           S t          d          |dk    rMt%          t          |                     }d||<   t1          t9          g t;          |                     |          S t          |           |         dk    rt          |           S t=          |d	          j        d                              d          }tC          j"        |          }tG          |gtH                    }	|	j        |         %                    d	          }	tC          j"        |	          d	z
  }
tM          | |
|          S )aD	  Construct an array from repeated elements.

  JAX implementation of :func:`numpy.repeat`.

  Args:
    a: N-dimensional array
    repeats: 1D integer array specifying the number of repeats. Must match the
      length of the repeated axis.
    axis: integer specifying the axis of ``a`` along which to construct the
      repeated array. If None (default) then ``a`` is first flattened.
    total_repeat_length: this must be specified statically for ``jnp.repeat``
      to be compatible with :func:`~jax.jit` and other JAX transformations.
      If ``sum(repeats)`` is larger than the specified ``total_repeat_length``,
      the remaining values will be discarded. If ``sum(repeats)`` is smaller
      than ``total_repeat_length``, the final value will be repeated.

  Returns:
    an array constructed from repeated values of ``a``.

  See Also:
    - :func:`jax.numpy.tile`: repeat a full array rather than individual values.

  Examples:
    Repeat each value twice along the last axis:

    >>> a = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> jnp.repeat(a, 2, axis=-1)
    Array([[1, 1, 2, 2],
           [3, 3, 4, 4]], dtype=int32)

    If ``axis`` is not specified, the input array will be flattened:

    >>> jnp.repeat(a, 2)
    Array([1, 1, 2, 2, 3, 3, 4, 4], dtype=int32)

    Pass an array to ``repeats`` to repeat each value a different number of times:

    >>> repeats = jnp.array([2, 3])
    >>> jnp.repeat(a, repeats, axis=1)
    Array([[1, 1, 2, 2, 2],
           [3, 3, 4, 4, 4]], dtype=int32)

    In order to use ``repeat`` within ``jit`` and other JAX transformations, the
    size of the output must be specified statically using ``total_repeat_length``:

    >>> jit_repeat = jax.jit(jnp.repeat, static_argnames=['axis', 'total_repeat_length'])
    >>> jit_repeat(a, repeats, axis=1, total_repeat_length=5)
    Array([[1, 1, 2, 2, 2],
           [3, 3, 4, 4, 4]], dtype=int32)

    If `total_repeat_length` is smaller than ``sum(repeats)``, the result will be truncated:

    >>> jit_repeat(a, repeats, axis=1, total_repeat_length=4)
    Array([[1, 1, 2, 2],
           [3, 3, 4, 4]], dtype=int32)

    If it is larger, then the additional entries will be filled with the final value:

    >>> jit_repeat(a, repeats, axis=1, total_repeat_length=7)
    Array([[1, 1, 2, 2, 2, 2, 2],
           [3, 3, 4, 4, 4, 4, 4]], dtype=int32)
  rD  Nr   z'axis' argument of jnp.repeat()zhjnp.repeat with a non-constant `repeats` is supported only when `total_repeat_length` is None. (repeats=z total_repeat_length=)zWhen jit-compiling jnp.repeat, the total number of repeats must be static. To fix this, either specify a static value for `repeats`, or pass a static value to `total_repeat_length`.r   c                     g | ]
}|k    |S rj   rj   )r*  rD  aux_axiss     rK   r2  zrepeat.<locals>.<listcomp>^  s    IIIQ1==q===rL   r   zf`repeat` with a scalar parameter `a` is only implemented for scalar values of the parameter `repeats`.rn   )shiftrh  )'r*   r   r   r  r  rS   r   r   r   rF   r^   r  r   r}   rE   r?   rO  r   rH   r"  r  r   r  r   r=  r  r  r   r  r[   rollr  r  r(   r  r  r  r  take)r   r  rb  r  input_shape	aux_shaperesult_shapeexclusive_repeatsscatter_indicesblock_split_indicatorsgather_indicesr  s              @rK   rD  rD    s   B x###+gA$.xAA	\aADD

A		6W	X	X$	D#			'"" c& b?Fb bJ]b b b c c c  $T7() )G 
ww1aA!HHkc+&6&677dh!%k!2!2ixD<PQX<Y<Y!f!8!8!8_fggg

	9IIII%I"7"7IIIK Ka$($5$5l4G#Q%%%hwGAww!||%((4.)9::g&//GnnGAww!||WuQxx~&677g 
!WW\\W~~&'+++ B C C C Aa>>LL56!99---|<<< 1XXd^q1:: 7!,,,/266q99%&788/ "5!6eDDD14_EII!LL$%;<<q@.	ad	+	+	++rL   	trapezoidtrapzr  r  c                   |;t          j        d|            t          j        |           \  }t          |          }nit          j        d| |           t          j        | |          \  }}|j        dk    rt          |          }n t          t          ||          |d          }t          ||d          }d||ddd f         |dd df         z   z                      d          z  S )Nr  r   rh  r   r   .)r*   r   r   rS   rE   r  r  r  )r   rM   r  rb  y_arrdx_arrayrK  s          rK   r  r    s     Ya((((++FEr{{HHa+++.q!44LE5zQehh$u4000$;;h
5$
#
#%	E#qrr'NU38_<=BB2FF	FFrL   c                z    t          j        |d           ||n| }|pt          }t          j        || |f|          S )a	  Return an array with ones on and below the diagonal and zeros elsewhere.

  JAX implementation of :func:`numpy.tri`

  Args:
    N: int. Dimension of the rows of the returned array.
    M: optional, int. Dimension of the columns of the returned array. If not
      specified, then ``M = N``.
    k: optional, int, default=0. Specifies the sub-diagonal on and below which
      the array is filled with ones. ``k=0`` refers to main diagonal, ``k<0``
      refers to sub-diagonal below the main diagonal and ``k>0`` refers to
      sub-diagonal above the main diagonal.
    dtype: optional, data type of the returned array. The default type is float.

  Returns:
    An array of shape ``(N, M)`` containing the lower triangle with elements
    below the sub-diagonal specified by ``k`` are set to one and zero elsewhere.

  See also:
    - :func:`jax.numpy.tril`: Returns a lower triangle of an array.
    - :func:`jax.numpy.triu`: Returns an upper triangle of an array.

  Examples:
    >>> jnp.tri(3)
    Array([[1., 0., 0.],
           [1., 1., 0.],
           [1., 1., 1.]], dtype=float32)

    When ``M`` is not equal to ``N``:

    >>> jnp.tri(3, 4)
    Array([[1., 0., 0., 0.],
           [1., 1., 0., 0.],
           [1., 1., 1., 0.]], dtype=float32)

    when ``k>0``:

    >>> jnp.tri(3, k=1)
    Array([[1., 1., 0.],
           [1., 1., 1.],
           [1., 1., 1.]], dtype=float32)

    When ``k<0``:

    >>> jnp.tri(3, 4, k=-1)
    Array([[0., 0., 0., 0.],
           [1., 0., 0., 0.],
           [1., 1., 0., 0.]], dtype=float32)
  tri)r   r  r  r   _tri)r   ry  rX  rP   s       rK   r   r     sH    d 	#E5111=aaa!

7%		51a&!	,	,,rL   rX  c                T   t          j        d|            t          |           }t          |          dk     rt	          d          |dd         \  }}t          |||t                    }t          j        t          j	        ||dd                   | t          |                     S )ah  Return lower triangle of an array.

  JAX implementation of :func:`numpy.tril`

  Args:
    m: input array. Must have ``m.ndim >= 2``.
    k: k: optional, int, default=0. Specifies the sub-diagonal above which the
      elements of the array are set to zero. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.

  Returns:
    An array with same shape as input containing the upper triangle of the given
    array with elements below the sub-diagonal specified by ``k`` are set to zero.

  See also:
    - :func:`jax.numpy.triu`: Returns an upper triangle of an array.
    - :func:`jax.numpy.tri`: Returns an array with ones on and below the diagonal
      and zeros elsewhere.

  Examples:
    >>> x = jnp.array([[1, 2, 3, 4],
    ...                [5, 6, 7, 8],
    ...                [9, 10, 11, 12]])
    >>> jnp.tril(x)
    Array([[ 1,  0,  0,  0],
           [ 5,  6,  0,  0],
           [ 9, 10, 11,  0]], dtype=int32)
    >>> jnp.tril(x, k=1)
    Array([[ 1,  2,  0,  0],
           [ 5,  6,  7,  0],
           [ 9, 10, 11, 12]], dtype=int32)
    >>> jnp.tril(x, k=-1)
    Array([[ 0,  0,  0,  0],
           [ 5,  0,  0,  0],
           [ 9, 10,  0,  0]], dtype=int32)

    When ``m.ndim > 2``, ``jnp.tril`` operates batch-wise on the trailing axes.

    >>> x1 = jnp.array([[[1, 2],
    ...                  [3, 4]],
    ...                 [[5, 6],
    ...                  [7, 8]]])
    >>> jnp.tril(x1)
    Array([[[1, 0],
            [3, 4]],
    <BLANKLINE>
           [[5, 0],
            [7, 8]]], dtype=int32)
  trilr   z.Argument to jax.numpy.tril must be at least 2Dr  NrX  rP   r*   r   r?   r   r   r   rN   r   rq  r  r  rZ  rX  m_shaper   ry  r  s         rK   r  r    s    h vq!!!!HH'\\A
E
F
FF	$!Q	QQd	#	#	#$	CM$55q*Q--	H	HHrL   c                Z   t          j        d|            t          |           }t          |          dk     rt	          d          |dd         \  }}t          |||dz
  t                    }t          j        t          j	        ||dd                   t          |           |           S )a  Return upper triangle of an array.

  JAX implementation of :func:`numpy.triu`

  Args:
    m: input array. Must have ``m.ndim >= 2``.
    k: optional, int, default=0. Specifies the sub-diagonal below which the
      elements of the array are set to zero. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.

  Returns:
    An array with same shape as input containing the lower triangle of the given
    array with elements above the sub-diagonal specified by ``k`` are set to zero.

  See also:
    - :func:`jax.numpy.tril`: Returns a lower triangle of an array.
    - :func:`jax.numpy.tri`: Returns an array with ones on and below the diagonal
      and zeros elsewhere.

  Examples:
    >>> x = jnp.array([[1, 2, 3],
    ...                [4, 5, 6],
    ...                [7, 8, 9],
    ...                [10, 11, 12]])
    >>> jnp.triu(x)
    Array([[1, 2, 3],
           [0, 5, 6],
           [0, 0, 9],
           [0, 0, 0]], dtype=int32)
    >>> jnp.triu(x, k=1)
    Array([[0, 2, 3],
           [0, 0, 6],
           [0, 0, 0],
           [0, 0, 0]], dtype=int32)
    >>> jnp.triu(x, k=-1)
    Array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 0,  8,  9],
           [ 0,  0, 12]], dtype=int32)

    When ``m.ndim > 2``, ``jnp.triu`` operates batch-wise on the trailing axes.

    >>> x1 = jnp.array([[[1, 2],
    ...                  [3, 4]],
    ...                 [[5, 6],
    ...                  [7, 8]]])
    >>> jnp.triu(x1)
    Array([[[1, 2],
            [0, 4]],
    <BLANKLINE>
           [[5, 6],
            [0, 8]]], dtype=int32)
  triur   z.Argument to jax.numpy.triu must be at least 2Dr  Nr   r  r  r  s         rK   r
  r
    s    p vq!!!!HH'\\A
E
F
FF	$!Q	QQU$	'	'	'$	CM$55z!}}a	H	HHrL   )r  r  rP   c                j   t          j        d|            |t          d          t          j        |d           t          |           }t          | ||fd          } t          t          ||         ||         |t                    | t          |                     } t          j        | d|          S )Ntracez1The 'out' argument to jnp.trace is not supported.r  r   r  r  )r*   r   r   r   r  r?   r  r   r  rN   r  r(   r  )r   r=  r  r  rP   r   r  s          rK   r  r  X  s     w"""_
Q
R
RR#E7333!HH'q5%.(++! C&EEEz!}} !		6	6	66rL   c                J     t          j         d           fd            }|S )NFr   c                     fdt          |           D             } fd|                                D             }t          d  | i |D                       S )Nc                Z    g | ]'\  }}t          j        d |d| dj         d          (S )Nz	argument z of jnp.()r   r   rs   )r*  rD  argr  s      rK   r2  z;_wrap_indices_function.<locals>.wrapper.<locals>.<listcomp>m  sY     + + +3 "C>Q>>
>>>@ @ + + +rL   c                \    i | ](\  }}|t          j        d |d| dj         d          )S )Nz
argument 'z	' of jnp.r  r  )r*  keyr   r  s      rK   
<dictcomp>z;_wrap_indices_function.<locals>.wrapper.<locals>.<dictcomp>p  s[     . . .#s 4)cDDDajDDDF F . . .rL   c              3  4   K   | ]}t          |          V  d S r`   r  r  s     rK   r,  z:_wrap_indices_function.<locals>.wrapper.<locals>.<genexpr>s  s(      88888888rL   )r  itemsrG   )r   r   r  s     rK   wrapperz'_wrap_indices_function.<locals>.wrapperk  s    + + + +#D//+ + +D. . . .$llnn. . .F 88QQ%7%7%7888888rL   )r*   r  )r  r  s   ` rK   _wrap_indices_functionr  j  s=    ?1'''9 9 9 9 ('9 
.rL   c                    |dk     r| |z  t          || d|z
            z
  S ||k    rdS t          | ||z
            }||dz   z  dz  |||z
  |z
  z  z   S )Nr   r   r   )
_triu_sizer   )r  rZ  rX  mks       rK   r  r  y  sn    UUq5:aQU,,,,Avv1	QABa=Aa!ebj 111rL   c                T   t          j        t          j        | d          } t          j        t          j        |d          }|| nt          j        t          j        |d          }t	          t          t          | |f          |          t          | ||                    \  }}||fS )a  Return the indices of upper triangle of an array of size ``(n, m)``.

  JAX implementation of :func:`numpy.triu_indices`.

  Args:
    n: int. Number of rows of the array for which the indices are returned.
    k: optional, int, default=0. Specifies the sub-diagonal on and above which
      the indices of upper triangle are returned. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.
    m: optional, int. Number of columns of the array for which the indices are
      returned. If not specified, then ``m = n``.

  Returns:
    A tuple of two arrays containing the indices of the upper triangle, one along
    each axis.

  See also:
    - :func:`jax.numpy.tril_indices`: Returns the indices of lower triangle of an
      array of size ``(n, m)``.
    - :func:`jax.numpy.triu_indices_from`: Returns the indices of upper triangle
      of a given array.
    - :func:`jax.numpy.tril_indices_from`: Returns the indices of lower triangle
      of a given array.

  Examples:
    If only ``n`` is provided in input, the indices of upper triangle of an array
    of size ``(n, n)`` array are returned.

    >>> jnp.triu_indices(3)
    (Array([0, 0, 0, 1, 1, 2], dtype=int32), Array([0, 1, 2, 1, 2, 2], dtype=int32))

    If both ``n`` and ``m`` are provided in input, the indices of upper triangle
    of an ``(n, m)`` array are returned.

    >>> jnp.triu_indices(3, m=2)
    (Array([0, 0, 1], dtype=int32), Array([0, 1, 1], dtype=int32))

    If ``k = 1``, the indices on and above the first sub-diagonal above the main
    diagonal are returned.

    >>> jnp.triu_indices(3, k=1)
    (Array([0, 0, 1], dtype=int32), Array([1, 2, 2], dtype=int32))

    If ``k = -1``, the indices on and above the first sub-diagonal below the main
    diagonal are returned.

    >>> jnp.triu_indices(3, k=-1)
    (Array([0, 0, 0, 1, 1, 1, 2, 2], dtype=int32), Array([0, 1, 2, 0, 1, 2, 1, 2], dtype=int32))
  n argument of jnp.triu_indicesk argument of jnp.triu_indicesNm argument of jnp.triu_indicesr  r  )r   r   r   r   rd  r
  rN  r  r  rX  rZ  rD  r  s        rK   triu_indicesr$    s    f X^Q0PQQ!
X^Q0PQQ!9aa$0Ddee!	dAq6lla(((z!Q/B/B	C	C	C$!Q	
A+rL   c                V   t          j        t          j        | d          } t          j        t          j        |d          }|| nt          j        t          j        |d          }t	          t          t          | |f          |          t          || |                     \  }}||fS )a  Return the indices of lower triangle of an array of size ``(n, m)``.

  JAX implementation of :func:`numpy.tril_indices`.

  Args:
    n: int. Number of rows of the array for which the indices are returned.
    k: optional, int, default=0. Specifies the sub-diagonal on and below which
      the indices of lower triangle are returned. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.
    m: optional, int. Number of columns of the array for which the indices are
      returned. If not specified, then ``m = n``.

  Returns:
    A tuple of two arrays containing the indices of the lower triangle, one along
    each axis.

  See also:
    - :func:`jax.numpy.triu_indices`: Returns the indices of upper triangle of an
      array of size ``(n, m)``.
    - :func:`jax.numpy.triu_indices_from`: Returns the indices of upper triangle
      of a given array.
    - :func:`jax.numpy.tril_indices_from`: Returns the indices of lower triangle
      of a given array.

  Examples:
    If only ``n`` is provided in input, the indices of lower triangle of an array
    of size ``(n, n)`` array are returned.

    >>> jnp.tril_indices(3)
    (Array([0, 1, 1, 2, 2, 2], dtype=int32), Array([0, 0, 1, 0, 1, 2], dtype=int32))

    If both ``n`` and ``m`` are provided in input, the indices of lower triangle
    of an ``(n, m)`` array are returned.

    >>> jnp.tril_indices(3, m=2)
    (Array([0, 1, 1, 2, 2], dtype=int32), Array([0, 0, 1, 0, 1], dtype=int32))

    If ``k = 1``, the indices on and below the first sub-diagonal above the main
    diagonal are returned.

    >>> jnp.tril_indices(3, k=1)
    (Array([0, 0, 1, 1, 1, 2, 2, 2], dtype=int32), Array([0, 1, 0, 1, 2, 0, 1, 2], dtype=int32))

    If ``k = -1``, the indices on and below the first sub-diagonal below the main
    diagonal are returned.

    >>> jnp.tril_indices(3, k=-1)
    (Array([1, 2, 2], dtype=int32), Array([0, 0, 1], dtype=int32))
  r  r   Nr!  r  r"  )r   r   r   r   rd  r  rN  r  r#  s        rK   tril_indicesr&    s    f X^Q0PQQ!
X^Q0PQQ!9aa$0Ddee!	dAq6lla(((z!Q/C/C	D	D	D$!Q	
A+rL   c                    t          |           }t          |          dk    rt          d          t          |d         ||d                   S )a  Return the indices of upper triangle of a given array.

  JAX implementation of :func:`numpy.triu_indices_from`.

  Args:
    arr: input array. Must have ``arr.ndim == 2``.
    k: optional, int, default=0. Specifies the sub-diagonal on and above which
      the indices of upper triangle are returned. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.

  Returns:
    A tuple of two arrays containing the indices of the upper triangle, one along
    each axis.

  See also:
    - :func:`jax.numpy.tril_indices_from`: Returns the indices of lower triangle
      of a given array.
    - :func:`jax.numpy.triu_indices`: Returns the indices of upper triangle of an
      array of size ``(n, m)``.
    - :func:`jax.numpy.triu`: Return an upper triangle of an array.

  Examples:
    >>> arr = jnp.array([[1, 2, 3],
    ...                  [4, 5, 6],
    ...                  [7, 8, 9]])
    >>> jnp.triu_indices_from(arr)
    (Array([0, 0, 0, 1, 1, 2], dtype=int32), Array([0, 1, 2, 1, 2, 2], dtype=int32))

    Elements indexed by ``jnp.triu_indices_from`` correspond to those in the
    output of ``jnp.triu``.

    >>> ind = jnp.triu_indices_from(arr)
    >>> arr[ind]
    Array([1, 2, 3, 5, 6, 9], dtype=int32)
    >>> jnp.triu(arr)
    Array([[1, 2, 3],
           [0, 5, 6],
           [0, 0, 9]], dtype=int32)

    When ``k > 0``:

    >>> jnp.triu_indices_from(arr, k=1)
    (Array([0, 0, 1], dtype=int32), Array([1, 2, 2], dtype=int32))

    When ``k < 0``:

    >>> jnp.triu_indices_from(arr, k=-1)
    (Array([0, 0, 0, 1, 1, 1, 2, 2], dtype=int32), Array([0, 1, 2, 0, 1, 2, 1, 2], dtype=int32))
  r   Only 2-D inputs are acceptedr   r   rX  rZ  )r?   r   r   r$  r  rX  	arr_shapes      rK   triu_indices_fromr,    M    f Cjj)^^q
3
4
44	ila9Q<	8	8	88rL   c                    t          |           }t          |          dk    rt          d          t          |d         ||d                   S )a  Return the indices of lower triangle of a given array.

  JAX implementation of :func:`numpy.tril_indices_from`.

  Args:
    arr: input array. Must have ``arr.ndim == 2``.
    k: optional, int, default=0. Specifies the sub-diagonal on and below which
      the indices of upper triangle are returned. ``k=0`` refers to main diagonal,
      ``k<0`` refers to sub-diagonal below the main diagonal and ``k>0`` refers
      to sub-diagonal above the main diagonal.

  Returns:
    A tuple of two arrays containing the indices of the lower triangle, one along
    each axis.

  See also:
    - :func:`jax.numpy.triu_indices_from`: Returns the indices of upper triangle
      of a given array.
    - :func:`jax.numpy.tril_indices`: Returns the indices of lower triangle of an
      array of size ``(n, m)``.
    - :func:`jax.numpy.tril`: Returns a lower triangle of an array

  Examples:
    >>> arr = jnp.array([[1, 2, 3],
    ...                  [4, 5, 6],
    ...                  [7, 8, 9]])
    >>> jnp.tril_indices_from(arr)
    (Array([0, 1, 1, 2, 2, 2], dtype=int32), Array([0, 0, 1, 0, 1, 2], dtype=int32))

    Elements indexed by ``jnp.tril_indices_from`` correspond to those in the
    output of ``jnp.tril``.

    >>> ind = jnp.tril_indices_from(arr)
    >>> arr[ind]
    Array([1, 4, 5, 7, 8, 9], dtype=int32)
    >>> jnp.tril(arr)
    Array([[1, 0, 0],
           [4, 5, 0],
           [7, 8, 9]], dtype=int32)

    When ``k > 0``:

    >>> jnp.tril_indices_from(arr, k=1)
    (Array([0, 0, 1, 1, 1, 2, 2, 2], dtype=int32), Array([0, 1, 0, 1, 2, 0, 1, 2], dtype=int32))

    When ``k < 0``:

    >>> jnp.tril_indices_from(arr, k=-1)
    (Array([1, 2, 2], dtype=int32), Array([0, 0, 1], dtype=int32))
  r   r(  r   r   r)  )r?   r   r   r&  r*  s      rK   tril_indices_fromr/  0  r-  rL   )inplacer  r0  c               T    |rt          d          |rt          d          t          j        d |           t                      t          |          } j        dk     rt          d           j        dk    r7t           fd j        dd         D                       st          d	          t           j                  }t          | j                  } j
        |                             |j        d
k    r|n!t          |                                |                    S )a  Return a copy of the array with the diagonal overwritten.

  JAX implementation of :func:`numpy.fill_diagonal`.

  The semantics of :func:`numpy.fill_diagonal` are to modify arrays in-place, which
  is not possible for JAX's immutable arrays. The JAX version returns a modified
  copy of the input, and adds the ``inplace`` parameter which must be set to
  `False`` by the user as a reminder of this API difference.

  Args:
    a: input array. Must have ``a.ndim >= 2``. If ``a.ndim >= 3``, then all
      dimensions must be the same size.
    val: scalar or array with which to fill the diagonal. If an array, it will
      be flattened and repeated to fill the diagonal entries.
    inplace: must be set to False to indicate that the input is not modified
      in-place, but rather a modified copy is returned.

  Returns:
    A copy of ``a`` with the diagonal set to ``val``.

  Examples:
    >>> x = jnp.zeros((3, 3), dtype=int)
    >>> jnp.fill_diagonal(x, jnp.array([1, 2, 3]), inplace=False)
    Array([[1, 0, 0],
           [0, 2, 0],
           [0, 0, 3]], dtype=int32)

    Unlike :func:`numpy.fill_diagonal`, the input ``x`` is not modified.

    If the diagonal value has too many entries, it will be truncated

    >>> jnp.fill_diagonal(x, jnp.arange(100, 200), inplace=False)
    Array([[100,   0,   0],
           [  0, 101,   0],
           [  0,   0, 102]], dtype=int32)

    If the diagonal has too few entries, it will be repeated:

    >>> x = jnp.zeros((4, 4), dtype=int)
    >>> jnp.fill_diagonal(x, jnp.array([3, 4]), inplace=False)
    Array([[3, 0, 0, 0],
           [0, 4, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]], dtype=int32)

    For non-square arrays, the diagonal of the leading square slice is filled:

    >>> x = jnp.zeros((3, 5), dtype=int)
    >>> jnp.fill_diagonal(x, 1, inplace=False)
    Array([[1, 0, 0, 0, 0],
           [0, 1, 0, 0, 0],
           [0, 0, 1, 0, 0]], dtype=int32)

    And for square N-dimensional arrays, the N-dimensional diagonal is filled:

    >>> y = jnp.zeros((2, 2, 2))
    >>> jnp.fill_diagonal(y, 1, inplace=False)
    Array([[[1., 0.],
            [0., 0.]],
    <BLANKLINE>
           [[0., 0.],
            [0., 1.]]], dtype=float32)
  z0JAX arrays are immutable, must use inplace=Falsez1wrap=True is not implemented, must use wrap=Falsefill_diagonalr   zarray must be at least 2-dc              3  :   K   | ]}|j         d          k    V  dS r  r)  )r*  r  r   s     rK   r,  z fill_diagonal.<locals>.<genexpr>  s-      AAAOAAAAAArL   r   N/All dimensions of input must be of equal lengthr   )r   r*   r   rS   rE   r   r  r?   r   diag_indicesr  r  _tile_to_sizer  )r   r   r  r0  r  rp  s   `     rK   r2  r2  i  s   B  R
P
Q
QQ	 S
Q
R
RR3///ajj!#VaZZ
1
2
22VaZZAAAAQWQRR[AAAAAZ
F
G
GG	!'ll!Q#	
cch!mmsssyy{{A1N1N	O	OOrL   rE   c                ^   t          j        t          j        | d          } t          j        t          j        |d          }| dk     r"t	          d                    |                     |dk     r"t	          d                    |                    t          j        t          |           f|z  S )Nz"'n' argument of jnp.diag_indices()z%'ndim' argument of jnp.diag_indices()r   z6n argument to diag_indices must be nonnegative, got {}z9ndim argument to diag_indices must be nonnegative, got {})	r   r   r   r   r   r   r   r  r  )r  rE   s     rK   r5  r5    s    
X^Q0TUU!		6]	^	^$UU
MfQii! ! !	AXX
PfTll$ $ $
(4

		$$rL   c                R   t          j        d|            t          |           }t          |           dk    st          d          t	          |           }t          t          t	          |                               dk    rt          d          t          |d         |          S )Ndiag_indices_fromr   z input array must be at least 2-dr   r4  r   r  )r*   r   rE   r   r?   r   r  r5  )r  r  r  s      rK   r9  r9    s    *C000Cyy"	ca
7
8
88Cjj!U3ZZQ
F
G
GG	ad	$	$	$$rL   )r=  r  r  c                <   t          j        d|            t          |           }t          |           dk     rt	          d          t          j        t          j        |d          }t          | ||fd          } t          dt          ||         t          |d          z   ||         t          |d          z
                      }t          |          }t          t          |          t          |          |z             }|dk    r| d||f         n
| d||f         S )Ndiagonalr   z6diagonal requires an array of at least two dimensions.z#'offset' argument of jnp.diagonal()r  r   .)r*   r   r?   rE   r   r   r   r   r   r  r   r   r  r0  )r   r=  r  r  r  	diag_sizerD  r  s           rK   r;  r;    s    z1%%%!HH'	!WWq[[
M
N
NN!(.&:_``&q5%.(++!!S#fa..8 #fa..8: : ; ;)Y!S[[#f++	122!1319!CAI,6rL   c                F    t          | t          j        |                    S r`   )_diagr   r   )r   rX  s     rK   diagr?    s    	q(.##	$	$$rL   c           	        t          j        d|            t          |           }t          |          dk    rd }|d         t	          |          z   }t          j        |  ||           t          d|          t          d|           dff          } t          t          ||t                    | t          |                     S t          |          dk    rt          | |          S t          d          )	Nr?  r   c                0    t          j        | dd          S )Nrj   r   )r?   rZ  )r   r?  rZ   s    rK   r  z_diag.<locals>.<lambda>  s    S]1B1=== rL   r   r  r   )r=  zdiag input must be 1d or 2d)r*   r   r?   r   r0  r   r"  r   r   r  rN   r  r;  r   )r   rX  v_shaper  r  s        rK   r>  r>    s    vq!!!!HH'\\Q==D
SVVA4477c!QiiQQ79::AQ!4(((!Z]];;;
7||qAa    
2
3
33rL   zThis differs from np.diagflat for some scalar values of v,
jax always returns a two-dimensional array, whereas numpy may
return a scalar depending on the type of v.
c                   t          j        d|            t          |           }t          |          }|t	          |          z   }t          ||z  |j                  }t          d|t	          |          z
            }|dk    r||z   ||z  z   }n|||z
  |z  z   }|j        |         	                    |          }|
                    ||          }|S )Ndiagflatrn   r   )r*   r   r  r   r0  r  rP   r  r  r  r=  )r   rX  v_ravelv_length
adj_lengthr  rD  fis           rK   rD  rD    s    z1%%%!HH'\\(#a&& *j#7=999#Q
3q66!""!1ff	
1Qz\	BB	
AaC	Br
w#J
++#	*rL   fbc                   t          j        t          | d          } | dk    }t          j        |          rt          dt          |                     S d|                                v rt          |          nd}d|                                v rt          |d d d                   nd}| |t          |           |z
           S )Nz2Error arose in the `filt` argument of trim_zeros()r   r  r  r   )
r   r   rS   r(   r  rw  r[   lowerargminr   )filttrimnzr  r  s        rK   
trim_zerosrP    s    		8
: 
:$	"^B "F4LL!!!tzz||++&***%4::<<//r$$B$xQ#	eCIIO#	$$rL   c                   t          j        t          | d          } t          j        |           |k     }t          j        |          rt          dt          |                     S d|	                                v rt          |          nd}d|	                                v rt          |d d d                   nd}| |t          |           |z
           S )Nz6Error arose in the `filt` argument of trim_zeros_tol()r   r  r  r   )r   r   rS   r)   r0  r(   r  rw  r[   rK  rL  r   )rM  tolrN  rO  r  r  s         rK   trim_zeros_tolrS    s    		<
> 
>$
43"^B "F4LL!!!tzz||++&***%4::<<//r$$B$xQ#	eCIIO#	$$rL   valuesc                    |,t          t          |           t          |          gd          S t          | |g|          S )a  Return a new array with values appended to the end of the original array.

  JAX implementation of :func:`numpy.append`.

  Args:
    arr: original array.
    values: values to be appended to the array. The ``values`` must have
      the same number of dimensions as ``arr``, and all dimensions must
      match except in the specified axis.
    axis: axis along which to append values. If None (default), both ``arr``
      and ``values`` will be flattened before appending.

  Returns:
    A new array with values appended to ``arr``.

  See also:
    - :func:`jax.numpy.insert`
    - :func:`jax.numpy.delete`

  Examples:
    >>> a = jnp.array([1, 2, 3])
    >>> b = jnp.array([4, 5, 6])
    >>> jnp.append(a, b)
    Array([1, 2, 3, 4, 5, 6], dtype=int32)

    Appending along a specific axis:

    >>> a = jnp.array([[1, 2],
    ...                [3, 4]])
    >>> b = jnp.array([[5, 6]])
    >>> jnp.append(a, b, axis=0)
    Array([[1, 2],
           [3, 4],
           [5, 6]], dtype=int32)

    Appending along a trailing axis:

    >>> a = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> b = jnp.array([[7], [8]])
    >>> jnp.append(a, b, axis=1)
    Array([[1, 2, 3, 7],
           [4, 5, 6, 8]], dtype=int32)
  Nr   rh  )r  r  )r  rT  rb  s      rK   r8  r8  %  sB    ` 
\c

E&MM2A666V}40000rL   )assume_unique_indicesArrayLike | slicerV  c          	        t          j        d|            |t          |           } d}t          |           }t	          ||j                  }	 t          j        |          }t	          ||j        |                   }t          d t          |          D                       }t          ||t          d|          fz            ||t          |dz   d          fz            g|          S # t          $ r Y nw xY wt          |t                    r"t          |j        |                   |         }d}t          j        d||           t!          t#          |          t$                    r|rt          |                                          }t'          t)          |dk     ||j        |         z   |          d|j        |                   }t+          |          }|t          t-          |                    z  }t          |j        |         |j        z
            }||dddf         |dddf         k                        d          z  }|t          d          f|z  |fz            S t3          j        t6          j        |d          }t!          |j        t$                    r,t7          j        |j        |         t<          	          }d
||<   nR|j        t<          k    r*|j        |j        |         fk    rt?          d          | }nt?          d|j         d          |t          d t          |          D                       |fz            S )a  Delete entry or entries from an array.

  JAX implementation of :func:`numpy.delete`.

  Args:
    arr: array from which entries will be deleted.
    obj: index, indices, or slice to be deleted.
    axis: axis along which entries will be deleted.
    assume_unique_indices: In case of array-like integer (not boolean) indices,
      assume the indices are unique, and perform the deletion in a way that is
      compatible with JIT and other JAX transformations.

  Returns:
    Copy of ``arr`` with specified indices deleted.

  Note:
    ``delete()`` usually requires the index specification to be static. If the
    index is an integer array that is guaranteed to contain unique entries, you
    may specify ``assume_unique_indices=True`` to perform the operation in a
    manner that does not require static indices.

  Examples:
    Delete entries from a 1D array:

    >>> a = jnp.array([4, 5, 6, 7, 8, 9])
    >>> jnp.delete(a, 2)
    Array([4, 5, 7, 8, 9], dtype=int32)
    >>> jnp.delete(a, slice(1, 4))  # delete a[1:4]
    Array([4, 8, 9], dtype=int32)
    >>> jnp.delete(a, slice(None, None, 2))  # delete a[::2]
    Array([5, 7, 9], dtype=int32)

    Delete entries from a 2D array along a specified axis:

    >>> a2 = jnp.array([[4, 5, 6],
    ...                 [7, 8, 9]])
    >>> jnp.delete(a2, 1, axis=1)
    Array([[4, 6],
           [7, 9]], dtype=int32)

    Delete multiple entries via a sequence of indices:

    >>> indices = jnp.array([0, 1, 3])
    >>> jnp.delete(a, indices)
    Array([6, 8, 9], dtype=int32)

    This will fail under :func:`~jax.jit` and other transformations, because
    the output shape cannot be known with the possibility of duplicate indices:

    >>> jax.jit(jnp.delete)(a, indices)  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected: traced array with shape int32[3].

    If you can ensure that the indices are unique, pass ``assume_unique_indices``
    to allow this to be executed under JIT:

    >>> jit_delete = jax.jit(jnp.delete, static_argnames=['assume_unique_indices'])
    >>> jit_delete(a, indices, assume_unique_indices=True)
    Array([6, 8, 9], dtype=int32)
  deleteNr   c              3  4   K   | ]}t          d           V  d S r`   r   r  s     rK   r,  zdelete.<locals>.<genexpr>  s(      11d111111rL   r   rh  Tz$'obj' array argument of jnp.delete()rn   Fzjnp.delete(arr, obj): for boolean indices, obj must be one-dimensional with length matching specified axis.z#np.delete(arr, obj): got obj.dtype=z; must be integer or bool.c              3  4   K   | ]}t          d           V  d S r`   r[  r  s     rK   r,  zdelete.<locals>.<genexpr>  s(      22t222222rL   ) r*   r   r  rS   rO  rE   r   r   r?   rG   r   r  r   rx   rF   r  rT   r[   r   r   r   sortr   r  r  r   r   r}   rP   rN  rN   r   )	r  r   rb  rV  r   rp  rD  	obj_arrayr  s	            rK   rY  rY  [  s*   H x%%%	\
**CDcll!	D!&	)	)$a
.

C
S!'$-
0
0C 11U4[[111
1
1C#q# 0011SE#'4<P<P;R5R3ST[_````	 
 	 	 	D	 U !



$C  xC((( sW%% +*? +
#,,



C
uS1WcAGDM1377AGDM
J
JC
s))C6#c((Cqwt}sx'((A!D!!!G*AAAtG
$	)	)!	,	,,AeDkk^d"aT)** $RZ6\]])	)) h 7174=---DDOO$174=*** > ? ? ?:DD
f9?fff
g
gg	
522eDkk22222dW<	==s   /C) )
C65C6c                   t          j        d| t          |t                    rdn||           t	          |           }t	          |          }|t          |          }d}t          j        d |d          }t          ||j	                  }t          |t                    r(t          |                    |j        |                    }nt	          |          }|j	        dk    rt          d|           t          j        |j        t          j                  sM|j        dk    r0t          |t&                    s|                    t*                    }nt          d|           t-          ||j	        |j        d          }|j        dk    rLt          |          d         }|j	        dk    rt/          |d|          }t1          |j        |         |          }|j        |         }t3          |j        |j        |         f          d         }	t5          |j                  }
|
|xx         |	z  cc<   t7          |t9          |
          	          }t;          |dk     ||z   |          }t=          |d|          }|j        tA          |                   !                    t          |	|j        
                    }tE          ||	z   tF          
          j        |         $                    d          }t;          ||          d         }|j        t          d           f|z  |fz            $                    |          }|j        t          d           f|z  |fz            $                    |          }|S )Nr"  r   zaxis argument of jnp.insert()r   zMjnp.insert(): obj must be a slice, a one-dimensional array, or a scalar; got z5jnp.insert(): index array must be integer typed; got F)r  rP   r   r)  rn   r"  )%r*   r   rF   r   rS   r  r   r   rO  rE   r  r  r?   r   r}   rT   rP   r   r  r,   r   r^   r  r  r   rx  rH   r  rG   r   r   r  argsortr  rN  rN   r  )r  r   rT  rb  r   
values_arrr  r   n_inputn_insert	out_shaper   
values_indarr_maskarr_inds                  rK   r"  r"    s.    x:c5+A+A&JaasFSSScll!v*	\aAD		d,K	L	L$	D!&	)	)$U ckk!'$-001GGcllG\A
 6036 6 7 7 7	w}bj	1	1 4|qC!7!7s##gg  3-03 3 4 4 4ZqvQW5III*\Q'NN1E|qJ400j:#D)511GGDM'gmj.>t.D-FGGJ(17mm)D///X///1E),,---#'A+w0'::'!W%%'z''**+//xw}0U0U0UVV*'H$D1114Z@DDUKK(()))!,'d~$
}4599*EE#d~$z1266q99#	*rL   func1dr   c                @    t          j        d|           t          |          }t          ||          } fd}t	          d||z
            D ]}t          j        ||d          }t	          |          D ]}t          j        |dd          } ||          S )Nrj  c                     | gR i S r`   rj   )r  r   rh  r   s    rK   r  z"apply_along_axis.<locals>.<lambda>  s!    VVC1$111&11 rL   r   r   )rq  out_axesr   )r*   r   rE   rO  r   r  r  )rh  rb  r  r   r   num_dimsrg  rD  s   `  ``   rK   rj  rj  	  s     )3///#YY(	D(	+	+$	1	1	1	1	1	1$HtO$$ 2 2a8D!b111DD;; 1 1a8D!a000DD	crL   !Callable[[ArrayLike, int], Array]c                    t          j        d|           t          |          }|D ]S} | ||          }|j        |j        k    r|}!|j        |j        dz
  k    rt	          ||          }Et          d          |S )Napply_over_axesr   z7function is not returning an array of the correct shape)r*   r   rS   rE   r  r   )rg  r   rJ  a_arrrb  r  s         rK   ro  ro    s     (!,,,
!**% R RdUDAvee	
5:>	!	!!T""eePQQQ	,rL   c               F   t          j        d| |           t          j        |d           t	          |           t	          |          }} |t          j        | |d          \  }}nd}d}t          |           t          |          }}|dk    s|dk    rB|*|                     |          } |                    |          }t          j	        | |          }n6|dk    r	|dz
  fd	f}	n|dz
  f|d
z
  ff}	t          j
        | ||	|f||          }t          j        |||          S )a		  Compute the dot product of two arrays.

  JAX implementation of :func:`numpy.dot`.

  This differs from :func:`jax.numpy.matmul` in two respects:

  - if either ``a`` or ``b`` is a scalar, the result of ``dot`` is equivalent to
    :func:`jax.numpy.multiply`, while the result of ``matmul`` is an error.
  - if ``a`` and ``b`` have more than 2 dimensions, the batch indices are
    stacked rather than broadcast.

  Args:
    a: first input array, of shape ``(..., N)``.
    b: second input array. Must have shape ``(N,)`` or ``(..., N, M)``.
      In the multi-dimensional case, leading dimensions must be broadcast-compatible
      with the leading dimensions of ``a``.
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    array containing the dot product of the inputs, with batch dimensions of
    ``a`` and ``b`` stacked rather than broadcast.

  See also:
    - :func:`jax.numpy.matmul`: broadcasted batched matmul.
    - :func:`jax.lax.dot_general`: general batched matrix multiplication.

  Examples:
    For scalar inputs, ``dot`` computes the element-wise product:

    >>> x = jnp.array([1, 2, 3])
    >>> jnp.dot(x, 2)
    Array([2, 4, 6], dtype=int32)

    For vector or matrix inputs, ``dot`` computes the vector or matrix product:

    >>> M = jnp.array([[2, 3, 4],
    ...                [5, 6, 7],
    ...                [8, 9, 0]])
    >>> jnp.dot(M, x)
    Array([20, 38, 26], dtype=int32)
    >>> jnp.dot(M, M)
    Array([[ 51,  60,  29],
           [ 96, 114,  62],
           [ 61,  78,  95]], dtype=int32)

    For higher-dimensional matrix products, batch dimensions are stacked, whereas
    in :func:`~jax.numpy.matmul` they are broadcast. For example:

    >>> a = jnp.zeros((3, 2, 4))
    >>> b = jnp.zeros((3, 4, 1))
    >>> jnp.dot(a, b).shape
    (3, 2, 3, 1)
    >>> jnp.matmul(a, b).shape
    (3, 2, 1)
  dotNTreturn_weak_type_flagFrj   rj   r   r   r~  r   )dimension_numbersr   r   )r*   r   r   r  rS   r   rE   r   r   r1  dot_generalr   r   )
r   r  r   r   output_weak_type
batch_dimsa_ndimb_ndimr   contract_dimss
             rK   rr  rr  *  sK   B ua####$:EBBB	WQZZQ!#/5/A!Q^b/c/c/c,,,*77DGG&&q[[FaKK )
(()
*
*a
(()
*
*aWQ]]FF{{
}d+mm
}vzm4m_QmZ5P'0I_a a aF		+F4JL\	]	]]rL   c          	     	   t          j        d| |           t          j        |d           t	          |           t	          |          }} t          | |f          D ]<\  }}t          |          dk     r$d| dt          |           }t          |          =|t          j        | |d          \  }}nd}t          |           dk    t          |          dk    }	}|rt          |           dd	         nd
}
|	rt          |          dd	         nd
}t          t          |
          t          |                    }d|t          |
          z
  z  |
z   }
d|t          |          z
  z  |z   }g }g }g }g }g }g }g }t          t          |
|                    D ]\  }\  }}||                    |           !||                    |           9t          j        |d          rX|                    |           |                    t          |          t          |          z   t          |          z              t          j        |d          rY|                    |           |                    t          |          t          |          z   t          |          z              t          j        ||          r{|                    t          |          t          |          z              |                    t          |          t          |          z              |                    |           t          d                    t          |           t          |                              |r|                    |           |	r|                    ||z              t#          j        t#          j        |||g                    }t)          j        | t-          |                    } t)          j        |t-          |                    }t)          j        | |t          |           dz
  ft          |          dz
  |	z
  ff||ff||          }t)          j        ||          }t3          j        |||          S )ag  Perform a matrix multiplication.

  JAX implementation of :func:`numpy.matmul`.

  Args:
    a: first input array, of shape ``(..., N)``.
    b: second input array. Must have shape ``(N,)`` or ``(..., N, M)``.
      In the multi-dimensional case, leading dimensions must be broadcast-compatible
      with the leading dimensions of ``a``.
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    array containing the matrix product of the inputs. Shape is ``a.shape[:-1]``
    if ``b.ndim == 1``, otherwise the shape is ``(..., M)``, where leading
    dimensions of ``a`` and ``b`` are broadcast together.

  See Also:
    - :func:`jax.numpy.linalg.vecdot`: batched vector product.
    - :func:`jax.numpy.linalg.tensordot`: batched tensor product.
    - :func:`jax.lax.dot_general`: general N-dimensional batched dot product.

  Examples:
    Vector dot products:

    >>> a = jnp.array([1, 2, 3])
    >>> b = jnp.array([4, 5, 6])
    >>> jnp.matmul(a, b)
    Array(32, dtype=int32)

    Matrix dot product:

    >>> a = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> b = jnp.array([[1, 2],
    ...                [3, 4],
    ...                [5, 6]])
    >>> jnp.matmul(a, b)
    Array([[22, 28],
           [49, 64]], dtype=int32)

    For convenience, in all cases you can do the same computation using
    the ``@`` operator:

    >>> a @ b
    Array([[22, 28],
           [49, 64]], dtype=int32)
  matmulr   zmatmul input operand z, must have ndim at least 1, but it has ndim NTrs  Fr  rj   r`   z3Incompatible shapes for matmul arguments: {} and {}r   )r*   r   r   r  rS   r  rE   r   r   r?   r   r   r  r8  r   definitely_equalr   r}   r`  r  r   r  rG   rw  r  r   r   )r   r  r   r   rD  rM   rn  rx  a_is_matb_is_mata_batch_dimsb_batch_dimsnum_batch_dims	a_squeeze	b_squeezea_batchb_batch	idx_batchidx_a_otheridx_b_otherbabbra  r   r   s                            rK   r~  r~    sx   t xA&&&#$:HEEE	WQZZQ!A  daAww{{*Q * * $Q* *csOO  #/5/A!Q^b/c/c/c,,,Q!tAww{H(:B)Jq#2#,:B)Jq#2#,s<((#l*;*;<<.NS->->>?,N,NS->->>?,N, )) '' )++s<>>?? 4 4ka"b	z			r1	%	% 4s9~~K(8(883y>>IJJJJ		r1	%	% 	4s9~~K(8(883y>>IJJJJ		r2	&	& 4nnS^^c+&6&66777nnS^^c+&6&66777qLuQxxq224 4 4 1{!!.111<{!!.8";<<<	BNI{K#HII	J	J$	k!U9%%&&!	k!U9%%&&!qT!WWq[NT!WWq[8356'8J
K0F	H 	H 	H# =d##&		+F4JL\	]	]]rL   c                   t          j        d| |           t          t          |           t                    rt          j        |           } t          t          |           t          |          ||          S )a  Perform a conjugate multiplication of two 1D vectors.

  JAX implementation of :func:`numpy.vdot`.

  Args:
    a: first input array, if not 1D it will be flattened.
    b: second input array, if not 1D it will be flattened. Must have ``a.size == b.size``.
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    Scalar array (shape ``()``) containing the conjugate vector product of the inputs.

  See Also:
    - :func:`jax.numpy.vecdot`: batched vector product.
    - :func:`jax.numpy.matmul`: general matrix multiplication.
    - :func:`jax.lax.dot_general`: general N-dimensional batched dot product.

  Examples:
    >>> x = jnp.array([1j, 2j, 3j])
    >>> y = jnp.array([1., 2., 3.])
    >>> jnp.vdot(x, y)
    Array(0.-14.j, dtype=complex64)

    Note the difference between this and :func:`~jax.numpy.dot`, which does not
    conjugate the first input when complex:

    >>> jnp.dot(x, y)
    Array(0.+14.j, dtype=complex64)
  vdotr   )	r*   r   rT   r[   rU   r)   r   rr  r  r   r  r   r   s       rK   r  r    sk    R vq!$$$q		?++ AA	U1XXuQxx9$:
< 
< 
< <rL   )rb  r   r   c                 t          j        d| |           t          |           t          |          }}|j        |         |j        |         k    r"t	          d|j         d|j         d|          t
          j                            ||d          }t
          j                            ||d          } t          t          t          ||          d          ||          S )	a  Perform a conjugate multiplication of two batched vectors.

  JAX implementation of :func:`numpy.vecdot`.

  Args:
    a: left-hand side array.
    b: right-hand side array. Size of ``b[axis]`` must match size of ``a[axis]``,
      and remaining dimensions must be broadcast-compatible.
    axis: axis along which to compute the dot product (default: -1)
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    array containing the conjugate dot product of ``a`` and ``b`` along ``axis``.
    The non-contracted dimensions are broadcast together.

  See Also:
    - :func:`jax.numpy.vdot`: flattened vector product.
    - :func:`jax.numpy.matmul`: general matrix multiplication.
    - :func:`jax.lax.dot_general`: general N-dimensional batched dot product.

  Examples:
    Vector conjugate-dot product of two 1D arrays:

    >>> a = jnp.array([1j, 2j, 3j])
    >>> b = jnp.array([4., 5., 6.])
    >>> jnp.linalg.vecdot(a, b)
    Array(0.-32.j, dtype=complex64)

    Batched vector dot product of two 2D arrays:

    >>> a = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> b = jnp.array([[2, 3, 4]])
    >>> jnp.linalg.vecdot(a, b, axis=-1)
    Array([20, 47], dtype=int32)
  z
jnp.vecdotzaxes must match; got shapes r   z with axis=r   r   z(n),(n)->())	signature)r*   r   rS   r?   r   r  r   r  r+   r   r  )r   r   rb  r   r   x1_arrx2_arrs          rK   vecdotr  1  s    Z |R,,,2;;&&\$6<---
bFLbbv|bb[_bb
c
cc9fdB//&9fdB//&
,749Mcddd*
, 
, 
,,2F
< 
< <rL   -int | Sequence[int] | Sequence[Sequence[int]]c                  t          j        d| |           t          j        |d           t	          |           t	          |          }} t          |           t          |          |t          j        | |d          \  }}nd}t          |          t          u r|t                    k    r0d}t          |                    || j        |j                            t          t          |z
                      t          t          |                    f}nrt          |t          t           f          rDt#          |          dk    r0|\  }}	t          |          t          |	          cxk    rt          k    r&n n#t%          |          ft%          |	          ff}nt          |t          t           f          rt          |	t          t           f          r|t#          |          t#          |	          k    r%d}t          |                    ||	                    t          fd	|D                       t          fd
|	D                       f}n6d}t          |                    ||	                    d}t          |          t'          j        | ||df||          }
t+          j        |
||          S )aO
  Compute the tensor dot product of two N-dimensional arrays.

  JAX implementation of :func:`numpy.linalg.tensordot`.

  Args:
    a: N-dimensional array
    b: M-dimensional array
    axes: integer or tuple of sequences of integers. If an integer `k`, then
      sum over the last `k` axes of ``a`` and the first `k` axes of ``b``,
      in order. If a tuple, then ``axes[0]`` specifies the axes of ``a`` and
      ``axes[1]`` specifies the axes of ``b``.
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    array containing the tensor dot product of the inputs

  See also:
    - :func:`jax.numpy.einsum`: NumPy API for more general tensor contractions.
    - :func:`jax.lax.dot_general`: XLA API for more general tensor contractions.

  Examples:
    >>> x1 = jnp.arange(24.).reshape(2, 3, 4)
    >>> x2 = jnp.ones((3, 4, 5))
    >>> jnp.tensordot(x1, x2)
    Array([[ 66.,  66.,  66.,  66.,  66.],
           [210., 210., 210., 210., 210.]], dtype=float32)

    Equivalent result when specifying the axes as explicit sequences:

    >>> jnp.tensordot(x1, x2, axes=([1, 2], [0, 1]))
    Array([[ 66.,  66.,  66.,  66.,  66.],
           [210., 210., 210., 210., 210.]], dtype=float32)

    Equivalent result via :func:`~jax.numpy.einsum`:

    >>> jnp.einsum('ijk,jkm->im', x1, x2)
    Array([[ 66.,  66.,  66.,  66.,  66.],
           [210., 210., 210., 210., 210.]], dtype=float32)

    Setting ``axes=1`` for two-dimensional inputs is equivalent to a matrix
    multiplication:

    >>> x1 = jnp.array([[1, 2],
    ...                 [3, 4]])
    >>> x2 = jnp.array([[1, 2, 3],
    ...                 [4, 5, 6]])
    >>> jnp.linalg.tensordot(x1, x2, axes=1)
    Array([[ 9, 12, 15],
           [19, 26, 33]], dtype=int32)
    >>> x1 @ x2
    Array([[ 9, 12, 15],
           [19, 26, 33]], dtype=int32)

    Setting ``axes=0`` for one-dimensional inputs is equivalent to
    :func:`~jax.numpy.outer`:

    >>> x1 = jnp.array([1, 2])
    >>> x2 = jnp.array([1, 2, 3])
    >>> jnp.linalg.tensordot(x1, x2, axes=0)
    Array([[1, 2, 3],
           [2, 4, 6]], dtype=int32)
    >>> jnp.outer(x1, x2)
    Array([[1, 2, 3],
           [2, 4, 6]], dtype=int32)
  	tensordotNTrs  FzBNumber of tensordot axes (axes {}) exceeds input ranks ({} and {})r   zBtensordot requires axes lists to have equal length, got {} and {}.c              3  8   K   | ]}t          |          V  d S r`   rO  )r*  rD  rz  s     rK   r,  ztensordot.<locals>.<genexpr>  .      KK! 21f = =KKKKKKrL   c              3  8   K   | ]}t          |          V  d S r`   r  )r*  rD  r{  s     rK   r,  ztensordot.<locals>.<genexpr>  r  rL   zTtensordot requires both axes lists to be either ints, tuples or lists, got {} and {}zZtensordot axes argument must be an int, a pair of ints, or a pair of lists/tuples of ints.ru  r   )r*   r   r   r  rS   rE   r   rQ   r^   r   rx   r   r?   rG   r   rF   rH   r   rO  r   rw  r   r   )r   r  rJ  r   r   rx  rn  contracting_dimsr_  r`  r   rz  r{  s              @@rK   r  r  h  s   V {Aq)))#$:KHHH	WQZZQ!77&77&#/5/A!Q^b/c/c/c,,,	$ZZ3c&&!!!!Pccjjqw88999U6D=&99::E%++<N<NN$&& 3t99>>HCCyyDII$$$$$$$$$-c6::<-c6::<>	C%	'	' 	,JsUDM,J,J 	,	SSXX		R

3,,---KKKKsKKKKKKKKKsKKKKKM$ccjjc**+++&C
C..?1a"2H!=%.G]_ _ _&		+F4JL\	]	]]rL   c                      e Zd ZdZd ZdS )UnoptimizedzUnoptimized path for einsum.c                .    dgt          |          dz
  z  S )NrY  r   r/  )rb   inputsr   r   s       rK   ro   zUnoptimized.__call__  s    8s6{{Q''rL   N)rs   rt   ru   __doc__ro   rj   rL   rK   r  r    s)        $$( ( ( ( (rL   r  optimal)r   optimizer   r   _dot_general	subscriptoperandsr  "str | bool | list[tuple[int, ...]]r  c                  d S r`   rj   )r  r   r  r   r   r  r  s          rK   einsumr    s	     CrL   Sequence[Any]ArrayLike | Sequence[Any]c                  d S r`   rj   )r  rJ  r   r  r   r   r  r  s           rK   r  r    s	     CrL   c              $   | g|R }|t          d          t          |d         t                    r|d         nd}|du rdn|du rt                      n|}d |D             }	|	st          j        }
n<t          t          |	                    }t          	                    |t                    }
 |
|dd|d\  }}t          d	 |D                       }t          t          d
d          }|t          j        ||          } ||||||          S )aY  Einstein summation

  JAX implementation of :func:`numpy.einsum`.

  ``einsum`` is a powerful and generic API for computing various reductions,
  inner products, outer products, axis reorderings, and combinations thereof
  across one or more input arrays. It has a somewhat complicated overloaded API;
  the arguments below reflect the most common calling convention. The Examples
  section below demonstrates some of the alternative calling conventions.

  Args:
    subscripts: string containing axes names separated by commas.
    *operands: sequence of one or more arrays corresponding to the subscripts.
    optimize: specify how to optimize the order of computation. In JAX this defaults
      to ``"optimal"`` which produces optimized expressions via the opt_einsum_
      package. Other options are ``True`` (same as ``"optimal"``), ``False``
      (unoptimized), or any string supported by ``opt_einsum``, which
      includes ``"auto"``, ``"greedy"``, ``"eager"``, and others. It may also
      be a pre-computed path (see :func:`~jax.numpy.einsum_path`).
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``).
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.
    out: unsupported by JAX
    _dot_general: optionally override the ``dot_general`` callable used by ``einsum``.
      This parameter is experimental, and may be removed without warning at any time.

  Returns:
    array containing the result of the einstein summation.

  See also:
    :func:`jax.numpy.einsum_path`

  Examples:
    The mechanics of ``einsum`` are perhaps best demonstrated by example. Here we
    show how to use ``einsum`` to compute a number of quantities from one or more
    arrays. For more discussion and examples of ``einsum``, see the documentation
    of :func:`numpy.einsum`.

    >>> M = jnp.arange(16).reshape(4, 4)
    >>> x = jnp.arange(4)
    >>> y = jnp.array([5, 4, 3, 2])

    **Vector product**

    >>> jnp.einsum('i,i', x, y)
    Array(16, dtype=int32)
    >>> jnp.vecdot(x, y)
    Array(16, dtype=int32)

    Here are some alternative ``einsum`` calling conventions to compute the same
    result:

    >>> jnp.einsum('i,i->', x, y)  # explicit form
    Array(16, dtype=int32)
    >>> jnp.einsum(x, (0,), y, (0,))  # implicit form via indices
    Array(16, dtype=int32)
    >>> jnp.einsum(x, (0,), y, (0,), ())  # explicit form via indices
    Array(16, dtype=int32)

    **Matrix product**

    >>> jnp.einsum('ij,j->i', M, x)  # explicit form
    Array([14, 38, 62, 86], dtype=int32)
    >>> jnp.matmul(M, x)
    Array([14, 38, 62, 86], dtype=int32)

    Here are some alternative ``einsum`` calling conventions to compute the same
    result:

    >>> jnp.einsum('ij,j', M, x) # implicit form
    Array([14, 38, 62, 86], dtype=int32)
    >>> jnp.einsum(M, (0, 1), x, (1,), (0,)) # explicit form via indices
    Array([14, 38, 62, 86], dtype=int32)
    >>> jnp.einsum(M, (0, 1), x, (1,))  # implicit form via indices
    Array([14, 38, 62, 86], dtype=int32)

    **Outer product**

    >>> jnp.einsum("i,j->ij", x, y)
    Array([[ 0,  0,  0,  0],
           [ 5,  4,  3,  2],
           [10,  8,  6,  4],
           [15, 12,  9,  6]], dtype=int32)
    >>> jnp.outer(x, y)
    Array([[ 0,  0,  0,  0],
           [ 5,  4,  3,  2],
           [10,  8,  6,  4],
           [15, 12,  9,  6]], dtype=int32)

    Some other ways of computing outer products:

    >>> jnp.einsum("i,j", x, y)  # implicit form
    Array([[ 0,  0,  0,  0],
           [ 5,  4,  3,  2],
           [10,  8,  6,  4],
           [15, 12,  9,  6]], dtype=int32)
    >>> jnp.einsum(x, (0,), y, (1,), (0, 1))  # explicit form via indices
    Array([[ 0,  0,  0,  0],
           [ 5,  4,  3,  2],
           [10,  8,  6,  4],
           [15, 12,  9,  6]], dtype=int32)
    >>> jnp.einsum(x, (0,), y, (1,))  # implicit form via indices
    Array([[ 0,  0,  0,  0],
           [ 5,  4,  3,  2],
           [10,  8,  6,  4],
           [15, 12,  9,  6]], dtype=int32)

    **1D array sum**

    >>> jnp.einsum("i->", x)  # requires explicit form
    Array(6, dtype=int32)
    >>> jnp.einsum(x, (0,), ())  # explicit form via indices
    Array(6, dtype=int32)
    >>> jnp.sum(x)
    Array(6, dtype=int32)

    **Sum along an axis**

    >>> jnp.einsum("...j->...", M)  # requires explicit form
    Array([ 6, 22, 38, 54], dtype=int32)
    >>> jnp.einsum(M, (..., 0), (...,))  # explicit form via indices
    Array([ 6, 22, 38, 54], dtype=int32)
    >>> M.sum(-1)
    Array([ 6, 22, 38, 54], dtype=int32)

    **Matrix transpose**

    >>> y = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> jnp.einsum("ij->ji", y)  # explicit form
    Array([[1, 4],
           [2, 5],
           [3, 6]], dtype=int32)
    >>> jnp.einsum("ji", y)  # implicit form
    Array([[1, 4],
           [2, 5],
           [3, 6]], dtype=int32)
    >>> jnp.einsum(y, (1, 0))  # implicit form via indices
    Array([[1, 4],
           [2, 5],
           [3, 6]], dtype=int32)
    >>> jnp.einsum(y, (0, 1), (1, 0))  # explicit form via indices
    Array([[1, 4],
           [2, 5],
           [3, 6]], dtype=int32)
    >>> jnp.transpose(y)
    Array([[1, 4],
           [2, 5],
           [3, 6]], dtype=int32)

    **Matrix diagonal**

    >>> jnp.einsum("ii->i", M)
    Array([ 0,  5, 10, 15], dtype=int32)
    >>> jnp.diagonal(M)
    Array([ 0,  5, 10, 15], dtype=int32)

    **Matrix trace**

    >>> jnp.einsum("ii", M)
    Array(30, dtype=int32)
    >>> jnp.trace(M)
    Array(30, dtype=int32)

    **Tensor products**

    >>> x = jnp.arange(30).reshape(2, 3, 5)
    >>> y = jnp.arange(60).reshape(3, 4, 5)
    >>> jnp.einsum('ijk,jlk->il', x, y)  # explicit form
    Array([[ 3340,  3865,  4390,  4915],
           [ 8290,  9940, 11590, 13240]], dtype=int32)
    >>> jnp.tensordot(x, y, axes=[(1, 2), (0, 2)])
    Array([[ 3340,  3865,  4390,  4915],
           [ 8290,  9940, 11590, 13240]], dtype=int32)
    >>> jnp.einsum('ijk,jlk', x, y)  # implicit form
    Array([[ 3340,  3865,  4390,  4915],
           [ 8290,  9940, 11590, 13240]], dtype=int32)
    >>> jnp.einsum(x, (0, 1, 2), y, (1, 3, 2), (0, 3))  # explicit form via indices
    Array([[ 3340,  3865,  4390,  4915],
           [ 8290,  9940, 11590, 13240]], dtype=int32)
    >>> jnp.einsum(x, (0, 1, 2), y, (1, 3, 2))  # implicit form via indices
    Array([[ 3340,  3865,  4390,  4915],
           [ 8290,  9940, 11590, 13240]], dtype=int32)

    **Chained dot products**

    >>> w = jnp.arange(5, 9).reshape(2, 2)
    >>> x = jnp.arange(6).reshape(2, 3)
    >>> y = jnp.arange(-2, 4).reshape(3, 2)
    >>> z = jnp.array([[2, 4, 6], [3, 5, 7]])
    >>> jnp.einsum('ij,jk,kl,lm->im', w, x, y, z)
    Array([[ 481,  831, 1181],
           [ 651, 1125, 1599]], dtype=int32)
    >>> jnp.einsum(w, (0, 1), x, (1, 2), y, (2, 3), z, (3, 4))  # implicit, via indices
    Array([[ 481,  831, 1181],
           [ 651, 1125, 1599]], dtype=int32)
    >>> w @ x @ y @ z  # direct chain of matmuls
    Array([[ 481,  831, 1181],
           [ 651, 1125, 1599]], dtype=int32)
    >>> jnp.linalg.multi_dot([w, x, y, z])
    Array([[ 481,  831, 1181],
           [ 651, 1125, 1599]], dtype=int32)

  .. _opt_einsum: https://github.com/dgasmith/opt_einsum
  Nz2The 'out' argument to jnp.einsum is not supported.r   Tr  Fc                    h | ]Q}t          |t                    t          j        |          D ]%}t	          j        |          t          |          &RS rj   )rF   rA   r}   r?   r   r  rQ   )r*  r   r  s      rK   	<setcomp>zeinsum.<locals>.<setcomp>  sl       
2s(;(;x|| 
4#7#:#:
1gg   rL   )einsum_calluse_blasr  c              3  B   K   | ]^}}}}|t          |          |fV  d S r`   )	frozenset)r*  r   r  r  r  s        rK   r,  zeinsum.<locals>.<genexpr>  s7      LL1a!9Q<<+LLLLLLrL   )r   r   r  r^  )ro  r  )r  )r   rF   rA   r  
opt_einsumcontract_pathnextr  _poly_einsum_handlersr  _default_poly_einsum_handlerrG   r   _einsumr  
named_call)
subscriptsr   r  r   r   r  r  spec	path_typenon_constant_dim_typesr  tycontractionsr  s                 rK   r  r    sa   r $8$$(_
R
S
SS"8A;44	>!$$#t++ii(eBSBSYa)     
  P,MM	d)**	+	+B)--b2NOOM(=	tdYH H H(L LL|LLLLL,w|DAAA&	^F...F	,	&
6 
6 6rL   c                      t          j        dddg          fd D             }d t          |          D             t          j        |i |\  }} fd|D             }||fS )Ndummyr?   rP   c                    g | ]A}t          |d           r- t          d |j        D                       |j                  n|BS )rP   c              3  J   K   | ]}t          |          t          u r|nd V  dS )   N)rQ   r^   r  s     rK   r,  z:_default_poly_einsum_handler.<locals>.<listcomp>.<genexpr>  s4      EEd1ggnn!EEEEEErL   )r   rG   r?   rP   )r*  rM   r  s     rK   r2  z0_default_poly_einsum_handler.<locals>.<listcomp>  sd     > > >/07##+UU5EEQWEEEEEqwOOO)*> > >rL   c                4    i | ]\  }}t          |          |S rj   rf   r  s      rK   r  z0_default_poly_einsum_handler.<locals>.<dictcomp>  s$    555$!QRUUA555rL   c                F    g | ]}t          |                            S rj   r  )r*  r  mappingr  s     rK   r2  z0_default_poly_einsum_handler.<locals>.<listcomp>  s(    EEEAx1/EEErL   )collections
namedtupler  r  r  )r  r   dummiesout_dummiesr  contract_operandsr  r  s   `     @@rK   r  r    s    

 7G*<
=
=%> > > >4<> > >'55)G"4"4555'(6J6JJ+|EEEEEEEE	L	((rL   )r  r  "bool | str | list[tuple[int, ...]]!tuple[list[tuple[int, ...]], Any]c                  d S r`   rj   r  r  r  s      rK   einsum_pathr    s	    
 ),rL   c                  d S r`   rj   )r  rJ  r  r  s       rK   r  r    s	     ),rL   autoc              ^    |du rd}n|du rt                      }t          j        | g|R d|iS )a  Evaluates the optimal contraction path without evaluating the einsum.

  JAX implementation of :func:`numpy.einsum_path`. This function calls into
  the opt_einsum_ package, and makes use of its optimization routines.

  Args:
    subscripts: string containing axes names separated by commas.
    *operands: sequence of one or more arrays corresponding to the subscripts.
    optimize: specify how to optimize the order of computation. In JAX this defaults
      to ``"auto"``. Other options are ``True`` (same as ``"optimize"``), ``False``
      (unoptimized), or any string supported by ``opt_einsum``, which
      includes ``"optimize"``,, ``"greedy"``, ``"eager"``, and others.

  Returns:
    A tuple containing the path that may be passed to :func:`~jax.numpy.einsum`, and a
    printable object representing this optimal path.

  Examples:
    >>> key1, key2, key3 = jax.random.split(jax.random.key(0), 3)
    >>> x = jax.random.randint(key1, minval=-5, maxval=5, shape=(2, 3))
    >>> y = jax.random.randint(key2, minval=-5, maxval=5, shape=(3, 100))
    >>> z = jax.random.randint(key3, minval=-5, maxval=5, shape=(100, 5))
    >>> path, path_info = jnp.einsum_path("ij,jk,kl", x, y, z, optimize="optimal")
    >>> print(path)
    [(1, 2), (0, 1)]
    >>> print(path_info)
          Complete contraction:  ij,jk,kl->il
                Naive scaling:  4
            Optimized scaling:  3
              Naive FLOP count:  9.000e+3
          Optimized FLOP count:  3.060e+3
          Theoretical speedup:  2.941e+0
          Largest intermediate:  1.500e+1 elements
        --------------------------------------------------------------------------------
        scaling        BLAS                current                             remaining
        --------------------------------------------------------------------------------
          3           GEMM              kl,jk->lj                             ij,lj->il
          3           GEMM              lj,ij->il                                il->il

    Use the computed path in :func:`~jax.numpy.einsum`:

    >>> jnp.einsum("ij,jk,kl", x, y, z, optimize=path)
    Array([[-539,  216,   95,  592,  209],
           [ 527,   76,  285, -436, -529]], dtype=int32)

  .. _opt_einsum: https://github.com/dgasmith/opt_einsum
  Tr  Fr  )r  r  r  r  s      rK   r  r  	  sL    h HH5}}H		!*	Kx	K	K	K(	K	KKrL   c                    |                      t                              t                              |                              S r`   )	translaterA   	maketransdictfromkeys)r  charss     rK   _removecharsr  C  s,    	
S]]4==#7#788	9	99rL   r   r  5Sequence[tuple[tuple[int, ...], frozenset[str], str]]c           
        !"#$%&'() t          j        d           t          t          t          |                     } t          j        | ddi\  }nd}fd))fd})fd}d }|D ]\  }	}
}t          |
          }|                    d	          \  }}|                    d
          }t          |	          dk    rd| 	                    |	d                   }|\  %t          j        %          fd|D             } ||%|          \  }% ||%|          \  }%n~t          |	          dk    rct          | j	        |	          \   &|\  #( | #t          &          (          \   # |&(t                     #          \  &(t          j        #          "t          j        (          '"'fd|D             } | #|          \   #"'fd|D             } |&(|          \  &( | #"|(z             \   # |&('|#z             \  &(t          #          t          (          z  $$fd|D             }t          #          t          (          z  !!fd|D             }t          #(fd|D                       \  }}t          j        j        s>t%           #&(fd|D                       s J d j         d# d&j         d(             d                    |          }t          #(fd|D                       \  }}|d                    |          z   }t)          #|          }t)          (|          }||z   |z   %%|k    r||f||ff} |& ||          }n(||z   |z   %||f||ff} | &||          }nt*          t          %          t          |          cxk    r t          t          %                    k    sn J t          %          t          |          k    sJ %|k    r0t-          %fd|D                       }t/          j        ||          }|                     |           t5          j        | d         |          S )Nr  rt  TFc                   t          j        |           | j        k    r|                               } t	          j        | t          j        d| j                  | j        t          k    rt          j	        nt          j
        |          S Nr   )r   r   rP   r   r   reducer}   r  r  r  
bitwise_or)rM   rJ  r   s     rK   r  z_einsum.<locals>.sumU  sr    !344??
(()
*
*a:a!QW--!"E!1!1cggs~tM M MrL   c                f    |r*fd|D             } | |          } t          |          | fS )Nc                :    g | ]}                     |          S rj   r   r*  r  namess     rK   r2  z0_einsum.<locals>.sum_uniques.<locals>.<listcomp>]  s%    444Dekk$444rL   )r  )operandr  uniquesrJ  r  s    `  rK   sum_uniquesz_einsum.<locals>.sum_uniques[  sO     +4444G444dGT""g5'**eE>rL   c                   |                                 D ]\  }|dk    rfdt          |          D             }t          j        t	          j        d          | j        |          }t          j        || t          |                     } |vr# | |          } |
                    d          } | |d d                   } |
                    d|dz
            }| |fS )Nr   c                &    g | ]\  }}|k    |S rj   rj   )r*  rD  r  r  s      rK   r2  z0_einsum.<locals>.sum_repeats.<locals>.<listcomp>e  s"    <<<da!t)))))rL   rN   r>   r   )r  r  r   _deltar}   rP   r?   r   rq  r  replace)	r  r  r  
keep_namesr]  rJ  r  r  r  s	          @rK   sum_repeatsz_einsum.<locals>.sum_repeatsb  s    ||~~ 
5 
5e	<<<<i..<<<!"(6"2"2GM4HH*S':g+>+>??z!!C&&'--b))%%Ccrc++'--b%!)44%E>rL   c                R    t           j         fdt          t          |j                            D             }t          |t          t           j                                      \  }}t          j
         |          d                    fd|D                       fS )Nc                v    g | ]5\  }} j         |         d            p|dk    p |         d           6S )r   r   r)  )r*  rD  r  r|  r  other_shapes      rK   r2  z:_einsum.<locals>.filter_singleton_dims.<locals>.<listcomp>r  sg     A A A1 7=#Q'''K17KbbQ6K6K A A ArL   r>   c              3  (   K   | ]}|         V  d S r`   rj   )r*  rD  r  s     rK   r,  z9_einsum.<locals>.filter_singleton_dims.<locals>.<genexpr>u  s'      3P3PE!H3P3P3P3P3P3PrL   )r   r  r  r  findr9   rH   r   rE   r   r  join)r  r  r  other_nameskeep	sqez_axes	keep_axesr|  s   ```    @rK   filter_singleton_dimsz&_einsum.<locals>.filter_singleton_dimsp  s    		BA A A A A A!#k&6">">??A A AD)$U7<5H5H0I0IJJIy;w	**BGG3P3P3P3Pi3P3P3P,P,PPPrL   z->,r   r   c                ,    g | ]}|         d k    |S r   rj   )r*  r  r  s     rK   r2  z_einsum.<locals>.<listcomp>  s'    HHH$fTla6G6G6G6G6GrL   r   c                D    g | ]}|         d k    |         dk    |S r  rj   r*  r  
lhs_counts
rhs_countss     rK   r2  z_einsum.<locals>.<listcomp>  D     I I Id"4(A--*T2Ba2G2G 2G2G2GrL   c                D    g | ]}|         d k    |         dk    |S r  rj   r  s     rK   r2  z_einsum.<locals>.<listcomp>  r  rL   c                    g | ]}|v |	S rj   rj   )r*  rM   lhs_or_rhs_namess     rK   r2  z_einsum.<locals>.<listcomp>  s$    OOO>N9N9N!9N9N9NrL   c                    g | ]}|v |	S rj   rj   )r*  rM   lhs_and_rhs_namess     rK   r2  z_einsum.<locals>.<listcomp>  s$    GGG15F0F0FQ0F0F0FrL   c              3  l   K   | ].}                     |                               |          fV  /d S r`   )r  r*  r  	lhs_names	rhs_namess     rK   r,  z_einsum.<locals>.<genexpr>  sT       $: $:() &/^^A%6%6	q8I8I$J $: $: $: $: $: $:rL   c              3     K   | ]N}|v oE|v oAj                             |                   j                             |                   k    V  Od S r`   )r?   r   )r*  r  lhsr  rhsr  s     rK   r,  z_einsum.<locals>.<genexpr>  s       0& 0&  		 	Mdi/ 	M	)//$''(CIiood6K6K,LL0& 0& 0& 0& 0& 0&rL   z-Incompatible reduction dimensions: lhs.shape=z lhs_names=z rhs.shape=z rhs_names=r>   c              3  l   K   | ].}                     |                               |          fV  /d S r`   r  r  s     rK   r,  z_einsum.<locals>.<genexpr>  sT       "= "=&' $-??1#5#5yq7I7I"J "= "= "= "= "= "=rL   )r   c              3  B   K   | ]}                     |          V  d S r`   r  r  s     rK   r,  z_einsum.<locals>.<genexpr>  s/      >>5;;t$$>>>>>>rL   )r   r  rH   r  rS   r   r!  r  r   popr  Counterr?   r  r5   r   r  r  r  r  r  r   rG   r   r  r8  r   r   )*r  r  r   r   r  rx  r  r  r  operand_indicescontracted_names_seteinstrcontracted_names	input_strresult_namesinput_namesr  r  lhs_uniquesrhs_uniquesbatch_names	lhs_batch	rhs_batchbatch_names_strlhs_contrhs_contdeleted_namesremaining_lhs_namesremaining_rhs_namesrv  ra  r  r  r	  r  r  r  r  r  r  r  r  s*      `                           @@@@@@@@@@@rK   r  r  G  s    	#$:HEEE#gx(())(#/5/A8/hcg/h/h,,,M M M M M        Q Q Q 8D a a3o+V233$ll400I|//#&&K ?q  _Q/00gfe"5))f IHHH"2HHHg"{7E7;;ngu #{7E6<HHnguu	_			"	"X\?33hc3(i -,S)U3ZZ-68 8nc9,,S)U3ZZ-68 8nc9 &y11j&y11jI I I I I&6 I I Ik"{3	;??nc9I I I I I&6 I I Ik"{3	;??nc9 #{3	:#/)#;= =nc9"{3	:#/)#;= =nc9 Y#i..8OOOO%5OOOi..3y>>9GGGGGGGk# $: $: $: $: $:-8$: $: $: : :i
 "( :C 0& 0& 0& 0& 0& 0& 0& %0& 0& 0& -& -& : :9y9 9-69 9y9 9-69 9	: : : ,,o! "= "= "= "= "=+;"= "= "= = =h%0@(A(AAm(MBB(MBB
  336IIe	,		&1Iy3IJ,sC):I6LN N N  "558KK&1Iy3IJ,sC):I6LN N N   u::\**====c#e**oo======u::\******>>>>>>>>>dgt,,gOOG		+HQK9OQa	b	bbrL   DType | Nonec                   t          j        d| |           t          |           dk    st          |          dk    r't          | |          } t          ||          }| |z  S t	          | |d||          S )a>  Compute the inner product of two arrays.

  JAX implementation of :func:`numpy.inner`.

  Unlike :func:`jax.numpy.matmul` or :func:`jax.numpy.dot`, this always performs
  a contraction along the last dimension of each input.

  Args:
    a: array of shape ``(..., N)``
    b: array of shape ``(..., N)``
    precision: either ``None`` (default), which means the default precision for
      the backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,
      ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two
      such values indicating precision of ``a`` and ``b``.
    preferred_element_type: either ``None`` (default), which means the default
      accumulation type for the input types, or a datatype, indicating to
      accumulate results to and return a result with that datatype.

  Returns:
    array of shape ``(*a.shape[:-1], *b.shape[:-1])`` containing the batched vector
    product of the inputs.

  See also:
    - :func:`jax.numpy.vecdot`: conjugate multiplication along a specified axis.
    - :func:`jax.numpy.tensordot`: general tensor multiplication.
    - :func:`jax.numpy.matmul`: general batched matrix & vector multiplication.

  Examples:
    For 1D inputs, this implements standard (non-conjugate) vector multiplication:

    >>> a = jnp.array([1j, 3j, 4j])
    >>> b = jnp.array([4., 2., 5.])
    >>> jnp.inner(a, b)
    Array(0.+30.j, dtype=complex64)

    For multi-dimensional inputs, batch dimensions are stacked rather than broadcast:

    >>> a = jnp.ones((2, 3))
    >>> b = jnp.ones((5, 3))
    >>> jnp.inner(a, b).shape
    (2, 5)
  r  r   rn   )r   r   r   )r*   r   rE   rS   r  r  s       rK   r  r    s    ^ w1%%%	!WW\\T!WW\\/000A/000Aq5L	1aY*@
B 
B 
B BrL   )r  c                    |t          d          t          j        d| |           t          j        | |          \  } }t	          |           d d d f         t	          |          d d d f         z  S )Nz1The 'out' argument to jnp.outer is not supported.outer)r   r*   r   r   r  )r   r  r   s      rK   r*  r*    st     	_
Q
R
RRw1%%%		Q	"	"$!Q	q!!!T'	U1XXdAAAg.	..rL   )axisaaxisbaxiscrb  r+  r,  r-  c                   t          j        d| |           ||}|}|}t          | |d          } t          ||d          }| j        d         dvs|j        d         dvrt	          d          | j        d         dk    r4|j        d         dk    r#| d         |d         z  | d         |d         z  z
  S | d         }| d         }| j        d         dk    r| d	         nt          |          }|d         }	|d         }
|j        d         dk    r|d	         nt          |	          }t          ||z  ||
z  z
  ||	z  ||z  z
  ||
z  ||	z  z
  g          }t          |d
|          S )Ncrossr   )r   r  z1Dimension must be either 2 or 3 for cross productr   ).r   ).r   r  ).r   r   )r*   r   r  r?   r   r  r  )r   r  r+  r,  r-  rb  a0rT  rU  b0b1b2r  s                rK   r/  r/    s}   
 w1%%%	EEEq%!q%!WR[!'"+V";";
H
I
IIWR[A!'"+**V9qy 1V9qy#888y"y"GBK1$$qyy*R.."y"y"GBK1$$qyy*R.."R"WrBwR"r' 127R"W3DEFF!	!Q		rL   c           
     B   t          j        d| |           t          j        | |          \  } }t          |           t          |          k     r;t	          | t          t          |          t          |           z
                      } nZt          |          t          |           k     r:t	          |t          t          |           t          |          z
                      }t	          | t          ddt          |           z  d                    }t	          |t          ddt          |          z  d                    }t          t          j        t          |           t          |                              }t          t          j        ||          |          S )Nkronr   r   r   )r*   r   r   rE   r  r   rG   r}   r  r?   r=  r   r1  )r   r  
a_reshaped
b_reshapedrd  s        rK   r5  r5  ;  s:    vq!$$$		Q	"	"$!Q	!WWtAwwAuT!WWtAww.//00AAAwwaAuT!WWtAww.//00A1eAq477{A6677*1eAq477{A6677*BKa%((3344)	Z00)	<	<<rL   )r   
increasingr8  c                   t          j        d|            t          |           } | j        dk    rt	          d          || j        d         nt          j        t          j	        |d          }|dk     rt	          d          t          j        | j        |          }|s&t          j        t          ||dz
            |          }t          j        | d         t#          |t%          t'          | j                                                S )Nvanderr   z!x must be a one-dimensional arrayr   z'N' argument of jnp.vander()zN must be nonnegative.N)r*   r   rS   rE   r   r?   r   r   r   r   r   r  rP   r  r   r)   r  r  rG   r   )rM   r   r8  r  s       rK   r:  r:  J  s    
 x###ajj!Vq[[
8
9
99Iagajj4#9NA5$7 $7!UU
,
-
--	!'1		$	 27:dAE**D11D	a	lKeE!&MM6J6J$K$K	L	LLrL   c          	     H   t          t          t          t          |           ||                              }t	          |           dk    r)|dd                             |j        d         d          S |                    |j        d         t	          |                     S )a  Find the indices of nonzero array elements

  JAX implementation of :func:`numpy.argwhere`.

  ``jnp.argwhere(x)`` is essentially equivalent to ``jnp.column_stack(jnp.nonzero(x))``
  with special handling for zero-dimensional (i.e. scalar) inputs.

  Because the size of the output of ``argwhere`` is data-dependent, the function is not
  typically compatible with JIT. The JAX version adds the optional ``size`` argument, which
  specifies the size of the leading dimension of the output - it must be specified statically
  for ``jnp.argwhere`` to be compiled with non-static operands. See :func:`jax.numpy.nonzero`
  for a full discussion of ``size`` and its semantics.

  Args:
    a: array for which to find nonzero elements
    size: optional integer specifying statically the number of expected nonzero elements.
      This must be specified in order to use ``argwhere`` within JAX transformations like
      :func:`jax.jit`. See :func:`jax.numpy.nonzero` for more information.
    fill_value: optional array specifying the fill value when ``size`` is specified.
      See :func:`jax.numpy.nonzero` for more information.

  Returns:
    a two-dimensional array of shape ``[size, x.ndim]``. If ``size`` is not specified as
    an argument, it is equal to the number of nonzero elements in ``x``.

  See Also:
    - :func:`jax.numpy.where`
    - :func:`jax.numpy.nonzero`

  Examples:
    Two-dimensional array:

    >>> x = jnp.array([[1, 0, 2],
    ...                [0, 3, 0]])
    >>> jnp.argwhere(x)
    Array([[0, 0],
           [0, 2],
           [1, 1]], dtype=int32)

    Equivalent computation using :func:`jax.numpy.column_stack` and :func:`jax.numpy.nonzero`:

    >>> jnp.column_stack(jnp.nonzero(x))
    Array([[0, 0],
           [0, 2],
           [1, 1]], dtype=int32)

    Special case for zero-dimensional (i.e. scalar) inputs:

    >>> jnp.argwhere(1)
    Array([], shape=(1, 0), dtype=int32)
    >>> jnp.argwhere(0)
    Array([], shape=(0, 0), dtype=int32)
  rY  r   N)r  r  rd  r  rE   r=  r?   )r   r  rZ  r   s       rK   argwherer=  a  s    v VGJqMMTTTUUVV&	!WW\\"1":fl1oq111	Qa	1	11rL   r  c                    t          j        d|            |t          d          t          t	          |           |d nt          j        |          t          |                    S )Nrl  z2The 'out' argument to jnp.argmax is not supported.r  )r*   r   r   _argmaxrS   r   r   rN   r   rb  r   r  s       rK   rl  rl    g     x###_
R
S
SS	T\TTx~d7K7Kx..
* 
* 
* *rL   r  c                j   |;t          t          t          |                               }t          |           } d}n|g}| j        |         dk    rt          d          t          j        | t          || j                  t          j
        t                              }|rt          ||          n|S )Nr   z*attempt to get argmax of an empty sequence)rH   r   rE   r  r?   r   r   rl  rO  r   r   r  r  r   rb  r  r  r   s        rK   r@  r@        	\d1ggDaADD6DWT]a
A
B
BB:a+D!&996;TUY;Z;Z[[&&.	:VT	"	"	"F:rL   c                    t          j        d|            |t          d          t          t	          |           |d nt          j        |          t          |                    S )NrL  z2The 'out' argument to jnp.argmin is not supported.r?  )r*   r   r   _argminrS   r   r   rN   rA  s       rK   rL  rL    rB  rL   c                j   |;t          t          t          |                               }t          |           } d}n|g}| j        |         dk    rt          d          t          j        | t          || j                  t          j
        t                              }|rt          ||          n|S )Nr   z*attempt to get argmin of an empty sequence)rH   r   rE   r  r?   r   r   rL  rO  r   r   r  r  rD  s        rK   rG  rG    rE  rL   zTWarning: jax.numpy.arg{} returns -1 for all-NaN slices and does not raise
an error.
)rW  r  c                    |t          d          t          | |d nt          j        |          t	          |                    S )Nz5The 'out' argument to jnp.nanargmax is not supported.r?  )r   
_nanargmaxr   r   rN   rA  s       rK   	nanargmaxrK    I     	_
U
V
VV	At|tt1E1EPTU]P^P^	_	_	__rL   c                Z   t          j        d|            t          t          |           t                    st          | ||          S t          j        |           }t          |t           |           } t          | ||          }t          t          j        |||          d|          S )NrK  r  r   )r*   r   rT   r[   r  rl  r)   r   r   infr(   r  r   rb  r  nan_maskr  s        rK   rJ  rJ    s    {A&&&	F1IIw	'	' 3!$2222\!__(HsdA!qth///#	z~hTHEEEr3	O	OOrL   c                    |t          d          t          | |d nt          j        |          t	          |                    S )Nz5The 'out' argument to jnp.nanargmin is not supported.r?  )r   
_nanargminr   r   rN   rA  s       rK   	nanargminrS    rL  rL   c                X   t          j        d|            t          t          |           t                    st          | ||          S t          j        |           }t          |t          |           } t          | ||          }t          t          j        |||          d|          S )NrS  r  r   )r*   r   rT   r[   r  rL  r)   r   r   rN  r(   r  rO  s        rK   rR  rR    s    {A&&&	F1IIw	'	' 3!$2222\!__(Hc1!qth///#	z~hTHEEEr3	O	OOrL   )rb  kindr  stable
descending)rU  r  rV  rW  rU  rV  rW  c               D   t          j        d|            |t          d          |t          d          |t          |           }d}nt	          |           }t          ||j                  }t          j        |||          }|rt          j	        ||g          n|S )a  Return a sorted copy of an array.

  JAX implementation of :func:`numpy.sort`.

  Args:
    a: array to sort
    axis: integer axis along which to sort. Defaults to ``-1``, i.e. the last
      axis. If ``None``, then ``a`` is flattened before being sorted.
    stable: boolean specifying whether a stable sort should be used. Default=True.
    descending: boolean specifying whether to sort in descending order. Default=False.
    kind: deprecated; instead specify sort algorithm using stable=True or stable=False.
    order: not supported by JAX

  Returns:
    Sorted array of shape ``a.shape`` (if ``axis`` is an integer) or of shape
    ``(a.size,)`` (if ``axis`` is None).

  Examples:
    Simple 1-dimensional sort

    >>> x = jnp.array([1, 3, 5, 4, 2, 1])
    >>> jnp.sort(x)
    Array([1, 1, 2, 3, 4, 5], dtype=int32)

    Sort along the last axis of an array:

    >>> x = jnp.array([[2, 1, 3],
    ...                [4, 3, 6]])
    >>> jnp.sort(x, axis=1)
    Array([[1, 2, 3],
           [3, 4, 6]], dtype=int32)

  See also:
    - :func:`jax.numpy.argsort`: return indices of sorted values.
    - :func:`jax.numpy.lexsort`: lexicographical sort of multiple arrays.
    - :func:`jax.lax.sort`: lower-level function wrapping XLA's Sort operator.
  r]  Nzd'kind' argument to sort is not supported. Use stable=True or stable=False to specify sort stability.z*'order' argument to sort is not supported.r   r'  	is_stabler  )
r*   r   rx   r  rS   rO  rE   r   r]  rm  )	r   rb  rU  r  rV  rW  r  r'  r   s	            rK   r]  r]    s    ^ vq!!!	
 N O O O

@
A
AA	\
((CDD
!**C sx00)8C9???&4>	JYK	0	0	0	0FJrL   c                    t          j        d|            t          j        t	          |           d          } t          j        | t          j        | j                            S )Nsort_complexr   r&  )	r*   r   r   r]  rS   r  r   to_complex_dtyperP   )r   s    rK   r\  r\  B  sQ     ~q)))	hwqzzQ'''!		!!V%<QW%E%E	F	FFrL   keys(Array | np.ndarray | Sequence[ArrayLike]c                   t          |           }t          j        dg|R   t          d |D                       }t          |          dk    rt	          d          t          d |D                       dk    rt          d          t          |d                   dk    r(t          dt          j	        t                              S t          |t          |d                             }|d         j        |         d	k    }t          j        |rt          nt          t          |d                   |          }t          j        g |d d d
         |R |t          |                    d
         S )Nlexsortc              3  4   K   | ]}t          |          V  d S r`   r  )r*  rX  s     rK   r,  zlexsort.<locals>.<genexpr>N  s(      33AWQZZ333333rL   r   z-need sequence of keys with len > 0 in lexsortc                ,    h | ]}t          |          S rj   r)  )r*  r  s     rK   r  zlexsort.<locals>.<setcomp>Q  s    	+	+	+%**	+	+	+rL   r   z"all keys need to be the same shapern           r   )r'  num_keys)rG   r*   r   r   rx   r   rE   r  r   r   r  rO  r?   r   r  r  r]  )r^  rb  	key_tuple
key_arraysuse_64bit_indexr  s         rK   ra  ra  I  sb    Dkk)y-9----3333333*__
C
D
DD	+	+
	+	+	+,,q00
9
:
::	*Q-A&3D99::::	D$z!}"5"5	6	6$qM'-':/		@eeD%
STBVBVX\	]	]$	+Jttt$+d++tc*oo	V	V	VWY	ZZrL   c                  t          j        d|            t          |           }|t          d          |t          d          |t	          |          }d}nt          |           }t          ||j                  }t          j        |j	        |                    p|j	        |         dk    }t          j        |rt          nt          |j	        |          }	|r0|r.t          j        ||g          }t          j        |	|g          }	t          j        ||	||          \  }
}|rt          j        ||g          n|S )	a  Return indices that sort an array.

  JAX implementation of :func:`numpy.argsort`.

  Args:
    a: array to sort
    axis: integer axis along which to sort. Defaults to ``-1``, i.e. the last
      axis. If ``None``, then ``a`` is flattened before being sorted.
    stable: boolean specifying whether a stable sort should be used. Default=True.
    descending: boolean specifying whether to sort in descending order. Default=False.
    kind: deprecated; instead specify sort algorithm using stable=True or stable=False.
    order: not supported by JAX

  Returns:
    Array of indices that sort an array. Returned array will be of shape ``a.shape``
    (if ``axis`` is an integer) or of shape ``(a.size,)`` (if ``axis`` is None).

  Examples:
    Simple 1-dimensional sort

    >>> x = jnp.array([1, 3, 5, 4, 2, 1])
    >>> indices = jnp.argsort(x)
    >>> indices
    Array([0, 5, 4, 1, 3, 2], dtype=int32)
    >>> x[indices]
    Array([1, 1, 2, 3, 4, 5], dtype=int32)

    Sort along the last axis of an array:

    >>> x = jnp.array([[2, 1, 3],
    ...                [6, 4, 3]])
    >>> indices = jnp.argsort(x, axis=1)
    >>> indices
    Array([[1, 0, 2],
           [2, 1, 0]], dtype=int32)
    >>> jnp.take_along_axis(x, indices, axis=1)
    Array([[1, 2, 3],
           [3, 4, 6]], dtype=int32)


  See also:
    - :func:`jax.numpy.sort`: return sorted values directly.
    - :func:`jax.numpy.lexsort`: lexicographical sort of multiple arrays.
    - :func:`jax.lax.sort`: lower-level function wrapping XLA's Sort operator.
  r`  Nzg'kind' argument to argsort is not supported. Use stable=True or stable=False to specify sort stability.z-'order' argument to argsort is not supported.r   rd  r  rY  )r*   r   rS   rx   r  rO  rE   r   r  r?   r   r  r  r  rm  rH  )r   rb  rU  r  rV  rW  r  r'  rh  r  r  r  s               rK   r`  r`  [  sS   n y!$$$

#	
 N O O O

C
D
DD	\
**CDD
!**C sx00),SYy-ABBBgciPYFZ_fFg/		@eeD#)Y	W	W$  1F 1
'#9+
.
.
.C74YK000DTY&QQQ*!W5?	Li[	1	1	1	1WLrL   kthc                   t          j        d|            t          |           }t          |j        t
          j                  rt          d          t          ||j	                  }t          ||j
        |                   }t          ||d          }t          j        |j        d          r't          j        |dz    |dz             d          dz
  }n t          j        | |dz             d          }t          j        ||j
        d         |z
  dz
            d         }t          j        ||g|j	        dz
            }t          |d|          S )a  Returns a partially-sorted copy of an array.

  JAX implementation of :func:`numpy.partition`. The JAX version differs from
  NumPy in the treatment of NaN entries: NaNs which have the negative bit set
  are sorted to the beginning of the array.

  Args:
    a: array to be partitioned.
    kth: static integer index about which to partition the array.
    axis: static integer axis along which to partition the array; default is -1.

  Returns:
    A copy of ``a`` partitioned at the ``kth`` value along ``axis``. The entries
    before ``kth`` are values smaller than ``take(a, kth, axis)``, and entries
    after ``kth`` are indices of values larger than ``take(a, kth, axis)``

  Note:
    The JAX version requires the ``kth`` argument to be a static integer rather than
    a general array. This is implemented via two calls to :func:`jax.lax.top_k`. If
    you're only accessing the top or bottom k values of the output, it may be more
    efficient to call :func:`jax.lax.top_k` directly.

  See Also:
    - :func:`jax.numpy.sort`: full sort
    - :func:`jax.numpy.argpartition`: indirect partial sort
    - :func:`jax.lax.top_k`: directly find the top k entries
    - :func:`jax.lax.approx_max_k`: compute the approximate top k entries
    - :func:`jax.lax.approx_min_k`: compute the approximate bottom k entries

  Examples:
    >>> x = jnp.array([6, 8, 4, 3, 1, 9, 7, 5, 2, 3])
    >>> kth = 4
    >>> x_partitioned = jnp.partition(x, kth)
    >>> x_partitioned
    Array([1, 2, 3, 3, 4, 9, 8, 7, 6, 5], dtype=int32)

    The result is a partially-sorted copy of the input. All values before ``kth``
    are of smaller than the pivot value, and all values after ``kth`` are larger
    than the pivot value:

    >>> smallest_values = x_partitioned[:kth]
    >>> pivot_value = x_partitioned[kth]
    >>> largest_values = x_partitioned[kth + 1:]
    >>> print(smallest_values, pivot_value, largest_values)
    [1 2 3 3] 4 [9 8 7 6 5]

    Notice that among ``smallest_values`` and ``largest_values``, the returned
    order is arbitrary and implementation-dependent.
  	partitionz3jnp.partition for complex dtype is not implemented.r   unsigned integerr   r   r&  )r*   r   rS   rT   rP   r}   rU   r   rO  rE   r?   r  r   r   r   top_kr  )r   rj  rb  r  bottomtopr   s          rK   rl  rl    s7   h {A&&&

#	2-.. U
S
T
TT	D#(	+	+$3	$00#dB#^CI122 *i#'
C!G,,Q//!3FFicAg&&q))F	#sy}s*Q.//2#A>>>#	#r4	 	  rL   c                8   t          j        d|            t          |           }t          |j        t
          j                  rt          d          t          ||j	                  }t          ||j
        |                   }t          ||d          }t          j        |j        d          r#t          j        |dz    |dz             d         }nt          j        | |dz             d         }d }t!          |j	        dz
            D ]}t#          j        |          } |t'          |j
                  |          }t          j        ||j
        d         |z
  dz
            d         }t          j        ||g|j	        dz
            }	t          |	d|          S )ae  Returns indices that partially sort an array.

  JAX implementation of :func:`numpy.argpartition`. The JAX version differs from
  NumPy in the treatment of NaN entries: NaNs which have the negative bit set are
  sorted to the beginning of the array.

  Args:
    a: array to be partitioned.
    kth: static integer index about which to partition the array.
    axis: static integer axis along which to partition the array; default is -1.

  Returns:
    Indices which partition ``a`` at the ``kth`` value along ``axis``. The entries
    before ``kth`` are indices of values smaller than ``take(a, kth, axis)``, and
    entries after ``kth`` are indices of values larger than ``take(a, kth, axis)``

  Note:
    The JAX version requires the ``kth`` argument to be a static integer rather than
    a general array. This is implemented via two calls to :func:`jax.lax.top_k`. If
    you're only accessing the top or bottom k values of the output, it may be more
    efficient to call :func:`jax.lax.top_k` directly.

  See Also:
    - :func:`jax.numpy.partition`: direct partial sort
    - :func:`jax.numpy.argsort`: full indirect sort
    - :func:`jax.lax.top_k`: directly find the top k entries
    - :func:`jax.lax.approx_max_k`: compute the approximate top k entries
    - :func:`jax.lax.approx_min_k`: compute the approximate bottom k entries

  Examples:
    >>> x = jnp.array([6, 8, 4, 3, 1, 9, 7, 5, 2, 3])
    >>> kth = 4
    >>> idx = jnp.argpartition(x, kth)
    >>> idx
    Array([4, 8, 3, 9, 2, 0, 1, 5, 6, 7], dtype=int32)

    The result is a sequence of indices that partially sort the input. All indices
    before ``kth`` are of values smaller than the pivot value, and all indices
    after ``kth`` are of values larger than the pivot value:

    >>> x_partitioned = x[idx]
    >>> smallest_values = x_partitioned[:kth]
    >>> pivot_value = x_partitioned[kth]
    >>> largest_values = x_partitioned[kth + 1:]
    >>> print(smallest_values, pivot_value, largest_values)
    [1 2 3 3] 4 [6 8 9 7 5]

    Notice that among ``smallest_values`` and ``largest_values``, the returned
    order is arbitrary and implementation-dependent.
  rl  z6jnp.argpartition for complex dtype is not implemented.r   rm  r   c                B    | j         |                             d          S r  )r  r  )r   rD  s     rK   r  zargpartition.<locals>.<lambda>5  s    QT!W[[^^ rL   r&  )r*   r   rS   rT   rP   r}   rU   r   rO  rE   r?   r  r   r   r   rn  r   r  r  rN  r  )
r   rj  rb  r  
bottom_indset_to_zeror  proxytop_indr   s
             rK   argpartitionrw    s~   j {A&&&

#	2-.. X
V
W
WW	D#(	+	+$3	$00#dB#^CI122 -S1W:sQw//2JJC4q))!,J ,++A ( (a(;''KK
+d39ooz
2
2%IeSYr]S01455a8'W-AFFF#	#r4	 	  rL   r   r  c           
        t          j        |j        t          j        |                    }t	          |          dk    rd}t          |          t          t          ||          t          j        ||                    D ]\  }}t          | j        |         t          j	                  }t          j        t          j        |t          j	                  t          j        |t          j	        d                              }t          j        | | f|          }t          j        |||z
  | j        |         |          } | S )Nr   zA'shift' and 'axis' arguments to roll must be scalars or 1D arraysrn   rh  )r   rx  r?   r}   r   r   r  r  r  r  r)   	remainderr  r   r  dynamic_slice_in_dim)	r   r  rb  b_shapern  rM   rD  	a_shape_ia_concats	            rK   _roll_dynamicr~  >  s    bhtnn=='\\Q
MC
S//,ug../$002 2 N Ndaagaj111I1!RX>>BHQKK88	: 	:A1vq))H 9q=!'!*1MMMAA	
(rL   r
  c           
     .   t          t          j        ||           D ]w\  }}| j        |         dk    r| | j        |         z  }t	          j        t	          j        | || j        |         |          t	          j        | d||          g|          } x| S )Nr   rh  r&  )r  r}   rk  r?   r   r  r  )r   r  rb  rl  r  rD  s         rK   _roll_staticr  N  s    B'e445 & &eb!wr{a
qwr{A)!Q"EEE)!Q;;;="$	& 	& 	&AA 
(rL   ArrayLike | Sequence[int]c                   t          j        d|            t          |           |;t                                          |d                              j                  S t          |          }t          fd|D                       }	 t          |          }t          ||          S # t          $ r! t          t          |          |          cY S w xY w)Nr  r   c              3  B   K   | ]}t          |j                  V  d S r`   rN  )r*  rl  r  s     rK   r,  zroll.<locals>.<genexpr>a  s0      ??B!"ch//??????rL   )r*   r   rS   r  r  r=  r?   r   rG   r  rx   r~  )r   r  rb  r  s      @rK   r  r  Y  s     vq!!!

#	\		UA&&..sy999	T	"	"$	????$???	?	?$*&&E UD))) 
 4 4 4gennd333334s   B. .(CC)rb  r  c                J   t          j        d|            t          j        t          j        |d          }t          |           }t          ||          }| |cxk    r|k    sn t          d|d|  d|           |dk     r||z  }||k    r|dz  }t          | ||          S )aQ  Roll the specified axis to a given position.

  JAX implementation of :func:`numpy.rollaxis`.

  This function exists for compatibility with NumPy, but in most cases the newer
  :func:`jax.numpy.moveaxis` instead, because the meaning of its arguments is
  more intuitive.

  Args:
    a: input array.
    axis: index of the axis to roll forward.
    start: index toward which the axis will be rolled (default = 0). After
      normalizing negative axes, if ``start <= axis``, the axis is rolled to
      the ``start`` index; if ``start > axis``, the axis is rolled until the
      position before ``start``.

  Returns:
    Copy of ``a`` with rolled axis.

  Notes:
    Unlike :func:`numpy.rollaxis`, :func:`jax.numpy.rollaxis` will return a copy rather
    than a view of the input array. However, under JIT, the compiler will optimize away
    such copies when possible, so this doesn't have performance impacts in practice.

  See also:
    - :func:`jax.numpy.moveaxis`: newer API with clearer semantics than ``rollaxis``;
      this should be preferred to ``rollaxis`` in most cases.
    - :func:`jax.numpy.swapaxes`: swap two axes.
    - :func:`jax.numpy.transpose`: general permutation of axes.

  Examples:
    >>> a = jnp.ones((2, 3, 4, 5))

    Roll axis 2 to the start of the array:

    >>> jnp.rollaxis(a, 2).shape
    (4, 2, 3, 5)

    Roll axis 1 to the end of the array:

    >>> jnp.rollaxis(a, 1, a.ndim).shape
    (2, 4, 5, 3)

    Equivalent of these two with :func:`~jax.numpy.moveaxis`

    >>> jnp.moveaxis(a, 2, 0).shape
    (4, 2, 3, 5)
    >>> jnp.moveaxis(a, 1, -1).shape
    (2, 4, 5, 3)
  rollaxisz"'start' argument of jnp.rollaxis()zstart=z must satisfy z	<=start<=r   r   )
r*   r   r   r   r   r   rE   rO  r   r  )r   rb  r  rz  s       rK   r  r  j  s    h z1%%%

 8\
]
]%77&	D&	)	)$'U
$
$
$
$f
$
$
$
$
HHHvgHHHH
I
II
QYY	VOE
T\\	QJE	!T5	!	!!rL   )rb  bitorderbigr  c           	        t          j        d|            t          |           }t          |j        t
                    s)t          |j        t                    st          d          |dvrt          d          t          j
        |t          | d                                        d          }t          dd          }|d	k    r|d d d
         }|t          |          }d}t          ||d
          }|j        d
         dz  }|r>t          j        |t%          j        d          |j        dz
  dgz  dd|z
  dfgz             }|                    |j        d d
         |j        d
         dz  dfz             }t-          |t/          t1          |j        dz
                                }||z                      d
                              d          }t          ||d
          S )Npackbitsz7Expected an input array of integer or boolean data typelittler  ('order' must be either 'little' or 'big'r   uint8r  rn   r  r   r   r  )r*   r   rS   rT   rP   r   r  rx   r   r   gtr   r   r  r  r  r?   r"  r}   r  rE   r=  r  rG   r   r  )r   rb  r  r  bitsry  packeds          rK   r  r    s   
 z1%%%

#
SY
(
( OJsy%,H,H O
M
N
NN&&&
?
@
@@sJq!$$%%,,W55#		!	!	!$":D	\
**CDdB#ima) J
'#rx{{8a<I;.1a)mQ2G1HHJ JC 	CIcrcNcimq&8!%<<==#	T5sx!|!4!455	6	6$4KR  ''00&	&$	#	##rL   )rb  r]  r  c           	        t          j        d|            t          |           }t          |           t          k    rt          d          |dvrt          d          t          d          t          dd          z  }|d	k    r|d d d
         }|t          |          }d}t          ||d
          }|d         t          |t          t          |j                                      z  dk                        d          }|                    |j        d d         dz             }|N||j        d
         k    r1t#          |dg|j        dz
  z  d||j        d
         z
  fgz             }n|dd |f         }t          ||d
          S )N
unpackbitsz2Expected an input array of unsigned byte data typer  r  r   r  r  rn   r  r   r   r;  r  r   r   .)r*   r   rS   r[   r  rx   r   r  r  r  r  rG   r   rE   r   r=  r?   r"  )r   rb  r]  r  r  r  unpackeds          rK   r  r    s    |Q'''

#AYY%
H
I
II&&&
?
@
@@	vaw///	/$":D	\
**CDdB#9~D%ch2H2H I IIQNVVW^__(hnSbS1E9::(
x~b!!!Xx8=1+<=!UX^\^M_E_A`@aabbhh#vv+&h	(D"	%	%%rL   unique_indicesindices_are_sortedStaticScalar | Nonec           
     \    t          | ||dnt          j        |          |||||          S )aY  Take elements from an array.

  JAX implementation of :func:`numpy.take`, implemented in terms of
  :func:`jax.lax.gather`. JAX's behavior differs from NumPy in the case
  of out-of-bound indices; see the ``mode`` parameter below.

  Args:
    a: array from which to take values.
    indices: N-dimensional array of integer indices of values to take from the array.
    axis: the axis along which to take values. If not specified, the array will
      be flattened before indexing is applied.
    mode: Out-of-bounds indexing mode, either ``"fill"`` or ``"clip"``. The default
      ``mode="fill"`` returns invalid values (e.g. NaN) for out-of bounds indices;
      the ``fill_value`` argument gives control over this value. For more discussion
      of ``mode`` options, see :attr:`jax.numpy.ndarray.at`.
    fill_value: The fill value to return for out-of-bounds slices when mode is 'fill'.
      Ignored otherwise. Defaults to NaN for inexact types, the largest negative value for
      signed types, the largest positive value for unsigned types, and True for booleans.
    unique_indices: If True, the implementation will assume that the indices are unique,
      which can result in more efficient execution on some backends. If set to True and
      indices are not unique, the output is undefined.
    indices_are_sorted : If True, the implementation will assume that the indices are
      sorted in ascending order, which can lead to more efficient execution on some
      backends. If set to True and indices are not sorted, the output is undefined.

  Returns:
    Array of values extracted from ``a``.

  See also:
    - :attr:`jax.numpy.ndarray.at`: take values via indexing syntax.
    - :func:`jax.numpy.take_along_axis`: take values along an axis

  Examples:
    >>> x = jnp.array([[1., 2., 3.],
    ...                [4., 5., 6.]])
    >>> indices = jnp.array([2, 0])

    Passing no axis results in indexing into the flattened array:

    >>> jnp.take(x, indices)
    Array([3., 1.], dtype=float32)
    >>> x.ravel()[indices]  # equivalent indexing syntax
    Array([3., 1.], dtype=float32)

    Passing an axis results ind applying the index to every subarray along the axis:

    >>> jnp.take(x, indices, axis=1)
    Array([[3., 1.],
           [6., 4.]], dtype=float32)
    >>> x[:, indices]  # equivalent indexing syntax
    Array([[3., 1.],
           [6., 4.]], dtype=float32)

    Out-of-bound indices fill with invalid values. For float inputs, this is `NaN`:

    >>> jnp.take(x, indices, axis=0)
    Array([[nan, nan, nan],
           [ 1.,  2.,  3.]], dtype=float32)
    >>> x.at[indices].get(mode='fill', fill_value=jnp.nan)  # equivalent indexing syntax
    Array([[nan, nan, nan],
           [ 1.,  2.,  3.]], dtype=float32)

    This default out-of-bound behavior can be adjusted using the ``mode`` parameter, for
    example, we can instead clip to the last valid value:

    >>> jnp.take(x, indices, axis=0, mode='clip')
    Array([[4., 5., 6.],
           [1., 2., 3.]], dtype=float32)
    >>> x.at[indices].get(mode='clip')  # equivalent indexing syntax
    Array([[4., 5., 6.],
           [1., 2., 3.]], dtype=float32)
  N)r  r  rZ  )_taker   r   )r   r  rb  r   r   r  r  rZ  s           rK   r  r    sA    d 
q'4<44X^D5I5I3NGY$
& 
& 
& &rL   )rb  r   r  r  rZ  c                "   |t          d          t          j        d| |           t          |           } t          |          }|t	          |           } d}nt          |t          |                     }||dk    r5t          j        j	        }	t          |dk     || j        |         z   |          }n|dk    rt          d          |dk    r@t          j        |t          || j        |                             }t          j        j        }	n+|dk    rt          j        j        }	nt#          d	| d
          t%          t          |                    }
t'          t          |                     }||         dk    r|j        dk    rt+          d          | S |j        dk    r?|d |         t'          |j                  z   ||dz   d          z   }t-          | d|          S d||<   t          j        t1          t'          t3          |                    t'          t3          ||
z   t%          | j                  |
z   dz
                      z             |f|f          }t          j        | |d         |t1          |          |	|||          S )Nz0The 'out' argument to jnp.take is not supported.r  r   fillr  z.The 'raise' mode to jnp.take is not supported.r  r   zInvalid mode 'z' for np.takez4Cannot do a non-empty jnp.take() from an empty axis.r   r)  offset_dimscollapsed_slice_dimsstart_index_mapr;  )rv  slice_sizesr   r  r  rZ  )r   r*   r   rS   r  rO  rE   r   GatherScatterModeFILL_OR_DROPr   r?   r)   r  r   PROMISE_IN_BOUNDSCLIPr   r   rH   r  
IndexErrorr?  GatherDimensionNumbersrG   r   gather)r   r  rb  r   r   r  r  rZ  axis_idxgather_mode
index_dimsr  rd  dnumss                 rK   r  r  @  s    	_
P
Q
QQvq'***ajj!G'	\aAHH!$Q00H	\TV^^'4KGaK178+<!<gFFGGw
N
O
OOv~~j*Wagh6G"H"HIIG'9KKv~~',KK
9d999
:
::5>>""*U1XX+a|qMNNNH\QYhY'$w}*=*==X\]]+,IQ+++++h

$
5??
5J&AGz(AA(EFFGGHI I #K! ! !% 
Awy)U %k 2 2$^'9j
R 
R 
R RrL   c                   t          t          |           t          j                  r| S t	          j        |          rt          | |          }n4t          j        t	          j	        |          t          |                     }t          | t          t          j        f          r| dk     rt          j        | |          n| S t          j        | dk     t          j        | |          |           S )zCNormalizes an index value in the range [-N, N) to the range [0, N).r   )rT   r[   r}   unsignedintegerr   r  r   r   r  dimension_as_valuerF   r^   r   r  rq  )r   r8  axis_size_vals      rK   _normalize_indexr  w  s    ur122 L	)$$ <ui00MM,T-DY-O-O-3E]]< <MRZ()) G,1AII375-(((5@:eai!>!>FFFrL   )rb  r   rZ  "str | lax.GatherScatterMode | Nonec                   t          j        d| |           t          |           }t          j        |          }t          |          }t          j        |t                    st          d|           |Mt          |          dk    r$d}t          |                    |                    |                                }d}|j	        }	|	t          |          k    r7d}t          |                    t          |          |j	                            t          ||	          fd}
t          d	 |j        D                       }t	          |rt          nt                     }t#          j        ||          }|j                 } |
|j        d          }t#          j        ||          }|dk    rt)          ||j                  S fd
t+          |          D             }t-          t/          j        |          |                   dz   }g }g }g }g }g }d}t3          |	          D ]}|k    r}t5          ||          }|                    t#          j        ||                     |                    d           |                    |           |                    |           |dz  }t;          j        ||         d          r1|                    |           |                    ||                    t;          j        ||         d          rj|                    t)          ||                     |                    d           |                    |           |                    |           |dz  }Wt#          j        |||          }|                    |           |                    d           |                    |           |                    |           |dz  }t#          j         ||          }t#          j!        t-          |          t-          |          t-          |                    }t#          j"        |||t-          |          |dn||          S )a
  Take elements from an array.

  JAX implementation of :func:`numpy.take_along_axis`, implemented in
  terms of :func:`jax.lax.gather`. JAX's behavior differs from NumPy
  in the case of out-of-bound indices; see the ``mode`` parameter below.

  Args:
    a: array from which to take values.
    indices: array of integer indices. If ``axis`` is ``None``, must be one-dimensional.
      If ``axis`` is not None, must have ``a.ndim == indices.ndim``, and ``a`` must be
      broadcast-compatible with ``indices`` along dimensions other than ``axis``.
    axis: the axis along which to take values. If not specified, the array will
      be flattened before indexing is applied.
    mode: Out-of-bounds indexing mode, either ``"fill"`` or ``"clip"``. The default
      ``mode="fill"`` returns invalid values (e.g. NaN) for out-of bounds indices.
      For more discussion of ``mode`` options, see :attr:`jax.numpy.ndarray.at`.

  Returns:
    Array of values extracted from ``a``.

  See also:
    - :attr:`jax.numpy.ndarray.at`: take values via indexing syntax.
    - :func:`jax.numpy.take`: take the same indices along every axis slice.

  Examples:
    >>> x = jnp.array([[1., 2., 3.],
    ...                [4., 5., 6.]])
    >>> indices = jnp.array([[0, 2],
    ...                      [1, 0]])
    >>> jnp.take_along_axis(x, indices, axis=1)
    Array([[1., 3.],
           [5., 4.]], dtype=float32)
    >>> x[jnp.arange(2)[:, None], indices]  # equivalent via indexing syntax
    Array([[1., 3.],
           [5., 4.]], dtype=float32)

    Out-of-bound indices fill with invalid values. For float inputs, this is `NaN`:

    >>> indices = jnp.array([[1, 0, 2]])
    >>> jnp.take_along_axis(x, indices, axis=0)
    Array([[ 4.,  2., nan]], dtype=float32)
    >>> x.at[indices, jnp.arange(3)].get(
    ...     mode='fill', fill_value=jnp.nan)  # equivalent via indexing syntax
    Array([[ 4.,  2., nan]], dtype=float32)

    ``take_along_axis`` is helpful for extracting values from multi-dimensional
    argsorts and arg reductions. For, here we compute :func:`~jax.numpy.argsort`
    indices along an axis, and use ``take_along_axis`` to construct the sorted
    array:

    >>> x = jnp.array([[5, 3, 4],
    ...                [2, 7, 6]])
    >>> indices = jnp.argsort(x, axis=1)
    >>> indices
    Array([[1, 2, 0],
           [0, 2, 1]], dtype=int32)
    >>> jnp.take_along_axis(x, indices, axis=1)
    Array([[3, 4, 5],
           [2, 6, 7]], dtype=int32)

    Similarly, we can use :func:`~jax.numpy.argmin` with ``keepdims=True`` and
    use ``take_along_axis`` to extract the minimum value:

    >>> idx = jnp.argmin(x, axis=1, keepdims=True)
    >>> idx
    Array([[1],
           [0]], dtype=int32)
    >>> jnp.take_along_axis(x, idx, axis=1)
    Array([[3],
           [2]], dtype=int32)
  take_along_axisz5take_along_axis indices must be of integer type, got Nr   z=take_along_axis indices must be 1D if axis=None, got shape {}r   zBindices and arr must have the same number of dimensions; {} vs. {}c                J    t          |           }||<   t          |          S r`   )rH   rG   )r  r   lstaxis_ints      rK   r  z take_along_axis.<locals>.replace  s#    
s))CCM::rL   c              3  L   K   | ]}t          j        |           p|d k    V   dS rd  Nr   r  r  s     rK   r,  z"take_along_axis.<locals>.<genexpr>  s9      WW!D0333EqW~WWWWWWrL   c                P    g | ]"\  }}|k    st          j        |d            |#S r   )r   r  )r*  rD  rp  r  s      rK   r2  z#take_along_axis.<locals>.<listcomp>  s5    kkkfaXTMbcfhiMjMjrL   r   rn   r&  r  r  )r   rZ  )#r*   r   rS   r   rP   r?   rT   r   rx   rE   r   r   r  rO  r6  r  r  r   r  rx  r  r  rG   r}   r  r   r  r8  r=  r   r  r  r  r  r  )r  r  rb  r   rZ  r   index_dtype	idx_shapern  r  r  rh  r8  r+  rd  r  gather_index_shaper  r  r  r  r  r  rD  r  gather_indices_arrr  r  s                              @rK   r  r    s   ^ (#w777cll!W%%+Gnn)		;	0	0 &
 %"% % & & &	\G}}Kcszz),,---			AD	
$	T']]
NC
SZZWqv66
7
77d++(    
 WWqwWWWWW/9eeE::+$Wk::'gh)gagq!!)"9i88)!^^AG$$$kkkk	) 4 4kkk*RXi00<==D.++/!;;  aH}} )44gCK1CDDEEEQ!!!$$$1faa		y|Q	/	/  1&&&&		y|Q	/	/  E"4KHHHIIIQ!!!$$$1faa
 !+/A1EEdD!!!Q!!!$$$1faa~CCC

$k""344/**, , ,% 
A)5%2D2D#'<Tj
R 
R 
R RrL   rp  c                    t          | t          t          j        f          o!t          | t          t          j        f           S r`   )rF   r^   r}   r   rN   r  rp  s    rK   _is_integer_indexr  +  s2    	C#rz*	+	+	UJsT28DT4U4U0UUrL   c                    t          | t                    o:| j        | j        cxu od u nc o$t          | j        t
                    o
| j        dk    S )Nr   )rF   r   r  r@  r  r^   r  s    rK   _is_simple_reverse_slicer  .  s^    
S%
 
  7
)sx
'
'
'
'4
'
'
'
'7
SXs
#
#7(+B8rL   c                   |dk    rdS t          |           r| | cxk    o|k     nc S 	 t          j        |           t          |           }}n#  Y dS xY w|dk    r#t          j        |t          j                  r|dv S dS )Nr   Frj   )Npromise_inboundsr   )r  r}   r?   r[   rT   r   )rp  r  r   r?   rP   s        rK   !_is_valid_integer_index_for_slicer  3  s    	QYY5s 5C$8C==&++5EE55
b[[R]5"*55[555	s   #A Ac                    t          | t                    oa| j        d u pt          | j                  oD| j        d u pt          | j                  o'| j        d u pt          | j                  o
| j        dk    S Nr   )rF   r   r  r  r@  r  r  s    rK   _is_contiguous_slicer  A  s    
S%
 
  P9< 1#) < <P8t:0::P 8tN 1#( ; ; MAQrL   Array | Nonec                    t          t                    rnft          d  j        D                       sd S t	                     j        k    rd S t          d D                       rd S t          d D                       rd S t          d D                       rt           j                  d t                    D             fdt          t           j                            D             }d t                    D             }t           t                    ot          j         j                   }t           fd	|D                       }|r|s|rd S t	                    t	          |          z   t	          |          z   t	                    k    rd S rOt          j         t                               t          fd
t                    D                       |z  }|s|s S  j        t	                    z
  t!          d           fz  z  g }g }t#           j                  D ]\  }	}
t          |	t                     r]|	                    |
          \  }}}|dk    sJ |                    |           |                    t)          d||z
                       wt+          j        t/          |	          t*          j                  sJ t+          j        |	          dk    sJ |                    |	           |                    d           t          d |D                       r>d |D             }d t          ||          D             }t          j         ||           n8t	          |          dk    rt3          j        | }t          j         ||           |r"t          j         t          |                      S )Nc              3  @   K   | ]}t          |t                    V  d S r`   rS  r  s     rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>K  s,      33AZ3333333rL   c              3     K   | ]}|d u V  	d S r`   rj   r  s     rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>O  s&        qd      rL   c              3     K   | ]D}t          |t                    |j        |j        |j        fD ]}t          j        |          V  Ed S r`   )rF   r   r  r@  r  r   r  r*  rD  r  s      rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>R  st       	/ 	/Au--	/Wafaf-	/ 	/ 
	c	"	" 	/ 	/ 	/ 	/ 	/ 	/ 	/rL   c              3  (   K   | ]}|t           u V  d S r`   Ellipsisr  s     rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>W  s&      $$1h$$$$$$rL   r  c                6    h | ]\  }}t          |          |S rj   )r  r*  rD  inds      rK   r  z4_attempt_rewriting_take_via_slice.<locals>.<setcomp>[  s*    QQQvq#3KC3P3PQQQQrL   c                B    h | ]\  }\  }}t          ||          |S rj   )r  )r*  rD  r  r  r   s       rK   r  z4_attempt_rewriting_take_via_slice.<locals>.<setcomp>\  sH     H H H~q+35c4FFH H H HrL   c                6    h | ]\  }}t          |          |S rj   )r  r  s      rK   r  z4_attempt_rewriting_take_via_slice.<locals>.<setcomp>^  s*    SSSVQ9Mc9R9RSqSSSrL   c              3     K   | ]<}|                              j        |                   d j        |         dfk    V  =dS r  )r  r?   )r*  rD  r  rp  s     rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>f  s_       7 7  q6>>#)A,77Asy|Q;OO 7 7 7 7 7 7rL   c              3  H   K   | ]\  }}|v rt          d           n|V  d S r`   r[  )r*  rD  r  simple_revss      rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>p  sO       . .As  !K//dS . . . . . .rL   r   r   rj   c              3  d   K   | ]+}t          |t          t          j        f          o|d k    V  ,dS r  )rF   r^   r}   r   r  s     rK   r,  z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s<      LLARZ(	)	)	4a1fLLLLLLrL   c                ,    g | ]}t          |          S rj   )r^   r  s     rK   r2  z5_attempt_rewriting_take_via_slice.<locals>.<listcomp>  s    777AQ777rL   c                    g | ]
\  }}||z   S rj   rj   )r*  rD  r  s      rK   r2  z5_attempt_rewriting_take_via_slice.<locals>.<listcomp>  s     OOO41aQOOOrL   )start_indiceslimit_indices)r  r  )rF   rG   r  r?   r   rE   r6  _canonicalize_tuple_indexr  r  r    r   is_single_device_shardingr  r   rm  r   r7   r  r8  r   r}   rT   r[   r   r*   r   dynamic_slicer  )r  rp  r   int_indicescontiguous_slices
is_shardedhas_partial_slicesr  r  r  r  r  r@  r  int_start_indicesint_limit_indicesr  s   ```             @rK   !_attempt_rewriting_take_via_slicer  G  s   #u%%1C6#	33333	3	3 4XX4  C      4 	/ 	/	/ 	/ 	/ / /  4$$$$$$$ 7
#CH#
6
6
6CQQ3QQQ+H H H H3sCI3F3F)G)G H H H+SSy~~SSS 3	** E6s|DDD  7 7 7 7 7$57 7 7 7 7 [ $6 4K(((3/@+A+AASXXMM4 %
'#u[))
*
*C
 . . . .'nn. . . . .C$
 + J#(SXX
%++	//#')-!+C++ 
 
ic4#u 	++d++eT4QYYYY5!!!Qu--....]6#;;
33333Xc]]b    3LLmLLLLL C77777OO3/@++N+NOOO
),<MO O OCC
 =A)=9m

=kC C CC /
+c5--
.
.C	*rL   c           
     B   t          | ||          x}|S t          j        j        r| j        dk    rt          j        |          }t          |t
          j                  r|j	        dk    rt          j        |j        t          j                  r[t          j        |j        t          j                  s7t          | j	        d         t                     rt#          j        | |d          S n#  Y nxY wt'          || j	                  \  }}	}
t)          | ||	|
||||          S )Nr   rj   Fr?  )r  r   r  r  rE   r   get_avalrF   DShapedArrayr?   r   rT   rP   r}   r   r  r^   r   dynamic_index_in_dim_split_index_for_jit_gather)r  rp  r  r  r   rZ  r   r'  treedef
static_idxdynamic_idxs              rK   _rewriting_taker    s#    2#sDAAAfNM   BSX\\c"" T4,
-
- B$*2B2B

DJ

3
3 3C
FL99 3C SYq\3
'
' 3C 'S5AAAA DD &:#sy%I%I"':{	gz;8Jz
3 
3 3s   C+ +C/c           
        t          |||          }t          t          |           |          }	| }
|kt          j        d |d           t          j        |          dk    rt          d          t          |t
          j	                  r|
                                }|	j        rt          j        |
|	j                  }
t          j        |	j                  rt!          |
|	j                  S t          j        |	j        j                  s9t          j        |
|	j        |	j        |	j        |p|	j        |p|	j        ||          }
|	j        rt          j        |
|	j                  }
t          |
|	j                  S )Nz$fill_value argument to indexed get()r   z5fill_value argument to indexed get() must be a scalarr)  )r  r  r   rZ  )!_merge_static_and_dynamic_indices_index_to_gatherr?   r   r   r}   rE   r   rF   r   itemscalar_bool_dimsr   r  is_empty_shapeslice_shaper  r  r  r  gather_slice_shaper  r  reversed_y_dimsrm  newaxis_dims)r  r  r  r  r  r  r   rZ  rp  indexerr   s              rK   r  r    sy   )':{KK#U3ZZ--'	!4AC C C	wzaNOOO*bj)) %??$$j 57344A 
,-- 4aw23333 
	W39	:	: (
	0J#=w'=+Iw/IJ		( 	( 	(A  ,7*++A 
Q,	-	--rL   c                  j    e Zd ZU ded<   ded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   dS )_Indexerr  r  r  r-   r  zlax.GatherDimensionNumbersr  rN   r  r  r  r  r  N)rs   rt   ru   rv   rj   rL   rK   r   r     s         ########
  !     "!!!!!rL   r   c                   t          |           } t          d | D                       rt          d|           t          | |          } t	          |           \  }}dgt          |          z  }dgt          |          z  }t          |          D ]F\  }}|t          u r|||<   t          |t                    r|j
        |j        |j        f||<   A|||<   G|t          |          |fS )zmSplits indices into necessarily-static and dynamic parts.

  Used to pass indices into `jit`-ted function.
  c              3  @   K   | ]}t          |t                    V  d S r`   )rF   rA   r  s     rK   r,  z'_split_index_for_jit.<locals>.<genexpr>  s,      ))As		))))))rL   z.JAX does not support string indexing; got idx=N)#_eliminate_deprecated_list_indexingr6  rx   _expand_bool_indicesr   r   r  r  rF   r   r  r@  r  rG   )rp  r?   r)  r  dynamicstaticrD  rM   s           rK   r  r    s    	,C00#))S))))) I
GGG
H
HH 	S%((# %%/&'FS[[ '6CKK&  daH}}fQii	Au		 7AFAF+fQiigajj	%--	((rL   c           	     N   g }t          ||          D ]~\  }}||                    |           t          |t                    r7|                    t	          |d         |d         |d                              i|                    |           |                     |          S )z;Recombines indices that were split by _split_index_for_jit.Nr   r   r   )r  r8  rF   rG   r   	unflatten)r  r  r  rp  r  r  s         rK   r  r    s    
#*k**  da}	jjmmmm	Au		 	jjqtQqT1Q4(())))	jjmmmm			3		rL   c                F    | j          ot          | j        t                    S r`   )r?   rT   rP   r   )r'  s    rK   _intr
    s    Z	;Jtz7;;;rL   x_shapenormalize_indicesc                   &'( t          t                     |          }d t          |          D             }|r_t          d |D                       }t	                      t          |          D ]}                     |d           t                      d}d }g }d }t          |          rd t          |          D             }	d t          |	          D             }
|r fd|
D             }
t          |
 \  }}}t          t          j        t          j        |          dk                        }d}d}d}g }g }g }t          d	  D                       ot          j        j        }|rt"          nt$          'g }g &g }g }g }g }t          |          D ]\  }}||r||d         k    s|s|dk    rt'          | }|d         j        }t          |          }t          &          (|'(fd
|D             z  }&|z  &|                    |           |                    |           |                    |           ||z  }||z  }||v r|dz  }|                    d           	 t/          j        |          }n# t2          $ r d }Y nw xY wt5          |t6          t8          f          rt;          |          rt/          j         |         d          rt?          d| d          |rtA          | |                   n|}tC          j"        |'          }|                    |t          &          f           |                    |           |                    d           |                    |           |dz  }|1|                    d           |                    |           |dz  }t5          |tF                    rt          d |j$        |j%        |j&        fD                       s*d|j$         d|j%         d|j&         d}t?          |          tO          | |                   \  }}}|                    |           t/          j        |d          rt/          j        | |                   sL|                    tC          j"        |'          t          &          f           |                    |           |                    |           |                    |           ntQ          |'          tQ          |'          tC          j)        '|          z  z   } |dk     r+|                    |           tC          j*        | d          } |                    d           |                    | t          &          f           |                    |           &                    |           |                    |           |dz  }|dz  }|dz  }R|dtW          |j,        tZ                    sJtW          |j,        t\                    s0d}t3          |/                    |j,        j0        ||                    t?          d| d|          t          |          dk    rt          j1        d'          }!nt          |          dk    r'|d         \  }"}#tC          j2        |"|"j3        f          }!nEt          &          }$&                    d           tC          j4        &fd|D             |$          }!tC          j5        t          |          t          t          |                    t          |                    }%tm          |t          |          |||%|!|d u |d u |	  	        S )Nc                B    g | ]\  }}t          |t                    |S rj   )rF   rN   )r*  r  rD  s      rK   r2  z$_index_to_gather.<locals>.<listcomp>)  s-    $Y$Y$Y41aZPQSWEXEX$YQ$Y$Y$YrL   c              3     K   | ]<}t          |t                    r!t          j        t	          |                    n|V  =d S r`   )rF   rN   r}   r  r^   r  s     rK   r,  z#_index_to_gather.<locals>.<genexpr>+  sF      MMAZ4%8%8?	#a&&!!!aMMMMMMrL   r   Fc                     g | ]\  }}|||fS r`   rj   r  s      rK   r2  z$_index_to_gather.<locals>.<listcomp>B  s!    GGGtq!QFrL   c              3     K   | ]R\  }\  }}t          |          s't          |t          t          t          j        f          >t          |          ||fV  Sd S r`   )r   rF   r   r,   r}   r   rS   )r*  r  rD  r  s       rK   r,  z#_index_to_gather.<locals>.<genexpr>C  s|       F F&QA	!F"1x
&CDDFqzz1aF F F F F FrL   c              3  R   K   | ]!\  }}}t          ||                   ||fV  "d S r`   )r  )r*  r  rD  r  r  s       rK   r,  z#_index_to_gather.<locals>.<genexpr>G  sR       7 7#Aq! *!WQZ88!Q? 7 7 7 7 7 7rL   r   c              3  L   K   | ]}t          j        |           p|d k    V   dS r  r  r  s     rK   r,  z#_index_to_gather.<locals>.<genexpr>V  s9      GG!D ###5qW~GGGGGGrL   c              3  F   K   | ]}t          j        |          fV  d S r`   )r   r  )r*  r   r  	start_dims     rK   r,  z#_index_to_gather.<locals>.<genexpr>{  sI       4 4 21kBBIN 4 4 4 4 4 4rL   z index is out of bounds for axis z with size 0c              3  4   K   | ]}t          |          V  d S r`   )._is_slice_element_none_or_constant_or_symbolic)r*  r  s     rK   r,  z#_index_to_gather.<locals>.<genexpr>  s?       7 7 @DD 7 7 7 7 7 7rL   zhArray slice indices must have static start/stop/step to be used with NumPy indexing syntax. Found slice(rR  z). To index a statically sized array at a dynamic position, try lax.dynamic_slice/dynamic_update_slice (JAX does not support dynamically sized arrays within JIT compiled functions).rn   r~  r  zdIndexer must have integer or boolean type, got indexer with type {} at position {}, indexer value {}zEIndexing mode not yet supported. Got unsupported indexer at position : c                    g | ]>\  }}t          j        |t          t          |||j        z                                 ?S rj   )r   r  rG   r   rE   )r*  grD  gather_indices_shapes      rK   r2  z$_index_to_gather.<locals>.<listcomp>  sU     ," ," ,"
!Q 
12E%1qv::N:N4O4OPP," ," ,"rL   r  )	r  r  r  r  r  r  r  r  r  )7r  r   r  rG   rH   r!  r"  _is_advanced_int_indexerr  rN   r}   r  r  r6  r   
enable_x64r  r  r  rk  r?   extendr8  r   r  rx   rF   r"   r!   r
  r  r  r  r   r  r   r  r@  r  _preprocess_slicer  r  rm  rT   rP   r   r  r   r  r  r  rE   r  r  r   ))r  rp  r  r  rD  advanced_axes_are_contiguousadvanced_indexesidx_advanced_axesx_advanced_axesidx_no_nonesadvanced_pairsx_axisy_axiscollapsed_y_axisr  r  r  rh  r  r  r  r  r  idx_posr?   rE   
abstract_ii_convertedrn  r  r  
slice_sizer  gather_indices_arrayr  r  last_dimr  r  r  r  s)   `                                     @@@rK   r  r  "  s    	"#g,,44# %Z$Y9S>>$Y$Y$Y 
MMMMM
M
MC7mmG$%%  nnQGnnG "':> &( +//c"" 	QGGy~~GGGLF F*3L*A*AF F FN  77 7 7 7'57 7 7n;>;O8'#'rw7H/I/IQ/N(O(O#P#P &&  "+(*#%/ GGwGGGGG 
  )3e+ -/.$&
  "+ !#, $&/&(cNN b7 b7jgq 	$	% 	%*15Fq5I*I*I) +J.5ll)+;<q!'eZZd*++i 4 4 4 4 4"24 4 4 4ne#_---!!/222nf$ ###kf"""=##jj   jjj *}k:;; A7Z@P@P A7		wv	2	2 RPFPPPQQQ2C
J
1gfo
.
.
.a,Q<<k[#.B*C*CDEEE!!&)))"""V$$$kff	
&!!!kff	Au		 07 7 7Wafaf57 7 7 7 7 	8g8 8)*8 83468 8 8 oo 1!WV_ E EeT:$$$		tQ	'	' ,$ZAA 	)


!9%!M!M #$8 9 9!; < < <

 
 
(
(
(!!*---+,,,,k222[111CH[*4U4UUV!88

 
 !1
2
2
2GG555'!!!$$$w,@(A(ABCCCv&&&##J///##F+++!kfkff

 **G44 !8B:CSUZ8[8[ !?

:#3#8'1EEFFF 6%,6 6016 6 7 7 7 	A&(ht;&G&G&G
>a!DAq?1qvi88'((H"""? ," ," ," ," ," ," ,"  
 
$$$ (<!=!=>>O,,  %
 
|$$)#
'#t+'4/%	
' 	
' 	
' 	's   ,JJJc                    t          | t          j        t          f          rt          j        |           dk    p(t          | t
          t          f          p| t          u p| du S )z/Helper for _eliminate_deprecated_list_indexing.r   N)rF   r}   r   r,   rE   r   r   r  rZ   s    rK   _should_unpack_list_indexr0    s[    
QU+
,
,
@q (He,--((](4i)rL   c                   t          | t                    slt          | t                    rTt          | t          t          j        t          f          s-t          d | D                       rd}nd}t          |          | f} | S )Nc              3  4   K   | ]}t          |          V  d S r`   )r0  r  s     rK   r,  z6_eliminate_deprecated_list_indexing.<locals>.<genexpr>    s+      77a&q))777777rL   zUsing a non-tuple sequence for multidimensional indexing is not allowed; use `arr[tuple(seq)]` instead of `arr[seq]`. See https://github.com/google/jax/issues/4564 for more information.zUsing a non-tuple sequence for multidimensional indexing is not allowed; use `arr[array(seq)]` instead of `arr[seq]`. See https://github.com/google/jax/issues/4564 for more information.)	rF   rG   r   r,   r}   r   rA   r6  rx   )rp  rn  s     rK   r  r    s     
C		 #x   C%S9Q)R)R 
 
773777	7	7 VUU cNNFc	*rL   c                   	 t          j        |           }n# t          $ r d }Y nw xY wt          |t                    rt          |j        t                    p/t          | t                    o| ot          d | D                       S )Nc              3     K   | ]:}t          |          o&t          t          |          t          j                  V  ;d S r`   )
_is_scalarrT   r[   r}   r  r*  r  s     rK   r,  z$_is_boolean_index.<locals>.<genexpr>   sV       /: /:23 0:!}} 0.BH--/: /: /: /: /: /:rL   )
r   r  rx   rF   r!   rT   rP   r  rH   r  )rD  r*  s     rK   _is_boolean_indexr7     s    q!!JJ	   JJJ
Z
-
-
U*Z=Mu2U2U :4   :Q :3 /: /:78/: /: /: ,: ,:;s    &&c           	     .   g }t          |          }t          d | D                       }|dk    rt          d          |dk    rt          d | D                       }d}d}t          |           D ]\  }}	 t	          j        |          }	n# t          $ r d}	Y nw xY wt          |          rt          |t                    r#t          |          }t	          j        |          }	t          |	          t          urt          j        |	          t          |          dk    r#|                    t#          |                     nt%          |          }
t          |          |z   |z
  }|||t          |          z            }|
|k    rt          d| d|
 d	|           |                    t)          j        |                     n|                    |           |t,          u rt          |          |z
  dz
  }||dz  }t/          |          S )
z=Converts concrete bool indexes into advanced integer indexes.c              3  (   K   | ]}|t           u V  d S r`   r  r6  s     rK   r,  z'_expand_bool_indices.<locals>.<genexpr>   s&      00qQ(]000000rL   r   z0an index can only have a single ellipsis ('...')c              3  l   K   | ]/}||t           ut          |          rt          |          ndV  0d S r  )r  r7  r   r6  s     rK   r,  z'_expand_bool_indices.<locals>.<genexpr>   sS       = =!8*;*; "31!5!5<U1XXX1*;*;*;*;= =rL   r   Nz<boolean index did not match shape of indexed array in index z: got z, expected )r   r  r  r  r   r  rx   r7  rF   rH   r  rQ   r"   r   NonConcreteBooleanIndexErrorr   r8  rN   r  r  r}   r   r  rG   )rp  r?   r   
total_dimsnum_ellipsisellipsis_offsetnewaxis_offset
dim_numberrD  r*  i_shaper  expected_shapes                rK   r  r     sW   
#5zz*00C00000,A
G
H
HHq = =c = = = = =J/. ~~  mj!=##jj   jjj 	At		 &!HH]1%%
*..1*===88q==

477))C?*^;ueeAhh&667n$$ U(U U07U UDRU U V V V

28A;;	jjmmmH}}E

Z/!3oyn	ss   9BBBc                    | dS t          j        |           rdS 	 t          t          j        |                     t          u S # t
          $ r Y dS w xY w)z)Return True if elt is a constant or None.NTF)r   r  rQ   r  r"   rx   )r  s    rK   r  r  B   sd    [	#+ttc""##}44	   55s   'A 
AAc                    t          | t                    sJ t          d | D                       rdS t          d | D                       S )zGReturns True if idx should trigger int array indexing, False otherwise.c              3     K   | ]\}|d u pS|t           u pJt          |t                    p5t          |          o&t	          t          |          t          j                  V  ]d S r`   )r  rF   r   r5  rT   r[   r}   r   r6  s     rK   r,  z+_is_advanced_int_indexer.<locals>.<genexpr>P   s       	N 	NDE 
d 
@a8m 
@z!U';'; 
@qMM?jBJ??	N 	N 	N 	N 	N 	NrL   Fc              3  x   K   | ]5}|d u p,|t           u p#t          |t                    pt          |          V  6d S r`   )r  rF   r   _is_int_arrayliker6  s     rK   r,  z+_is_advanced_int_indexer.<locals>.<genexpr>S   sf       3 3)* $Y %!x- %:a+?+? %!!$$3 3 3 3 3 3rL   )rF   rG   r  r  s    rK   r  r  L   s     
C		 	N 	NIL	N 	N 	N N N 5	 3 3.13 3 3 
3 
3 3rL   c                   t          | t                    rt          | t                     p]t          t	          | dd          t
          j                  p4t          | t          t          f          ot          d | D                       S )zDReturns True if x is array-like with integer dtype, False otherwise.rP   Nc              3  4   K   | ]}t          |          V  d S r`   )rG  r6  s     rK   r,  z$_is_int_arraylike.<locals>.<genexpr>Z   s+      1R1R12CA2F2F1R1R1R1R1R1RrL   )
rF   r^   rN   rT   rI   r}   r   rH   rG   r  rZ   s    rK   rG  rG  V   s|    
Q


8Z4%8%8!8 S7D112:>>SD%=))Rc1R1RPQ1R1R1R.R.RTrL   c                    t          j        |           p8t          | t           j        t          f          ot          j        |           dk    S )z#Checks if a Python or NumPy scalar.r   )r}   r   rF   r   r,   rE   rZ   s    rK   r5  r5  \   s>    
+a.. 2ZBJ+>?? 1!#q2rL   c           	        t          d |D                       }|| k    rt          d| d| d|  d          d t          |          D             }t          |d          }|ut          |d          3t          dt	          t          t          |                     d          t          d          f| |z
  z  }|d|         |z   ||d	z   d         z   }n.|| k     r(t          d          f| |z
  z  }t          |          |z   }|S )
zGHelper to remove Ellipsis and add in the implicit trailing slice(None).c              3  \   K   | ]'}|d u p|t           u pt          |t                     V  (d S r`   )r  rF   rN   r6  s     rK   r,  z,_canonicalize_tuple_index.<locals>.<genexpr>c   sC      ee\]Q$Y%V!x-%V:aQUCVCV WeeeeeerL   zToo many indices for r  z# non-None/Ellipsis indices for dim r   c              3  2   K   | ]\  }}|t           u |V  d S r`   r  r  s      rK   r,  z,_canonicalize_tuple_index.<locals>.<genexpr>h   s*      @@FAsxa@@rL   Nz'Multiple ellipses (...) not supported: r   )	r  r  r  r  rH   r  rQ   r   rG   )arr_ndimrp  
array_namenum_dimensions_consumedellipsesellipsis_indexcolonss          rK   r  r  a   s[   eeadeeeeex''
	9
 	9 	9.E 	9 	9-5	9 	9 	9: : : A@inn@@@($''.Hd'
KDT34H4H
K
K
KM M MDkk^x*AABF
o~o

'#nq.@.A.A*B
BCC))Dkk^x*AABF
**v
C	*rL   r  r   r8  core.DimSize/tuple[core.DimSize, core.DimSize, core.DimSize]c                   dd}| j          || j                   nd}	 |dk    rt          d          |dk    n5# t          j        $ r#}t          j        d	| d
d| z             d}~ww xY wdfd}| j        
rdndz
  }n | || j                  d          }| j        rnd}n | || j                  d          }r|n| }r||z
  n||z
  }	t          j        d|	|z   dz
            |z  }
|||
fS )z=Computes the start index, step, and size of the slice `x[s]`.r  r/   rB   c                >    	 t          j        |           S #  | cY S xY wr`   )r   r   )r  s    rK   convert_to_indexz+_preprocess_slice.<locals>.convert_to_index}   s)    ^Ahhhs    Nr   r   zslice step cannot be zeroz.In slice with non-constant elements the step (r  r  rD  whichrA   c                J   	 | dk    }n8# t           j        $ r&}t          j        d| d|  dd| z             d }~ww xY w|r/rt          j        |           S t          j        dz
  |           S rt          j        d| z             S t          j        d| z             S )Nr   z(In slice with non-constant elements the z (r  z/be resolved statically if it is >= 0.
Details: r   r   )r   r:  min_dimr  )rD  rY  i_ge_0r  r8  r  s       rK   clamp_indexz&_preprocess_slice.<locals>.clamp_index   s    BQff. B B B/
HU
H
Ha
H
H
H
@Q
@
@AB B BB  	/	 .|Iq)))|IM1---	 /|Ay1}---|B	A...s   
 ?!:?r  r   r@  )r  r/   rB   r/   )rD  r/   rY  rA   )r  r   r   r:  r  r@  r  )r  r8  rX  r  r  r]  r  r@  r  r  r,  r  s    `         @rK   r  r  u   s       &'V%7		!&	!	!	!Q$Fqyy2333II		, F F F

-FFFFDDD	EF F FF
/ / / / / / /$ W_-AA	AEEK((117;;EV^!)99rDD;''//88D%v#(<dUllut|(|Ax#~122c9*	j	  s   = A/A**A/c                h   t          j        t          | d          } t          j        t
                    }| dk    rt          | |          S t          j        ||           }ddt          j
        dt          z  |z  | dz
  z            z  z
  dt          j
        dt          z  |z  | dz
  z            z  z   S )NzM argument of jnp.blackmanr   gzG?r   r   g{Gz?r^  r   r   r^   r   r   r   rN  r   r  r)   cospiry  rP   r  s      rK   blackmanrc     s    
S!%ABB!

#F
+
+%!VV5>>	hua!	fjR!q1u!5666	6
1r6TU:YZ]^Y^K_@`@`9`	``rL   c                   t          j        t          | d          } t          j        t
                    }| dk    rt          | |          S t          j        ||           }dt          j
        d|z  dz   | z
            | dz
  z  z
  S )NzM argument of jnp.bartlettr   r   )r   r   r^   r   r   r   rN  r   r  r)   r0  rb  s      rK   bartlettre     sy    
S!%ABB!

#F
+
+%!VV5>>	hua!	
VZA	A&&!a%0	00rL   c                   t          j        t          | d          } t          j        t
                    }| dk    rt          | |          S t          j        ||           }ddt          j
        dt          z  |z  | dz
  z            z  z
  S )NzM argument of jnp.hammingr   gHzG?gq=
ףp?r   r_  rb  s      rK   hammingrg     sz    
S!%@AA!

#F
+
+%!VV5>>	hua!	vz!b&1*A"6777	77rL   c                   t          j        t          | d          } t          j        t
                    }| dk    rt          | |          S t          j        ||           }ddt          j
        dt          z  |z  | dz
  z            z
  z  S )NzM argument of jnp.hanningr   r   r   r_  rb  s      rK   hanningri     sz    
S!%@AA!

#F
+
+%!VV5>>	hua!	FJq2vzQU3444	55rL   betac                P   t          j        t          | d          } t          j        t
                    }| dk    rt          | |          S t          j        ||           }d| dz
  z  }t          |t          j        d||z
  |z  dz  z
            z            t          |          z  S )NzM argument of jnp.kaiserr   r   r   )r   r   r^   r   r   r   rN  r   r  r  r)   sqrt)ry  rj  rP   r  alphas        rK   kaiserrn     s    
S!%?@@!

#F
+
+%!VV5>>	hua!
Q-%	D6;qQY%$7A#==>>>	?	?"T((	JJrL   c                <    | \  }}t          j        |dk              S r  r  r  r   r   s      rK   _gcd_cond_fnrq     s    &"b	a	 	  rL   c           	         | \  }}t          |dk    ||          t          |dk    t          j        ||          t          |d                    }}t          ||k     ||          t          ||k     ||          fS r  )r   r   remr   rp  s      rK   _gcd_body_fnrt     sw    &"b"'2r"""'372r??Jr1,=,=>> 	"
RR
 
 %RR"8"8	99rL   c                |   t          j        d| |           t          j        | |          \  } }t          t	          |           t
                    st          d          t          | |          \  } }t          j	        t          t          t          j        |           t          j        |          f          \  }}|S )Ngcdz,Arguments to jax.numpy.gcd must be integers.)r*   r   r   rT   r[   r   r   rk  r   
while_looprq  rt  r)   r0  )r   r   rv  r  s       rK   rv  rv     s     ub"%%%r2&&&"b	F2JJ	(	( E
C
D
DDB##&"b>,vz"~~vzRT~~6VWW&#q	*rL   c                   t          j        d| |           t          j        | |          \  } }t          j        |           t          j        |          }} t          t          |           t                    st          d          t          | |          }t          |dk    t          |d          t          j        | t          j        ||                              S )Nlcmz,Arguments to jax.numpy.lcm must be integers.r   )r*   r   r   r)   r0  rT   r[   r   r   rv  r   r   r  floor_divide)r   r   r  s      rK   ry  ry     s     ub"%%%r2&&&"b:b>>6:b>>b"	F2JJ	(	( E
C
D
DD	"bkk!	qAvz!Q''r6#6r1#=#=>>
@ 
@ @rL   c                   t          j        d| ||           t          t          |           t          |          ||          S )a  Return the elements of an array that satisfy a condition.

  JAX implementation of :func:`numpy.extract`.

  Args:
    condition: array of conditions. Will be converted to boolean and flattened to 1D.
    arr: array of values to extract. Will be flattened to 1D.
    size: optional static size for output. Must be specified in order for ``extract``
      to be compatible with JAX transformations like :func:`~jax.jit` or :func:`~jax.vmap`.
    fill_value: if ``size`` is specified, fill padded entries with this value (default: 0).

  Returns:
    1D array of extracted entries . If ``size`` is specified, the result will have shape
    ``(size,)`` and be right-padded with ``fill_value``. If ``size`` is not specified,
    the output shape will depend on the number of True entries in ``condition``.

  Notes:
    This function does not require strict shape agreement between ``condition`` and ``arr``.
    If ``condition.size > arr.size``, then ``condition`` will be truncated, and if
    ``arr.size > condition.size``, then ``arr`` will be truncated.

  See also:
    :func:`jax.numpy.compress`: multi-dimensional version of ``extract``.

  Examples:
     Extract values from a 1D array:

     >>> x = jnp.array([1, 2, 3, 4, 5, 6])
     >>> mask = (x % 2 == 0)
     >>> jnp.extract(mask, x)
     Array([2, 4, 6], dtype=int32)

     In the simplest case, this is equivalent to boolean indexing:

     >>> x[mask]
     Array([2, 4, 6], dtype=int32)

     For use with JAX transformations, you can pass the ``size`` argument to
     specify a static shape for the output, along with an optional ``fill_value``
     that defaults to zero:

     >>> jnp.extract(mask, x, size=len(x), fill_value=0)
     Array([2, 4, 6, 0, 0, 0], dtype=int32)

     Notice that unlike with boolean indexing, ``extract`` does not require strict
     agreement between the sizes of the array and condition, and will effectively
     truncate both to the minimum size:

     >>> short_mask = jnp.array([False, True])
     >>> jnp.extract(short_mask, x)
     Array([2], dtype=int32)
     >>> long_mask = jnp.array([True, False, True, False, False, False, False, False])
     >>> jnp.extract(long_mask, x)
     Array([1, 3], dtype=int32)
  extreactrY  )r*   r   compressr  )r[  r  r  rZ  s       rK   extractr~  !  sA    r z9c:>>>	%	""E#JJTj	Q	Q	QQrL   )r  rZ  r   c               ^   t          j        d| ||           t          |                               t                    }|t          d          |j        dk    rt          d          |d}t          |          }nt          ||d          }|d|j
        d                  ||j
        d         d         }}|d|j
        d                  }|,t          j        |          rt          d          ||         }	nd|cxk    r|j
        d         k    s"n t          d|d	|j
        d                    t          |t          d|j                            }
t          |
|t!          ||j        
                    }|t%          |dd                   d|         }	t          |	d|          S )a	  Compress an array along a given axis using a boolean condition.

  JAX implementation of :func:`numpy.compress`.

  Args:
    condition: 1-dimensional array of conditions. Will be converted to boolean.
    a: N-dimensional array of values.
    axis: axis along which to compress. If None (default) then ``a`` will be
      flattened, and axis will be set to 0.
    size: optional static size for output. Must be specified in order for ``compress``
      to be compatible with JAX transformations like :func:`~jax.jit` or :func:`~jax.vmap`.
    fill_value: if ``size`` is specified, fill padded entries with this value (default: 0).
    out: not implemented by JAX.

  Returns:
    An array of dimension ``a.ndim``, compressed along the specified axis.

  See also:
    - :func:`jax.numpy.extract`: 1D version of ``compress``.
    - :meth:`jax.Array.compress`: equivalent functionality as an array method.

  Notes:
    This function does not require strict shape agreement between ``condition`` and ``a``.
    If ``condition.size > a.shape[axis]``, then ``condition`` will be truncated, and if
    ``a.shape[axis] > condition.size``, then ``a`` will be truncated.

  Examples:
    Compressing along the rows of a 2D array:

    >>> a = jnp.array([[1,  2,  3,  4],
    ...                [5,  6,  7,  8],
    ...                [9,  10, 11, 12]])
    >>> condition = jnp.array([True, False, True])
    >>> jnp.compress(condition, a, axis=0)
    Array([[ 1,  2,  3,  4],
           [ 9, 10, 11, 12]], dtype=int32)

    For convenience, you can equivalently use the :meth:`~jax.Array.compress`
    method of JAX arrays:

    >>> a.compress(condition, axis=0)
    Array([[ 1,  2,  3,  4],
           [ 9, 10, 11, 12]], dtype=int32)

    Note that the condition need not match the shape of the specified axis;
    here we compress the columns with the length-3 condition. Values beyond
    the size of the condition are ignored:

    >>> jnp.compress(condition, a, axis=1)
    Array([[ 1,  3],
           [ 5,  7],
           [ 9, 11]], dtype=int32)

    The optional ``size`` argument lets you specify a static output size so
    that the output is statically-shaped, and so this function can be used
    with transformations like :func:`~jax.jit` and :func:`~jax.vmap`:

    >>> f = lambda c, a: jnp.extract(c, a, size=len(a), fill_value=0)
    >>> mask = (a % 3 == 0)
    >>> jax.vmap(f)(mask, a)
    Array([[ 3,  0,  0,  0],
           [ 6,  0,  0,  0],
           [ 9, 12,  0,  0]], dtype=int32)
  r}  Nz4The 'out' argument to jnp.compress is not supported.r   zcondition must be a 1D arrayr   z1condition contains entries that are out of boundszPsize must be positive and not greater than the size of the array axis; got size=z for a.shape[axis]=rn   T)rV  rW  )r*   r   rS   r   rN   r   rE   r   r  r  r?   r(   r6  r  r   r   r  rP   r`  )r[  r   rb  r  rZ  r   condition_arrr  extrar   r  s              rK   r}  r}  D!  s   D z9a<<<)$$++D11-_
T
U
UU1
3
4
44	\D
((CC
1dA

C&}	!}5}SYq\]]7S-#] ##$#	\~e LJKKKFF$$$$	!$$$$
 F!F F7:y|F F G G G }eAsx&8&899D
c539===
>
>CtEEEFuuMF	&!T	"	""rL   )rowvarbiasddofr  r  r  fweightsaweightsc                   |4t          j        d| |          \  } }|j        dk    rt          d          nt          j        d|           \  } | j        dk    rt          d          t	          |           }|s|j        d         dk    r|j        }|j        d         dk    r#t          g                               dd          S |<t	          |          }|s|j        d         dk    r|j        }t          ||fd          }|
|dk    rdnd}d }	|t          j
        d|           t          |          dk    rt          d          t          |          d         |j        d         k    rt          d	          t          t          |          t                    st          d
          t!          t#          j        |                    }	|t          j
        d|           t          |          dk    rt          d          t          |          d         |j        d         k    rt          d          t#          j        |          }|	t!          |          n|	t!          |          z  }	t'          j        |d|	d          \  }
}|d         }|	|j        d         |z
  }n1|dk    r|}n(|||z
  }n ||t'          j        |	|z            z  |z  z
  }||
d d d f         z
  }|	|j        n!|t-          j        |	|j                  z  j        }t#          j        t3          ||                                          |                                          S )Ncovr   zy has more than 2 dimensionszm has more than 2 dimensionsr   r   rh  z'cannot handle multidimensional fweightsz,incompatible numbers of samples and fweightszfweights must be integer.z'cannot handle multidimensional aweightsz,incompatible numbers of samples and aweightsT)rb  r   returned)r*   r-  rE   r   r  r?   r=   r  r=  r  r   RuntimeErrorrT   r[   r   rx   rS   r)   r0  r(   averager  r   broadcast_to_ranktrue_dividerr  r   r  )rZ  r   r  r  r  r  r  Xr  wavgw_sumr  X_Ts                 rK   r  r  !  sJ    ]$UAq11DAqvzz5666  
	"5!	,	,BAVaZZ
3
4
44mm!	 AGAJ!OO	AWQZ1__99Q"""]qMME ek!n))geQJQ'''A	\		11qD!)))H~~BCCCXqQWQZ''GHHHfX&&00 31222
8$$%%A)))H~~BCCCXqQWQZ''GHHHz(##HYA0A0A,AA!!!QFFF*#u
(%Y	
TAAqyyAAAAz~a(l333e;;A#aaag,!yq3#8AF#C#CCF#		C388::..	2	2	:	:	<	<<rL   )r  c                h   t          j        d|            t          | ||          }t          t	          |                    dk    rt          j        ||          S t          |          }t          j        t          j	        |                    
                    |j                  }||d d d f         z  |d d d f         z  }t          t          j	        |          dd          }t          |          r9t          t          j        |          dd          }t          j        ||          }n|}|S )Ncorrcoefr   r   r   )r*   r   r  r   r?   r)   divider?  rl  r  r   rP   r   rW   rv  r   r  )rM   r   r  r  r  stddev	real_partcomplex_parts           rK   r  r  !  s    z1%%%	!Q!q]]a=A
1gg!;v{1~~&&--ag66&&D/F47O+!6;q>>2q)))!__ AA..LI|,,AAA	
(rL   >   r   r   r  r^  excludedunrolled
sorted_arrqueryr  c           	     Z  
 |dk    rt           nt          

fd}t          t          j        t          j        t                    dz                                 } |d           |t                              f}t          j        ||d|| r|nd          \  }}	|d         S )NrB  c                    | \  }}||z   dz  } |                   }t          |||          t          |||          fdfS )Nr   rj   r  )	stater  lowhighmidgo_leftr   r  r  s	         rK   body_funz(_searchsorted_via_scan.<locals>.body_fun!  sW    IC:!
Cb
3((G'3$$eGS$&?&?@"DDrL   r   r   rj   )r5  unroll)	r%   r$   r^   r}   r   log2r   r   scan)r  r  r  r  rP   r  n_levelsinitcarryr  r   s    ``       @rK   _searchsorted_via_scanr  !  s    "fnn2E"E E E E E E E
 Z1!4556677(
%((EE#j//**	+$Xhb)18XXq: : :(%	q/rL   c                (   | j         |j         z   t          j        t          j                  j        k     rt          nt
          fd}|                                }|dk    r. |t          j        || gd                    d |j                  }n- |t          j        | |gd                    | j         d          }t          j	        t          j
        | ||                    t          j        |                                        |          S )Nc                    t          j        t          |                     }t          |          j        t          |                                        |          S r`   )r   r  r   r  r  r`  r  )rM   rp  working_dtypes     rK   _rankz%_searchsorted_via_sort.<locals>._rank"  sB    
(=#a&&
)
)Cc??gajj)--c222rL   rB  r   )r  r}   r   r  r   r  r  r   r  r=  r  r?   r   )r  r  r  rP   r  
query_flatr   r  s          @rK   _searchsorted_via_sortr  
"  s    %?UZ7"(28:L:L:PPP%%V[-3 3 3 3 3 {{}}*	V^^E#/:z":A>>??LEEE#/:z":A>>??
@P@PQE	SWUEE*$5$566	H	H	O	OPU	V	VVrL   c                    |dk    rt           nt          } t          j        |d          | |          }|                    |d          S )NrB  r  rp  r   )rP   rb  )r$   r%   r  r  r  )r  r  r  rP   r   comparisonss         rK   _searchsorted_via_compare_allr  "  sL    "fnn2E"/Y///
EBB+	u1	-	--rL   )r  methodr  )r  sorterr  c                  |t          j        d| |           nt          j        d| ||           |dvrt          |d          |dvrt          |d          t          |           dk    rt          d          t          j        | |          \  } }|| |         } t          |           t          j        t          j                  j	        k    rt          nt          }t          |           d	k    rt          ||
          S t          t          d          t          t          d          t          t          d|         } |t!          |           t!          |          ||          S )a  Perform a binary search within a sorted array.

  JAX implementation of :func:`numpy.searchsorted`.

  This will return the indices within a sorted array ``a`` where values in ``v``
  can be inserted to maintain its sort order.

  Args:
    a: one-dimensional array, assumed to be in sorted order unless ``sorter`` is specified.
    v: N-dimensional array of query values
    side: ``'left'`` (default) or ``'right'``; specifies whether insertion indices will be
      to the left or the right in case of ties.
    sorter: optional array of indices specifying the sort order of ``a``. If specified,
      then the algorithm assumes that ``a[sorter]`` is in sorted order.
    method: one of ``'scan'`` (default), ``'scan_unrolled'``, ``'sort'`` or ``'compare_all'``.
      See *Note* below.

  Returns:
    Array of insertion indices of shape ``v.shape``.

  Note:
    The ``method`` argument controls the algorithm used to compute the insertion indices.

    - ``'scan'`` (the default) tends to be more performant on CPU, particularly when ``a`` is
      very large.
    - ``'scan_unrolled'`` is more performant on GPU at the expense of additional compile time.
    - ``'sort'`` is often more performant on accelerator backends like GPU and TPU, particularly
      when ``v`` is very large.
    - ``'compare_all'`` tends to be the most performant when ``a`` is very small.

  Examples:
    Searching for a single value:

    >>> a = jnp.array([1, 2, 2, 3, 4, 5, 5])
    >>> jnp.searchsorted(a, 2)
    Array(1, dtype=int32)
    >>> jnp.searchsorted(a, 2, side='right')
    Array(3, dtype=int32)

    Searching for a batch of values:

    >>> vals = jnp.array([0, 3, 8, 1.5, 2])
    >>> jnp.searchsorted(a, vals)
    Array([0, 3, 7, 1, 1], dtype=int32)

    Optionally, the ``sorter`` argument can be used to find insertion indices into
    an array sorted via :func:`jax.numpy.argsort`:

    >>> a = jnp.array([4, 3, 5, 1, 2])
    >>> sorter = jnp.argsort(a)
    >>> jnp.searchsorted(a, vals, sorter=sorter)
    Array([0, 2, 5, 1, 1], dtype=int32)

    The result is equivalent to passing the sorted array:

    >>> jnp.searchsorted(jnp.sort(a), vals)
    Array([0, 2, 5, 1, 1], dtype=int32)
  Nr  )rB  r  zK is an invalid value for keyword 'side'. Expected one of ['left', 'right'].)r  scan_unrolledr]  compare_allzl is an invalid value for keyword 'method'. Expected one of ['sort', 'scan', 'scan_unrolled', 'compare_all'].r   za should be 1-dimensionalr   rn   FT)r*   r   r   rE   r   r   r}   r   r  r   r  r  r   r  r  r  rS   )r   r   r  r  r  rP   impls          rK   r  r  "  s   z ^A....Av666	"""
 : : : ; ; ;CCC
 	L 	L 	LM M M 
!WW\\
0
1
11		Q	"	"$!Q	&	Aq66RXbh//333%%%VVq[[au%%%%,e445t<<$2	
 

 
$ 
gajj'!**dE	2	22rL   )r  c                   t          j        d| |           t          j        t          |d          }t          |          }|j        dk    rt          d|          |j        d         dk    rt          | t                    S |sdnd}t          |d	         |d         k    t          || |
          t          |          t          |d d d	         | |
          z
            S )Ndigitizez right argument of jnp.digitize()r   z7digitize: bins must be a 1-dimensional array; got bins=r   rn   r  rB  r   r  )r*   r   r   r   rN   rS   rE   r   r?   r  r  r   r  r   )rM   r   r  bins_arrr  s        rK   r  r  u"  s     z1d+++

 u.P
Q
Q%T]](]a
Q$QQ
R
RR^A!au%%%%	)6$	RLHQK14(((MML$$B$>>>>
 
 rL   zUnlike `np.piecewise`, :py:func:`jax.numpy.piecewise` requires functions in
`funclist` to be traceable by JAX, as it is implemented via :func:`jax.lax.switch`.
See the :func:`jax.lax.switch` documentation for more information.
Array | Sequence[ArrayLike]funclist&list[ArrayLike | Callable[..., Array]]c           
         t          j        d|            t          |          t          |          }}||dz   k    r|dd          |d d         z   }n8||k    rdgt          |          z   }nt	          d| d| d|dz    d|           d	 t          |          D             }d
 t          |          D             }t          t          |           t          |t                    |t          |
                                          g|R i |S )N	piecewiser   r   r   zwith z condition(s), either z or z functions are expected; got c                8    i | ]\  }}t          |          ||S rj   r  )r*  rD  r  s      rK   r  zpiecewise.<locals>.<dictcomp>"  s)    DDDTQDAqDDDrL   c                8    i | ]\  }}t          |          ||S rj   r  )r*  rD  r  s      rK   r  zpiecewise.<locals>.<dictcomp>"  s)    
?
?
?DAq8A;;
?1a
?
?
?rL   rn   )r*   r   r   rH   r   r  
_piecewiserS   r  r  r  )	rM   rf  r  r   kwncnfconstsfuncss	            rK   r  r  "  s4    {A&&&x==#h--b"26\\}x},HH	RxxsT(^^#HH
fRffrffr!tffbdff
g
ggDDYx00DDD&
?
?Ih//
?
?
?%	GAJJ > > >ekkmm,,
!
! 
! 
!
! 
! !rL   r  r  dict[int, ArrayLike]+frozenset[tuple[int, Callable[..., Array]]]c                  	
 t          |          fdt          t          |          dz             D             }t          t	          j        t          t          |d d                   |gd          d          d          }t          |           

fd
fd		fd|D             } t          t          j        d          |||           S )	Nc                b    g | ]+}                     |                     |                    ,S rj   )r  )r*  rD  r  funcdicts     rK   r2  z_piecewise.<locals>.<listcomp>"  s1    OOOfjjHLLOO,,OOOrL   r   r   c                      fdS )Nc                B     | gR i                                S r`   )r   )rM   r   rP   r  r  s    rK   r  z+_piecewise.<locals>._call.<locals>.<lambda>"  s/    QQq&4&&&2&&--e44 rL   rj   )r  r   rP   r  s   `rK   _callz_piecewise.<locals>._call"  s    44444444rL   c                      fdS )Nc                &    t                    S rm   r  )rM   rP   r   s    rK   r  z,_piecewise.<locals>._const.<locals>.<lambda>"  s    U1E*** rL   rj   )r   rP   s   `rK   _constz_piecewise.<locals>._const"  s    ******rL   c                Z    g | ]'}t          |          r |          n
 |          (S rj   r  )r*  r  r  r  s     rK   r2  z_piecewise.<locals>.<listcomp>"  s8    GGG(1++4eeAhhh66!99GGGrL   r   r  )r  r   r   rl  r(   r  r  r  r[   r+   r   switch)rM   rf  r  r  r   r  r  r  r  r  rP   r  s     ` ``  @@@@rK   r  r  "  s	    %[[(OOOOOeCMMA<M6N6NOOO(:$[*Xbqb\2J2JH1UWX%Y%Y[\]]_`aa'
))%5 5 5 5 5 5 5+ + + + +GGGGGhGGG(	-3:	-	-	-gx	C	CCrL   c           	         | j         dk    sJ | j        |k     r7t          | t          t	          j        || j        z                                } | j        |k    sJ | j        |k    r
| d |         n| S r  )rE   r  r  r^   r}   r   )r  r  s     rK   r6  r6  "  sr    	QX__
sCsx0011
2
2C	T				x$UdUC/rL   r  valsc               b   t          j        d| ||           t          |           t          |          t          |          }}}|rt	          d          |j        |j        k    rt	          d          |j        st	          d          |j        s|S t          |                                |j        |j                  d         }t          |t          |                    }|                                j	        |         
                    |d                              |j                  S )	a  Update array elements based on a mask.

  JAX implementation of :func:`numpy.place`.

  The semantics of :func:`numpy.place` are to modify arrays in-place, which
  is not possible for JAX's immutable arrays. The JAX version returns a modified
  copy of the input, and adds the ``inplace`` parameter which must be set to
  `False`` by the user as a reminder of this API difference.

  Args:
    arr: array into which values will be placed.
    mask: boolean mask with the same size as ``arr``.
    vals: values to be inserted into ``arr`` at the locations indicated
      by mask. If too many values are supplied, they will be truncated.
      If not enough values are supplied, they will be repeated.
    inplace: must be set to False to indicate that the input is not modified
      in-place, but rather a modified copy is returned.

  Returns:
    A copy of ``arr`` with masked values set to entries from `vals`.

  See Also:
    - :func:`jax.numpy.put`: put elements into an array at numerical indices.
    - :func:`jax.numpy.ndarray.at`: array updates using NumPy-style indexing

  Examples:
    >>> x = jnp.zeros((3, 5), dtype=int)
    >>> mask = (jnp.arange(x.size) % 3 == 0).reshape(x.shape)
    >>> mask
    Array([[ True, False, False,  True, False],
           [False,  True, False, False,  True],
           [False, False,  True, False, False]], dtype=bool)

    Placing a scalar value:

    >>> jnp.place(x, mask, 1, inplace=False)
    Array([[1, 0, 0, 1, 0],
           [0, 1, 0, 0, 1],
           [0, 0, 1, 0, 0]], dtype=int32)

    In this case, ``jnp.place`` is similar to the masked array update syntax:

    >>> x.at[mask].set(1)
    Array([[1, 0, 0, 1, 0],
           [0, 1, 0, 0, 1],
           [0, 0, 1, 0, 0]], dtype=int32)

    ``place`` differs when placing values from an array. The array is repeated
    to fill the masked entries:

    >>> vals = jnp.array([1, 3, 5])
    >>> jnp.place(x, mask, vals, inplace=False)
    Array([[1, 0, 0, 3, 0],
           [0, 5, 0, 0, 1],
           [0, 0, 3, 0, 0]], dtype=int32)
  placezjax.numpy.place cannot modify arrays in-place, because JAX arrays are immutable. Pass inplace=False to instead return an updated array.z)place: arr and mask must be the same sizez'Cannot place values from an empty arrayrY  r   dropr3  )r*   r   rS   r  r   r  r   r6  r   r  r  r=  r?   )r  r  r  r0  r  mask_arrvals_arrr  s           rK   r  r  "  s   t wT4000$S\\74==%++($ @
?@ @ @ 
Y(-
@
A
AA	 @
>
?
??	 K(..""8=QQQRST'8S\\22(		!	%	%hV	%	<	<	D	DTZ	P	PPrL   r  c               @   t          j        d| ||           t          |           t          |          t          |          }}}|j        r|j        r|j        s|S t          |t          |                    }|rt          d          |d}n\|dk    rt          |d|j        dz
            }d}n:|d	k    r||j        z  }d}n'|d
k    rt          d          t          d|          |j
        t          ||j                                               ||          S )aH	  Put elements into an array at given indices.

  JAX implementation of :func:`numpy.put`.

  The semantics of :func:`numpy.put` are to modify arrays in-place, which
  is not possible for JAX's immutable arrays. The JAX version returns a modified
  copy of the input, and adds the ``inplace`` parameter which must be set to
  `False`` by the user as a reminder of this API difference.

  Args:
    a: array into which values will be placed.
    ind: array of indices over the flattened array at which to put values.
    v: array of values to put into the array.
    mode: string specifying how to handle out-of-bound indices. Supported values:

      - ``"clip"`` (default): clip out-of-bound indices to the final index.
      - ``"wrap"``: wrap out-of-bound indices to the beginning of the array.

    inplace: must be set to False to indicate that the input is not modified
      in-place, but rather a modified copy is returned.

  Returns:
    A copy of ``a`` with specified entries updated.

  See Also:
    - :func:`jax.numpy.place`: place elements into an array via boolean mask.
    - :func:`jax.numpy.ndarray.at`: array updates using NumPy-style indexing.
    - :func:`jax.numpy.take`: extract values from an array at given indices.

  Examples:
    >>> x = jnp.zeros(5, dtype=int)
    >>> indices = jnp.array([0, 2, 4])
    >>> values = jnp.array([10, 20, 30])
    >>> jnp.put(x, indices, values, inplace=False)
    Array([10,  0, 20,  0, 30], dtype=int32)

    This is equivalent to the following :attr:`jax.numpy.ndarray.at` indexing syntax:

    >>> x.at[indices].set(values)
    Array([10,  0, 20,  0, 30], dtype=int32)

    There are two modes for handling out-of-bound indices. By default they are
    clipped:

    >>> indices = jnp.array([0, 2, 6])
    >>> jnp.put(x, indices, values, inplace=False, mode='clip')
    Array([10,  0, 20,  0, 30], dtype=int32)

    Alternatively, they can be wrapped to the beginning of the array:

    >>> jnp.put(x, indices, values, inplace=False, mode='wrap')
    Array([10,  30, 20,  0, 0], dtype=int32)

    For N-dimensional inputs, the indices refer to the flattened array:

    >>> x = jnp.zeros((3, 5), dtype=int)
    >>> indices = jnp.array([0, 7, 14])
    >>> jnp.put(x, indices, values, inplace=False)
    Array([[10,  0,  0,  0,  0],
           [ 0,  0, 20,  0,  0],
           [ 0,  0,  0,  0, 30]], dtype=int32)
  putzjax.numpy.put cannot modify arrays in-place, because JAX arrays are immutable. Pass inplace=False to instead return an updated array.Nr  r   r   r   promise_in_boundsr  r  z-The 'raise' mode to jnp.put is not supported.z1mode should be one of 'wrap' or 'clip'; got mode=r3  )r*   r   rS   r  r  r6  r   r   r   r   r  r  r?   r  )	r   r  r   r   r0  r  ind_arrv_arrscatter_modes	            rK   r  r  #  s@   @ uaa(((

E#JJaw#	  UZ J
s7||
,
,% @
?@ @ @ 
\LLv~~7Asx!|,,G&LLv~~ G&LLw
M
N
NN
KDKK
L
LL	gsy11	2	6	6u<	6	P	PPrL   )r>   )r?   r   r@   rA   rB   rC   )rM   r   rB   rN   )rM   r   rB   r1   )rz   rQ   rB   r]   )r   r   r   rN   r   rN   rB   r1   )r   r-   rP   r1   rB   r,   )r   r   r   r   rB   r,   )r   r-   r   r-   rB   r,   )r   r2   r   r2   rB   rN   )r   r   rB   rN   )r   r   rB   r1   r  r`   )rM   r,   r   r,   r   rA   r   rA   r   r&   r   r   rB   r,   )r   )r   r-   r   r-   r   rA   r   r&   r   r   rB   r,   )r   )r   NN)
r   r-   r   r-   r   r   r   r   rB   r,   )r   NNN)r   r-   r   r-   r   r  r   r   r  r  rB   r  )rM   r-   r   r-   r   r  r   r  r   r   r  r  rB   r  )r#  r-   r   r  r   r  r   r   r  r  rB   r&  )r   r-   rJ  rK  rB   r,   )rJ  rS  r   r-   rB   r,   )r   rY  )rZ  r-   rX  r^   rJ  r[  rB   r,   )rZ  r-   rb  rc  rB   r,   )rZ  r,   rb  ri  rB   r,   )rZ  r-   rB   r,   )F)r  r-   r~  rN   rB   r,   )r   r   NN)r   r-   r  r^   rb  r^   r  r   r8  r   rB   r,   )NN)r  r-   r  r   r  r   rB   r,   )
r  r-   r  r-   rb  rc  r  r  rB   r  )Nr  )
r   r-   r?   r  r  rA   r  r  rB   r,   )r  )r   r-   r  rA   rB   r,   )r  r  )
r  r  r  r  r   rA   r  rA   rB   r,   )r  r-   r?   r3   rB   r  )r   r-   r  r3   rB   r,   )r   r-   rb  rc  rB   r,   )r   r,   rb  rS  rB   r,   )r   r-   rb  r  rB   r,   )r   r-   r  r^   r  r^   rB   r,   )r   r-   r  r  r  r  rB   r,   )r   r,   r  rS  r  rS  rB   r,   )r&  r'  F)r   r-   r  r-   r(  r-   r)  r-   r%  rN   rB   r,   )NNN)rM   r-   r@  r-   rA  r-   rB  rC  r  rC  rD  r   rB   r,   )r[  r-   rM   r\  r   r\  r  r  rZ  r]  rB   r  )r[  r-   rM   r-   r   r-   r  r  rZ  r]  rB   r,   )r[  r-   rM   r   r   r   r  r  rZ  r]  rB   ra  r~  )rf  r  rg  r  rh  r-   rB   r,   r  )
rM   r-   r   r   rr  r^   r5  r  rB   r,   )ru  r  rB   rS  )ru  ry  rB   rz  )r   r-   rB   r  )r  r-   r?   r  rB   r,   )
r   rA   r  r-   r  r  rb  r^   rB   r  )r  r-   r  r  rb  r^   rB   r  )r   rA   rb  r^   rB   r  )r   r   r   r   r  r   r   r  r  r  r  r  rB   r,   r  )r   r-   r  r^   r   r  rB   r,   )rM   r-   r   r  rB   r,   )Tr  NN)rM   r-   r   rN   r  r-   r  r   r  r   rB   r,   )r   r-   r  r  rZ  r]  rB   r  )r   r-   r  r  rZ  r]  rB   r,   )
r  r-   r  r   rb  r^   rD  r-   rB   r,   )r  r  r  r^   r  rA   rB   r  )r  r  r   rA   )r  r,   r  r  r  r,   rB   r,   )r  r,   r  r  rB   r,   )
r  r,   r  r  r   rA   r/  rA   rB   r,   )r  r,   r  r  rL  rM  rB   r,   )
r  r,   r  r  rV  rW  rX  r  rB   r,   )r  r,   r  r  rg  rh  rB   r,   )r  r-   r  rp  r   rA   r  r-   rV  rp  rL  rq  r/  rA   )ru  )r  r-   r  r}  r   r~  rB   r,   )r   NN)
r  r  rb  r^   r   r  rP   r   rB   r,   )rM   r-   rb  r^   rB   r  )r  r-   r  r  rB   r,   )r  r-   rb  r  rP   r   rB   r,   )r  r  rb  r  rP   r   rB   r,   )r  r  rb  r  rB   r,   )r  r  rP   r   rB   r,   )r  r  rB   r,   )Nr  )
r   r-   r  r  r   r  r   rA   rB   r,   )rM   r-   r  r^   rB   r,   )r  r  rB   r  )r  r  rB   r,   )rB   r  )rM   r-   r   r-   r  r-   rB   r  )r  r-   rB   r  )NTr  r   )r|   r   rP   r   r   rN   r  r  r  r^   r  r  rB   r,   )r  r  rB   r+  )rM   r-   rB   r-   )
rM   r-   rP   r   r   rN   r  r  rB   r,   )r   r   rP   r   r  r  r   r  r  r  rB   r,   )r   r-   r  r  rB   r,   )
r   r<  rP   r   r?   r   r  r  rB   r,   )
rB  r<  rP   r   r?   r   r  r  rB   r,   )
r?   r   rZ  r-   rP   r   r  r  rB   r,   )r   r<  rZ  r-   rP   r   r?   r   r  r  rB   r,   )r?   r   rP   r   r  r  rB   r,   )rB   r  )rT  r-   rU  r-   r%  rN   rB   r,   )rT  r-   rU  r-   rB   r,   )
r[  r\  rP   r2   r]  r^   r=  r^   rB   r,   )rM   r   r  r  r   r  rB   r,   )rl  rm  r?   r   rP   r2   rB   r,   )
rt  rA   rP   r2   r]  r^   ru  rA   rB   r,   )Nr   N)r   r/   ry  rz  rX  r{  rP   r   r  r  rB   r,   )
r   r/   ry  rz  rX  r{  rP   r   rB   r,   )r  r/   rP   r   rB   r,   )r  r  r@  r  r  r   rP   r   r  r  rB   r,   )
r  r  r@  r  r  r   rP   r   rB   r,   )
r  r/   r@  r/   r  r/   rP   r2   rB   r,   )r  TFNr   )r  r-   r@  r-   rP  r^   rQ  rN   r  r  rP   r   rb  r^   r  r  rB   r,   )r  r-   r@  r-   rP  r^   rQ  rN   r  r  rP   r   rb  r^   r  r  rB   r  )r  T)r  r-   r@  r-   rP  r^   rQ  rN   r  rN   rP   r   rb  r^   r  r  rB   r  )r  Tr  Nr   )r  r-   r@  r-   rP  r^   rQ  rN   r  r-   rP   r   rb  r^   rB   r,   )r  TNr   )r  r-   r@  r-   rP  r^   rQ  rN   rP   r   rb  r^   rB   r,   )
r  r-   r   rN   r  rN   r  rA   rB   r  )r   r-   rB   r  )NF)r  r  rP   r   r  r  rB   r,   )r  r  rP   r   r  r  rB   r  )r  r  rP   r   r  rN   rB   ra  )
r   r-   r  r-   rb  r  r  r  rB   r,   )Nr  r   )
r   r-   rM   r   r  r-   rb  r^   rB   r,   )
r   r^   ry  r  rX  r^   rP   r   rB   r,   )rZ  r-   rX  r^   rB   r,   )r   r   r   NN)r   r-   r=  r{  r  r^   r  r^   rP   r   r   r  rB   r,   )r  r^   rX  r^   rZ  r  rB   r  )r  r-   rX  r^   rB   r  )
r   r-   r   r-   r  rN   r0  rN   rB   r,   )r  r^   rE   r^   rB   r  )r  r-   rB   r  )r   r   r   )
r   r-   r=  r^   r  r^   r  r^   rB   r,   )r   r-   rX  r^   rB   r,   )rI  )r  r-   rT  r-   rb  r  rB   r,   )
r  r-   r   rW  rb  r  rV  rN   rB   r,   )
r  r-   r   rW  rT  r-   rb  r  rB   r,   )rh  r   rb  r^   r  r-   rB   r,   )rg  rm  r   r-   rJ  r  rB   r,   )
r   r-   r  r-   r   r&   r   r   rB   r,   )r   r-   r   r-   rb  r^   r   r&   r   r   rB   r,   )r   r-   r  r-   rJ  r  r   r&   r   r   rB   r,   )r  rA   r  r-   r   r  r  r  r   r&   r   r   r  rm  rB   r,   )r  r-   rJ  r  r  r  r   r  r  r  r   r&   r   r   r  rm  rB   r,   )r   r  r  r  r   r&   r   r   r  rm  rB   r,   )r  rA   r  r-   r  r  rB   r  )
r  r-   rJ  r  r  r  r  r  rB   r  )r  r  rB   r  )r  r   r  r  )
r   r-   r  r-   r   r&   r   r'  rB   r,   )r   r-   r  r-   r   r  rB   r,   )r   r   r   N)r+  r^   r,  r^   r-  r^   rb  r  )r   r-   r  r-   rB   r,   )rM   r-   r   r  r8  rN   rB   r,   )r   r-   r  r  rZ  r   rB   r,   )
r   r-   rb  r  r   r  r  r  rB   r,   )r   r,   rb  r  r  rN   rB   r,   )rb  r  r  rN   r  )r   r-   rb  r  rU  r  r  r  rV  rN   rW  rN   rB   r,   )r   r-   rB   r,   )r^  r_  rb  r^   rB   r,   )r   r-   rj  r^   rb  r^   rB   r,   )r   r,   r  r,   rb  r  rB   r,   )r   r,   r  r  rb  r  rB   r,   )r   r-   r  r  rb  rc  rB   r,   )r   r-   rb  r^   r  r^   rB   r,   )Nr  )r   r-   rb  r  r  rA   rB   r,   )NNr  )
r   r-   rb  r  r]  r  r  rA   rB   r,   )NNNFFN)r   r-   r  r-   rb  r  r   r  r   r  r  rN   r  rN   rZ  r  rB   r,   )rb  r  )r  r-   r  r-   rb  r  r   r  rZ  r  rB   r,   )rp  r   rB   rN   )r  r,   rp  r   r   r  rB   r  )FFNN)T)r  r  rp  r  r  rN   rB   r   r  )r  r   r8  rT  rB   rU  )ry  r^   rB   r,   )ry  r^   rj  r-   rB   r,   )r  r  rB   r,   )r  r  rB   r  )
r[  r-   r  r-   r  r  rZ  r-   rB   r,   )r[  r-   r   r-   rb  r  r  r  rZ  r-   r   r  rB   r,   )NTFNNN)rZ  r-   r   r   r  rN   r  rN   r  r  r  r   r  r   rB   r,   )NT)rM   r-   r   r   r  rN   rB   r,   )r  rN   r  r,   r  r,   r  rA   rP   rQ   rB   r,   )
r  r,   r  r,   r  rA   rP   rQ   rB   r,   )rB  N)r   r-   r   r-   r  rA   r  r   r  rA   rB   r,   )rM   r-   r   r-   r  rN   rB   r,   )rM   r-   rf  r  r  r  rB   r,   )
rM   r,   rf  r,   r  r  r  r  rB   r,   )r  r,   r  r^   rB   r,   )
r  r-   r  r-   r  r-   r0  rN   rB   r,   )r   r-   r  r-   r   r-   r   r  r0  rN   rB   r,   (  r  
__future__r   r7  r  collections.abcr   r   	functoolsr   	importlibr;  r   rI  typingr   r   r	   r
   r   r   r   textwrapr   _dedentr  r   r}   r  r  r   r   r   jax.shardingr   r   jax.tree_utilr   r   r   jax._srcr   r   r   jax._src.custom_derivativesr   r   r   r   r   jax._src.api_utilr   jax._src.arrayr    jax._src.corer!   r"   jax._src.lax.laxr#   r$   r%   r&   jax._src.laxr   jax._src.libr'   r!  jax._src.numpyr(   r)   r*   jax._src.numpy.vectorizer+   jax._src.typingr,   r-   r.   r/   r0   r1   r2   r3   r4   jax._src.utilr5   r6   r7   r8   r9   r:   rO  r;   pkg_nameimport_moduler  ImportErrornewaxisr=   rJ   _PRECISION_DOCr~   ra  r  euler_gammarN  r  get_printoptionsprintoptionsset_printoptionsrW   r?   r  rE   r   r  r[   rQ   r]   ry   _shaped_abstractify_handlersr   r  uint2uint4r  uint16uint32uint64int2int4int8int16r  r  float8_e4m3fnfloat8_e4m3fnuzfloat8_e5m2float8_e5m2fnuzfloat8_e4m3b11fnuzr   r  r  singlefloat64double	complex64csingle
complex128cdoubler  uintr   rv   complex_genericnumberr  rU   r  r   signedintegerr  flexible	characterobject_r   rI  rP   can_castpromote_typesr6  	array_str
array_reprsavesavezr  r   rN   r^   r  r  r   r  r   r   r   r   r   rT   r   iterabler   r   (_CONV_PREFERRED_ELEMENT_TYPE_DESCRIPTIONr   r   r   r   r
  r  r  _ARRAY_VIEW_DOCr  rI   rR  rV  r]  r   re  ro  rt  ry  r}  r  r  _EDIFF1D_DOCr  r  r  r=  r  r9  r  r   r  r	  r  r  r  r  r+  rV  rF  r   rq  r:  rx  rk  r  r  r  r  r  r  r  r  registerr   aroundr  round_r  r  r  rd  r  r  r  rG   r  r  r  r  r$  r.  rB  rK  rU  ra  rf  rl  r|  r"  rj  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
_ARRAY_DOCr  r  r  r   rS   r   r  r  rc  r7  r   r?  r  rN  rw  rK  rW  rZ  r`  rd  rg  rh  rs  rx  r  r}  r  r  r  r  r  r  r  r  r  r  r  r  defjvpr  r>  r  rD  r  r   r  r
  r  r  mask_indicesr  r$  r&  r,  r/  r2  r5  r9  r;  r?  r>  _SCALAR_VALUE_DOCrD  rP  rS  r8  rY  r"  rj  ro  rr  r~  r  r  r  pathsPathOptimizerr  rw  r  r  r  r  r  r  r  r*  r/  r5  r:  r=  rl  r@  rL  rG  _NANARG_DOCrK  r   rJ  rS  rR  r]  r\  ra  r`  rl  rw  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r
  r  r0  r  r7  r  r  r  rG  r5  r  r  rc  re  rg  ri  rn  rq  rt  rv  ry  r~  r}  r  r  r  r  r  r  r  _PIECEWISE_DOCr  r  r6  r  r  rj   rL   rK   <module>r8     s>   	 	 	 # " " " " "      . . . . . . . .             . . . . . . . . . . . . . . . . . . & & & & & &          



                   7 7 7 7 7 7 7 7 = = = = = = = = = =                   2 2 2 2 2 2 ! ! ! ! ! !                   1 1 1 1 1 1 $ $ $ $ $ $ 4 4 4 4 4 4 4 4B B B B B B B B B B B B , , , , , , ) ) ) ) ) ) % % % % % % ! ! ! ! ! !       . . . . . .                     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 4 
 
H
3I3+++  
E 
 ! ! ! !
 GCLL
3 3 3 3 3 "  UDnff & & %* %* %* %*N  w u	w, , , ,1 1 1 1 1$ 1 1 1$P P P5M %k 2    	"(##	<

FL
)
)%&,''"(##		29	%	%		29	%	%		29	%	%	;		6;	'	'$%%!!"(##"(##"(##!!&"677##F$:;; 233##F$:;;&&v'@AA V_--

BJ
'
'$$RZ00 0&$$RZ00 0&''55 5	G((77 7
Wrx''uuU	))vvv"*44gg' A A A A2<7799Z
*	
*$;
* $;L	
*
?$$L	]
	w
7<!	/ 	/ 	/ 	/ 	/ 	/ t	8	-       
&3 &3 &3 &3R U+++   ,+  )))? ? ?  *)? )))B B B  *)B ' ' '  ' B B B B
 ;  # # # ! # '***M M M  +*M, ( 	SSSTTT59$! $! $! $! UT$!N 	MNNNGS(,8<GS GS GS GS GS ONGST 	MNNNQS)-9=QS QS QS QS QS ONQSh '((8:DH48A A A A )(A2 .026*.%)    .   PRMQ,0'+" " " " ! "$   GIMQ,0'+7  7  7  7  ! 7 t
K! K! K! K! K!\ ^T2233      43 
2  2  2  2 j ?;;;m,,,+ + + + -, <;+29C 9C 9C 9C 9Cv 	i(((F F F F )(F   4   2 % % % %, % % % %. 	ug&&&/3 /3 /3 /3 '&/3d m,,,/1%)$(2 2 2 2 -, 2h \:::7;)-     ;: <.9994555 (,!	D7 D7 D7 D7 D7 65 :9D7N   F FI^00=^0 ^0 ^0 ^0 ^0 ^0B 	j6661' 1' 1' 1' 761'j 9<X X X X Xv<9 <9 <9 <9| n---! ! ! .- !&9W 9W 9W 9W 9Wv 	i555   65C" C" C" C"L 	0>>>+& +& +& ?>+&\25 25 25 25h 	7EEE	  	  	  FE	  	n---SX#N N N N .-Nd +/+/&*; ; ; ; ;| '         +/+/&*7 7 7 7   
7 
37!&<@AE& & & & & 
&
 
!AE     

 
6: $.?CAE. . . . . 
.H( H( H( H( H( H(V  ; ; ; ; ;$ 8<QD9=QD QD QD QD QD QDf 
 D D D 
 D	= = = 
= /6677' ' 87' $ 7   ' ' ' '  3   * * * * $H $H $H $H $HL ?;;;> > > > <;>
 
 
 
 
q	)	)	)	q	)	)	)	q	)	)	)  D D D D ! D  . / / /	G "/,9MOO,9MOOG G G G G GR 000m,,,    -, 10< 
	 eW---A A A A  .-A AD*.*.      * 	n---;@8=,> ,> ,> ,> .-,>^ 15CGh h h h h hV 59GK*@ *@ *@ *@ *@ *@Z i(((59q2v    )( 6 QXhqk%::;q!tc!"5 5 5 5 5( 5 5 5&P &P &P &PR' ' ' '      &B B B BJ   (   B% % % %P	 	 	 	    	_---2, 2, 2, .-2,j  *    *4$^ $^ $^ $^ 
$^R w///EI; ; ; ; 0/;( Y--..f%%%,- % % % % % &% /.% @ @ @ @" 26- - - - -   @D    ! 4 Xt,,--AB 2 2 2 2 2 .-2
 %)	0 	0 	0 	0 	0 %)I I I I I %)	0 	0 	0 	0 	0 !!   "! 000)0B B B B 10B4C C C C         
 
   
	   
	   
5/RRR= = =  SR= 
   
	   
	   
5/RRR= = =  SR= 
   
	   
	   
5/RRR- - -  SR-   
  , - - -: E    EI01i37i i i i i	 iX        8 9 9 9 $15>1 >1 >1 >1 >1 >1B Z G   L#'26L L L L L	 L$ *555* * * * 65* *. 'T 6:'T 'T 'T 'T 'T 'TV )-'T 59'T 'T 'T 'T 'T 'TV *. 'H 6:'H 'H 'H 'H 'H 'HT    $(-G/3-G -G -G -G -G -Gb @D5G 595G 5G 5G 5G 5G 5Gp!X04!X !X !X !X !X !XH!X/3!X !X !X !X !X !XH ,04 ,  ,  ,  ,  ,  ,D; ; ; ;& & & & &R# # # #P 7<aX X X X  X
` ` `$` ` `" ]D11 D    EI$(2 2 2 2 2 2
 !!',F F F F F "!F /42 R R R R  R )-"&8 268 8 8 8 8 8v *."&) ) ) ) )&    B KODHL48L L L L L L^ LPEI&F &F &F &F &FR< < < <. 
;=>C'+J 7;	J J J J J 
J
 
 (,X 7;	X X X X X 
X
 
;="U'+37	U U U U U 
U
 
;=49'+` 7;	` ` ` ` ` 
`
  ,    <>49'+T 7;	T T T T T	 T 	WXXX<>5:(,60 8<	60 60 60 60 60 YX60r ;=6:9:B B B B B 	BCCC<>7;:;B B B B DCB" QU:;= = = = = 	BCCCRV;<. . . . DC.* o>>>*.u!     ?>* 8 8 8   8 > > >3 3 3 3l 
AE%*: : : : 
:	@ @ @ @ 
@	AE D D D D 
DAE @ @ @ @ @(M,-1M, M, M, M, M, M,` [''"gt*D*DEEFFi(((HKG G G G )( GFG&5- 5- 5- 5- 5-p 	f%%%9I 9I 9I 9I &%9Ix 	f%%%=I =I =I =I &%=I@ w///9:::RS6:7 7 7 7 ;: 0/7 
 
 
 &%bo662 2 27 7 7 7 7t7 7 7 7 7t69 69 69 69 69r69 69 69 69 69rNP"&NP NP NP NP NP NPb !!	% 	% 	% 	% "!	% %&&
% 
% 
% '&
% o>>>:;;;9:7 7 7 7 <; ?>7" /:::% % % % ;:% 	f%%%4 4 &%4  .?@@@    A@  % % %  %% % % % 	i(((:>21 21 21 21 )(21p v>
 #(v> v> v> v> v> v>r "1 1 1 1 1h $%%   &% #$$   %$" 	EdSSS#'37X^ X^ X^ X^ X^ TSX^v 	EdSSS&*6:w^ w^ w^ w^ w^ TSw^t 	EdSSS  $/3,< ,< ,< ,< ,< TS,<^ <>&*6:4< 4< 4< 4< 4< 4<p EFp^,09=p^ p^ p^ p^ p^ p^f( ( ( ( (*"0 ( ( (
 
 3<#/3),     
 

 3<#/3),	 	 	 	 	 
	 3<#/3),s6 s6 s6 s6 s6 s6p  ) ) ) 
 58, , , , , 
, 

 58	, , , , , 
, 4:8L 8L 8L 8L 8L 8Lt: : : Sc Sc Sc Sc Scl 	EdSSS>B+/4B 4B 4B 4B 4B TS4Bn w///T/ / / /  0// ABBB?A!    CB 6 
= 
= 
=  
= 1222;@M M M M 32 M0 #'	>2 >2 >2 >2 >2 >2B 000>B#'* * * * 10* 	24@@@
; 
; 
; 
; A@
; 000>B#'* * * * 10* 	24@@@
; 
; 
; 
; A@
; {/A/A%/H/HW\V]^^^  	` ` ` ` _^` 	2333P P P P 43P {/A/A%/H/HX]W^___  	` ` ` ` `_` 	2333P P P P 43P 	OPPP ;K ;K ;K ;K ;K ;K QP;K| !!G G G  "!G
 i((([ [ [ [ )( [  	OPPP LM LM LM LM LM LM QPLM^ 	ufo...B! B! B! B! /.B!J 	ufo...I! I! I! I! /.I!X 	T"""   #" 	V$$$   %$ ,0* * * * *  	/000=" =" =" =" 10="@ 2333;@$ $ $ $ 43 $: ;<<< 	& & & & =<  &@  $&*T& T& T& T& T&n 	deee>BEI3R 3R 3R 3R fe3RlG G G 	<===
 04&*_R _R _R _R >=_RHV V V V8 8 8 8
  Q Q QN N N Nb HM*.3 3 3 3<#. #. #.J" " " " "z " " ":) ) )6
  
  
 < < < 04L' L' L' L' L'\) ) )  .; ; ;) ) )X  3 3 3T T T2 2 2
   (9! 9! 9! 9!x a a a a 1 1 1 1 8 8 8 8 6 6 6 6 K K K K! ! ! !: : : : (((    )( (((@ @ @  )(@ #':R :R :R :R :R :Rz[##'PT[# [# [# [# [# [#| 8999AE/3%)%)?= ?= ?= ?= :9 ?=D k***    +* & 	\\\***   +*
W 
W 
W 
W. . . . 	01119?,0U3CIU3 U3 U3 U3 U3 21U3n j)))    *)  ~>>>! ! ! ?>!" 	wi(((D D D )(D0 0 0 0 HQ HQ HQ HQ HQ HQX  UQ48UQ UQ UQ UQ UQ UQ UQ UQs   D22D<;D<