a
    S/b                 
   @  s&  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZ d dlmZmZmZmZmZmZmZ d dlmZmZmZ d dlmZmZ d dlmZmZ d dlmZm Z  d d	l!m"Z" d d
l#m$Z$ d dl%Z&d dl'm(Z( d dl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m>Z? ddl>m@Z@ ddlAmBZB ddl5mCZC ddlDmEZEmDZD ddlFmGZGmHZH ddlImJZJmKZK ddlLmLZL ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZa ddlbmcZc ddl2mdZd ddldmeZe ddlfmgZgmhZh ddlimjZjmkZkmlZl dd lmmnZnmoZo dd!lpmqZqmrZrmsZs e4td"d#d$d%i d&ZuG d'd( d(evZwdd*d+Zxdd,d-Zydd.d/Zzdd0l{m|Z|m}Z} i Z~d1d2 Zd3d4d5d6Zd7d8 Zd9d: Zexd;d)dd;fd<d4d=d>Zdd?d@Zg fdAdBZddDdEZdFdG ZdHdI Zddddg dddJdKdLZdMdN ZddOdPdQd3d3dRdSdTZdUdV ZdWdX ZdY ZG dZd[ d[e8Zd\d] Zdd^d_Zd`d`dadbdcZddddeZdfdg Zdhdi ZddkdlZddmdnZddodpZdqdr ZddsdtZdddui fdvdwZdxdy Zdzd{ Zd|d} Zdd~dZdddZdd Zdd Zdd Zd)dd;d;ddddddd3d3ddddZdddddddZdddddZddd;dddZdd Zdd Zdd)dddddZdd Zdd Zdd Zdd Zdd ZdddZeTe&d;dddZdd Zdd Zdd Zdd ZdddZdddZdd Zdd Zd)dÜddńZddǄ ZddɄ Zdd˄ Zdd̈́ Zddτ Zddф Zddӄ ZddՄ ZdddׄZdddڄZddd܄ZG ddބ dރZddl>m>Z> ddlMmZmZ dS )    )annotationsNbisect)
CollectionHashableIterableIteratorMappingMutableMappingSequence)partialreducewraps)productzip_longest)IntegralNumber)addmul)Lock)Any)
get_mapper)
accumulateconcatfirstfrequenciesgroupby	partition)pluck   )computeconfigcorethreaded)DaskMethodsMixincompute_as_if_collectiondont_optimizeis_dask_collectionpersisttokenize)	blockwise)broadcast_dimensions)globalmethod)quoteDelayeddelayed)HighLevelGraphMaterializedLayer)ArraySliceDepreshapelist)sizeof)IndexCallableMSerializableLockcached_cumsumcached_propertyconcretederived_fromfactorsformat_bytesfuncnamehas_keywordis_arraylikeis_dataframe_likeis_index_like
is_integeris_series_likendeepmapndimlistparse_bytestypename)get_template   )chunk)getitem)is_valid_array_chunkis_valid_chunk_type)concatenate_lookupeinsum_lookuptensordot_lookup)
_numpy_120	_Recurser)replace_ellipsissetitem_arrayslice_arrayarrayZ128MiB   )z
chunk-sizezrechunk-thresholdz

A possible solution: https://docs.dask.org/en/latest/array-chunks.html#unknown-chunks
Summary: to compute chunks sizes, use

   x.compute_chunk_sizes()  # for Dask Array `x`
   ddf.to_dask_array(lengths=True)  # for Dask DataFrame `ddf`c                   @  s   e Zd ZdZdS )PerformanceWarningz<A warning given when bad chunking may cause poor performanceN)__name__
__module____qualname____doc__ r_   r_   .lib/python3.9/site-packages/dask/array/core.pyrZ   `   s   rZ   Tc                 C  s   t |trTtdd |D rTtdd |D }tdd |D }t| |||d| S |r`|  z:| | }|rt|rt |tjrt|}W |r|	  n|r|	  0 |S )Nc                 s  s   | ]}|d u V  qd S Nr_   .0xr_   r_   r`   	<genexpr>e       zgetter.<locals>.<genexpr>c                 s  s   | ]}|d ur|V  qd S ra   r_   rb   r_   r_   r`   re   f   rf   c                 s  s.   | ]&}t |ts|d u rd ntd d V  qd S ra   )
isinstancer   slicerb   r_   r_   r`   re   g   s   
asarraylock)
rg   tupleanygetteracquirerA   npZmatrixrj   release)abrj   rk   b2Zb3cr_   r_   r`   rn   d   s"    

rn   c                 C  s   t | |||dS )zA simple wrapper around ``getter``.

    Used to indicate to the optimization passes that the backend doesn't
    support fancy indexing.
    ri   rn   rr   rs   rj   rk   r_   r_   r`   getter_nofancy~   s    rx   c                 C  s   t | |||dS )a  A getter function that optimizations feel comfortable inlining

    Slicing operations with this function may be inlined into a graph, such as
    in the following rewrite

    **Before**

    >>> a = x[:10]  # doctest: +SKIP
    >>> b = a + 1  # doctest: +SKIP
    >>> c = a * 2  # doctest: +SKIP

    **After**

    >>> b = x[:10] + 1  # doctest: +SKIP
    >>> c = x[:10] * 2  # doctest: +SKIP

    This inlining can be relevant to operations when running off of disk.
    ri   rv   rw   r_   r_   r`   getter_inline   s    ry   )
fuse_sliceoptimizec                    s    fdd}|S )a  Register an __array_function__ implementation for dask.array.Array

    Register that a function implements the API of a NumPy function (or several
    NumPy functions in case of aliases) which is handled with
    ``__array_function__``.

    Parameters
    ----------
    \*numpy_functions : callables
        One or more NumPy functions that are handled by ``__array_function__``
        and will be mapped by `implements` to a `dask.array` function.
    c                   s    D ]}| t |< q| S ra   )_HANDLED_FUNCTIONS)Z	dask_funcZnumpy_functionnumpy_functionsr_   r`   	decorator   s    
zimplements.<locals>.decoratorr_   )r~   r   r_   r}   r`   
implements   s    r   boolreturnc                 C  sB   t | dr| jdu rdS t | dr>t| s>t| jtjur>dS dS )zCheck whether Dask should delegate to the other.
    This implementation follows NEP-13:
    https://numpy.org/neps/nep-0013-ufunc-overrides.html#behavior-in-combination-with-python-s-binary-operations
    __array_ufunc__NTF)hasattrr   rN   typeArray)otherr_   r_   r`   _should_delegate   s    r   c                   s   t   fdd}|S )zCheck if method is handled by Dask given type of other

    Ensures proper deferral to upcast types in dunder operations without
    assuming unknown types are automatically downcast types.
    c                   s   t |rtS  | |S d S ra   )r   NotImplementedselfr   fr_   r`   wrapper   s    z-check_if_handled_given_other.<locals>.wrapper)r   )r   r   r_   r   r`   check_if_handled_given_other   s    r   c                 C  s.   dd | D }dd t || D }tt| S )a  Translate chunks tuple to a set of slices in product order

    >>> slices_from_chunks(((2, 2), (3, 3, 3)))  # doctest: +NORMALIZE_WHITESPACE
     [(slice(0, 2, None), slice(0, 3, None)),
      (slice(0, 2, None), slice(3, 6, None)),
      (slice(0, 2, None), slice(6, 9, None)),
      (slice(2, 4, None), slice(0, 3, None)),
      (slice(2, 4, None), slice(3, 6, None)),
      (slice(2, 4, None), slice(6, 9, None))]
    c                 S  s   g | ]}t |d dqS TZinitial_zeror9   rc   bdsr_   r_   r`   
<listcomp>   rf   z&slices_from_chunks.<locals>.<listcomp>c                 S  s$   g | ]\}}d d t ||D qS )c                 S  s   g | ]\}}t ||| qS r_   rh   )rc   sdimr_   r_   r`   r      rf   z1slices_from_chunks.<locals>.<listcomp>.<listcomp>zip)rc   startsshapesr_   r_   r`   r      s   )r   listr   )chunksZcumdimsslicesr_   r_   r`   slices_from_chunks   s
    r   Fr1   c	              
   C  s   t |||d}ttt|}	t|drJt|drJ|r:|rJt|||d}
n|}
|rzt|
||	| dt||	i d}t	||S d| }i }t
|| i||< t|
||	|dt||	i d||< |t ||hi}t||S dS )a  
    HighLevelGraph for slicing chunks from an array-like according to a chunk pattern.

    If ``inline_array`` is True, this make a Blockwise layer of slicing tasks where the
    array-like is embedded into every task.,

    If ``inline_array`` is False, this inserts the array-like as a standalone value in
    a MaterializedLayer, then generates a Blockwise layer of slicing tasks that refer
    to it.

    >>> dict(graph_from_arraylike(arr, chunks=(2, 3), shape=(4, 6), name="X", inline_array=True))  # doctest: +SKIP
    {(arr, 0, 0): (getter, arr, (slice(0, 2), slice(0, 3))),
     (arr, 1, 0): (getter, arr, (slice(2, 4), slice(0, 3))),
     (arr, 1, 1): (getter, arr, (slice(2, 4), slice(3, 6))),
     (arr, 0, 1): (getter, arr, (slice(0, 2), slice(3, 6)))}

    >>> dict(  # doctest: +SKIP
            graph_from_arraylike(arr, chunks=((2, 2), (3, 3)), shape=(4,6), name="X", inline_array=False)
        )
    {"original-X": arr,
     ('X', 0, 0): (getter, 'original-X', (slice(0, 2), slice(0, 3))),
     ('X', 1, 0): (getter, 'original-X', (slice(2, 4), slice(0, 3))),
     ('X', 1, 1): (getter, 'original-X', (slice(2, 4), slice(3, 6))),
     ('X', 0, 1): (getter, 'original-X', (slice(0, 2), slice(3, 6)))}
    dtyperj   rk   ri   N)	numblocksz	original-)normalize_chunksrl   rangelenr@   r   core_blockwiser3   r1   from_collectionsr2   set)arrr   shapenamerM   rk   rj   r   inline_arrayout_indrn   layeroriginal_namelayersZdepsr_   r_   r`   graph_from_arraylike   sR    $

r   c                 K  s:   |rt || } |rt ||}tt ttjfi || |S )a  Dot product of many aligned chunks

    >>> x = np.array([[1, 2], [1, 2]])
    >>> y = np.array([[10, 20], [10, 20]])
    >>> dotmany([x, x, x], [y, y, y])
    array([[ 90, 180],
           [ 90, 180]])

    Optionally pass in functions to apply to the left and right chunks

    >>> dotmany([x, x, x], [y, y, y], rightfunc=np.transpose)
    array([[150, 150],
           [150, 150]])
    )mapsumr   rp   dot)ABZleftfuncZ	rightfunckwargsr_   r_   r`   dotmanyB  s
    

r   c                   s    dkrt | tr| d S | S t | tr0t| } t | ttfsB| S t dkr` fdd| D } ttt| dd d}t | d t	rt| d 
 tfd	d
| D sJ t	 }D ]*|tfdd
| D  d d|< q|S ||  d dS dS )a  Recursively concatenate nested lists of arrays along axes

    Each entry in axes corresponds to each level of the nested list.  The
    length of axes should correspond to the level of nesting of arrays.
    If axes is an empty list or tuple, return arrays, or arrays[0] if
    arrays is a list.

    >>> x = np.array([[1, 2], [3, 4]])
    >>> _concatenate2([x, x], axes=[0])
    array([[1, 2],
           [3, 4],
           [1, 2],
           [3, 4]])

    >>> _concatenate2([x, x], axes=[1])
    array([[1, 2, 1, 2],
           [3, 4, 3, 4]])

    >>> _concatenate2([[x, x], [x, x]], axes=[0, 1])
    array([[1, 2, 1, 2],
           [3, 4, 3, 4],
           [1, 2, 1, 2],
           [3, 4, 3, 4]])

    Supports Iterators
    >>> _concatenate2(iter([x, x]), axes=[1])
    array([[1, 2, 1, 2],
           [3, 4, 3, 4]])

    Special Case
    >>> _concatenate2([x, x], axes=())
    array([[1, 2],
           [3, 4]])
    r_   r   rK   c                   s    g | ]}t | d d dqS )rK   Naxes)_concatenate2rc   rr   r   r_   r`   r     rf   z!_concatenate2.<locals>.<listcomp>c                 S  s   t | ddS N__array_priority__r   getattrrd   r_   r_   r`   <lambda>  rf   z_concatenate2.<locals>.<lambda>keyc                 3  s   | ]}t |  kV  qd S ra   )r   keysr   )r   r_   r`   re     rf   z _concatenate2.<locals>.<genexpr>c                 3  s   | ]}|  V  qd S ra   r_   r   kr_   r`   re     rf   axisN)rg   r   r   rl   r   rP   dispatchr   maxdictr   all)arraysr   concatenateretr_   )r   r   r   r`   r   X  s*    #

(r   r   c                   s  ddl m   fdd|D }z>tjdd | |i |}W d   n1 sP0    Y  W nr ty } zZt \}}	}
dt	|
}|rd	j
|d
nd}d| d| d|d| }W Y d}~nd}~0 0 d}|durt||du r|jS tdd |D S )a  
    Tries to infer output dtype of ``func`` for a small set of input arguments.

    Parameters
    ----------
    func: Callable
        Function for which output dtype is to be determined

    args: List of array like
        Arguments to the function, which would usually be used. Only attributes
        ``ndim`` and ``dtype`` are used.

    kwargs: dict
        Additional ``kwargs`` to the ``func``

    funcname: String
        Name of calling function to improve potential error messages

    suggest_dtype: None/False or String
        If not ``None`` adds suggestion to potential error message to specify a dtype
        via the specified kwarg. Defaults to ``'dtype'``.

    nout: None or Int
        ``None`` if function returns single output, integer if many.
        Deafults to ``None``.

    Returns
    -------
    : dtype or List of dtype
        One or many dtypes (depending on ``nout``)
    rK   meta_from_arrayc                   s4   g | ],}t |r,tj |d |j |jdn|qS )rK   r   r   )rA   rp   Z	ones_likendimr   rb   r   r_   r`   r     s   z%apply_infer_dtype.<locals>.<listcomp>ignorer   N z@Please specify the dtype explicitly using the `{dtype}` kwarg.

r   z`dtype` inference failed in `z`.

z2Original error is below:
------------------------
z

Traceback:
---------
c                 s  s   | ]}|j V  qd S ra   r   rc   er_   r_   r`   re     rf   z$apply_infer_dtype.<locals>.<genexpr>)utilsr   rp   Zerrstate	Exceptionsysexc_infojoin	traceback	format_tbformat
ValueErrorr   rl   )funcargsr   r?   suggest_dtypenoutor   exc_type	exc_valueexc_tracebacktbZsuggestmsgr_   r   r`   apply_infer_dtype  s<     
0	r   c                 C  sd   t | r| S t| tr*td| r*t| S t| trHt| dkrHt| S t| dkr\t| S | S dS )a>  Normalize user provided arguments to blockwise or map_blocks

    We do a few things:

    1.  If they are string literals that might collide with blockwise_token then we
        quote them
    2.  IF they are large (as defined by sizeof) then we put them into the
        graph on their own by using dask.delayed
    z_\d+
   g    .AN)	r'   rg   strrematchr0   r   r   r5   r   r_   r_   r`   normalize_arg  s    
r   c                 O  s*   | t|| | |t|d i |S )zHelper for :func:`dask.array.map_blocks` to pass `block_info` or `block_id`.

    For each element of `keys`, a corresponding element of args is changed
    to a keyword argument with that key, before all arguments re passed on
    to `func`.
    N)updater   r   )r   r   r   r   r_   r_   r`   _pass_extra_kwargs  s    r   )r   tokenr   r   	drop_axisnew_axismetac             
     sv  t | sd}
t|
t| j |r4tjdtd |}|p>t|  dt| |||g|R i |	 }i }t	t
rxgt	|t
r|g}dd |D }dd |D }|rtttdd	 |D d
d
d nd|	}|d
u r*|d
u r*zt| |g|R i |	}W n ty   Y n0 t| ||d}rttfdd	D rftd d dfddD tfdd	tD |d
u r|d
urtt|k rtt|t }|rHtt|D ]B}tt }|| |d
ur|| ||< nd||< qtt|tkrHtd|d
urt|tkrtdt| dt dtt|}nd
}t| gt|R |||dd||d|	g }g }t| dr<dj fddtd d	 jD  D }t |td!d	 jD t!j"d"}|#|f |#d t| d#ri 
i i }t|D ]~\\ }|d
ur\ j$|< r fd$dt|D 
< td%d	 
 D < nd&d  jD 
<  j%< q\d'd jD 	d(j }i }td)d	 jD  D ]}fd*dt|D i }|& D ]Z\}tfd+d	t| d D }| 
fd,dt|D |d-|< q4j$j%	fd.dt|D |tfd/d	t|D |d0|d
< |||f| < qt ||td1d	 jD t!j"d"}|#|f |#d# |rrtt'| d
t|d
gt|t|R jj(ddttj|d2|	S )3a#  Map a function across all blocks of a dask array.

    Note that ``map_blocks`` will attempt to automatically determine the output
    array type by calling ``func`` on 0-d versions of the inputs. Please refer to
    the ``meta`` keyword argument below if you expect that the function will not
    succeed when operating on 0-d arrays.

    Parameters
    ----------
    func : callable
        Function to apply to every block in the array.
        If ``func`` accepts ``block_info=`` or ``block_id=``
        as keyword arguments, these will be passed dictionaries
        containing information about input and output chunks/arrays
        during computation. See examples for details.
    args : dask arrays or other objects
    dtype : np.dtype, optional
        The ``dtype`` of the output array. It is recommended to provide this.
        If not provided, will be inferred by applying the function to a small
        set of fake data.
    chunks : tuple, optional
        Chunk shape of resulting blocks if the function does not preserve
        shape. If not provided, the resulting array is assumed to have the same
        block structure as the first input array.
    drop_axis : number or iterable, optional
        Dimensions lost by the function.
    new_axis : number or iterable, optional
        New dimensions created by the function. Note that these are applied
        after ``drop_axis`` (if present).
    token : string, optional
        The key prefix to use for the output array. If not provided, will be
        determined from the function name.
    name : string, optional
        The key name to use for the output array. Note that this fully
        specifies the output key name, and must be unique. If not provided,
        will be determined by a hash of the arguments.
    meta : array-like, optional
        The ``meta`` of the output array, when specified is expected to be an
        array of the same type and dtype of that returned when calling ``.compute()``
        on the array returned by this function. When not provided, ``meta`` will be
        inferred by applying the function to a small set of fake data, usually a
        0-d array. It's important to ensure that ``func`` can successfully complete
        computation without raising exceptions when 0-d is passed to it, providing
        ``meta`` will be required otherwise. If the output type is known beforehand
        (e.g., ``np.ndarray``, ``cupy.ndarray``), an empty array of such type dtype
        can be passed, for example: ``meta=np.array((), dtype=np.int32)``.
    **kwargs :
        Other keyword arguments to pass to function. Values must be constants
        (not dask.arrays)

    See Also
    --------
    dask.array.blockwise : Generalized operation with control over block alignment.

    Examples
    --------
    >>> import dask.array as da
    >>> x = da.arange(6, chunks=3)

    >>> x.map_blocks(lambda x: x * 2).compute()
    array([ 0,  2,  4,  6,  8, 10])

    The ``da.map_blocks`` function can also accept multiple arrays.

    >>> d = da.arange(5, chunks=2)
    >>> e = da.arange(5, chunks=2)

    >>> f = da.map_blocks(lambda a, b: a + b**2, d, e)
    >>> f.compute()
    array([ 0,  2,  6, 12, 20])

    If the function changes shape of the blocks then you must provide chunks
    explicitly.

    >>> y = x.map_blocks(lambda x: x[::2], chunks=((2, 2),))

    You have a bit of freedom in specifying chunks.  If all of the output chunk
    sizes are the same, you can provide just that chunk size as a single tuple.

    >>> a = da.arange(18, chunks=(6,))
    >>> b = a.map_blocks(lambda x: x[:3], chunks=(3,))

    If the function changes the dimension of the blocks you must specify the
    created or destroyed dimensions.

    >>> b = a.map_blocks(lambda x: x[None, :, None], chunks=(1, 6, 1),
    ...                  new_axis=[0, 2])

    If ``chunks`` is specified but ``new_axis`` is not, then it is inferred to
    add the necessary number of axes on the left.

    Map_blocks aligns blocks by block positions without regard to shape. In the
    following example we have two arrays with the same number of blocks but
    with different shape and chunk sizes.

    >>> x = da.arange(1000, chunks=(100,))
    >>> y = da.arange(100, chunks=(10,))

    The relevant attribute to match is numblocks.

    >>> x.numblocks
    (10,)
    >>> y.numblocks
    (10,)

    If these match (up to broadcasting rules) then we can map arbitrary
    functions across blocks

    >>> def func(a, b):
    ...     return np.array([a.max(), b.max()])

    >>> da.map_blocks(func, x, y, chunks=(2,), dtype='i8')
    dask.array<func, shape=(20,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>

    >>> _.compute()
    array([ 99,   9, 199,  19, 299,  29, 399,  39, 499,  49, 599,  59, 699,
            69, 799,  79, 899,  89, 999,  99])

    Your block function can get information about where it is in the array by
    accepting a special ``block_info`` or ``block_id`` keyword argument.
    During computation, they will contain information about each of the input
    and output chunks (and dask arrays) relevant to each call of ``func``.

    >>> def func(block_info=None):
    ...     pass

    This will receive the following information:

    >>> block_info  # doctest: +SKIP
    {0: {'shape': (1000,),
         'num-chunks': (10,),
         'chunk-location': (4,),
         'array-location': [(400, 500)]},
     None: {'shape': (1000,),
            'num-chunks': (10,),
            'chunk-location': (4,),
            'array-location': [(400, 500)],
            'chunk-shape': (100,),
            'dtype': dtype('float64')}}

    The keys to the ``block_info`` dictionary indicate which is the input and
    output Dask array:

    - **Input Dask array(s):** ``block_info[0]`` refers to the first input Dask array.
      The dictionary key is ``0`` because that is the argument index corresponding
      to the first input Dask array.
      In cases where multiple Dask arrays have been passed as input to the function,
      you can access them with the number corresponding to the input argument,
      eg: ``block_info[1]``, ``block_info[2]``, etc.
      (Note that if you pass multiple Dask arrays as input to map_blocks,
      the arrays must match each other by having matching numbers of chunks,
      along corresponding dimensions up to broadcasting rules.)
    - **Output Dask array:** ``block_info[None]`` refers to the output Dask array,
      and contains information about the output chunks.
      The output chunk shape and dtype may may be different than the input chunks.

    For each dask array, ``block_info`` describes:

    - ``shape``: the shape of the full Dask array,
    - ``num-chunks``: the number of chunks of the full array in each dimension,
    - ``chunk-location``: the chunk location (for example the fourth chunk over
      in the first dimension), and
    - ``array-location``: the array location within the full Dask array
      (for example the slice corresponding to ``40:50``).

    In addition to these, there are two extra parameters described by
    ``block_info`` for the output array (in ``block_info[None]``):

    - ``chunk-shape``: the output chunk shape, and
    - ``dtype``: the output dtype.

    These features can be combined to synthesize an array from scratch, for
    example:

    >>> def func(block_info=None):
    ...     loc = block_info[None]['array-location'][0]
    ...     return np.arange(loc[0], loc[1])

    >>> da.map_blocks(func, chunks=((4, 4),), dtype=np.float_)
    dask.array<func, shape=(8,), dtype=float64, chunksize=(4,), chunktype=numpy.ndarray>

    >>> _.compute()
    array([0, 1, 2, 3, 4, 5, 6, 7])

    ``block_id`` is similar to ``block_info`` but contains only the ``chunk_location``:

    >>> def func(block_id=None):
    ...     pass

    This will receive the following information:

    >>> block_id  # doctest: +SKIP
    (4, 3)

    You may specify the key name prefix of the resulting task in the graph with
    the optional ``token`` keyword argument.

    >>> x.map_blocks(lambda x: x + 1, name='increment')
    dask.array<increment, shape=(1000,), dtype=int64, chunksize=(100,), chunktype=numpy.ndarray>

    For functions that may not handle 0-d arrays, it's also possible to specify
    ``meta`` with an empty array matching the type of the expected result. In
    the example below, ``func`` will result in an ``IndexError`` when computing
    ``meta``:

    >>> da.map_blocks(lambda x: x[2], da.random.random(5), meta=np.array(()))
    dask.array<lambda, shape=(5,), dtype=float64, chunksize=(5,), chunktype=numpy.ndarray>

    Similarly, it's possible to specify a non-NumPy array to ``meta``, and provide
    a ``dtype``:

    >>> import cupy  # doctest: +SKIP
    >>> rs = da.random.RandomState(RandomState=cupy.random.RandomState)  # doctest: +SKIP
    >>> dt = np.float32
    >>> da.map_blocks(lambda x: x[2], rs.random(5, dtype=dt), meta=cupy.array((), dtype=dt))  # doctest: +SKIP
    dask.array<lambda, shape=(5,), dtype=float32, chunksize=(5,), chunktype=cupy.ndarray>
    z~First argument must be callable function, not %s
Usage:   da.map_blocks(function, x)
   or:   da.map_blocks(function, x, y, z)zThe `token=` keyword to `map_blocks` has been moved to `name=`. Please use `name=` instead as the `token=` keyword will be removed in a future release.)category-c                 S  s   g | ]}t |tr|qS r_   rg   r   r   r_   r_   r`   r     rf   zmap_blocks.<locals>.<listcomp>c                 S  s:   g | ]2}t |tr.|tt|jd d d fn|d fqS N)rg   r   rl   r   r   r   r_   r_   r`   r     s   c                 s  s   | ]}|j V  qd S ra   r   r   r_   r_   r`   re     rf   zmap_blocks.<locals>.<genexpr>Nr   r_   
