
    Cd0                    <   d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	 ddl
mZ ddlZddlmZ ddlmZ d	 Zej        Zej        Zej        Zej        Z eej                  Z eej                  Z eej                  Z eej                  Zej        Zej        Zej        Zej        Zej        Zej         Z ej!        Z!ej"        Z"ej#        Z# ej$        e%          5  ej&        Z&ddd           n# 1 swxY w Y   ej'        Z' ej$        e%          5  ej(        Z(ddd           n# 1 swxY w Y   ej)        Z) ej$        e%          5  ej*        Z*ddd           n# 1 swxY w Y   ddZ+ddZ,d Z-d Z.d Z/d Z0d Z1ddZ2ddZ3ddZ4ddZ5d Z6d Z7d Z8dS )z- A set of NumPy functions to apply per chunk     )annotationsN)	ContainerIterableSequencewraps)Integral)concat)flattenc                >     t                     d fd	            }|S )zU
    A wrapper for functions that don't provide keepdims to ensure that they do.
    Nc                :    	| g|R d|i|}|s|S |}|t          | j                  }t          |t          t          t
          f          s|g}t                      }t          | j                  D ]}||v r|dz  }|t          d           fz  } ||         }|S )NaxisN)rangendim
isinstancer   r   r   tupleslice)
xr   keepdimsargskwargsraxesr_slice	each_axis
a_callables
            0lib/python3.11/site-packages/dask/array/chunk.pykeepdims_wrapped_callablez3keepdims_wrapper.<locals>.keepdims_wrapped_callable   s    Jq54555d5f55 	H<==D$Hh ?@@ 	6D''qv 	* 	*ID  7"E$KK>)gJ    )NNr   )r   r   s   ` r   keepdims_wrapperr!      s>    
 :     2 %$r    Fc                   t          j                  D ]}|vrd|<   |r5t          fdt          j                  D                       }|         t          t          fdt          j                  D                                 } |                     |          fdt          t          dj        dz  d                    i|S )a  Coarsen array by applying reduction to fixed size neighborhoods

    Parameters
    ----------
    reduction: function
        Function like np.sum, np.mean, etc...
    x: np.ndarray
        Array to be coarsened
    axes: dict
        Mapping of axis to coarsening factor

    Examples
    --------
    >>> x = np.array([1, 2, 3, 4, 5, 6])
    >>> coarsen(np.sum, x, {0: 2})
    array([ 3,  7, 11])
    >>> coarsen(np.max, x, {0: 3})
    array([3, 6])

    Provide dictionary of scale per dimension

    >>> x = np.arange(24).reshape((4, 6))
    >>> x
    array([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11],
           [12, 13, 14, 15, 16, 17],
           [18, 19, 20, 21, 22, 23]])

    >>> coarsen(np.min, x, {0: 2, 1: 3})
    array([[ 0,  3],
           [12, 15]])

    You must avoid excess elements explicitly

    >>> x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
    >>> coarsen(np.min, x, {0: 3}, trim_excess=True)
    array([1, 4])
       c              3     K   | ]<\  }}||         z  rt          d ||         z             nt          dd          V  =dS )r   Nr   ).0idr   s      r   	<genexpr>zcoarsen.<locals>.<genexpr>   sk       
 
1 )*DGJE!q47{^$$$tT9J9J
 
 
 
 
 
r    c                L    g | ] }j         |         |         z  |         f!S  )shape)r&   r'   r   r   s     r   
<listcomp>zcoarsen.<locals>.<listcomp>   s1    UUU!agajDG3T!W=UUUr    r      )r   r   r   	enumerater,   r
   reshape)	reductionr   r   trim_excessr   r'   indnewshapes    ``     r   coarsenr5   T   s    P 16]]  D==DG  
 
 
 
