
    Cd@o                    z   d dl mZ d dlZd dlmZmZ d dlZd dlm	Z	m
Z
mZ d dlmZ d dlmZ d dlmZmZmZmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d Z d Z!d#dZ"d#dZ#d Z$d Z%d Z&d Z'd Z(d Z)d$dZ*d Z+dddZ,d Z-dddddddZ.d Z/d  Z0d! Z1 eej2        j3                  d#d"            Z4dS )%    )annotationsN)IntegralNumber)concatgetpartial)map)chunk)Arrayconcatenate
map_blocksunify_chunks)
empty_like	full_like)tokenize)HighLevelGraph)ArrayOverlapLayer)derived_fromc                   g }t          |           D ]\  }}|                    |d          }t          |t                    r|d         }|d         }n|}|}t	          |          dk    r|                    |           n|d         |z   g}|d         |z   g}	g }
|dd         D ]}|
                    ||z   |z              |                    ||
z   |	z              |S )z&Get new chunks for array with overlap.r      )	enumerater   
isinstancetuplelenappend)original_chunksaxeschunksibdsdepth
left_depthright_depthleftrightmidbds               2lib/python3.11/site-packages/dask/array/overlap.py_overlap_internal_chunksr*      s   FO,, . .3AeU## 	 qJ(KKJKs88q==MM#F[()DWz)*EC!B$i : :

2
?[89999MM$*u,----M    c                    t          | |          }d|z   }t          | j        || j        | j        |          }t          j        ||| g          }t          | j        |          }t          ||||           S )aJ  Share boundaries between neighboring blocks

    Parameters
    ----------

    x: da.Array
        A dask array
    axes: dict
        The size of the shared boundary per axis

    The axes input informs how many cells to overlap between neighboring blocks
    {0: 2, 2: 5} means share two cells in 0 axis, 5 cells in 2 axis
    zoverlap-)namer   r   	numblockstoken)dependencies)meta)	r   r   r-   r   r.   r   from_collectionsr*   r   )xr   r/   r-   graphr   s         r)   overlap_internalr5   +   s     QEDVx+  E +D%qcJJJE%ah55Ff1----r+   c                P    t          | j        |          }t          | ||          S )zTrim sides from each block.

    This couples well with the ``map_overlap`` operation which may leave
    excess data on each block.

    See also
    --------
    dask.array.overlap.map_overlap

    r   boundary)coerce_depthndimtrim_internal)r3   r"   r8   r   s       r)   trim_overlapr<   I   s*     &&D9999r+   c                :   t          | j        |          }g }t          | j                  D ]-\  }}|                    |d          }|                    |d          }g }t          |          D ]\  }	}
|dk    r1t          |t                    r|
t          |          z
  }
n|
|dz  z
  }
nvt          |t                    r7|	dk    r|
|d         z
  n|
}
|	t          |          dz
  k    r|
|d         z
  n|
}
n*|	dk    r|
|z
  n|
}
|	t          |          dz
  k    r|
|z
  n|
}
|	                    |
           |	                    t          |                     /t          |          }t          t          t          ||          | || j        | j                  S )zTrim sides from each block

    This couples well with the overlap operation, which may leave excess data on
    each block

    See also
    --------
    dask.array.chunk.trim
    dask.array.map_blocks
    noner      r   r7   )r   dtyper1   )coerce_boundaryr:   r   r   r   r   r   sumr   r   r   r   _trimr@   _meta)r3   r   r8   olistr    r(   bdyoverlapilistjdr   s               r)   r;   r;   Z   s    qvx00HE18$$ # #2ll1f%%((1a..bMM 	 	DAqf}}gu-- (CLL(AAGaKAA gu-- ?*+q&&GAJaA*+s2ww{*:*:GAJAA'(AvvG1A'(CGGaK'7'7GQALLOOOOU5\\""""5\\FD8444	gW   r+   c                   fdt          | j                  D             d D             }d D             }fdt          t          |d         d         |                    D             }fdt          t          |d         d         |d         d         |                    D             }t	          d	 t          ||          D                       }| |         S )