map_blocksc                 3  s    | ]}|  k p| kV  qd S ra   r_   rc   indim_outr_   r`   re     rf   z"drop_axis out of range (drop_axis=z, but output is zd).c                   s   g | ]}|  qS r_   r_   r  r  r_   r`   r     rf   c                 3  s   | ]\}}| vr|V  qd S ra   r_   )rc   r  rd   )r   r_   r`   re     rf   rK   z-New_axis values do not fill in all dimensionszProvided chunks have z dims; expected z dimsTF)r   new_axesr   r   align_arraysadjust_chunksr   block_idz	block-id-c                   s   i | ]} f| |qS r_   r_   )rc   r
  )block_id_namer_   r`   
<dictcomp>H  s   zmap_blocks.<locals>.<dictcomp>c                 s  s   | ]}t t|V  qd S ra   r   r   rc   ru   r_   r_   r`   re   J  rf   c                 s  s   | ]}d t | V  qdS r   Nr   r  r_   r_   r`   re   O  rf   r   r   
block_infoc                   s8   g | ]0\}}|v r&t  j| d dnd j| gqS )Tr   r   )r9   r   r   rc   jind)argr   r_   r`   r   b  s   c                 s  s   | ]}t |d  V  qdS rK   Nr  rc   r   r_   r_   r`   re   j  rf   c                 S  s   g | ]}t |d dqS r   r   r  r_   r_   r`   r   l  s   c                 S  s   g | ]}t |d dqS r   r   r  r_   r_   r`   r   p  rf   zblock-info-c                 s  s   | ]}t t|V  qd S ra   r  r  r_   r_   r`   re   t  rf   c                   s   i | ]\}} | |qS r_   r_   )rc   r  loc)r   r_   r`   r  v  rf   c                 3  s2   | ]*\}}  | d kr& |dndV  qdS rK   r   Ngetr  )r  location
num_chunksr_   r`   re   }  s   c                   s4   g | ],\}}  | |   | |d   fqS r   r_   rc   Zijr  )r  r   r_   r`   r     s   )r   
num-chunksarray-locationchunk-locationc                   s,   g | ]$\}} | |  | |d   fqS r   r_   r  )
out_startsr_   r`   r     s   c                 3  s    | ]\}} j | | V  qd S ra   r   r  outr_   r`   re     s   )r   r   r!  r"  zchunk-shaper   c                 s  s   | ]}d t | V  qdS r  r  r  r_   r_   r`   re     rf   )r   r   r   r  r	  r   ))callable	TypeErrorr   r[   warningswarnFutureWarningr?   r)   rg   r   rl   r   r   compute_metar   r   r   rm   r   	enumerater   sortedinsertr   r   r*   r   r@   r   r   r   r   rp   Zobject_appendr   r   itemsr   r   )r   r   r   r   r   r   r   r   r   r   r   r  ZarrsZargpairsZoriginal_kwargsaxnr	  Zextra_argpairsZextra_namesZblock_id_dskZblock_id_arrayr   Zin_indZblock_info_nameZblock_info_dskr
  infor   Zarr_kr  r_   )r  r  r   r  r  r  r  r&  r   r#  r   r`   r     sP    f0

&&












	r  c                    s   | sdS t | dkr| d S ttt | fdd| D }g }tD ]j  fdd|D }tdd |D rv|}nd	d |D }t t|dkrtd
t| ||d  qHt	|S )a\  Construct a chunks tuple that broadcasts many chunks tuples

    >>> a = ((5, 5),)
    >>> b = ((5, 5),)
    >>> broadcast_chunks(a, b)
    ((5, 5),)

    >>> a = ((10, 10, 10), (5, 5),)
    >>> b = ((5, 5),)
    >>> broadcast_chunks(a, b)
    ((10, 10, 10), (5, 5))

    >>> a = ((10, 10, 10), (5, 5),)
    >>> b = ((1,), (5, 5),)
    >>> broadcast_chunks(a, b)
    ((10, 10, 10), (5, 5))

    >>> a = ((10, 10, 10), (5, 5),)
    >>> b = ((3, 3,), (5, 5),)
    >>> broadcast_chunks(a, b)
    Traceback (most recent call last):
        ...
    ValueError: Chunks do not align: [(10, 10, 10), (3, 3)]
    r_   rK   r   c                   s    g | ]}d  t |  | qS )r   r  r  )r3  r_   r`   r     rf   z$broadcast_chunks.<locals>.<listcomp>c                   s   g | ]}|  qS r_   r_   r  r  r_   r`   r     rf   c                 s  s   | ]}|d kV  qdS r  r_   r  r_   r_   r`   re     rf   z#broadcast_chunks.<locals>.<genexpr>c                 S  s   g | ]}|d kr|qS r5  r_   r  r_   r_   r`   r     rf   zChunks do not align: %s)
r   r   r   r   r   r   r   r   r0  rl   )chunkssZchunkss2resultZstep1Zstep2r_   )r  r3  r`   broadcast_chunks  s     r9  zArray | Collection[Array]zbool | Lockz8tuple[slice, ...] | Collection[tuple[slice, ...]] | None)sourcesrk   regionsr    return_storedc                   s0  t | tr| g} |g}tdd | D r0tdt| t|krXtdt| t|f t |tsj|du rp|g}t| dkrt|dkr|t| 9 }t| t|krtdt| t|t|f tjdd	 | D  }t|t	t
d
d	 | D }dt|  }	|	|i}
|	t i}g }g }|D ]@}t |trL||j ||  nt|r tdq |rtj| }t||}dt| }||
|< t ||< |o| }dd	 t| ||D }g }t| |||D ]v\}}}}t| |jt |tr|jn||||||d}||
|< t |tr.|	|h||< n
|	h||< || 7 }q|rt|
| |rfdd	|D }t|i |}tjdd	 |D  }t|| dd	 |D }t fddt| |D S |rt|
|tt|fi | dS dt| }||i|
|< t|||< t|
|t|S dS )a  Store dask arrays in array-like objects, overwrite data in target

    This stores dask arrays into object that supports numpy-style setitem
    indexing.  It stores values chunk by chunk so that it does not have to
    fill up memory.  For best performance you can align the block size of
    the storage target with the block size of your array.

    If your data fits in memory then you may prefer calling
    ``np.array(myarray)`` instead.

    Parameters
    ----------

    sources: Array or collection of Arrays
    targets: array-like or Delayed or collection of array-likes and/or Delayeds
        These should support setitem syntax ``target[10:20] = ...``
    lock: boolean or threading.Lock, optional
        Whether or not to lock the data stores while storing.
        Pass True (lock each file individually), False (don't lock) or a
        particular :class:`threading.Lock` object to be shared among all writes.
    regions: tuple of slices or collection of tuples of slices
        Each ``region`` tuple in ``regions`` should be such that
        ``target[region].shape = source.shape``
        for the corresponding source and target in sources and targets,
        respectively. If this is a tuple, the contents will be assumed to be
        slices, so do not provide a tuple of tuples.
    compute: boolean, optional
        If true compute immediately; return :class:`dask.delayed.Delayed` otherwise.
    return_stored: boolean, optional
        Optionally return the stored result (default False).
    kwargs:
        Parameters passed to compute/persist (only used if compute=True)

    Returns
    -------

    If return_stored=True
        tuple of Arrays
    If return_stored=False and compute=True
        None
    If return_stored=False and compute=False
        Delayed

    Examples
    --------

    >>> import h5py  # doctest: +SKIP
    >>> f = h5py.File('myfile.hdf5', mode='a')  # doctest: +SKIP
    >>> dset = f.create_dataset('/data', shape=x.shape,
    ...                                  chunks=x.chunks,
    ...                                  dtype='f8')  # doctest: +SKIP

    >>> store(x, dset)  # doctest: +SKIP

    Alternatively store many arrays at the same time

    >>> store([x, y, z], [dset1, dset2, dset3])  # doctest: +SKIP
    c                 s  s   | ]}t |t V  qd S ra   r   r  r_   r_   r`   re   1  rf   zstore.<locals>.<genexpr>z&All sources must be dask array objectsz1Different number of sources [%d] and targets [%d]NrK   zCDifferent number of sources [%d] and targets [%d] than regions [%d]c                 S  s   g | ]}|  qS r_   )__dask_graph__r   r_   r_   r`   r   G  rf   zstore.<locals>.<listcomp>c                 S  s   g | ]}|  qS r_   )__dask_keys__r   r_   r_   r`   r   I  rf   zstore-sources-z5Targets must be either Delayed objects or array-likeszstore-targets-c                 S  s4   g | ],\}}}d t |t|tr"|nt|| qS )z
store-map-)r)   rg   r/   id)rc   r   trr_   r_   r`   r   b  s   )r   r   r&  r   rk   regionr<  load_storedc                   s   g | ]}t | |d  dqS )r   r   r/   rc   r   )	store_dskr_   r`   r   ~  rf   c                 S  s   g | ]
}|j qS r_   daskr   r_   r_   r`   r     rf   c                 S  s   g | ]}d | qS )load-r_   )rc   r3  r_   r_   r`   r     rf   c                 3  s$   | ]\}}t  ||j|d V  qdS )r   N)r   r   )rc   r   r3  )load_store_dskr_   r`   re     s   zstore-)rg   r   rm   r   r   rl   r1   merge__dask_optimize__r   r"   flattenr)   r   r/   r0  r   r=  r'   r(  r   insert_to_oocr>  r   r   r(   retrieve_from_oocr%   )r:  targetsrk   r;  r    r<  r   Zsources_hlgZsources_layerZsources_namer   dependenciesZtargets_keysZtargets_dsksr@  Ztargets_hlgZtargets_layerZtargets_namerC  Z	map_namesZmap_keysr   r3  rA  Z	map_layerZstore_dlydsZstore_dsk_2r   r_   )rL  rG  r`   store  s    D










rT  c                 C  s   |du rt d| du r t dtt| s<tt|rNtd| |tf ttt|sdtdttt| sztdt	tt
| } t	tt
|}t	dd t| |D S )	z

    >>> blockdims_from_blockshape((10, 10), (4, 3))
    ((4, 4, 2), (3, 3, 3, 1))
    >>> blockdims_from_blockshape((10, 0), (4, 0))
    ((4, 4, 2), (0,))
    Nz$Must supply chunks= keyword argumentz#Must supply shape= keyword argumentz6Array chunk sizes are unknown. shape: %s, chunks: %s%sz!chunks can only contain integers.z shape can only contain integers.c                 s  s>   | ]6\}}|r2|f||  || r,|| fnd  ndV  qdS )r_   r   Nr_   )rc   dbdr_   r_   r`   re     s   z,blockdims_from_blockshape.<locals>.<genexpr>)r(  rp   isnanr   r   unknown_chunk_messager   r   rD   rl   intr   r   r   r_   r_   r`   blockdims_from_blockshape  s&    r\  c                 C  sD   | st | S | }t|ttfr<t|dkr2t | S |d }qt| S )NrK   r   )concatenate3rg   rl   r   r   unpack_singleton)resultsZresults2r_   r_   r`   finalize  s    
r`  z
You must specify a chunks= keyword argument.
This specifies the chunksize of your array blocks.

See the following documentation page for details:
  https://docs.dask.org/en/latest/array-creation.html#chunks
c                      s\  e Zd ZdZdZd fdd	Zdd Zdd	 Zd
d Zdd Z	dd Z
eededZeejZdd Zdd ZddddZd ddZedd Zedd Zedd  Zd!d" Zed#d$ Zed%d& Zed'd( Zed)d* Z e j!d+d* Z ed,d- Z"e"j!d.d- Z"d/d0 Z#d1d2 Z$d3d4 Z%d5d6 Z&ed7d8 Z'ed9d: Z(ed;d< Z)ed=d> Z*ed?d@ Z+e+j!dAd@ Z+edBdC Z,e,j!dDdC Z,dEdF Z-dGZ.d!dHdIZ/dJdK Z0edLdM Z1e2e3dNdO Z3d"dQdRZ4dSdT Z5d#dUdVZ6dWdX Z7e7Z8dYdZ Z9d[d\ Z:e:Z;d]d^ Z<d_d` Z=dadb Z>dcdd Z?dedf Z@dgdh ZAedidj ZBedkdl ZCedmdn ZDeEeFjGdodp ZHedqdr ZIedsdt ZJeEeFjGdudv ZKeEeFjGdwdx ZLeLZMeEeFjGdydz ZNeEeFjGd{dd|d}d~ZOd$ddZPd%ddZQdd ZRdd ZSeTdd ZUeTdd ZVeTdd ZWeTdd ZXeTdd ZYeTdd ZZeTdd Z[eTdd Z\eTdd Z]dd Z^eTdd Z_eTdd Z`eTdd ZaeTdd ZbeTdd ZceTdd ZdeTdd ZeeTdd ZfeTdd Zgdd ZheTdd Zidd ZjeTdd ZkeTdd ZleTdd ZmeTdd ZneTdd ZoeTdd ZpeTdd ZqeTddÄ ZreTddń ZseTddǄ ZteTddɄ ZueTdd˄ ZveTdd̈́ ZweTddτ ZxeTddф ZyeTddӄ ZzeTddՄ Z{eEeFjGd&dd؄Z|eEeFjGd'ddڄZ}eEeFjGd(dd܄Z~eEeFjGd)ddބZeEeFjGd*ddZeEeFjGd+ddZeEeFjGd,ddZeEeFjGd-ddZeEeFjGd.ddZeEeFjGd/ddZeEeFjGd0ddZeEeFjGd1ddZd2ddZe2edd Zd3ddZeEeFjGd4ddddZeEeFjGd5ddddZeEeFjGd6ddZd7d dZedd Zedd Zdd ZeEeFjGd8dd	Zd9ddZeEeFjGdd ZeEeFjGd:ddZdd Zdd Zd;ddZeEeFjGd<ddZeEeFjGdd Zdd Zdd Z  ZS (=  r   a  Parallel Dask Array

    A parallel nd-array comprised of many numpy arrays arranged in a grid.

    This constructor is for advanced uses only.  For normal use see the
    :func:`dask.array.from_array` function.

    Parameters
    ----------
    dask : dict
        Task dependency graph
    name : string
        Name of array in dask
    shape : tuple of ints
        Shape of the entire array
    chunks: iterable of tuples
        block sizes along each dimension
    dtype : str or dtype
        Typecode or data-type for the new Dask Array
    meta : empty ndarray
        empty ndarray created with same NumPy backend, ndim and dtype as the
        Dask Array being created (overrides dtype)

    See Also
    --------
    dask.array.from_array
    )rI  Z__name_cached_keysZ__chunks_meta__dict__Nc              
     s~  t  | }t|tsJ t|ts4tj||dd}||_t||_t	||d}t|tszt|t
r|rtdd |D r|j}nd }t|||d|_|jd u rttt	||j|d|_tddD ]}	|	|}
|
d ur|
}qz|jj| }W n ttfy   Y nr0 |jd u rF|j|j|j|jtt|tt|jd|_n4|j|j|j|j|jtt|tt|jd |S )	Nr_   rS  r   c                 s  s   | ]}t |tV  qd S ra   rg   r   r  r_   r_   r`   re     rf   z Array.__new__.<locals>.<genexpr>)r   r   Zarray_plugins)r   r   	chunksizer   r   Z
chunk_type)super__new__rg   r	   r1   r   rI  r   _namer   rl   rm   r   r   _chunksr   r   CHUNKS_NONE_ERROR_MESSAGEr   rb  r!   r  r   AttributeErrorKeyErrorZcollection_annotationsr   rf  rI   r   r   )clsrI  r   r   r   r   r   r   dtZpluginr8  r   	__class__r_   r`   rh    s^    




	
zArray.__new__c                 C  s   t | j| j| j| jffS ra   )r   rI  r   r   r   r   r_   r_   r`   
__reduce__#  s    zArray.__reduce__c                 C  s   | j S ra   rH  rr  r_   r_   r`   r=  &  s    zArray.__dask_graph__c                 C  s   | j fS ra   r   rr  r_   r_   r`   __dask_layers__)  s    zArray.__dask_layers__c                   sH   | j d ur| j S | j| j| j    fdd  | _ }|S )Nc                    sb   sfgS t  }|d t krB fddt| D }n fddt| D }|S )NrK   c                   s   g | ]}f  |f qS r_   r_   r  )r   r   r_   r`   r   7  rf   z5Array.__dask_keys__.<locals>.keys.<locals>.<listcomp>c                   s   g | ]} |f  qS r_   r_   r  )r   r   r_   r`   r   9  rf   )r   r   )r   r  r8  r   r   r   r   )r   r`   r   2  s    z!Array.__dask_keys__.<locals>.keys)ra  r   r   r   )r   r8  r_   rv  r`   r>  ,  s    

