
    CdD@                   0   d dl mZ d dlZd dlZd dlmZ d dlmZmZm	Z	 d dl
mZ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mZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#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. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z< d dl=m>Z> d dl?m@Z@mAZA d dlBmCZC d dlDmEZEmFZFmGZGmHZHmIZI eJZK eFe          dddd            ZL eFe          d             ZM eFe          d             ZN eFe          d             ZO eFe          d             ZP eFe          dd            ZQ eFe          dd            ZR eFe          dd            ZS eFe          d             ZT eFe          dd            ZUdd ZV eFe          d!             ZW eFe          d"             ZX eFe          dd%            ZYd& ZZd' Z[ eFe          dd)            Z\ eFed*g+          d,             Z] eFe          d-             Z^dd.Z_dd/Z`d0 Za eFe          d1             Zb eFe          d2             Zcd3 Zd eFe          ddd4d5            Ze eFe          d6             Zf eFe          dd7            Zg eFe          dd9            Zh eFe          dd:            Zid; Zj eFe          dd<d=            Zkd> Zl eFe          dd?            Zm eFe          dd@            ZndA Zo eFe          ddC            ZpddEZqddFZrddGZsddIZtdJ ZudK ZvddLZw eFe          ddM            Zx eFe          ddN            Zy e ejz        ej{                   eFe          ddO                        Zz e ej|                   eFe          dP                         Z| e ej}                   eFe          dQ                         Z}ddRZ~	 ddSZ eFe          ddT            ZddUZ e6 eedVd                    ddW            Z eFe          ddX            Z eFe          dY             Z eFe          dZ             Z eFe          d[             Z eFe          d\             Z eFe          dd]            Z eFe          dd^            Z eFe          d_             Z eFe          dd`            Zda Z eFe          ddb            Zdc Zdd Zde Z eFe          ddh            Z eFe          ddi            Zdj Z eFe          dk             Zdl Z ej        eegm          Zdn Z eFe          do             Z eFe          ddp            Z eFe          ddq            Z eFe          dr             Z eFe          ds             Zdt Z eFe          ddv            Z e	ej                  ddx            Zdy Z eFe          dz             Zd{ Z eFe          dd|            ZddZddZ e	ej                  dd            ZddZ eFe          d             Z eFe          d             Z eFe          dd            Z	 ddZ eFe          dd            Z eFe          dd            Z eFe          dd            Z eFe          dd            Z eFe          dd            Z eFe          dd            Z eFe          dd            ZdS )    )annotationsN)Iterable)partialreducewraps)IntegralReal)concat
interleavesliding_window)chunk)Array
asanyarrayasarray	blockwisebroadcast_arraysbroadcast_shapesbroadcast_toconcatenateelemwise
from_array
implementsis_scalar_for_elemwise
map_blocksstacktensordot_lookup)arangediagemptyindicestri)einsum)	reduction)multiplysqrt)
array_safeasarray_safemeta_from_array
safe_wrapsvalidate_axis)ones)is_dask_collectiontokenize)flatten)Delayedunpack_collections)HighLevelGraph)applyderived_fromfuncnameis_arraylikeis_cupy_typelikec                   t          | |          } |$| j        |k     r| d d d f         } || j        |k     | | j        |k    r|                     |          } | S )Nr7   )r   ndimdtypeastype)xr;   ndminr8   s       3lib/python3.11/site-packages/dask/array/routines.pyarrayr@   4   sm    A

dAAAgJ 
QW--HHUOOH    c                 6    d | D             } t          j        |  S )Nc                >    g | ]}t          |          r|n|j        S  )r   r;   ).0as     r?   
<listcomp>zresult_type.<locals>.<listcomp>@   s,    FFFA'**7AAFFFrA   )npresult_type)argss    r?   rI   rI   >   s"    FFFFFD>4  rA   c                     g }| D ]m}t          |          }|j        dk    r	|d         }n3|j        dk    r|d d d d f         }n|j        dk    r|d d d d d f         }|                    |           nt          |          dk    r|d         S |S )Nr   NNN      r   r:   appendlenarysnew_arysr=   s      r?   
atleast_3drU   D   s    H 	 	qMM6Q;;"#AAVq[[$4- AAVq[[!!!QQQ*A
8}}{rA   c                     g }| D ]Q}t          |          }|j        dk    r	|d         }n|j        dk    r|d d d f         }|                    |           Rt          |          dk    r|d         S |S )Nr   NNrM   rO   rR   s      r?   
atleast_2drX   X   s    H  qMM6Q;;*AAVq[[$'
A
8}}{rA   c                     g }| D ]9}t          |          }|j        dk    r|d          }|                    |           :t          |          dk    r|d         S |S )Nr   rM   rO   rR   s      r?   
atleast_1drZ   j   sj    H  qMM6Q;;$A
8}}{rA   Fc                    t          | t                    rt          d          t          d | D                       } t	          | d|          S )Nz=``vstack`` expects a sequence of arrays as the first argumentc              3  4   K   | ]}t          |          V  d S N)rX   rE   r=   s     r?   	<genexpr>zvstack.<locals>.<genexpr>   (      ++!
1++++++rA   r   axisallow_unknown_chunksizes
isinstancer   NotImplementedErrortupler   tuprc   s     r?   vstackrj   z   ]    #u 
!K
 
 	
 ++s+++
+
+Cs=UVVVVrA   c                    t          | t                    rt          d          t          d | D                       rt	          | d|          S t	          | d|          S )Nz=``hstack`` expects a sequence of arrays as the first argumentc              3  ,   K   | ]}|j         d k    V  dS rM   Nr:   r^   s     r?   r_   zhstack.<locals>.<genexpr>   s(      
$
$116Q;
$
$
$
$
$
$rA   r   ra   rM   )re   r   rf   allr   rh   s     r?   hstackrq      s    #u 
!K
 
 	
 
$
$
$
$
$$$ 
a2J
 
 
 	
 a2J
 
 
 	
rA   c                    t          | t                    rt          d          t          d | D                       } t	          | d|          S )Nz=``dstack`` expects a sequence of arrays as the first argumentc              3  4   K   | ]}t          |          V  d S r]   )rU   r^   s     r?   r_   zdstack.<locals>.<genexpr>   r`   rA   rN   ra   rd   rh   s     r?   dstackrt      rk   rA   c           	        ||k    r| S |dk     r
|| j         z   }|dk     r
|| j         z   }t          t          | j                             }t          |          }||c||<   ||<   t          t          j        || |||| j                  S )Nr   )axis1axis2r;   )r:   listranger   rH   swapaxesr;   )rF   rv   rw   indouts        r?   rz   rz      s    ~~qyyqyy
uQV}}

C
s))C"ECJE
R[#q#U%qwWWWWrA   c           
     h    |rCt          |           j        k    rt          d          t           fd|D                       }n*t          t	           j                            d d d         }t          t          j        | t          t	           j                             j        |          S )Nzaxes don't match arrayc              3  <   K   | ]}|d k     r
|j         z   n|V  dS r   Nro   )rE   drF   s     r?   r_   ztranspose.<locals>.<genexpr>   s5      >>A1q55QZZa>>>>>>rA   )r;   axes)	rQ   r:   
ValueErrorrg   ry   r   rH   	transposer;   )rF   r   s   ` r?   r   r      s     *t995666>>>>>>>>>U16]]##DDbD)
dAuU16]]3317   rA   c           	        t          |           } | j        t          d          gz  }|t          | j                  }t	          |t
                    s|f}	 |D ]}t          ddd          ||<   nH# t          $ r;}t          dt          |           dt          | j                   d          |d}~ww xY wt          |          }| |         S )a;  
    Reverse element order along axis.

    Parameters
    ----------
    m : array_like
        Input array.
    axis : None or int or tuple of ints, optional
        Axis or axes to reverse element order of. None will reverse all axes.

    Returns
    -------
    dask.array.Array
        The flipped array.
    Nr   z
`axis` of z invalid for z-D array)
r   r:   slicery   re   r   
IndexErrorr   strrg   )mrb   slaxes        r?   flipr      s    " 	1A	
5;;-	B|QV}}dH%% w 	+ 	+B4r**BrFF	+   FTFFQVFFF
 
	 
rBR5Ls   A1 1
B6;6B11B6c                "    t          | d          S Nr   r   r   s    r?   flipudr          1::rA   c                "    t          | d          S NrM   r   r   s    r?   fliplrr      r   rA   rM   r   rM   c                   t          |          }t          |          dk    rt          d          t          |           } |d         |d         k    s,t	          j        |d         |d         z
            | j        k    rt          d          |d         | j        k    s5|d         | j         k     s#|d         | j        k    s|d         | j         k     rt          d| d| j         d          |d	z  }|dk    r
