
    Cdt                    *   d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlZd dlmZ d dlmZ d d	lmZ d d
lmZmZmZmZmZmZmZmZmZ d dlmZmZ d dl m!Z! d dl"m#Z#m$Z$m%Z%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z,m-Z-m.Z. d;d<dZ/d=dZ0d=dZ1d=dZ2d>dZ3d Z4	 d?d Z5 ej6        d!          dddd"d#            Z7 e-e          dd$d%d&            Z8e9dfd'Z:ddd e;fd(Z< e-e          d@d)            Z= e-e          dAd+            Z> e-e          dd e;dfdd,d-            Z? e-e          dBd.            Z@ e-e          d;d/            ZA e-e          d0             ZBd1 ZCd2 ZDd3 ZEd4 ZFd5 ZGd6 ZHd7 ZId8 ZJ e-e          dCd:            ZKdS )D    )annotationsN)Sequence)partial)product)IntegralNumber)sliding_window)chunk)array_creation_dispatch)	Arrayasarrayblock	blockwisebroadcast_arraysbroadcast_toconcatenatenormalize_chunksstack)greater_equalrint)meta_from_array)emptyfulloneszeros)tokenize)HighLevelGraph)cached_cumsumderived_fromis_cupy_typexr   backend
str | Nonec                b    |pt           j        }t          j        |          } |j        | fi |S )a  Move an Array collection to a new backend

    Parameters
    ----------
    x : Array
        The input Array collection.
    backend : str, Optional
        The name of the new backend to move to. The default
        is the current "array.backend" configuration.

    Returns
    -------
    dask.Array
        A new Array collection with the backend specified
        by ``backend``.
    )r   r"   dispatch
to_backend)r!   r"   kwargsbackend_entrypoints       3lib/python3.11/site-packages/dask/array/creation.pyr&   r&   !   s?    $ 808G09'BB((55f555    Cc                D   t          | d          } t          | ||          \  }}t          j        |                                          r5|                     t          t          j        |p| j                            S t          ||p| j        |||| j
                  S )a  
    Return a new array with the same shape and type as a given array.

    Parameters
    ----------
    a : array_like
        The shape and data-type of `a` define these same attributes of the
        returned array.
    dtype : data-type, optional
        Overrides the data type of the result.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    chunks : sequence of ints
        The number of samples on each block. Note that the last block will have
        fewer samples if ``len(array) % chunks != 0``.
    name : str, optional
        An optional keyname for the array. Defaults to hashing the input
        keyword arguments.
    shape : int or sequence of ints, optional.
        Overrides the shape of the result.

    Returns
    -------
    out : ndarray
        Array of uninitialized (arbitrary) data with the same
        shape and type as `a`.

    See Also
    --------
    ones_like : Return an array of ones with shape and type of input.
    zeros_like : Return an array of zeros with shape and type of input.
    empty : Return a new uninitialized array.
    ones : Return a new array setting values to one.
    zeros : Return a new array setting values to zero.

    Notes
    -----
    This function does *not* initialize the returned array; to do that use
    `zeros_like` or `ones_like` instead.  It may be marginally faster than
    the functions that do set the array values.
    Fnamedtyper0   orderchunksr.   meta)r    _get_like_function_shapes_chunksnpisnanany
map_blocksr   
empty_liker0   r   _metaar0   r2   r3   r.   shapes         r)   r:   r:   :   s    X 	A4QFFME6 
x N||GBM%:J17LLLMMMW   r*   c                D   t          | d          } t          | ||          \  }}t          j        |                                          r5|                     t          t          j        |p| j                            S t          ||p| j        |||| j
                  S )a  
    Return an array of ones with the same shape and type as a given array.

    Parameters
    ----------
    a : array_like
        The shape and data-type of `a` define these same attributes of
        the returned array.
    dtype : data-type, optional
        Overrides the data type of the result.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    chunks : sequence of ints
        The number of samples on each block. Note that the last block will have
        fewer samples if ``len(array) % chunks != 0``.
    name : str, optional
        An optional keyname for the array. Defaults to hashing the input
        keyword arguments.
    shape : int or sequence of ints, optional.
        Overrides the shape of the result.

    Returns
    -------
    out : ndarray
        Array of ones with the same shape and type as `a`.

    See Also
    --------
    zeros_like : Return an array of zeros with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    zeros : Return a new array setting values to zero.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    Fr-   r/   r1   )r   r5   r6   r7   r8   r9   r   	ones_liker0   r   r;   r<   s         r)   r@   r@   x   s    J 	A4QFFME6 
x M||GBL9I!'KKKLLLW   r*   c                D   t          | d          } t          | ||          \  }}t          j        |                                          r5|                     t          t          j        |p| j                            S t          ||p| j        |||| j
                  S )a  
    Return an array of zeros with the same shape and type as a given array.

    Parameters
    ----------
    a : array_like
        The shape and data-type of `a` define these same attributes of
        the returned array.
    dtype : data-type, optional
        Overrides the data type of the result.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    chunks : sequence of ints
        The number of samples on each block. Note that the last block will have
        fewer samples if ``len(array) % chunks != 0``.
    name : str, optional
        An optional keyname for the array. Defaults to hashing the input
        keyword arguments.
    shape : int or sequence of ints, optional.
        Overrides the shape of the result.

    Returns
    -------
    out : ndarray
        Array of zeros with the same shape and type as `a`.

    See Also
    --------
    ones_like : Return an array of ones with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    zeros : Return a new array setting values to zero.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    Fr-   r/   r1   )r   r5   r6   r7   r8   r9   r   