zArray.__dask_keys__c                 C  s   | j S ra   rt  rr  r_   r_   r`   __dask_tokenize__?  s    zArray.__dask_tokenize__Zarray_optimize)r   Zfalseyc                 C  s   t dfS Nr_   )r`  rr  r_   r_   r`   __dask_postcompute__G  s    zArray.__dask_postcompute__c                 C  s
   | j dfS rx  )_rebuildrr  r_   r_   r`   __dask_postpersist__J  s    zArray.__dask_postpersist__)renamec                C  s,   | j }|r|||}t||| j| j| jS ra   )ri  r  r   r   r   rb  )r   dskr|  r   r_   r_   r`   rz  M  s    zArray._rebuildc                 C  s&   |du r| j   n| j |d dS )z
        Reset cached properties.

        Parameters
        ----------
        key : str, optional
            Remove specified key. The default removes all items.
        N)rc  clearpopr   r   r_   r_   r`   _reset_cacheS  s    	zArray._reset_cachec                 C  s   t j|  tdS )Nr   )rp   rX   r>  objectrr  r_   r_   r`   
_key_arraya  s    zArray._key_arrayc                 C  s   t tt| jS ra   )rl   r   r   r   rr  r_   r_   r`   r   e  s    zArray.numblocksc                 C  s   t t| jdS NrK   )r   r   r   rr  r_   r_   r`   npartitionsi  s    zArray.npartitionsc                 C  s   | }|j tttdd |jD |jff |jd}g }t|jD ]<}|jdg |g }td||< t|}|t||  q@tdd t	t|d D |_
|S )a  
        Compute the chunk sizes for a Dask array. This is especially useful
        when the chunk sizes are unknown (e.g., when indexing one Dask array
        with another).

        Notes
        -----
        This function modifies the Dask array in-place.

        Examples
        --------
        >>> import dask.array as da
        >>> import numpy as np
        >>> x = da.from_array([-2, -1, 0, 1, 2], chunks=2)
        >>> x.chunks
        ((2, 2, 1),)
        >>> y = x[x <= 0]
        >>> y.chunks
        ((nan, nan, nan),)
        >>> y.compute_chunk_sizes()  # in-place computation
        dask.array<getitem, shape=(3,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>
        >>> y.chunks
        ((2, 1, 0),)

        c                 s  s   | ]}t |d  V  qdS r  r  r  r_   r_   r`   re     rf   z,Array.compute_chunk_sizes.<locals>.<genexpr>r   r   r   r   Nc                 s  s    | ]}t d d |D V  qdS )c                 s  s   | ]}t |V  qd S ra   )rZ  )rc   rL   r_   r_   r`   re     rf   z6Array.compute_chunk_sizes.<locals>.<genexpr>.<genexpr>Nrl   )rc   r   r_   r_   r`   re     s   )r  _get_chunk_shaperZ  rl   r   r   r   rh   r0  r    rj  )r   rd   Zchunk_shapesru   r  r   r_   r_   r`   compute_chunk_sizesm  s"    
zArray.compute_chunk_sizesc                 C  s   t dd | jD S )Nc                 s  s   | ]}t |d dd V  qdS )Tr   r   Nr   r  r_   r_   r`   re     rf   zArray.shape.<locals>.<genexpr>rl   r   rr  r_   r_   r`   r     s    zArray.shapec                 C  s   t dd | jD S )Nc                 s  s   | ]}t |V  qd S ra   r   r  r_   r_   r`   re     rf   z"Array.chunksize.<locals>.<genexpr>r  rr  r_   r_   r`   rf    s    zArray.chunksizec                 C  s&   t | jtr| jd j}n| jj}|S Nr   )rg   rb  rl   r   )r   r   r_   r_   r`   r     s    zArray.dtypec                 C  s   | j S )z9Non-public chunks property. Allows setting a chunk value._Array__chunksrr  r_   r_   r`   rj    s    zArray._chunksc                 C  s   || _ dD ]}| | q
d S )N)r   r  r   r   sizer  )r  r  )r   r   r   r_   r_   r`   rj    s    c                 C  s   | j S )zChunks property.r  rr  r_   r_   r`   r     s    zArray.chunksc                 C  s   t d| dd S )NzPCan not set chunks directly

Please use the rechunk method instead:
  x.rechunk(zC)

If trying to avoid unknown chunks, use
  x.compute_chunk_sizes()r(  )r   r   r_   r_   r`   r     s
    c                 C  sF   | j stdt| j d  r4dt }t|tt| j d S )Nzlen() of unsized objectr   z4Cannot call len() on object with unknown chunk size.)	r   r(  rp   rX  rm   rY  r   rZ  r   )r   r   r_   r_   r`   __len__  s    zArray.__len__c                 O  sB  | dd}|| D ]}t|rt  S q|dkr|tju rVddlm} ||i |S |jd urddlm} |||jg|R i |S |j	dkrddl
m}	 zt|	|j}
W n ty   t Y S 0 |
|i |S t|g|R i |S nT|dkr:ddl
m}	 zt|	|j}
W n ty(   t Y S 0 |
j|i |S tS d S )	Nr&  r_   __call__rK   matmul)apply_gufunc)ufuncouter)r  r   r   rp   r  routinesZ	signatureZgufuncr  r   r   r  r   r[   rl  elemwiser  )r   Znumpy_ufuncmethodinputsr   r&  rd   r  r  r  Zda_ufuncr_   r_   r`   r     sB    






zArray.__array_ufunc__c              	   C  sN   t | j}| jddd }d|| j| j|t| jj	
dd t| jjS )z

        >>> import dask.array as da
        >>> da.ones((10, 10), chunks=(5, 5), dtype='i4')
        dask.array<..., shape=(10, 10), dtype=int32, chunksize=(5, 5), chunktype=numpy.ndarray>
        r   rK   r   zAdask.array<{}, shape={}, dtype={}, chunksize={}, chunktype={}.{}>.)r   rf  r   rsplitr   r   r   r   rb  r\   splitr[   )r   rf  r   r_   r_   r`   __repr__  s    

zArray.__repr__c                 C  s   z| j tddd}W n ty.   d}Y n0 dtt| jv rLd }d }n8t| j	s|t
| j	}t
t| j| jj }nd}d}tdj| |||dS )	Nzarray.svg.sizex   r  r   Zsparseunknownzarray.html.j2)rX   gridnbytescbytes)to_svgr!   r  NotImplementedErrorrI   r   rb  mathrX  r  r>   rp   prodrf  r   itemsizerJ   Zrender)r   r  r  r  r_   r_   r`   _repr_html_  s$    

zArray._repr_html_c                 C  s
   t | jS ra   r   r   rr  r_   r_   r`   r   (  s    z
Array.ndimc                 C  s   t t| jdS )zNumber of elements in arrayrK   )r   r   r   rr  r_   r_   r`   r  ,  s    z
Array.sizec                 C  s   | j | jj S )zNumber of bytes in array)r  r   r  rr  r_   r_   r`   r  1  s    zArray.nbytesc                 C  s   | j jS )z$Length of one array element in bytes)r   r  rr  r_   r_   r`   r  6  s    zArray.itemsizec                 C  s   | j S ra   _Array__namerr  r_   r_   r`   ri  ;  s    zArray._namec                 C  s   || _ d | _| d d S )Nr  )r  ra  r  r   valr_   r_   r`   ri  ?  s    c                 C  s   | j S ra   r  rr  r_   r_   r`   r   F  s    z
Array.namec                 C  s   t dd S )NzCannot set name directly

Name is used to relate the array to the task graph.
It is uncommon to need to change it, but if you do
please set ``._name``r  r  r_   r_   r`   r   J  s    c                 c  s    t t| D ]}| | V  qd S ra   r  )r   r  r_   r_   r`   __iter__S  s    zArray.__iter__   c                 K  s:   |   }|r |j|kr ||}t|tjs6t|}|S ra   )r    r   astyperg   rp   ndarrayrX   )r   r   r   rd   r_   r_   r`   	__array__Y  s    

zArray.__array__c           	   	   C  s   dd l m} dd }tdd |D s*tS |jddd  D ]6}zt||}W q> tyr   |||| Y   S 0 q>t||j	s||||S t||j	}||u r||||S t
|dr| |d< ||i |S )	Nr   c                 S  sT   | t vrBtd| jd | j t t||\}}| |i |S t |  |i |S )NzThe `{}` function is not implemented by Dask array. You may want to use the da.map_blocks function or something similar to silence this warning. Your code may stop working in a future release.r  )r|   r)  r*  r   r\   r[   r+  r    )r   r   r   r_   r_   r`   handle_nonmatching_namesd  s    z:Array.__array_function__.<locals>.handle_nonmatching_namesc                 s  s   | ]}|t u pt|V  qd S ra   )r   rO   )rc   r   r_   r_   r`   re   y  rf   z+Array.__array_function__.<locals>.<genexpr>r  rK   like)Z
dask.arrayrX   r   r   r\   r  r   rl  r   r[   r@   )	r   r   typesr   r   moduler  Z	submoduleZda_funcr_   r_   r`   __array_function__a  s"    
zArray.__array_function__c                 C  s   t S ra   )r  rr  r_   r_   r`   	_elemwise  s    zArray._elemwisec                 K  s.   t | g|gfi |}|ddr*|d }|S )Nr<  Fr   )rT  r  )r   targetr   rA  r_   r_   r`   rT    s    zArray.store  c                 C  s   ddl m } || j|dS )ae  Convert chunks from Dask Array into an SVG Image

        Parameters
        ----------
        chunks: tuple
        size: int
            Rough size of the image

        Examples
        --------
        >>> x.to_svg(size=500)  # doctest: +SKIP

        Returns
        -------
        text: An svg string depicting the array as a grid of chunks
        rK   )svgr  )r  r   )r   r  r  r_   r_   r`   r    s    zArray.to_svgc                 K  s   t ||| fi |S )ac  Store array in HDF5 file

        >>> x.to_hdf5('myfile.hdf5', '/x')  # doctest: +SKIP

        Optionally provide arguments as though to ``h5py.File.create_dataset``

        >>> x.to_hdf5('myfile.hdf5', '/x', compression='lzf', shuffle=True)  # doctest: +SKIP

        See Also
        --------
        da.store
        h5py.File.create_dataset
        )to_hdf5)r   filenamedatapathr   r_   r_   r`   r    s    zArray.to_hdf5c                 C  s   ddl m} || |||dS )a^  Convert dask Array to dask Dataframe

        Parameters
        ----------
        columns: list or string
            list of column names if DataFrame, single string if Series
        index : dask.dataframe.Index, optional
            An optional *dask* Index to use for the output Series or DataFrame.

            The default output index depends on whether the array has any unknown
            chunks. If there are any unknown chunks, the output has ``None``
            for all the divisions (one per chunk). If all the chunks are known,
            a default index with known divsions is created.

            Specifying ``index`` can be useful if you're conforming a Dask Array
            to an existing dask Series or DataFrame, and you would like the
            indices to match.
        meta : object, optional
            An optional `meta` parameter can be passed for dask
            to specify the concrete dataframe type to use for partitions of
            the Dask dataframe. By default, pandas DataFrame is used.

        See Also
        --------
        dask.dataframe.from_dask_array
        r   )from_dask_array)columnsindexr   )Z	dataframer  )r   r  r  r   r  r_   r_   r`   to_dask_dataframe  s    zArray.to_dask_dataframec                 C  s0   | j dkr td| jj dnt|  S d S )NrK   zThe truth value of a z& is ambiguous. Use a.any() or a.all().)r  r   rq  r[   r   r    rr  r_   r_   r`   __bool__  s
    
zArray.__bool__c                 C  s$   | j dkrtdn||  S d S )NrK   z7Only length-1 arrays can be converted to Python scalars)r  r(  r    )r   Z	cast_typer_   r_   r`   _scalarfunc  s    

zArray._scalarfuncc                 C  s
   |  tS ra   )r  rZ  rr  r_   r_   r`   __int__  s    zArray.__int__c                 C  s
   |  tS ra   )r  floatrr  r_   r_   r`   	__float__  s    zArray.__float__c                 C  s
   |  tS ra   )r  complexrr  r_   r_   r`   __complex__  s    zArray.__complex__c                 C  s   |  tjS ra   )r  operatorr  rr  r_   r_   r`   	__index__   s    zArray.__index__c           
   
   C  s^  |t jju rt jd}t|trddlm} t|trJ|jdkrJt	dz|||| }W n. t	y } zt	d|W Y d }~n
d }~0 0 |j
| _
|j| _|j| _|j| _d S t | j rt	dt t|}dt| || }t|| ||}t| j
}t |rt |}tj||| gd}	t|	|| j| j|d	}|j
| _
|j| _|j| _|j| _d S )
Nr_   rK   wherez+boolean index array should have 1 dimensionzBoolean index assignment in Dask expects equally shaped arrays.
Example: da1[da2] = da3 where da1.shape == (4,), da2.shape == (4,) and da3.shape == (4,).z Arrays chunk sizes are unknown. zsetitem-rd  )r   r   r   )rp   ZmaZmaskedZ
masked_allrg   r   r  r  r   r   rb  rI  r   ri  r   rj  rX  r   rm   rY  
asanyarrayr)   rV   r   isscalarrX   r1   r   r   )
r   r   valuer  yr   r&  r}  r   graphr_   r_   r`   __setitem__  sB    


zArray.__setitem__c                   s   t |ts*t |tr|rtdd |D rt |tr@ j| }n4t| fdd|D  fdd|D  jjd}|jrtt j	 j	t
|j } jtdd |jD  } jt||j||dS  jt||d	S t |ts|f}d
dlm}m}m} || j} jh}	|D ]}
t |
tr|	|
j qtdd |D rT| |\ }tdd |D rv| |\ }tdd |D r S dt | }t| j j| j\}}tj|| gd}t jt
|d}t|rt|}t||||dS )Nc                 s  s   | ]}t |tV  qd S ra   re  r  r_   r_   r`   re   5  rf   z$Array.__getitem__.<locals>.<genexpr>c                   s   g | ]} j j| d  qS rU  r   fieldsrc   r   rr  r_   r`   r   =  rf   z%Array.__getitem__.<locals>.<listcomp>c                   s   g | ]} j j| d  qS r   r  r  rr  r_   r`   r   >  rf   )namesformatsZoffsetsr  c                 s  s   | ]}|fV  qd S ra   r_   r  r_   r_   r`   re   E  rf   r  r   rK   )normalize_indexslice_with_bool_dask_arrayslice_with_int_dask_arrayc                 s  s$   | ]}t |to|jjd v V  qdS )iuN)rg   r   r   kindr  r_   r_   r`   re   [  rf   c                 s  s"   | ]}t |to|jtkV  qd S ra   )rg   r   r   r   r  r_   r_   r`   re   ]  rf   c                 s  s$   | ]}t |to|td kV  qd S ra   rg   rh   r  r_   r_   r`   re   `  rf   zgetitem-rd  r  rK  ) rg   r   r   r   r   rp   r  r   r   r   r   r   rl   r  rM   baseslicingr  r  r  r   r   r   rm   r)   rW   r1   r   r   rb  r  rX   )r   r  ro  r   r   r  r  r  index2rS  r  r&  r}  r  r   r_   rr  r`   __getitem__2  sX    

	

zArray.__getitem__c                 C  s~   t |ts|f}tdd |D r0td|tdd |D rntdd t|| jD r`| S td|t| g|R  S )Nc                 s  s   | ]}|d u V  qd S ra   r_   rF  r_   r_   r`   re   q  rf   z Array._vindex.<locals>.<genexpr>z?vindex does not support indexing with None (np.newaxis), got {}c                 s  s   | ]}t |tV  qd S ra   r  rF  r_   r_   r`   re   v  rf   c                 s  s,   | ]$\}}| |td | |kV  qdS r   N)indicesrh   )rc   r   rV  r_   r_   r`   re   w  s   zvindex requires at least one non-slice to vectorize over when the slices are not over the entire array (i.e, x[:]). Use normal slicing instead when only using slices. Got: {})	rg   rl   rm   
IndexErrorr   r   r   r   _vindexr  r_   r_   r`   r  n  s&    

zArray._vindexc                 C  s
   t | jS )al  Vectorized indexing with broadcasting.

        This is equivalent to numpy's advanced indexing, using arrays that are
        broadcast against each other. This allows for pointwise indexing:

        >>> import dask.array as da
        >>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> x = da.from_array(x, chunks=2)
        >>> x.vindex[[0, 1, 2], [0, 1, 2]].compute()
        array([1, 5, 9])

        Mixed basic/advanced indexing with slices/arrays is also supported. The
        order of dimensions in the result follows those proposed for
        `ndarray.vindex <https://github.com/numpy/numpy/pull/6256>`_:
        the subspace spanned by arrays is followed by all slices.

        Note: ``vindex`` provides more general functionality than standard
        indexing, but it also has fewer optimizations and can be significantly
        slower.
        )r6   r  rr  r_   r_   r`   vindex  s    zArray.vindexc                 C  s   t | S )a@  An array-like interface to the blocks of an array.

        This returns a ``Blockview`` object that provides an array-like interface
        to the blocks of a dask array.  Numpy-style indexing of a ``Blockview`` object
        returns a selection of blocks as a new dask array.

        You can index ``array.blocks`` like a numpy array of shape
        equal to the number of blocks in each dimension, (available as
        array.blocks.size).  The dimensionality of the output array matches
        the dimension of this array, even if integer indices are passed.
        Slicing with ``np.newaxis`` or multiple lists is not supported.

        Examples
        --------
        >>> import dask.array as da
        >>> x = da.arange(8, chunks=2)
        >>> x.blocks.shape # aliases x.numblocks
        (4,)
        >>> x.blocks[0].compute()
        array([0, 1])
        >>> x.blocks[:3].compute()
        array([0, 1, 2, 3, 4, 5])
        >>> x.blocks[::2].compute()
        array([0, 1, 4, 5])
        >>> x.blocks[[-1, 0]].compute()
        array([6, 7, 0, 1])
        >>> x.blocks.ravel() # doctest: +NORMALIZE_WHITESPACE
        [dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>]

        Returns
        -------
        An instance of ``dask.array.Blockview``
        )	BlockViewrr  r_   r_   r`   blocks  s    &zArray.blocksc                 C  s   | j S )a  Slice an array by partitions. Alias of dask array .blocks attribute.

        This alias allows you to write agnostic code that works with both
        dask arrays and dask dataframes.

        This returns a ``Blockview`` object that provides an array-like interface
        to the blocks of a dask array.  Numpy-style indexing of a ``Blockview`` object
        returns a selection of blocks as a new dask array.

        You can index ``array.blocks`` like a numpy array of shape
        equal to the number of blocks in each dimension, (available as
        array.blocks.size).  The dimensionality of the output array matches
        the dimension of this array, even if integer indices are passed.
        Slicing with ``np.newaxis`` or multiple lists is not supported.

        Examples
        --------
        >>> import dask.array as da
        >>> x = da.arange(8, chunks=2)
        >>> x.partitions.shape # aliases x.numblocks
        (4,)
        >>> x.partitions[0].compute()
        array([0, 1])
        >>> x.partitions[:3].compute()
        array([0, 1, 2, 3, 4, 5])
        >>> x.partitions[::2].compute()
        array([0, 1, 4, 5])
        >>> x.partitions[[-1, 0]].compute()
        array([6, 7, 0, 1])
        >>> x.partitions.ravel() # doctest: +NORMALIZE_WHITESPACE
        [dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
         dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>]

        Returns
        -------
        An instance of ``da.array.Blockview``
        )r  rr  r_   r_   r`   
partitions  s    )zArray.partitionsc                 C  s.   ddl m} || || jd f|jd ffdS )NrK   )	tensordotr   r   )r  r  r   )r   r   r  r_   r_   r`   r     s    z	Array.dotc                 C  s   | S ra   r_   rr  r_   r_   r`   r     s    zArray.Ac                 C  s   |   S ra   	transposerr  r_   r_   r`   T  s    zArray.Tc                 G  st   ddl m} |sd }n"t|dkr8t|d tr8|d }|tt| jks`|tt| j dkrd| S || |dS d S )NrK   r  r   r   )r  r  r   rg   r   rl   r   r   )r   r   r  r_   r_   r`   r    s    (zArray.transposec                 C  s   ddl m} || S )NrK   )ravel)r  r  )r   r  r_   r_   r`   r  	  s    zArray.ravelc                 C  s   ddl m} || |S )NrK   )choose)r  r  )r   choicesr  r_   r_   r`   r    s    zArray.chooseTmerge_chunkslimitc                G  s>   ddl m } t|dkr.t|d ts.|d }|| |||dS )z
        .. note::

           See :meth:`dask.array.reshape` for an explanation of
           the ``merge_chunks`` and `limit` keywords.
        rK   )reshaper   r  )r  r   rg   r   )r   r  r  r   r  r_   r_   r`   r    s    zArray.reshaper   c                 C  s   ddl m} || |||dS )z]The top k elements of an array.

        See :func:`dask.array.topk` for docstring.

        rK   )topkr   split_every)
reductionsr  )r   r   r   r  r  r_   r_   r`   r  %  s    z
Array.topkc                 C  s   ddl m} || |||dS )zoThe indices of the top k elements of an array.

        See :func:`dask.array.argtopk` for docstring.

        rK   )argtopkr  )r  r  )r   r   r   r  r  r_   r_   r`   r  /  s    zArray.argtopkc                 K  s   t |ddh }|r&tdt| |dd}t|}| j|krJ| S tj| j||dsxtd| jd|d|| jtj	f||d	|S )
a  Copy of the array, cast to a specified type.

        Parameters
        ----------
        dtype : str or dtype
            Typecode or data-type to which the array is cast.
        casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
            Controls what kind of data casting may occur. Defaults to 'unsafe'
            for backwards compatibility.

            * 'no' means the data types should not be cast at all.
            * 'equiv' means only byte-order changes are allowed.
            * 'safe' means only casts which can preserve values are allowed.
            * 'same_kind' means only safe casts or casts within a kind,
                like float64 to float32, are allowed.
            * 'unsafe' means any data conversions may be done.
        copy : bool, optional
            By default, astype always returns a newly allocated array. If this
            is set to False and the `dtype` requirement is satisfied, the input
            array is returned instead of a copy.
        castingcopyz6astype does not take the following keyword arguments: Zunsafer  zCannot cast array from z to z according to the rule )r   Zastype_dtype)
r   r(  r   r  rp   r   can_castr  rL   r  )r   r   r   Zextrar  r_   r_   r`   r  9  s     