| d d          S |dk    r*t          t          | |d                   |d                   S t          t          d| j                            }||d                  ||d                  c||d         <   ||d         <   |dk    r$t          t          | |d                   |          S t          t          | |          |d                   S )
NrN   zlen(axes) must be 2.r   rM   zAxes must be different.zAxes=z  out of range for array of ndim=.   )rg   rQ   r   r   rH   absoluter:   r   rx   ry   r   )r   kr   	axes_lists       r?   rot90r      s   ;;D
4yyA~~/0001AAw$q'R[a47):;;qvEE2333Aw!&DGqvg--aAF1B1Bd1gQRQWPWFWFWPPPqvPPPQQQFAAvvtAvvDDG$$d1g...U1af%%&&I09$q'0BIdSTgDV,YtAw47+Avvaa))9555 Ia++T!W555rA   c                ~   t          | |gd           }t          j        t          |                    } || ||          }|rt	          |d                   dk    r|S t          d d           g|j        z  }t          |d                   D ]} |                    | d            |t          |                   }|S )Nc                    | j         S r]   )__array_priority__r=   s    r?   <lambda>z_tensordot.<locals>.<lambda>  s	    !"6 rA   )keyr   r   rM   )
maxr   dispatchtyperQ   r   r:   sortedinsertrg   )rF   br   	is_sparser=   	tensordotr{   s          r?   
_tensordotr   
  s    QF66777A )$q''22I	!QT"""A Sa\\Q&&T4  !AF*Q 	  	 AJJq$eCjjMrA   c                    dt          t          | j                            v }|r#dt          t          | j                            v}|S )Nsparsezsparse._coo.core.COO)r   r   _meta)r=   r   s     r?   _tensordot_is_sparser     sE    CQW...I E*#d17mm2D2DD	rA   rN   c                   t          | t                    st          |           } t          |t                    st          |          }t          |t                    r|\  }}nGt	          t          | j        |z
  | j                            }t	          t          d|                    }t          |t                    r|f}t          |t                    r|f}t          |t                    rt	          |          }t          |t                    rt	          |          }t          |           pt          |          }|rt          |          dk    rd}nd}t          j        | j        |j                  }t          t          | j                            }t          t          | j        | j        |j        z                       }	||	z   }
i }t          ||          D ]U\  }}|
                    |	|                    ||         |	|<   |r|
                    ||                    Id |||         <   Vt!          t"          |
| |||	|||||f|          }|r|S |                    |          S )Nr   rM   TFc                    dS r   rD   )cs    r?   r   ztensordot.<locals>.<lambda>D  s    Q rA   )r;   r   adjust_chunksr   r   rb   )re   r   r   r   rg   ry   r:   r   rx   r   rQ   rH   promote_typesr;   zipremover   r   sum)lhsrhsr   	left_axes
right_axesr   r   dt
left_indexright_index	out_indexr   lrintermediates                  r?   r   r      sr   c5!! ooc5!! oo$!! + $	::%4::;;	5D>>**
)X&& !L	*h'' # ]
)T"" %)$$	*d## ':&&
$S))F-A#-F-FI S^^q((		#)SY	/	/BeCHoo&&JuSXsx#(':;;<<K[(IMIz** 7 71Q(((#AA 	7Z]+++++6;M*Q-((#$  L  0Y///rA   r|   )ua_argsc                N    t          | || j        dz
  f|j        dz
  ff          S )NrM   rN   r   )r   r:   rF   r   s     r?   dotr   X  s,    Q!&1*! >????rA   c                    t          |                                                                 |                                          S r]   )r   conjravelr   s     r?   vdotr   ]  s,    qvvxx~~+++rA   c                    t          |           t          u r*t          t          t          j        |          |           }n| }|r|S |                    |d                   S )Nr;   r   )r   rx   r   r   rH   addsqueeze)rF   rb   r;   keepdimsr|   s        r?   
_chunk_sumr   b  s[     Aww$WRV5111155 $
{{47###rA   c                   |At          t          j        d| j                                                  dt
                    }| j        |         dk    r|                     |          S t          | t          t          ||d          S )NrM   r   r;   F)rb   r;   r   )
getattrrH   zerosr;   r   objectshaper   r#   r   )rF   rb   r;   s      r?   _sum_wo_catr   v  sz    }!'2226688'6JJwt}yy	:zEu   rA   c                    t           }t          |           rdd l}|}|                    | |          }|d|j        d d f         S )Nr   .)rH   r6   cupymatmulnewaxis)rF   r   xpr   r   s        r?   _matmulr     sP    	BA  	IIaOOE bj!!!#$$rA   c                   t          |           } t          |          }| j        dk    s|j        dk    rt          d          d}| j        dk    rd}| t          j        d d f         } d}|j        dk    rd}|d d t          j        f         }| j        |j        k     r$| |j        | j        z
  t          j        fz           } n3| j        |j        k    r#|| j        |j        z
  t          j        fz           }t          t          | j        dz                       }t          t          | j                            }t          t          | j        dz
                      |d         | j        fz   }t          t          || ||||d         dit          | |          d	  	        }t          |d	
          }|r|                    d	          }|r|                    d          }|S )Nr   z"`matmul` does not support scalars.FrM   TrN   r   )r   r;   r   r   )r   r:   r   rH   r   rg   ry   r   r   rI   r   r   )rF   r   a_is_1db_is_1dout_indlhs_indrhs_indr|   s           r?   r   r     s   1A1Av{{afkk=>>>Gv{{bj!!!mGv{{aaamvqv2:-/0	
!&qv2:-/0 E!&1*%%&&GE!&MM""G E!&1*%%&&'"+qv)>>G
		r{A&!Q
 
 
C$ c
#
#
#C kk"oo kk"ooJrA   c           	     "   |                                  } |                                 }t          j        | j                                        |j                                                  j        }t          t          j        d| d|d|          S )Nijijr   )r.   rH   outerr;   r   r   )rF   r   r;   s      r?   r   r     sc    			A			AHQW\\^^QW\\^^44:ERXtQQ5AAAArA   c                0    t          j        ||| g|R i |S r]   )rH   apply_along_axis)arrfunc1dfunc1d_axisfunc1d_argsfunc1d_kwargss        r?   _inner_apply_along_axisr     s'    v{CW+WWWWWWrA   )r;   r   c                  t          |          }t          |j        d|                   }||Kt          j        d|j                  }t          j         | |g|R i |          }||j        }||j        }|                    |j        d|         |j        ||dz            fz   |j        |dz   d         z             }|	                    t          t          |           dz   ||j        d|         |z   |j        |dz   d         z   |t          t          ||t          |          z   d                    | |||
  
        }	|	S )aj  
    This is a blocked variant of :func:`numpy.apply_along_axis` implemented via
    :func:`dask.array.map_blocks`

    Notes
    -----
    If either of `dtype` or `shape` are not provided, Dask attempts to
    determine them by calling `func1d` on a dummy array. This may produce
    incorrect values for `dtype` or `shape`, so we recommend providing them.
    NrM   r   rM   z-along-axis)	namer;   chunks	drop_axisnew_axisr   r   r   r   )r   rQ   r   rH   r+   r;   r@   rechunkr   r   r   r4   rx   ry   )
r   rb   r   r;   r   rJ   kwargs	test_datatest_resultresults
             r?   r   r     sj    #,,C sy$  D }GD	222	hvviA$AAA&AABB=%E=%E ++
5D5SYtdQh799CJtaxzz<RR C ^^f-
5D5!E)CJtaxzz,BBeD$U"3Q7788   F MrA   c                Z   t          |          }	 t          |          }n# t          $ r |f}Y nw xY w|j        t	          d           fz  }|}|D ]Z}t          | ||d          }|j        |j        dz
  k    r||d |         dz            };|j        |j        k    rt          d          [|S )Nr   rM   r]   zJfunc must either preserve dimensionality of the input or reduce it by one.)r   rg   	TypeErrorr:   r   r   r   )funcrF   r   r   r   r   s         r?   apply_over_axesr    s     	

AT{{   w 
5;;.	 B F 
 
!$6155 ;16A:&&BrrFW,-FF[AF""(   # Ms   ! 11c                \    |                      |          |                     |          z
  S Nr   )r   minrF   rb   s     r?   ptpr  2  s)    55d5aeee....rA   r   c                (   t          |           } t          |          }t          |          }|dk    r| S |dk     rt          d|z            g }|tt          |t	          |                     }|j        dk    r6t          | j                  }d||<   t          |t          |                    }|
                    |           |
                    |            |yt          |t	          |                     }|j        dk    r;t          | j                  }d||<   t          j        |t          |                    }|
                    |           t          |          dk    rt          ||          } | j        t          d           gz  }| j        t          d           gz  }t          dd           ||<   t          d d          ||<   t          |          }t          |          }| }	t          |          D ]}
|	|         |	|         z
  }	|	S )Nr   z%order must be non-negative but got %dr7   rM   r   )r   intr   r'   r(   r:   rx   r   r   rg   rP   rH   rQ   r   r   ry   )rF   nrb   prependrP   combinedr   sl_1sl_2r   _s              r?   diffr  7  s   

AAAt99DAvv1uu@1DEEEHw_Q-?-?@@@<1MMEE$K"7E%LL99G   OOAf?1+=+=>>>;!MMEE$K_VU5\\::F
8}}q$''6U4[[M!D6U4[[M!Dq$DJtRDJ;;D;;D	A1XX  dGagHrA   c                6   t          |           } |                                 }|dd          |d d         z
  }|g}|%t          |                                          g|z   }|%|t          |                                          gz   }t          |          }|S )NrM   r   )r   r.   r   )aryto_endto_beginaryfr   s        r?   ediff1dr  h  s    
#,,C;;==DQRR49A	
AX&&(()A-((**++AAHrA   c                    ||         }|"||d         |         |d         |                  }t          j        | |fd|i|}|S )aU  
    x: nd-array
        array of one block
    coord: 1d-array or scalar
        coordinate along which the gradient is computed.
    axis: int
        axis along which the gradient is computed
    array_locs:
        actual location along axis. None if coordinate is scalar
    grad_kwargs:
        keyword to be passed to np.gradient
    Nr   rM   rb   )rH   gradient)r=   block_idcoordrb   
array_locsgrad_kwargs	block_locgrads           r?   _gradient_kernelr   y  sW     IjmI.Ay1IIJ;q%::d:k::DKrA   r   c                   t                      t          j        |                    dd                    |d<   |d         dk    rt	          d          d}|"t          t           j                            }nt          |t                    rd}|f}t          | j                  }t          |          t          t          |                    k    rt	          d          t           fd|D                       }|d	k    rd
}t          |          dk    rt          |          |z  }t          |          t          |          k    rt          d          t           j        j        t"          j        t          f          r                     t(                     nIt           j        j        t*                    r* j        j        dk     r                     t(                     g }t/          |          D ]h\  } j                 D ]X}t#          j        |          |d         dz   k     r5t	          d                    t#          j        |                              Yt#          j        ||                   rd }nt          ||         t8                    rt;          d          t#          j         j                           }	t#          j        |	          dz   }
|
|	z
  dz
  }|
dxx         dz  cc<   d|d<   ||
f}|                      !                    tD           j        fdt           j                  D             d||         ||                     j|r|d         }|S )N
edge_orderrM   rN   z+edge_order must be less than or equal to 2.FTzduplicate axes not allowedc              3  ,   K   | ]}|j         z  V  d S r]   ro   )rE   r   fs     r?   r_   zgradient.<locals>.<genexpr>  s)      ,,af,,,,,,rA   rD   r   zGSpacing must either be a single scalar, or a scalar / 1d-array per axisr   zcChunk size must be larger than edge_order + 1. Minimum chunk for axis {} is {}. Rechunk to proceed.z(dask array coordinated is not supported.r   r   c                &    i | ]}||k    rd ndS )rM   r   rD   )rE   r   r   s     r?   
<dictcomp>zgradient.<locals>.<dictcomp>  s'    EEE!qqBww!!AEEErA   none)r;   depthboundaryr  rb   r  r  )#r   mathceilgetr   rg   ry   r:   re   r   r*   rQ   setr  
issubclassr;   r   rH   bool_r<   floatr	   itemsize	enumerater   r  formatisscalarr   rf   r@   cumsumrP   map_overlapr   )r$  rb   varargsr   drop_result_listresultsr   r   r  r   array_loc_stoparray_loc_startr   s   `           @r?   r  r    sb   

A9VZZa%@%@AAF<laFGGG|U16]]##	D(	#	# wqv&&D
4yyCD		NN""5666,,,,t,,,,,D"}}
7||qd))g%
7||s4yy  U
 
 	
 !',8 455 HHUOO	AGL$	'	' AG,<q,@,@HHUOOG4 !
 !
2" 	 	Avayy6,/!333 %vb"&))44   4 ;wqz"" 	;JJ'!*e,, V)*TUUUHQXb\**EYu--1N,u4q8O2!#!"OA)>:JMM gEEEEuQV}}EEEaj%"  	 		
 	
 	
 	
  !*NrA   c                    t          | t                    s| S t          t          t          |                     }t          j        | d         ||          }| D ]!}|d t	          |          xx         |z  cc<   "|S )Nr   )r   r;   )re   rx   r   maprQ   rH   
zeros_like)	bincountsr;   r   r  r|   r   s         r?   _bincount_aggr@    s    i&& CY  A
-	!AU
;
;
;C  Hc!ffHJrA   c           	     6   | j         dk    rt          d          ||j        | j        k    rt          d          t          | ||          }| dg}|Lt	          t          j        dgdg          t          |                     }|                    |dg           n0t	          t          j        g           t          |                     }|dk    rt
          j	        f}n|f}t          t          t
          j        |          dg|R ||d	}|t          |j        d                   z  g|j        dd          R |_        dd
lm}	  |	|t          t           |j                  dd|j        |d          }
|g|j        dd          R |
_        ||
_        |
S )NrM   z8Input array must be one dimensional. Try using x.ravel()z/Chunks of input array x and weights must match.r   )weightsr7   r   )	minlength)tokenmeta)_tree_reducer   r   TF)	aggregaterb   r   r;   split_everyr   )r:   r   r   r-   r&   rH   bincountr(   extendnanr   r   rQ   _chunksdask.array.reductionsrF  r@  r;   r   )r=   rB  rC  rI  rD  rJ   rE  output_sizechunked_countsrF  outputs              r?   rJ  rJ    s   v{{STTT>QX%%NOOOQ++Es8D"+qcA3777oa>P>PQQQWcN####"+b//0B0BCCCA~~vi ly11139= EJQU  N 	c./2333		qrr	" N
 322222\-tz:::j  F ">N$9!""$=>>FNFLMrA   c                    t          |t          |                     }t          j        t          dg|          |d          j        }|                     t          j        |||          S )Nr7   r   F)right)r;   binsrS  )r'   r(   rH   digitizer;   r   )rF   rT  rS  r;   s       r?   rU  rU    s`    ?1#5#5666DKaSt444d%HHHNE<<5t5<IIIrA   c                n    t          j        | ||          }d||dk    <   |t           j        d d f         S )N)sider   r   )rH   searchsortedr   )r=   yrW  ress       r?   _searchsorted_blockr[    s<    
/!QT
*
*
*C CqMrz111}rA   leftc                   | j         dk    rt          d          |t          d          t          j        | j        |j                  }t          t          t          t          |j         dz                       | dg|t          t          d|j         dz                       |d |ddi
  
        }t          dg| j        d         R t          |                     }t          j        |          d d         }|t          f|j         t          j        fz  z            }t!          |d          }t#          |dk     |||z             }|                    d	          }d||dk    <   |S )
NrM   z%Input array a must be one dimensionalz7da.searchsorted with a sorter argument is not supportedr   )rE  r   r7   r   r   r   )r:   r   rf   rH   rX  r   r   r[  rx   ry   r&   r   r(   r5  Ellipsisr   r   wherer   )	rF   vrW  sorterrE  r|   a_chunk_sizesa_chunk_offsets	a_offsetss	            r?   rX  rX  #  sg   v{{@AAA!E
 
 	

 ?17AG,,D
U16A:		
	U1afqj!!""!f  C 0AHQK00q7I7IJJJMi..ss3O%xkAFbj]4J&JKO222I
acIo
.
.C ''q'//C Cr	NJrA   2   c                x   dt          | ||          z   }t          | ||g          \  \  }}}}t          |          dk    rt          j        | ||          S |dft          j        |||fi}t          j        |||          }	t          |          rt          j        ffn|ff}
t          |	||
t                    S )Nz	linspace-r   )numdependenciesr   )r-   r0   rQ   rH   linspacer1   from_collectionsr,   rL  r   r0  )startstoprh  linspace_name	start_refstop_refnum_refdepslinspace_dsklinspace_graphr   s              r?   _linspace_from_delayedrv  M  s    (5$"<"<<M+=udC>P+Q+Q("Y'D
4yyA~~{5$C0000"A&i7(STL#4|$  N 044Crvi\\C6)FeDDDDrA   c                ^    t          j        | |||          d         t           j                 S )Nry   rB  r   )rH   	histogramr   )r=   rT  ry   rB  s       r?   _block_histrz  \  s'    <4ug>>>qA"*MMrA   c                   t          |t                    r|j        dk    }nBt          |t                    r|j        du p
|j        dk    }nt          j        |          dk    }||r|t          d          ||j        | j        k    rt          d          |durt          d          |r-|r+t          |t          t          f          rt          d          d	|fd
|fd|ffD ]S\  }}t          |t          t          f          s2t          |          r#t          d                    ||                    T|	 t          |          dk    r t          dt          |           d          t          |t          t
          j        f          r"|j        dk    rt          d|j                   n!# t          $ r t          d|           dw xY wt          | ||||          }	d|	z   |r!t!          |d         |d         |dz             }nRt          |t          t
          j        f          st#          |          }|j        dk    rt          d|j                   t%          ||g          \  \  }
|\fdt'          t)          |                                                     D             }t          j        g           d         j        }ntt)          |                                           }t)          |                                          }fdt'          t1          ||                    D             }|j        }| f|
z   }
||
|fz  }
t3          j        ||
          }t          t7          t)          |                                                               }|j        dz
  }d|z  |ff}t          |||          }|                    d          }|b|r\t#          t          j        |                              t@                    |j                  }||z  |                                z  |fS ||fS ||fS )aW  
    Blocked variant of :func:`numpy.histogram`.

    Parameters
    ----------
    a : dask.array.Array
        Input data; the histogram is computed over the flattened
        array. If the ``weights`` argument is used, the chunks of
        ``a`` are accessed to check chunking compatibility between
        ``a`` and ``weights``. If ``weights`` is ``None``, a
        :py:class:`dask.dataframe.Series` object can be passed as
        input data.
    bins : int or sequence of scalars, optional
        Either an iterable specifying the ``bins`` or the number of ``bins``
        and a ``range`` argument is required as computing ``min`` and ``max``
        over blocked arrays is an expensive operation that must be performed
        explicitly.
        If `bins` is an int, it defines the number of equal-width
        bins in the given range (10, by default). If `bins` is a
        sequence, it defines a monotonically increasing array of bin edges,
        including the rightmost edge, allowing for non-uniform bin widths.
    range : (float, float), optional
        The lower and upper range of the bins.  If not provided, range
        is simply ``(a.min(), a.max())``.  Values outside the range are
        ignored. The first element of the range must be less than or
        equal to the second. `range` affects the automatic bin
        computation as well. While bin width is computed to be optimal
        based on the actual data within `range`, the bin count will fill
        the entire range including portions containing no data.
    normed : bool, optional
        This is equivalent to the ``density`` argument, but produces incorrect
        results for unequal bin widths. It should not be used.
    weights : dask.array.Array, optional
        A dask.array.Array of weights, of the same block structure as ``a``.  Each value in
        ``a`` only contributes its associated weight towards the bin count
        (instead of 1). If ``density`` is True, the weights are
        normalized, so that the integral of the density over the range
        remains 1.
    density : bool, optional
        If ``False``, the result will contain the number of samples in
        each bin. If ``True``, the result is the value of the
        probability *density* function at the bin, normalized such that
        the *integral* over the range is 1. Note that the sum of the
        histogram values will not be equal to 1 unless bins of unity
        width are chosen; it is not a probability *mass* function.
        Overrides the ``normed`` keyword if given.
        If ``density`` is True, ``bins`` cannot be a single-number delayed
        value. It must be a concrete number, or a (possibly-delayed)
        array/sequence of the bin edges.

    Returns
    -------
    hist : dask Array
        The values of the histogram. See `density` and `weights` for a
        description of the possible semantics.
    bin_edges : dask Array of dtype float
        Return the bin edges ``(length(hist)+1)``.

    Examples
    --------
    Using number of bins and range:

    >>> import dask.array as da
    >>> import numpy as np
    >>> x = da.from_array(np.arange(10000), chunks=10)
    >>> h, bins = da.histogram(x, bins=10, range=[0, 10000])
    >>> bins
    array([    0.,  1000.,  2000.,  3000.,  4000.,  5000.,  6000.,  7000.,
            8000.,  9000., 10000.])
    >>> h.compute()
    array([1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000])

    Explicitly specifying the bins:

    >>> h, bins = da.histogram(x, bins=np.array([0, 5000, 10000]))
    >>> bins
    array([    0,  5000, 10000])
    >>> h.compute()
    array([5000, 5000])
    r   NrM   zudask.array.histogram requires either specifying bins as an iterable or specifying both a range and the number of binsz<Input array and weights must have the same chunked structureFzThe normed= keyword argument has been deprecated. Please use density instead. See the numpy.histogram docstring for more information.zWhen `density` is True, `bins` cannot be a scalar Dask object. It must be a concrete number or a (possibly-delayed) array/sequence of bin edges.rT  ry   rB  zdDask types besides Array and Delayed are not supported for `histogram`. For argument `{}`, got: {!r}rN   z7range must be a sequence or array of length 2, but got z itemsrN   zLrange must be a 1-dimensional array of two items, but got an array of shape z,Expected a sequence or array for range, not zhistogram-sum-z:bins must be a 1-dimensional array or sequence, got shape c                4    i | ]\  }}|d ft           |fS rG  rz  )rE   r   r   bins_refr   	range_refs      r?   r&  zhistogram.<locals>.<dictcomp>  s>     
 
 
1 1aL;8Y?
 
 
rA   c                <    i | ]\  }\  }}|d ft           ||fS rG  r~  )rE   r   r   wr  r   r  s       r?   r&  zhistogram.<locals>.<dictcomp>  sD     
 
 
6Aq 1aL;8YB
 
 
rA   ri  r   r   r   r^  )!re   r   r:   r/   _lengthrH   r   r   rf   r,   r  r3  rQ   ndarrayr   r-   rv  r   r0   r2  r.   __dask_keys__ry  r;   r   r1   rl  rx   sizer   r  r<   r0  )rF   rT  ry   normedrB  densityscalar_binsargnamevalrD  rs  dskr;   a_keysw_keysgraphnchunksnbinsr   mappedr  dbr  r   r  s                         @@@r?   ry  ry  `  s   b $ )i1n	D'	"	" )ld*?dla.?gdmmq(||!
 
 	
 w~99WXXXUF
 
 	
  
; 
:dUG4D#E#E 
!`
 
 	

 !$'5)9Iw;OP  $ 011 	6H6N6N 	@@FwPS@T@T  
 	5zzQ `cRWjj```   %%!455 %+:M:M pchcnpp    	 	 	FuFF 	
 QeWg66Ee#D 
%eAha$(CC $
 344 	!4==D9>>YTZYY   #5dE]"C"CXy4 
 
 
 
 
 
!'!//*;*;"<"<==
 
 
 R  #)**++..0011
 
 
 
 
 
&s66':':;;
 
 
 4$;D
+D#DIIIE $wq00112233GIMEWnuh'F5$e444F 	


A  	--e44QXFFFBr6AEEGG#T))d7N$ws   A6F8 8G
   c                X    t          | |f|||||          \  }}||d         |d         fS )a  Blocked variant of :func:`numpy.histogram2d`.

    Parameters
    ----------
    x : dask.array.Array
        An array containing the `x`-coordinates of the points to be
        histogrammed.
    y : dask.array.Array
        An array containing the `y`-coordinates of the points to be
        histogrammed.
    bins : sequence of arrays describing bin edges, int, or sequence of ints
        The bin specification. See the `bins` argument description for
        :py:func:`histogramdd` for a complete description of all
        possible bin configurations (this function is a 2D specific
        version of histogramdd).
    range : tuple of pairs, optional.
        The leftmost and rightmost edges of the bins along each
        dimension when integers are passed to `bins`; of the form:
        ((xmin, xmax), (ymin, ymax)).
    normed : bool, optional
        An alias for the density argument that behaves identically. To
        avoid confusion with the broken argument in the `histogram`
        function, `density` should be preferred.
    weights : dask.array.Array, optional
        An array of values weighing each sample in the input data. The
        chunks of the weights must be identical to the chunking along
        the 0th (row) axis of the data sample.
    density : bool, optional
        If False (the default) return the number of samples in each
        bin. If True, the returned array represents the probability
        density function at each bin.

    Returns
    -------
    dask.array.Array
        The values of the histogram.
    dask.array.Array
        The edges along the `x`-dimension.
    dask.array.Array
        The edges along the `y`-dimension.

    See Also
    --------
    histogram
    histogramdd

    Examples
    --------
    >>> import dask.array as da
    >>> x = da.array([2, 4, 2, 4, 2, 4])
    >>> y = da.array([2, 2, 4, 4, 2, 4])
    >>> bins = 2
    >>> range = ((0, 6), (0, 6))
    >>> h, xedges, yedges = da.histogram2d(x, y, bins=bins, range=range)
    >>> h
    dask.array<sum-aggregate, shape=(2, 2), dtype=float64, chunksize=(2, 2), chunktype=numpy.ndarray>
    >>> xedges
    dask.array<array, shape=(3,), dtype=float64, chunksize=(3,), chunktype=numpy.ndarray>
    >>> h.compute()
    array([[2., 1.],
           [1., 2.]])
    )rT  ry   r  rB  r  r   rM   )histogramdd)	r=   rY  rT  ry   r  rB  r  countsedgess	            r?   histogram2dr     sJ    ~  	
A  MFE 58U1X%%rA   c                B    t          j        | |||          dd         S )aO  Call numpy.histogramdd for a blocked/chunked calculation.

    Slurps the result into an additional outer axis; this new axis
    will be used to stack chunked calls of the numpy function and add
    them together later.

    Returns
    -------
    :py:object:`np.ndarray`
        NumPy array with an additional outer dimension.

    rx  r   rM   rH   r  )samplerT  ry   rB  s       r?   _block_histogramdd_rectr  j  s&     >&$eWEEEacJJrA   c                 r    | dd         \  }}}| dd         }t          j        ||||          dd         S )ax  Call numpy.histogramdd for a multi argument blocked/chunked calculation.

    Slurps the result into an additional outer axis; this new axis
    will be used to stack chunked calls of the numpy function and add
    them together later.

    The last three arguments _must be_ (bins, range, weights).

    The difference between this function and
    _block_histogramdd_rect is that here we expect the sample
    to be composed of multiple arguments (multiple 1D arrays, each one
    representing a coordinate), while _block_histogramdd_rect
    expects a single rectangular (2D array where columns are
    coordinates) sample.

    N)rT  ry   rB  r   rM   r  )rJ   rT  ry   rB  r  s        r?   _block_histogramdd_multiargr  z  sG    "  9D%#2#YF>&t5'JJJ1Q3OOrA   c                    ||d}n||}nt          d          t                    }t          t          t          f          r|pt          d D                       }t          d D                       nd}|s|rt          d          t           ||          }d| t           d          rpt           j
                  d	k    rt          d
           j
        \  }	 j        d         }
d} j
        dd          j        dd         k    rt          d          nt           t          t          f          rcd}t                      d         j        d         }
t          d          D ]-} |         j         d         j        k    rt          d          .nt          d          dfdfd|ffD ]S\  }}t          t           t"          f          s2t                    r#t          d                    ||                    T|O|r+|j        d          j        d         k    rt          d          |s |j        d         |
k    rt          d          t          t          t          f          r"t                    k    rt          d          Jt                    k    rt          d          t'          d D                       st          d          t          t(                    rfz  t'          d D                       r4t'          d D                       rd t+                    D             }nd D             }|r f}nt	                     }|/t-          |                                          }||fz  }|j        }n$d|
z  }t3          j        g           d         j        }t	          d  t                    D                       |rNt-                                                     fd!t7          t+          |                    D             }np fd"t          t                               D             fd#t          |
          D             }fd$t7          t+          ||                    D             }t9          j        ||%          }t	          d& |D                       }d'|
z  g|R }t!          |||(          }|                    d)          }|rt3          j        |j
                  }t                    D ]\}t3          j        t(                    }|j
        |         ||<   |t3          j         ||                   !                    |          z  }]tE          ||j        *          }||z  |                                z  |fS |d+ |D             fS ),a  Blocked variant of :func:`numpy.histogramdd`.

    Chunking of the input data (``sample``) is only allowed along the
    0th (row) axis (the axis corresponding to the total number of
    samples). Data chunked along the 1st axis (column) axis is not
    compatible with this function. If weights are used, they must be
    chunked along the 0th axis identically to the input sample.

    An example setup for a three dimensional histogram, where the
    sample shape is ``(8, 3)`` and weights are shape ``(8,)``, sample
    chunks would be ``((4, 4), (3,))`` and the weights chunks would be
    ``((4, 4),)`` a table of the structure:

    +-------+-----------------------+-----------+
    |       |      sample (8 x 3)   |  weights  |
    +=======+=====+=====+=====+=====+=====+=====+
    | chunk | row | `x` | `y` | `z` | row | `w` |
    +-------+-----+-----+-----+-----+-----+-----+
    |       |   0 |   5 |   6 |   6 |   0 | 0.5 |
    |       +-----+-----+-----+-----+-----+-----+
    |       |   1 |   8 |   9 |   2 |   1 | 0.8 |
    |   0   +-----+-----+-----+-----+-----+-----+
    |       |   2 |   3 |   3 |   1 |   2 | 0.3 |
    |       +-----+-----+-----+-----+-----+-----+
    |       |   3 |   2 |   5 |   6 |   3 | 0.7 |
    +-------+-----+-----+-----+-----+-----+-----+
    |       |   4 |   3 |   1 |   1 |   4 | 0.3 |
    |       +-----+-----+-----+-----+-----+-----+
    |       |   5 |   3 |   2 |   9 |   5 | 1.3 |
    |   1   +-----+-----+-----+-----+-----+-----+
    |       |   6 |   8 |   1 |   5 |   6 | 0.8 |
    |       +-----+-----+-----+-----+-----+-----+
    |       |   7 |   3 |   5 |   3 |   7 | 0.7 |
    +-------+-----+-----+-----+-----+-----+-----+

    If the sample 0th dimension and weight 0th (row) dimension are
    chunked differently, a ``ValueError`` will be raised. If
    coordinate groupings ((x, y, z) trios) are separated by a chunk
    boundry, then a ``ValueError`` will be raised. We suggest that you
    rechunk your data if it is of that form.

    The chunks property of the data (and optional weights) are used to
    check for compatibility with the blocked algorithm (as described
    above); therefore, you must call `to_dask_array` on a collection
    from ``dask.dataframe``, i.e. :class:`dask.dataframe.Series` or
    :class:`dask.dataframe.DataFrame`.

    The function is also compatible with `x`, `y`, and `z` being
    individual 1D arrays with equal chunking. In that case, the data
    should be passed as a tuple: ``histogramdd((x, y, z), ...)``

    Parameters
    ----------
    sample : dask.array.Array (N, D) or sequence of dask.array.Array
        Multidimensional data to be histogrammed.

        Note the unusual interpretation of a sample when it is a
        sequence of dask Arrays:

        * When a (N, D) dask Array, each row is an entry in the sample
          (coordinate in D dimensional space).
        * When a sequence of dask Arrays, each element in the sequence
          is the array of values for a single coordinate.
    bins : sequence of arrays describing bin edges, int, or sequence of ints
        The bin specification.

        The possible binning configurations are:

        * A sequence of arrays describing the monotonically increasing
          bin edges along each dimension.
        * A single int describing the total number of bins that will
          be used in each dimension (this requires the ``range``
          argument to be defined).
        * A sequence of ints describing the total number of bins to be
          used in each dimension (this requires the ``range`` argument
          to be defined).

        When bins are described by arrays, the rightmost edge is
        included. Bins described by arrays also allows for non-uniform
        bin widths.
    range : sequence of pairs, optional
        A sequence of length D, each a (min, max) tuple giving the
        outer bin edges to be used if the edges are not given
        explicitly in `bins`. If defined, this argument is required to
        have an entry for each dimension. Unlike
        :func:`numpy.histogramdd`, if `bins` does not define bin
        edges, this argument is required (this function will not
        automatically use the min and max of of the value in a given
        dimension because the input data may be lazy in dask).
    normed : bool, optional
        An alias for the density argument that behaves identically. To
        avoid confusion with the broken argument to `histogram`,
        `density` should be preferred.
    weights : dask.array.Array, optional
        An array of values weighing each sample in the input data. The
        chunks of the weights must be identical to the chunking along
        the 0th (row) axis of the data sample.
    density : bool, optional
        If ``False`` (default), the returned array represents the
        number of samples in each bin. If ``True``, the returned array
        represents the probability density function at each bin.

    See Also
    --------
    histogram

    Returns
    -------
    dask.array.Array
        The values of the histogram.
    list(dask.array.Array)
        Sequence of arrays representing the bin edges along each
        dimension.

    Examples
    --------
    Computing the histogram in 5 blocks using different bin edges
    along each dimension:

    >>> import dask.array as da
    >>> x = da.random.uniform(0, 1, size=(1000, 3), chunks=(200, 3))
    >>> edges = [
    ...     np.linspace(0, 1, 5), # 4 bins in 1st dim
    ...     np.linspace(0, 1, 6), # 5 in the 2nd
    ...     np.linspace(0, 1, 4), # 3 in the 3rd
    ... ]
    >>> h, edges = da.histogramdd(x, bins=edges)
    >>> result = h.compute()
    >>> result.shape
    (4, 5, 3)

    Defining the bins by total number and their ranges, along with
    using weights:

    >>> bins = (4, 5, 3)
    >>> ranges = ((0, 1),) * 3  # expands to ((0, 1), (0, 1), (0, 1))
    >>> w = da.random.uniform(0, 1, size=(1000,), chunks=x.chunksize[0])
    >>> h, edges = da.histogramdd(x, bins=bins, range=ranges, weights=w)
    >>> np.isclose(h.sum().compute(), w.sum().compute())
    True

    Using a sequence of 1D arrays as the input:

    >>> x = da.array([2, 4, 2, 4, 2, 4])
    >>> y = da.array([2, 2, 4, 4, 2, 4])
    >>> z = da.array([4, 2, 4, 2, 4, 2])
    >>> bins = ([0, 3, 6],) * 3
    >>> h, edges = da.histogramdd((x, y, z), bins)
    >>> h
    dask.array<sum-aggregate, shape=(2, 2, 2), dtype=float64, chunksize=(2, 2, 2), chunktype=numpy.ndarray>
    >>> edges[0]
    dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>
    >>> h.compute()
    array([[[0., 2.],
            [0., 1.]],
    <BLANKLINE>
           [[1., 0.],
            [2., 0.]]])
    >>> edges[0].compute()
    array([0, 3, 6])
    >>> edges[1].compute()
    array([0, 3, 6])
    >>> edges[2].compute()
    array([0, 3, 6])

    NFz*Cannot specify both 'normed' and 'density'c                ,    g | ]}t          |          S rD   r,   rE   r   s     r?   rG   zhistogramdd.<locals>.<listcomp>E  s!    !F!F!FA"4Q"7"7!F!F!FrA   c                ,    g | ]}t          |          S rD   r  rE   r   s     r?   rG   zhistogramdd.<locals>.<listcomp>G  s!    222q""222rA   zCPassing dask collections to bins=... or range=... is not supported.zhistogramdd-sum-r   rN   z4Single array input to histogramdd should be columnarr   TrM   z3Input array can only be chunked along the 0th axis.z2All coordinate arrays must be chunked identically.zCIncompatible sample. Must be a 2D array or a sequence of 1D arrays.rT  ry   rB  zfDask types besides Array and Delayed are not supported for `histogramdd`. For argument `{}`, got: {!r}z_Input array and weights must have the same shape and chunk structure along the first dimension.zFInput arrays and weights must have the same shape and chunk structure.zCThe dimension of bins must be equal to the dimension of the sample.zArange argument requires one entry, a min max pair, per dimension.c              3  <   K   | ]}t          |          d k    V  dS rN   NrQ   r  s     r?   r_   zhistogramdd.<locals>.<genexpr>  s,      ..13q66Q;......rA   z,range argument should be a sequence of pairsc              3  @   K   | ]}t          |t                    V  d S r]   )re   r
  r  s     r?   r_   zhistogramdd.<locals>.<genexpr>  s,      
,
,!:a
,
,
,
,
,
,rA   c              3  <   K   | ]}t          |          d k    V  dS r  r  r  s     r?   r_   zhistogramdd.<locals>.<genexpr>  s,      4P4PQSVVq[4P4P4P4P4P4PrA   c                ^    g | ]*\  }}t          j        |d          |d         |dz             +S r   )rH   rk  )rE   r   r   s      r?   rG   zhistogramdd.<locals>.<listcomp>  s6    MMMDAqQqT1Q4Q//MMMrA   c                6    g | ]}t          j        |          S rD   )rH   r   r  s     r?   rG   zhistogramdd.<locals>.<listcomp>  s     ---1A---rA   r]   c              3     K   | ]}d V  dS r   rD   )rE   r  s     r?   r_   zhistogramdd.<locals>.<genexpr>  s"      ..q......rA   c                @    i | ]\  }\  }}|gR t           ||fS rD   )r  rE   r   r   r  rT  column_zerosr   ry   s       r?   r&  zhistogramdd.<locals>.<dictcomp>  sM     
 
 
6Aq 1$|$$'>4PQ&R
 
 
rA   c                x    g | ]6}t          t          |                                                             7S rD   )rx   r.   r  )rE   r   r  s     r?   rG   zhistogramdd.<locals>.<listcomp>  sF     
 
 
9:D00223344
 
 
rA   c                d    g | ]+t          fd t                    D                       ,S )c              3  4   K   | ]}|                  V  d S r]   rD   )rE   r   r   sample_keyss     r?   r_   z)histogramdd.<locals>.<listcomp>.<genexpr>  s,      77+a.#777777rA   )rg   _range)rE   r   Dr  s    @r?   rG   zhistogramdd.<locals>.<listcomp>  sM     
 
 
<=E77777VAYY77777
 
 
rA   c                P    i | ]"\  }\  }}|gR t           gg ||R R #S rD   )r  r  s       r?   r&  zhistogramdd.<locals>.<dictcomp>  sl     
 
 

 6Aq	 1$|$$+'%1%d%E%1%%' '
 
 
rA   ri  c              3  ,   K   | ]}|j         d z
  fV  dS rn   )r  r  s     r?   r_   zhistogramdd.<locals>.<genexpr>  s*      33qvzm333333rA   r   r   r   r^  c                ,    g | ]}t          |          S rD   r   )rE   entrys     r?   rG   zhistogramdd.<locals>.<listcomp>  s    111%wu~~111rA   )#r  r,   re   rx   rg   anyrf   r-   hasattrrQ   r   r   	numblocks	chunksizer  r   r   r/   r3  rp   r
  r   r.   r  r;   rH   r  r2  r1   rl  r   r+   r  reshaper   ) r  rT  ry   r  rB  r  dc_binsdc_rangerD  r  n_chunksrectangular_sampler   r  r  r  rs  r  r;   r  fused_on_chunk_keysr  	all_nbinsstacked_chunksr  r  width_dividerr   r  r  r   r  s    ```                         @@@@r?   r  r    s    P ~?G	DEEE !&&G$u&& HGS!F!F!F!F!FGG7<7H22E222333e   
( 
!Q
 
 	

 VT5'7;;E%e%%D vw 
v|!!STTT<DAq#A&!<v/333RSSS 4	FUDM	*	* 

"KK!9&q)1 	W 	WAay6!9#333 !UVVV 4	W Q
 
 	

 !$'5)9Iw;OP  $ 011 	6H6N6N 	BBH&RUBVBV    		'."3v}Q7G"G"GA   $ 	(9!(<(H(H'   $u&& t99>>U   u::??S   ....... 	MKLLL $ w{ 
,
,t
,
,
,,, .4P4P%4P4P4P1P1P .MMCe<L<LMMM----- yV}}..0011
8#r""1%+ ..F1II.....L   
f224455
 
 
 
 
 
 
&s;'?'?@@
 
 


 
 
 
>DS[[>Q>Q
 
 

 
 
 
 
AGAQAQ
 
 

 
 
 
 
 
 

 's+>'G'GHH
 
 
 +D#DIIIE33U33333IXo2	22N5$e<<<F 	


A 	2 (( 	> 	>AGAsOOE$*1-E!HRWU1X..66u===MMah???= 15577*E1111511111rA   c                   |"|t          |          k    rt          d          t          |           } | t          j        | t          j                  }n/t          |          }t          j        | |t          j                  }t          | d|          }|j        d         dk    rd}|r|j        d         }d}n|j        d         }d}||dk    rd}nd}t          ||z
            }	|	dk    rt          j
        dt                     d}	|$t          |d|          }t          ||f|          }||                    d|z
  d	          z
  }|s<t          |j        |                                          |	z                                  S t          ||j                                                  |	z                                  S )
Nzddof must be integerrN   )r>   r;   r   rM   z!Degrees of freedom <= 0 for sliceg        T)rb   r   )r
  r   r   rH   rI   float64r@   r   r0  warningswarnRuntimeWarningr   meanr   Tr   r   )
r   rY  rowvarbiasddofr;   XNrb   facts
             r?   covr    s   
 DCII--/000 	

Ayq"*--AJJq!RZ00aq&&&AwqzQ GAJGAJ |199DDDT??Dqyy9>JJJ}!1E***A%%	AFFD4F000A 5AC""T)22444Aqsxxzz""T)22444rA   c                    t          | ||          }|j        dk    r||z  S t          |          }|                    |j        d         df          }t	          |          }||z  |j        z  S )NrD   r   rM   )r  r   r   r  r%   r  )r=   rY  r  r   r   sqr_ds         r?   corrcoefr    si    Aq&Aw"}}1uQA			171:q/""AGGEI  rA   c                P    |                      t          j        || j                  S )N)decimalsr;   )r   rH   roundr;   )rF   r  s     r?   r  r  !  s      <<817<CCCrA   c                    | j         S r]   ro   rF   s    r?   r:   r:   '  s     6MrA   c                J    t          | j        j        t          j                  S r]   )r.  r;   r   rH   complexfloatingr   s    r?   iscomplexobjr  -  s     aglB$6777rA   c                   |du}|du}t          j        |           }d|j        fg}|r!|                    dt           j        f           |r!|                    dt           j        f           |r!|                    dt           j        f           t          j        |j        |          }||d<   |r0t          j        t          |          t           j                  |d<   |s|rt          |d                   D ]k\  }	}
| |
k    }|r.||         
                    d|d         |	|	dz            	           |r.||                             d|d         |	|	dz            	           l|S )
a  
    Helper/wrapper function for :func:`numpy.unique`.

    Uses :func:`numpy.unique` to find the unique values for the array chunk.
    Given this chunk may not represent the whole array, also take the
    ``indices`` and ``counts`` that are in 1-to-1 correspondence to ``ar``
    and reduce them in the same fashion as ``ar`` is reduced. Namely sum
    any counts that correspond to the same value and take the smallest
    index that corresponds to the same value.

    To handle the inverse mapping from the unique values to the original
    array, simply return a NumPy array created with ``arange`` with enough
    values to correspond 1-to-1 to the unique values. While there is more
    work needed to be done to create the full inverse mapping for the
    original array, this provides enough information to generate the
    inverse mapping in Dask.

    Given Dask likes to have one array returned from functions like
    ``blockwise``, some formatting is done to stuff all of the resulting arrays
    into one big NumPy structured array. Dask is then able to handle this
    object and can split it apart into the separate results on the Dask side,
    which then can be passed back to this function in concatenated chunks for
    further reduction or can be return to the user to perform other forms of
    analysis.

    By handling the problem in this way, it does not matter where a chunk
    is in a larger array or how big it is. The chunk can still be computed
    on the same way. Also it does not matter if the chunk is the result of
    other chunks being run through this function multiple times. The end
    result will still be just as accurate using this strategy.
    Nvaluesr    inverser  r   TrM   )r   r|   )rH   uniquer;   rP   intpr   r   r   rQ   r2  r  r   )arr    r  return_inversereturn_indexreturn_countsur   r   r   ra  r   s               r?   _unique_internalr  3  s   B $&L$&M
	"AQW
	B (
		9bg&''' (
		9bg&''' '
		8RW%&&&
###AAhK 8yQrw777) I} Iak** 	I 	IDAqaA K
!I,q1q5y2IJJJ Iq	t8QQY1GHHHHrA   c                Z   |dus|dus|durt          d          |                                 } | dg}t          |           }t          t          j        dg|R d|i}t          d |j        D                       |_        |g}d|j	        z   }|dft          j        ft          d |D                       z   i}	d	 |D             }
t          j        ||	|

          }t          j        ff}t          ||||          }|g}t          |          dk    r	|d         }nt          |          }|S )NFzdask.array.unique does not support `return_index`, `return_inverse` or `return_counts` with array types that don't support structured arrays.r   rE  c              3  P   K   | ]!}t           j        ft          |          z  V  "d S r]   rH   rL  rQ   rE   r   s     r?   r_   z+unique_no_structured_arr.<locals>.<genexpr>  1      ??q	CFF*??????rA   unique-aggregate-r   c              3  z   K   | ]6}t          |d           r t          j        |                                fn|V  7dS r  Nr  rH   r   r  rE   os     r?   r_   z+unique_no_structured_arr.<locals>.<genexpr>  `          1o..!2!233     rA   c                2    g | ]}t          |d           |S r  r  r  s     r?   rG   z,unique_no_structured_arr.<locals>.<listcomp>  '    HHH!GA,G,GHAHHHrA   ri  rE  rM   )r   r   r(   r   rH   r  rg   r   rM  r   r1   rl  rL  r   rQ   )r  r  r  r  rJ   rE  r|   	out_partsr   r  rj  r  r   r   s                 r?   unique_no_structured_arrr   p  s{    	E!!&&%%
 
 	
 
B9D2D
BIs
5T
5
5
5
5
5C??CJ?????CKI)D	q	YL   #	    
C IHyHHHL+D#LQQQEvi\F
tV$
/
/
/CUF
6{{avMrA   c                   	 t          |           }t          j        |dt          fdt          fg           n## t
          $ r t          | |||          cY S w xY w|                                 } | dg}d| j        fg}|ri|	                    t          | j        d         t          j        | j        d                   dg           |                    d	t          j        f           n|	                    d d g           |rj|	                    t          | j        d         ft          j        | j        d                   dg           |                    d
t          j        f           n|	                    d d g           t!          t"          dg|R |dd}t%          d |j        D                       |_        |d         g}|r|                    |d	                    n|                    d            |r|                    |d
                    n|                    d            d|j        z   }	|	dft"          ft%          d |D                       z   |fz   i}
d| j        fg}|r!|                    d	t          j        f           |r!|                    dt          j        f           |r!|                    d
t          j        f           d |D             }t+          j        |	|
|          }t          j        ff}t1          ||	||          }|d         g}|r|                    |d	                    |ro| d d d f         |d         d d d f         k                        t          j                  }|                    ||d         z                      d                     |r|                    |d
                    t7          |          dk    r	|d         }nt%          |          }|S )NrF   r   r   )r  r  r  r   r  r   r;   r   r    r  F)r;   r  c              3  P   K   | ]!}t           j        ft          |          z  V  "d S r]   r  r  s     r?   r_   zunique.<locals>.<genexpr>  r  rA   r  c              3  z   K   | ]6}t          |d           r t          j        |                                fn|V  7dS r  r  r  s     r?   r_   zunique.<locals>.<genexpr>  r  rA   r  c                2    g | ]}t          |d           |S r  r  r  s     r?   rG   zunique.<locals>.<listcomp>  r  rA   ri  rM   r   )r(   rH   
empty_liker
  r0  r  r   r   r;   rK  r   r   r  r   rP   r+   r   r  rg   rM  r   r1   rl  rL  r   r<   r   rQ   )r  r  r  r  rE  rJ   	out_dtyper|   r  r   r  rj  r  r   r   mtchess                   r?   r  r    sK   	
r""
dC:U|"<===== 
 
 
'%)'	
 
 
 	
 	
 	

 
B
 9DBH%&I "VBHQKrwry|LLLcRSSS)RW-....T4L!!! "T28A;.	!MMMsSTTT(BG,----T4L!!!
$c
XD
X
X	RW
X
X
XC??CJ?????CK XI Y(((( X'''')D	q	   #	      C BH%&I /)RW-... /)RW-... .(BG,---HHyHHHL+D#LQQQEvi\F
tVY
/
/C (m_F &c)n%%% = QQQW+XtQQQw!77??HHvI.333;;<<< %c(m$$$
6{{avMs   58 AAc                    t          j        |                                 ||          }|                    | j        d|j        z  z             S )N)assume_uniquer   )rH   in1dr   r  r   r:   )elementtest_elementsr
  r  s       r?   _isin_kernelr    sA    WW]]__m=QQQF>>'-$1C*CCDDDrA   isinc                t    t                      t          |          }t          t           j                            }t           fdt          |j                  D                       }t	          t
          ||z    |||d |D             t          |	  	        }|                    |          }|r| }|S )Nc              3  ,   K   | ]}|j         z   V  d S r]   ro   )rE   r   r  s     r?   r_   zisin.<locals>.<genexpr>  s*      JJ1a',&JJJJJJrA   c                    i | ]}|d  S )c                    dS r   rD   )r  s    r?   r   z!isin.<locals>.<dictcomp>.<lambda>'  s    q rA   rD   )rE   rb   s     r?   r&  zisin.<locals>.<dictcomp>'  s    ???Tt[[???rA   )r   r;   r
  r   )r   rg   ry   r:   r   r  boolr  )r  r  r
  invertelement_axes	test_axesr  r   s   `       r?   r  r    s    gGM**Mw|,,--LJJJJm6H0I0IJJJJJIy ??Y???#
 
 
F ZZYZ''F MrA   c                ^   | }|9t          |          }t          |t                    st          d          |f}d}nH	 t	          |           n# t          $ r |f}Y nw xY w	 t	          |           n# t          $ r |f}Y nw xY wt	          |          t	          |          k    rt          d          t          ||          D ]\  }}|j        |         }|dk    rdn| |z  }|j        t          d           gz  }|j        t          d           gz  }t          |d           ||<   t          d |          ||<   t          |          }t          |          }t          ||         ||         g|          }|                    | j                  }|| u r|                                n|}|S )NzAExpect `shift` to be an instance of Integral when `axis` is None.rG  z,Must have the same number of shifts as axes.r   r   )r   re   r   r  rQ   r   r   r   r:   r   rg   r   r  copy)	r@   shiftrb   r   r   sr   sl1sl2s	            r?   rollr  2  s   F|v%** 	S   	JJJJ 	 	 	HEEE		IIII 	 	 	7DDD	 5zzSYYGHHHD%   A A1Q!AA!ekU4[[M)kU4[[M)q$AtQACjjCjjfSk6#;7a@@@^^EK((F$ooV[[]]]6FMs#   A AA#A3 3BBc                    | j         S r]   r   )r@   s    r?   r   r   c  s
    ;rA   c                    t          t          |                                 |                                f                    S r]   )r  r   r   )ar1ar2s     r?   union1dr$  h  s-    +syy{{CIIKK899:::rA   c                F    t          |                               d          S )N)r   )r   r  )
array_likes    r?   r   r   m  s    j!!))%000rA   c                   t                    t          t          fvrft                    | j        z   }t          |          t          | j                  fdt          |          D             }| 	                    |          S )Nc                :    g | ]}|v rd nt                    S r   )next)rE   r   rb   shape_its     r?   rG   zexpand_dims.<locals>.<listcomp>{  s+    KKKR"**QQ$x..KKKrA   )
r   rg   rx   rQ   r:   r*   iterr   ry   r  )rF   rb   out_ndimr   r*  s    `  @r?   expand_dimsr-  r  s    Dzz%&&w4yy16!Hx((DAG}}HKKKKK5??KKKE99UrA   c                    ,t          d t           j                  D                       nt          t                     sft	           fdD                       rt          d          t           j                  t          fdt           j                  D                       }t          d |D                       rqt          d  j        D                       rS 	                    t          j         j        t          t          t           j                                                S  |           S )Nc              3  ,   K   | ]\  }}|d k    |V  dS rn   rD   )rE   r   r   s      r?   r_   zsqueeze.<locals>.<genexpr>  s*      @@41aaQ@@rA   c              3  :   K   | ]}j         |         d k    V  dS rn   r   )rE   r   rF   s     r?   r_   zsqueeze.<locals>.<genexpr>  s-      
)
)q171:?
)
)
)
)
)
)rA   z,cannot squeeze axis with size other than onec              3  H   K   | ]\  }}|v rd nt          d          V  dS r   r   )rE   r   r  rb   s      r?   r_   zsqueeze.<locals>.<genexpr>  s9      NN41aAIIqq5;;NNNNNNrA   c              3  "   K   | ]
}|d k    V  dS r   rD   rE   r  s     r?   r_   zsqueeze.<locals>.<genexpr>  s&      

a16





rA   c              3  "   K   | ]
}|d k    V  dS rn   rD   r4  s     r?   r_   zsqueeze.<locals>.<genexpr>  s&      &?&?!qAv&?&?&?&?&?&?rA   )rE  r   )rg   r2  r   re   r  r   r*   r:   rp   r   rH   r   r   ry   rQ   )rF   rb   r   s   `` r?   r   r     sK   |@@9QW#5#5@@@@@e$$ w

)
)
)
)D
)
)
))) IGHHHqv&&D	NNNN9QW;M;MNNN	N	NB 

2


 
3&?&?qw&?&?&?#?#? 
||JQWeCLL6I6I0J0J  
 
 	
 	
"AHrA   c                     t                     st          j                                         t                     t          |          } j        dk    rt          d          |                                }dt          |j                  |t           fdt          |j                  D                                }|t           fdt          |j                  D                                }|S )NrM   z!Condition must be one dimensionalr   c              3  |   K   | ]6}|k    rt          d t                              nt          d           V  7d S r]   )r   rQ   rE   r   rb   	conditions     r?   r_   zcompress.<locals>.<genexpr>  sZ       
 
 ,-99E$I'''%++
 
 
 
 
 
rA   c              3  F   K   | ]}|k    rnt          d           V  d S r]   r2  r8  s     r?   r_   zcompress.<locals>.<genexpr>  s5      OOAQ$YY		E$KKOOOOOOrA   )r5   rH   r   r<   r  r:   r   r   r*   rg   ry   )r9  rF   rb   s   ` `r?   compressr;    s   	"" * Jy))	  &&I

A~<===|GGIIqv&&D 	
 
 
 
 
 
16]]
 
 
 	
 	
	A 	
%OOOOOqvOOO
O
OPAHrA   c                    t          |                               t                    } t          |          }t          |                                 |                                          S r]   )r   r<   r  r;  r   )r9  r   s     r?   extractr=    sJ    	""))$//I
#,,CIOO%%syy{{333rA   c                    t          || j                  }t          | t          j                  r&t          |t
                    rt          | ||          S | t          d           f|z  |fz            S r]   )r*   r:   re   rH   r  r   _take_dask_array_from_numpyr   rF   r    rb   s      r?   takerA    si    qv&&D!RZ   5Z%?%? 5*1gt<<<%++$&'344rA   c                     t           t          j                  sJ t          |t                    sJ  |j         fd|j         j                  S )Nc                0    t          j        |           S r]   )rH   rA  )blockrF   rb   s    r?   r   z-_take_dask_array_from_numpy.<locals>.<lambda>  s    bga-- rA   r   r;   )re   rH   r  r   r   r   r;   r@  s   ` `r?   r?  r?    se    a$$$$$gu%%%%%7-----gnAG   rA   c                b    t          t          t          j        |          | | j                  S )N)r  r   )r   r   rH   aroundr;   )r=   r  s     r?   rG  rG    s(    gbi(;;;QagNNNNrA   c                X    dd l }t          j        |                    |                     S r   )pandasrH   r   isnullr  pds     r?   _asarray_isnullrM    s*    :bii''(((rA   c                8    ddl }t          t          | d          S )zpandas.isnull for dask arraysr   Nr  r   )rI  r   rM  rK  s     r?   rJ  rJ    s%     OV6::::rA   c                "    t          |            S )zpandas.notnull for dask arrays)rJ  )r  s    r?   notnullrP    s    6NN?rA   h㈵>:0yE>c                b    t          t          j        |||          }t          || |d          S )Nrtolatol	equal_nanr  r   )r   rH   iscloser   )arr1arr2rU  rV  rW  r  s         r?   rX  rX    s1    2:DtyIIIDD$F3333rA   c                N    t          | ||||                                          S )NrT  )rX  rp   )rY  rZ  rU  rV  rW  s        r?   allcloser\    s'    4DtyIIIMMOOOrA   c                ,    t          j        | |          S r]   )rH   chooserF   choicess     r?   variadic_choosera    s    9Q   rA   c                (    t          t          | g|R  S r]   )r   ra  r_  s     r?   r^  r^    s    OQ11111rA   c                D    t          t          j        |                     S r]   )r  rH   count_nonzero)ra  s    r?   _isnonzero_vecre    s     ##$$$rA   )otypesc                v   | j         j        dv r!|                     t          t                    S 	 t          j        t                      | j                                       t                     |                     t                    S # t          $ r$ |                     t          t                    cY S w xY w)N>   SUr   )
r;   kindr   re  r  rH   r   rg   r<   r   r  s    r?   	isnonzerork    s    w|z!! ||N$|777
(((//555 xx~~  8 8 8 ||N$|777778s   ?B
 
+B87B8c                \   t          |           } t          |                                           }t          | j        t
          j        | j                  j        dk    r7t          fdt          t                              D             d          t          |d          S )Nr  rM   c                D    g | ]}|                                          S rD   )r   rE   r   r{   s     r?   rG   zargwhere.<locals>.<listcomp>$  s%    ===SV\\^^===rA   r   r   )r   rk  r.   r    r   rH   r  r   r:   r   ry   rQ   r;  )rF   nzr{   s     @r?   argwhererp    s    

A	1				B
!'
:
:
:C
x!||====U3s88__===AFFF
2s
#
#
#CJrA   c                   |d u |d u k    rt          d          ||t          |           S t          j        |           rqt	          ||          }t          |          }t          |          }t          |j        |j                  }| r|n|}t          ||          	                    |          S t          t          j        | ||          S )Nz1either both or neither of x and y should be given)r   nonzerorH   r4  rI   r   r   r   r   r<   r   r`  )r9  r=   rY  r;   r   r|   s         r?   r`  r`  *  s    	T	qDy!!LMMM			y!!!	{9 
3Aq!!AJJAJJ !'22#aa!C''..u555)Q222rA   c                    t          t          |                                         t          j                                      |          S r  )rk  r   r<   rH   r  r   r  s     r?   rd  rd  >  s7    WQZZ  ''0044$4???rA   c                r    t          t          |                                                     d d df         S r   )rp  r   r   r  s    r?   flatnonzeroru  C  s/    GAJJ$$&&''1--rA   c                    t          |           j        dk    r3t          fdt          j        d                   D                       S fS )NrM   c              3  0   K   | ]}d d |f         V  d S r]   rD   rn  s     r?   r_   znonzero.<locals>.<genexpr>L  s/      <<1SAY<<<<<<rA   )rp  r:   rg   ry   r   )rF   r{   s    @r?   rr  rr  H  sQ    
1++C
x!||<<<<cil(;(;<<<<<<vrA   c                J    t          j        t          j        | fi |          S r]   )rH   r   unravel_index)r    func_kwargss     r?   _unravel_index_kernelr{  Q  s%    8B$W<<<<===rA   Cc                    |rS| j         rLt           | j        t          t          j        t          |          ff| j        z   d||d                    }nt          d |D                       }|S )Nr   )r   order)r;   r   r   rz  c              3  N   K   | ] }t          d t          j        d          V  !dS )rG  rM   r  N)r   rH   r  rE   r   s     r?   r_   z unravel_index.<locals>.<genexpr>b  s3      !V!V1%BGA"F"F"F!V!V!V!V!V!VrA   )r  rg   r   r{  rH   r  rQ   r   )r    r   r~  unraveled_indicess       r?   ry  ry  U  s     W W!G%ge**(7>9&+e<<  
 
 "!V!VPU!V!V!VVVrA   raisec           	        t          j        |          r|f}t          |          st          d |D                       rt	          d|          t          |           rt          |           }nt          |  }t          |          }t          j	        |j
                                                  s?t          |          t          |          k    rt          dt          |                     t          j        |j        t           j                  st!          d          |                    t           j        t           j        |j        dd          d|||          S )Nc              3  4   K   | ]}t          |          V  d S r]   r  )rE   r   s     r?   r_   z$ravel_multi_index.<locals>.<genexpr>k  s+      &K&K'9!'<'<&K&K&K&K&K&KrA   z5Dask types are not supported in the `dims` argument: z3parameter multi_index must be a sequence of length zonly int indices permittedrM   r   )r;   r   r   dimsmoder~  )rH   r4  r,   r  rf   r5   r   r   r   isnanr   rQ   r   
issubdtyper;   signedintegerr  r   ravel_multi_indexr  r   )multi_indexr  r  r~  index_stackmulti_index_arrss         r?   r  r  g  sj   	{4 w$ 
3&K&Kd&K&K&K#K#K 
!LDLL
 
 	
 K   .k**+[9,--8K%&&**,, 
[1A1ASYY1N1NM#d))MM
 
 	
 =*B,<== 64555!!
g!!""% "   rA   c                n    t          j        | t          |          |d         g|d         R i |d         S )Nfunclist	func_argsfunc_kw)rH   	piecewiserx   )r=   condlistr   s      r?   _int_piecewiser    sL    <	4>>6*-06{0C  GMiGX  rA   c           	     @    t          t          | g|R | j        d|||dS )Nr  )r;   r   r  r  r  )r   r  r;   )r=   r  r  rJ   kws        r?   r  r    sF    		 
	 	 g	 	 	 	rA   c                 t    t          |           dz  }| d|         }| |d         }t          j        ||fi |S )z
    This is a version of :func:`numpy.select` that acceptes an arbitrary number of arguments and
    splits them in half to create ``condlist`` and ``choicelist`` params.
    rN   N)rQ   rH   select)rJ   r   split_atr  
choicelists        r?   _selectr    sG    
 4yyA~HIXIHhiiJ9Xz44V444rA   c                   t          |           t          |          k    rt          d          t          |           dk    rt          d          d |D             }	 t          | }n$# t          $ r}d}t          |          |d }~ww xY wt	          t          |d         j                            fd| D             }fd|D             }t          t          g||R |d|d	S )
Nz7list of cases must be same length as list of conditionsr   z3select with an empty condition list is not possiblec                ,    g | ]}t          |          S rD   r  )rE   choices     r?   rG   zselect.<locals>.<listcomp>  s    ;;;f'&//;;;rA   z/Choicelist elements do not have a common dtype.c                "    g | ]}|fD ]}|S rD   rD   rE   elemargblockwise_shapes      r?   rG   zselect.<locals>.<listcomp>  s+    LLLT?4KLLSLLLLrA   c                "    g | ]}|fD ]}|S rD   rD   r  s      r?   rG   zselect.<locals>.<listcomp>  s+    PPP$8OPP#PPPPrA   r  )r;   r   default)	rQ   r   rI   r  rg   ry   r:   r   r  )	r  r  r  intermediate_dtyper   msgcondargs
choiceargsr  s	           @r?   r  r    s9    8}}J''RSSS
8}}NOOO;;
;;;J$(*5 $ $ $?nn!#$ E*Q-"45566OLLLLLLLHPPPP*PPPJ 
 
	 
 !   s    	A* *
B4BBtotalr
  divisorreturn'tuple[tuple[int, ...], tuple[int, ...]]c                6    |f| |z  z  }| |z  r| |z  fnd}||fS )a>  Given a total and a divisor, return two tuples: A tuple containing `divisor`
    repeated the number of times it divides `total`, and length-1 or empty tuple
    containing the remainder when `total` is divided by `divisor`. If `divisor` factors
    `total`, i.e. if the remainder is 0, then `remainder` is empty.
    rD   rD   )r  r  	multiples	remainders       r?   
_partitionr    s:     
ew./I&+go=""2IirA   r   	list[int]multipletuple[int, ...]c                b   t          j        |           |z  }|                                }t          j        |           |z
  }|| k    }t          j        |          d         t          j        |           d         }}g |t          j        ||                            |t          j        ||                            }t          ||          \  }	}
t          |	          D ]\  }}|||         xx         |z  cc<   t          j        g ||
          }||dk             }t          |          S )a  
    Returns a new chunking aligned with the coarsening multiple.
    Any excess is at the end of the array.

    Examples
    --------
    >>> aligned_coarsen_chunks(chunks=(1, 2, 3), multiple=4)
    (4, 2)
    >>> aligned_coarsen_chunks(chunks=(1, 20, 3, 4), multiple=4)
    (4, 20, 4)
    >>> aligned_coarsen_chunks(chunks=(20, 10, 15, 23, 24), multiple=10)
    (20, 10, 20, 20, 20, 2)
    r   )rH   r@   r   r`  argsortr  r2  rg   )r   r  overflowexcess
new_chunkschunk_validity
valid_indsinvalid_indschunk_modification_orderpartitioned_excessr  idxextras                r?   aligned_coarsen_chunksr    s=    x(*H\\^^F&!!H,J6)N!x77:BHn_<U<UVW<XJ 	bjL!9::	; 	BJz*566	7  %/vx$@$@!	   233 ; ;
U+C0111U:11113J3344JJN+JrA   c                r    sJt          fd                                D                       sd dj         d}t          |           j                            d          rt          t           j                   i }                                D ]6\  }}t          j
        |         |          }	|	j
        |         k    r|	||<   7|r                    |          dt                     z    fdt                                                    D             }
fdt          fd	t!          j
                  D                       }  t          j        d
j        z  j                  fi }t)          j        |
g          }t-          |||          S )Nc              3  F   K   | ]\  }}j         |         |z  d k    V  dS r   r   )rE   r   divr=   s      r?   r_   zcoarsen.<locals>.<genexpr>  s7      "T"TVQ171:#3q#8"T"T"T"T"T"TrA   zCoarsening factors z do not align with array shape r   zdask.zcoarsen-c           	     \    i | ](}f|d d         z   t           t          j        |gf)S rn   )r2   r   coarsen)rE   r   r   r   r   r#   trim_excesss     r?   r&  zcoarsen.<locals>.<dictcomp>	  sT         

abb'	5=9c4*MvV  rA   c                P    t          |                     |d          z            S r   )r
  r,  )dimr   r   s     r?   r   zcoarsen.<locals>.<lambda>	  s     #cTXXb!__&<"="= rA   c              3  X   K   | ]#\  }t          fd |D                       V  $dS )c              3  P   K   | ] } |          d k     |          V  !dS r   rD   )rE   bdcoarsen_dimr   s     r?   r_   z$coarsen.<locals>.<genexpr>.<genexpr>	  sE      IIR++b!2D2Dq2H2Hkk"a  2H2H2H2HIIrA   N)rg   )rE   bdsr   r  s     @r?   r_   zcoarsen.<locals>.<genexpr>	  s\        As 	IIIII3IIIII     rA   r   r   ri  r  )rp   itemsr   r   
__module__
startswithr   rH   __name__r  r   r   r-   r.   r  rg   r2  r   r:   r;   r1   rl  r   )r#   r=   r   r  r   r  r  r   r  alignedr  r   rE  r  r  r   s   `````         @@r?   r  r    s    s"T"T"T"Ttzz||"T"T"TTT SDSSSSSoo&&w// 4B	 233	J**,, $ $3(!c::ahqk!!#JqM "IIj!!At[AAAD        1??,,--  C >===K    ))    F
 9RXdQVm17;;;FFvFFD+D#QCHHHEf40000rA   c                     t          dg|dgg          }d t          d|          D             }t          d          f|z   fd|D             }|S )zSplit an array into a list of arrays (using slices) at the given breaks

    >>> split_at_breaks(np.arange(6), [3, 5])
    [array([0, 1, 2]), array([3, 4]), array([5])]
    Nc                4    g | ]\  }}t          ||          S rD   r2  )rE   r   r   s      r?   rG   z#split_at_breaks.<locals>.<listcomp>#	  s$    GGGdaeAqkkGGGrA   rN   c                (    g | ]}|fz            S rD   rD   )rE   r  r@   preslices     r?   rG   z#split_at_breaks.<locals>.<listcomp>%	  s$    :::a5QD):::rA   )r
   r   r   )r@   breaksrb   padded_breaksslicessplit_arrayr  s   `     @r?   split_at_breaksr  	  so     TFFTF344MGGnQ&F&FGGGFd~$H:::::6:::KrA   c           	     J   t          | j                  t          t                    r,t	          j                            | j                            t	          j                  j        dk    }|rt	          j	                  t	          j
        dk     | j                 z             t	          j                  dk                                     rt          d          t          | t	          j                            }t!          |dd          dk    rdt#          |          z   }t!          |dt%          |                    }t'          |f|i|d|          }t)          fdt+          | j                  D                       }t-          ||          }n|r|t          d           fz  d	z            }t)          fd
t+          t/          | j        |j                            D                       }	|                    |	          }t	          j                  d d         }
t	          j        |
|
dk                       }t          ||          }t9          t;          ||g                    }d |D             }t=          |          S )Nr   z9da.insert only implemented for monotonic ``obj`` argumentr:   zvalues-r;   rD   rE  c              3  L   K   | ]\  }}|k    rt                    n|V  d S r]   r  )rE   r  r  rb   objs      r?   r_   zinsert.<locals>.<genexpr>D	  sJ       
 
-1Q		CHHHq
 
 
 
 
 
rA   r]   c              3  8   K   | ]\  }\  }}|k    r|n|V  d S r]   rD   )rE   r  arr_bd	values_bdrb   s       r?   r_   zinsert.<locals>.<genexpr>K	  sL        "A"	 QYY		F     rA   r   c                     g | ]}|j         	|S rD   )nbytesr  s     r?   rG   zinsert.<locals>.<listcomp>V	  s    666QX61666rA   r   )r*   r:   re   r   rH   r   r    r   r   rZ   r`  r  r  rf   r  r  r   r-   r   r   rg   r2  r   r   r   r   rJ  r5  rx   r   r   )r   r  r  rb   
scalar_obj	split_arrr   r;   values_shapevalues_chunksr  values_breakssplit_valuesinterleaveds    ` `          r?   r   r   )	  s    sx((D#u 7iSYt_556
*S//CQJ !mC  
(37C#)D/13
7
7C
q 
!G
 
 	
  RYs^^T::Ivvq!!Q&&8F+++f66($rGGG 
 
 
 
 
5>sy5I5I
 
 
 
 
 fl33	 9t-78    &/CJ0N0N&O&O    M ^^M**F[crc"FIfVaZ011M"6=$??Lz9l";<<==K66k666K{....rA   c                
   t          | j                  t          |t                    rLt	          j        |                    | j                            }|j        r|j        dk     r|ddd         n|}nPt	          j	        |          }t	          j
        |dk     || j                 z   |          }t	          j        |          }t          | |          }fdt          |          D             }t          |          S )zf
    NOTE: If ``obj`` is a dask array it is implicitly computed when this function
    is called.
    r   Nr   c           	         g | ]@\  }}|d k    r3|t          fdt          |j                  D                                n|AS )r   c              3  b   K   | ])}|k    rt          d d          nt          d          V  *dS rn   r2  )rE   r  rb   s     r?   r_   z$delete.<locals>.<listcomp>.<genexpr>p	  s=      XX1DAII%4...5;;XXXXXXrA   )rg   ry   r:   )rE   r   r   rb   s      r?   rG   zdelete.<locals>.<listcomp>n	  sq        As 66 	XXXXchXXXXX	
 	
   rA   r   )r*   r:   re   r   rH   r   r    r   stepr   r`  r  r  r2  r   )r   r  rb   tmp
target_arrs     `  r?   deleter  Z	  s     sx((D#u iSYt_5568=1c$$B$ii#joohsQwcio 5s;;inn c400J     
++  J z----rA   c                    t          |           } |E| j        dk    r|                                 } t          t          |                    }| j        dz
  }t          | |f|          S )NrM   r   )r   r:   r   r   )r   r  rb   s      r?   rP   rP   y	  sc     S//C|8q==))++Cz&))**x!|V}40000rA   c                   t          |           } |@|                     ||          }|j                            | j        |j        z            }nmt          |          }t          | j        j        t          j        t          j        f          rt          | j        |j        d          }	nt          | j        |j                  }	| j
        |j
        k    r|t          d          |j        dk    rt          d          |j
        d         | j
        |         k    rt          d          t          || j        dz
  dz  |j
        z             }|                    d	|          }|rdd
lm}
 | |
|            z  }|                    ||	|          }t'          | ||	                              ||          |z  }|r;|j
        |j
        k    r't          ||j
                                                  }||fS |S )N)r   f8z;Axis must be specified when shapes of a and weights differ.rM   z81D weights expected when shapes of a and weights differ.r   z5Length of weights not compatible with specified axis.r   r   )getmaskarray)rb   r;   r   r   )r   r  r;   r   r  r.  rH   integerr/  rI   r   r  r:   r   r   rz   dask.array.mar  r   r$   r  )rF   rb   rB  returned	is_maskedr   avgsclwgtresult_dtyper  s              r?   _averager  	  s    	1AffTHf--innQVch.//!!aglRZ$:;; 	;&qw	4@@LL&qw	::L 7ci|Q   x1}}N   y|qwt},, K  
 sQVaZ4$7#)$CDDC,,r4((C 	+222222,,q//)*Cgg4|hgGGq#\22266th6OORUU 9	!!sCI..3355CCx
rA   c                ,    t          | |||d|          S )NF)r  r   )r  )rF   rb   rB  r  r   s        r?   averager  	  s    AtWh%(SSSSrA   c           	         t          | |           } t          | j        dd          |t          | j        dd          t          |           d}t          || t          j        | d                    S )Nr7   r   r   r;   r   r8   r   r   	r'   r!   r   r  r   r(   r`  rH   r>  r   r   masks      r?   trilr  	  sv    QQA	

x}Q  D q"-666777rA   c           	         t          | |           } t          | j        dd          |dz
  t          | j        dd          t          |           d}t          |t          j        | d          |           S )Nr7   r   rM   r  r   r   r  r  s      r?   triur	  	  sz    QQA	

a%x}Q  D r}Qd333Q777rA   autoc           	     N    t          t          | ||t          |                    S )Nr   r;   r   rr  r!   r  r  r   r   r   s       r?   tril_indicesr  	  s#    3q!qV<<<===rA   c                    | j         dk    rt          d          t          | j        d         || j        d         | j                  S NrN   zinput array must be 2-dr   r   )r   r   r   )r:   r   r  r   r   r   r   s     r?   tril_indices_fromr  	  A    
x1}}2333	"cimCJOOOOrA   c           	     V    t          t          | ||dz
  t          |                     S )NrM   r  r  r  s       r?   triu_indicesr  	  s*    C1AT&AAAABBBrA   c                    | j         dk    rt          d          t          | j        d         || j        d         | j                  S r  )r:   r   r  r   r   r  s     r?   triu_indices_fromr  	  r  rA   rW   )Fr]   )rM   r   r|  rL   )rM   r   NN)Nr   N)r\  N)rf  )NNFNN)r  NNNN)NNNN)NrM   r   Nr   rG  )FFF)FF)rQ  rR  F)r|  )r  r|  )r  r
  r  r
  r  r  )r   r  r  r
  r  r  )NNFFF)NNFF)r   Nr
  )
__future__r   r*  r  collections.abcr   	functoolsr   r   r   numbersr   r	   numpyrH   tlzr
   r   r   
dask.arrayr   dask.array.corer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dask.array.creationr   r   r   r    r!   dask.array.einsumfuncsr"   rN  r#   dask.array.ufuncr$   r%   dask.array.utilsr&   r'   r(   r)   r*   dask.array.wrapr+   	dask.baser,   r-   	dask.corer.   dask.delayedr/   r0   dask.highlevelgraphr1   
dask.utilsr2   r3   r4   r5   r6   ry   r  r@   rI   rU   rX   rZ   rj   rq   rt   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r   r  r@  rJ  rU  r[  rX  rv  rz  ry  r  r  r  r  r  r  r  round_r:   r  r  r   r  r  r   r  r  r   r$  r   r-  r   r;  r=  rA  r?  rG  rM  rJ  rP  rX  r\  ra  r^  re  	vectorizer  rk  rp  r`  rd  ru  rr  r{  ry  r  r  r  r  r  r  r  r  r  r   r  rP   r  r  r  r	  r  r  r  r  rD   rA   r?   <module>r-     s   " " " " " "   $ $ $ $ $ $ , , , , , , , , , , " " " " " " " "     2 2 2 2 2 2 2 2 2 2                                       " B A A A A A A A A A A A A A ) ) ) ) ) ) + + + + + + + + + + + + + +              !           2 2 2 2 2 2 2 2       4 4 4 4 4 4 4 4 . . . . . . P P P P P P P P P P P P P P 
 bT      b! ! !
 b  & b  " b   bW W W W b
 
 
 
  bW W W W bX X X b	 	 	 	! ! ! !H b   b   b6 6 6 6<     b40 40 40 40n b5'"""@ @ #"@ b, , ,$ $ $ $(	 	 	 	% % %, b; ; ;| bB B BX X X b59 - - - - -` b  6 b/ / / / b- - - -` b      ( b# J J J J JZ   b) ) ) )X bJ J J J   b% % % %RE E E EN N N N} } } }@G& G& G& G&TK K K P P P,S2 S2 S2 S2l
 b,5 ,5 ,5 ,5^ b! ! ! ! BHbi  bD D D  ! D BGb    BOb8 8  8: : : :| AF5 5 5 5p bi i i iXE E E E
 GGB%%&&   '&. b- - - -` b   b; ; ; b1 1 1 b
 
 
 b   2 b   < b4 4 4 b5 5 5 5   bO O O O) ) ); ; ;  
 b4 4 4 4
 bP P P P! ! ! b2 2 2% % % ndV<<<  , b
 
 
 b3 3 3 3& b@ @ @ @ b. . . b  > > > b   " r   >   b
 
 
5 5 5 b   B       # # # #L u}1 1 1 1D
 
 
 
 b-/ -/ -/` b. . .< b1 1 1 1 KP2 2 2 2j bT T T T b
8 
8 
8 
8 b
8 
8 
8 
8 b> > > > bP P P P bC C C C bP P P P P PrA   