zeros_liker0   r   r;   r<   s         r)   rB   rB      s    J 	A4QFFME6 
x N||GBM%:J17LLLMMMW   r*   c           	     H   t          | d          } t          | ||          \  }}t          j        |                                          r6|                     t          t          j        |p| j                  |          S t          |||p| j        |||| j
                  S )a  
    Return a full array with the same shape and type as a given array.

    Parameters
    ----------
    a : array_like
        The shape and data-type of `a` define these same attributes of
        the returned array.
    fill_value : scalar
        Fill value.
    dtype : data-type, optional
        Overrides the data type of the result.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    chunks : sequence of ints
        The number of samples on each block. Note that the last block will have
        fewer samples if ``len(array) % chunks != 0``.
    name : str, optional
        An optional keyname for the array. Defaults to hashing the input
        keyword arguments.
    shape : int or sequence of ints, optional.
        Overrides the shape of the result.

    Returns
    -------
    out : ndarray
        Array of `fill_value` with the same shape and type as `a`.

    See Also
    --------
    zeros_like : Return an array of zeros with shape and type of input.
    ones_like : Return an array of ones with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    zeros : Return a new array setting values to zero.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    full : Fill a new array.
    Fr-   r/   r1   )r   r5   r6   r7   r8   r9   r   	full_liker0   r   r;   )r=   
fill_valuer2   r0   r3   r.   r>   s          r)   rD   rD      s    R 	A4QFFME6 
x Y||GBL9I!'KKKZXXXW   r*   c                8    || j         }|| j        }n|d}||fS )zb
    Helper function for finding shapes and chunks for *_like()
    array creation functions.
    Nauto)r>   r3   )r=   r3   r>   s      r)   r5   r5   "  s1    
 }>XF	&=r*   2   TFrG   c           	        t          |          }|t          j        ddd          j        }t	          ||f|          }|| z
  }|r|dz
  n|}|dk    rd}t          |          |z  }	dt          | |||||f          z   }
i }| }t          |d                   D ]E\  }}|r|dz
  n|}|||	z  z   }t          t          j        ||          |||f}||	|z  z   }|||
|f<   F|rt          ||
||          |	fS t          ||
||          S )a-  
    Return `num` evenly spaced values over the closed interval [`start`,
    `stop`].

    Parameters
    ----------
    start : scalar
        The starting value of the sequence.
    stop : scalar
        The last value of the sequence.
    num : int, optional
        Number of samples to include in the returned dask array, including the
        endpoints. Default is 50.
    endpoint : bool, optional
        If True, ``stop`` is the last sample. Otherwise, it is not included.
        Default is True.
    retstep : bool, optional
        If True, return (samples, step), where step is the spacing between
        samples. Default is False.
    chunks :  int
        The number of samples on each block. Note that the last block will have
        fewer samples if `num % blocksize != 0`
    dtype : dtype, optional
        The type of the output array.

    Returns
    -------
    samples : dask array
    step : float, optional
        Only returned if ``retstep`` is True. Size of spacing between samples.


    See Also
    --------
    dask.array.arange
    Nr      r/   z	linspace-)endpointr0   )intr6   linspacer0   r   floatr   	enumerater   r
   r   )startstopnumrK   retstepr3   r0   range_divstepr.   dsk