zArray.astypec                 C  s   t tj| S ra   )r  r  absrr  r_   r_   r`   __abs__a  s    zArray.__abs__c                 C  s   t tj| |S ra   r  r  r   r   r_   r_   r`   __add__d  s    zArray.__add__c                 C  s   t tj|| S ra   r  r   r_   r_   r`   __radd__h  s    zArray.__radd__c                 C  s   t tj| |S ra   r  r  and_r   r_   r_   r`   __and__l  s    zArray.__and__c                 C  s   t tj|| S ra   r  r   r_   r_   r`   __rand__p  s    zArray.__rand__c                 C  s   t tj| |S ra   r  r  Zdivr   r_   r_   r`   __div__t  s    zArray.__div__c                 C  s   t tj|| S ra   r  r   r_   r_   r`   __rdiv__x  s    zArray.__rdiv__c                 C  s   t tj| |S ra   )r  r  eqr   r_   r_   r`   __eq__|  s    zArray.__eq__c                 C  s   t tj| |S ra   )r  r  gtr   r_   r_   r`   __gt__  s    zArray.__gt__c                 C  s   t tj| |S ra   )r  r  ger   r_   r_   r`   __ge__  s    zArray.__ge__c                 C  s   t tj| S ra   )r  r  invertrr  r_   r_   r`   
__invert__  s    zArray.__invert__c                 C  s   t tj| |S ra   r  r  lshiftr   r_   r_   r`   
__lshift__  s    zArray.__lshift__c                 C  s   t tj|| S ra   r  r   r_   r_   r`   __rlshift__  s    zArray.__rlshift__c                 C  s   t tj| |S ra   )r  r  ltr   r_   r_   r`   __lt__  s    zArray.__lt__c                 C  s   t tj| |S ra   )r  r  ler   r_   r_   r`   __le__  s    zArray.__le__c                 C  s   t tj| |S ra   r  r  modr   r_   r_   r`   __mod__  s    zArray.__mod__c                 C  s   t tj|| S ra   r  r   r_   r_   r`   __rmod__  s    zArray.__rmod__c                 C  s   t tj| |S ra   r  r  r   r   r_   r_   r`   __mul__  s    zArray.__mul__c                 C  s   t tj|| S ra   r"  r   r_   r_   r`   __rmul__  s    zArray.__rmul__c                 C  s   t tj| |S ra   )r  r  ner   r_   r_   r`   __ne__  s    zArray.__ne__c                 C  s   t tj| S ra   )r  r  negrr  r_   r_   r`   __neg__  s    zArray.__neg__c                 C  s   t tj| |S ra   r  r  or_r   r_   r_   r`   __or__  s    zArray.__or__c                 C  s   | S ra   r_   rr  r_   r_   r`   __pos__  s    zArray.__pos__c                 C  s   t tj|| S ra   r)  r   r_   r_   r`   __ror__  s    zArray.__ror__c                 C  s   t tj| |S ra   r  r  powr   r_   r_   r`   __pow__  s    zArray.__pow__c                 C  s   t tj|| S ra   r.  r   r_   r_   r`   __rpow__  s    zArray.__rpow__c                 C  s   t tj| |S ra   r  r  rshiftr   r_   r_   r`   
__rshift__  s    zArray.__rshift__c                 C  s   t tj|| S ra   r2  r   r_   r_   r`   __rrshift__  s    zArray.__rrshift__c                 C  s   t tj| |S ra   r  r  subr   r_   r_   r`   __sub__  s    zArray.__sub__c                 C  s   t tj|| S ra   r6  r   r_   r_   r`   __rsub__  s    zArray.__rsub__c                 C  s   t tj| |S ra   r  r  truedivr   r_   r_   r`   __truediv__  s    zArray.__truediv__c                 C  s   t tj|| S ra   r:  r   r_   r_   r`   __rtruediv__  s    zArray.__rtruediv__c                 C  s   t tj| |S ra   r  r  floordivr   r_   r_   r`   __floordiv__  s    zArray.__floordiv__c                 C  s   t tj|| S ra   r>  r   r_   r_   r`   __rfloordiv__  s    zArray.__rfloordiv__c                 C  s   t tj| |S ra   r  r  xorr   r_   r_   r`   __xor__  s    zArray.__xor__c                 C  s   t tj|| S ra   rB  r   r_   r_   r`   __rxor__  s    zArray.__rxor__c                 C  s   ddl m} || |S NrK   r  r  r  r   r   r  r_   r_   r`   
__matmul__  s    zArray.__matmul__c                 C  s   ddl m} ||| S rF  rG  rH  r_   r_   r`   __rmatmul__  s    zArray.__rmatmul__c                 C  s   ddl m} || |S NrK   )divmodr  rL  r   r   rL  r_   r_   r`   
__divmod__  s    zArray.__divmod__c                 C  s   ddl m} ||| S rK  rM  rN  r_   r_   r`   __rdivmod__  s    zArray.__rdivmod__Fc                 C  s   ddl m} || ||||dS )NrK   )rm   r   keepdimsr  r&  )r  rm   )r   r   rR  r  r&  rm   r_   r_   r`   rm   	  s    z	Array.anyc                 C  s   ddl m} || ||||dS )NrK   r   rQ  )r  r   )r   r   rR  r  r&  r   r_   r_   r`   r   	  s    z	Array.allc                 C  s   ddl m} || ||||dS )NrK   )minrQ  )r  rS  )r   r   rR  r  r&  rS  r_   r_   r`   rS  	  s    z	Array.minc                 C  s   ddl m} || ||||dS )NrK   r  rQ  )r  r   )r   r   rR  r  r&  r   r_   r_   r`   r   	  s    z	Array.maxc                 C  s   ddl m} || |||dS )NrK   )argminr   r  r&  )r  rT  )r   r   r  r&  rT  r_   r_   r`   rT  	  s    zArray.argminc                 C  s   ddl m} || |||dS )NrK   )argmaxrU  )r  rV  )r   r   r  r&  rV  r_   r_   r`   rV  #	  s    zArray.argmaxc                 C  s    ddl m} || |||||dS )NrK   r   r   r   rR  r  r&  )r  r   )r   r   r   rR  r  r&  r   r_   r_   r`   r   )	  s    z	Array.sumr   rK   c                 C  s   ddl m} || ||||dS )NrK   )trace)offsetaxis1axis2r   )r  rY  )r   rZ  r[  r\  r   rY  r_   r_   r`   rY  6	  s    zArray.tracec                 C  s    ddl m} || |||||dS )NrK   )r  rX  )r  r  )r   r   r   rR  r  r&  r  r_   r_   r`   r  <	  s    z
Array.prodc                 C  s    ddl m} || |||||dS )NrK   )meanrX  )r  r]  )r   r   r   rR  r  r&  r]  r_   r_   r`   r]  I	  s    z
Array.meanc              	   C  s"   ddl m} || ||||||dS )NrK   )stdr   r   rR  ddofr  r&  )r  r^  )r   r   r   rR  r`  r  r&  r^  r_   r_   r`   r^  V	  s    z	Array.stdc              	   C  s"   ddl m} || ||||||dS )NrK   )varr_  )r  ra  )r   r   r   rR  r`  r  r&  ra  r_   r_   r`   ra  f	  s    z	Array.varc           	   
   C  s$   ddl m} || |||||||dS )aC  Calculate the nth centralized moment.

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

        Returns
        -------
        moment : ndarray

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

        rK   )momentr_  )r  rb  )	r   orderr   r   rR  r`  r  r&  rb  r_   r_   r`   rb  v	  s    ,zArray.momentc                 O  s   t || g|R i |S ra   )r  )r   r   r   r   r_   r_   r`   r  	  s    zArray.map_blocksc                 K  s&   ddl m} ||| f|||d|S )a  Map a function over blocks of the array with some overlap

        We share neighboring zones between blocks of the array, then map a
        function, then trim away the neighboring strips.

        Note that this function will attempt to automatically determine the output
        array type before computing it, please refer to the ``meta`` keyword argument
        in :func:`map_blocks <dask.array.core.map_blocks>` if you expect that the function will not succeed when
        operating on 0-d arrays.

        Parameters
        ----------
        func: function
            The function to apply to each extended block
        depth: int, tuple, or dict
            The number of elements that each block should share with its neighbors
            If a tuple or dict then this can be different per axis
        boundary: str, tuple, dict
            How to handle the boundaries.
            Values include 'reflect', 'periodic', 'nearest', 'none',
            or any constant value like 0 or np.nan
        trim: bool
            Whether or not to trim ``depth`` elements from each block after
            calling the map function.
            Set this to False if your mapping function already does this for you
        **kwargs:
            Other keyword arguments valid in :func:`map_blocks <dask.array.core.map_blocks>`.

        Examples
        --------
        >>> import dask.array as da
        >>> x = np.array([1, 1, 2, 3, 3, 3, 2, 1, 1])
        >>> x = da.from_array(x, chunks=5)
        >>> def derivative(x):
        ...     return x - np.roll(x, 1)

        >>> y = x.map_overlap(derivative, depth=1, boundary=0)
        >>> y.compute()
        array([ 1,  0,  1,  1,  0,  0, -1, -1,  0])

        >>> import dask.array as da
        >>> x = np.arange(16).reshape((4, 4))
        >>> d = da.from_array(x, chunks=(2, 2))
        >>> y = d.map_overlap(lambda x: x + x.size, depth=1, boundary='reflect')
        >>> y.compute()
        array([[16, 17, 18, 19],
               [20, 21, 22, 23],
               [24, 25, 26, 27],
               [28, 29, 30, 31]])

        >>> func = lambda x: x + x.size
        >>> depth = {0: 1, 1: 1}
        >>> boundary = {0: 'reflect', 1: 'none'}
        >>> d.map_overlap(func, depth, boundary).compute()  # doctest: +NORMALIZE_WHITESPACE
        array([[12,  13,  14,  15],
               [16,  17,  18,  19],
               [20,  21,  22,  23],
               [24,  25,  26,  27]])

        >>> x = np.arange(16).reshape((4, 4))
        >>> d = da.from_array(x, chunks=(2, 2))
        >>> y = d.map_overlap(lambda x: x + x[2], depth=1, boundary='reflect', meta=np.array(()))
        >>> y
        dask.array<_trim, shape=(4, 4), dtype=float64, chunksize=(2, 2), chunktype=numpy.ndarray>
        >>> y.compute()
        array([[ 4,  6,  8, 10],
               [ 8, 10, 12, 14],
               [20, 22, 24, 26],
               [24, 26, 28, 30]])

        >>> import cupy  # doctest: +SKIP
        >>> x = cupy.arange(16).reshape((4, 4))  # doctest: +SKIP
        >>> d = da.from_array(x, chunks=(2, 2))  # doctest: +SKIP
        >>> y = d.map_overlap(lambda x: x + x[2], depth=1, boundary='reflect', meta=cupy.array(()))  # doctest: +SKIP
        >>> y  # doctest: +SKIP
        dask.array<_trim, shape=(4, 4), dtype=float64, chunksize=(2, 2), chunktype=cupy.ndarray>
        >>> y.compute()  # doctest: +SKIP
        array([[ 4,  6,  8, 10],
               [ 8, 10, 12, 14],
               [20, 22, 24, 26],
               [24, 26, 28, 30]])
        rK   )map_overlap)depthboundarytrim)Zoverlaprd  )r   r   re  rf  rg  r   rd  r_   r_   r`   rd  	  s    SzArray.map_overlapZ
sequential)r  c                C  s   ddl m} || ||||dS )a  Dask added an additional keyword-only argument ``method``.

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

            * 'sequential' performs the cumsum of each prior block before the current block.
            * 'blelloch' is a work-efficient parallel cumsum.  It exposes parallelism by
              first taking the sum of each block and combines the sums via a binary tree.
              This method may be faster or more memory efficient depending on workload,
              scheduler, and hardware.  More benchmarking is necessary.
        rK   )cumsumr&  r  )r  rh  )r   r   r   r&  r  rh  r_   r_   r`   rh  
  s    zArray.cumsumc                C  s   ddl m} || ||||dS )a  Dask added an additional keyword-only argument ``method``.

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

            * 'sequential' performs the cumprod of each prior block before the current block.
            * 'blelloch' is a work-efficient parallel cumprod.  It exposes parallelism by first
              taking the product of each block and combines the products via a binary tree.
              This method may be faster or more memory efficient depending on workload,
              scheduler, and hardware.  More benchmarking is necessary.
        rK   )cumprodri  )r  rj  )r   r   r   r&  r  rj  r_   r_   r`   rj  
  s    zArray.cumprodc                 C  s   ddl m} || |S )NrK   )squeeze)r  rk  )r   r   rk  r_   r_   r`   rk  .
  s    zArray.squeezeautoc                 C  s   ddl m } || ||||S )zSee da.rechunk for docstringrK   rechunkrm  )r   r   Z	thresholdZblock_size_limitZbalancern  r_   r_   r`   rn  4
  s    zArray.rechunkc                 C  s   ddl m} || S )NrK   )real)r  ro  )r   ro  r_   r_   r`   ro  <
  s    z
Array.realc                 C  s   ddl m} || S )NrK   )imag)r  rp  )r   rp  r_   r_   r`   rp  B
  s    z
Array.imagc                 C  s   ddl m} || S )NrK   )conj)r  rq  )r   rq  r_   r_   r`   rq  H
  s    z
Array.conjc                 C  s   ddl m} || ||S )NrK   )clip)r  rr  )r   rS  r   rr  r_   r_   r`   rr  M
  s    z
Array.clipCc                   s   |du r| j }n
t |}| j j|j  |dkr^| jdd t fdd| jd D f }n>|dkrt fdd| jd D f| jd	d  }ntd
| jtj||||dS )a@  Get a view of the array as a new data type

        Parameters
        ----------
        dtype:
            The dtype by which to view the array.
            The default, None, results in the view having the same data-type
            as the original array.
        order: string
            'C' or 'F' (Fortran) ordering

        This reinterprets the bytes of the array under a new dtype.  If that
        dtype does not have the same size as the original array then the shape
        will change.

        Beware that both numpy and dask.array can behave oddly when taking
        shape-changing views of arrays under Fortran ordering.  Under some
        versions of NumPy this function will fail when taking shape-changing
        views of Fortran ordered arrays if the first dimension has chunks of
        size one.
        Nrs  r   c                 3  s   | ]}t |  V  qd S ra   
ensure_intr  Zmultr_   r`   re   q
  rf   zArray.view.<locals>.<genexpr>Fc                 3  s   | ]}t |  V  qd S ra   rt  r  rv  r_   r`   re   u
  rf   r   rK   zOrder must be one of 'C' or 'F')rc  r   r   )	r   rp   r  r   rl   r   r  rL   view)r   r   rc  r   r_   rv  r`   rx  S
  s"    
z
Array.viewc                 C  s   ddl m} || ||S )NrK   )swapaxes)r  ry  )r   r[  r\  ry  r_   r_   r`   ry  ~
  s    zArray.swapaxesc                 C  s   ddl m} || |dS )NrK   )round)decimals)r  rz  )r   r{  rz  r_   r_   r`   rz  
  s    zArray.roundc                 C  s0   | j dkr| tjS t| j| j| j| dS dS )zS
        Copy array.  This is a no-op for dask.arrays, which are immutable
        rK   rK  N)r  r  r7   r  r   rI  r   r   rr  r_   r_   r`   r  
  s    
z
Array.copyc                 C  s   |   }||t| < |S ra   )r  r?  )r   memoru   r_   r_   r`   __deepcopy__
  s    zArray.__deepcopy__c                   sl   |   }|   |  d |rF|  | d| j tj dd t| j fdd|}t	j
|tdS )ai  Convert into an array of :class:`dask.delayed.Delayed` objects, one per chunk.

        Parameters
        ----------
        optimize_graph : bool, optional
            If True [default], the graph is optimized before converting into
            :class:`dask.delayed.Delayed` objects.

        See Also
        --------
        dask.array.from_delayed
        r   zdelayed-r_   rd  c                   s   t |  dS )NrD  rE  r   r  r   r_   r`   r   
  rf   z"Array.to_delayed.<locals>.<lambda>r   )r>  r=  ru  rN  r   r1   r   rF   r   rp   rX   r  )r   Zoptimize_graphr   Lr_   r~  r`   
to_delayed
  s    
