
    uki                       d Z ddlmZ ddlZddl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mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z" ddlm#Z# ddlm$Z$ ddlm%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z;  e9d      Z< G d d ejz                        Z> G d! d"e      Z?	 	 	 	 	 	 dLd#Z@e0 ej                  d$d$%       G d& d'                    ZBe<	 	 	 	 	 	 dM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dNd)       ZC ej                  d*+      	 	 dMdOd,       ZEd- ZFe< ej                  d.+      	 	 	 dP	 	 	 	 	 	 	 	 	 	 	 dQd/              ZGd0 ZHe< ej                  d1+      	 dRdd2	 	 	 	 	 	 	 	 	 	 	 	 	 dSd3              ZIdTd4ZJdTd5ZKd6 ZLd7 ZMdd8	 	 	 	 	 	 	 	 	 dUd9ZN G d: d;ejz                        ZOd(d(ddd$deOj                  d<	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dVd=ZQd> ZR G d? d@e      ZSd$dA	 	 	 dWdBZTdC ZUdD ZVdE ZWdF ZXdG ZYdH ZZe<d$dI	 	 	 dXdJ       Z[e<	 dYd$dI	 	 	 	 	 dZdK       Z\y)[zIndexing code for jax.numpy.    )annotationsN)partial)Any
NamedTuple)Sequence)api)array)config)core)dispatch)dtypes)errors)literals)lax)slicing)utils)array_constructors)einsum)error)	lax_numpy)ufuncs)util)PartitionSpec)	auto_axes)canonicalize_shardingNamedSharding)tree_flattentree_unflattenregister_pytree_node_class)Array	ArrayLikeIndexStaticScalar)canonicalize_axissafe_zip
set_moduletuple_updateunzip3z	jax.numpyc                  :    e Zd ZdZdZdZdZdZdZdZ	e
d
d       Zy	)	IndexTypez'Enum for tracking the type of an index.nonesliceellipsisintegerbooleanr	   c                8   || j                   S |t        u r| j                  S t        |t              r| j
                  S t        |      r| j                  S t        |      r| j                  S t        |t        t        j                  t        j                  f      rRt        j                   |j"                  t        j$                        r| j&                  S t)        d|j"                         t        |t*              rt)        d|      t        |t,              r|s| j&                  S t/        j0                  t2        j4                  |      }|j"                  t6        k(  r| j                  S t        j                   |j"                  t        j$                        r| j&                  S t)        d|j"                         t        |t8        t:        t        j<                  f      r*t)        dt        j"                  t?        |                   tA        d|       )z:Create an IndexType enum from a supported JAX array index.zAIndexer must have integer or boolean type, got indexer with type z.JAX does not support string indexing; got idx=zuonly integers, slices (`:`), ellipsis (`...`), newaxis (`None`) and integer or boolean arrays are valid indices. Got )!NONEEllipsisELLIPSIS