blockstartibsbs_space	blockstoptasks                     r)   rM   rM   0  s`   N c((C}Aq!$$*fsfE:::FE\F
(377SC
axx==3D5$Xvu"MNNND
CJ6!9%% 
 
2%-2662(T/2	ENXUCCC	
  4"9-
T1I 5S$e444d::S$e4444r*   numpy)r3   liker0   c                d   t          |          dk    rd}|d         }d}nOt          |          dk    r|d         }|d         }d}n)t          |          dk    r|\  }}}nt          d          t          t          t	          j        ||z
  |z            d                    }|t          |          nd}	|"t	          j        |||r||z  n|          j        }t          | |f|          } |r7t          dd	
                    |                                          z            d
t          |||| |f          z   }
i }d}t          | d                   D ]E\  }}|||z  z   }|||z   |z  z   }t          t          j        |          |||||f}|||
|f<   ||z  }Ft!          ||
| ||	          S )a  
    Return evenly spaced values from `start` to `stop` with step size `step`.

    The values are half-open [start, stop), so including start and excluding
    stop. This is basically the same as python's range function but for dask
    arrays.

    When using a non-integer step, such as 0.1, the results will often not be
    consistent. It is better to use linspace for these cases.

    Parameters
    ----------
    start : int, optional
        The starting value of the sequence. The default is 0.
    stop : int
        The end of the interval, this value is excluded from the interval.
    step : int, optional
        The spacing between the values. The default is 1 when not specified.
        The last value of the sequence.
    chunks :  int
        The number of samples on each block. Note that the last block will have
        fewer samples if ``len(array) % chunks != 0``.
        Defaults to "auto" which will automatically determine chunk sizes.
    dtype : numpy.dtype
        Output dtype. Omit to infer it from start, stop, step
        Defaults to ``None``.
    like : array type or ``None``
        Array to extract meta from. Defaults to ``None``.

    Returns
    -------
    samples : dask array

    See Also
    --------
    dask.array.linspace
    rJ   r         zT
        arange takes 3 positional arguments: arange([start], stop, [step])
        Nr/   z"Unexpected keyword argument(s): %s,zarange-r_   )r0   r4   )len	TypeErrorrL   maxr6   ceilr   aranger0   r   joinkeysr   rO   r   r
   r   )r3   r_   r0   argsr'   rP   rQ   rV   rR   r4   r.   rW   
elem_countrY   rZ   rX   r\   r]   s                     r)   ri   ri   }  s   N 4yyA~~Aw	TaQAw	Ta tTT
 
 	
 c"'4%<4/00!44
5
5C$($4?4   $D}	%S'BtczzdCCIfsfE:::F X<sxx?V?VVWWWxdFE BCCCD
CJ6!9%%  2j4/0
j2o56	ELt,,,
 T1Ib

dF%d;;;;r*   xy)sparseindexingc                   t          |           } d|v rt          d          |rt          d          |dvrt          d          d |D             }d |D             }|dk    r*t	          |          d	k    r|d	         |d
         c|d
<   |d	<   g }t          t	          |                    D ]Y}t	          |          d gz  }t          d           ||<   t          |          }||         |         }|                    |           Z| s	t          | }|dk    r*t	          |          d	k    r|d	         |d
         c|d
<   |d	<   |S )Ncopyz`copy` not supportedz(unsupported keyword argument(s) provided)ijrn   z#`indexing` must be `'ij'` or `'xy'`c                ,    g | ]}t          |          S  )r   .0es     r)   
<listcomp>zmeshgrid.<locals>.<listcomp>  s    	!	!	!'!**	!	!	!r*   c                6    g | ]}|                                 S ru   )flattenrv   s     r)   ry   zmeshgrid.<locals>.<listcomp>  s     	"	"	"!!))++	"	"	"r*   rn   rJ   r   )
boolNotImplementedErrorrf   
ValueErrorre   rangeslicetupleappendr   )ro   rp   xir'   gridrY   srs           r)   meshgridr     si   &\\F!"8999 DBCCC|##>???	!	!b	!	!	!B	"	"r	"	"	"B4CGGaKK!ube1r!uD3r77^^  GGtfT{{!!HHqE!HA '&4CGGaKK7DGQaKr*   c           	        t          |           } t          j        |          }t          || |          }t	          |           t	          |          k    rt          d          g }t          t	          |                     D ]4}|                    t          | |         |||         f                     5g }t          |           rt          |ddi}|rt          |          }n&t          t	          |           f| z   |d|z             }|S )a  
    Implements NumPy's ``indices`` for Dask Arrays.

    Generates a grid of indices covering the dimensions provided.

    The final array has the shape ``(len(dimensions), *dimensions)``. The
    chunks are used to specify the chunking for axis 1 up to
    ``len(dimensions)``. The 0th axis always has chunks of length 1.

    Parameters
    ----------
    dimensions : sequence of ints
        The shape of the index grid.
    dtype : dtype, optional
        Type to use for the array. Default is ``int``.
    chunks : sequence of ints, str
        The size of each block.  Must be one of the following forms:

        - A blocksize like (500, 1000)
        - A size in bytes, like "100 MiB" which will choose a uniform
          block-like shape
        - The word "auto" which acts like the above, but uses a configuration
          value ``array.chunk-size`` for the chunk size

        Note that the last block will have fewer samples if ``len(array) % chunks != 0``.

    Returns
    -------
    grid : dask array
    r>   r0   z)Need same number of chunks as dimensions.r0   r3   rp   rs   rJ   )r   r6   r0   r   re   r~   r   r   ri   allr   r   r   )
dimensionsr0   r3   r   rY   r   s         r)   indicesr     s   > z""JHUOOEfJeDDDF
:#f++%%DEEE	B3z??## K K
		&AeVAYLIIIJJJJD
: ,+d++ YT{{c*oo'*4E$QW-XXXKr*   c                   i }|| }|t           }t          |t          t          f          st	          d          t          || |f|          \  }}|d         }t          | ||||          }d|z   }	t          |          D ]t\  }
}t          |          D ]_\  }}||
z
  dz
  |z  |cxk    r||
z
  dz   |z  k    r$n n!t          j	        |||||
z
  |z  z
  |f||	|
|f<   Ht          j
        ||f|f||	|
|f<   `ut          ||	| |f||f|          S )a  
    Return a 2-D Array with ones on the diagonal and zeros elsewhere.

    Parameters
    ----------
    N : int
      Number of rows in the output.
    chunks : int, str
        How to chunk the array. Must be one of the following forms:

        -   A blocksize like 1000.
        -   A size in bytes, like "100 MiB" which will choose a uniform
            block-like shape
        -   The word "auto" which acts like the above, but uses a configuration
            value ``array.chunk-size`` for the chunk size
    M : int, optional
      Number of columns in the output. If None, defaults to `N`.
    k : int, optional
      Index of the diagonal: 0 (the default) refers to the main diagonal,
      a positive value refers to an upper diagonal, and a negative value
      to a lower diagonal.
    dtype : data-type, optional
      Data-type of the returned array.

    Returns
    -------
    I : Array of shape (N,M)
      An array where all elements are equal to zero, except for the `k`-th
      diagonal, whose values are equal to one.
    Nzchunks must be an int or stringr   r   zeye-rJ   )r>   r3   r0   )rN   