zArray.to_delayedc                 C  s   ddl m} || ||dS )NrK   )repeatr   )Zcreationr  )r   Zrepeatsr   r  r_   r_   r`   r  
  s    zArray.repeatc                 C  s   ddl m} || S )NrK   )nonzero)r  r  )r   r  r_   r_   r`   r  
  s    zArray.nonzeroc                 O  s   t | g|R i |S )zSave array to the zarr storage format

        See https://zarr.readthedocs.io for details about the format.

        See function :func:`dask.array.to_zarr` for parameters.
        )to_zarr)r   r   r   r_   r_   r`   r  
  s    zArray.to_zarrc                 O  s$   ddl m} || |g|R i |S )zSave array to the TileDB storage manager

        See function :func:`dask.array.to_tiledb` for argument documentation.

        See https://docs.tiledb.io for details about the format and engine.
        rK   )	to_tiledb)Z	tiledb_ior  )r   Zurir   r   r  r_   r_   r`   r  
  s    zArray.to_tiledb)NNN)N)N)r  )NNN)r   N)r   N)NFNN)NFNN)NFNN)NFNN)NNN)NNN)NNFNN)r   r   rK   N)NNFNN)NNFNN)NNFr   NN)NNFr   NN)NNFr   NN)NT)NN)NN)N)rl  NNF)NN)Nrs  )r   )T)N)r[   r\   r]   r^   	__slots__rh  rs  r=  ru  r>  rw  r,   r{   r&   rN  staticmethodr#   r  Z__dask_scheduler__ry  r{  rz  r  r:   r  r   r  r  r   propertyrf  r   rj  setterr   r  r   r  r  r   r  r  r  ri  r   r  r   r  r  r  r   rT  r  r  r  r  Z__nonzero__r  r  Z__long__r  r  r  r  r  r  r  r  r  r<   rp   r  r   r   r  r  r  rO  r  r  r  r  r  r  r   r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r   r!  r#  r$  r&  r(  r+  r,  r-  r0  r1  r4  r5  r8  r9  r<  r=  r@  rA  rD  rE  rI  rJ  rO  rP  rm   r   rS  r   rT  rV  r   rY  r  r]  r^  ra  rb  r  rd  rh  rj  rk  rn  ro  rp  rq  rr  rx  ry  rz  r  r}  r  r  r  r  r  __classcell__r_   r_   rp  r`   r     s  <



1






	'







2

	/<

'
*







(



































     
9
Y+		r   c                 C  s    t | }|| krtd|  |S )NzCould not coerce %f to integer)rZ  r   )r   r  r_   r_   r`   ru  
  s    ru  c                   s  |rt |tjst|} du r*ttt  tr<t  t  ttfrX ft	|  t  t
rt fddtt	|D  t  tjr    s|rtdd |D rdt	|  |rt	|dkrt	 dkrtdd  D r f |rt	 t	|krtd |f d	 v s*d v rBtd
d t |D   D ]N}t |trF|dkrFt|}|du rx|}n||krFtd||f qFtdd  D  tdd  D rt |||| |durtdd t |D   r|durtdd t| D d  D ]}|stdq|durt	 t	|krftdt	|t	 f tdd ttt |D std |f tdd  D S )a>	  Normalize chunks to tuple of tuples

    This takes in a variety of input types and information and produces a full
    tuple-of-tuples result for chunks, suitable to be passed to Array or
    rechunk or any other operation that creates a Dask array.

    Parameters
    ----------
    chunks: tuple, int, dict, or string
        The chunks to be normalized.  See examples below for more details
    shape: Tuple[int]
        The shape of the array
    limit: int (optional)
        The maximum block size to target in bytes,
        if freedom is given to choose
    dtype: np.dtype
    previous_chunks: Tuple[Tuple[int]] optional
        Chunks from a previous array that we should use for inspiration when
        rechunking auto dimensions.  If not provided but auto-chunking exists
        then auto-dimensions will prefer square-like chunk shapes.

    Examples
    --------
    Specify uniform chunk sizes

    >>> from dask.array.core import normalize_chunks
    >>> normalize_chunks((2, 2), shape=(5, 6))
    ((2, 2, 1), (2, 2, 2))

    Also passes through fully explicit tuple-of-tuples

    >>> normalize_chunks(((2, 2, 1), (2, 2, 2)), shape=(5, 6))
    ((2, 2, 1), (2, 2, 2))

    Cleans up lists to tuples

    >>> normalize_chunks([[2, 2], [3, 3]])
    ((2, 2), (3, 3))

    Expands integer inputs 10 -> (10, 10)

    >>> normalize_chunks(10, shape=(30, 5))
    ((10, 10, 10), (5,))

    Expands dict inputs

    >>> normalize_chunks({0: 2, 1: 3}, shape=(6, 6))
    ((2, 2, 2), (3, 3))

    The values -1 and None get mapped to full size

    >>> normalize_chunks((5, -1), shape=(10, 10))
    ((5, 5), (10,))

    Use the value "auto" to automatically determine chunk sizes along certain
    dimensions.  This uses the ``limit=`` and ``dtype=`` keywords to
    determine how large to make the chunks.  The term "auto" can be used
    anywhere an integer can be used.  See array chunking documentation for more
    information.

    >>> normalize_chunks(("auto",), shape=(20,), limit=5, dtype='uint8')
    ((5, 5, 5, 5),)

    You can also use byte sizes (see :func:`dask.utils.parse_bytes`) in place of
    "auto" to ask for a particular size

    >>> normalize_chunks("1kiB", shape=(2000,), dtype='float32')
    ((250, 250, 250, 250, 250, 250, 250, 250),)

    Respects null dimensions

    >>> normalize_chunks((), shape=(0, 0))
    ((0,), (0,))
    Nc                 3  s   | ]}  |d V  qd S ra   r  r  r$  r_   r`   re   +  rf   z#normalize_chunks.<locals>.<genexpr>c                 s  s   | ]}|d kV  qdS r  r_   r  r_   r_   r`   re   .  rf   rU  rK   c                 s  s   | ]}t |ttfV  qd S ra   )rg   r   r   r  r_   r_   r`   re   5  rf   zNChunks and shape must be of the same length/dimension. Got chunks=%s, shape=%sr   c                 s  s*   | ]"\}}|d ks|du r|n|V  qdS r   Nr_   rc   ru   r   r_   r_   r`   re   ?  rf   rl  zDOnly one consistent value of limit or chunk is allowed.Used %s != %sc                 s  s(   | ] }t |tr|d krd n|V  qdS rl  Nre  r  r_   r_   r`   re   N  rf   c                 s  s   | ]}|d kV  qdS r  r_   r  r_   r_   r`   re   P  rf   c                 s  s"   | ]\}}|d vr|n|V  qdS )>   Nr   Nr_   r  r_   r_   r`   re   T  rf   c                 s  s4   | ],\}}t |ttfs&t|f|fn|fV  qd S ra   )rg   rl   r   r\  )rc   r   ru   r_   r_   r`   re   X  s   r_   zZEmpty tuples are not allowed in chunks. Express zero length dimensions with 0(s) in chunkszLInput array has %d dimensions but the supplied chunks has only %d dimensionsc                 s  s.   | ]&\}}||kp$t |p$t |V  qd S ra   )r  rX  r  r_   r_   r`   re   m  s   z6Chunks do not add up to shape. Got chunks=%s, shape=%sc                 s  s    | ]}t d d |D V  qdS )c                 s  s$   | ]}t |st|n|V  qd S ra   )r  rX  rZ  rb   r_   r_   r`   re   v  rf   z-normalize_chunks.<locals>.<genexpr>.<genexpr>Nr  r  r_   r_   r`   re   v  rf   )rg   rp   r   r   rk  r   rl   r   r   r   r   r   r  tolistr   r   rH   rm   auto_chunksr   r   )r   r   r  r   previous_chunksru   parsedr_   r$  r`   r   
  s    K







	

r   rZ  )r  largest_blockc                 C  s*   | |j  | ttdd | D  S )z
    Utility function for auto_chunk, to fin how much larger or smaller the ideal
    chunk size is relative to what we have now.
    c                 s  s   | ]}|d kr|ndV  qdS r   rK   Nr_   )rc   rA  r_   r_   r`   re     rf   z&_compute_multiplier.<locals>.<genexpr>)r  rp   r  r   values)r  r   r  r8  r_   r_   r`   _compute_multipliery  s    r  c                   s   durt dd  D  t| } dd t| D }|s@t | S |du rRtd}t|trdt|}|du rttd|j	rt
dt | t  D ]<}t|trt|st|t rt| rtd	t qtd
|}tdd | D } rr fdd|D }g }	tD ]d\}
}t |
 }t| dd d\}}|d
krj|t |
 d krj|	| n
|	| qt||||}d}t }||ks||krN|}t|}t|D ]}|	| dkrd||< q|| |d
t|   }|| kr&|| || 9 }| | |< ||= nt||	| ||< qt||||}q| D ]\}}|| |< qVt | S ||j | d
t|  fdd|D }|r|D ]}
|
 f| |
< qt| ||S |D ]}
t|
 | |
< qt | S dS )ad  Determine automatic chunks

    This takes in a chunks value that contains ``"auto"`` values in certain
    dimensions and replaces those values with concrete dimension sizes that try
    to get chunks to be of a certain size in bytes, provided by the ``limit=``
    keyword.  If multiple dimensions are marked as ``"auto"`` then they will
    all respond to meet the desired byte limit, trying to respect the aspect
    ratio of their dimensions in ``previous_chunks=``, if given.

    Parameters
    ----------
    chunks: Tuple
        A tuple of either dimensions or tuples of explicit chunk dimensions
        Some entries should be "auto"
    shape: Tuple[int]
    limit: int, str
        The maximum allowable size of a chunk in bytes
    previous_chunks: Tuple[Tuple[int]]

    See also
    --------
    normalize_chunks: for full docstring and parameters
    Nc                 s  s"   | ]}t |tr|n|fV  qd S ra   )rg   rl   r  r_   r_   r`   re     s   zauto_chunks.<locals>.<genexpr>c                 S  s   h | ]\}}|d kr|qS rl  r_   rc   r  ru   r_   r_   r`   	<setcomp>  rf   zauto_chunks.<locals>.<setcomp>zarray.chunk-sizez%dtype must be known for auto-chunkingziCan not use auto rechunking with object dtype. We are unable to estimate the size in bytes of object datazFCan not perform automatic rechunking with unknown (nan) chunk sizes.%srK   c                 S  s*   g | ]"}|d krt |tr|nt|qS r  )rg   r   r   )rc   csr_   r_   r`   r     rf   zauto_chunks.<locals>.<listcomp>c                   s   i | ]}|t  | qS r_   )rp   Zmedianr   )r  r_   r`   r    rf   zauto_chunks.<locals>.<dictcomp>c                 S  s   | d S r  r_   )Zkvr_   r_   r`   r     rf   zauto_chunks.<locals>.<lambda>r   r   r   c                   s   g | ]} | k r|qS r_   r_   r  )r   r  r_   r`   r     rf   )rl   r   r-  r!   r  rg   r   rH   r(  Z	hasobjectr  r   rp   rX  rm   r   rY  r   r  r   r1  r   r0  r  r   r.  removeround_tor  r  )r   r   r  r   r  Zautosrd   r  r8  Zideal_shaper  r   Zchunk_frequenciesmodecountZ
multiplierZlast_multiplierZ
last_autosrr   Zproposedr   vZsmallr_   )r  r   r  r`   r    s    


 
r  c                   sX    |krHzt  fddt|D W S  tyD   t dt  Y S 0 n | | S dS )a  Return a chunk dimension that is close to an even multiple or factor

    We want values for c that are nicely aligned with s.

    If c is smaller than s then we want the largest factor of s that is less than the
    desired chunk size, but not less than half, which is too much.  If no such
    factor exists then we just go with the original chunk size and accept an
    uneven chunk at the end.

    If c is larger than s then we want the largest multiple of s that is still
    smaller than c.
    c                 3  s.   | ]&} d  |  kr krn q|V  qdS )r   Nr_   )rc   r   ru   r_   r`   re     rf   zround_to.<locals>.<genexpr>rK   N)r   r=   r   rZ  )ru   r   r_   r  r`   r    s    r  c                 C  s*   t j| jtd}|t|d td f  S )Nr   ra   )rp   rj   r   rZ  r   rh   )rr   r   r_   r_   r`   r    s    r  rl  c	                   s  t  trtdnt r&td t  tttft	j
 rFt	  |du rZt d }t dd}	t| j j|	d}|dv rt ||||||}
|pd|
 }n|d	u rdtt  }|d
u rt }t t	ju }tdd |D }|rB|sB|sBt|}t|ggdd |D R  } fdd|D }tt||}nZ|rd|rd|fd j   i}n8|du r~|rzt}nt}t  | j|||| j|d	} j!j"#dd dkrt drt||| jdS |du r }t||||t dddS )a  Create dask array from something that looks like an array.

    Input must have a ``.shape``, ``.ndim``, ``.dtype`` and support numpy-style slicing.

    Parameters
    ----------
    x : array_like
    chunks : int, tuple
        How to chunk the array. Must be one of the following forms:

        - A blocksize like 1000.
        - A blockshape like (1000, 1000).
        - Explicit sizes of all blocks along all dimensions like
          ((1000, 1000, 500), (400, 400)).
        - 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

        -1 or None as a blocksize indicate the size of the corresponding
        dimension.
    name : str or bool, optional
        The key name to use for the array. Defaults to a hash of ``x``.

        Hashing is useful if the same value of ``x`` is used to create multiple
        arrays, as Dask can then recognise that they're the same and
        avoid duplicate computations. However, it can also be slow, and if the
        array is not contiguous it is copied for hashing. If the array uses
        stride tricks (such as :func:`numpy.broadcast_to` or
        :func:`skimage.util.view_as_windows`) to have a larger logical
        than physical size, this copy can cause excessive memory usage.

        If you don't need the deduplication provided by hashing, use
        ``name=False`` to generate a random name instead of hashing, which
        avoids the pitfalls described above. Using ``name=True`` is
        equivalent to the default.

        By default, hashing uses python's standard sha1. This behaviour can be
        changed by installing cityhash, xxhash or murmurhash. If installed,
        a large-factor speedup can be obtained in the tokenisation step.

        .. note::

           Because this ``name`` is used as the key in task graphs, you should
           ensure that it uniquely identifies the data contained within. If
           you'd like to provide a descriptive name that is still unique, combine
           the descriptive name with :func:`dask.base.tokenize` of the
           ``array_like``. See :ref:`graphs` for more.

    lock : bool or Lock, optional
        If ``x`` doesn't support concurrent reads then provide a lock here, or
        pass in True to have dask.array create one for you.
    asarray : bool, optional
        If True then call np.asarray on chunks to convert them to numpy arrays.
        If False then chunks are passed through unchanged.
        If None (default) then we use True if the ``__array_function__`` method
        is undefined.
    fancy : bool, optional
        If ``x`` doesn't support fancy indexing (e.g. indexing with lists or
        arrays) then set to False. Default is True.
    meta : Array-like, optional
        The metadata for the resulting dask array.  This is the kind of array
        that will result from slicing the input array.
        Defaults to the input array.
    inline_array : bool, default False
        How to include the array in the task graph. By default
        (``inline_array=False``) the array is included in a task by itself,
        and each chunk refers to that task by its key.

        .. code-block:: python

           >>> x = h5py.File("data.h5")["/x"]  # doctest: +SKIP
           >>> a = da.from_array(x, chunks=500)  # doctest: +SKIP
           >>> dict(a.dask)  # doctest: +SKIP
           {
              'array-original-<name>': <HDF5 dataset ...>,
              ('array-<name>', 0): (getitem, "array-original-<name>", ...),
              ('array-<name>', 1): (getitem, "array-original-<name>", ...)
           }

        With ``inline_array=True``, Dask will instead inline the array directly
        in the values of the task graph.

        .. code-block:: python

           >>> a = da.from_array(x, chunks=500, inline_array=True)  # doctest: +SKIP
           >>> dict(a.dask)  # doctest: +SKIP
           {
              ('array-<name>', 0): (getitem, <HDF5 dataset ...>, ...),
              ('array-<name>', 1): (getitem, <HDF5 dataset ...>, ...)
           }

        Note that there's no key in the task graph with just the array `x`
        anymore. Instead it's placed directly in the values.

        The right choice for ``inline_array`` depends on several factors,
        including the size of ``x``, how expensive it is to create, which
        scheduler you're using, and the pattern of downstream computations.
        As a heuristic, ``inline_array=True`` may be the right choice when
        the array ``x`` is cheap to serialize and deserialize (since it's
        included in the graph many times) and if you're experiencing ordering
        issues (see :ref:`order` for more).

        This has no effect when ``x`` is a NumPy array.

    Examples
    --------

    >>> x = h5py.File('...')['/data/path']  # doctest: +SKIP
    >>> a = da.from_array(x, chunks=(1000, 1000))  # doctest: +SKIP

    If your underlying datastore does not support concurrent reads then include
    the ``lock=True`` keyword argument or ``lock=mylock`` if you want multiple
    arrays to coordinate around the same lock.

    >>> a = da.from_array(x, chunks=(1000, 1000), lock=True)  # doctest: +SKIP

    If your underlying datastore has a ``.chunks`` attribute (as h5py and zarr
    datasets do) then a multiple of that chunk shape will be used if you
    do not provide a chunk shape.

    >>> a = da.from_array(x, chunks='auto')  # doctest: +SKIP
    >>> a = da.from_array(x, chunks='100 MiB')  # doctest: +SKIP
    >>> a = da.from_array(x)  # doctest: +SKIP

    If providing a name, ensure that it is unique

    >>> import dask.base
    >>> token = dask.base.tokenize(x)  # doctest: +SKIP
    >>> a = da.from_array('myarray-' + token)  # doctest: +SKIP

    NumPy ndarrays are eagerly sliced and then embedded in the graph.

    >>> import dask.array
    >>> a = dask.array.from_array(np.array([[1, 2], [3, 4]]), chunks=(1,1))
    >>> a.dask[a.name, 0, 0][0]
    array([1])

    Chunks with exactly-specified, different sizes can be created.

    >>> import numpy as np
    >>> import dask.array as da
    >>> x = np.random.random((100, 6))
    >>> a = da.from_array(x, chunks=((67, 33), (6,)))
    zBArray is already a dask array. Use 'asarray' or 'rechunk' instead.ztPassing an object to dask.array.from_array which is already a Dask collection. This can lead to unexpected behavior.Nr  r   r   r  NTzarray-FTc                 s  s   | ]}t |d kV  qdS r  r  r  r_   r_   r`   re     rf   zfrom_array.<locals>.<genexpr>c                 s  s   | ]}t t|V  qd S ra   r  r   r_   r_   r`   re     rf   c                   s   g | ]} | qS r_   r_   rc   slcr   r_   r`   r     rf   zfrom_array.<locals>.<listcomp>rU  )rM   rk   rj   r   r   r  r   ZtiledbZ_ctx_r   r   )r   r   )$rg   r   r   r'   r)  r*  r   rl   
memoryviewrp   Z
ScalarTyperX   r   r   r   r   r   r)   r   uuiduuid1r8   r   r  r   r   r   r   r   r   rn   rx   r   rq  r\   r  )rd   r   r   rk   rj   ZfancyrM   r   r   r  r   Z
is_ndarrayZis_single_blockr   r   r  r}  r_   r   r`   
from_array  sj     


$
r  c           
      K  s   ddl }|pi }t| |jr"| }nlt| ttjfrrt| tjrHt| } t| fi |}	|j|	fd|d|}n| }	|j|	fd|d|}|dur|n|j}|du rdt	||||fi | }t
||||dS )a"  Load array from the zarr storage format

    See https://zarr.readthedocs.io for details about the format.

    Parameters
    ----------
    url: Zarr Array or str or MutableMapping
        Location of the data. A URL can include a protocol specifier like s3://
        for remote data. Can also be any MutableMapping instance, which should
        be serializable if used in multiple processes.
    component: str or None
        If the location is a zarr group rather than an array, this is the
        subcomponent that should be loaded, something like ``'foo/bar'``.
    storage_options: dict
        Any additional parameters for the storage backend (ignored for local
        paths)
    chunks: tuple of ints or tuples of ints
        Passed to :func:`dask.array.from_array`, allows setting the chunks on
        initialisation, if the chunking scheme in the on-disc dataset is not
        optimal for the calculations to follow.
    name : str, optional
         An optional keyname for the array.  Defaults to hashing the input
    kwargs:
        Passed to :class:`zarr.core.Array`.
    inline_array : bool, default False
        Whether to inline the zarr Array in the values of the task graph.
        See :meth:`dask.array.from_array` for an explanation.

    See Also
    --------
    from_array
    r   NT)Z	read_onlypathz
from-zarr-)r   r   )zarrrg   r   r   osPathLikefspathr   r   r)   r  )
url	componentstorage_optionsr   r   r   r   r  zmapperr_   r_   r`   	from_zarr  s    )
r  c              	     sx  ddl }	t| j r$tdt t||	jr|}
t|
j	t
tfr\tdddv r\td|du rv| |
j} d}nZdd	lm m} t|
j|
j}|||
j}t fd
dt|
j||D }| |} |g}| j	|
d|||dS |durtdt| jstd|pi }t|tr0t|fi |}n|}dd | jD }|	jf | j|| j|||d|}
| j	|
d||dS )a   Save array to the zarr storage format

    See https://zarr.readthedocs.io for details about the format.

    Parameters
    ----------
    arr: dask.array
        Data to store
    url: Zarr Array or str or MutableMapping
        Location of the data. A URL can include a protocol specifier like s3://
        for remote data. Can also be any MutableMapping instance, which should
        be serializable if used in multiple processes.
    component: str or None
        If the location is a zarr group rather than an array, this is the
        subcomponent that should be created/over-written.
    storage_options: dict
        Any additional parameters for the storage backend (ignored for local
        paths)
    overwrite: bool
        If given array already exists, overwrite=False will cause an error,
        where overwrite=True will replace the existing data.
    region: tuple of slices or None
        The region of data that should be written if ``url`` is a zarr.Array.
        Not to be used with other types of ``url``.
    compute: bool
        See :func:`~dask.array.store` for more details.
    return_stored: bool
        See :func:`~dask.array.store` for more details.
    **kwargs:
        Passed to the :func:`zarr.creation.create` function, e.g., compression options.

    Raises
    ------
    ValueError
        If ``arr`` has unknown chunk sizes, which is not supported by Zarr.
        If ``region`` is specified and ``url`` is not a zarr.Array

    See Also
    --------
    dask.array.store
    dask.array.Array.compute_chunk_sizes

    r   NzRSaving a dask array with unknown chunk sizes is not currently supported by Zarr.%sZ	schedulerr   )zdask.distributedZdistributedzGCannot store into in memory Zarr Array using the Distributed Scheduler.rK   )new_blockdimr  c                 3  s$   | ]\}}}t  |||V  qd S ra   r  )rc   r   ru   rA  r  r_   r`   re     s   zto_zarr.<locals>.<genexpr>F)rk   r;  r    r<  z;Cannot use `region` keyword when url is not a `zarr.Array`.z\Attempt to save array to zarr with irregular chunking, please call `arr.rechunk(...)` first.c                 S  s   g | ]}|d  qS rU  r_   r  r_   r_   r`   r     rf   zto_zarr.<locals>.<listcomp>)r   r   r   rT  r  	overwrite)rk   r    r<  )r  rp   rX  r   rm   r   rY  rg   r   rT  r   r
   r!   r  RuntimeErrorrn  r   r  r  r  r   rl   r   _check_regular_chunksr   r   Zcreater   )r   r  r  r  r  rB  r    r<  r   r  r  r;  r  Z
old_chunksr  r   r  r_   r  r`   r  B  sj    6


	r  c                 C  sP   | D ]F}t |dkrqt t|dd dkr4 dS |d |d kr dS qdS )a  Check if the chunks are regular

    "Regular" in this context means that along every axis, the chunks all
    have the same size, except the last one, which may be smaller

    Parameters
    ----------
    chunkset: tuple of tuples of ints
        From the ``.chunks`` attribute of an ``Array``

    Returns
    -------
    True if chunkset passes, else False

    Examples
    --------
    >>> import dask.array as da
    >>> arr = da.zeros(10, chunks=(5, ))
    >>> _check_regular_chunks(arr.chunks)
    True

    >>> arr = da.zeros(10, chunks=((3, 3, 3, 1), ))
    >>> _check_regular_chunks(arr.chunks)
    True

    >>> arr = da.zeros(10, chunks=((3, 1, 3, 3), ))
    >>> _check_regular_chunks(arr.chunks)
    False
    rK   Nr   Fr   T)r   r   )Zchunksetr   r_   r_   r`   r    s    r  c           
      C  s   ddl m}m } t| |s,t| dr,|| } |p@dt| ||| }|fdt|  | ji}tdd |D }tj	||| gd}	t
|	||||d	S )
au  Create a dask array from a dask delayed value

    This routine is useful for constructing dask arrays in an ad-hoc fashion
    using dask delayed, particularly when combined with stack and concatenate.

    The dask array will consist of a single chunk.

    Examples
    --------
    >>> import dask
    >>> import dask.array as da
    >>> import numpy as np
    >>> value = dask.delayed(np.ones)(5)
    >>> array = da.from_delayed(value, (5,), dtype=float)
    >>> array
    dask.array<from-value, shape=(5,), dtype=float64, chunksize=(5,), chunktype=numpy.ndarray>
    >>> array.compute()
    array([1., 1., 1., 1., 1.])
    r   r.   r   zfrom-value-rU  c                 s  s   | ]}|fV  qd S ra   r_   rc   rV  r_   r_   r`   re     rf   zfrom_delayed.<locals>.<genexpr>rd  r   r   )r0   r/   rg   r   r)   r   r   rl   r1   r   r   )
