
    Ug֌                       d Z ddlmZ ddlmZ ddlmZmZ ddlZ	ddl
mZ ddlmZmZ 	 ddlmZ dd	lmZ 	 ddlZdZdZdZdZdZdZdZdZdZdZe	j@                  jC                  e	j@                  j!                  dggdgg            Z"dZ# e$ee      Z% e$eeeeeeee      Z&d Z'd
dZ(	 	 	 d-dZ)	 	 	 d.dZ*er ee*      ndZ+eddfdZ,edddfdZ-d Z.d  Z/d! Z0d" Z1ed#        Z2d$ Z3ed%        Z4ed&        Z5ee5ee4iZ6ed'        Z7ed(        Z8ed)        Z9ed*        Z:ed+        Z;ee:ee7ee7ee8ee8ee9ee;ee;iZ<d/d,Z=y# e$ r	 d
\  ZZY w xY w# e$ r dZY !w xY w)0a  
This module was adapted from https://github.com/CAB-LAB/gridtools

                        The MIT License (MIT)

Copyright (c) 2016, Brockmann Consult GmbH and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
    )annotations)groupby)floorceilN)prange   )ngjitngjit_parallel)delayed)NN
      2   3   4   5   6   8   9   :   )maskg|=)nearestlinear)firstlastmodemeanvarstdminmaxc                4   |\  }}|\  }}t        t        d||            |gz   }t        t        d||            |gz   }| \  }	}
|
|z  }|	|z  }i }t        t        |      dz
        D ]  }|||dz    \  }}||z  ||z  }}t        |      t	        |      }}||z
  ||z
  }}t        t        |      dz
        D ]]  }|||dz    \  }}||z  ||z  }}t        |      t	        |      }}||z
  ||z
  }}||f||f||z
  ||z
  d||f||f||f||fdd|||f<   _  |S )a=  
    Maps index in source array to target array chunks.

    For each chunk in the target array this function computes the
    indexes into the source array that will be fed into the regridding
    operation.

    Parameters
    ----------
    in_shape: tuple(int, int)
      The shape of the input array
    out_shape: tuple(int, int)
      The shape of the output array
    out_chunks: tuple(int, int)
      The shape of each chunk in the output array

    Returns
    -------
      Dictionary mapping of chunks and their indexes
      in the input and output array.
    r   r      )xywh)r#   r$   xoffsetyoffset)outin)listrangelenr   r   ) in_shape	out_shape
out_chunksoutyoutxcyscxsxchunksychunksinyinxxscaleyscalemappingicumy0cumy1iny0iny1iny0riny1ry0_offy1_offjcumx0cumx1inx0inx1inx0rinx1rx0_offx1_offs                                    5lib/python3.12/site-packages/datashader/resampling.py
map_chunksrO   b   s   , JD$HC5D#&'4&0G5D#&'4&0GHCXFXFG3w<>"q1~u6\5<dT{DJueU4Zs7|A~&A"1QqS>LE5vuV|$D ;T
5E!%ZtFF  ++	   &/ &/	GQFO ' #0 N    c                h   || j                   n|}||S | j                  \  }}t        |      |z  }t        |      |z  }	|\  }
}d}| j                  j                  }|
|z  ||	z  z  |z  |kD  r"|r|dz  }n|
dz  }
| }|
|z  ||	z  z  |z  |kD  r"|
dk(  s|dk(  r||	z  |z  }t        d|z        |
|fS )a!  
    Attempts to compute a chunksize for the resampling output array
    that is as close as possible to the input array chunksize, while
    also respecting the maximum memory constraint to avoid loading
    to much data into memory at the same time.

    Parameters
    ----------
    src : dask.array.Array
        The source array to resample
    w : int
        New grid width
    h : int
        New grid height
    chunksize : tuple(int, int) (optional)
        Size of the output chunks. By default the chunk size is
        inherited from the *src* array.
    max_mem : int (optional)
        The maximum number of bytes that should be loaded into memory
        during the regridding operation.

    Returns
    -------
    chunksize : tuple(int, int)
        Size of the output chunks.
    Tr   r   a7  Given the memory constraints the resampling operation could not find a chunksize that avoids loading too much data into memory. Either relax the memory constraint to a minimum of %d bytes or resample to a larger grid size. Note: A future implementation could handle this condition by declaring temporary arrays.)	chunksizeshapefloatdtypeitemsize
