
    biP3                    6   d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZ d dlZd dlmZmZmZ d dlmZ d dlmZ d d	lmZmZmZmZmZ d d
lmZ d dlmZm Z m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z)m*Z*m+Z+ 	 	 	 	 	 	 	 	 	 	 	 ddZ,	 	 	 	 	 ddZ-	 ddZ.y)    )annotationsN)partial)product)Integral)composegetpartition_all)config)	blockwise)Array_concatenate2
asanyarraybroadcast_to
handle_out)ComplexWarning)compute_metais_arraylikevalidate_axis)tokenize)
lol_tuples)HighLevelGraph)funcname
getargspecis_series_likec                   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}|)t        |      }	 t        || j                        }|||fz  }t        ||g|d||xs t         d}t        fd	t#        |j$                        D              |_        |3t)        | d
      r'	 t+        || j,                  | j.                  dd      }nd}t3        ||||||||

      }|r2dk7  r-t        fdt#        |j$                        D              |_        |||_        t5        |	|      S # t        $ r& t        d|j                   d| j                         w xY w# t0        $ r' t+        || j,                  | j.                  d      }Y t        $ r Y w xY w)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 dtypedtyper   zWeights with shape z' are not broadcastable to x with shape T)axiskeepdimstokenr   c              3  N   K   | ]  \  }}|v rft        |      z  n|  y wN)len.0icr   output_sizes      Y/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/dask/array/_reductions_generic.py	<genexpr>zreduction.<locals>.<genexpr>   s0      8<119Q!3s   "%_meta)r   r   computing_metar   r   )nameconcatenatereduced_meta   c              3  6   K   | ]  \  }}|v rfn|  y wr"    r$   s      r)   r*   zreduction.<locals>.<genexpr>   s'      
371aa4i[NQ.
s   )tuplerangendim
isinstancer   r   
ValueErrorr   argsr   r   valuesr   r   shaper   float	enumeratechunks_chunkshasattrr   r   r+   	TypeError_tree_reducer   )xchunk	aggregater   r   r   split_everycombiner.   outr/   r(   metaweightsindsr9   wgttmpr0   results      `       `        r)   	reductionrO      se   f |U166]#$!wqvv&D}-..*U#(((U+*Y',,,IU3	aHH qvvDt9D!	sAGG,C 	d t!%DQVC  @I#**@U CK |7+		'qwwdTRVL !F K1$ 
;DSZZ;P
 
 c6""a  	%cii[ 1##$77)- 	*  	'qwwdTL  		s$   (G" %H "/H-IIIc
                   |xs t        j                  dd      }t        |t              r!|D 
ci c]  }
|
|j                  |
d       }}
ndt        |t              rIt        j                  t        |dt        |      xs dz  z        d      }t        j                  ||      }nt        d      d}t        | j                        D ]\  \  }}||v s||   dk7  st        t        j                  |t        j                  t        j                  |||                           }^ t!        |xs ||d      }|r$t#        |t!        t$        t'        |                  }t)        |dz
        D ](  }t+        || |d||xs t-        |xs |      d	z   |	
      } * t!        |||      }|r$t#        |t!        t$        t'        |                  }t+        || ||||xs t-        |      dz   |	      S c c}
w )zPerform the tree reduction step of a reduction.

    Lower level, users should use ``reduction`` or ``arg_reduction`` directly.
    rF         r1   z#split_every must be a int or a dictTr-   )axesz-partial)r   r.   r0   z
-aggregate)r   r   r.   r0   )r
   r   r7   dictr   builtinsmaxintr#   fromkeysr8   r=   	numblocksmathceillogr   r   r   sortedr5   partial_reducer   )rC   rE   r   r   r   rF   rG   r.   r/   r0   kndepthr&   func_s                   r)   rB   rB      s   " =M1!=K+t$9=>Aq+//!Q//>>	K	*LL[Q#d).q-ABCQGmmD!,>?? E!++& U1A! 3UDIIdhhq+a.6Q,RSTEU 7'idTBDtW]FG519 	