r  r   r   r   r   r/   r0   r}  r   r  r_   r_   r`   from_delayed  s    r  r_   c                 C  sn   |pdt | |||| }|s |r6t| g|R i |} |fdt|  | fi}tdd |D }t||||S )a:  Create dask array in a single block by calling a function

    Calling the provided function with func(*args, **kwargs) should return a
    NumPy array of the indicated shape and dtype.

    Examples
    --------

    >>> a = from_func(np.arange, (3,), dtype='i8', args=(3,))
    >>> a.compute()
    array([0, 1, 2])

    This works particularly well when coupled with dask.array functions like
    concatenate and stack:

    >>> arrays = [from_func(np.array, (), dtype='i8', args=(n,)) for n in range(5)]
    >>> stack(arrays).compute()
    array([0, 1, 2, 3, 4])
    z
from_func-rU  c                 s  s   | ]}|fV  qd S ra   r_   r  r_   r_   r`   re     rf   zfrom_func.<locals>.<genexpr>)r)   r   r   rl   r   )r   r   r   r   r   r   r}  r   r_   r_   r`   	from_func  s    r  c                 C  s  t | sdS dd | D }t|dkr.t|S t|dkrFt| tdS tttt| rftd|  tt	tt|dkrtd| d	d
 |D }tt|}d}g }||k rt
dd |D }|| |D ](}|d  |8  < |d dkr|  q||7 }qt|S )a  Find the common block dimensions from the list of block dimensions

    Currently only implements the simplest possible heuristic: the common
    block-dimension is the only one that does not span fully span a dimension.
    This is a conservative choice that allows us to avoid potentially very
    expensive rechunking.

    Assumes that each element of the input block dimensions has all the same
    sum (i.e., that they correspond to dimensions of the same size).

    Examples
    --------
    >>> common_blockdim([(3,), (2, 1)])
    (2, 1)
    >>> common_blockdim([(1, 2), (2, 1)])
    (1, 1, 1)
    >>> common_blockdim([(2, 2), (3, 1)])  # doctest: +SKIP
    Traceback (most recent call last):
        ...
    ValueError: Chunks do not align
    r_   c                 S  s   h | ]}t |d kr|qS r   r  r  r_   r_   r`   r  9  rf   z"common_blockdim.<locals>.<setcomp>rK   r   r   zUArrays' chunk sizes (%s) are unknown.

A possible solution:
  x.compute_chunk_sizes()z"Chunks do not add up to same valuec                 S  s   g | ]}t |d d d qS r   r   )rc   Zntdr_   r_   r`   r   T  rf   z#common_blockdim.<locals>.<listcomp>c                 s  s   | ]}|d  V  qdS r  r_   r  r_   r_   r`   re   Z  rf   z"common_blockdim.<locals>.<genexpr>r   )rm   r   r   r   rp   rX  r   r   r   r   rS  r0  r  rl   )Z	blockdimsZnon_trivial_dimsZrchunkstotalr  r&  mru   r_   r_   r`   common_blockdim!  s8    




r  c                    s  | si g fS dd t d| D }|dd}t| \tdd D rVi tfS tfddD rtfd	dD rttd
 d
 jfS g }t }d
}|D ]H\ }|dur| j|f  j| j< t	| j
}q| |f qt||tdtttt }|rR|rR||d krRtjd||  tdd g |D ]p\ }	|	du rx  nPt fddt|	D }
|
 jkrt jr |
 n
  qZfS )aT  
    Unify chunks across a sequence of arrays

    This utility function is used within other common operations like
    :func:`dask.array.core.map_blocks` and :func:`dask.array.core.blockwise`.
    It is not commonly used by end-users directly.

    Parameters
    ----------
    *args: sequence of Array, index pairs
        Sequence like (x, 'ij', y, 'jk', z, 'i')

    Examples
    --------
    >>> import dask.array as da
    >>> x = da.ones(10, chunks=((5, 2, 3),))
    >>> y = da.ones(10, chunks=((2, 3, 5),))
    >>> chunkss, arrays = unify_chunks(x, 'i', y, 'i')
    >>> chunkss
    {'i': (2, 3, 2, 3)}

    >>> x = da.ones((100, 10), chunks=(20, 5))
    >>> y = da.ones((10, 100), chunks=(4, 50))
    >>> chunkss, arrays = unify_chunks(x, 'ij', y, 'jk', 'constant', None)
    >>> chunkss  # doctest: +SKIP
    {'k': (50, 50), 'i': (20, 20, 20, 20, 20), 'j': (4, 1, 3, 2)}

    >>> unify_chunks(0, None)
    ({}, [0])

    Returns
    -------
    chunkss : dict
        Map like {index: chunks}.
    arrays : list
        List of rechunked arrays.

    See Also
    --------
    common_blockdim
    c                 S  s(   g | ] \}}|d urt |n||fqS ra   )r  )rc   rr   r  r_   r_   r`   r     s   z unify_chunks.<locals>.<listcomp>r   r*  Tc                 s  s   | ]}|d u V  qd S ra   r_   rc   r  r_   r_   r`   re     rf   zunify_chunks.<locals>.<genexpr>c                 3  s   | ]}| d  kV  qdS r  r_   r  )indsr_   r`   re     rf   c                 3  s   | ]}|j  d  j kV  qdS r  r$  r   )r   r_   r`   re     s   r   N)Zconsolidater   z+Increasing number of chunks by factor of %d   )
stacklevelc                 3  sH   | ]@\}} j | d kr | ntt| s< j | ndV  qdS r  )r   rp   rX  r   )rc   r3  r  )rr   r7  r_   r`   re     s   
)r   r  r   r   r   r   r   r0  r   r   r  r+   r  rp   r  r   r   r  r)  r*  rZ   rl   r-  rn  )r   r   Zargindsr*  ZnameindsZblockdim_dictZ	max_partsr  Znpartsr  r   r_   )rr   r   r7  r  r`   unify_chunkse  sR    *"

r  c              
   C  s>   t | ttfr:z| d } W q  tttfy6   Y q:Y q 0 q | S )z

    >>> unpack_singleton([[[[1]]]])
    1
    >>> unpack_singleton(np.array(np.datetime64('2000-01-01')))
    array('2000-01-01', dtype='datetime64[D]')
    r   )rg   r   rl   r  r(  rm  r   r_   r_   r`   r^    s    r^  c                   s,  dd dd }t dd d}d}d	}|| D ]\}}}t|tu rXtd
|||sft|}	n t|dkr0t|d }	d}nq0|dur||	krtd||	|||	}q0|rtd|j| t	t
d} |j| dd td}
t||
| }|j| fddt
d} |j|  fdddd |dS )a&  
    Assemble an nd-array from nested lists of blocks.

    Blocks in the innermost lists are concatenated along the last
    dimension (-1), then these are concatenated along the second-last
    dimension (-2), and so on until the outermost list is reached

    Blocks can be of any dimension, but will not be broadcasted using the normal
    rules. Instead, leading axes of size 1 are inserted, to make ``block.ndim``
    the same for all blocks. This is primarily useful for working with scalars,
    and means that code like ``block([v, 1])`` is valid, where
    ``v.ndim == 1``.

    When the nested list is two levels deep, this allows block matrices to be
    constructed from their components.

    Parameters
    ----------
    arrays : nested list of array_like or scalars (but not tuples)
        If passed a single ndarray or scalar (a nested list of depth 0), this
        is returned unmodified (and not copied).

        Elements shapes must match along the appropriate axes (without
        broadcasting), but leading 1s will be prepended to the shape as
        necessary to make the dimensions match.

    allow_unknown_chunksizes: bool
        Allow unknown chunksizes, such as come from converting from dask
        dataframes.  Dask.array is unable to verify that chunks line up.  If
        data comes from differently aligned sources then this can cause
        unexpected results.

    Returns
    -------
    block_array : ndarray
        The array assembled from the given blocks.

        The dimensionality of the output is equal to the greatest of:
        * the dimensionality of all the inputs
        * the depth to which the input list is nested

    Raises
    ------
    ValueError
        * If list depths are mismatched - for instance, ``[[a, b], c]`` is
          illegal, and should be spelt ``[[a, b], [c]]``
        * If lists are empty - for instance, ``[[a, b], []]``

    See Also
    --------
    concatenate : Join a sequence of arrays together.
    stack : Stack arrays in sequence along a new dimension.
    hstack : Stack arrays in sequence horizontally (column wise).
    vstack : Stack arrays in sequence vertically (row wise).
    dstack : Stack arrays in sequence depth wise (along third dimension).
    vsplit : Split array into a list of multiple sub-arrays vertically.

    Notes
    -----

    When called with only scalars, ``block`` is equivalent to an ndarray
    call. So ``block([[1, 2], [3, 4]])`` is equivalent to
    ``array([[1, 2], [3, 4]])``.

    This function does not enforce that the blocks lie on a fixed grid.
    ``block([[a, b], [c, d]])`` is not restricted to arrays of the form::

        AAAbb
        AAAbb
        cccDD

    But is also allowed to produce, for some ``a, b, c, d``::

        AAAbb
        AAAbb
        cDDDD

    Since concatenation happens along the last axis first, `block` is _not_
    capable of producing the following directly::

        AAAbb
        cccbb
        cccDD

    Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
    equivalent to ``block([[A, B, ...], [p, q, ...]])``.
    c                 S  s:   t | } t|| j d}|dkr$| S | d| tf  S d S )Nr   ra   )r  r   r   Ellipsis)rd   r   diffr_   r_   r`   
atleast_nd5  s
    zblock.<locals>.atleast_ndc                 S  s   dd dd | D  S )Nr   r   c                 s  s   | ]}d | dV  qdS )[]Nr_   r  r_   r_   r`   re   >  rf   z.block.<locals>.format_index.<locals>.<genexpr>)r   r  r_   r_   r`   format_index=  s    zblock.<locals>.format_indexc                 S  s   t | tu S ra   )r   r   r   r_   r_   r`   r   @  rf   zblock.<locals>.<lambda>)Z
recurse_ifNFz{} is a tuple. Only lists can be used to arrange blocks, and np.block does not allow implicit conversion from tuple to ndarray.r   rK   TzcList depths are mismatched. First element was at depth {}, but there is an element at depth {} ({})zLists cannot be empty)Zf_mapf_reducec                 S  s   | j S ra   r  Zxir_   r_   r`   r   l  rf   c                   s
    | S ra   r_   r  )r  r   r_   r`   r   t  rf   c                   s   t t| | dS )N)r   allow_unknown_chunksizes)r   r   )Zxsr   r  r_   r`   r   z  s   
c                 S  s   t | d dS )NrK   r   )r   r   r_   r_   r`   r   }  rf   )r  Zf_kwargsr   )rT   walkr   rl   r(  r   r   r   Z
map_reducer  r   r   )r   r  r  ZrecZ	list_ndimZ	any_emptyr  r  ZenteringZ
curr_depthZ	elem_ndimZ
first_axisr_   )r  r  r   r`   block  sP    ]



r  c                   s  ddl m}  fddD s*tddu rDdd D dd	d D }ttt|d
d d}||dfddD td jt	fddt
D }dd D sʈdk rڈ krd}t|f t}|dkrHz|j||jdW S  tyD   |j||jd Y S 0 n|dkrZd S  stfddt
D stttjd jrtdtd j tddd D fddt
|D }	t|	D ]\}
}|
d  |< qttt|	}t|ddi\}dd D }d jd tfdd|D df d jd d  }dgtttfddD  d d D d!t }tt|ggd"d |D R  }fd#d|D }t t||}t!j"||d$}t#|||d%S )&a  
    Concatenate arrays along an existing axis

    Given a sequence of dask Arrays form a new dask Array by stacking them
    along an existing dimension (axis=0 by default)

    Parameters
    ----------
    seq: list of dask.arrays
    axis: int
        Dimension along which to align all of the arrays. If axis is None,
        arrays are flattened before use.
    allow_unknown_chunksizes: bool
        Allow unknown chunksizes, such as come from converting from dask
        dataframes.  Dask.array is unable to verify that chunks line up.  If
        data comes from differently aligned sources then this can cause
        unexpected results.

    Examples
    --------

    Create slices

    >>> import dask.array as da
    >>> import numpy as np

    >>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2))
    ...          for i in range(3)]

    >>> x = da.concatenate(data, axis=0)
    >>> x.shape
    (12, 4)

    >>> da.concatenate(data, axis=1).shape
    (4, 12)

    Result is a new dask Array

    See Also
    --------
    stack
    rK   wrapc                   s   g | ]}t | d qS r  rj   r   r  r_   r`   r     rf   zconcatenate.<locals>.<listcomp>zNeed array(s) to concatenateNc                 S  s   g | ]}|  qS r_   )rO  r   r_   r_   r`   r     rf   r   c                 S  s   g | ]}t |qS r_   r   r  r_   r_   r`   r     rf   c                 S  s   t | ddS r   r   r   r_   r_   r`   r     rf   zconcatenate.<locals>.<lambda>r   r   c                   s   g | ]}|  jqS r_   r  r   r   rK  r_   r`   r     rf   c                 3  s:   | ]2  kr$t  fd dD nd j  V  qdS )c                 3  s   | ]}|j   V  qd S ra   r   r   r6  r_   r`   re     rf   (concatenate.<locals>.<genexpr>.<genexpr>r   N)r   r   rc   r   seqr6  r`   re     s   zconcatenate.<locals>.<genexpr>c                 S  s   g | ]}|j r|qS r_   r  r   r_   r_   r`   r     rf   zXAxis must be less than than number of dimensions
Data has %d dimensions, but got axis=%dr   r   r   r  c                 3  s.   | ]&  kp$t  fd dD V  qdS )c                 3  s&   | ]}|j   d  j   kV  qdS r  r  rb   )r  seq2r_   r`   re     rf   r  Nr   r  )r   r  r6  r`   re     s   zTried to concatenate arrays with unknown shape %s.

Two solutions:
  1. Force concatenation pass allow_unknown_chunksizes=True.
  2. Compute shapes with [x.compute_chunk_sizes() for x in seq]zShapes do not align: %sc                 S  s   g | ]
}|j qS r_   r  rb   r_   r_   r`   r     rf   c                   s   g | ]}t t qS r_   )r   r   r  r  r_   r`   r     rf   r*  Fc                 S  s   g | ]
}|j qS r_   r$  r   r_   r_   r`   r     rf   c                 3  s   | ]}|  V  qd S ra   r_   rc   rW  r   r_   r`   re     rf   r_   c                   s   g | ]}t |j  qS r_   )r   r   r   r   r_   r`   r     rf   c                 S  s   g | ]
}|j qS r_   rt  r   r_   r_   r`   r     rf   zconcatenate-c                 S  s   g | ]}t t|qS r_   r  r  r_   r_   r`   r     rf   c              
     sp   g | ]h}t | d   d   f|d  d    | d   t | d   d    f | d d  qS rK   r   Nr   rc   r   )r   cum_dimsr  r_   r`   r     s   &rd  rK  )$r   r  r   rP   r   r   r   r   r   rl   r   
empty_liker   r(  emptyr   rm   r   rp   rX  r   r-  r   r   r   r  r   r   r   r   r)   r   r   r1   r   r   )r  r   r  r  Z	seq_metasZ_concatenater   r   r3  r  r  r  uc_args_r   r   r   r   r  r}  r  r_   )r  r   r  r   r  r   r  r  r`   r     s    +


" r   c                 C  sx   d}|r|s|}|r|   zH| durFt| r8| ||< nt| ||< |rV|rV|| }W |rt|  n|rr|  0 |S )a  
    A function inserted in a Dask graph for storing a chunk.

    Parameters
    ----------
    x: array-like
        An array (potentially a NumPy one)
    out: array-like
        Where to store results too.
    index: slice-like
        Where to store result from ``x`` in ``out``.
    lock: Lock-like or False
        Lock to use before writing to ``out``.
    return_stored: bool
        Whether to return ``out``.
    load_stored: bool
        Whether to return the array stored in ``out``.
        Ignored if ``return_stored`` is not ``True``.

    Examples
    --------

    >>> a = np.ones((5, 6))
    >>> b = np.empty(a.shape)
    >>> load_store_chunk(a, b, (slice(None), slice(None)), False, False, False)
    N)ro   rA   rp   r  rq   )rd   r&  r  rk   r<  rC  r8  r_   r_   r`   load_store_chunk  s"    



r  c                 C  s   t | ||||dS )NFr  )rd   r&  r  rk   r<  r_   r_   r`   store_chunkC  s    r  c                 C  s   t d | ||ddS r  r  )r&  r  rk   r_   r_   r`   
load_chunkG  s    r  )rk   rB  r<  rC  r   ztuple[tuple[int, ...], ...]r   zLock | boolzslice | Noner   )r   r   r   rk   rB  r<  rC  r   c          
        st   du rt  t|}r,fdd|D }r@|r@t|f ntd  fddtt| |D }	|	S )a  
    Creates a Dask graph for storing chunks from ``arr`` in ``out``.

    Parameters
    ----------
    keys: list
        Dask keys of the input array
    chunks: tuple
        Dask chunks of the input array
    out: array-like
        Where to store results to
    name: str
        First element of dask keys
    lock: Lock-like or bool, optional
        Whether to lock or with what (default is ``True``,
        which means a :class:`threading.Lock` instance).
    region: slice-like, optional
        Where in ``out`` to store ``arr``'s results
        (default is ``None``, meaning all of ``out``).
    return_stored: bool, optional
        Whether to return ``out``
        (default is ``False``, meaning ``None`` is returned).
    load_stored: bool, optional
        Whether to handling loading from ``out`` at the same time.
        Ignored if ``return_stored`` is not ``True``.
        (default is ``False``, meaning defer to ``return_stored``).

    Returns
    -------
    dask graph of store operation

    Examples
    --------
    >>> import dask.array as da
    >>> d = da.ones((5, 6), chunks=(2, 3))
    >>> a = np.empty(d.shape)
    >>> insert_to_ooc(d.__dask_keys__(), d.chunks, a, "store-123")  # doctest: +SKIP
    Tc                   s   g | ]}t  |qS r_   )rz   r  )rB  r_   r`   r     rf   z!insert_to_ooc.<locals>.<listcomp>r_   c              	     s4   i | ],\}}f|d d  ||f  qS r  r_   )rc   r@  r  )r   r   rk   r   r&  r<  r_   r`   r    s   z!insert_to_ooc.<locals>.<dictcomp>)r   r   r  r  r   r"   rO  )
r   r   r&  r   rk   rB  r<  rC  r   r}  r_   )r   r   rk   r   r&  rB  r<  r`   rP  K  s    2rP  zCollection[Hashable]r	   )r   dsk_predsk_postr   c                   s    fdd| D }|S )a  
    Creates a Dask graph for loading stored ``keys`` from ``dsk``.

    Parameters
    ----------
    keys: Collection
        A sequence containing Dask graph keys to load
    dsk_pre: Mapping
        A Dask graph corresponding to a Dask Array before computation
    dsk_post: Mapping
        A Dask graph corresponding to a Dask Array after computation

    Examples
    --------
    >>> import dask.array as da
    >>> d = da.ones((5, 6), chunks=(2, 3))
    >>> a = np.empty(d.shape)
    >>> g = insert_to_ooc(d.__dask_keys__(), d.chunks, a, "store-123")
    >>> retrieve_from_ooc(g.keys(), g, {k: k for k in g.keys()})  # doctest: +SKIP
    c                   s@   i | ]8}d |d  f|dd  t  | f| dd  qS )rJ  r   rK   Nr  r   )r  rF  r  r  r_   r`   r    s   z%retrieve_from_ooc.<locals>.<dictcomp>r_   )r   r  r  Zload_dskr_   r  r`   rQ    s    rQ  )r  c                K  s   |du rt | tr| S t| dr(|  S t| jdd dkrTt| drTt| jS t | t	t
frtdd | D rt| |d	S t t| d
dtstj| ||d} nDtstdt|}t | tr| jtj|||dS tj| |||d} t| fdti|S )u  Convert the input to a dask array.

    Parameters
    ----------
    a : array-like
        Input data, in any form that can be converted to a dask array. This
        includes lists, lists of tuples, tuples, tuples of tuples, tuples of
        lists and ndarrays.
    allow_unknown_chunksizes: bool
        Allow unknown chunksizes, such as come from converting from dask
        dataframes.  Dask.array is unable to verify that chunks line up.  If
        data comes from differently aligned sources then this can cause
        unexpected results.
    dtype : data-type, optional
        By default, the data-type is inferred from the input data.
    order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
        Memory layout. ‘A’ and ‘K’ depend on the order of input array a.
        ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory
        representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’
        otherwise ‘K’ (keep) preserve input order. Defaults to ‘C’.
    like: array-like
        Reference object to allow the creation of Dask arrays with chunks
        that are not NumPy arrays. If an array-like passed in as ``like``
        supports the ``__array_function__`` protocol, the chunk type of the
        resulting array will be definde by it. In this case, it ensures the
        creation of a Dask array compatible with that passed in via this
        argument. If ``like`` is a Dask array, the chunk type of the
        resulting array will be defined by the chunk type of ``like``.
        Requires NumPy 1.20.0 or higher.

    Returns
    -------
    out : dask array
        Dask array interpretation of a.

    Examples
    --------
    >>> import dask.array as da
    >>> import numpy as np
    >>> x = np.arange(3)
    >>> da.asarray(x)
    dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>

    >>> y = [[1, 2, 3], [4, 5, 6]]
    >>> da.asarray(y)
    dask.array<array, shape=(2, 3), dtype=int64, chunksize=(2, 3), chunktype=numpy.ndarray>
    Nto_dask_arrayr  r   xarraydatac                 s  s   | ]}t |tV  qd S ra   r   r  r_   r_   r`   re     rf   zasarray.<locals>.<genexpr>r  r   r   rc  *The use of ``like`` required NumPy >= 1.20r  r   rc  rM   )rg   r   r   r  r   r\   r  rj   r  r   rl   rm   stackr   r   rp   rS   r  r   r  r  ry   )rr   r  r   rc  r  r   	like_metar_   r_   r`   rj     s$    2