isinstancer,   SLICE_is_integer_indexINTEGER_is_boolean_indexBOOLEANr    npndarrayr   TypedNdArrayr   
issubdtypedtyper.   ARRAY	TypeErrorstrr   r   
eval_shaper   asarrayboolfloatcomplexgenerictype
IndexError)clsidxidx_avals      R/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/numpy/indexing.py
from_indexzIndexType.from_indexD   s    {XXo	\\	C	YY	3	[[	3	[[	C%X-B-BC	D			399bjj	1yyMcii[
Y[ 	[	C	 G3&IJJ	C	"yy 2 : :C@h	4	{{X^^RZZ8yyMhnnM]
^` 	`	C%"**5	6
KBHHUYZ]U^L_K`ac c  PPSuV W W    N)rK   r"   returnr*   )__name__
__module____qualname____doc__r1   r5   r3   r7   r9   r?   classmethodrN    rO   rM   r*   r*   ;   s7    /	$
%(''
%&W &WrO   r*   c                  0    e Zd ZU dZded<   ded<   ded<   y)	ParsedIndexzNStructure for tracking an indexer parsed within the context of an array shape.r"   indexr*   typtuple[int, ...]consumed_axesN)rQ   rR   rS   rT   __annotations__rV   rO   rM   rX   rX   n   s    V	,.  rO   rX   c                   g }g }g }t        |       D ]  \  }}t        j                  |      }|j                  |       |t        j                  k(  r|j                  d       R|t        j
                  k(  r#|j                  d       |j                  |       |t        j                  k(  r%|j                  t        j                  |             |t        j                  t        j                  t        j                  fv r|j                  d       t        d|        t        |      dkD  rt        d      t        |      }|t        |      kD  rt        dt        |       d| d      |rt        |      |z
  ||d   <   g }	d}
t        | ||      D ]I  \  }}}t!        t#        |
|
|z               }|
t        |      z  }
|	j                  t%        |||             K |	S )	a  Parse indices in the context of an array shape.

  Args:
    indices: a tuple of user-supplied indices to be parsed.
    shape: the shape of the array being indexed.

  Returns:
    The list of parsed indices stored in :class:`ParsedIndex` objects.
    This list will have the same length as ``indices``.

  Raises:
    IndexError: if any unrecognized index types are present or if there
      are too many indices, or too many ellipses.
  r      zUnrecognized index type: z0an index can only have a single ellipsis ('...')zToo many indices: array is z-dimensional, but z were indexedrY   rZ   r\   )	enumerater*   rN   appendr1   r3   r9   r:   ndimr7   r?   r5   rI   lensumr%   tuplerangerX   )indicesshapedimensions_consumedellipses_indicesindex_typesirK   rZ   total_consumedresultcurrent_dimrY   
n_consumedr\   s                 rM   _parse_indicesrr   u   s   ( $& "!#+'" :fa


s
#Cs
inn  #		""	"   #a 		!!	!  .	""IOOY__E	E  #23%899!:& 		Q
G
HH*+.c%j 
23u:, ?+,M; < </25zN/J(+, !&+ (+?R S ReS*%[:-EFGM3}%%K
MM+Es-PQR 
-rO   T)frozenkw_onlyc                      e Zd ZU dZded<   ded<   edd       ZdddZddZdd	Z	dddZ
ddZddZddZddZd Z	 d	 	 	 ddZd Zed        Zy
)	NDIndexera  Object that implements NumPy-style indexing operations on top of JAX.

  Generally this will be constructed via the :meth:`NDIndexer.from_raw_indices`
  method.

  Attributes:
    shape: the shape of the array being indexed.
    indices: a list of :class:`ParsedIndex` objects.
  r[   ri   list[ParsedIndex]rh   c                D    t        |      }t        ||      } | ||      S )z:Create an NDIndexer object from raw user-supplied indices.ri   rh   )"eliminate_deprecated_list_indexingrr   )rJ   rh   ri   s      rM   from_raw_indiceszNDIndexer.from_raw_indices   s'     19GWe,GUG,,rO   c                   t        | j                        D ]  \  }}|j                  t        j                  k(  s$t        |j                  t        t        j                  f      sJ t        j                  |j                        }|j                  \  }| j                  |   }|r
|dk  r||z   n|}d|cxk  r|k  rn t        d| d| d| d|d	       y)zsCheck that all static integer indices are in-bounds.

    Raises an IndexError in case of out-of-bound indices
    r   zindex z out of bounds for axis z with size z (normalize_indices=)N)ra   rh   rZ   r*   r7   r4   rY   intr:   r.   operatorr\   ri   rI   )selfnormalize_indicespositionrK   rm   axissize
normed_idxs           rM   validate_static_indicesz!NDIndexer.validate_static_indices   s    
 #4<<0 	7#	I%%	%#))c2::%6777NN399%!!zz$!2q1uQX!
J%%VA3&>tfKPTv2 1316 7 7	7rO   c                   t        | j                        D ]  \  }}|j                  t        j                  k(  s$t        |j                  t              sJ t        d |j                  j                  |j                  j                  |j                  j                  fD              rt        d|j                   d|        y)zwCheck that all slices have static start/stop/step values.

    Raises an IndexError in case of non-static entries.
    c              3  2   K   | ]  }t        |        y wN)._is_slice_element_none_or_constant_or_symbolic).0vals     rM   	<genexpr>z,NDIndexer.validate_slices.<locals>.<genexpr>   s       Q B#F Q   z+Slice entries must be static integers. Got  at position N)ra   rh   rZ   r*   r5   r4   rY   r,   allstartstopsteprI   )r   r   rK   s      rM   validate_sliceszNDIndexer.validate_slices   s    
 #4<<0 F#	IOO	##))U+++ Q"yy				OQ Q ""%))M(E F FFrO   c           	        g }t        | j                        D ]  \  }}|j                  t        j                  k7  r|j                  |       6t        j                  |j                        s2t        j                  t        j                  |j                              t        |j                  t        t        j                  t         t"        j$                  t&        f      sJ t        j(                  |j                        dk(  rM|j*                  dk(  sJ |j                  t-        t        |j                        |j                  d             ;t        j.                  |j                        }|j*                  D cg c]  }| j.                  |    }}t1        d t3        ||      D              st5        d| d| d|       t        j6                  t        j8                  |j                              }|j;                  d t=        ||j*                        D                t?        | j.                  |	      S c c}w )
zReturns a new NDIndexer with boolean indices replaced by array indices.

    The only exception are scalar boolean indices, which are left in-place.
    r   rV   r`   c              3  .   K   | ]  \  }}|d |fv   ywr   NrV   )r   s1s2s      rM   r   z0NDIndexer.expand_bool_indices.<locals>.<genexpr>   s     L62r2wLs   z<boolean index did not match shape of indexed array in index z: got z, expected c              3  \   K   | ]$  \  }}t        |t        j                  |f        & yw)r`   N)rX   r*   r?   )r   rm   r   s      rM   r   z0NDIndexer.expand_bool_indices.<locals>.<genexpr>   s2      `")!T *yW[V]^^ `s   *,ry   ) ra   rh   rZ   r*   r9   rb   r   is_concreterY   r   NonConcreteBooleanIndexErrorget_avalr4   rD   r:   r;   r    r   r<   listrc   r\   rX   ri   r   ziprI   whererC   extendr%   rv   )r   expanded_indicesr   rK   	idx_shaperm   expected_shapeexpanded_indices_raws           rM   expand_bool_indiceszNDIndexer.expand_bool_indices   s   
 +-"4<<0 `#	I%%	%$cii(11$--		2JKK		D"**eX=R=RTX#YZZZ		q	   B&&&$syy/sww^` ab((399%i/2/@/@A!

1AnALSN-KLL $:VI;k.AQS T 	TXXbjj&;< `-56JCL]L]-^` `'`* 4::/?@@ Bs    I Nc                .   t        | j                        }t        |d | j                  D        n|      }t        | j                        }d}t        | j                        D ]
  \  }}|j                  t
        j                  k(  rt        j                  |j                        dk(  rp|j                  |d       |j                  |d        t        t        j                  t        |j                              t
        j                  |f      ||<   |dz  }t        |j                         }t        |j                  |j                  t#        t%        |||z                     ||<   ||z  } |d n
t#        |      }t'        |t#        |            |fS )Nc              3      K   | ]  }d   y wr   rV   )r   _s     rM   r   z7NDIndexer.expand_scalar_bool_indices.<locals>.<genexpr>  s     7qd7s   r   r_   rZ   r\   r`   rh   ri   )r   ri   rh   ra   rZ   r*   r9   r:   rc   rY   insertrX   aranger~   r?   rd   r\   rf   rg   rv   )	r   sharding_spec	new_shapenew_sharding_specnew_indicesrp   rm   rK   rq   s	            rM   expand_scalar_bool_indicesz$NDIndexer.expand_scalar_bool_indices  sR   TZZ I=;P7DJJ7Vcdt||$KKDLL) "3	I%%	%"''#))*<*AA  D)$
))C		N
#XAq**+
$		ggk;3K LM
A
 	z!" !. 55AR;S[i0@ACTTTrO   c                   | j                   D cg c]]  }t        |j                  t              r?t	        t        j                  |j                        |j                  |j                        n|_ }}t        || j                        S c c}w )Nr   r   )rh   r4   rY   r   rX   r   rC   rZ   r\   rv   ri   )r   rK   r   s      rM   convert_sequences_to_arraysz%NDIndexer.convert_sequences_to_arrays  su    JN,,XCFjH5 y00;X[XiXij;>? XK X[