ValueError)srcr%   r&   rR   max_memstart_chunksizeshswheight_fractionwidth_fractionchcwdimnbytesmin_mems                  rN   compute_chunksizerd      s    6 (1'8cmmiOYYFBBikO2Yq[NFB
CYYF R.%89FBg
M!GB!GBg  R.%89FBg
M 
Qw"'!N2V;-
 0778 	8 r6MrP   c	                   t         t        d      t        | ||||      }	|| j                  }t	        | j
                  ||f|	      }
i }|
j                         D ]n  \  \  }}}|d   }|d   \  }}|d   \  }}|d   }| ||||f   }t        ||d   |d   |||||d   |d	   	      }||d   |d   f| j                  |d   |d
|||f<   p t        |j                         d       }g }|D ]]  \  }}t        j                  |D cg c]%  \  }}t        j                  |d   |d   |d         ' c}}d      }|j                  |       _ t        j                  |d      }| |j                  |k7  r|j                  |      }|S c c}}w )a  
    A distributed version of 2-d grid resampling which operates on
    dask arrays and performs regridding on a chunked array.

    Parameters
    ----------
    src : dask.array.Array
        The source array to resample
    w : int
        New grid width
    h : int
        New grid height
    ds_method : str (optional)
        Grid cell aggregation method for a possible downsampling
        (one of the *DS_* constants).
    us_method : str (optional)
        Grid cell interpolation method for a possible upsampling
        (one of the *US_* constants, optional).
    fill_value : scalar (optional)
        If None, numpy's default value is used.
    mode_rank : scalar (optional)
        The rank of the frequency determined by the *ds_method*
        ``DS_MODE``. One (the default) means most frequent value, two
        means second most frequent value, and so forth.
    chunksize : tuple(int, int) (optional)
        Size of the output chunks. By default this the chunk size is
        inherited from the *src* array.
    max_mem : int (optional)
        The maximum number of bytes that should be loaded into memory
        during the regridding operation.

    Returns
    -------
    resampled : dask.array.Array
        A resampled version of the *src* array.
    z+dask is required for distributed regriddingr*   r#   r$   r)   r%   r&   r'   r(   )arrayrS   rU   r*   r)   c                    | d   d   S )Nr    )r#   s    rN   <lambda>z)resample_2d_distributed.<locals>.<lambda>  s    1arP   rf   rS   rU   r   r   )daImportErrorrd   rR   rO   rS   items_resample_2d_delayedrU   r   concatenatefrom_delayedappendrechunk)rX   r%   r&   	ds_method	us_method
fill_value	mode_rankrR   rY   temp_chunks	chunk_mapr0   r<   rE   chunkindsrH   rI   r?   r@   r)   chunk_array	resampledrowscolsrow_s                              rN   resample_2d_distributedr      s   N 
zGHH#CAy'BKMM	399q!fk:IJ"*AT{#Y
d#Y
dEl$t)T$Y./(SXs3xIItIYI	 #hC)YY+

Aq6 +" :##%'89DD3nn!5 OOE'NE'NE'NK!"#% 	C	 
 ..q
!C )!;kk)$J!s   *Fc
                $   t        |	| ||f      }	|	| S t        |       \  }
}t        || |	      }t        |   }t        |   }t        | t        j                  j                        r| j                  } t        | |
||||||||	
      }t        || |      S )a  
    Resample a 2-D grid to a new resolution.

    Parameters
    ----------
    src : np.ndarray
        The source array to resample
    w : int
        New grid width
    h : int
        New grid height
    ds_method : str (optional)
        Grid cell aggregation method for a possible downsampling
        (one of the *DS_* constants).
    us_method : str (optional)
        Grid cell interpolation method for a possible upsampling
        (one of the *US_* constants, optional).
    fill_value : scalar (optional)
        If ``None``, it is taken from **src** if it is a masked array,
        otherwise from *out* if it is a masked array,
        otherwise numpy's default value is used.
    mode_rank : scalar (optional)
        The rank of the frequency determined by the *ds_method*
        ``DS_MODE``. One (the default) means most frequent value, zwo
        means second most frequent value, and so forth.
    x_offset : tuple(float, float) (optional)
        Offsets for the x-axis indices in the source array (useful
        for distributed regridding where chunks are not aligned with
        the underlying array).
    y_offset : tuple(float, float) (optional)
        Offsets for the x-axis indices in the source array (useful
        for distributed regridding where chunks are not aligned with
        the underlying array).
    out : numpy.ndarray (optional)
        Alternate output array in which to place the result. The
        default is *None*; if provided, it must have the same shape as
        the expected output.

    Returns
    -------
    resampled : numpy.ndarray or dask.array.Array
        A resampled version of the *src* array.
    )_get_out	_get_mask_get_fill_valueupsample_methodsdownsample_methods
