
    Cd                       d dl mZ d dl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mZ d dlmZmZ d dlZd dlmZmZmZ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!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' d dl(m)Z)m*Z* d dl+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@mAZAmBZBmCZCmDZDmEZE d[dZFd ZGd ZH	 	 	 	 	 	 	 	 	 	 	 d\dZI	 	 	 	 	 d]dZJ	 d^dZK eBe          d_d            ZL eBe          d_d            ZM e&ejN        ejO                   eBe          d`d                        ZNdad ZP e&ejQ        ejR                   eBe          d`d!                        ZQdad"ZS eBe          d`d#            ZT eBe          d`d$            ZU eBe          d_d%            ZV eBe          d_d&            ZW eBe          dad'd(d)            ZX eBe          dad'd(d*            ZY eBe          d`d+            ZZd, Z[ eBe          d`d-            Z\d. Z]ejL        eGd/dfd0Z^ejL        eGd/ddfd1Z_dbd2Z` eBe          d_d3            Za eBe          d_d4            Zbd5ejL        eGd/dfd6Zcd7 Zdd5d d/ejL        ddfd8Zed5d d/ejL        ddfd9Zf	 dcd:Zg eBe          dcd;            Zh eBe          	 dcd<            Zid= Zjd> Zk eBe          dcd?            Zl eBe          	 dcd@            ZmdddAZndB Zod[dCZpdedDZqdedEZr	 d`dFZsdG ZtdH Zu eBe          d`dI            Zv eBe          d`dJ            Zw eBe          d`dK            Zx eBe          d`dL            ZydM ZzdN Z{dfdOZ|	 	 	 	 	 dgdPZ}dQ Z~dR Z eBe          dhdS            Z eBe          dhdT            ZdidVZdidWZ eBe          djdX            Z eBe          dkdY            Z eBe          dkdZ            ZdS )l    )annotationsN)Iterable)partial)productrepeat)IntegralNumber)