isinstancerL   strr~   r   r   rO   r6   eyer   r   )Nr3   Mkr0   r   vchunkshchunkstokenname_eyerY   vchunkjhchunks                 r)   r   r   2  s}   > Cy}fsCj)) <:;;;'q!fEJJJGWQZFQ1e,,E~Hw'' J J	6"7++ 
	J 
	JIAvA	V#q@@@@QUQY&,@@@@@@FQ&(('HaN## (*x&&1A5&IHaN##
	J hq!fff5EUSSSSr*   c                   t          | t          j                  s4t          | t                    st	          dt          |                      dt          | |          z   t          | | j        dk    rdnd          }t          | t          j                  s%t          | d          rt          | t                    s| j        dk    rFt          |          }| j        d         |z   f| j        d         |z   ff}ddft          j        | |fi}ny| j        dk    r_t          d|           }t          | j        d         | j        d         |z
            }||z
  }|dk    rdn|ff}dft          j        | |fi}nt          d          t          |||	          S | j        dk    r| j        dk    rt          d          |dk    r| j        d         | j        d         k    rdfd
t#          |                                           D             }t'          j        || g          }	t          |	| j        d         f|	          S t+          | |          S |dk    r| j        d         }
|                                 }i }t#          |
          D ]r\  }}t#          |
          D ]]\  }}||f}||k    rt          j        ||         f||<   (t          j        ||ff||<   t/          t          j        ||f          |f||<   ^st'          j        || g          }	t          |	|
|
f|	          S |dk    r%t3          t          |           d|g|dggd          S |dk     r't3          t          |           | dgd| ggd          S d S )Nz+v must be a dask array or numpy array, got zdiag-rJ   ra   __array_function__r   r   zArray must be 1d or 2d onlyr4   c                D    i | ]\  }}|ft           j        ||         fS ru   )r6   diag)rw   rY   rowr.   s      r)   
<dictcomp>zdiag.<locals>.<dictcomp>  s;       17Cq	BGSV,  r*   dependencies)r>   constant)mode)r   r6   ndarrayr   rf   typer   r   ndimhasattrabsr>   r   rg   minr~   r3   rO   __dask_keys__r   from_collectionsdiagonalr   r   rB   pad)vr   r4   mr3   rW   kdiag_row_startkdiag_row_stop	len_kdiaggraph	chunks_1dblocksrY   r   nkeyr.   s                   @r)   r   r   o  s   a$$ QZ5-A-A QOd1ggOOPPPXa^^#D116Q;;aaA66D!RZ   3'((31;Au1E1E3 6Q;;AAwqzA~'!'!*q.):;F!Q<"'1a1CCVq[[!!aRjjO QWQZ!^<<N&8I )QWWi\OF!9rw1o.CC:;;;S$T2222v{{6Q;;:;;;66ahqkQXa[00   ;DQ__EVEV;W;W  C #3D#QCPPPEqx{n4@@@@Aq>>!AvvHQK	""i(( 	L 	LDAq!),, L L1Ql66 "3CHH "1a&1CH 'aV D D DdKCHHL /cLLLUD9i"8tDDDD	
Q477aVaV,:>>>>	
Q477qb!Wq1"g.Z@@@@ 
r*   rJ   c                4	   '( dt           |||          z   } j        dk     rt          d          d }d } ||d j                  } ||d j                  }||k    rt          d          t                      |}||k    r||}}| }t	          t           j                            ||hz
  }t          t           fd	|D                        }	t          |          }
t          d
|           }t          d
|          }t           j        |          j        |         |z
            }||z
  }|d
k    rt          }t           j                  rd
d l}|} | j        ||          dz   (t#                      }|	D ]U't%          '(fdt          |
          D                       }t'          |j         j                  |dz   f||f'z   dz   <   Vt-           |
dz             }t/          ||(|          S t          j         j        |                   }t          j        |d          }d
|d
<   t          j         j        |                   }t          j        |d          }d
|d
<   t          j         j        |                   }t          j         j        |                   }||k    ||k     z  }||k    ||k     z  }||         \  }||         \  }t#                      }d
}d}| j        |         k     rF| j        |         k     r4 j        |         |          j        |         |         }!} |||         z  }|||         z  }|d
k    r| n|}t          | |!|z
            }"|"|z
  }#|	D ]W''d |         |fz   '||dz
           z   |fz   '|dz
  d          z   }$'|fz   }%t          j         j        f|$z   |||f||f|%z   <   X||#fz  }|dz  }|"||         z   }t          |!| |z             ||         z   }|||         k    r|dz   n|}|||         k    r|dz   n|}| j        |         k     r| j        |         k     4 | j        ||          |fz   (t=          j        || g          }&t-           |
dz             }t/          |&|(|          S )Nz	diagonal-ra   z1diag requires an array of at least two dimensionsc                    | dk     r8|| z   }|dk     r+d}t          j        |                    || |                    |} | S )Nr   z6{}: axis {} is out of bounds for array of dimension {})r6   	AxisErrorformat)axisr.   r   tmsgs        r)   	_axis_fmtzdiagonal.<locals>._axis_fmt  sL    !88tA1uuNl3::dD$#?#?@@@Dr*   c                    t          |           } |                     |           |                     |           t          |           S N)listpopr   )r3   axis1axis2s      r)   pop_axeszdiagonal.<locals>.pop_axes  s=    f

5