isinstancenpmaMaskedArraydata_resample_2d_mask_or_not)rX   r%   r&   rr   rs   rt   ru   x_offsety_offsetr)   r   use_maskr{   s                rN   resample_2dr   !  s    \ 3aV
$C
{
s^ND( S#6Jy)I +I#ruu(()hhS$)Y'HhMI	3
33rP   c           	         t        || ||f      }|| S t        |       \  }}t        || |      }|t        vrt	        d      t        |   } || |||dd|      }	t        |	| |      S )a  
    Upsample a 2-D grid to a higher resolution by interpolating original grid cells.

    src: 2-D *ndarray*
    w: *int*
        Grid width, which must be greater than or equal to *src.shape[-1]*
    h:  *int*
        Grid height, which must be greater than or equal to *src.shape[-2]*
    method: one of the *US_* constants, optional
        Grid cell interpolation method
    fill_value: *scalar*, optional
        If ``None``, it is taken from **src** if it is a masked array,
        otherwise from *out* if it is a masked array,
        otherwise numpy's default value is used.
    out: 2-D *ndarray*, optional
        Alternate output array in which to place the result. The default is *None*; if provided,
        it must have the same shape as the expected output.

    Returns
    -------
    upsampled : numpy.ndarray or dask.array.Array
        An upsampled version of the *src* array.
    invalid upsampling methodr   r   )r   r   r   UPSAMPLING_METHODSrW   r   )
rX   r%   r&   methodrt   r)   r   r   upsampling_method	upsampleds
             rN   upsample_2dr   c  s    0 3aV
$C
{
s^ND( S#6J''455*62!T8Z>I	3
33rP   c                   |t         k(  r|dk  rt        d      t        || ||f      }|| S t        |       \  }}t	        || |      }|t
        vrt        d      t
        |   }	 |	| |||||dd|	      }
t        |
| |      S )a  
    Downsample a 2-D grid to a lower resolution by aggregating original grid cells.

    Parameters
    ----------
    src : numpy.ndarray or dask.array.Array
        The source array to resample
    w : int
        New grid width
    h : int
        New grid height
    ds_method : str (optional)
        Grid cell aggregation method for a possible downsampling
        (one of the *DS_* constants).
    fill_value : scalar (optional)
        If ``None``, it is taken from **src** if it is a masked array,
        otherwise from *out* if it is a masked array,
        otherwise numpy's default value is used.
    mode_rank : scalar (optional)
        The rank of the frequency determined by the *ds_method*
        ``DS_MODE``. One (the default) means most frequent value, two
        means second most frequent value, and so forth.
    out : numpy.ndarray (optional)
        Alternate output array in which to place the result. The
        default is *None*; if provided, it must have the same shape as
        the expected output.

    Returns
    -------
    downsampled : numpy.ndarray or dask.array.Array
        An downsampled version of the *src* array.
    r   zmode_rank must be >= 1invalid downsampling methodr   )DS_MODErW   r   r   r   DOWNSAMPLING_METHODSr   )rX   r%   r&   r   rt   ru   r)   r   r   downsampling_methoddownsampleds              rN   downsample_2dr     s    B Y]122