!!'**
 
 
 
 
 cF VUUUUUuQV}}UUUVVWWH9QYYx((XXuU1afqj!5L5L/M/MXQWXXXr    c                    t          t                    rg| j        z  t          t                    r fdt	          | j                  D             | t          d D                                S )aC  Trim boundaries off of array

    >>> x = np.arange(24).reshape((4, 6))
    >>> trim(x, axes={0: 0, 1: 1})
    array([[ 1,  2,  3,  4],
           [ 7,  8,  9, 10],
           [13, 14, 15, 16],
           [19, 20, 21, 22]])

    >>> trim(x, axes={0: 1, 1: 1})
    array([[ 7,  8,  9, 10],
           [13, 14, 15, 16]])
    c                <    g | ]}                     |d           S )r   )get)r&   r'   r   s     r   r-   ztrim.<locals>.<listcomp>   s%    6661A666r    c              3  @   K   | ]}t          ||r| nd           V  d S r   r%   )r&   axs     r   r)   ztrim.<locals>.<genexpr>   s7      AAb5B0bSSD11AAAAAAr    )r   r	   r   dictr   r   )r   r   s    `r   trimr<      sy     $!! v$ 76666af666UAADAAAAABBr    c                H   |du sJ d         t          |          | j                 k    r| S t          j        | |           } |dk    rt	          | d          nt	          |           | t          fdt          | j                  D                                S )a  Chunk and combine function of topk

    Extract the k largest elements from a on the given axis.
    If k is negative, extract the -k smallest elements instead.
    Note that, unlike in the parent function, the returned elements
    are not sorted internally.
    Tr   r   Nc              3  F   K   | ]}|k    rnt          d           V  d S r   r%   r&   r'   r   k_slices     r   r)   ztopk.<locals>.<genexpr>   s5      PPQa4ii77U4[[PPPPPPr    )absr,   np	partitionr   r   r   r   )akr   r   rA   s     ` @r   topkrG      s     t7D
1vv
Q&&&A!"QeQBoooE1"IIGUPPPPP%--PPPPPQQr    c                    |du sJ t          | ||          } d         t          j        |           } |dk     r| S | t          fdt	          | j                  D                                S )zmFinal aggregation function of topk

    Invoke topk one final time and then sort the results internally.
    Tr   r>   c              3  d   K   | ]*}|k    rt          d d d          nt          d           V  +d S Nr%   r&   r'   r   s     r   r)   z!topk_aggregate.<locals>.<genexpr>   S       
 
DEQ$YYE$b!!!E$KK
 
 
 
 
 
r    )rG   rC   sortr   r   r   )rE   rF   r   r   s     ` r   topk_aggregaterO      s    
 tQ4""A7D
A1uu 
 
 
 
INqv
 
 
 	
 	
 r    c                
    | |fS )z^Preparatory step for argtopk

    Put data together with its original indices in a tuple.
    r+   )rE   idxs     r   argtopk_preprocessrR      s    
 c6Mr    c                   |du sJ d         t          | t                    r[t          t          |                     } t          j        d | D                       }t          j        d | D                       }n| \  }}t          |          |j                 k    r| S t          j        ||           }|dk    rt          | d          nt          |           |t          fdt          |j                  D                                }t          j        ||          t          j        ||          fS )a)  Chunk and combine function of argtopk

    Extract the indices of the k largest elements from a on the given axis.
    If k is negative, extract the indices of the -k smallest elements instead.
    Note that, unlike in the parent function, the returned elements
    are not sorted internally.
    Tr   c                    g | ]\  }}|S r+   r+   )r&   ai_s      r   r-   zargtopk.<locals>.<listcomp>   s    77752qB777r    c                H    g | ]\  }}t          j        ||j                   S r+   )rC   broadcast_tor,   )r&   rU   idxis      r   r-   zargtopk.<locals>.<listcomp>   s*    HHHTR_T28,,HHHr    r>   Nc              3  F   K   | ]}|k    rnt          d           V  d S r   r%   r@   s     r   r)   zargtopk.<locals>.<genexpr>   s5      SSdggdSSSSSSr    )r   listr   rC   concatenaterB   r,   argpartitionr   r   r   r   take_along_axis)
a_plus_idxrF   r   r   rE   rQ   idx2rA   s     `    @r   argtopkra      sK    t7D*d## '*--..
N77J777>>nHHZHHH$
 
 3