5V}}r*   r   r   z"axis1 and axis2 cannot be the samec              3  L   K   | ]}t          j        |                   V  d S r   )r   	numblocks)rw   rY   r=   s     r)   	<genexpr>zdiagonal.<locals>.<genexpr>  s1      !K!KA%A"7"7!K!K!K!K!K!Kr*   r   r   c              3  @   K   | ]}|         |                  V  d S r   ru   )rw   r   free_idx
out_chunkss     r)   r   zdiagonal.<locals>.<genexpr>  sB        59
4 $0     r*   r/   r   rJ   r   ru   r   ) r   r   r~   r   setr   r   r   re   rg   r   r>   r6   r    r;   cupyr3   dictr   r   r   r0   r   r   cumsumrollri   r   r   r.   r   r   ))r=   offsetr   r   r.   r   r   r   	free_axesfree_indices
ndims_freer   kdiag_col_startr   r   xpr   rW   r>   r4   
row_stops_
row_starts
col_stops_
col_startsrow_blockidcol_blockid
row_filter
col_filterIJrY   kdiag_chunksnrowsncolskdiag_row_end	kdiag_len	input_idx
output_idxr   r   r   s)   `                                      @@r)   r   r     st   !VUE:::DvzzLMMM     IeWaf--EIeWaf--E~~=>>>

AAu}}euGE!&MM""eU^3I!K!K!K!K!K!K!KLMMLYJ !aRjjO!QiiO!);<<N0IA~~   	KKKBXahu55?
ff$ 	 	H     =B:=N=N    E 000.C("T)**
 q*q.11S$
6666 18E?++JQ''JJqM 18E?++JQ''JJqM )AK.//K)AK.//K/Oj4PQJ/Oj4PQJz"DQz"DQ &&C	AL
AGEN
*
*/O/Oxq)18E?1+=u:a=(:a=( /! 3 3_E519--!O3	 % 	 	H% $5519,-. $ 519;;'	(  "QDJ	I%)C*$%% 	$	Q'*Q-7eUQY//*Q-?$
155AEE1$
155AEE1C AGEN
*
*/O/OF !(E511\OCJ+D#QCHHHE1j1n--Djt4444r*   rd   c                  t           j        j        j        }|| }t	          || |f|          }t          t          | |d         d          |d|           |                              d|           j        t          | ||z
  |d         d          || ||z
            |                    }|	                    |d          }|S )Nr   r   )r3   r0   r_   rJ   F)rr   )
r6   libtwodim_base_min_intr   r   ri   reshapeTastype)r   r   r   r0   r3   r_   r   r   s           r)   trir   .  s    v!*HyfQF%@@@Fq1XXa^^$GGGOOPQSTUUWr1q51XXqb!a%5H5HtTTT	 	A 	
U##AHr*   c                f   pt           t          ||          }t          t          t	          |                              }fdt          ||          D             }t          |ddi}t          t          |t          j	        |                    d          }t          | |g|R ddi|}|S )Nr/   c                :    g | ]\  }}t          ||           S )r   )ri   )rw   r   cr0   s      r)   ry   z fromfunction.<locals>.<listcomp>I  s,    LLLAF1E!,,,LLLr*   rp   rs   ru   r   fromfunction)rN   r   r   r   re   zipr   sum	itertoolsrepeatr   )	funcr3   r>   r0   r'   indsarrsrl   ress	      `     r)   r   r   B  s    NUEfe5999Fs5zz""##DLLLLUF9K9KLLLDT)D))Ds4)$//00"55D
D$
F
F
F
F^
Fv
F
FCJr*   c                     j         dk    rdnt          d          t          |t                    st          d           j          cxk    rdk     rn n j         z  n)dcxk    r j         dz
  k    sn t	          dz            |dk    r3 t          fdt           j                   D                                S |dk    r S t           j                 d          }g }t          d	|          D ]m\  }}t          j        |||                              d          }t          d	|          D ].\  }}	||	k    r#|                    t          ||	                     /nt          d d d            fd