3aV
$C
{
s^ND( S#6J))677.v6%T8VZFK S*55rP   c                    | !t        j                  ||j                        S | j                  |k7  rt	        d      | j                  |j                  k(  ry | S )NrU   z"'shape' and 'out' are incompatible)r   zerosrU   rS   rW   )r)   rX   rS   s      rN   r   r     sL    
{xxSYY//99ABB99		!
rP   c                    t        | t        j                  j                        r?t        j                  j	                  |       }|t        j                  j
                  ur|dfS t        dfS )NTF)r   r   r   r   getmasknomask	_NOMASK2D)rX   r   s     rN   r   r     sM    #ruu(()uu}}S!ruu||#:erP   c                n   t        |t        j                  j                        rt        | t        j                  j                        slt        j                  |      r#t        j                  j                  | |d      }n!t        j                  j                  | d      }|j                  |       |S | S )NF)copy)r   r   r   r   isfinitemasked_equalmasked_invalidset_fill_value)r)   rX   rt   maskeds       rN   r   r     s    #ruu(()#ruu001{{:&++C%+H--c->!!*-MJrP   c                B   | t        |t        j                  j                        r|j                  } | S t        |t        j                  j                        r|j                  } | S t        j                  j                  dgdg|j                        j                  } | S )Nr   F)r   rU   )r   r   r   r   rt   rf   rU   )rt   rX   r)   s      rN   r   r     s    c255,,-J  RUU../J  aSwciiHSSJrP   c                    | j                   d   }| j                   d   }|j                   d   }|j                   d   }||||fS )N)rS   )rX   r)   src_wsrc_hout_wout_hs         rN   _get_dimensionsr     sE    IIbMEIIbMEIIbMEIIbME%%%rP   c
                
   t        | |	      \  }
}}}|\  }}|\  }}|
|z
  |z
  }||z
  |z
  }|t        vrt        d      |t        vrt        d      t        |   }t        |   }|dk(  s|
dk(  s
|dk(  s|dk(  r#t	        j
                  ||f| j                        S ||k  r||k  r || ||||||||		      S ||k  rV||kD  rAt	        j
                  ||f| j                        } || ||||||||	      } ||||||||	      S  || ||||||||		      S ||k  rV||kD  rAt	        j
                  ||
f| j                        } || ||||||||	      } ||||||||	      S  || ||||||||		      S ||kD  s||kD  r || ||||||	      S | S )Nr   r   r   r   )r   r   rW   r   r   r   rU   )rX   r   r   rr   rs   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   src_wosrc_hor   r   temps                          rN   r   r     s#   !0c!:E5%NFFNFFfnv%Ffnv%F**455	.	.677.y9*95zUaZ5A:!hhu~SYY77	EFN"3h	#-y(#+S2 	2 
6>88UEN#))<D&sD(I'19h'/$8D %T4:%-x> > 'sD(I'19h'/6 6 
6>88UEN#))<D&sD(I'19h'/$8D %T4:%-x> > 'sD(I'19h'/6 6 
56> dHj!)8c; 	;JrP   c                   t        | |      \  }}}	}
|\  }}|\  }}||z
  |z
  }||z
  |z
  }||	k(  r||
k(  r| S |	|k  s|
|k  rt        d      ||	z  }||
z  }t        |
      D ]h  }t        ||z  |z         }t	        |	      D ]G  }t        ||z  |z         }| ||f   }t        j                  |      r|r|||f   s||||f<   A||||f<   I j |S )Ninvalid target sizer   rW   r   intr,   r   r   )rX   r   r   rt   r   r   r)   r   r   r   r   rL   rM   rC   rD   scale_xscale_yout_ysrc_yout_xsrc_xvalues                         rN   _upsample_2d_nearestr   '  s   !0c!:E5%NFFNFFV^f$EV^f$E~%5.