8(7#7i8JF%
	
 94(;DtW]FG	)hy)\9! 9 ?s   G-c                   |xs t        |       dz   t        | |||      z   }t        |j                        D cg c]3  \  }}t	        t        j                  |d      t        |                  5 }	}}t        t        t        t        t        |	             }
t        |j                        D cg c]*  \  }}|v rt        d t        |   |      D              n|, }}}|sJt        |j                        D cg c]	  }|vs| c}fd}t        ||
      }
t	         ||            }i }t        |
t        |	       D ]  \  }}t        |      D ci c]  \  }}t        |      dk(  s|vs||d   ! }}}t        fdt        |      D              }t!        |j"                  ft        |j                        ||      }| |f||f|z   <    t%        j&                  |||g      }|j(                  }|	  | |d	
      }t1        |      rT|j                  t        |      k7  r<t        |      dk(  r|j3                         }n|j5                  dt        |      z        }t7        j8                  |      rt;        ||||      S t=        j>                  t@              5  tC        jD                         5  |jG                  d      rtC        jH                  dtJ               |jM                  |      }ddd       ddd       t;        ||||      S c c}}w c c}}w c c}w c c}}w # t*        $ r3 	  | |      }n%# t,        $ r}dt/        |      v r|}Y d}~nd}~ww xY wY _t,        $ r Y jw xY w# 1 sw Y   xY w# 1 sw Y   xY w)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
    -r1   c              3      K   | ]  }d   yw)r1   Nr3   )r%   ps     r)   r*   z!partial_reduce.<locals>.<genexpr>-  s     :Aa:s   c                    t        |       S r"   )r   )r_   out_axiss    r)   <lambda>z partial_reduce.<locals>.<lambda>2  s    3x+     r   c              3  2   K   | ]  }|d    v s|  yw)r   Nr3   )r%   r&   rF   s     r)   r*   z!partial_reduce.<locals>.<genexpr>:  s     D1!0CQDs   )dependenciesNT)r,   z&zero-size array to reduction operation)r   r   )varmomentignore)rI   )'r   r   r=   rY   listr	   r   r5   r   mapr#   r>   r4   r6   ziprT   r   r.   r   from_collectionsr+   rA   r8   strr   sumreshapenpisscalarr   
contextlibsuppressAttributeErrorwarningscatch_warnings
startswithsimplefilterr   astype)rb   rC   rF   r   r   r.   r0   r&   r`   partskeysr'   
out_chunksgetterdskr_   rg   jfreedummyggraphrI   eri   s     `                     @r)   r^   r^     sJ   ( 
	$3&$;RW)XX 	
  ,Q 	];??1a0%(;<E  Cs3/0D  )Q ?@;>N:{1~q9::TUUJ  $QVV}E!0DAE+64 &,-

CD'5/* %1"+A,
A#a&A+!;BVAqtG
 
 D	!DDy%-u= !9TGaK% ++D#QCHE77D	T:D  Ddii3z?:z?a88:D<<s: 67D	{{4UD*E::  0 	&(2I2I2K 	&01%%h?;;u%D	& 	& UD*488q

 F
  	((L) (;s1vE'D(
  			& 	& 	& 	&s   8L4/L?	L"	L"L'1L'6L'?
L- %N:=M77N-	M47M ?M4 	M"	MM4M""M4(M43M47N 	<NN)NFNNNNNTr1   NN)NNNTN)FNNN)/
__future__r   rU   rz   rZ   r}   	functoolsr   	itertoolsr   numbersr   numpyrx   tlzr   r   r	   daskr
   dask.array.blockwiser   dask.array.corer   r   r   r   r   dask.array.numpy_compatr   dask.array.utilsr   r   r   	dask.baser   dask.blockwiser   dask.highlevelgraphr   
dask.utilsr   r   r   rO   rB   r^   r3   rk   r)   <module>r      s    "         + +  * V V 2 F F  % . ; ; 

		{#H 	7v OSN9rk   