zSimilar to dask.array.chunk.trim but requires one to specificy the
    boundary condition.

    ``axes``, and ``boundary`` are assumed to have been coerced.

    c                <    g | ]}                     |d           S )r   r   ).0r    r   s     r)   
<listcomp>z_trim.<locals>.<listcomp>   s%    222qDHHQNN222r+   c              3  T   K   | ]#}t          |t                    r|d          n|V  $dS r   N)r   r   rN   axs     r)   	<genexpr>z_trim.<locals>.<genexpr>   s9      HHR:b%008"Q%%bHHHHHHr+   c              3     K   | ]F}t          |t                    r|d          r	|d           nt          |t                    r|r| ndV  GdS r   N)r   r   r   rR   s     r)   rT   z_trim.<locals>.<genexpr>   s         	 b%  	%'U	A b(##(*bSS     r+   c              3  l   K   | ].\  }\  }}|d k    r                     |d          dk    rd n|V  /dS )r   r>   NrM   )rN   r    chunk_locationrS   r8   s       r)   rT   z_trim.<locals>.<genexpr>   sf        #A# !!hll1f&=&=&G&Gb     r+   r   zchunk-locationc              3  t   K   | ]2\  }\  }}}||d z
  k    r                     |d          dk    rdn|V  3dS )r   r>   NrM   )rN   r    r   rX   rS   r8   s        r)   rT   z_trim.<locals>.<genexpr>   sr         ,A+ fqj((X\\!V-D-D-N-N 	     r+   z
num-chunksc              3  <   K   | ]\  }}t          ||          V  d S N)slice)rN   frontbacks      r)   rT   z_trim.<locals>.<genexpr>   s0      QQ{udeT""QQQQQQr+   )ranger:   r   zipr   )	r3   r   r8   
block_info
axes_front	axes_back
trim_front	trim_backinds	    ``      r)   rC   rC      s*    3222E!&MM222DHH4HHHJ    I   '0
1./<<(
 (
  J    09
1l+Z];K-LiXX0
 0
	  I QQc*i6P6PQQQ
Q
QCS6Mr+   c                   t          ddd          f|z  t          d|          fz   t          ddd          f| j        |z
  dz
  z  z   }t          ddd          f|z  t          | d          fz   t          ddd          f| j        |z
  dz
  z  z   }| |         }| |         }t          ||||          \  }}t          || |g|          S )zuCopy a slice of an array around to its other side

    Useful to create periodic boundary conditions for overlap
    Nr   r   axisr\   r:   _remove_overlap_boundariesr   r3   ri   r"   r%   r&   lrs          r)   periodicro      s     
tT4	 	 "T)E??
	tT""
$(9
:	; 	 
tT4	 	 "T)%
 	!tT""
$(9
:	; 

 	
$A	%A%aD%88DAq1ayt,,,,r+   c                D   |dk    rIt          ddd          f|z  t          dd          fz   t          ddd          f| j        |z
  dz
  z  z   }nLt          ddd          f|z  t          |dz
  dd          fz   t          ddd          f| j        |z
  dz
  z  z   }t          ddd          f|z  t          d| dz
  d          fz   t          ddd          f| j        |z
  dz
  z  z   }| |         }| |         }t          ||||          \  }}t          || |g|          S )z[Reflect boundaries of array on the same side

    This is the converse of ``periodic``
    r   Nr   r   rh   rj   rl   s          r)   reflectrq      sj   
 zz4t$$&-Q{{nT4&&(AFTMA,=>? 	 4t$$&-UQYb))+,T4&&(AFTMA,=>? 	 
tT4	 	 "T)eVaZ$$
&	'tT""
$(9
:	; 

 	
$A	%A%aD%88DAq1ayt,,,,r+   c                   t          ddd          f|z  t          dd          fz   t          ddd          f| j        |z
  dz
  z  z   }t          ddd          f|z  t          ddd          fz   t          ddd          f| j        |z
  dz
  z  z   }t          | |         g|z  |          }t          | |         g|z  |          }t          ||||          \  }}t          || |g|          S )zEach reflect each boundary value outwards

    This mimics what the skimage.filters.gaussian_filter(... mode="nearest")
    does.
    Nr   r   r   rh   )r\   r:   r   rk   rl   s          r)   nearestrt      s!    