u}.//emGemGWu_./5\E5F23Eu%E{{5!8UE\8J$)E5L!$.E5L! "  JrP   c                \   t        | |      \  }}}	}
|\  }}|\  }}||z
  |z
  }||z
  |z
  }||	k(  r||
k(  r| S |	|k  s|
|k  rt        d      |dz
  |	dkD  r|	dz
  ndz  }|dz
  |
dkD  r|
dz
  ndz  }t        |
      D ]  }||z  |z   }t        |      }||z
  }|dz   }||k\  r|}t	        |	      D ]v  }||z  |z   }t        |      }||z
  }|dz   }||k\  r|}| ||f   }| ||f   }| ||f   }| ||f   } |r}t        j                  |      xr |||f    }!t        j                  |      xr |||f    }"t        j                  |      xr |||f    }#t        j                  |       xr |||f    }$nTt        j                  |      }!t        j                  |      }"t        j                  |      }#t        j                  |       }$|!r*|"r(|#r&|$r$d}%||||z
  z  z   }&||| |z
  z  z   }'|&||'|&z
  z  z   }(n"|dk  r|dk  r|!}%|}(n|#}%|}(n|dk  r|"}%|}(n|$}%| }(|%r	|(|||f<   p||||f<   y  |S )Nr         ?r   T      ?r   ))rX   r   r   rt   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   r   r   r   src_yfsrc_y0wysrc_y1r   src_xfsrc_x0wxsrc_x1v00v01v10v11v00_okv01_okv10_okv11_okokv0v1r   s)                                            rN   _upsample_2d_linearr   D  s   !0c!:E5%NFFNFFfnv%Ffnv%F6U?
u}.//|DG|DGE/V+Vf_!U?F5\Eo/F[F&BaZFffn%Cffn%Cffn%Cffn%CS)F$vv~2F.FS)F$vv~2F.FS)F$vv~2F.FS)F$vv~2F.FS)S)S)S)&V2s++2s++R27^+c8BEBE 8BEBE$)E5L!$.E5L![ " j JrP   c	                   t        | |      \  }	}
}}|	|k(  r|
|k(  r| S ||	kD  s||
kD  rt        d      |\  }}|\  }}|	|z
  |z
  |z  }|
|z
  |z
  |z  }t        |      D ]  }||z  |z   }||z   }t        |      }t        |      }||z
  }|t        k  r
||kD  r|dz  }t        |      D ]  }||z  |z   }||z   }t        |      }t        |      }||z
  }|t        k  r
||kD  r|dz  }d}|} t        ||dz         D ]P  }!t        ||dz         D ]8  }"| |!|"f   }#t        j                  |#      s |r||!|"f   r*|#} |t        k(  s6d} n |sP n | |||f<     |S )Nr   r   FT)	r   rW   r   r   _EPSr,   r   r   DS_FIRST)$rX   r   r   r   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   r   src_yf0src_yf1r   r   wy1r   src_xf0src_xf1r   r   wx1doner   r   r   vs$                                       rN   _downsample_2d_first_lastr     s    "1c!:E5%~%5.
u}.//NFFNFFv~&%/Gv~&%/GU?f,G#WW:&6/aKF5\E&0G'G\F\FF"CTzfvo!DEvvz2"66A:6EE5L)A{{1~xD<N !!X-#'D! 7  3 !&Cu) " : JrP   c	                J   t        | |      \  }	}
}}|	|k(  r|
|k(  r| S ||	kD  s||
kD  rt        d      |\  }}|\  }}|	|z
  |z
  |z  }|
|z
  |z
  |z  }t        |      D ]A  }||z  |z   }||z   }t        |      }t        |      }||z
  }|t        k  r
||kD  r|dz  }t        |      D ]  }||z  |z   }||z   }t        |      }t        |      }||z
  }|t        k  r
||kD  r|dz  }|t        k(  rt        j                  }nt        j                   }t        ||dz         D ]W  } t        ||dz         D ]C  }!| | |!f   }"t        j                  |"      s |r|| |!f   r*|t        k(  r	|"|k  s9|"}<|"|kD  sB|"}E Y t        j                  |      r||||f<   ||||f<    D |S )Nr   r   )
r   rW   r   r   r   r,   DS_MINr   infr   )#rX   r   r   r   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s#                                      rN   _downsample_2d_min_maxr     s    "1c!:E5%~%5.
u}.//NFFNFFv~&%/Gv~&%/GU?f,G#WW:&6/aKF5\E&0G'G\F\FF"CTzfvo!vvz2"66A:6EE5L)A{{1~xD<N!V+ 5y() 5y() 7 3 {{5!$)E5L!$.E5L!3 " D JrP   c	           	        t        | |      \  }	}
}}|	|k(  r|
|k(  r| S ||	kD  s||
kD  rt        d      |\  }}|\  }}|	|z
  |z
  |z  }|