accumulatecomposedropgetpartition_allpluck)config)chunk)	blockwise)Array_concatenate2
asanyarraybroadcast_to
handle_out
implementsunknown_chunk_message)arangediagonal)divide_lookupnannumel_lookupnumel_lookup)
array_safeasarray_safecompute_metais_arraylikemeta_from_arrayvalidate_axis)oneszeros)tokenize)
lol_tuples)HighLevelGraph)applydeepmapderived_fromfuncname
getargspecis_series_likec           	         d }t          j        t          t          j        | ||                              } || ||          S )Nc                >    t          | dt          d                    S )N__array_priority__z-inf)getattrfloat)xs    5lib/python3.11/site-packages/dask/array/reductions.py<lambda>zdivide.<locals>.<lambda>5   s    GA3U6]]CC     )keydtype)r   dispatchtypebuiltinsmax)abr;   r9   fs        r6   dividerC   4   sJ    
C
CCtHLA3$?$?$?@@AAA1Qr8   c                    t          | fi |S N)r   r5   kwargss     r6   numelrH   :   s    $$V$$$r8   c                    t          | fi |S rE   )r   rF   s     r6   nannumelrJ   >   s    1'''''r8   FT   c                   !t          t          | j                            t          t                    rft          | j                  |t          d          dt          |          j        v rt          ||          }dt          |          j        v rt          ||          }t          |           r| j        } t          t          | j                            }| |f}|Zt          |          }	 t          || j                  }n-# t          $ r  t          d|j         d| j                   w xY w|||fz  }t          ||g|R d||pt           d}t          fd	t#          |j                  D                       |_        |jt)          | d
          rZ	 t+          || j        | j        dd          }n;# t0          $ r! t+          || j        | j        d          }Y nt          $ r Y nw xY wd}t3          ||||||||
|
  
        }|r9dk    r3t          fdt#          |j                  D                       |_        |||_        t5          |	|          S )an  General version of reductions

    Parameters
    ----------
    x: Array
        Data being reduced along one or more axes
    chunk: callable(x_chunk, [weights_chunk=None], axis, keepdims)
        First function to be executed when resolving the dask graph.
        This function is applied in parallel to all original chunks of x.
        See below for function parameters.
    combine: callable(x_chunk, axis, keepdims), optional
        Function used for intermediate recursive aggregation (see
        split_every below). If omitted, it defaults to aggregate.
        If the reduction can be performed in less than 3 steps, it will not
        be invoked at all.
    aggregate: callable(x_chunk, axis, keepdims)
        Last function to be executed when resolving the dask graph,
        producing the final output. It is always invoked, even when the reduced
        Array counts a single chunk along the reduced axes.
    axis: int or sequence of ints, optional
        Axis or axes to aggregate upon. If omitted, aggregate along all axes.
    keepdims: boolean, optional
        Whether the reduction function should preserve the reduced axes,
        leaving them at size ``output_size``, or remove them.
    dtype: np.dtype
        data type of output. This argument was previously optional, but
        leaving as ``None`` will now raise an exception.
    split_every: int >= 2 or dict(axis: int), optional
        Determines the depth of the recursive aggregation. If set to or more
        than the number of input chunks, the aggregation will be performed in
        two steps, one ``chunk`` function per input chunk and a single
        ``aggregate`` function at the end. If set to less than that, an
        intermediate ``combine`` function will be used, so that any one
        ``combine`` or ``aggregate`` function has no more than ``split_every``
        inputs. The depth of the aggregation graph will be
        :math:`log_{split_every}(input chunks along reduced axes)`. Setting to
        a low value can reduce cache size and network transfers, at the cost of
        more CPU and a larger dask graph.

        Omit to let dask heuristically decide a good default. A default can
        also be set globally with the ``split_every`` key in
        :mod:`dask.config`.
    name: str, optional
        Prefix of the keys of the intermediate and output nodes. If omitted it
        defaults to the function names.
    out: Array, optional
        Another dask array whose contents will be replaced. Omit to create a
        new one. Note that, unlike in numpy, this setting gives no performance
        benefits whatsoever, but can still be useful  if one needs to preserve
        the references to a previously existing Array.
    concatenate: bool, optional
        If True (the default), the outputs of the ``chunk``/``combine``
        functions are concatenated into a single np.array before being passed
        to the ``combine``/``aggregate`` functions. If False, the input of
        ``combine`` and ``aggregate`` will be either a list of the raw outputs
        of the previous step or a single output, and the function will have to
        concatenate it itself. It can be useful to set this to False if the
        chunk and/or combine steps do not produce np.arrays.
    output_size: int >= 1, optional
        Size of the output of the ``aggregate`` function along the reduced
        axes. Ignored if keepdims is False.
    weights : array_like, optional
        Weights to be used in the reduction of `x`. Will be
        automatically broadcast to the shape of `x`, and so must have
        a compatible shape. For instance, if `x` has shape ``(3, 4)``
        then acceptable shapes for `weights` are ``(3, 4)``, ``(4,)``,
        ``(3, 1)``, ``(1, 1)``, ``(1)``, and ``()``.

    Returns
    -------
    dask array

    **Function Parameters**

    x_chunk: numpy.ndarray
        Individual input chunk. For ``chunk`` functions, it is one of the
        original chunks of x. For ``combine`` and ``aggregate`` functions, it's
        the concatenation of the outputs produced by the previous ``chunk`` or
        ``combine`` functions. If concatenate=False, it's a list of the raw
        outputs from the previous functions.
    weights_chunk: numpy.ndarray, optional
        Only applicable to the ``chunk`` function. Weights, with the
        same shape as `x_chunk`, to be applied during the reduction of
        the individual input chunk. If ``weights`` have not been
        provided then the function may omit this parameter. When
        `weights_chunk` is included then it must occur immediately
        after the `x_chunk` parameter, and must also have a default
        value for cases when ``weights`` are not provided.
    axis: tuple
        Normalized list of axes to reduce upon, e.g. ``(0, )``
        Scalar, negative, and None axes have been normalized away.
        Note that some numpy reduction functions cannot reduce along multiple
        axes at once and strictly require an int in input. Such functions have
        to be wrapped to cope.
    keepdims: bool
        Whether the reduction function should preserve the reduced axes or
        remove them.

    NzMust specify dtyper;   r:   zWeights with shape z' are not broadcastable to x with shape T)axiskeepdimstokenr;   c              3  P   K   | ] \  }}|v rft          |          z  n|V  !d S rE   len.0icrM   output_sizes      r6   	<genexpr>zreduction.<locals>.<genexpr>   sR        8<1199Q!     r8   _meta)rM   rN   computing_metarM   rN   )nameconcatenatereduced_metarK   c              3  0   K   | ]\  }}|v rfn|V  d S rE    rS   s      r6   rX   zreduction.<locals>.<genexpr>   sF       
 
371aa4ii[NNQ
 
 
 
 
 
r8   )tuplerangendim
isinstancer   r$   
ValueErrorr.   argsr   r/   valuesr   r   shaper   r4   	enumeratechunks_chunkshasattrr!   r;   rY   	TypeError_tree_reducer   )r5   r   	aggregaterM   rN   r;   split_everycombiner\   outr]   rW   metaweightsindsrf   wgttmpr^   results      `       `        r6   	reductionry   B   sD   f |U16]]##$!! wqv&&D}-...*U##(((U+++*Y'',,,IU333	a H qvDt9D!!	sAG,,CC 	 	 	-ci - -#$7- -  	 	d t !%DQV  C      @I#*@U@U    CK |7++|		'qwdTRV  LL  	 	 	'qwdT  LLL  	 	 	D	 !  F  
K1$$ 
 
 
 
 
;DSZ;P;P
 
 
 
 
 c6"""s$   ?D *D?*G
 
(H 4	H ?H c
                @   pt          j        dd          t          t                    rfd|D             nwt          t                    rSt          j        t          dt          |          pdz  z            d          }
t          	                    ||
          nt          d          d}t          | j                  D ]b\  }}
|v rY|         dk    rMt          t          j        |t          j        t          j        |
|                                                 }ct!          |p||d          }|r1t#          |t!          t$          t'          |          	                    }t)          |dz
            D ],}t+          || d||pt-          |p|          d
z   |	          } -t!          |||          }|r1t#          |t!          t$          t'          |          	                    }t+          || |||pt-          |          dz   |	          S )zPerform the tree reduction step of a reduction.

    Lower level, users should use ``reduction`` or ``arg_reduction`` directly.
    rp      c                >    i | ]}|                     |d           S )   r   )rT   krp   s     r6   
<dictcomp>z _tree_reduce.<locals>.<dictcomp>  s)    >>>Aq+//!Q//>>>r8   rK   r}   z#split_every must be a int or a dictTr[   axesz-partial)r;   r\   r^   z
-aggregate)rN   r;   r\   r^   )r   r   rd   dictr   r>   r?   intrR   fromkeysre   ri   	numblocksmathceillogr   r   r   sortedrb   partial_reducer-   )r5   ro   rM   rN   r;   rp   rq   r\   r]   r^   ndepthrU   func_s        `         r6   rn   rn      s@   " =M1!=!=K+t$$ @>>>>>>>	K	*	* @L[Q#d)).q-ABCCQGGmmD!,,>??? E!+&& U U1A! 3 3UDIdhq+a.6Q6Q,R,RSSTTE7'idTBBBD HtW]FFFGG519 	
 	
8(7#7i88JF%
 
 
 94(;;;D HtW]FFFGG	)hy))\9!   r8   c           	        |pt          |           dz   t          | |||          z   }fdt          |j                  D             }t	          t          t          t          t          |                     }fdt          |j                  D             }	|sMfdt          |j	                  D             fd}
t          |
|          }t           |
|	                    }	i }t          |t	          |           D ]}\  }}fdt          |          D             }t          fdt          |          D                       }t          |j        ft          |j	                  ||          }| |f||f|z   <   ~t          j        |||g          }|j        }|a	  | |d
          }nR# t$          $ r: 	  | |          }n*# t&          $ r}dt)          |          v r|}Y d	}~nd	}~ww xY wY nt&          $ r Y nw xY wt+          |          re|j	        t          |	          k    rMt          |	          dk    r|                                }n%|                    dt          |	          z            }t1          j        |          rt5          |||	|          S t7          j        t:                    5  |                    |          }d	d	d	           n# 1 swxY w Y   t5          |||	|          S )a  Partial reduction across multiple axes.

    Parameters
    ----------
    func : function
    x : Array
    split_every : dict
        Maximum reduction block sizes in each dimension.

    Examples
    --------
    Reduce across axis 0 and 2, merging a maximum of 1 block in the 0th
    dimension, and 3 blocks in the 2nd dimension:

    >>> partial_reduce(np.min, x, {0: 1, 2: 3})    # doctest: +SKIP
    -c           
         g | ]C\  }}t          t                              |d           t          |                              DS rK   )listr   r   rb   )rT   rU   r   rp   s      r6   
<listcomp>z"partial_reduce.<locals>.<listcomp>P  sS       Q 	];??1a00%((;;<<  r8   c           	     |    g | ]8\  }}|v r-t          d  t          |         |          D                       n|9S )c              3     K   | ]}d V  dS rK   Nr`   )rT   ps     r6   rX   z,partial_reduce.<locals>.<listcomp>.<genexpr>V  s"      ::Aa::::::r8   )ra   r   )rT   rU   rV   rp   s      r6   r   z"partial_reduce.<locals>.<listcomp>U  sc       Q ?@;>N>N::{1~q99::::::TU  r8   c                    g | ]}|v|	S r`   r`   rT   rU   rp   s     r6   r   z"partial_reduce.<locals>.<listcomp>Z  s#    EEE!0D0DA0D0D0Dr8   c                $    t          |           S rE   r~   )r   out_axiss    r6   r7   z partial_reduce.<locals>.<lambda>[  s    3x++ r8   c                V    i | ]%\  }}t          |          d k    |v||d         &S )rK   r   rQ   )rT   rU   jrp   s      r6   r   z"partial_reduce.<locals>.<dictcomp>`  sB     
 
 
A#a&&A++!;BVBVAqtBVBVBVr8   c              3  0   K   | ]}|d          v |V  dS )r   Nr`   r   s     r6   rX   z!partial_reduce.<locals>.<genexpr>c  s1      DD1!0C0CQ0C0C0C0CDDr8   dependenciesNT)rZ   z&zero-size array to reduction operationr   r   r:   rs   )r-   r'   ri   r   r   maprb   rR   rj   rc   r   zipr   r(   r\   r)   from_collectionsrY   rm   re   strr"   sumreshapenpisscalarr   
contextlibsuppressAttributeErrorastype)r   r5   rp   rN   r;   r\   r^   partskeys
out_chunksgetterdskr   r   freedummyggraphrs   er   s     `                 @r6   r   r   :  s   ( 
	$3&$;RW)X)XX 	   ,,  E Cs3//0D   ))  J  .EEEEuQV}}EEE++++64  &&,,--

CD'5/** % %1
 
 
 
"+A,,
 
 
 DDDD	!DDDDDy%--u== !9TGaK+D#QCHHHE7D	4T:::DD 	( 	( 	((tL)) ( ( (;s1vvEE'D(
  	 	 	D	 D 8di3z??::z??a88::DD<<s: 677D	{4 9UD*E:::: 00 	& 	&;;u%%D	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&UD*48888sT   "F0 0
G?;GG?
G.G)$G?)G..G?3	G?>G?6KKKc           
         |At          t          j        d| j                                                  dt
                    }t          | t          j        t          j        |||||          }|S )NrK   r:   r;   rM   rN   r;   rp   rr   )r3   r   r&   r;   r   objectry   r   )r@   rM   r;   rN   rp   rr   rx   s          r6   r   r     sl    }!'2226688'6JJ				 	 	F Mr8   c           
         ||}nAt          t          j        d| j                                                  dt
                    }t          | t          j        t          j        |||||          S Nr   r:   r;   r   )r3   r   r%   r;   prodr   ry   r   r@   rM   r;   rN   rp   rr   dts          r6   r   r     sp    RWT1116688'6JJ	

	 	 	 	r8   c                d    t          | t          t          j        t          ||| j        ||	  	        S N)rq   rM   rN   r;   rp   rr   )ry   	chunk_minr   minr;   r@   rM   rN   rp   rr   s        r6   r   r     :     		g
 
 
 
r8   c                    | j         dk    rt          g | | j        | j                  S t	          j        | ||          S )z-Version of np.min which ignores size 0 arraysr   ndminr;   r[   )sizer   rc   r;   r   r   r5   rM   rN   s      r6   r   r     ?    v{{"aqvQW====vadX6666r8   c                d    t          | t          t          j        t          ||| j        ||	  	        S r   )ry   	chunk_maxr   r?   r;   r   s        r6   r?   r?     r   r8   c                    | j         dk    rt          g | | j        | j                  S t	          j        | ||          S )z-Version of np.max which ignores size 0 arraysr   r   r[   )r   r   rc   r;   r   r?   r   s      r6   r   r     r   r8   c           
     X    t          | t          j        t          j        ||d||          S Nboolr   )ry   r   anyr   s        r6   r   r     5    				 	 	 	r8   c           
     X    t          | t          j        t          j        ||d||          S r   )ry   r   allr   s        r6   r   r     r   r8   c           
         ||}nAt          t          j        t          j        d| j                            dt                    }t          | t          j        t          j        |||||          S r   )	r3   r   nansumr   r%   r;   r   ry   r   r   s          r6   r   r     sn    U\"'$ag">">">??&QQ			 	 	 	r8   c           
         ||}nAt          t          j        t          j        d| j                            dt                    }t          | t          j        t          j	        |||||          S r   )
r3   r   r   r   r%   r;   r   ry   nanprodr   r   s          r6   r   r   
  sn    U\"'$ag">">">??&QQ	
	 	 	 	r8   
sequential)methodc               n    t          t          j        t          j        d| ||||t
          j        	  	        S )ai  Dask added an additional keyword-only argument ``method``.

    method : {'sequential', 'blelloch'}, optional
        Choose which method to use to perform the cumsum.  Default is 'sequential'.

        * 'sequential' performs the cumsum of each prior block before the current block.
        * 'blelloch' is a work-efficient parallel cumsum.  It exposes parallelism by
            first taking the sum of each block and combines the sums via a binary tree.
            This method may be faster or more memory efficient depending on workload,
            scheduler, and hardware.  More benchmarking is necessary.
    r   rr   r   preop)cumreductionr   	nancumsumoperatoraddr   r   r5   rM   r;   rr   r   s        r6   r   r     s<     		i
 
 
 
r8   c               n    t          t          j        t          j        d| ||||t
          j        	  	        S )at  Dask added an additional keyword-only argument ``method``.

    method : {'sequential', 'blelloch'}, optional
        Choose which method to use to perform the cumprod.  Default is 'sequential'.

        * 'sequential' performs the cumprod of each prior block before the current block.
        * 'blelloch' is a work-efficient parallel cumprod.  It exposes parallelism by first
            taking the product of each block and combines the products via a binary tree.
            This method may be faster or more memory efficient depending on workload,
            scheduler, and hardware.  More benchmarking is necessary.
    rK   r   )r   r   
nancumprodr   mulr   r   r   s        r6   r   r   6  s=     		j
 
 
 
r8   c           
         t          j        | j                  rt          dt                     | j        dk    rt          d          t          | t          t          ||| j        ||          S )N Arrays chunk sizes are unknown. r   zAzero-size array to reduction operation fmin which has no identityr   )r   isnanr   re   r   ry   _nanmin_skipr;   r   s        r6   nanminr   P      	x US<QSSTTTv{{O
 
 	
 	g	 	 	 	r8   c                D   | j         dk    r_t          j                    5  t          j        ddt                     t          j        | ||          cd d d            S # 1 swxY w Y   d S t          t          j        g | j	                  t          |                     S Nr   ignorezAll-NaN slice encounteredr[   r:   like)r   warningscatch_warningsfilterwarningsRuntimeWarningr   r   r    arrayr;   r#   x_chunkrM   rN   s      r6   r   r   d      |a$&& 	D 	D#5~   9W4(CCC		D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D HRw}---OG4L4L
 
 
 	
   2AA"%A"c           
         t          j        | j                  rt          dt                     | j        dk    rt          d          t          | t          t          ||| j        ||          S )Nr   r   zAzero-size array to reduction operation fmax which has no identityr   )r   r   r   re   r   ry   _nanmax_skipr;   r   s        r6   nanmaxr   q  r   r8   c                D   | j         dk    r_t          j                    5  t          j        ddt                     t          j        | ||          cd d d            S # 1 swxY w Y   d S t          t          j        g | j	                  t          |                     S r   )r   r   r   r   r   r   r   r    r   r;   r#   r   s      r6   r   r     r   r   f8c                @    |r| S  || fd|i|} || fd|i|}||dS )Nr;   r   totalr`   )r5   r   rH   r;   rZ   rG   r   r  s           r6   
mean_chunkr    sW      a''u'''AC)))&))EU###r8   c                   t          | t                    s| g} |st          d |           n| } t          ||          j        dd|i|}|r|S t          d |           }	 t          |	|          j        dd|i|}
||
dS )Nc                    | d         S Nr   r`   pairs    r6   r7   zmean_combine.<locals>.<lambda>  
    d3i r8   r   rM   c                    | d         S Nr  r`   r
  s    r6   r7   zmean_combine.<locals>.<lambda>  
    $w- r8   r  r`   )rd   r   r+   r   r   )pairsr   rH   r;   rM   rZ   rG   nsr   totalsr  s              r6   mean_combiner    s     eT"" 7E	P''	/	/	/5B(bt$$$(==d=f==A //77F0M&t,,,0EEdEfEEEU###r8   c                d   |st          d |           n| }t          ||          }t          j        |f||d|}|r|S t          d |           } t          ||          j        d||d|}t          j        dd          5  t          |||          cd d d            S # 1 swxY w Y   d S )	Nc                    | d         S r	  r`   r
  s    r6   r7   zmean_agg.<locals>.<lambda>  r  r8   r   rM   r;   c                    | d         S r  r`   r
  s    r6   r7   zmean_agg.<locals>.<lambda>  r  r8   r   rC   invalidr:   r`   )r+   r   r   r   errstaterC   )	r  r;   rM   rZ   rG   r  r   r  r  s	            r6   mean_aggr    s&   7E	P''	/	/	/5Bbt$$$A