tT4	 	 "T)A;;.	tT""
$(9
:	; 	 
tT4	 	 "T)R
	tT""
$(9
:	; 
 	QtWI%D111AQuXJ&T222A%aD%88DAq1ayt,,,,r+   c           
         t          | j                  }|f||<   t          | |t          t	          t
          |                    t          |          | j                  }t          || |g|          S )z*Add constant slice to either side of arrayshaper   r@   rh   )listr   r   r   r	   rB   r@   r   )r3   ri   r"   valuer   cs         r)   constantr{      sr    !(^^F8F4L	CV$$%%V}}g	 	 	A 1ayt,,,,r+   c                    t          | j                  }|f||<   t          |j                  }|f||<   |                     t          |                    } |                    t          |                    }| |fS r[   )rx   r   rechunkr   )rm   rn   ri   r"   lchunksrchunkss         r)   rk   rk     si    18nnGHGDM18nnGHGDM			%..!!A			%..!!Aa4Kr+   c                H   t          t                    s fdt          | j                  D             t          t                    s fdt          | j                  D             t          | j                  D ]}                    |d          }|dk    r                    |d          }|dk    r<|dk    rt          | ||          } T|dk    rt          | ||          } l|dk    rt          | ||          } |v rt          | |||                   } | S )zoAdd boundary conditions to an array before overlaping

    See Also
    --------
    periodic
    constant
    c                    i | ]}|S  r   )rN   r    kinds     r)   