|D             } fd|D             }
g }|
D ]}t          |j                  }t!          |                   dk    sJ |         d         |z  f|<   t          |          }|                    t          j        |||j                  }|                    |           t)          |          S )NrJ   r   z!Must supply an integer axis valuez%Only integer valued repeats supportedzaxis(=%d) out of boundsc              3  `   K   | ](}|k    rt          d           nt          d          V  )d S )Nr   )r   )rw   dr   s     r)   r   zrepeat.<locals>.<genexpr>d  s;      UU!a4iiuT{{{U1XXUUUUUUr*   T)initial_zerora   c                H    g | ]}fz  |fz   fj         z
  d z
  z  z   S r   )r   )rw   r   r=   	all_slicer   s     r)   ry   zrepeat.<locals>.<listcomp>q  sK       LMtqd"i\QVd]Q5F%GG  r*   c                     g | ]
}|         S ru   ru   )rw   slcr=   s     r)   ry   zrepeat.<locals>.<listcomp>u  s    &&&QsV&&&r*   )r   r3   r0   r   )r   r}   r   r   r~   r   r   r   r3   r	   r6   rM   roundr   r   r   re   r9   r   r0   r   )r=   repeatsr   cchunksslicesc_startc_stoplsls_startls_stopslabsoutslabr3   resultr  s   ` `            @r)   r   r   S  s   |6Q;;DD%&IJJJgx(( K!"IJJJ	w$$$$$$!&1*$$$$2T9:::!||UUUUuQV}}UUUUUVV	AAHTN>>>GF)!W55 8 8[&'2288;;!/2!6!6 	8 	8Hg7""eHg66777	8 dD$''I     QW  F '&&&v&&&E
C  dk""6$<  A%%%%tQ'13tvIwT&
 ! 
 
 	

6s&&&&r*   c                :   	 t          |          }n# t          $ r |f}Y nw xY wt          d |D                       rt          d          t	          |           }t          |          r#|d d d         D ]}||gz  }	t          |          S t          |          }||j        k     rd|j        |z
  z  |z   }|j        |k     rd||j        z
  z  |j	        z   }n|j	        }t          d t          ||          D                       }t          ||j                  S )Nc              3  "   K   | ]
}|d k     V  dS )r   Nru   rw   rY   s     r)   r   ztile.<locals>.<genexpr>  s&      

Q1q5





r*   z Negative `reps` are not allowed.r   c              3  &   K   | ]\  }}||z  V  d S r   ru   )rw   r   r   s      r)   r   ztile.<locals>.<genexpr>  s*      881a!e888888r*   r   )r   rf   r8   r~   r   r   r   re   r   r>   r   r   r0   )Arepstupr   nrepr  r>   	shape_outs           r)   tiler#    sA   Dkk   g


#


 =;<<<

A
3xx "I 	 	Ds
AAQxxCA16zzafqj!C'vzzAF
#ag-88E388888Iy0000s    ""c                \   t          |t                    st          |dd           dk    r| j        ||ffz  }nt          |t                    rGt          d |D                       r.t          |          dk    r| j        |d         |d         ffz  }nt          |t                    rFt          |          dk    r3t          d |D                       r| j        t          |          fz  }n;t          |t                    r}t          |          | j        k    ret          d |D                       rLt          d |D                       r3t          d	 |D                       rt          d
 |D                       }nt          |t                    rt          |          dk    rrt          |d         t                    rWt          |d                   dk    r>t          d |d         D                       r| j        t          |d                   fz  }nt          d          |S )Nr   r   c              3  @   K   | ]}t          |t                    V  d S r   r   r   rw   pws     r)   r   z#expand_pad_value.<locals>.<genexpr>  ,      ;;2
2v&&;;;;;;r*   rJ   ra   c              3  @   K   | ]}t          |t                    V  d S r   r&  r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  r)  r*   c              3  @   K   | ]}t          |t                    V  d S r   )r   r   r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  s,      ==R
2x((======r*   c              3  <   K   | ]}t          |          d k    V  dS ra   N)re   r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  s,      332RA333333r*   c              3  H   K   | ]}t          d  |D                       V  dS )c              3  @   K   | ]}t          |t                    V  d S r   r&  )rw   ws     r)   r   z-expand_pad_value.<locals>.<genexpr>.<genexpr>  s,      66aJq&))666666r*   N)r   r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  s9      KK266266666KKKKKKr*   c              3  4   K   | ]}t          |          V  d S r   r   r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  s(      88%))888888r*   c              3  @   K   | ]}t          |t                    V  d S r   r&  r'  s     r)   r   z#expand_pad_value.<locals>.<genexpr>  s,      >>2
2v&&>>>>>>r*   z6`pad_value` must be composed of integral typed values.)	r   r   getattrr   r   r   re   r   rf   )array	pad_values     r)   expand_pad_valuer7    sP   )V$$ R	64(H(HA(M(MJ9i"8!::		9h''R;;;;;;;R 	NNaJ9Q<1">!@@		9h''R	NNa;;;;;;;   J%	"2"2!44		9h''R	NNej((==9===== )3333333 ) KKKKKKK )
 88i88888		9h''	R	NNay|X..  	!"">>1>>>>> # J%	!"5"5!77		PQQQr*   c                f   t          | j                  t          | j                  g}t          | j                  t          | j                  g}|D ]C}t          d          D ]1}||         |         ||         |<   ||         |         f||         |<   2Dd |D             }d |D             }||fS )zD
    Helper function for finding shapes and chunks of end pads.
    ra   c                ,    g | ]}t          |          S ru   r2  )rw   r   s     r)   ry   z)get_pad_shapes_chunks.<locals>.<listcomp>      ///q%((///r*   c                ,    g | ]}t          |          S ru   r2  )rw   r   s     r)   ry   z)get_pad_shapes_chunks.<locals>.<listcomp>  r:  r*   )r   r>   r3   r   )r5  	pad_widthaxes
pad_shapes
pad_chunksr  rY   s          r)   get_pad_shapes_chunksr@    s    
 u{##T%+%6%67Ju|$$d5<&8&89J 2 2q 	2 	2A(|AJqM! )!Q1JqM!	2 0/J///J//J///Jz!!r*   c                   |dz   }t          | j                  }|||<   t          |          }t          j        | j                  }t          j        | ||          }t          j        | j                  D ]d}	t          |	          }
t          d          |
|<   t          |
          }
t          j        | |	         |||          dd         dd|         ||
<   e|S )z>
    Helper function to find the linear ramp for a chunk.
    rJ   r   Nr/   )	r   r>   r   r6   r0   r:   ndindexr   rM   )rP   rQ   rR   dimrV   num1r>   r0   r  rY   r   s              r)   linear_ramp_chunkrE    s     7DEE#J%LLEHU[!!E]5U;;;FZ$$ O OGGt#!HHKa$EBBB122FvvvNq		Mr*   c           
        
  fd|                                 D             } t           j                  D ]t          |f          \  }}g}|dk    rAddlm
 |d                  } 
fd|D             }d t          |||          D             }n|dv rj        t          d	          gz  j        t          d	          gz  g}t          d	d
d	          |d         <   t          dd	d	          |d
         <   d |D             }fd|D             }|dk    rd t          |||          D             }ni|dk    r@|d                  }	fdt          t          ||	|         |                    D             }n"|dk    r fdt          ||          D             }t          |d         |d
         g          S )zu
    Helper function for padding edges.

    Handles the cases where the only the values on the edge are needed.
    c                8    i | ]\  }}|t          |          S ru   )r7  )rw   r   r   r5  s      r)   r   zpad_edge.<locals>.<dictcomp>  s*    GGG1a!%++GGGr*   r   r   )asarray_safeconstant_valuesc                P    g | ]"} |t                    j                   #S ))r_   r0   )r   r0   )rw   r   r5  rH  r  s     r)   ry   zpad_edge.<locals>.<listcomp>   sD        Q_U%;%;6<PPP  r*   c                8    g | ]\  }}}t          |||          S ru   r   )rw   r   r   r   s       r)   ry   zpad_edge.<locals>.<listcomp>  s:       Aq! Q1%%  r*   )edgelinear_rampNrJ   r  c                ,    g | ]}t          |          S ru   r2  )rw   sls     r)   ry   zpad_edge.<locals>.<listcomp>  s    999%))999r*   c                     g | ]
}|         S ru   ru   )rw   rP  r  s     r)   ry   zpad_edge.<locals>.<listcomp>  s    :::&*:::r*   rM  c                8    g | ]\  }}}t          |||          S ru   rL  )rw   r=   r   r   s       r)   ry   zpad_edge.<locals>.<listcomp>  s:       1a !Aq))  r*   rN  
end_valuesc                x    g | ]6\  }\  }}}}|                     t          |||j        d |z  dz
            7S )ra   rJ   )r3   r0   rC  rV   )r9   rE  r0   )rw   rY   r=   evr(  r   r  r  s         r)   ry   zpad_edge.<locals>.<listcomp>  si        *>Ar2q LL) $l!eai !    r*   r   c                F    g | ]\  }}t          |j        |           S ))r>   r0   r3   )r:   r0   )rw   r   r   r5  s      r)   ry   zpad_edge.<locals>.<listcomp>(  s@       Aq 5QGGG  r*   r  )
itemsr   r   r@  dask.array.utilsrH  r   r   rO   r   )r5  r<  r   r'   r>  r?  
pad_arraysrI  
pad_slicesrS  rH  r  r  s   `         @@@r)   pad_edger[    s    HGGGGGGFF5: 5M 5M!6vy1$!O!O
Jf%
:555555$%67:O     (  O
 "?J
KK  JJ ,,, +t5v{eDkk]7RSJ$T1d33JqM!$Rt44JqM!99j999J::::z:::Jv~~ #&z:z#J#J  

 &&#L1!4
     .7J
IaL*MM. .  
 W__   
J77  J
 jmVZ]C!LLLMr*   c           	        |dv r@|                     dd          }|dk    rt          d          |dk    rt          d          t          j        | j        dz  t                    }t          j        |j                  D ]}g }g }t          || j        |          D ]_\  }	}
}|d	k    r|d
d
d         }|	dk     r_|dk    r.|
                    t          d|d         dz   d
                     n|
                    t          d