;;Xs   A"B
c           	     &   g }d}| j                   D ]  }|t        |j                        z  }|j                  t        j
                  k(  rG|j                  D ]7  }|j                  t        t        d      t        j                  |f             9 |j                  |        t        |t        | j                              D ]7  }|j                  t        t        d      t        j                  |f             9 t        | j                  |      S )zq
    Returns a new indexer with ellipsis and implicit trailing slices
    replaced by explicit empty slices.
    r   Nr`   ry   )rh   rd   r\   rZ   r*   r3   rb   rX   r,   r5   rg   ri   rv   )r   expandedconsumedrK   r   s        rM   expand_ellipseszNDIndexer.expand_ellipses  s    
 #%HH|| #c''((h	I&&	&%% 	fD
//+E$KY__]a\cd
e	f 	 hDJJ0 bookdY]X_`ab4::x88rO   c                d   g }| j                   D ]  }|j                  t        j                  k(  r|j                  \  }| j
                  |   }t        |j                  t        j                        r|j                  }n*|j                  dk  r|j                  |z   n|j                  }|j                  t        ||j                  |j                               |j                  t        j                  k(  rt        |j                  t        t        j                  t        j                   f      sJ |j                  \  }t#        j$                  |j                  j&                  t        j                        r|j                  }n| j
                  |   }t)        j*                  |      r!t-        j.                  |j                  |      }n=t-        j0                  t)        j2                  |      |j                  j&                        }t-        j4                  |j                  dk  t-        j6                  |j                  |      |j                        }|j                  t        ||j                  |j                               x|j                  |        t9        || j
                        S )Nr   r   r   )rh   rZ   r*   r7   r\   ri   r4   rY   r:   unsignedintegerrb   rX   r?   r    r;   r   r<   r   r=   r>   r   is_constant_dimr   _constconvert_element_typedimension_as_valueselectaddrv   )r   r   rK   r   r   normed_indexs         rM   r   zNDIndexer.normalize_indices1  s   %'K||  	I%%	%!!**T*cii!3!34 #		,-0YY]T)		,;|PSPaPabc77ioo%#))eRZZ9N9N%OPPP!!SYY__b.@.@A,D!$!!$'::cii.D++D,C,CD,I,/IIOO=DCIIM377399d3KSYYW,;|PSPaPabc31 2 [

;;rO   c                   | j                  d       | j                          t        | j                        D ]  \  }}|j                  t
        j                  t
        j                  t
        j                  fv rB|j                  t
        j                  k(  rt        d|j                   d|       |j                  t
        j                  t
        j                  fv rt        d|j                   d|       t        d|j                   d| d       g }g }g }g }g }| j                         }	|	j                  D ]  }|j                  t
        j                  t
        j                  t
        j                  t
        j                  fv rt        d|       |j                  t
        j                  k(  rt!        |j                  t"        t$        j&                  f      sJ |j(                  \  }
t#        |j                  d	k  r|j                  |j*                  |
   z   n|j                        }|j-                  |       |j-                  |d
z          |j-                  d
       |j-                  |
       <|j                  t
        j                  k(  rt!        |j                  t.              sJ |j(                  \  }
|j*                  |
   }|j                  j                  |      \  }}}|d	k  r|d
z   t1        ||z
  d
z
        t1        |      z  z   }|j-                  |       |j-                  t3        ||d
z                |j-                  t1        |             |j-                  |
       6|j-                  |       |j-                  |       |j-                  |       kt        d|j                          |}|rt5        j.                  ||||      }|rt7        j8                  ||      }|rt7        j:                  ||      }|S )zEquivalent of arr[idx] implemented in terms of static :func:`lax.slice` operations.

    This supports only INTEGER, ELLIPSIS, and SLICE indices, and will raise a TypeError
    if other indices are present.
    Tr   zstatic_slice: got r   z<static_slice: indices must be static scalars or slices. Got z!static_slice: unrecognized index .z(Internal: unexpected index encountered: r   r_   )r   r   ra   rh   rZ   r*   r7   r3   r5   r1   r@   rY   r?   r9   r   RuntimeErrorr4   r~   r:   r.   r\   ri   rb   r,   absmaxr   r   revsqueeze)r   arrr   pidxstart_indiceslimit_indicesstridesrev_axessqueeze_axesr   r   start_indexr   r   r   stride	new_startro   s                     rM   compute_via_static_slicez"NDIndexer.compute_via_static_sliceN  sg    	  4 8#DLL1 	b$	i''););Y__M	M88y~~%,TZZLhZPQQ88	):):;;   $

|=
D E 	E ;DJJ<}U]T^^_`aa	b  "M!MGH L##%H   J	iooy'8'8)..)J\J\]	]EdVLMM88y((($**sBJJ&7888""$**q.$**syy6djjY[)[1_-qD!88y&$**e,,,""yy"jj006tVA:QhUT\A%5!6V!DD)


y
)


s9eai8
9
..V
%
//$



u
%


t
$
..
 ;DJJ<HII7J8 F}}V]M7Kfwwvx(f{{6<0fMrO   c                :    t        d | j                  D              S )zGReturns True if idx should trigger int array indexing, False otherwise.c              3     K   | ]T  }|j                   t        j                  t        j                  fv xr" t	        j
                  |j                        d kD   V ywr   )rZ   r*   r?   r9   r:   rc   rY   )r   rK   s     rM   r   z4NDIndexer.is_advanced_int_indexer.<locals>.<genexpr>  sK      ( ww9??I,=,=>>Y277399CUXYCYY (s   AA)anyrh   )r   s    rM   is_advanced_int_indexerz!NDIndexer.is_advanced_int_indexer  s"      (,,( ( (rO   c                    t        | ||      S )N)
x_shardingr   )_index_to_gather)r   r   r   s      rM   	to_gatherzNDIndexer.to_gather  s    DZK\]]rO   c                   dd}| j                   D cg c]  } ||      r|j                  nd  }}| j                   D cg c].  } ||      r"t        d |j                  |j                        n|0 }}|| j
                  |ffS c c}w c c}w )Nc                x    | j                   t        j                  t        j                  t        j                  fv S r   )rZ   r*   r7   r?   r9   )rm   s    rM   
is_dynamicz*NDIndexer.tree_flatten.<locals>.is_dynamic  s(    UUy(()//9;L;LMMMrO   r`   )rm   rX   )rh   rY   rX   rZ   r\   ri   )r   r   rm   raw_dynamic_indicesstatic_metadatas        rM   r   zNDIndexer.tree_flatten  s    NGK||T!jm177=TT ||
 LVVW=k!%%qG^__O  _ ===	 Us   B 3B
c           	         |\  }}t        ||      D cg c]*  \  }}||n t        ||j                  |j                        , }}} | ||      S c c}}w )Nr   )r%   rX   rZ   r\   )rJ   aux_datachildrenri   r   	dyn_indexrK   rh   s           rM   r   zNDIndexer.tree_unflatten  sg    %E?%-h%HJ!9c  's[CGGSM^M^-__ JG Jwe,,Js   /A)rh   Index | tuple[Index, ...]ri   r[   rP   rv   T)r   rD   rP   None)rP   r   )rP   rv   r   )r   r   rP   ztuple[NDIndexer, Any])r   r    rP   r    )r   NamedSharding | Anyr   rD   rP   _GatherIndexer)rQ   rR   rS   rT   r]   rU   r{   r   r   r   r   r   r   r   r   r   r   r   r   rV   rO   rM   rv   rv      s     
- -7 FA<U.<
9$<:@D( +/^#'^3A^> - -rO   rv   Fc           
     V    t        | ||dnt        j                  |      |||||      S )a  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
      after normalization of negative indices, which lets the compiler emit more efficient
      code during the backward pass. If set to True and normalized indices are not unique,
      the result is implementation-defined and may be non-deterministic.
    indices_are_sorted : If True, the implementation will assume that the indices are
      sorted in ascending order after normalization of negative indices, which can lead
      to more efficient execution on some backends. If set to True and normalized indices
      are not sorted, the output is implementation-defined.

  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)unique_indicesindices_are_sorted