q3t533F33A //77F0M&t,,,0Rd%RR6RRE	Hh	7	7	7 - -eQe,,,- - - - - - - - - - - - - - - - - -s   B%%B),B)c                   ||}nY| j         t          k    rt          }nAt          t          j        t          j        d| j                             dt                    }t          | t          t          ||||t          |d
  
        S )Nr   rh   r;   r;   FrM   rN   r;   rp   rq   rr   r]   )
r;   r   r3   r   meanr&   ry   r  r  r  r   s          r6   r  r    s    	
F		RWRXD@@@AA7FSS	   r8   c                Z   ||}nAt          t          j        t          j        d| j                            dt
                    }t          | t          t          t          j
        t                    t          |||||dt          t          t          j
        t                    
  
        S )Nr   r  r;   r   rH   FrM   rN   r;   rp   rr   r]   rq   )r3   r   r  r%   r;   r   ry   r   r  r   r   rJ   r  r  r   s          r6   nanmeanr#    s    RWRW4qw???@@'6RR	
H===%,hGGG   r8   r}   c                ^    |r S  | fi }|                     t          j                  }  fdi}t          j        dd          5  ||z  d d d            n# 1 swxY w Y    fdt	          d|dz             D             }	t          j        |	d          }
|||
d	S )
Nr;   r   r  c                2    g | ]} z
  |z  fd iS r:   r`   )rT   rU   Ar;   rG   r   us     r6   r   z moment_chunk.<locals>.<listcomp>  s8    	P	P	Pq##q1ul
2
2%
26
2
2	P	P	Pr8   r}   rK   rM   r  r   M)r   r   int64r  rb   stack)r&  orderr   rH   r;   rZ   rG   r   r  xsr+  r'  s   ` ` ` `    @r6   moment_chunkr0    s&     a6A	AC)))&))E	Hh	7	7	7  AI              	P	P	P	P	P	P	P	PE!UQY<O<O	P	P	PB
"A+++s   A%%A),A)c           	     V    | d|dz
  f         j         dd|i| ||||z  z  fd|i|z   }t          d|dz
            D ]h}t          j        |          t          j        |          t          j        ||z
            z  z  }	||	 || d||z
  dz
  f         ||z  z  fd|i|z  z  }i|S )N.r}   rM   rK   r`   )r   rb   r   	factorial)