1vv?1qbt,,,D!"QeQBoooE1"IIGSSSSSU16]]SSSSSTDat,,b.@dD.Q.QQQr    c                R   |du sJ t          |           dk    r| n| d         } t          | ||          \  }}d         t          j        |          }t          j        ||          }|dk     r|S |t          fdt          |j                  D                                S )zFinal aggregation function of argtopk

    Invoke argtopk one final time, sort the results internally, drop the data
    and return the index only.
    Tr#   r   r>   c              3  d   K   | ]*}|k    rt          d d d          nt          d           V  +d S rJ   r%   rL   s     r   r)   z$argtopk_aggregate.<locals>.<genexpr>   rM   r    )lenra   rC   argsortr^   r   r   r   )r_   rF   r   r   rE   rQ   r`   s     `    r   argtopk_aggregaterf      s     t":22
1JZD(33FAs7D:ad###D

S$
-
-C1uu
 
 
 
 
INsx
 
 
 	
 	
 r    c                l    ddl m}  || ||||          }t          |          |k    r
|d d         n|S )Nr   )arange_safelikerK   )dask.array.utilsrh   rd   )startstopsteplengthdtyperj   rh   ress           r   arangerr     sP    ,,,,,,
+eT4T
:
:
:C3xx&((3ss88c1r    Tc                    ddl m} t          | |          r|                                 } t          ||          r|                                }t	          j        | ||||          S )Nr   )Array)endpointrp   )dask.array.corert   r   computerC   linspace)rl   rm   numru   rp   rt   s         r   rx   rx   	  sm    %%%%%%%  $ ||~~;udC(%HHHHr    c                     | j         |fi |S r   )astype)r   astype_dtyper   s      r   r{   r{     s    18L++F+++r    Cc                f   |dk    rQ	 t          j        | |           } n$# t          $ r t          j        |           } Y nw xY w|                     |          S 	 t          j        | |           } n$# t          $ r t          j        |           } Y nw xY w| j                            |          j        S )Nr}   ri   )rC   ascontiguousarray	TypeErrorviewasfortranarrayT)r   rp   orders      r   r   r     s    ||	($QQ///AA 	( 	( 	($Q''AAA	(vve}}	%!!!,,,AA 	% 	% 	%!!$$AAA	%sxx  s     A A A0 0BBc                l   ddl m}m}  | ||                                         t          j                  t	          j        dk     |z             |z
  dk    | j                 k     z  }|         | t          fdt          | j
                  D                                S )a  Chunk function of `slice_with_int_dask_array_on_axis`.
    Slice one chunk of x by one chunk of idx.

    Parameters
    ----------
    x: ndarray, any dtype, any shape
        i-th chunk of x
    idx: ndarray, ndim=1, dtype=any integer
        j-th chunk of idx (cartesian product with the chunks of x)
    offset: ndarray, shape=(1, ), dtype=int64
        Index of the first element along axis of the current chunk of x
    x_size: int
        Total size of the x da.Array along axis
    axis: int
        normalized axis to take elements from (0 <= axis < x.ndim)

    Returns
    -------
    x sliced along axis, using only the elements of idx that fall inside the
    current chunk.
    r   )asarray_safemeta_from_arrayri   c              3  F   K   | ]}|k    rnt          d           V  d S r   r%   )r&   r'   r   rQ   s     r   r)   z,slice_with_int_dask_array.<locals>.<genexpr>S  s5      LL!t))33tLLLLLLr    )rk   r   r   r{   rC   int64wherer,   r   r   r   )r   rQ   offsetx_sizer   r   r   