"
 
rj   )r  r   c                C  s   |du rt | tr| S t| dr(|  S t| jdd dkrTt| drTt| jS t | t	t
fr|tdd | D r|t| S t t| d	dtstj| ||d
} nDtstdt|}t | tr| jtj|||dS tj| |||d} t| | jtd|dS )u  Convert the input to a dask array.

    Subclasses of ``np.ndarray`` will be passed through as chunks unchanged.

    Parameters
    ----------
    a : array-like
        Input data, in any form that can be converted to a dask array. This
        includes lists, lists of tuples, tuples, tuples of tuples, tuples of
        lists and ndarrays.
    dtype : data-type, optional
        By default, the data-type is inferred from the input data.
    order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
        Memory layout. ‘A’ and ‘K’ depend on the order of input array a.
        ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory
        representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’
        otherwise ‘K’ (keep) preserve input order. Defaults to ‘C’.
    like: array-like
        Reference object to allow the creation of Dask arrays with chunks
        that are not NumPy arrays. If an array-like passed in as ``like``
        supports the ``__array_function__`` protocol, the chunk type of the
        resulting array will be definde by it. In this case, it ensures the
        creation of a Dask array compatible with that passed in via this
        argument. If ``like`` is a Dask array, the chunk type of the
        resulting array will be defined by the chunk type of ``like``.
        Requires NumPy 1.20.0 or higher.
    inline_array:
        Whether to inline the array in the resulting dask graph. For more information,
        see the documentation for ``dask.array.from_array()``.

    Returns
    -------
    out : dask array
        Dask array interpretation of a.

    Examples
    --------
    >>> import dask.array as da
    >>> import numpy as np
    >>> x = np.arange(3)
    >>> da.asanyarray(x)
    dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>

    >>> y = [[1, 2, 3], [4, 5, 6]]
    >>> da.asanyarray(y)
    dask.array<array, shape=(2, 3), dtype=int64, chunksize=(2, 3), chunktype=numpy.ndarray>
    Nr  r  r   r  r  c                 s  s   | ]}t |tV  qd S ra   r   r  r_   r_   r`   re   1  rf   zasanyarray.<locals>.<genexpr>r   r  r  r  F)r   rM   rj   r   )rg   r   r   r  r   r\   r  r  r  r   rl   rm   r  r   r   rp   rS   r  r   r  r  r   ry   )rr   r   rc  r  r   r  r_   r_   r`   r    s0    0

"
 
r  c                 C  sZ   t | dd}t|t p(tdd |D }t| pX|pXt| tjpXt| tjoX| jdkS )a  

    >>> is_scalar_for_elemwise(42)
    True
    >>> is_scalar_for_elemwise('foo')
    True
    >>> is_scalar_for_elemwise(True)
    True
    >>> is_scalar_for_elemwise(np.array(42))
    True
    >>> is_scalar_for_elemwise([1, 2, 3])
    True
    >>> is_scalar_for_elemwise(np.array([1, 2, 3]))
    False
    >>> is_scalar_for_elemwise(from_array(np.array(0), chunks=()))
    False
    >>> is_scalar_for_elemwise(np.dtype('i4'))
    True
    r   Nc                 s  s   | ]}t |V  qd S ra   r'   rb   r_   r_   r`   re   ^  s   z)is_scalar_for_elemwise.<locals>.<genexpr>r   )	r   rg   r   rm   rp   r  r   r  r   )r  Zmaybe_shapeZshape_conditionr_   r_   r`   is_scalar_for_elemwiseG  s    

r  c               	     s   t | dkr| d S g }ttt| ddiD ]j}t| rFtj nd|v rRdnt| t fdd|D rt	d
dtt| |  q,tt|S )	a2  
    Determines output shape from broadcasting arrays.

    Parameters
    ----------
    shapes : tuples
        The shapes of the arguments.

    Returns
    -------
    output_shape : tuple

    Raises
    ------
    ValueError
        If the input shapes cannot be successfully broadcast together.
    rK   r   	fillvaluer   c                 3  s*   | ]"}|d dd fvo t | V  qdS )r   r   rK   N)rp   rX  r  r   r_   r`   re     rf   z#broadcast_shapes.<locals>.<genexpr>z7operands could not be broadcast together with shapes {} )r   r   r   reversedrp   rX  rm   nanr   r   r   r   r   r0  rl   )r   r&  Zsizesr_   r  r`   broadcast_shapesj  s    r  )r&  r  r   r   c                O  s  |rt | j dt| t|}t|}dd |D }g }|D ]0}t|dd}	tdd |	D rhd}	||	 qBt|t	r||j
 t|t	r||j
 dd |D }tt| }
tt|
d	d	d
 }|d	urd}nPdd |D }zt| |i ddd}W n ty   t Y S 0 tdd |D }|sXt|  dt| |g||R   }t||t| dd}|dur| |d< t} |||g |r||d< | |d< t} t| |gtdd |D R i |}t||S )a  Apply an elementwise ufunc-like function blockwise across arguments.

    Like numpy ufuncs, broadcasting rules are respected.

    Parameters
    ----------
    op : callable
        The function to apply. Should be numpy ufunc-like in the parameters
        that it accepts.
    *args : Any
        Arguments to pass to `op`. Non-dask array-like objects are first
        converted to dask arrays, then all arrays are broadcast together before
        applying the function blockwise across all arguments. Any scalar
        arguments are passed as-is following normal numpy ufunc behavior.
    out : dask array, optional
        If out is a dask.array then this overwrites the contents of that array
        with the result.
    where : array_like, optional
        An optional boolean mask marking locations where the ufunc should be
        applied. Can be a scalar, dask array, or any other array-like object.
        Mirrors the ``where`` argument to numpy ufuncs, see e.g. ``numpy.add``
        for more information.
    dtype : dtype, optional
        If provided, overrides the output array dtype.
    name : str, optional
        A unique key name to use when building the backing dask graph. If not
        provided, one will be automatically generated based on the input
        arguments.

    Examples
    --------
    >>> elemwise(add, x, y)  # doctest: +SKIP
    >>> elemwise(sin, x)  # doctest: +SKIP
    >>> elemwise(sin, x, out=dask_array)  # doctest: +SKIP

    See Also
    --------
    blockwise
    z/ does not take the following keyword arguments c                 S  s(   g | ] }t |ttfr t|n|qS r_   )rg   r   rl   rp   rj   r   r_   r_   r`   r     rf   zelemwise.<locals>.<listcomp>r   r_   c                 s  s   | ]}t |V  qd S ra   r  rb   r_   r_   r`   re     rf   zelemwise.<locals>.<genexpr>c                 S  s   g | ]}t |tr|nd qS )r_   )rg   r   r  r_   r_   r`   r     rf   Nr   Tc                 S  s4   g | ],}t |s,tjd td|j |jdn|qS )r   rK   r   )r  rp   r  r   r   r   r   r_   r_   r`   r     s   r  F)r   c                 s  s"   | ]}t | o|jd kV  qdS r  )r  r   r   r_   r_   r`   re     s   r   r  )r   r   r   elemwise_where_functionenforce_dtypeenforce_dtype_functionc                 s  s6   | ].}|t |s(tt|jd d d nd fV  qd S r   )r  rl   r   r   r   r_   r_   r`   re     s   )r(  r[   r.  _elemwise_normalize_out_elemwise_normalize_wherer   rm   r0  rg   r   r   r   r  rl   r   r   r   r   r?   r)   r   strip_elemwise_handle_whereextend_enforce_dtyper*   r   
handle_out)opr&  r  r   r   r   r   r   r  r   Zout_ndimZ	expr_indsZneed_enforce_dtypeZvalsZblockwise_kwargsr8  r_   r_   r`   r    st    (



$

r  c                 C  s(   | du rdS | du s| d u r dS t | S )NTFr  r  r_   r_   r`   r    s
    r  c                  O  s<   | d}| ^ } }}t|dr(| }|| ||d|S )Nr  r  )r  r&  )r  r   r  )r   r   functionr  r&  r_   r_   r`   r    s
    

r  c                 C  sf   t | tr:t| dkr | d } nt| dkr6tdnd } | d u sbt | tsbtdt| j d| S )NrK   r   z(The out parameter is not fully supportedz8The out parameter is not fully supported. Received type z, expected Dask Array)rg   rl   r   r  r   r   r[   r%  r_   r_   r`   r     s    


r   c                 C  sf   t | } t| tr^| j|jkr:tdt| jt|jf |j| _|j| _|j	| _	|j
| _| S |S dS )zzHandle out parameters

    If out is a dask.array then this overwrites the contents of that array with
    the result
    zEMismatched shapes between result and out parameter. out=%s, result=%sN)r   rg   r   r   r   r   r   rj  rI  rb  r   ri  )r&  r8  r_   r_   r`   r  &  s    
r  c                  O  s   | d}| d}|| i |}t|dr||jkr|tkrtj||ddsntdt|t|t|jf t	|r|
|}n0z|j
|dd}W n ty   |
|}Y n0 |S )	a6  Calls a function and converts its result to the given dtype.

    The parameters have deliberately been given unwieldy names to avoid
    clashes with keyword arguments consumed by blockwise

    A dtype of `object` is treated as a special case and not enforced,
    because it is used as a dummy value in some places when the result will
    not be a block in an Array.

    Parameters
    ----------
    enforce_dtype : dtype
        Result dtype
    enforce_dtype_function : callable
        The wrapped function, which will be passed the remaining arguments
    r  r  r   Z	same_kindr   z`Inferred dtype from function %r was %r but got %r, which can't be cast using casting='same_kind'Fr  )r  r   r   r  rp   r  r   r?   r   r  r  r(  )r   r   r   r  r8  r_   r_   r`   r  <  s"    


r  c              	   C  s  t | } t|}|du r t| }| j|kr@|du s<|| jkr@| S t|| j }|dk sxtdd t||d | jD rt	d| j d| |du rtdd |d| D tdd t| j| j||d D  }nZt
||| j| jd	}t| j||d D ]0\}}||kr |d
kr t	d| j|f q dt| || }i }tdd |D  }	dd |	D D ]V\}
}tdd t| j|
|d D }| jf| }|f|
 }tj|t|f||< qftj||| gd}t|||| j|dS )aH  Broadcast an array to a new shape.

    Parameters
    ----------
    x : array_like
        The array to broadcast.
    shape : tuple
        The shape of the desired array.
    chunks : tuple, optional
        If provided, then the result will use these chunks instead of the same
        chunks as the source array. Setting chunks explicitly as part of
        broadcast_to is more efficient than rechunking afterwards. Chunks are
        only allowed to differ from the original shape along dimensions that
        are new on the result or have size 1 the input array.
    meta : empty ndarray
        empty ndarray created with same NumPy backend, ndim and dtype as the
        Dask Array being created (overrides dtype)

    Returns
    -------
    broadcast : dask array

    See Also
    --------
    :func:`numpy.broadcast_to`
    Nr   c                 s  s"   | ]\}}|d kr||kV  qdS r  r_   )rc   newoldr_   r_   r`   re     s   zbroadcast_to.<locals>.<genexpr>zcannot broadcast shape z
 to shape c                 s  s   | ]}|fV  qd S ra   r_   r  r_   r_   r`   re     rf   c                 s  s&   | ]\}}}|d kr|n|fV  qdS r  r_   )rc   rW  r  r
  r_   r_   r`   re     s   r  r   zqcannot broadcast chunks %s to chunks %s: new chunks must either be along a new dimension or a dimension of size 1zbroadcast_to-c                 s  s   | ]}t |V  qd S ra   )r-  r   r_   r_   r`   re     rf   c                 s  s   | ]}t | V  qd S ra   r   )rc   Zecr_   r_   r`   re     rf   c                 s  s"   | ]\}}|d krdn|V  qdS )r   r   Nr_   )rc   rW  r  r_   r_   r`   re     s   rd  r  )rj   rl   r   r   r   r   r   rm   r   r   r   r   r)   r   r   rp   broadcast_tor-   r1   r   r   )rd   r   r   r   Zndim_newZold_bdZnew_bdr   r}  Zenumerated_chunksZ	new_indexZchunk_shapeZ	old_indexZold_keyZnew_keyr  r_   r_   r`   r  f  sJ     
r  )subokc                   s   t | } | rtnttfdd|D }dd |D }tt||}t|ddi\}}tdd |D  tdd |D    fd	d|D }|S )
Nc                 3  s   | ]} |V  qd S ra   r_   r   )to_arrayr_   r`   re     rf   z#broadcast_arrays.<locals>.<genexpr>c                 S  s   g | ]}t tt|jqS r_   )r   r  r   r   rb   r_   r_   r`   r     rf   z$broadcast_arrays.<locals>.<listcomp>r*  Fc                 s  s   | ]}|j V  qd S ra   r  r   r_   r_   r`   re     rf   c                 s  s   | ]}|j V  qd S ra   r$  r   r_   r_   r`   re     rf   c                   s   g | ]}t | d qS )r[  )r  r   )r   r   r_   r`   r     rf   )	r   r  rj   rl   r   r   r  r  r9  )r  r   r  r  r  r8  r_   )r   r   r  r`   broadcast_arrays  s    r  c                   sH    fdd}t t d j |_W d   n1 s:0    Y  |S )zOffsets inputs by offset

    >>> double = lambda x: x * 2
    >>> f = offset_func(double, (10,))
    >>> f(1)
    22
    >>> f(300)
    620
    c                    s   t tt| } | S ra   )r   r   r   )r   Zargs2r   rZ  r_   r`   _offset  s    zoffset_func.<locals>._offsetZoffset_N)
contextlibsuppressr   r[   )r   rZ  r   r  r_   r  r`   offset_func  s    *r  c                   s^   | sdS g }d dd t | ttfrV|t fdd| D  | d }  d7  qt|S )a_  Chunks tuple from nested list of arrays

    >>> x = np.array([1, 2])
    >>> chunks_from_arrays([x, x])
    ((2, 2),)

    >>> x = np.array([[1, 2]])
    >>> chunks_from_arrays([[x], [x]])
    ((1, 1), (2,))

    >>> x = np.array([[1, 2]])
    >>> chunks_from_arrays([[x, x]])
    ((1,), (2, 2))

    >>> chunks_from_arrays([1, 1])
    ((1, 1),)
    r_   r   c                 S  s"   z| j W S  ty   Y dS 0 d S )Nr   )r   rl  r   r_   r_   r`   r     s    z!chunks_from_arrays.<locals>.shapec                 3  s   | ]}t |  V  qd S ra   )	deepfirstr   r   r   r_   r`   re     rf   z%chunks_from_arrays.<locals>.<genexpr>rK   )rg   r   rl   r0  )r   r8  r_   r  r`   chunks_from_arrays  s    
r  c                 C  s"   t | ttfs| S t| d S dS )z`First element in a nested list

    >>> deepfirst([[[1, 2], [3, 4]], [5, 6], [7, 8]])
    1
    r   N)rg   r   rl   r  r  r_   r_   r`   r    s    r  c                 C  s2   t | tu r*tt| gtt| d  S dS dS )zGet the shape of nested listr   r_   N)r   r   rl   r   	shapelist)rr   r_   r_   r`   r  
  s    r  c                   s   t  t| krtd|dk r(tdt  t t krDtdt d }t|  fddt|| D }tt	| }t
||S )zPermute axes of nested list

    >>> transposelist([[1,1,1],[1,1,1]], [2,1])
    [[[1, 1], [1, 1], [1, 1]]]

    >>> transposelist([[1,1,1],[1,1,1]], [2,1], extradims=1)
    [[[[1], [1]], [[1], [1]], [[1], [1]]]]
    2Length of axes should equal depth of nested arraysr   z`newdims` should be positivez`axes` should be uniquerK   c                   s&   g | ]}| v r  | nd qS r   r  r  r   r   r_   r`   r   $  s   z!transposelist.<locals>.<listcomp>)r   rG   r   r   r   r  r   r   r"   rO  r4   )r   r   	extradimsr   Znewshaper8  r_   r  r`   transposelist  s    	
r  c                   sj  ddl m}  fddD s*td stfddD stfddtD }td	d
 j d|d
 d  d|d j dtjdd D dfddD j	d d
k rֈ d t
fddtj	D }dd D }|s}t|}|d
kr\z|j||jdW S  tyZ   |j||jd Y S 0 ttttfdd|D }t| \}	}tdd |D dksJ |d
 jd d| f |d
 jd  }