fill_value)_taker   rY   )arh   r   outmoder   r   r   s           rM   taker     s4    j 
q'4<4X^^D5I3NGY$
& &rO   )r   r   r   r   r   )static_argnamesc                   |t        d      t        j                  d| |      \  } }|| j                         } d}nt	        |t        j                  |             }||dk(  rEt        j                  j                  }	t        j                  |dk  || j                  |   z   |      }n|dk(  rt        d      |dk(  rRt        j                  |t        j                  || j                  |               }t        j                  j                   }	n/|dk(  rt        j                  j"                  }	nt%        d	| d
      t'        t        j                  |            }
t)        t        j                  |             }||   dk(  r|j*                  dk7  rt-        d      | S |j*                  dk(  r<|d | t)        |j                        z   ||dz   d  z   }t        j.                  | d|      S d||<   t        j0                  t3        t)        t5        |            t)        t5        ||
z   t'        | j                        |
z   dz
              z         |f|f      }t        j6                  | |d   |t3        |      |	|||      S )Nz0The 'out' argument to jnp.take is not supported.r   r   fillraisez.The 'raise' mode to jnp.take is not supported.wrapclipzInvalid mode 'z' for np.takez4Cannot do a non-empty jnp.take() from an empty axis.r_   ri   offset_dimscollapsed_slice_dimsstart_index_map).N)dimension_numbersslice_sizesr   r   r   r   )NotImplementedErrorr   ensure_arraylikeravelr$   r:   rc   r   GatherScatterModeFILL_OR_DROP_whereri   r   modr   r   PROMISE_IN_BOUNDSCLIP
ValueErrorrd   r   r   rI   	full_likeGatherDimensionNumbersrf   rg   gather)r   rh   r   r   r   r   r   r   axis_idxgather_mode
index_dimsr   	out_shapednumss                 rM   r   r     sE    	_
P
QQ$$VQ8*!W	\		AH rwwqz2H	\TV^++88Kkk'A+w1B'BGLGw
N
OOv~jj#**Waggh6G"HIG++==Kv~++00K
~dV=9
::288G$%*RXXa[!+a||qMNNH\\QYh'$w}}*==X\]+,I==AY//+h

(
(
5?
5J&AGGz(AA(EFGHI #K!% 
79-$)+$6(+=*
V VrO   c                   t        j                  t        j                  |       t        j                        r| S t        j                  |      rt        j                  | |      }n<t        j                  t        j                  |      t        j                  |             }t        | t        t        j                  f      r| dk  rt        j                  | |      S | S t        j                  | dk  t        j                  | |      |       S )zCNormalizes an index value in the range [-N, N) to the range [0, N).r   )r   r=   r>   r:   r   r   r   r   r   r   r   r4   r~   r.   r   r   )rY   	axis_sizeaxis_size_vals      rM   _normalize_indexr  ;  s    v||E*B,>,>?L	)$JJui0M,,T-D-DY-O-3\\%-@BMRZZ(),1AI3775-(@5@::eai!>FFrO   )r   r   r   c           	     
  " t        j                  d| |      \  }}|j                  }t        j                  |      }t        j                  |t        j                        st        d|       |Ft        j                  |      dk7  rd}t        |j                  |            |j                         }d}|j                  }	|	t        j                  |      k7  r:d}t        |j                  t        j                  |      |j                              t        ||	      ""fd}
t        j                  |j                  d	      }t!        j"                  ||      }|j                  "   } |
|j                  d      }t!        j$                  ||      }|dk(  r!t!        j&                  |d|j                        S |d
k(  rddlm} t-        ||      }|j/                  ||t        j0                        }|j                  dk(  r#t3        j2                  d|||j                        S "t5        t6        j8                        dz
  kD  rt        d      dj;                  t=        "      D cg c]  }t6        j8                  |    c}      }|dz   |z   dz   |z   dz   }t3        j2                  |||t         j>                  j@                  |j                        S tC        |      D cg c]#  \  }}|"k(  stE        jF                  |d      r"|% }}}tI        t        jJ                  |      |         dz   }g }g }g }g }g }g }g }g }d}d}t=        |	      D ]X  }|"k(  rt|dk7  rt-        ||      }|jM                  t!        jN                  ||             |jM                  d       |jM                  |       |jM                  |       |dz  }|dz  }}tE        jF                  ||   d      r+|jM                  |       |jM                  ||          |dz  }tE        jF                  ||   d      r|jM                  |       |dz  }tE        jF                  ||   d      r|jM                  d       n|jM                  d       |jM                  |       |jM                  |       |dz  }|dz  }[ t!        jP                  ||      }t!        jR                  ||      } tU        jV                  tI        |      tI        |      tI        |      tI        |      tI        |            }!tU        jX                  || |!tI        |      |d|      S ||      S c c}w c c}}w )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 r_   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                :    t        |       }||<   t        |      S r   )r   rf   )tupr   lstaxis_ints      rM   replacez take_along_axis.<locals>.replace  s    
s)CCM:rO   Tsignedone_hot)nnr>   z...b,b->...)preferred_element_type   zCOne Hot indexing is only supported for up to 50 leading dimensions. zy...z,zz...->zy...)	precisionr#  )r_   promise_in_bounds)	dimension)r   r   r   operand_batching_dimsstart_indices_batching_dimsr   )r   r   )-r   r  r>   r:   ri   r   r=   r.   r@   rc   r
  formatr  r$   	lax_utilsint_dtype_for_dimr   r   broadcast_shapesfulljaxr!  r  r   bool_r   rd   stringascii_lettersjoinrg   	PrecisionHIGHESTra   r   definitely_equalrf   r	   rb   reshaper   concatenater   r  r  )#r   rh   r   r   r   r   index_dtyper   msgrankr  r  	arr_shaper  r!  hotrm   labelseqrK   r  gather_index_shapegather_indicesr   r   r   r   r)  r*  dims_to_squeezenew_ijgather_indices_arrr  r  s#                                     @rM   r  r  J  s   ` $$%6WE*!W+hhw)			;

	3