idx_filters    `  `   r   slice_with_int_dask_arrayr   (  s    , ?>>>>>>>
,s!3!3
4
4
4C **RX

C (37C&L#
.
.C
 ,C (sQWT]23J
j/C ULLLLLeAFmmLLLLLMMr    c                  	 |                      t          j                  } t          j        | dk     | t	          |          z   |           } d}d}t          j        |           	|D ]`}| |k    | ||z   k     z  }t          j        |          }	t          j        ||dz
  |z   d          z  	||z  }|j        dk    r||d         z  }a|t          	fdt          |j
                  D                                S )aS  Final aggregation function of `slice_with_int_dask_array_on_axis`.
    Aggregate all chunks of x by one chunk of idx, reordering the output of
    `slice_with_int_dask_array`.

    Note that there is no combine function, as a recursive aggregation (e.g.
    with split_every) would not give any benefit.

    Parameters
    ----------
    idx: ndarray, ndim=1, dtype=any integer
        j-th chunk of idx
    chunk_outputs: ndarray
        concatenation along axis of the outputs of `slice_with_int_dask_array`
        for all chunks of x and the j-th chunk of idx
    x_chunks: tuple
        dask chunks of the x da.Array along axis, e.g. ``(3, 3, 2)``
    axis: int
        normalized axis to take elements from (0 <= axis < x.ndim)

    Returns
    -------
    Selection from all chunks of x for the j-th chunk of idx, in the correct
    order
    r   r#   rK   c              3  F   K   | ]}|k    rnt          d           V  d S r   r%   )r&   r'   r   	idx_finals     r   r)   z6slice_with_int_dask_array_aggregate.<locals>.<genexpr>  sF       
 
89dIId
 
 
 
 
 
r    )r{   rC   r   r   sum
zeros_likecumsumsizer   r   r   )
rQ   chunk_outputsx_chunksr   x_chunk_offsetchunk_output_offsetx_chunkr   idx_cumr   s
      `     @r   #slice_with_int_dask_array_aggregater   V  s+   4 **RX

C (37C#h--/
5
5CN c""I / /^+nw6N0NO
)J''RXj'A+8K*KQOOO	'!<!72;.  
 
 
 
 
=B=CU=V=V
 
 
 	
 	
 r    c                    	 | |         }n"# t           $ r}t          d          |d}~ww xY w	 |j        j        s'| j        d|j        z  k    r|                                }n# t          $ r Y nw xY w|S )af  Getitem function

    This function creates a copy of the desired selection for array-like
    inputs when the selection is smaller than half of the original array. This
    avoids excess memory usage when extracting a small portion from a large array.
    For more information, see
    https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing.

    Parameters
    ----------
    obj: ndarray, string, tuple, list
        Object to get item from.
    index: int, list[int], slice()
        Desired selection to extract from obj.

    Returns
    -------
    Selection obj[index]

    zTArray chunk size or shape is unknown. Possible solution with x.compute_chunk_sizes()Nr.   )
IndexError
ValueErrorflagsowndatar   copyAttributeError)objindexresultes       r   getitemr     s    *U   =
 
 	|# 	#AO(C(C[[]]F    Ms!    
*%*3A" "
A/.A/)Fr   )TN)r}   )9__doc__
__future__r   
contextlibcollections.abcr   r   r   	functoolsr   numbersr	   numpyrC   tlzr
   	dask.corer   r!   r   prodminmaxargmin	nanargminargmax	nanargmaxanyallnansumnanprod
nancumprod	nancumsumnanminnanmaxmeansuppressr   nanmeanvarnanvarstdnanstdr5   r<   rG   rO   rR   ra   rf   rr   rx   r{   r   r   r   r   r+   r    r   <module>r      s   3 3 " " " " " "     9 9 9 9 9 9 9 9 9 9                            % % %F 	f	wff		")	$	$R\**			")	$	$R\**	ff	
*]
L				wZ((  jG               	fZ((  YF               	fZ((  YF              6Y 6Y 6Y 6YrC C C C,R R R$  $  R R R:  ,2 2 2 2	I 	I 	I 	I, , , ,! ! ! !+N +N +N\5 5 5p# # # # #s6   !C55C9<C9D++D/2D/E!!E%(E%