<dictcomp>zboundaries.<locals>.<dictcomp>  s    ///A4///r+   c                    i | ]}|S r   r   )rN   r    r"   s     r)   r   zboundaries.<locals>.<dictcomp>!  s    111aE111r+   r   r>   ro   rq   rt   )	r   dictr_   r:   r   ro   rq   rt   r{   )r3   r"   r   r    rJ   	this_kinds    ``   r)   
boundariesr     sA    dD!! 0////qv///eT"" 211115==11116]] + +IIaOO66HHQ''	*$$Aq!!AA)##1a  AA)##1a  AA$YYAq$q'**AHr+   c                   | t          |          k    r|S g }d}|D ]_}|| k     r/|| | |z
  z   k    r|                    || |z
  z
             | }n||z  }|| k    r|                    |           d}|| k    r||z  }`|| k    r|                    |           nGt          |          dk    r|dxx         |z  cc<   n#t          d|  dt	          |           d          t          |          S )a  Determine new chunks to ensure that every chunk >= size

    Parameters
    ----------
    size: int
        The maximum size of any chunk.
    chunks: tuple
        Chunks along one axis, e.g. ``(3, 3, 2)``

    Examples
    --------
    >>> ensure_minimum_chunksize(10, (20, 20, 1))
    (20, 11, 10)
    >>> ensure_minimum_chunksize(3, (1, 1, 3))
    (5,)

    See Also
    --------
    overlap
    r   r   r   zThe overlapping depth z is larger than your array .)minr   r   
ValueErrorrB   r   )sizer   outputnewrz   s        r)   ensure_minimum_chunksizer   7  s3   * s6{{ F
C  t88TTAX&&&cTAX.///q$;;MM#C991HC
d{{c	V		r


c



XTXX#f++XXX
 
 	
 ==r+   T)allow_rechunkc               b   t          | j        |          }t          | j        |          d |                                D             }|rBt	          d t          || j                  D                       }|                     |          }nKt          d t          || j                  D                       }|rt          d| d| j         d          | }t          ||          }	t          |	|          }
fd|                                D             }t          j        |
|          }|S )a	  Share boundaries between neighboring blocks

    Parameters
    ----------

    x: da.Array
        A dask array
    depth: dict
        The size of the shared boundary per axis
    boundary: dict
        The boundary condition on each axis. Options are 'reflect', 'periodic',
        'nearest', 'none', or an array value.  Such a value will fill the
        boundary with that value.
    allow_rechunk: bool, keyword only
        Allows rechunking, otherwise chunk sizes need to match and core
        dimensions are to consist only of one chunk.

    The depth input informs how many cells to overlap between neighboring
    blocks ``{0: 2, 2: 5}`` means share two cells in 0 axis, 5 cells in 2 axis.
    Axes missing from this input will not be overlapped.

    Any axis containing chunks smaller than depth will be rechunked if
    possible, provided the keyword ``allow_rechunk`` is True (recommended).

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

    >>> x = np.arange(64).reshape((8, 8))
    >>> d = da.from_array(x, chunks=(4, 4))
    >>> d.chunks
    ((4, 4), (4, 4))

    >>> g = da.overlap.overlap(d, depth={0: 2, 1: 1},
    ...                       boundary={0: 100, 1: 'reflect'})
    >>> g.chunks
    ((8, 8), (6, 6))

    >>> np.array(g)
    array([[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
           [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
           [  0,   0,   1,   2,   3,   4,   3,   4,   5,   6,   7,   7],
           [  8,   8,   9,  10,  11,  12,  11,  12,  13,  14,  15,  15],
           [ 16,  16,  17,  18,  19,  20,  19,  20,  21,  22,  23,  23],
           [ 24,  24,  25,  26,  27,  28,  27,  28,  29,  30,  31,  31],
           [ 32,  32,  33,  34,  35,  36,  35,  36,  37,  38,  39,  39],
           [ 40,  40,  41,  42,  43,  44,  43,  44,  45,  46,  47,  47],
           [ 16,  16,  17,  18,  19,  20,  19,  20,  21,  22,  23,  23],
           [ 24,  24,  25,  26,  27,  28,  27,  28,  29,  30,  31,  31],
           [ 32,  32,  33,  34,  35,  36,  35,  36,  37,  38,  39,  39],
           [ 40,  40,  41,  42,  43,  44,  43,  44,  45,  46,  47,  47],
           [ 48,  48,  49,  50,  51,  52,  51,  52,  53,  54,  55,  55],
           [ 56,  56,  57,  58,  59,  60,  59,  60,  61,  62,  63,  63],
           [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
           [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]])
    c                Z    g | ](}t          |t                    rt          |          n|)S r   )r   r   maxrN   rJ   s     r)   rO   zoverlap.<locals>.<listcomp>  s1    MMM
1e,,3c!fff!MMMr+   c              3  <   K   | ]\  }}t          ||          V  d S r[   r   )rN   r   rz   s      r)   rT   zoverlap.<locals>.<genexpr>  sB       
 
29$$T1--
 
 
 
 
 
r+   c                :    g | ]\  }}t          |          |k     S r   )r   rN   rJ   rz   s      r)   rO   zoverlap.<locals>.<listcomp>  s&    (V(V(V1Q!(V(V(Vr+   zOverlap depth is larger than smallest chunksize.
Please set allow_rechunk=True to rechunk automatically.
Overlap depths required: z
Input chunks: 
c                Z    i | ]'\  }}|                     |d           d k    r|dz  nd(S )r>   r?   r   rM   )rN   kv	boundary2s      r)   r   zoverlap.<locals>.<dictcomp>  sL       BF!QIMM!V,,661q55A  r+   )r9   r:   rA   valuesr   r`   r   r}   anyr   r   r5   itemsr
   trim)r3   r"   r8   r   depth2depths
new_chunksx1original_chunks_too_smallx2x3r   x4r   s                @r)   rG   rG   j  ss   t !&%((F11IMMV]]__MMMF  
 