|z
  |z
  |z  }t        |dz         t        |dz         z  }||k\  rt        d      t        |      D ]a  }||z  |z   }||z   }t	        |      }t	        |      }d||z
  z
  }||z
  }|t
        k  rd}||kD  r|dz  }t        |      D ]
  }t        j                  |f| j                        }t        j                  |ft        j                        }||z  |z   }||z   }t	        |      } t	        |      }!d|| z
  z
  }"||!z
  }#|#t
        k  rd}#|!| kD  r|!dz  }!d}$t        ||dz         D ]  }%|%|k(  r|n|%|k(  r|nd}&t        | |!dz         D ]{  }'|'| k(  r|"n|'|!k(  r|#nd}(| |%|'f   })t        j                  |)      s0|r||%|'f   r:|(|&z  }*d}+t        |$      D ]  },|)||,   k(  s||,xx   |*z  cc<   d}+ n |+rm|)||$<   |*||$<   |$dz  }$}  d	}-|}.|dk(  r#t        |$      D ]  },||,   }*|*|-kD  s|*}-||,   }. n||k  rt        j                  |d	t        j                        }/t        j                  |t        j                        }0t        |$      D ]+  },||,   }*t        |      D ]  }1|*|/|1   kD  s|*|/|1<   |,|0|1<    + - ||0|dz
        }.|.|||f<    d |S )
Nr   r   zArequested mode_rank too large for max_value_count being collectedr   r   r   FTg      )r   rW   r   r   r   r   r,   r   r   rU   uint32r   fullfloat64int64)2rX   r   r   r   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   max_value_countr   r   r   r   r   wy0r   r   valuesfrequenciesr   r   r   r   wx0r   value_countr   r   r   r   r   r%   foundr<   w_maxr   max_frequenciesindicesrE   s2                                                     rN   _downsample_2d_moder     s    "1c!:E5%~%5.
u}.//NFFNFFv~&%/Gv~&%/G7Q;'$w{*;;OO#\]]U?f,G#WWWv%&:C!5\EXX0		BF((O#5RYYGK&0G'G\F\F6)*CF"CTzF?aKFKvvz2"f_S5F?3QT"66A:6E!&&usUXBE5L)A{{1~xD<NG %!&{!3A F1I~ +A! 3(, %	 "4
  %23F;/78K4'1,K 7 3" EEA~{+A#AA5y ! &q		 ,
 o-"$'')T"L((9BHH={+A#AA"9-q1112OA.)*GAJ!	 . , wy1}56 %Cug " ~ JrP   c	                B   t        | |      \  }	}
}}|	|k(  r|
|k(  r| S ||	kD  s||
kD  rt        d      |\  }}|\  }}|	|z
  |z
  |z  }|
|z
  |z
  |z  }t        |      D ]=  }||z  |z   }||z   }t        |      }t        |      }d||z
  z
  }||z
  }|t        k  rd}||kD  r|dz  }t        |      D ]  }||z  |z   }||z   }t        |      }t        |      }d||z
  z
  }||z
  } | t        k  rd} ||kD  r|dz  }d}!d}"t        ||dz         D ]o  }#|#|k(  r|n|#|k(  r|nd}$t        ||dz         D ]K  }%|%|k(  r|n|%|k(  r| nd}&| |#|%f   }'t        j                  |'      s0|r||#|%f   r:|&|$z  }(|!|(|'z  z  }!|"|(z  }"M q |"t        k  r||||f<   |!|"z  |||f<    @ |S Nr   r   r   g        )r   rW   r   r   r   r,   r   r   ))rX   r   r   r   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   v_sumw_sumr   r   r   r   r   r%   s)                                            rN   _downsample_2d_meanr  K  s,    "1c!:E5%~%5.
u}.//NFFNFFv~&%/Gv~&%/GU?f,W$WWWv%&:C!5\E&0G'G\F\F6)*CF"CTzF?aKFEEvvz2"f_S5F?3QT"66A:6E!&&usUXBE5L)A{{1~xD<NGQ
 7 3 t|$.E5L!$)EME5L!3 " L JrP   c	                   t        | |      \  }	}
}}|	|k(  r|
|k(  r| S ||	kD  s||
kD  rt        d      |\  }}|\  }}|	|z
  |z
  |z  }|