K"m% & &	\	www1Kcszz),--		AD	
$	RWWW
NC
SZZ 0!&&9
::tT*(
 ++AGGDA+$$Wk:'ggh)aggq!)""9i8)!^88Iq!''**	Yw	2G
**Wirxx*
8Cvv{]]=#qQQ#f**+a//
O  WWuXG!f**1-GHF	(	V	#h	.	7&	@B==
	--'' ww  !*) 4kfaXTMbMbcfhiMjk*kRXXi0<=D.++/ "
 /
%!; aH}	$	$"7I6CKK1CDEU#!!%(qje1fa			y|Q	/ 1&qje			y|Q	/ Q1fa 
		y|Q	/11""5)!((+qje1fa?D 
kk!_%!~C

(
(k"34/* 56 %&A BD% 
-ueK6H'+|V*
V V9=*
V VK H ls   )U%#U	Uc                l    |dk  r|t        |       z  }t        t        j                  | d      ||      S )Nr   T)sparse)rd   r'   r   rh   )ri   rh   r   s      rM   _make_along_axis_idxrI    s3    	AXCJD	i''d;T7	KKrO   )r   inplacer   r   c               V   |rt        d      t        j                  d| ||      \  } }}|}| j                  }|| j	                         } d}| j
                  |j
                  k(  s&t        d| j
                  d|j
                  d      	 t        j                  ||j                        }t        | j                  ||      }| j                  |   j                  ||	      }	||	j                  |      }	|	S # t         $ r' t        d|j                  d|j                  d      w xY w)
a  Put values into the destination array by matching 1d index and data slices.

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

  The semantics of :func:`numpy.put_along_axis` 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 put.
    indices: array of indices at which to put values.
    values: array of values to put into the array.
    axis: the axis along which to put values. If not specified, the array will
      be flattened before indexing is applied.
    inplace: must be set to False to indicate that the input is not modified
      in-place, but rather a modified copy is returned.
    mode: Out-of-bounds indexing mode. For more discussion of ``mode`` options,
      see :attr:`jax.numpy.ndarray.at`.

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

  See Also:
    - :func:`jax.numpy.put`: put elements into an array at given indices.
    - :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.
    - :func:`jax.numpy.take_along_axis`: extract values from an array along an axis.

  Examples:
    >>> from jax import numpy as jnp
    >>> a = jnp.array([[10, 30, 20], [60, 40, 50]])
    >>> i = jnp.argmax(a, axis=1, keepdims=True)
    >>> print(i)
    [[1]
     [0]]
    >>> b = jnp.put_along_axis(a, i, 99, axis=1, inplace=False)
    >>> print(b)
    [[10 99 20]
     [99 40 50]]
  zjax.numpy.put_along_axis cannot modify arrays in-place, because JAX arraysare immutable. Pass inplace=False to instead return an updated array.put_along_axisr   zOput_along_axis arguments 'arr' and 'indices' must have same ndim. Got arr.ndim=z and indices.ndim=r   zVput_along_axis argument 'values' must be broadcastable to 'indices'. Got values.shape=z and indices.shape=rK  )r
  r   r  ri   r  rc   _broadcast_torI  atsetr8  )
r   rh   valuesr   rJ  r   original_axisoriginal_arr_shaperK   ro   s
             rM   rM  rM    s@   j 
NO O ../?gvV#w-yy	\
))+CD	W\\	!
	&q* 
6F 	SYY6#66#;??6?-&^^./F	- 
 
	+W]],A/ s    C8 80D(c                    t        | t        t        j                  f      xr! t        | t        t        j
                  f       S r   )r4   r~   r:   r.   rD   r1  rK   s    rM   r6   r6   p  s0    	C#rzz*	+	UJsT288DT4U0UUrO   c                    t        | t              xrO | j                  | j                  cxu xr d u nc xr+ t        | j                  t
              xr | j                  dk(  S )N)r4   r,   r   r   r   r~   rU  s    rM   _is_simple_reverse_slicerX  s  sN    
S%
  7
))sxx
'4
'7
SXXs
#7(+B8rO   c                   |dk(  ryt        |       r| | cxk  xr |k  S c S 	 t        j                  |       t        j                  |       }}|dk(  r(t        j
                  |t        j                        r|dv S y#  Y yxY w)Nr   FrV   )Npromise_inbounds)r6   r:   ri   r   r>   r=   r.   )rK   r   r   ri   r>   s        rM   !_is_valid_integer_index_for_slicer[  x  s~    	QYs5C$88C=&,,s"35E b[R]]5"**5---	s   *A< <B c                .   t        | t              xr | j                  d u xs t        | j                        xr] | j                  d u xs t        | j                        xr6 | j
                  d u xs& t        | j
                        xr | j
                  dk(  S )Nr_   )r4   r,   r   r6   r   r   rU  s    rM   _is_contiguous_slicer]    s    
S%
  P99< 1#)) <P88t:0:P 88tN 1#(( ; MAQrO   )out_shardingc          
     
    t        d |j                  D              t        d  j                  D              sy t	        d D              ry t	        d D              ry t	        d D              rt         j                        t               j                  kD  ry t              D ch c]  \  }}t        |      s| c}}t        t         j                              D ch c]  \  }\  }}t        |||      r| }}}}t              D ch c]  \  }}t        |      s| }}}t         t        j                        xr  t!        j"                   j$                         }	t	         fd|D              }