=@=R=R
 
 
 
 

 YYz"" %((V(VFAH@U@U(V(V(V$W$W!$ 	.,2. . "#. . .   	B		*	*B	"f	%	%B   JP,,..  D 
B		BIr+   c                >   |                                 D ]\  }}|                    |d          }|dk    r|dk    rt          | j                  }|||<   t          | j                  }|f||<   t          t          | d|           ||| j                  }t          | j                  }	t          |	|                   }
|
dxx         |z  cc<   |
dxx         |z  cc<   t          |
          |	|<   t          || |g|          } | 
                    |	          } | S )a?  
    Pads an array which has 'none' as the boundary type.
    Used to simplify trimming arrays which use 'none'.

    >>> import dask.array as da
    >>> x = da.arange(6, chunks=3)
    >>> add_dummy_padding(x, {0: 1}, {0: 'none'}).compute()  # doctest: +NORMALIZE_WHITESPACE
    array([..., 0, 1, 2, 3, 4, 5, ...])
    r   r>   rD   rv   r   rh   )r   r   rx   rw   r   r   getattrr@   r   r   r}   )r3   r"   r8   r   r   rJ   empty_shapeempty_chunksempty
out_chunks	ax_chunkss              r)   add_dummy_paddingr     s,       & &1IIaOO;;1q55qw--KKN>>L dLO7A&&!#g	  E ahJZ]++IaLLLALLLbMMMQMMM!),,JqMUAu-A666A		*%%AHr+   )r"   r8   r   align_arraysr   c          
        t          | t                    rt          |d                   rt          j        dt
                     g d}t          |                    d          |          t          |                    d          |          t          |                    d          ||          }|d         | g}} t          |           s4t          d	                    t          |           j                            t          d |D                       s,t          d		                    d
 |D                                 d }	 |	|t                     |	|t                    |rCd |D             }
t          t!          t#          t%          ||
                              ddi\  }}t          d D                       rt'          | g|R i |S t)          |          D ]\  }}t+          |j                  D ]e}t          |         |         t.                    rB|         |         dk    r0t1          d	                    |||         |                             fd } ||           |sd|vr|d         j        |d<   fdt%          |          D             } ||           t'          | g|R i |} ||g           |rt5          t)          |          d           d         d         }|         |         |                    dd          t          t8                    rgt;          d |D                       fdD             t/          fdt+          ||         j                  D                       }fdt)          |          D             fdt)          |          D             t=          |          S |S )a  Map a function over blocks of arrays with some overlap

    We share neighboring zones between blocks of the array, map a
    function, and then trim away the neighboring strips. If depth is
    larger than any chunk along a particular axis, then the array is
    rechunked.

    Note that this function will attempt to automatically determine the output
    array type before computing it, please refer to the ``meta`` keyword argument
    in ``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.
        If multiple arrays are provided, then the function should expect to
        receive chunks of each array in the same order.
    args : dask arrays
    depth: int, tuple, dict or list, keyword only
        The number of elements that each block should share with its neighbors
        If a tuple or dict then this can be different per axis.
        If a list then each element of that list must be an int, tuple or dict
        defining depth for the corresponding array in `args`.
        Asymmetric depths may be specified using a dict value of (-/+) tuples.
        Note that asymmetric depths are currently only supported when
        ``boundary`` is 'none'.
        The default value is 0.
    boundary: str, tuple, dict or list, keyword only
        How to handle the boundaries.
        Values include 'reflect', 'periodic', 'nearest', 'none',
        or any constant value like 0 or np.nan.
        If a list then each element must be a str, tuple or dict defining the
        boundary for the corresponding array in `args`.
        The default value is 'reflect'.
    trim: bool, keyword only
        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
    align_arrays: bool, keyword only
        Whether or not to align chunks along equally sized dimensions when
        multiple arrays are provided.  This allows for larger chunks in some
        arrays to be broken into smaller ones that match chunk sizes in other
        arrays such that they are compatible for block function mapping. If
        this is false, then an error will be thrown if arrays do not already
        have the same number of blocks in each dimension.
    allow_rechunk: bool, keyword only
        Allows rechunking, otherwise chunk sizes need to match and core
        dimensions are to consist only of one chunk.
    **kwargs:
        Other keyword arguments valid in ``map_blocks``

    Examples
    --------
    >>> import numpy as np
    >>> 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])

    >>> x = np.arange(16).reshape((4, 4))
    >>> d = da.from_array(x, chunks=(2, 2))
    >>> d.map_overlap(lambda x: x + x.size, depth=1, boundary='reflect').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]])

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

    >>> func = lambda x, y: x + y
    >>> x = da.arange(8).reshape(2, 4).rechunk((1, 2))
    >>> y = da.arange(4).rechunk(2)
    >>> da.map_overlap(func, x, y, depth=1, boundary='reflect').compute() # doctest: +NORMALIZE_WHITESPACE
    array([[ 0,  2,  4,  6],
           [ 4,  6,  8,  10]])

    When multiple arrays are given, they do not need to have the
    same number of dimensions but they must broadcast together.
    Arrays are aligned block by block (just as in ``da.map_blocks``)
    so the blocks must have a common chunk size.  This common chunking
    is determined automatically as long as ``align_arrays`` is True.

    >>> x = da.arange(8, chunks=4)
    >>> y = da.arange(8, chunks=2)
    >>> r = da.map_overlap(func, x, y, depth=1, boundary='reflect', align_arrays=True)
    >>> len(r.to_delayed())
    4

    >>> da.map_overlap(func, x, y, depth=1, boundary='reflect', align_arrays=False).compute()
    Traceback (most recent call last):
        ...
    ValueError: Shapes do not align {'.0': {2, 4}}

    Note also that this function is equivalent to ``map_blocks``
    by default.  A non-zero ``depth`` must be defined for any
    overlap to appear in the arrays provided to ``func``.

    >>> func = lambda x: x.sum()
    >>> x = da.ones(10, dtype='int')
    >>> block_args = dict(chunks=(), drop_axis=0)
    >>> da.map_blocks(func, x, **block_args).compute()
    10
    >>> da.map_overlap(func, x, **block_args, boundary='reflect').compute()
    10
    >>> da.map_overlap(func, x, **block_args, depth=1, boundary='reflect').compute()
    12

    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``:

    >>> 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]])

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

    >>> 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]])
    r   zThe use of map_overlap(array, func, **kwargs) is deprecated since dask 2.17.0 and will be an error in a future release. To silence this warning, use the syntax map_overlap(func, array0,[ array1, ...,] **kwargs) instead.)funcr"   r8   r   r"   r8   r   zFirst argument must be callable function, not {}