|d         d
                     n|	dk    rh|dk    r4|
                    t          |
|d         z
  dz
  |
dz
  d
                     nP|
                    t          |
|d         z
  d
d
                     n"|
                    t          d
                     |	dk    r*|dv r&|
                    t          d
d
d                     =|
                    t          d
                     at          |          }t          |          }|d	k    rt          d |D                       }| |         |         ||<   t          |                                          }|S )z
    Helper function for padding boundaries with values in the array.

    Handles the cases where the padding is constructed from values in
    the array. Namely by reflecting them or tiling them to create periodic
    boundary constraints.
    >   reflect	symmetricr]  evenoddz/`pad` does not support `reflect_type` of `odd`.zBunsupported value for reflect_type, must be one of (`even`, `odd`)rb   r/   wrapNr  rJ   r   )r]  r^  c              3      K   | ]	}d |z
  V  
dS r-  ru   r  s     r)   r   zpad_reuse.<locals>.<genexpr>b  s&      ++!A++++++r*   )getr}   r~   r6   r   r   objectrB  r>   r   r   r   r   r   tolist)r5  r<  r   r'   reflect_typer  idxselectorientrY   r   r(  s               r)   	pad_reuserk  2  s{    '''zz)V445  %&WXXX6!!T   Xej4'v666Fz&,'' , ,Ci88 	+ 	+HAq"v~~"X1uu9$$MM%2a519d";";<<<<MM%beT":":;;;;Q9$$MM%BqE	Aq1ud"C"CDDDDMM%BqE	4">">????eDkk***Avv$":::eD$334444eDkk****vv6>>++s+++++CFmF+s6==??##FMr*   c           
     6   |dk    rt          d          t          | |          }t          j        | j        dz  t
                    }t          j        |j                  D ]}g }g }g }g }	t          t          || j        | j
        ||                    D ]T\  }
\  }}}}}|dk     rv|                    |
           |                    t          d|d         d                     |                    |d                    |	                    |d                    |dk    rz|                    |
           |                    t          ||d         z
  dd                     |                    |d                    |	                    |d                    |                    t          d                     |                    |           |	                    |           Vt          |          }t          |          }t          |          }t          |	          }	| |         }|r|dk    r|                    |d	
          }n;|dk    r|                    |d	
          }n|dk    r|                    |d	
          }t#          |||	          }|dk    rMt          j        | j        t          j                  rt+          |          }|                    | j                  }|||<   t/          |                                          }|S )a6  
    Helper function for padding boundaries with statistics from the array.

    In cases where the padding requires computations of statistics from part
    or all of the array, this function helps compute those statistics as
    requested and then adds those statistics onto the boundaries of the array.
    medianz*`pad` does not support `mode` of `median`.ra  r/   rJ   Nr   maximumT)r   keepdimsmeanminimum)r3   )r}   r7  r6   r   r   re  rB  r>   rO   r   r3   r   r   r   rg   rp  r   r   