dd |D dt }tt|ggdd |
D R  }fdd|D }fdd|D }tt||}tj|||d}t|||
d S )!a  
    Stack arrays along a new axis

    Given a sequence of dask arrays, form a new dask array by stacking them
    along a new dimension (axis=0 by default)

    Parameters
    ----------
    seq: list of dask.arrays
    axis: int
        Dimension along which to align all of the arrays
    allow_unknown_chunksizes: bool
        Allow unknown chunksizes, such as come from converting from dask
        dataframes.  Dask.array is unable to verify that chunks line up.  If
        data comes from differently aligned sources then this can cause
        unexpected results.

    Examples
    --------

    Create slices

    >>> import dask.array as da
    >>> import numpy as np

    >>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2))
    ...         for i in range(3)]

    >>> x = da.stack(data, axis=0)
    >>> x.shape
    (3, 4, 4)

    >>> da.stack(data, axis=1).shape
    (4, 3, 4)

    >>> da.stack(data, axis=-1).shape
    (4, 4, 3)

    Result is a new dask Array

    See Also
    --------
    concatenate
    rK   r  c                   s   g | ]}t | d qS r  r  r   r  r_   r`   r   [  rf   zstack.<locals>.<listcomp>zNeed array(s) to stackc                 3  s   | ]}|j  d  j kV  qdS r  r  rb   r  r_   r`   re   _  rf   zstack.<locals>.<genexpr>c                 3  s&   | ]}|d  j  d j kr|V  qdS r  r  r  r  r_   r`   re   `  rf   zCStacked arrays must have the same shape. The first array had shape r   z, while array z has shape r  c                 S  s   g | ]}t |qS r_   r   r   r_   r_   r`   r   f  rf   r   c                   s   g | ]}|  jqS r_   r  rb   rK  r_   r`   r   g  rf   c                 3  sF   | ]>}| krt n&| k r,d  j| nd  j|d  V  qdS r  r  r  r  r_   r`   re   l  s   
c                 S  s   g | ]}|j r|qS r_   r  r   r_   r_   r`   r   s  rf   r  r  c                 3  s   | ]}| fV  qd S ra   r_   rb   )r  r_   r`   re     rf   c                 S  s   h | ]
}|j qS r_   r$  r   r_   r_   r`   r    rf   zstack.<locals>.<setcomp>Nr   c                 S  s   g | ]
}|j qS r_   rt  r   r_   r_   r`   r     rf   zstack-c                 S  s   g | ]}t t|qS r_   r  r  r_   r_   r`   r     rf   c                   s>   g | ]6}| d    f|d  d    | d d  qS r  r_   r  )r   r  r_   r`   r     s   c              	     s>   g | ]6}t |td d d f  d td d d f    fqS )Nra   )rM   rh   )rc   inp)r   r   r_   r`   r     s   rd  rK  )r   r  r   r   r   r-  r   rp   r  r   rl   r   r   r  r   r(  r  r   r   r  r   r)   r   r   r   r1   r   r   )r  r   r  r  idxr   r  r3  r  r  r   r   r   r  r  r   r  r_   )r  r   r  r   r  r   r  r`   r  ,  sb    -


. r  c           
        sh  t tjdd t| } | s$tdS ttj| tt	fddd d}t
 fdd	tj| tt	fdD sz t| }t| t	t|jd
W S  ty   Y n0 tt|tjurt| }t| tt|jd
S t| }|s| S t| }t	tt|}dd }tj||t| d}tt|tj| tt	fdD ]6\}}	t|	drX|	j|k rX|	d }	q@|	||< q,|S )a  Recursive np.concatenate

    Input should be a nested list of numpy arrays arranged in the order they
    should appear in the array itself.  Each array should have the same number
    of dimensions as the desired output and the nesting of the lists.

    >>> x = np.array([[1, 2]])
    >>> concatenate3([[x, x, x], [x, x, x]])
    array([[1, 2, 1, 2, 1, 2],
           [1, 2, 1, 2, 1, 2]])

    >>> concatenate3([[x, x], [x, x], [x, x]])
    array([[1, 2, 1, 2],
           [1, 2, 1, 2],
           [1, 2, 1, 2]])
    r  Nr   )	containerc                 S  s   t | ddS r   r   r   r_   r_   r`   r     rf   zconcatenate3.<locals>.<lambda>r   c                 3  s"   | ]} t t|d  u V  qdS )r  N)r   r   )rc   r   ZNDARRAY_ARRAY_FUNCTIONr_   r`   re     s   zconcatenate3.<locals>.<genexpr>r   c                 S  s(   z| j W S  ty"   t|  Y S 0 d S ra   )r   rl  r   r   r_   r_   r`   r     s    zconcatenate3.<locals>.dtyper   r   )N.)r   rp   r  r;   r  r   r"   rO  r   rl   r   r^  r   r   r   r(  rP   r   r   r   rG   r  r   r   r  r   r   r   )
r   Zadvancedrd   r   r   r   r   r8  r  r   r_   r!  r`   r]    sD    
r]  c                 C  sF   t |t| krtdtdt| jt|d  }tt| ||dS )z*Recursively call np.concatenate along axesr  r   rK   )r  )r   rG   r   r   r  r   r]  r  )r   r   r  r_   r_   r`   concatenate_axes  s    r"  r$  c                  s   t |dkr$t|d tr$|d }nBt |dkr^t|d tr^t|d tr^|d |d i}ntdddl}|j| dd< fdd	| D }t	t
| | W d   n1 s0    Y  dS )
a  Store arrays in HDF5 file

    This saves several dask arrays into several datapaths in an HDF5 file.
    It creates the necessary datasets and handles clean file opening/closing.

    Parameters
    ----------
    chunks: tuple or ``True``
        Chunk shape, or ``True`` to pass the chunks from the dask array.
        Defaults to ``True``.

    Examples
    --------

    >>> da.to_hdf5('myfile.hdf5', '/x', x)  # doctest: +SKIP

    or

    >>> da.to_hdf5('myfile.hdf5', {'/x': x, '/y': y})  # doctest: +SKIP

    Optionally provide arguments as though to ``h5py.File.create_dataset``

    >>> da.to_hdf5('myfile.hdf5', '/x', x, compression='lzf', shuffle=True)  # doctest: +SKIP

    >>> da.to_hdf5('myfile.hdf5', '/x', x, chunks=(10,20,30))  # doctest: +SKIP

    This can also be used as a method on a single Array

    >>> x.to_hdf5('myfile.hdf5', '/x')  # doctest: +SKIP

    See Also
    --------
    da.store
    h5py.File.create_dataset
    rK   r   r   z/Please provide {'/data/path': array} dictionaryNrr   )r  c              	     sJ   g | ]B\}}j |f|j|j d u r8tdd |jD n dqS )Tc                 s  s   | ]}|d  V  qdS r  r_   r  r_   r_   r`   re     rf   z%to_hdf5.<locals>.<listcomp>.<genexpr>)r   r   r   )Zrequire_datasetr   r   rl   r   )rc   Zdprd   r   r   r   r_   r`   r     s   zto_hdf5.<locals>.<listcomp>)r   rg   r   r   r   r   h5pyZFiler1  rT  r   r  )r  r   r   r   r  r$  Zdsetsr_   r#  r`   r    s    $
(
r  c                 C  st   g }d }}t | t | }|| |k rl| | durL|| |  |d7 }q|||  |d7 }|d7 }qt|S )zK

    >>> interleave_none([0, None, 2, None], [1, 3])
    (0, 1, 2, 3)
    r   NrK   )r   r0  rl   )rr   rs   r8  r  r  r3  r_   r_   r`   interleave_none'  s    

r%  c                 C  s   | |ft dd |D  S )zE

    >>> keyname('x', 3, [None, None, 0, 2])
    ('x', 3, 0, 2)
    c                 s  s   | ]}|d ur|V  qd S ra   r_   rF  r_   r_   r`   re   A  rf   zkeyname.<locals>.<genexpr>r  )r   r  okeyr_   r_   r`   keyname;  s    r'  c                 G  s,  t | j|}g }g }t|D ]Z\}}t|tr:|| qt|tr^|| |td q|td || qt|}t|}| | } i }tt|| j	D ]r\}\}}t|tst
j|dd}|jjdkrtd||k|| k B  rtd|||f ||; }|||< q|r(t| |} | S )a3  Point wise indexing with broadcasting.

    >>> x = np.arange(56).reshape((7, 8))
    >>> x
    array([[ 0,  1,  2,  3,  4,  5,  6,  7],
           [ 8,  9, 10, 11, 12, 13, 14, 15],
           [16, 17, 18, 19, 20, 21, 22, 23],
           [24, 25, 26, 27, 28, 29, 30, 31],
           [32, 33, 34, 35, 36, 37, 38, 39],
           [40, 41, 42, 43, 44, 45, 46, 47],
           [48, 49, 50, 51, 52, 53, 54, 55]])

    >>> d = from_array(x, chunks=(3, 4))
    >>> result = _vindex(d, [0, 1, 6, 0], [0, 1, 0, 7])
    >>> result.compute()
    array([ 0,  9, 48,  7])
    NTr	  rs   z4vindex does not support indexing with boolean arrayszNvindex key has entries out of bounds for indexing along axis %s of size %s: %r)rU   r   r-  rg   r   r0  rh   rl   r   r   rp   rX   r   r  r  rm   _vindex_array)rd   indexesZnonfancy_indexesZreduced_indexesr  r  Zarray_indexesr  r_   r_   r`   r  D  s>    





r  c                   s  zt j|  }W nJ ty\ } z2ddd | D }td| |W Y d}~n
d}~0 0 |d j}tt||fddt	| j
D }|dg| j
t|   d	d |D }d
d | jD }dd t||D  t|}t| |}	d|	 }
t }ttdd |D  D ]R\}}dd t |D } fddtt||D }||t|t|f qdd t|| jD }|d|rt|fnd t|}|rtd|dd  D ttdd t|| jD  }dd |D }d|	 d|	 }i }|D ]tD ]L\}}tt| jft| t|tttd|  f|f|t|< qtfddD fddt	tD f|t|d< qtt j!|
|| gd|
|| j"| j#d}|$||jdd  S ddl%m&} |tt't(||| j"|
d}|$||jdd  S )z+Point wise indexing with only NumPy Arrays.r  c                 s  s   | ]}t |jV  qd S ra   )r   r   r   r_   r_   r`   re     rf   z _vindex_array.<locals>.<genexpr>zLshape mismatch: indexing arrays could not be broadcast together with shapes Nr   c                   s(   g | ] }| v r  |    nd qS ra   )r  r  r  )lookupr_   r`   r     s   z!_vindex_array.<locals>.<listcomp>c                 S  s    g | ]}|d urt |n|qS ra   r  )rc   r  r_   r_   r`   r     s   c                 S  s   g | ]}t ttd | qS r  )r   r   r   r  r_   r_   r`   r     rf   c                 S  s   g | ]\}}|d ur|qS ra   r_   )rc   r  rs   r_   r_   r`   r     rf   zvindex-merge-c                 S  s   g | ]}|d ur|qS ra   r_   r  r_   r_   r`   r     rf   c                 S  s   g | ]\}}t ||d  qS r   r   )rc   rs   r  r_   r_   r`   r     rf   c                   s$   g | ]\}\}}| | |  qS r_   r_   )rc   r   r  r  )bounds2r_   r`   r     s   c                 S  s   g | ]\}}|d u r|qS ra   r_   r  r_   r_   r`   r     rf   rU  rK   c                 S  s   i | ]\}}|r||qS r_   r_   )rc   r   r  r_   r_   r`   r    rf   z!_vindex_array.<locals>.<dictcomp>c                 S  s.   g | ]&\}}|d u r$t tt|nd gqS ra   )r   r   r   r  r_   r_   r`   r     s   c                 S  s"   g | ]}|d u rt d d nd qS ra   r   r  r_   r_   r`   r     rf   zvindex-slice-r   c                   s   g | ]}t td  | qS rU  )r   r   r  )	per_blockr_   r`   r     rf   c                   s   g | ]}t  |qS r_   )r'  r  )r   r&  r_   r`   r     rf   rd  rK  )r  )r   r   r   ))rp   r  r  r   r   r  r   r   r   r   r   r  r   r   	_get_axisr)   r   r-  r0  rl   r/  r   r1  r   _vindex_transpose_vindex_slicer   r%  r   r'  _vindex_merger   r1   r   r   rb  r  r  r  r   r   )rd   Zdict_indexesZbroadcast_indexesr   Z
shapes_strZbroadcast_shapeZflat_indexesZboundsr   r   Zout_namepointsr  r  Z	block_idxZinblock_idxr   Zother_blocksZfull_slicesZvindex_merge_namer}  r   Z	result_1dr  r_   )r+  r*  r   r&  r,  r`   r(  }  s    





	r(  c                 C  s<   t | }dd | D } td| }|t|  }|jdS )aO  Get axis along which point-wise slicing results lie

    This is mostly a hack because I can't figure out NumPy's rule on this and
    can't be bothered to go reading.

    >>> _get_axis([[1, 2], None, [1, 2], None])
    0
    >>> _get_axis([None, [1, 2], [1, 2], None])
    1
    >>> _get_axis([None, None, [1, 2], [1, 2]])
    2
    c                 S  s$   g | ]}|d u rt d d ndgqS r  r   r  r_   r_   r`   r     rf   z_get_axis.<locals>.<listcomp>)r   rK   )r   rp   r  rl   r   r  )r)  r   rd   Zx2r_   r_   r`   r-    s
    r-  c                 C  s   dd |D }| t | S )z%Pull out point-wise slices from blockc                 S  s"   g | ]}t |tr|nt|qS r_   )rg   rh   r   )rc   pr_   r_   r`   r     rf   z!_vindex_slice.<locals>.<listcomp>r  )r  r1  r_   r_   r`   r/    s    r/  c                 C  s0   |gt t| t t|d | j }| |S )z6Rotate block so that points are on the first dimensionrK   )r   r   r   r  )r  r   r   r_   r_   r`   r.    s    &r.  c           	      C  s   t tt | } t |}ttt| }t |d j}||d< t|}|d j}tj|d ||d}dd t	|j
D }t| |D ]\}}||d< ||t|< q~|S )z

    >>> locations = [0], [2, 1]
    >>> values = [np.array([[1, 2, 3]]),
    ...           np.array([[10, 20, 30], [40, 50, 60]])]

    >>> _vindex_merge(locations, values)
    array([[ 1,  2,  3],
           [40, 50, 60],
           [10, 20, 30]])
    r   )r   r   c                 S  s   g | ]}t d d qS ra   r   r  r_   r_   r`   r     rf   z!_vindex_merge.<locals>.<listcomp>)r   r   r   r   r   rl   r   rp   r  r   r   r   )	Z	locationsr  r3  r   r   rd   r  r  r  r_   r_   r`   r0    s    
r0  c           	        s   t  fddt|jD }||}tjs<t ||j d}t	tj
dd}t|| W d   n1 s0    Y  dtt  fdd	tt| D }tj||gd
}tt|t| dS )an  Write dask array to a stack of .npy files

    This partitions the dask.array along one axis and stores each block along
    that axis as a single .npy file in the specified directory

    Examples
    --------
    >>> x = da.ones((5, 10, 10), chunks=(2, 4, 4))  # doctest: +SKIP
    >>> da.to_npy_stack('data/', x, axis=0)  # doctest: +SKIP

    The ``.npy`` files store numpy arrays for ``x[0:2], x[2:4], and x[4:5]``
    respectively, as is specified by the chunk size along the zeroth axis::

        $ tree data/
        data/
        |-- 0.npy
        |-- 1.npy
        |-- 2.npy
        |-- info

    The ``info`` file stores the dtype, chunks, and axis information of the array.
    You can load these stacks with the :func:`dask.array.from_npy_stack` function.

    >>> y = da.from_npy_stack('data/')  # doctest: +SKIP

    See Also
    --------
    from_npy_stack
    c                 3  s(   | ] \}}| kr|nt |fV  qd S ra   rW  r  r   r_   r`   re   >  rf   zto_npy_stack.<locals>.<genexpr>)r   r   r   r4  wbNzto-npy-stack-c              	     s0   i | ](\}}|ft jtj d | |fqS z%d.npy)rp   Zsaver  r  r   )rc   r  r   )dirnamer   r_   r`   r  J  s   z to_npy_stack.<locals>.<dictcomp>rd  )rl   r-  r   rn  r  r  existsmkdirr   openr   pickledumpr   r  r  r"   rO  r>  r1   r   r%   r   r   )	r5  rd   r   r   xxr   r   r}  r  r_   )r   r5  r   r`   to_npy_stack  s    

*r<  rA  c                   s   t tj dd}t|}W d   n1 s40    Y  |d }|d }|d }d  }tt|ggdd	 |D R  } fd
d	tt	|| D }	t
t||	}
t|
|||S )zLoad dask array from stack of npy files

    See :func:`dask.array.to_npy_stack` for docstring.

    Parameters
    ----------
    dirname: string
        Directory of .npy files
    mmap_mode: (None or 'r')
        Read data in memory map mode
    r4  rbNr   r   r   zfrom-npy-stack-%sc                 S  s   g | ]}t t|qS r_   r  r  r_   r_   r`   r   g  rf   z"from_npy_stack.<locals>.<listcomp>c                   s&   g | ]}t jtj d | fqS r4  )rp   loadr  r  r   r  r5  	mmap_moder_   r`   r   h  s   )r8  r  r  r   r9  r>  r   r   r   r   r   r   r   )r5  r@  r   r4  r   r   r   r   r   r  r}  r_   r?  r`   from_npy_stackS  s    ( rA  c                 C  s|   t |st|st|rfddlm} tdd |dd D sBJ dgt|d d  }|| |||S t| ||||dS dS )	zGeneric constructor for dask.array or dask.dataframe objects.

    Decides the appropriate output class based on the type of `meta` provided.
    r   )new_dd_objectc                 s  s   | ]}t |d kV  qdS r  r  r  r_   r_   r`   re   y  rf   z new_da_object.<locals>.<genexpr>rK   Nr   )r   r   r   r   )rB   rE   rC   Zdataframe.corerB  r   r   r   )r}  r   r   r   r   rB  Z	divisionsr_   r_   r`   new_da_objectq  s    rC  c                   @  sr   e Zd ZdZdd dddZddddd	Zd
ddddZeddddZeddddZ	ddddZ
dS )r  a  An array-like interface to the blocks of an array.

    ``BlockView`` provides an array-like interface
    to the blocks of a dask array.  Numpy-style indexing of a
     ``BlockView`` returns a selection of blocks as a new dask array.

    You can index ``BlockView`` like a numpy array of shape
    equal to the number of blocks in each dimension, (available as
    array.blocks.size).  The dimensionality of the output array matches
    the dimension of this array, even if integer indices are passed.
    Slicing with ``np.newaxis`` or multiple lists is not supported.

    Examples
    --------
    >>> import dask.array as da
    >>> from dask.array.core import BlockView
    >>> x = da.arange(8, chunks=2)
    >>> bv = BlockView(x)
    >>> bv.shape # aliases x.numblocks
    (4,)
    >>> bv.size
    4
    >>> bv[0].compute()
    array([0, 1])
    >>> bv[:3].compute()
    array([0, 1, 2, 3, 4, 5])
    >>> bv[::2].compute()
    array([0, 1, 4, 5])
    >>> bv[[-1, 0]].compute()
    array([6, 7, 0, 1])
    >>> bv.ravel()  # doctest: +NORMALIZE_WHITESPACE
    [dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
     dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
     dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
     dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>]

    Returns
    -------
    An instance of ``da.array.Blockview``
    r   )rX   r   c                 C  s
   || _ d S ra   )_array)r   rX   r_   r_   r`   __init__  s    zBlockView.__init__z-int | Sequence[int] | slice | Sequence[slice])r  r   c                   s   ddl m} t|ts|f}tdd |D dkr:tdtdd |D rTtd||| jj}tdd |D }d	t	| j|  | jj
| td
d t| jj|D }tdd |D  } fdd|D }tj || jgd}t| || jdS )NrK   )r  c                 s  s   | ]}t |tjtfV  qd S ra   )rg   rp   r  r   r  r_   r_   r`   re     rf   z(BlockView.__getitem__.<locals>.<genexpr>z!Can only slice with a single listc                 s  s   | ]}|d u V  qd S ra   r_   r  r_   r_   r`   re     rf   z0Slicing with np.newaxis or None is not supportedc                 s  s*   | ]"}t |trt||d  n|V  qdS r  )rg   r   rh   rF  r_   r_   r`   re     rf   zblocks-c                 s  s(   | ] \}}t t||  V  qd S ra   )rl   rp   rX   r  )rc   ru   r  r_   r_   r`   re     s   c                 s  s   | ]}t t|V  qd S ra   r  r  r_   r_   r`   re     rf   c                   s$   i | ]} f| t |  qS r_   )rl   r  r  r   Znew_keysr_   r`   r    rf   z)BlockView.__getitem__.<locals>.<dictcomp>rd  rK  )r  r  rg   rl   r   r   rm   rD  r   r)   r  r   r   r   r1   r   r   )r   r  r  r   r   r   r  r_   rF  r`   r    s$    
zBlockView.__getitem__r   r   )r   r   c                 C  s   t |tr| j|ju S tS d S ra   )rg   r  rD  r   r   r_   r_   r`   r    s    
zBlockView.__eq__rZ  r   c                 C  s   t | jS )z:
        The total number of blocks in the array.
        )rp   r  r   rr  r_   r_   r`   r    s    zBlockView.sizeztuple[int, ...]c                 C  s   | j jS )zS
        The number of blocks per axis. Alias of ``dask.array.numblocks``.
        )rD  r   rr  r_   r_   r`   r     s    zBlockView.shapezlist[Array]c                   s    fddt  jD S )zT
        Return a flattened list of all the blocks in the array in C order.
        c                   s   g | ]} | qS r_   r_   )rc   r  rr  r_   r`   r     rf   z#BlockView.ravel.<locals>.<listcomp>)rp   Zndindexr   rr  r_   rr  r`   r    s    zBlockView.ravelN)r[   r\   r]   r^   rE  r  r  r  r  r   r  r_   r_   r_   r`   r    s   )r  )r,  r   )TN)TN)TN)NN)r   N)TNTF)NNNN)N)rl  NFNTNNF)NNNNF)NNFNTF)NNN)F)r   F)FNN)NN)NN)r   )r   F)r   )rA  )NN)Z
__future__r   r  r  r  r  r9  r   r   r   r  r)  r   collections.abcr   r   r   r   r	   r
   r   	functoolsr   r   r   	itertoolsr   r   Znumbersr   r   r   r   	threadingr   typingr   Znumpyrp   Zfsspecr   Ztlzr   r   r   r   r   r   Ztlz.curriedr   r   r    r!   r"   r#   r  r$   r%   r&   r'   r(   r)   r*   r   r+   contextr,   r-   r0   r/   Zhighlevelgraphr1   r2   r   r3   r4   r5   r   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   ZwidgetsrJ   rL   rM   Zchunk_typesrN   rO   r   rP   rQ   rR   Znumpy_compatrS   rT   r  rU   rV   rW   Zupdate_defaultsrY  WarningrZ   rn   rx   ry   optimizationrz   r{   r|   r   r   r   r   r   r   r   r   r   r   r  r9  rT  r\  r`  r  rk  r   ru  r   r  r  r  r  r  r  r  r  r  r  r  r  r^  r  r   r  r  r  rP  rQ  rj   r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r]  r"  r  r%  r'  r  r(  r-  r/  r.  r0  r<  rA  rC  r  r,  r   r_   r_   r_   r`   <module>   st  $	  X


	
T
?
H   @/     .	            
 #
}        
 k     
?      
y(
"Dc
 +
 1
 G  IM##y*
K$

qF	;	9a!
4

e