Usage:   da.map_overlap(function, x)
   or:   da.map_overlap(function, x, y, z)c              3  @   K   | ]}t          |t                    V  d S r[   )r   r   rN   r3   s     r)   rT   zmap_overlap.<locals>.<genexpr>  s,      22z!U##222222r+   z}All variadic arguments must be arrays, not {}
Usage:   da.map_overlap(function, x)
   or:   da.map_overlap(function, x, y, z)c                6    g | ]}t          |          j        S r   )type__name__r   s     r)   rO   zmap_overlap.<locals>.<listcomp>  s!    000aa!000r+   c                    t          |t                    s|gt          |           z  }fdt          | |          D             S )Nc                8    g | ]\  }} |j         |          S r   r:   )rN   r3   afns      r)   rO   z/map_overlap.<locals>.coerce.<locals>.<listcomp>  s)    777$!Q161777r+   )r   rx   r   r`   )xsargr   s     `r)   coercezmap_overlap.<locals>.coerce  sH    #t$$ 	"%#b''/C7777#b#,,7777r+   c           	     j    g | ]0}t          t          t          |j                                      1S r   )rx   reversedr_   r:   r   s     r)   rO   zmap_overlap.<locals>.<listcomp>  s0    <<<!XeAFmm,,--<<<r+   warnFc                d    g | ]-}t          d  |                                D                       .S )c              3  "   K   | ]
}|d k    V  dS rQ   r   )rN   	depth_vals     r)   rT   z)map_overlap.<locals>.<listcomp>.<genexpr>  s&      ;;9	Q;;;;;;r+   )allr   r   s     r)   rO   zmap_overlap.<locals>.<listcomp>  s7    KKKC;;