|	r|s|
ry t              t        |      z   t        |      z   t              k7  ry rAt'        j(                   t                     t        fdt              D              |z  }|s|
s S  j                  t              z
  t+        d       fz  z  g }g }g }t-         j                        D ]2  \  }}t        |t*              rg|j                  |      \  }}}|d	k(  sJ |j/                  |       |j/                  t1        d
||z
               |j/                  |d
k  xs |d
k         ~t3        j4                  t7        j8                  |      t2        j:                        sJ t3        j                  |      dk(  sJ |j/                  |       |j/                  d	       |j/                  t        |t<        t2        j:                  f       xs t?        |d
k               5 t        d |D              rR|D cg c]  }t=        |       }}t        ||      D cg c]
  \  }}||z    }}}tA        j*                   ||       nt        |      d	kD  rDtC        jD                   j                  d      }|D cg c]  }t'        jF                  ||       }}tI        jJ                   j                  |||       tM        t@        jN                  ||      }|6tQ        |d      } tS        |||jT                  jV                         |       n	 | |       |rt'        jX                   t        |              S c c}}w c c}}}w c c}}w c c}w c c}}w c c}w )Nc              3  4   K   | ]  }|j                     y wr   )rY   r   rm   s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s     /!agg/s   c              3  <   K   | ]  }t        |t                y wr   )r4   r~   ra  s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s     3AZ33s   c              3  $   K   | ]  }|d u  
 y wr   rV   ra  s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s      qd s   c              3     K   | ]Q  }t        |t              r?|j                  |j                  |j                  fD ]  }t        j                  |        S y wr   )r4   r,   r   r   r   r   is_symbolic_dimr   rm   elts      rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  sR      	/Au-WWaffaff-	/ 
		c	" 	/	" 	/s   AAc              3  ,   K   | ]  }|t         u   y wr   r2   ra  s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s     $1h$s   rU  c              3     K   | ]8  }|   j                  j                  |         d j                  |   dfk7   : yw)r   r_   Nr   )r   rm   r   rK   s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  sB      7  q6>>#))A,7Asyy|Q;OO 7s   >Ac              3  F   K   | ]  \  }}|v rt        d       n|  y wr   )r,   )r   rm   indsimple_revss      rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s-      .As  !K/dS8 .s   !r_   r   rV   c              3  j   K   | ]+  }t        |t        t        j                  f      xr |d k\   - ywr   )r4   r~   r:   r.   ra  s     rM   r   z4_attempt_rewriting_take_via_slice.<locals>.<genexpr>  s,     LARZZ(	)	4a1f	4Ls   13)r   r   Tr  )r   allow_negative_indicesr   r^  axes)-rf   rh   r   ri   r   _canonicalize_tuple_indexrc   rd   ra   rX  r   r[  r]  r4   r	   	ArrayImplr   is_single_device_shardingshardingr   r   r,   r%   rb   r   r:   r=   r   r>   r.   r~   rD   r   r,  int_dtype_for_shaper   	jnp_error%_check_precondition_oob_dynamic_slicer   dynamic_slicer   r   meshexplicit_axesr   )r   indexerr   r^  rm   rl  r   int_indicescontiguous_slices
is_shardedhas_partial_slicesr   r   ro  r   r   r   int_start_indicessint_limit_indicesr:  rK   internal_dsrm  s   `                    ` @rM   !_attempt_rewriting_take_via_slicer    s    	/w//#	33	3 C   	/	/ / $$$ $CHH#
6CX!*3Qvq#3KC3PQ+)23sCII3F)G H H~q+35c4F  H+ H'0~SVQ9Mc9RqSS 30 E66s||DD  7$57 7[$6K((3/@+AASXM
''#u[)
*C
 .'n. .C$
+J#((SX
%+	//#')-+')C+ Cic4#u++d+eT4QYY5!Qu-.##EAI$9:]]6<<,bjj999XXc]b   3##sBJJ/0
0
ADqMCC  	LmLL)67AQ77+./@++NO41aQOO
--,<MOC
 =A11#))DIkMZ[cs//[A[m[33		=+/E '//[1GIK*<@lI
#  .. 	]	c ]+c
++c5-
.C	*Y RHS^ 8O \s0   3SS2S$ S+4S+S1?S6S<c                      e Zd ZdZdZdZdZy)IndexingStrategyautor  scatterstatic_sliceN)rQ   rR   rS   AUTOGATHERSCATTERSTATIC_SLICErV   rO   rM   r  r    s    	$&',rO   r  )r   r   r   r   r   r^  strategyc          	        t         j                  || j                        }	t        |t              st        d|       t        j                  j                  rN|:t        j                  j                  |      t        j                  j                  k(  r|	j                  |       |t        j                  k(  r|st        d      |	j!                  |       S |t        j"                  k(  r|rt%        | |	||      }
|
|
S |	j'                         }	t)        |	      \  }}t+        t,        ||||||      }|5t/        |d      } t1        |||j2                  j4                        | |      S  || |      S )Nz.Expected strategy to be IndexingStrategy; got r   zDstrategy=STATIC_SLICE is only supported when normalize_indices=True.)r   r^  )treedefr   r   r   r   r   r   rp  )rv   r{   ri   r4   r  r@   r
   check_static_indicesvaluer   r  from_anyr  r   r  r
  r   r  r  r   r   r   _gatherr   r   rz  r{  )r   rK   r   r   r   r   r   r^  r  r|  ro   dynamic_idxr  internal_gathers                 rM   rewriting_taker    s    &&sCII6'	H.	/
DXJO
PP  &&DLG<U<U<^<^_c<dho  iB  iB  iT  iT  =T##6G#H!...]^^++C00
 !&&&+<.sG$UabFm'')'%g.+ww+NJ:KM/ (v>L9_<&++99K) ) 
k	**rO   c          
     0   t        ||      }|j                  t        j                  |       j                  |      }	t        j                  | j                  |	j                         | }
|tt        j                  d |d       t        j                  |      dk7  rt        d      t        |t        j                  t        j                   f      r|j#                         }|	j$                  r t'        j(                  |
|	j$                        }
t        j*                  |	j,                        r"t'        j.                  |
d|	j,                        S t        j*                  |	j                  j                        sWt1        j2                  |
|	j                  |	j4                  |	j6                  |xs |	j8                  |xs |	j:                  ||      }
|	j<                  r t'        j>                  |
|	j<                        }
t'        j(                  |
|	j@                        S )Nr   z$fill_value argument to indexed get()r   z5fill_value argument to indexed get() must be a scalarr   )r   r   r   r   )!r   r   r   typeofru  rw  _check_precondition_oob_gatherri   rB  concrete_or_errorr:   rc   r
  r4   r;   r   r<   itemscalar_bool_dimsr   expand_dimsis_empty_shapeslice_shaper  r   r  r  gather_slice_shaper   r   reversed_y_dimsr   newaxis_dims)r   r  r  r   r   r   r   r   