|z
  |z
  |z  }t        |      D ]_  }||z  |z   }||z   }t        |      }t        |      }d||z
  z
  }||z
  }|t        k  rd}||kD  r|dz  }t        |      D ]  }||z  |z   }||z   }t        |      }t        |      }d||z
  z
  }||z
  } | t        k  rd} ||kD  r|dz  }d}!d}"d}#d}$t        ||dz         D ]  }%|%|k(  r|n|%|k(  r|nd}&t        ||dz         D ][  }'|'|k(  r|n|'|k(  r| nd}(| |%|'f   })t        j                  |)      s0|r||%|'f   r:|(|&z  }*|!|)z  }!|"|*z  }"|#|*|)z  z  }#|$|*|)z  |)z  z  }$]  |"t        k  r||||f<   |$|"z  |#|#z  z
  |"z  |"z  |||f<    b |t        k(  rt        j                  |      }|S r   )
r   rW   r   r   r   r,   r   r   DS_STDsqrt)+rX   r   r   r   rt   ru   r   r   r)   r   r   r   r   rL   rM   rC   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  wv_sumwvv_sumr   r   r   r   r   r%   s+                                              rN   _downsample_2d_std_varr	    sz    "1c!:E5%~%5.
u}.//NFFNFFv~&%/Gv~&%/GU?f,G#WWWv%&:C!5\E&0G'G\F\F6)*CF"CTzF?aKFEEFGvvz2"f_S5F?3QT"66A:6E!&&usUXBE5L)A{{1~xD<NG

!a%1q519, 7 3 t|$.E5L!%,u_v%F%$ORW$WE5L!; " R ggclJrP   c                \   t         rt        | t         j                        rnt        j                  |       } t        |       dk(  r!t        j                  g | j                        S dt        j                  |       z  }t        j                  | dg      t        j                  |dg      z
  }t        j                  | dg      t        j                  |dg      z   }t        fdt        | j                        D              }t        j                  || |   |z   |g      S )z
    >>> infer_interval_breaks(np.arange(5))
    array([-0.5,  0.5,  1.5,  2.5,  3.5,  4.5])
    >>> infer_interval_breaks([[0, 1], [3, 4]], axis=1)
    array([[-0.5,  0.5,  1.5],
           [ 2.5,  3.5,  4.5]])
    r   r   r   )axisr   c              3  V   K   | ]   }|k(  rt        d d      n
t        d        " y w)Nr   )slice).0nr  s     rN   	<genexpr>z(infer_interval_breaks.<locals>.<genexpr>  s.      20! *+deD"odC0s   &))cupyr   ndarrayr   asarrayr-   rf   rU   difftaketupler,   ndimrn   )coordr  deltasr   r   	trim_lasts    `    rN   infer_interval_breaksr    s     
5$,,/

5!
5zQxx%++..2775t,,FGGEA3T*RWWVaSt-LLE7752$T*RWWVbT-MMD 2$UZZ02 2I>>5%	"2V";TBNNrP   )r   r   Nr   NN)r   r   Nr   r   r   N)r   )>__doc__
__future__r   	itertoolsr   mathr   r   numpyr   numbar   utilsr	   r
   
dask.arrayrf   rj   dask.delayedr   rk   r  
US_NEAREST	US_LINEARr   DS_LASTr   DS_MAXDS_MEANr   DS_VARr  r   getmaskarrayr   r   dictr   r   rO   rd   r   r   rm   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r   r  rh   rP   rN   <module>r-     s  4 #     ($ 
 	 
 
 
   
 
 EEruu{{QC5u{=>	*Y? wW&fF$f6 
6r4n DLDH$(L^ 8@7=%)<4~ 07w{+D  #,$ $4N %,t 06f		 & &3l  8 D DN  !4 "68  , ,^ 1 1h R Rj 5 5p : :z  !4 ";!: 6 6!4 6 68 OI  KB
  Ds"   E E 
EEEE