issubdtyper0   integerr   r   r   rf  )r5  r<  r   stat_lengthr  rh  r=  ri  	pad_shaper?  r  rY   r   r   r0  l
result_idxs                    r)   	pad_statsrx  k  s    x!"NOOO"5+66KXej4'v666Fz&,'' ,! ,!	
"+U[%,	;GG#
 #
 	% 	%A1aA 1uuAeD!A$55666  1&&&!!!A$''''QAeA!HdD99:::  1&&&!!!A$''''eDkk***  ###!!!$$$$T{{v)$$	:&&
6]
 	<y  '^^^EE

'__$_FF

""'^^^EE
%j)JOOOJv~~=bj99 2!%j!1!1J'..u{;;
 s6==??##FMr*   c                   t          j        |           }t          j        | j        d |         | j        |dz   d          z             D ]?}|d |         t	          d           fz   ||d          z   } || |         |||          ||<   @|S )NrJ   )r6   r:   rB  r>   r   )r5  pad_funciaxis_pad_widthiaxispad_func_kwargsr  rY   s          r)   wrapped_pad_funcr~    s    ]5!!FZFUF+ek%!)++.FFGG P PfufIt&5662HU1XOOq		Mr*   c           
     h   t          | |dd          }|j        }t          |j                  D ]}|                    |d|         |j        ||dz            fz   ||dz   d         z             }|                    t          d|j        |||         ||          }|                    |          }|S )a9  
    Helper function for padding boundaries with a user defined function.

    In cases where the padding requires a custom user defined function be
    applied to the array, this function assists in the prepping and
    application of this function to the Dask Array to construct the desired
    boundaries.
    r   r   )rI  NrJ   r   )r.   r0   rz  r{  r|  r}  )	r[  r3   r   r   rechunkr>   r9   r~  r0   )r5  r<  r   r'   r  r3   r  s          r)   pad_udfr    s     eY
AFFFF]F6; ( (2A2J&,q1q5y133fQUWWoE
 
 "",%aL" # 
 
 ''Mr*   r   c                6   t          |           } t          | |          }t          |          rt          | ||fi |S g g g dgdgdgdgdgdgdgdgd}	 t	          |          t	          ||                   z
  }n&# t
          $ r}t          d| d          |d }~ww xY w|r#t          d                    ||                    |d	v rD|                    dt          d
 | j
        D                                 }t          | |||          S |dk    r%|                    dd           t          | ||fi |S |dk    r%|                    dd           t          | ||fi |S |dv rt          | ||          S |dv rt          | ||fi |S t          d          )NrI  rS  rt  rg  )r   rM  rb  r   rN  rn  rp  rm  rq  r]  r^  zmode 'z' is not supportedz/unsupported keyword arguments for mode '{}': {}>   rp  rm  rn  rq  c              3     K   | ]}||fV  	d S r   ru   )rw   r   s     r)   r   zpad.<locals>.<genexpr>  s&      5R5Rq!f5R5R5R5R5R5Rr*   r   r   rN  >   rM  r   )r]  r^  rb  unreachable)r   r7  callabler  r   KeyErrorr~   r   rd  r   r>   rx  
setdefaultr[  rk  RuntimeError)r5  r<  r   r'   allowed_kwargsunsupported_kwargsrx   rt  s           r)   r   r     s6   ENNE 	22I~~ 9ui88888 &'$~!? /!?"#$% NC [[3~d/C+D+DD C C C:$:::;;BC 
=DD( 
 
 	
 777jj5R5Rek5R5R5R0R0RSS	4===			+Q///y$99&999			,***y$99&999	"	"	"y$///	1	1	1	4::6:::
}
%
%%s   %A; ;
BBBr   )r!   r   r"   r#   )Nr+   NNN)r+   NNNN)rH   TFrG   Nr   )r   r   rJ   )rG   NN)r   )L
__future__r   r   collections.abcr   	functoolsr   r   numbersr   r   r^   r6   tlzr	   
dask.arrayr
   dask.array.backendsr   dask.array.corer   r   r   r   r   r   r   r   r   dask.array.ufuncr   r   rX  r   dask.array.wrapr   r   r   r   	dask.baser   dask.highlevelgraphr   
dask.utilsr   r   r    r&   r:   r@   rB   rD   r5   rM   register_inplaceri   r   rL   r   rN   r   r   r   r   r   r   r#  r7  r@  rE  r[  rk  rx  r~  r  r   ru   r*   r)   <module>r     s   " " " " " "     $ $ $ $ $ $             $ $ $ $ $ $ $ $                 7 7 7 7 7 7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 1 0 0 0 0 0 0 0 , , , , , , 4 4 4 4 4 4 4 4 4 4 4 4       . . . . . . @ @ @ @ @ @ @ @ @ @6 6 6 6 62; ; ; ;|4 4 4 4n4 4 4 4n9 9 9 9x   MQJ5 J5 J5 J5Z *)'22d$ U< U< U< U< 32U<p b " " " " "J "& 3 3 3 3l DAU :T :T :T :Tz b8A 8A 8A 8Av b5 5 5 5D bQeF D     & b     b.' .' .' .'b b1 1 12" " "J" " "&  .A A AH6 6 6r? ? ?D    B b/& /& /& /& /& /&r*   