parsed_idxr|  ys              rM   r  r  1  s   g{3*  S!1!:!:3D ! F'**399g6L6LM	!4AC	wwzaNOO*rzz8+@+@AB??$j7334A 
,,-==AW%8%899 
		W3399	:	7!!7=='2L2L%?)?)?-K1K1Kj		*A 7**+A	G00	11rO   c                  v    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Zded<   y)r   zSequence[int]r  r  r!   rB  zslicing.GatherDimensionNumbersr  rD   r   r   r  r  r  NzNamedSharding | Noneslice_sharding)rQ   rR   rS   r]   r  rV   rO   rM   r   r   X  sM    ##	''
  !   "! *..&-rO   r   r   c                 ./ | j                          | j                         } t        j                  | j                  D cg c].  }|j
                  t        j                  t        j                  hv 0 c}      }t        j                  t        j                  |      dk(        }| j                         } t        | j                        D cg c]%  \  }}|j
                  t        j                  k(  s$|' }}}| j                  |j                        \  } }	|r| j!                         } g }
g }g }| j#                         rht        | j                        D cg c]'  \  }}|j
                  t        j$                  k7  s$||f) }}}d t        |      D        }t'        |      \  }
}}d}d}d}g }g }g }t)        j*                  | j,                  d      .g }g }g }g }g }g }g }t        | j                        D ]w  \  }}|
r|r||d   k(  s|s|dk(  rt/        j0                  |
 }|d   j,                  } t3        j4                  |d         j6                  j                  }!t9        |       }"t9        |      /|j;                  ./fd|D               || z  }|J |j;                  |       |j;                  |       |j;                  |        |j;                  |!       ||"z  }||"z  }||v r|dz  }|j=                  d       |j
                  t        j                  t        j                  fv rt        j>                  |j@                        dk(  rt3        jB                  | j,                  |   d      rtE        d| d      tG        jH                  |j@                  .      }#|j=                  |#t9        |      f       |j=                  |       |j=                  d       |j=                  |       |dz  }|j
                  t        j$                  k(  r:|j=                  d       |j=                  d        |j=                  |       |dz  }X|j
                  t        jJ                  k(  rtM        |j@                  tN              sJ t3        jP                  |j@                  | j,                  |         \  }$}%}&|j=                  |&       |j=                  |	|          t3        jB                  |%d      rt3        jB                  |&| j,                  |         sA|j=                  tG        jH                  |$.      t9        |      f       |j=                  |       |j=                  |&       |j=                  |       ntS        jT                  |$.	      tS        jT                  |%.	      tG        jV                  .|&      z  z   }'|%dk  r(|j=                  |       tG        jX                  |'d
      }'|j=                  d       |j=                  |'t9        |      f       |j=                  |       |j=                  |&       |j=                  |       |dz  }|dz  }|dz  }itE        d| d|       t9        |      dk(  rt        jZ                  d
.	      }(nt9        |      dk(  r*|d   \  })}*tG        j\                  |)|)j>                  f      }(nzt9        |      }+|j=                  d       tG        j^                  |D )cg c]<  \  })}tG        j`                  |)|tc        te        |||)j>                  z                     > c}})|+      }(tg        jh                  tc        |      tc        tk        |            tc        |            },|jm                  |      }-to        |tc        |      |||,|(|
 |
 ||-
      S c c}w c c}}w c c}}w c c}})w )Nr_   c              3     K   | ]X  \  }\  }}|j                   t        j                  t        j                  fv r$t	        j
                  |j                        ||f Z y wr   )rZ   r*   r?   r7   r   rC   rY   )r   rE  rm   es       rM   r   z#_index_to_gather.<locals>.<genexpr>  sQ      
!Va	
9??I$5$56	6 !1a(s   AA r   Tr  c              3  N   K   | ]  }t        j                  |      f  y wr   )r   r   )r   r   r:  	start_dims     rM   r   z#_index_to_gather.<locals>.<genexpr>  s+       ##A{3Y
?s   "%z index is out of bounds for axis z with size 0r"  )r   )
dimensionsz$Got unsupported indexer at position z: r   )spec)
r  r  r  r  r  rB  r   r   r  r  )8r   r   r:   nonzerorh   rZ   r*   r?   r7   r   diffr   ra   r9   r   r  r   r   r1   r(   r,  rv  ri   r   _broadcast_arraysr   r  ru  rd   r   rb   rc   rY   r7  rI   r   r   r5   r4   r,   canonicalize_slicer   r	   iotar   zerosr  r9  broadcast_in_dimrf   rg   r   r  sortedupdater   )0r|  r   r   rK   is_advancedadvanced_axes_are_contiguousnrm   r  x_specadvanced_indexesidx_advanced_axesx_advanced_axesdidx_without_noneadvanced_pairsx_axisy_axiscollapsed_y_axisr   r   r   rB  gather_indices_shaper  r  r  r  
slice_specidx_posrY   advanced_index_arrsri   aia_specrc   i_convertedr   r   
slice_sizerh   gather_indices_arraygr   last_dimr  r  r:  r  s0                                                 @@rM   r   r   x  s#   	//1'

W^WfWfgPSCGG	9J9J'KKgh+!#(<(A!B##%'3<W__3M$l41aQRQVQVZcZkZkQkQ$l$l66zG/'6'')G ') &( $&/$$&+4W__+Ea41aR[R`R`I`Aaa !12N
 <B.;Q8'&& +$&!/--gmmDI+ -/.$&
 + ,!/"$*!'//2 TTngu 		%'5Fq5I*I)gl 224DE!!$**e034==BBhZd*+i &  e#(((_-!!/2!nf$ ##kf"yyY&&	88RWWU[[=QUV=V			w}}V4a	8;F8<PQQ,,U[[+Fk[#.B*CDE!!&)"V$kf	inn	$&!kf	ioo	%U+++ $ 7 7W]]SYEZ [eT:$v'			tQ	'$$Zv1FG


!9!9%!M #$8 9!; <

 
 
(!!*-+,??5<??4{;chh{T^>__`!8

 
 !1
2GGG5'!!!$w,@(ABCv&##J/##F+!kfkf=gYb	RSSiTTl 	A&(hht;&G
>a!DAq??1qvvi8'(H"?? ,"
!Q 
12E%1qvv::N4OP," 
 
(
($ (<!=>O,%
 $$*$5.	|$)#
'''++%!

# 
#S h
 %m( bJ,"s%    3^9%^>3^>%_>_A_

c                    t        | t        j                  t        t        j
                  f      xr t        j                  |       dk7  xs& t        | t        t        f      xs | t        u xs | du S )z.Helper for eliminate_deprecated_list_indexing.r   N)
r4   r:   r;   r    r   r<   rc   r   r,   r2   xs    rM   _should_unpack_list_indexr  2  sf    
QUH,A,AB
C ggajAo(He,-( (](  4i)rO   c                   t        | t              sst        | t              r`t        | t        t        j
                  t        j                  t        f      s,t        d | D              rd}t        |      d}t        |      | f} | S )Nc              3  2   K   | ]  }t        |        y wr   )r  ra  s     rM   r   z5eliminate_deprecated_list_indexing.<locals>.<genexpr>E  s     7a&q)7r   zUsing a non-tuple sequence for multidimensional indexing is not allowed; use `arr[tuple(seq)]` instead of `arr[seq]`. See https://github.com/jax-ml/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/jax-ml/jax/issues/4564 for more information.)r4   rf   r   r    r:   r;   r   r<   rA   r   r@   )rK   r;  s     rM   rz   rz   9  s{     
C	#x eRZZ!6!6<* 
737	7U cNU cNFc	*rO   c                8   	 t        j                  |       }t        |t         j                        xr. t        j                  |j                  t        j                        xs( t        | t              xr | xr t        d | D              S # t        $ r d }Y w xY w)Nc              3     K   | ]H  }t        |      xr7 t        j                  t        j                  |      t        j
                         J y wr   )