;;;;;KKKr+   r>   zAsymmetric overlap is currently only implemented for boundary='none', however boundary for dimension {} in array argument {} is {}c                <    t          d | D                       sJ d S )Nc              3  `   K   | ])}|j         D ]}|D ]}t          |          t          u V   *d S r[   )r   r   int)rN   r3   ccrz   s       r)   rT   z<map_overlap.<locals>.assert_int_chunksize.<locals>.<genexpr>  sH      MMaMM""MMQ477c>MMMMMMMMr+   )r   )r   s    r)   assert_int_chunksizez)map_overlap.<locals>.assert_int_chunksize  s+    MM2MMMMMMMMMMr+   r   c                >    g | ]\  }}}t          |||           S ))r"   r8   r   )rG   )rN   r3   rJ   br   s       r)   rO   zmap_overlap.<locals>.<listcomp>  s@       Aq! 	QmDDD  r+   c                .    | d         j         | d          fS )Nr   r   r   )r   s    r)   <lambda>zmap_overlap.<locals>.<lambda>  s    1Q49qte2D r+   )keyr   	drop_axisNc              3  N   K   | ] }t          |t                    |j        V  !d S r[   )r   r   r:   )rN   r   s     r)   rT   zmap_overlap.<locals>.<genexpr>  s3      HHa:a3G3GH16HHHHHHr+   c                    g | ]}|z  S r   r   )rN   rJ   ndim_outs     r)   rO   zmap_overlap.<locals>.<listcomp>  s    999!X999r+   c              3  $   K   | ]
}|v|V  d S r[   r   )rN   rS   r   s     r)   rT   zmap_overlap.<locals>.<genexpr>  s-      VVR"IBUBUbBUBUBUBUVVr+   c                (    i | ]\  }}||         S r   r   )rN   nrS   r"   s      r)   r   zmap_overlap.<locals>.<dictcomp>  s#    DDDeaQb	DDDr+   c                (    i | ]\  }}||         S r   r   )rN   r   rS   r8   s      r)   r   zmap_overlap.<locals>.<dictcomp>  s#    JJJEAr8B<JJJr+   )r   r   callablewarningsr   FutureWarningr   index	TypeErrorformatr   r   r   r9   rA   r   rx   r   r`   r   r   r_   r:   r   NotImplementedErrorr   sortedpopr   r   r;   )r   r"   r8   r   r   r   argskwargssigr   inds_r    r3   rI   r   	kept_axesr   r   s    ``  `           @@r)   map_overlapr     s   J $ %8DG#4#4 %J 		
 	
 	
 433CIIg&&e44syy,,dH==399V$$dD11!WtfdD>> 
99?T

@S9T9T
 
 	

 22T22222 