Msr  
inner_termr.  r   rM   rG   r+  r   coeffs
             r6   _moment_helperr6    s    3	>33D3F33cc
Z7 7%)7-37 7 	A 1eai   V Vu%%):):T^ETUI=V=V)VW	USSCQ./*a-?UUdUfUUUUHr8   c                   t          | t                    s| g} |d<   dd<   |st          d |           n| t                     j        ddi}|r|S t          t          d |                     }	t          t          d |                      |	j        ddi}
t          j        d	d	
          5  t          |
||          }t          |	|          |z
  d d d            n# 1 swxY w Y   fdt          d|dz             D             }t          j	        |d          }|
||dS )Nr;   TrN   c                    | d         S r	  r`   r
  s    r6   r7   z moment_combine.<locals>.<lambda>  r  r8   r   rM   c                    | d         S r  r`   r
  s    r6   r7   z moment_combine.<locals>.<lambda>   
    W r8   c                    | d         S Nr+  r`   r
  s    r6   r7   z moment_combine.<locals>.<lambda>!  
    DI r8   r   r  r:   c                :    g | ]}t          |          S r`   )r6  )rT   or3  rM   r4  rG   r  r   s     r6   r   z"moment_combine.<locals>.<listcomp>)  s=     
 
 
 	r2z1c4@@
 
 
r8   r}   rK   r(  r)  r*  r`   )
rd   r   r+   r   r   r   r  rC   rb   r-  )r  r.  ddofr;   r   rM   rZ   rG   r   r  r  mur/  r+  r3  r4  r  s       `` `      @@@r6   moment_combinerB  	  s    eT"" F7OF:7E	P''	/	/	/5B	r	%	%	%B##D#F##A 7#=#=uEEDQQQF	w55u==D	I	I	IBFJ++D+F++E	Hh	7	7	7 : :E1E***FBe444r9
: : : : : : : : : : : : : : :
 
 
 
 
 
 
 
 
q%!)$$
 
 
B 	"A+++s   (C;;C?C?c           	     2   t          | t                    s| g} ||d<   |                                }d|d<   |st          d |           n| }	t	          |	|          }	 |	j        dd|i|}
|r|
S t	          t          d |           |          }t	          t          d |           |          }t           |j        dd|i||
|	          }t          j        d
d
          5  t          ||	|	          |z
  }d d d            n# 1 swxY w Y   t          ||	|||||          } |
j        dd|i||z
  }t          |t                    r|dk     rt          j        }n&|t          j        j        urt          j        ||dk     <   t          |||	          S )Nr;   TrN   c                    | d         S r	  r`   r
  s    r6   r7   zmoment_agg.<locals>.<lambda>D  r  r8   r   rM   c                    | d         S r  r`   r
  s    r6   r7   zmoment_agg.<locals>.<lambda>K  r:  r8   c                    | d         S r<  r`   r
  s    r6   r7   zmoment_agg.<locals>.<lambda>L  r=  r8   r:   r   r  r   r`   )rd   r   copyr+   r   r   rC   r   r  r6  r	   nanmamasked)r  r.  r@  r;   r   rM   rZ   rG   
keepdim_kwr  r   r  r3  rA  r4  r+  denominators                    r6   
moment_aggrM  1  s    eT"" F7O J!Jz7E	P''	/	/	/5B	r	%	%	%B''D'J''A 7#=#=uEEDQQQF	w55u==D	I	I	IB	

333
33Qe	D	D	DB	Hh	7	7	7 : :FBe444r9
: : : : : : : : : : : : : : : 	r2z5#tVDDA!%,,T,V,,t3K +v&& .??&K	BEL	(	(')vK!O$![....s   %DDDc                Z   t          |t                    r|dk     rt          d          |dk     r`|                     |          }|dk    r"t	          |j        |j        d|j                  S t          |j        |j        d|j                  S ||}	nAt          t          j        t          j        d| j        	                    d
t                    }	t          | t          t           |          t          t"          ||          |||	||dt          t$          |          
  
        S )a  Calculate the nth centralized moment.

    Parameters
    ----------
    a : Array
        Data over which to compute moment
    order : int
        Order of the moment that is returned, must be >= 2.
    axis : int, optional
        Axis along which the central moment is computed. The default is to
        compute the moment of the flattened array.
    dtype : data-type, optional
        Type to use in computing the moment. For arrays of integer type the
        default is float64; for arrays of float types it is the same as the
        array type.
    keepdims : bool, optional
        If this is set to True, the axes which are reduced are left in the
        result as dimensions with size one. With this option, the result
        will broadcast correctly against the original array.
    ddof : int, optional
        "Delta Degrees of Freedom": the divisor used in the calculation is
        N - ddof, where N represents the number of elements. By default
        ddof is zero.

    Returns
    -------
    moment : Array

    References
    ----------
    .. [1] Pebay, Philippe (2008), "Formulas for Robust, One-Pass Parallel
        Computation of Covariances and Arbitrary-Order Statistical Moments",
        Technical Report SAND2008-6212, Sandia National Laboratories.

    r   zOrder must be an integer >= 0r}   r)  r  )rj   r;   rs   Nr   r  r;   )r.  )r.  r@  Fr"  )rd   r   re   r   r%   rh   rj   rY   r&   r3   r   varr;   r   ry   r   r0  rM  rB  )
r@   r.  rM   r;   rN   r@  rp   rr   reducedr   s
             r6   momentrQ  a  s:   L eX&& :%!))8999qyy%%T%""A::gnDw}    M'.7=
 
 
 	
 RVBG$ag>>>??&QQ	E***
%d333e444   r8   c                    ||}nAt          t          j        t          j        d| j                            dt
                    }t          | t          t          t          |          ||||t          d|d          S )Nr   r  r;   )r@  rO  F)rM   rN   r;   rp   rq   r\   rr   r]   )r3   r   rO  r%   r;   r   ry   r0  r   rM  rB  r@   rM   r;   rN   r@  rp   rr   r   s           r6   rO  rO    s    RVBG$ag>>>??&QQ	
&&&   r8   c                   ||}nAt          t          j        t          j        d| j                            dt
                    }t          | t          t          t          j
        t                    t          t          t          j
        |          ||||t          t          t          j
                  |d
  
        S )	Nr   r  r;   r!  )r   r@  )r   Fr  )r3   r   rO  r%   r;   r   ry   r   r0  r   r   rJ   rM  rB  rS  s           r6   nanvarrU    s     RVBG$ag>>>??&QQ	%,h???
	555BI666   r8   c                    t          j        |           }t          |t           j        j                  r1|j        s*|j                                        rt           j        j        S |S rE   )	r   sqrtrd   rI  masked_arrayrh   maskr   rJ  )r@   r?  s     r6   _sqrtrZ    sO    


A!RU'((  QVZZ\\ u|Hr8   c                v    t          | d          r|                     t          |           S t          |           S )a  A version of sqrt that properly handles scalar masked arrays.

    To mimic ``np.ma`` reductions, we need to convert scalar masked arrays that
    have an active mask to the ``np.ma.masked`` singleton. This is properly
    handled automatically for reduction code, but not for ufuncs. We implement
    a simple version here, since calling `np.ma.sqrt` everywhere is
    significantly more expensive.
    	_elemwise)rl   r\  rZ  )r@   s    r6   	safe_sqrtr]    s5     q+ %{{5!$$$88Or8   c                    t          t          | ||||||                    }|r ||j        k    r|                    |          }|S N)rM   r;   rN   r@  rp   rr   )r]  rO  r;   r   r@   rM   r;   rN   r@  rp   rr   rx   s           r6   stdra    sd    #	
 	
 	

 
F  &&,&&u%%Mr8   c                    t          t          | ||||||                    }|r ||j        k    r|                    |          }|S r_  )r]  rU  r;   r   r`  s           r6   nanstdrc    sf     #	
 	
 	

 
F  &&,&&u%%Mr8   c                2   t          | t                    rX| d         j        | d         j        k    sJ t          |          | d         j        k    s| d         j        dk    rdn|d         }n-t          |          | j        k    s| j        dk    rdn|d         }| d         }| d         }|C ||||          }|                                |         }|                                |         }n |||          }t
          j        t          t          t          |j
                                     }|                    ||           t          |          }||         }||         }|r*t          j        ||          }t          j        ||          }||fS )z3Merge intermediate results from ``arg_*`` functionsvalsargrK   Nr   r[   r)  )rd   r   rc   rR   ravelr   ogridra   r   slicerh   insertexpand_dims)datarM   argfuncrN   re  rf  
local_argsru   s           r6   _arg_combinero    s   $ 
M F| DK$44444 4yyDL---f1Ba1G1G Da 	 4yyDI--attT!W<D
u+C|WTx@@@
zz||J'iikk*%WT---
xc%)9::;;<D*%%%T{{Dz$i 	,>$--D.d++C9r8   c                h   t          |          |j        k    s|j        dk    rd n|d         } | ||d          } |||d          }|j        dk    r|y|\  }}	t          j        |                                d         |j                  }
t          d t          ||
          D                       }t          j        ||	          |d d <   n||z  }t          |t          j
        j                  rhd|j        v r t          j
                            |          }nt          j
                            |          }t          j
                            ||          }	 t          j        ||j        d|j        fd|j        fg	          }n# t$          $ r t'                      }Y nw xY w||d<   ||d<   |S )
NrK   r   Tr[   c              3  &   K   | ]\  }}||z   V  d S rE   r`   )rT   r?  rU   s      r6   rX   zarg_chunk.<locals>.<genexpr>7  s*      CCAa!eCCCCCCr8   r   re  rf  r  )rR   rc   r   unravel_indexrg  rh   ra   r   ravel_multi_indexrd   rI  rX  __name__minimum_fill_valuemaximum_fill_valuefilled
empty_liker;   rm   r   )r   rm  r5   rM   offset_infoarg_axisre  rf  offsettotal_shapeind	total_ind
fill_valuerx   s                 r6   	arg_chunkr  /  s   4yyAF**afkktttAwH44000D
'!(T
2
2
2Cvzz"-FK"399;;q>17;;CCC#fc2B2BCCCCCI))[AACFF;C$*++ .G$$$11$77JJ11$77Ju||D*--
FDJ+?%AS*T
 
 
     F6NF5MMs   ,F
 
F%$F%c                    t          ||| d          \  }}	 t          j        ||j        d|j        fd|j        fg          }n# t
          $ r t                      }Y nw xY w||d<   ||d<   |S )NTrN   re  rf  r  )ro  r   rx  rh   r;   rm   r   )rm  rl  rM   rG   rf  re  rx   s          r6   arg_combiner  P  s    T44@@@IC
FDJ+?%AS*T
 
 
     F6NF5MMs   ,A A A c                4    t          ||| |          d         S )Nr  r   )ro  )rm  rl  rM   rN   rG   s        r6   arg_aggr  `  s    dGh???BBr8   c                    t          ||| |          \  }}t          j        t          j        |                    rt	          d          |S )Nr  zAll NaN slice encountered)ro  r   r   r   re   )rm  rl  rM   rN   rG   rf  re  s          r6   
nanarg_aggr  d  sJ    T48DDDIC	vbhtnn 64555Jr8   c           	        $t          t          | j                            d}nLt          t                    r$t          | j                  f| j        dk    }nt          d d          D ]W}	| j        |	         }
t          |
          dk    r5t          j
        |
                                          rt          d          Xdt          | ||           | j        t          t!          t#          t          | j                             }t          t!          d | j        D                        }|r#t'          |t)          | j                            }nt-          d	         |          }t          fd
t/          | j                  D                       }
fdt'          ||          D             }t          j        t3          dgt5          |                               }d}t7          |          r	|}|j        }t;          j        || g          }t?          ||
||          }tA          ||||||          }tC          ||          S )a7  Generic function for argreduction.

    Parameters
    ----------
    x : Array
    chunk : callable
        Partialed ``arg_chunk``.
    combine : callable
        Partialed ``arg_combine``.
    agg : callable
        Partialed ``arg_agg``.
    axis : int, optional
    split_every : int or dict, optional
    NTrK   z(axis must be either `None` or int, got ''zArg-reductions do not work with arrays that have unknown chunksizes. At some point in your computation this array lost chunking information.

A possible solution is with 
  x.compute_chunk_sizes()zarg-reduce-c              3  \   K   | ]'}t          t          j        |d d         d          V  (d S )Nr(  r   )r
   r   r   )rT   bds     r6   rX   z arg_reduction.<locals>.<genexpr>  s8      UUbZb"gqAAUUUUUUr8   r   c              3  N   K   | ]\  }}|v rd t          |          z  n|V   dS )r   NrQ   )rT   rU   rV   rM   s      r6   rX   z arg_reduction.<locals>.<genexpr>  s=      WW!QAII4#a&&==1WWWWWWr8   c                4    i | ]\  }}f|z   f|z   |fS r`   r`   )rT   r   offrM   r   r\   olds      r6   r   z!arg_reduction.<locals>.<dictcomp>  sD       Q 
!ecVaZs3  r8   r   r   )r;   rs   )rN   r;   rp   rq   )"ra   rb   rc   rd   r   r$   rm   rj   rR   r   r   r   re   r'   r\   r   r   r   r   r   r   rh   r   ri   argminr    r#   r"   r;   r)   r   r   rn   r   )r5   r   rq   aggrM   rN   rp   rr   rg  axrj   r   offsetsry  r   r;   rs   r   rw   rx   r\   r  s    `  `               @@r6   arg_reductionr  k  s   " |U16]]##	D(	#	# LT16**w!J4JJJKKK 	 	"v;;??rx//3355?,   J$5';GGIID
&CUAK00122D7UUAHUUUVWWG .'6!'??33DGW--WWWW9QXCVCVWWWWWF      D+..  C
 IlA3_Q-?-?@@@AAEDE  
+D#QCHHHE
tV5t
<
<
<C  F c6"""r8   c                    	 t          j        | |fi |S # t          $ rF t          j        t          j        t          j        |           t          j        |           |fi |cY S w xY wrE   )r   	nanargminre   r   wherer   infr5   rM   rG   s      r6   
_nanargminr    sy    Qq$11&111 Q Q QrxRVQ??PPPPPPPQs    AA%$A%c                    	 t          j        | |fi |S # t          $ rG t          j        t          j        t          j        |           t          j         |           |fi |cY S w xY wrE   )r   	nanargmaxre   r   r  r   r  r  s      r6   
_nanargmaxr    s{    Rq$11&111 R R RrxbfWa@@$QQ&QQQQQRs    AA&%A&c           
         t          | t          t          t          j        t          j                  t          t          t          j                  t          t          t          j                  ||||          S N)rM   rN   rp   rr   )r  r   r  r   r?   argmaxr  r  r   s        r6   r  r    Y    		59el33U\**&&	 	 	 	r8   c           
         t          | t          t          t          j        t          j                  t          t          t          j                  t          t          t          j                  ||||          S r  )r  r   r  r   r   r  r  r  r   s        r6   r  r    r  r8   c           
         t          | t          t          t          j        t
                    t          t          t
                    t          t          t
                    ||||          S r  )r  r   r  r   r   r  r  r  r   s        r6   r  r    S    		5<44Z((
J''	 	 	 	r8   c           
         t          | t          t          t          j        t
                    t          t          t
                    t          t          t
                    ||||          S r  )r  r   r  r   r   r  r  r  r   s        r6   r  r    r  r8   c                2     || | |||                    S )a  Combine results of a parallel prefix scan such as cumsum

    Parameters
    ----------
    func : callable
        Cumulative function (e.g. ``np.cumsum``)
    binop : callable
        Associative function (e.g. ``add``)
    pre : np.array
        The value calculated in parallel from ``preop``.
        For example, the sum of all the previous blocks.
    x : np.array
        Current block
    axis : int
    dtype : dtype

    Returns
    -------
    np.array
    r  r`   )r   binopprer5   rM   r;   s         r6   _prefixscan_combiner    s'    0 5dd14u555666r8   c                     | |||          S )a  Compute the prefix scan (e.g., cumsum) on the first block

    Parameters
    ----------
    func : callable
        Cumulative function (e.g. ``np.cumsum``)
    x : np.array
        Current block
    axis : int
    dtype : dtype

    Returns
    -------
    np.array
    r  r`   )r   r5   rM   r;   s       r6   _prefixscan_firstr    s      4E****r8   c           
        /                                                     j                  d|8t           | t	          j        dj                            dt                    }t          t                    sJ t          j                  | j         dt          | |||           }|f}                    |d|	          fd
t          j                           D             x^ }	}
}fd|	D             }i }t#          |          }d}|dk    r_d}d}||k    rt          |dz
  ||          D ]]}g }t%          |	|         |||z
           ||                   D ]-\  }}}||z   ||fz   }|||f||<   |                    |           .|||<   ^|}|dz  }|dz  }||k    t)          j        ddt-          j        t-          j        |dz                      z            }|dz  }|dk    rt          ||z   dz
  ||          D ]]}g }t%          |	|         |||z
           ||                   D ]-\  }}}||z   ||fz   }|||f||<   |                    |           .|||<   ^|}|dz  }|dz  }|dk    |r}|d         D ]}t2          | j        f|z   |f|||z   <   t%          t7          d|          |          D ]8\  }}t%          ||          D ]"\  }}t8          | ||j        f|z   |f|||z   <   #9t#          |          dk     rg}ng}t;          j        |||          }t?          ||j         j                  }tC          ||          S )a  Generic function to perform parallel cumulative scan (a.k.a prefix scan)

    The Blelloch prefix scan is work-efficient and exposes parallelism.
    A parallel cumsum works by first taking the sum of each block, then do a binary tree
    merge followed by a fan-out (i.e., the Brent-Kung pattern).  We then take the cumsum
    of each block and add the sum of the previous blocks.

    When performing a cumsum across N chunks, this method has 2 * lg(N) levels of dependencies.
    In contrast, the sequential method has N levels of dependencies.

    Floating point operations should be more accurate with this method compared to sequential.

    Parameters
    ----------
    func : callable
        Cumulative function (e.g. ``np.cumsum``)
    preop : callable
        Function to get the final value of a cumulative function (e.g., ``np.sum``)
    binop : callable
        Associative function (e.g. ``add``)
    x : dask array
    axis : int
    dtype : dtype

    Returns
    -------
    dask array
    Nrj   r   r   r:   r;   r   T)rM   rN   r;   c           
     |    g | ]7t          t          fd t          j                  D                        8S )c                F    g | ]\  }}|k    rt          |          ngS r`   rb   )rT   r   nbrM   rU   s      r6   r   z2prefixscan_blelloch.<locals>.<listcomp>.<listcomp>Y  1    VVVeaqDyy%)))qcVVVr8   )r   r   ri   r   )rT   rU   rM   r5   s    @r6   r   z'prefixscan_blelloch.<locals>.<listcomp>V  sb     + + +  	VVVVVy?U?UVVV	
 	
+ + +r8   c                ,    g | ]}fd |D             S )c                &    g | ]}j         f|z   S r`   )r\   )rT   indexbatchess     r6   r   z2prefixscan_blelloch.<locals>.<listcomp>.<listcomp>^  s"    >>>W\Oe+>>>r8   r`   )rT   re  r  s     r6   r   z'prefixscan_blelloch.<locals>.<listcomp>^  s.    SSS4>>>>>>>SSSr8   r}   rK   r   )"flattenrechunknpartitionsr3   r   r%   r;   r   rd   r   r$   rc   rt  r'   
map_blocksrb   r   rR   r   appendr>   r?   r   r   log2r  r\   r   r  r)   r   r   rj   r   )r   r   r  r5   rM   r;   rr   r\   base_keyindices
last_indexfull_indicesprefix_valsr   n_valslevelstridestride2rU   new_valsr  left_val	right_valr9   indexesre  valdepsr   rx   r  s      ``                         @r6   prefixscan_blellochr  ,  sh   : |IIKKq}55}RWT999::GVLLdH%%%%%qv&&DmLLhtT5%EJJLLDwH ll5td%lHHG+ + + + + q{4())+ + + Wj< TSSS7SSSK
CFE{{7Q;88 * *25AJAJ 7Q3 3 ) ).E8Y #U*eQZ7C %x;CHOOC((((!)AFqLGQJE " ,q!ty6Q;1G1G'H'H"HIIAqjj7V+a/AA * *25AJAJ 7Q3 3 ) ).E8Y #U*eQZ7C %x;CHOOC((((!)AGqLFQJE qjj  !!_ 	 	E!	E!%C5 !! !a!6!6DD 
	 
	MGT!'400 	 	
s'VI%)Hu$%%	 <1s7|+D#DIIIE5$'-88Fc6"""r8   c	           
        |dk    r'|t          d          t          | ||||          S |dk    rt          d|          /                                                    j                  d|8t           | t          j        d	j	        
                    dt                    }t          t                    sJ t          j                                      | |          }	| j         dt#          | |||           }
j                 }t'          ddd          }|fz  t'          dd          fz   |fj        z
  dz
  z  z   }t)          t+          fdt-          j                  D                        }t/                      }|D ]i}t1          fdt-          |          D                       }t2          t          j        j        ||	j	        fd|if||
df|z   <   |	j        f|z   ||
f|z   <   jt;          d|          D ]|}t)          t+          fdt-          j                  D                        }t=          ||          D ]D\  }}|
df|z   }||
df|z   t>          j         |	j        f|z   |ff||<   |||	j        f|z   f||
f|z   <   EtC          j"        |
||	g          }tG          ||
j$        |	j	        j                  }tK          ||          S )a  Generic function for cumulative reduction

    Parameters
    ----------
    func: callable
        Cumulative function like np.cumsum or np.cumprod
    binop: callable
        Associated binary operator like ``np.cumsum->add`` or ``np.cumprod->mul``
    ident: Number
        Associated identity like ``np.cumsum->0`` or ``np.cumprod->1``
    x: dask Array
    axis: int
    dtype: dtype
    method : {'sequential', 'blelloch'}, optional
        Choose which method to use to perform the cumsum.  Default is 'sequential'.

        * 'sequential' performs the scan of each prior block before the current block.
        * 'blelloch' is a work-efficient parallel scan.  It exposes parallelism by first
          calling ``preop`` on each block and combines the values via a binary tree.
          This method may be faster or more memory efficient depending on workload,
          scheduler, and hardware.  More benchmarking is necessary.
    preop: callable, optional
        Function used by 'blelloch' method,
        like ``np.cumsum->np.sum`` or ``np.cumprod->np.prod``

    Returns
    -------
    dask array

    See also
    --------
    cumsum
    cumprod
    blellochNz>cumreduction with "blelloch" method required `preop=` argument)rr   r   zMInvalid method for cumreduction.  Expected "sequential" or "blelloch".  Got: r  r   r   r:   r;   r  r   r(  rK   c                F    g | ]\  }}|k    rt          |          nd gS r   r  )rT   rU   r  rM   s      r6   r   z cumreduction.<locals>.<listcomp>  r  r8   c              3  T   K   | ]"\  }}|k    rj         |         |         nd V  #dS r   r  )rT   rU   iirM   r5   s      r6   rX   zcumreduction.<locals>.<genexpr>  s=      VVeadahqk"ooVVVVVVr8   rh   extrac                F    g | ]\  }}|k    rt          |          ngS r`   r  )rT   r  r  rM   rU   s      r6   r   z cumreduction.<locals>.<listcomp>  s1    XXXvr2rTzz%)))sXXXr8   r   r   )&rm   r  re   r  r  r  r3   r   r%   r;   r   rd   r   r$   rc   r  rt  r'   r   ri  r   r   ri   r   ra   r*   	full_likerY   r\   rb   r   r   getitemr)   r   r   rj   r   )r   r  identr5   rM   r;   rr   r   r   mr\   r   fullslcr  r   r}  rh   last_indicesr  
this_slicer   rx   rU   s      ``                  @r6   r   r     s|   Z =P   #4q$3OOOO	<		f\bff
 
 	
 |IIKKq}55}RWT999::GVLLdH%%%%%qv&&D	TE22AmLLhtT5%EJJLLD	DAtT""D'D.E"dOO-
-16D=1;L0M
MCVVVVy?U?UVVVW G &&C - -VVVVVyQT~~VVVVVLWeQW%e	&
T7Oc!"  fY_TGcM1a[[ F FXXXXX1;AWAWXXX
 

 L'22 	F 	FHC3.Jw#%!AF9s?C8C
O
 #(afY_!EC#	F +D#QCHHHE5$!'@@@Fc6"""r8   c                   t          | t          j        j                  st          |t          j        j                  r}t          j                            |           t          j                            |          z   }t          j                            |t          j                            |                    S | |z   S N)rY  rd   r   rI  rX  getdatagetmaskarrayr@   rA   rg   s      r6   _cumsum_merger        !RU'(( FJq"%:L,M,M Fq!!BEMM!$4$44u!!&ru/A/A!/D/D!EEEq5Lr8   c                   t          | t          j        j                  st          |t          j        j                  r}t          j                            |           t          j                            |          z  }t          j                            |t          j                            |                    S | |z  S r  r  r  s      r6   _cumprod_merger    r  r8   c                d    t          t          j        t          d| ||||t          j        	  	        S )ac  Dask added an additional keyword-only argument ``method``.

    method : {'sequential', 'blelloch'}, optional
        Choose which method to use to perform the cumsum.  Default is 'sequential'.

        * 'sequential' performs the cumsum of each prior block before the current block.
        * 'blelloch' is a work-efficient parallel cumsum.  It exposes parallelism by
          first taking the sum of each block and combines the sums via a binary tree.
          This method may be faster or more memory efficient depending on workload,
          scheduler, and hardware.  More benchmarking is necessary.
    r   r   )r   r   cumsumr  r   r   s        r6   r  r    s:     
			f
 
 
 
r8   c                d    t          t          j        t          d| ||||t          j        	  	        S )an  Dask added an additional keyword-only argument ``method``.

    method : {'sequential', 'blelloch'}, optional
        Choose which method to use to perform the cumprod.  Default is 'sequential'.

        * 'sequential' performs the cumprod of each prior block before the current block.
        * 'blelloch' is a work-efficient parallel cumprod.  It exposes parallelism by first
          taking the product of each block and combines the products via a binary tree.
          This method may be faster or more memory efficient depending on workload,
          scheduler, and hardware.  More benchmarking is necessary.
    rK   r   )r   r   cumprodr  r   r   s        r6   r  r  6  s:     

		g
 
 
 
r8   r(  c                    t          || j                  }t          t          j        |          }t          t          j        |          }t          | ||||d| j        |t          |          	  	        S )a  Extract the k largest elements from a on the given axis,
    and return them sorted from largest to smallest.
    If k is negative, extract the -k smallest elements instead,
    and return them sorted from smallest to largest.

    This performs best when ``k`` is much smaller than the chunk size. All
    results will be returned in a single chunk along the given axis.

    Parameters
    ----------
    x: Array
        Data being sorted
    k: int
    axis: int, optional
    split_every: int >=2, optional
        See :func:`reduce`. This parameter becomes very important when k is
        on the same order of magnitude of the chunk size or more, as it
        prevents getting the whole or a significant portion of the input array
        in memory all at once, with a negative impact on network transfer
        too when running on distributed.

    Returns
    -------
    Selection of x with size abs(k) along the given axis.

    Examples
    --------
    >>> import dask.array as da
    >>> x = np.array([5, 1, 3, 6])
    >>> d = da.from_array(x, chunks=2)
    >>> d.topk(2).compute()
    array([6, 5])
    >>> d.topk(-2).compute()
    array([1, 3])
    r   T)r   rq   ro   rM   rN   r;   rp   rW   )	r$   rc   r   r   topktopk_aggregatery   r;   abs)r@   r   rM   rp   chunk_combinero   s         r6   r  r  P  s}    H qv&&D
 EJ!,,,M ,222I	gFF
 
 
 
r8   c                   t          | j                  t          | j                 | j                 ft
          j                  }|t          fdt          | j                  D                                }| 	                    t          j        |t                    }t          t          j        |          }t          t          j        |          }t!          t"                    rd}nt%                    }| j                            t
          j                                      d| j        |z
  dz   z            }	t-          ||||dt
          j        |dt/          |          |		          S )
a  Extract the indices of the k largest elements from a on the given axis,
    and return them sorted from largest to smallest. If k is negative, extract
    the indices of the -k smallest elements instead, and return them sorted
    from smallest to largest.

    This performs best when ``k`` is much smaller than the chunk size. All
    results will be returned in a single chunk along the given axis.

    Parameters
    ----------
    x: Array
        Data being sorted
    k: int
    axis: int, optional
    split_every: int >=2, optional
        See :func:`topk`. The performance considerations for topk also apply
        here.

    Returns
    -------
    Selection of np.intp indices of x with size abs(k) along the given axis.

    Examples
    --------
    >>> import dask.array as da
    >>> x = np.array([5, 1, 3, 6])
    >>> d = da.from_array(x, chunks=2)
    >>> d.argtopk(2).compute()
    array([3, 0])
    >>> d.argtopk(-2).compute()
    array([1, 2])
    )rj   r;   c              3  Z   K   | ]%}|k    rt          d           nt          j        V  &d S rE   )ri  r   newaxis)rT   rU   rM   s     r6   rX   zargtopk.<locals>.<genexpr>  s7      TT199E$KKK"*TTTTTTr8   r:   r  rK   r   TF)
r   rq   ro   rM   rN   r;   rp   r]   rW   rs   )r$   rc   r   rh   rj   r   intpra   rb   r  r   argtopk_preprocessr   r   argtopkargtopk_aggregaterd   r	   rR   rY   r   r   ry   r  )
r@   r   rM   rp   idx
a_plus_idxr  ro   naxisrs   s
     `       r6   r  r    sK   B qv&&D '8
H
H
HC
eTTTTeAFmmTTTTT
UCe66JJJ EMQ///M /1555I$ D		7>>"'""**416E>A3E+FGGDgFF   r8   c                R    t          | |||                              d|          S )N)r{  axis1axis2r(  r:   )r   r   )r@   r{  r  r  r;   s        r6   tracer    s,    AfE???CCBeCTTTr8   c           
         t          d          t          t                    sf fdD             t          j         fdD                       r3                     fdt           j                  D                                             t          j
        ||snd|r fdt           j                  D             nd          }t          ||          }|S )z
    This works by automatically chunking the reduced axes to a single chunk if necessary
    and then calling ``numpy.median`` function across the remaining dimensions
    NzcThe da.median function only works along an axis.  The full algorithm is difficult to do in parallelc                4    g | ]}|d k     r
|j         z   n|S r   rc   rT   r  r@   s     r6   r   zmedian.<locals>.<listcomp>  +    999b266BKKr999r8   c              3  :   K   | ]}j         |         d k    V  dS r   r   r  s     r6   rX   zmedian.<locals>.<genexpr>  .      77BAKOa'777777r8   c                "    i | ]}||v rd ndS r(  autor`   rT   r  rM   s     r6   r   zmedian.<locals>.<dictcomp>  '    PPPBrt22PPPr8   c                &    g | ]\  }}|v rd n|S r   r`   rT   r  rV   rM   s      r6   r   zmedian.<locals>.<listcomp>  )    HHH52qR4ZZQHHHr8   rM   rN   	drop_axisrj   )NotImplementedErrorrd   r   r>   r   r  rb   rc   r  r   medianri   rj   r   r@   rM   rN   rr   rx   s   ``   r6   r  r    s#    |!@
 
 	

 dH%% w9999D999D |7777$77777 RIIPPPP%--PPPQQ\\
	&0$$DHHHHIah4G4GHHHH   F V$$FMr8   c           
         t          d          t          t                    sf fdD             t          j         fdD                       r3                     fdt           j                  D                                             t          j
        ||snd|r fdt           j                  D             nd          }t          ||          }|S )z
    This works by automatically chunking the reduced axes to a single chunk
    and then calling ``numpy.nanmedian`` function across the remaining dimensions
    NzzThe da.nanmedian function only works along an axis or a subset of axes.  The full algorithm is difficult to do in parallelc                4    g | ]}|d k     r
|j         z   n|S r   r   r  s     r6   r   znanmedian.<locals>.<listcomp>
  r  r8   c              3  :   K   | ]}j         |         d k    V  dS r   r  r  s     r6   rX   znanmedian.<locals>.<genexpr>  r  r8   c                "    i | ]}||v rd ndS r  r`   r	  s     r6   r   znanmedian.<locals>.<dictcomp>  r
  r8   c                &    g | ]\  }}|v rd n|S r   r`   r  s      r6   r   znanmedian.<locals>.<listcomp>  r  r8   r  )r  rd   r   r>   r   r  rb   rc   r  r   	nanmedianri   rj   r   r  s   ``   r6   r  r    s#    |!@
 
 	

 dH%% w9999D999D |7777$77777 RIIPPPP%--PPPQQ\\
&0$$DHHHHIah4G4GHHHH   F V$$FMr8   rE   )NFNNNNNTrK   NN)NNNTN)FNNN)NNFNN)NFNN)NN)r  NF)NNFr   NN)F)NF)NNN)NNNr   N)NNNr   )r(  N)r   r   rK   N)NFN)
__future__r   r>   r   r   r   r   collections.abcr   	functoolsr   	itertoolsr   r   numbersr   r	   numpyr   tlzr
   r   r   r   r   r   daskr   
dask.arrayr   dask.array.blockwiser   dask.array.corer   r   r   r   r   r   r   dask.array.creationr   r   dask.array.dispatchr   r   r   dask.array.utilsr   r    r!   r"   r#   r$   dask.array.wrapr%   r&   	dask.baser'   dask.blockwiser(   dask.highlevelgraphr)   
dask.utilsr*   r+   r,   r-   r.   r/   rC   rH   rJ   ry   rn   r   r   r   r   aminr   r?   amaxr   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r#  r0  r6  rB  rM  rQ  rO  rU  rZ  r]  ra  rc  ro  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r`   r8   r6   <module>r.     s
   " " " " " "         $ $ $ $ $ $       % % % % % % % % $ $ $ $ $ $ $ $     D D D D D D D D D D D D D D D D             * * * * * *                  1 0 0 0 0 0 0 0 L L L L L L L L L L                ( ' ' ' ' ' ' '       % % % % % % . . . . . .                      % % %( ( ( 

		{# {# {# {#H 	7 7 7 7v OSL9 L9 L9 L9^ b     b   " BFBGb    7 7 7 7 BFBGb    7 7 7 7 b
 
 
 
 b
 
 
 
 b   " b   " b|     2 b     2 b   &

 

 

 b   &

 

 

 9Ee	$ 	$ 	$ 	$ 		

	$ $ $ $0- - - - b   * b   ( EIU$u, , , ,    	


	%, %, %, %,T 	


	-/ -/ -/ -/b TXD D D DN b   ( bLP   *     b   " bLP   &   B  B    C C C C    NRJ# J# J# J#ZQ Q QR R R b
 
 
 
 b
 
 
 
 b
 
 
 
 b
 
 
 
7 7 76+ + +&u# u# u# u#z 


g# g# g# g#T     b   2 b   28 8 8 8vE E E EP bU U U U b   D b     r8   