_is_scalarr   r=   r>   r:   r1  r   r  s     rM   r   z$_is_boolean_index.<locals>.<genexpr>X  sD      /G?@ 0:!} 0;Q:0; /Gs   AA)r   r   r@   r4   ShapedArrayr   r=   r>   r:   r1  r   r   )rm   
abstract_is     rM   r8   r8   R  s    q!J Z!1!1
2
dv7H7HIYIY[][c[c7d G4  GQ G3 /GDE/G ,GH 
 Js   B BBc                ~    | yt        j                  |       ry	 t        j                  |       S # t        $ r Y yw xY w)z)Return True if elt is a constant or None.TF)r   re  r   r@   )rg  s    rM   r   r   \  sA    [	#tC  	 s   0 	<<c                    t        j                  |       xsI t        | t         j                  t        j
                  t        f      xr t        j                  |       dk(  S )z#Checks if a Python or NumPy scalar.r   )r:   isscalarr4   r;   r   r<   r    rc   r  s    rM   r  r  e  sF    	Q 
RZZ!6!6>? 
''!*/rO   c           	        t        d |D              }|| kD  r|dk(  rdnd}t        d|  d| d| d      d	 t        |      D        }t        |d
      }|Wt        |d
      &t        dt	        t        t        |             d      t        d
      f| |z
  z  }|d
| |z   ||dz   d
 z   }|S || 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 xs |t         u xs t        |t                ' y wr   )r2   r4   rD   r  s     rM   r   z,_canonicalize_tuple_index.<locals>.<genexpr>n  s.     e\]Q$Y%V!x-%V:aQUCV Wes   +-r_   rY   rh   zToo many indices: z -dimensional array indexed with z	 regular r   c              3  8   K   | ]  \  }}|t         u s|  y wr   ri  rf  s      rM   r   z,_canonicalize_tuple_index.<locals>.<genexpr>t  s     @FAsxa@s   Nz'Multiple ellipses (...) not supported: )	re   rI   ra   nextr   maprH   r,   rf   )arr_ndimrK   num_dimensions_consumedindex_or_indicesellipsesellipsis_indexcolonss          rM   rr  rr  l  s&   eadeex'"9Q">wI

XJ ''(	2B1C1	FG G Ain@($'.Hd'3DT34H3I
KM MDk^x*AABF
o~

'#nq.@.A*B
BC 
* )Dk^x*AABF
*v
C	*rO   )rJ  c               L   t        j                  d| ||      \  }}}|j                         }|rt        d      |j                  |j                  k7  rt        d      |j                  st        d      |j                  s|S t        j                  |j                         |j                  |j                        d   }t        j                  |t        |            }|j                         j                  |   j                  |d      j                  |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 array)r   r   r   droprK  )r   r  r  r
  r   r   r   _tile_to_sizerd   rO  rP  r8  ri   )r   maskvalsrJ  datamask_arrvals_arrrh   s           rM   r  r    s    v "227CtL$(^^(
?@ @ 
YY(--
@
AA	
>
??	KOOHNN,8==X]][\]^'$$Xs7|<(		!	%	%hV	%	<	D	DTZZ	PPrO   c               p   |rt        d      t        j                  d| ||      \  }}}|j                         }t	        j                  |      }|j
                  r|j
                  r|j
                  s|S t	        j                  |t        |            }|d}	na|dk(  r't	        j                  |d|j
                  dz
        }d}	n5|dk(  r||j
                  z  }d}	n|d	k(  rt        d
      t        d|      |j                  t	        j                  ||j                           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)
  zjax.numpy.put cannot modify arrays in-place, because JAX arrays are immutable. Pass inplace=False to instead return an updated array.putr  r   r   r_   r'  r   r   z-The 'raise' mode to jnp.put is not supported.z1mode should be one of 'wrap' or 'clip'; got mode=rK  )r
  r   r  r  r   r   r  rd   r   r  rO  unravel_indexri   rP  )
r   rl  vr   rJ  r   ind_arrr   v_arrscatter_modes
             rM   r  r    s!   B 
?@ @ ))%C;/#wMMO'
//!
%	UZZJ

!
!%W
6%	\Lv~nnWaA6G&Lv~ G&Lw
M
NN
ID7K
LL		'';	<	@	@\	@	ZZrO   )rh   ztuple[Index, ...]ri   r[   rP   rw   )NNNFFN)r   r!   rh   r!   r   
int | Noner   r   r   
str | Noner   rD   r   rD   r   StaticScalar | NonerP   r    )r   r  )rW  NN)r   r!   rh   r!   r   r  r   &str | slicing.GatherScatterMode | Noner   r  rP   r    r   )r   r!   rh   r!   rQ  r!   r   r  rJ  rD   r   r  rP   r    )rK   r   rP   rD   )
r   r    r|  rv   r   r  r^  $NamedSharding | PartitionSpec | NonerP   zArray | None)r   r    rK   r   r   rD   r   rD   r   r  r   zArrayLike | Noner   rD   r^  r  r  r  rP   r    )r|  rv   r   r   r   rD   rP   r   )
r   r!   r  r!   r  r!   rJ  rD   rP   r    r   )r   r!   rl  r!   r  r!   r   r  rJ  rD   rP   r    )]rT   
__future__r   dataclassesenum	functoolsr   r   r2  typingr   r   collections.abcr   numpyr:   jax._srcr   r	   r
   r   r   r   r   r   jax._src.laxr   r   r   r,  jax._src.numpyr   r   r   rw  r   r   r   jax._src.partition_specr   jax._src.pjitr   jax._src.sharding_implsr   r   jax._src.tree_utilr   r   r   jax._src.typingr    r!   r"   r#   jax._src.utilr$   r%   r&   r'   r(   exportEnumr*   rX   rr   	dataclassrv   r   jitr   r  r  rI  rM  r6   rX  r[  r]  r  r  r  r  r  r   r   r  rz   r8   r   r  rr  r  r  rV   rO   rM   <module>r     s[    # "      " $             + - ! - $ !  1 # H W W A A W W	K	 
0W		 0Wf!* !::: :z dD1u- u- 2 u-p   $&*V&V&V& V& 
	V&
 V& V& V& $V& V& V&r 	_`>BEI1V a1VhG 78 37&*V	VV V 1	V
 $V V 9 VDL 45 U UUU U 		U
 U 	U U 6 UtV8
Q :>g	g"g
0g 7g COgT tyy    % 37#'"9=!1!6!6.+	.+	".+ .+ 	.+
 1.+ !.+ .+ 7.+ .+ .+h$2N.Z .B 04x#(,x#8Fx#t)2H, HQHQ#(HQ HQV V[48V[V[-1V[=BV[ V[rO   