99?004000: :
 
 	
8 8 8
 F4--EvdHo66H  K<<t<<<VCdOO%<%< = =JEJJ4 KKUKKKLL 1$0000000$  1qv 	 	A%(1+u-- (1+a.F2J2J)44:F1a!Q4P4P  	N N N  *HF**7>x   411  D 4)$)))&))A! 9T??(D(DEEEbI!LaA;JJ{D11	 )V,, (&K	 HH4HHHHHH9999y999IVVVV5a+>+>VVVVVIDDDDy/C/CDDDEJJJJYy5I5IJJJHQx000r+   c                H   dt          t                    rf| z  t          t                    r*t          t	          t          |                               t          t                    rfdt          |           D             t          |           S )Nr   c                >    i | ]}|                     |          S r   rM   )rN   rS   defaultr"   s     r)   r   z coerce_depth.<locals>.<dictcomp>  s)    BBBUYYr7++BBBr+   )r   r   r   r   r`   r_   coerce_depth_type)r:   r"   r   s    `@r)   r9   r9     s    G}%""  4% .Ste,,--% CBBBBBeDkkBBBT5)))r+   c                    t          |           D ]X}t          ||         t                    r#t          d ||         D                       ||<   @t          ||                   ||<   Y|S )Nc              3  4   K   | ]}t          |          V  d S r[   )r   r   s     r)   rT   z$coerce_depth_type.<locals>.<genexpr>  s(      66SVV666666r+   )r_   r   r   r   )r:   r"   r    s      r)   r   r     sm    4[[ % %eAh&& 	%66U1X66666E!HH58}}E!HHLr+   c                :   dt          t          t          f          sf| z  t          t                    r*t          t          t	          |                               t          t                    rfdt	          |           D             S )Nr>   c                >    i | ]}|                     |          S r   rM   )rN   rS   r8   r   s     r)   r   z#coerce_boundary.<locals>.<dictcomp>  s)    HHHbBR11HHHr+   )r   r   r   r`   r_   )r:   r8   r   s    `@r)   rA   rA     s    Gh.. &;%(E"" 4E$KK2233(D!! IHHHHHE$KKHHHOr+   c                   ddl m} t          j        |          rt	          |          n|f}t          j        |          }t          j        |dk              rt          d          |jt	          t          | j	                            }t          |          t          |          k    r(t          dt          |           d| j	         d          nc ||| j	        d          }t          |          t          |          k    r0t          d	t          |           d
t          |           d          dg| j	        z  }t          ||          D ]\  }}||xx         |dz
  z  cc<   t	          d t          || j                  D                       }|                     |          } t	          d t          || j                  D                       t	          d |D                       z   }	t          t          j        j        j        | t	          d |D                       d| j        t          | j	        | j	        t          |          z             |	dd||          S )Nr   )normalize_axis_tuplez&`window_shape` must contain values > 0zOSince axis is `None`, must provide window_shape for all dimensions of `x`; got z' window_shape elements and `x.ndim` is r   T)allow_duplicatez8Must provide matching length window_shape and axis; got z window_shape elements and z axes elements.r   c              3  B   K   | ]\  }}t          |d z   |          V  dS rV   r   r   s      r)   rT   z&sliding_window_view.<locals>.<genexpr>1  sF        /3q! Q**     r+   c              3  J   K   | ]\  }}|d d         |d         |z
  fz   V  d S )Nr   r   r   s      r)   rT   z&sliding_window_view.<locals>.<genexpr>:  s=      NN1af"	|+NNNNNNr+   c              3     K   | ]}|fV  d S r[   r   )rN   windows     r)   rT   z&sliding_window_view.<locals>.<genexpr>:  s=       W W	W W W W W Wr+   c              3     K   | ]}d |fV  	dS rQ   r   r   s     r)   rT   z&sliding_window_view.<locals>.<genexpr>A  s&      ++qQF++++++r+   r>   F)	r"   r8   r1   new_axisr   r   r   window_shaperi   )numpy.core.numericr   npiterabler   arrayr   r   r_   r:   r   r`   r   r}   r   libstride_trickssliding_window_viewrD   )
r3   r   ri   r   window_shape_arrayr   rS   r   safe_chunks	newchunkss
             r)   r  r    s   777777*,+l*C*CX5&&&,L,//	v A%&& CABBB|U16]]##|D		))-<((- - $%6- - -   * $#D!&$GGG|D		)); ..; ; #D		; ; ;   S16\F$-- ! !
Fr


fqj 



   7:6187L7L    K 	
		+A NNFAH8M8MNNNNNQV W W ,W W W R R I 
0	++F+++++WqvqvD		122!   r+   r[   )NN)5
__future__r   r   numbersr   r   numpyr   tlzr   r   r   tlz.curriedr	   
dask.arrayr
   dask.array.corer   r   r   r   dask.array.creationr   r   	dask.baser   dask.highlevelgraphr   dask.layersr   
dask.utilsr   r*   r5   r<   r;   rC   ro   rq   rt   r{   rk   r   r   rG   r   r   r9   r   rA   r  r  r  r   r+   r)   <module>r     s   " " " " " "  $ $ $ $ $ $ $ $     $ $ $ $ $ $ $ $ $ $             H H H H H H H H H H H H 5 5 5 5 5 5 5 5       . . . . . . ) ) ) ) ) ) # # # # # #  0. . .<: : : :"+ + + +\! ! !H- - -0- - -<- - -2- - -      B0 0 0f 26 V V V V Vr" " "P 	A A A A AH
* 
* 
*  
 
 
 bf"##: : : $#: : :r+   