
    |Le                       d dl mZ d dlmZ d dlmZ d dlZd dlZd dl	Z
d dlmZ d dlmZ d dlmZmZ ddl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 dd
lm Z m!Z! ddl"m#Z$ 	 d dl%Z%n# e&$ r dZ%Y nw xY w	 d dl'Z'n# e&$ r dZ'Y nw xY w	 d dl(Z(n# e&$ r dZ(Y nw xY w G d d          Z) G d de)          Z* G d de)          Z+ e*             e+            dZ,d Z- G d d          Z.dddZ/d Z0d Z1d Z2 e            e/_3        dS )    )annotations)Number)log10N)	DataArrayDataset   )
Dispatcherngjitcalc_res	calc_bboxorient_arraydshape_from_xarray_dataset)get_indicesdshape_from_pandasdshape_from_dask)Expr)resample_2dresample_2d_distributed)
reductionsc                  0    e Zd ZdZd Zd Zd Zd Zd ZdS )Axisau  Interface for implementing axis transformations.

    Instances hold implementations of transformations to and from axis space.
    The default implementation is equivalent to:

    >>> def forward_transform(data_x):
    ...     scale * mapper(data_x) + t
    >>> def inverse_transform(axis_x):
    ...     inverse_mapper((axis_x - t)/s)

    Where ``mapper`` and ``inverse_mapper`` are elementwise functions mapping
    to and from axis-space respectively, and ``scale`` and ``transform`` are
    parameters describing a linear scale and translate transformation, computed
    by the ``compute_scale_and_translate`` method.
    c                V    t          | j        |          \  }}|||z
  z  }| |z  }||fS )a  Compute the scale and translate parameters for a linear transformation
        ``output = s * input + t``, mapping from data space to axis space.

        Parameters
        ----------
        range : tuple
            A tuple representing the range ``[min, max]`` along the axis, in
            data space. Both min and max are inclusive.
        n : int
            The number of bins along the axis.

        Returns
        -------
        s, t : floats
        )mapmapper)selfrangenstartendsts          /lib/python3.11/site-packages/datashader/core.pycompute_scale_and_translatez Axis.compute_scale_and_translate4   s:      e,,
ssU{OFQJ!t    c                p    t          j        |          dz   }|\  }}|                     ||z
  |z            S )a)  Compute a 1D array representing the axis index.

        Parameters
        ----------
        st : tuple
            A tuple of ``(scale, translate)`` parameters.
        n : int
            The number of bins along the dimension.

        Returns
        -------
        index : ndarray
        g      ?)nparangeinverse_mapper)r   str   pxr    r!   s         r"   compute_indexzAxis.compute_indexI   s;     Yq\\#1""BFA:...r$   c                    t           )z'A mapping from data space to axis spaceNotImplementedErrorvals    r"   r   zAxis.mapper[       !!r$   c                    t           )z'A mapping from axis space to data spacer-   r/   s    r"   r(   zAxis.inverse_mapper_   r1   r$   c                    dS )zNGiven a range (low,high), raise an error if the range is invalid for this axisN r   r   s     r"   validatezAxis.validatec   s    r$   N)	__name__
__module____qualname____doc__r#   r+   r   r(   r6   r4   r$   r"   r   r   #   si            */ / /$" " "" " "    r$   r   c                  ^    e Zd ZdZeed                         Zeed                         ZdS )
LinearAxiszA linear Axisc                    | S Nr4   r/   s    r"   r   zLinearAxis.mapperj   	     
r$   c                    | S r>   r4   r/   s    r"   r(   zLinearAxis.inverse_mappero   r?   r$   N)r7   r8   r9   r:   staticmethodr
   r   r(   r4   r$   r"   r<   r<   h   sb        
  U \ 
  U \  r$   r<   c                  d    e Zd ZdZeed                         Zeed                         Zd ZdS )LogAxiszA base-10 logarithmic Axisc                :    t          t          |                     S r>   )r   floatr/   s    r"   r   zLogAxis.mapperw   s     U3ZZ   r$   c                    d}|| z  S )N
   r4   )r0   ys     r"   r(   zLogAxis.inverse_mapper|   s     #vr$   c                \    |d S |d         dk    s|d         dk    rt          d          d S )Nr   r   z,Range values must be >0 for logarithmic axes
ValueErrorr5   s     r"   r6   zLogAxis.validate   s;    =F8q==E!HMMKLLL *Mr$   N)	r7   r8   r9   r:   rA   r
   r   r(   r6   r4   r$   r"   rC   rC   u   sv        $$
! ! U \! 
  U \M M M M Mr$   rC   )linearlogc           
         ||||Q||Ot          d                    | t          |          t          |          t          |                              d S d S )Nz
{glyph} coordinates may be specified by providing both the x and y arguments, or by
providing the geometry argument. Received:
    x: {x}
    y: {y}
    geometry: {geometry}
glyphxrH   geometry)rK   formatreprrO   s       r"   validate_xy_or_geometryrU      sm    ai19 amq}  F$q''T!WWtH~~FFFH H 	H ! }}r$   c                      e Zd ZdZ	 	 	 ddZddZ	 	 dd	Zdd
ZddZddZ	ddZ
dd ej                    dddddfdZd Zd Zd Zd ZdS )Canvasa  An abstract canvas representing the space in which to bin.

    Parameters
    ----------
    plot_width, plot_height : int, optional
        Width and height of the output aggregate in pixels.
    x_range, y_range : tuple, optional
        A tuple representing the bounds inclusive space ``[min, max]`` along
        the axis.
    x_axis_type, y_axis_type : str, optional
        The type of the axis. Valid options are ``'linear'`` [default], and
        ``'log'``.
    X  NrL   c                    || _         || _        |d nt          |          | _        |d nt          |          | _        t
          |         | _        t
          |         | _        d S r>   )
plot_widthplot_heighttuplex_rangey_range_axis_lookupx_axisy_axis)r   rZ   r[   r]   r^   x_axis_typey_axis_types          r"   __init__zCanvas.__init__   sY     %&&ttE'NN&ttE'NN";/";/r$   c                   ddl m}m} ddlm} t          d|||           |
 |            }| |||          }	nt          rht          |t          j        j	                  rI| j
        | j
        nd}
| j        | j        nd}|j        t          |
 t          | f         } ||          }	nt          r&t          |t          j                  r ||          }	n[|                     |          x}|}ddlm}  ||          }	n0t%          d	                    t)          |          
                    t+          || |	|          S )a  Compute a reduction by pixel, mapping data to pixels as points.

        Parameters
        ----------
        source : pandas.DataFrame, dask.DataFrame, or xarray.DataArray/Dataset
            The input datasource.
        x, y : str
            Column names for the x and y coordinates of each point. If provided,
            the geometry argument may not also be provided.
        agg : Reduction, optional
            Reduction to compute. Default is ``count()``.
        geometry: str
            Column name of a PointsArray of the coordinates of each point. If provided,
            the x and y arguments may not also be provided.
        r   )PointMultiPointGeometry)countrf   NNNr   )MultiPointGeoPandassource must be an instance of spatialpandas.GeoDataFrame, spatialpandas.dask.DaskGeoDataFrame, geopandas.GeoDataFrame, or dask_geopandas.GeoDataFrame. Received objects of type {typ}typ)glyphsrf   rg   r   rh   rU   spatialpandas
isinstancedaskDaskGeoDataFramer]   r^   cx_partitionssliceGeoDataFrame_source_from_geopandasdatashader.glyphs.pointsrj   rK   rS   typebypixel)r   sourcerQ   rH   aggrR   rf   rg   	count_rdnrP   r]   r^   geopandas_sourcerj   s                 r"   pointszCanvas.points   s     	65555555222222Ax888;)++CE!QKKEE +FM4F4W!X!X +*.,*B$,,*.,*B$,,-eWoug.NO**844 +:fm6P#Q#Q +**844&*&A&A&&I&II"V)HHHHHH++H55 RRXRX LL SY S* S*+ + + vtUC000r$   r   Fc	                   ddl m}	m}
m}m}m}m}m}m} t          d|||           |t          j                    }|d}|r|dk    rt          d          |rd}|t          rit          |t          j        j                  rJ| j        | j        nd}| j        | j        nd}|j        t)          | t)          | f         } ||          }n t          r't          |t          j                  r ||          }n|                     |          x}|}dd	lm}  ||          }nt          d
                    t5          |                              t          |t6                    rt          |t8                    rt          |t8                    r||         }||         }|j        dk    rt          d|j                   |j        dk    rt          d|j                   ||j        vrt          d          t?          |j         j                  }|!                    |          } ||||          }n||}}tE          ||          \  }}|dk    rt          |tF          t8          f          r*t          |tF          t8          f          r |	||          }nKt          |t>          tH          f          rDt          |t>          tH          f          r( |tI          |          tI          |                    }nt          d                    tK          |          tK          |                              |dk    rt          |t>          tH          f          rDt          |t>          tH          f          r( |
tI          |          tI          |                    }nFt          |tL          j'                  r6t          |t>          tH          f          r ||tI          |                    }nt          |t>          tH          f          r4t          |tL          j'                  r |tI          |          |          }nt          |tF          t8          f          r)t          |tF          t8          f          r |||          }nat          d                    tK          |          tK          |                              t          d                    |                    |dk    rXtP          rt          |tP          j)                  s!tT          r0t          |tT          j)                  rtW          j,        d           d}|-                    |           |j.        r|}t          |t          j/                  r|j0        }t          |t          j        t          j1        t          j2        t          j3        t          j4        t          j5        t          j6        t          j7        t          j8        t          j9        t          j:        t          j;        t          j<        t          j=        t          j>        f          st          t5          |           d          t          || |||j.                  S )aR  Compute a reduction by pixel, mapping data to pixels as one or
        more lines.

        For aggregates that take in extra fields, the interpolated bins will
        receive the fields from the previous point. In pseudocode:

        >>> for i in range(len(rows) - 1):    # doctest: +SKIP
        ...     row0 = rows[i]
        ...     row1 = rows[i + 1]
        ...     for xi, yi in interpolate(row0.x, row0.y, row1.x, row1.y):
        ...         add_to_aggregate(xi, yi, row0)

        Parameters
        ----------
        source : pandas.DataFrame, dask.DataFrame, or xarray.DataArray/Dataset
            The input datasource.
        x, y : str or number or list or tuple or np.ndarray
            Specification of the x and y coordinates of each vertex
            * str or number: Column labels in source
            * list or tuple: List or tuple of column labels in source
            * np.ndarray: When axis=1, a literal array of the
              coordinates to be used for every row
        agg : Reduction, optional
            Reduction to compute. Default is ``any()``.
        axis : 0 or 1, default 0
            Axis in source to draw lines along
            * 0: Draw lines using data from the specified columns across
                 all rows in source
            * 1: Draw one line per row in source using data from the
                 specified columns
        geometry : str
            Column name of a LinesArray of the coordinates of each line. If provided,
            the x and y arguments may not also be provided.
        line_width : number, optional
            Width of the line to draw, in pixels. If zero, the
            default, lines are drawn using a simple algorithm with a
            blocky single-pixel width based on whether the line passes
            through each pixel or does not. If greater than one, lines
            are drawn with the specified width using a slower and
            more complex antialiasing algorithm with fractional values
            along each edge, so that lines have a more uniform visual
            appearance across all angles. Line widths between 0 and 1
            effectively use a line_width of 1 pixel but with a
            proportionate reduction in the strength of each pixel,
            approximating the visual appearance of a subpixel line
            width.
        antialias : bool, optional
            This option is kept for backward compatibility only.
            ``True`` is equivalent to ``line_width=1`` and
            ``False`` (the default) to ``line_width=0``. Do not specify
            both ``antialias`` and ``line_width`` in the same call as a
            ``ValueError`` will be raised if they disagree.

        Examples
        --------
        Define a canvas and a pandas DataFrame with 6 rows
        >>> import pandas as pd  # doctest: +SKIP
        ... import numpy as np
        ... import datashader as ds
        ... from datashader import Canvas
        ... import datashader.transfer_functions as tf
        ... cvs = Canvas()
        ... df = pd.DataFrame({
        ...    'A1': [1, 1.5, 2, 2.5, 3, 4],
        ...    'A2': [1.5, 2, 3, 3.2, 4, 5],
        ...    'B1': [10, 12, 11, 14, 13, 15],
        ...    'B2': [11, 9, 10, 7, 8, 12],
        ... }, dtype='float64')

        Aggregate one line across all rows, with coordinates df.A1 by df.B1
        >>> agg = cvs.line(df, x='A1', y='B1', axis=0)  # doctest: +SKIP
        ... tf.spread(tf.shade(agg))

        Aggregate two lines across all rows. The first with coordinates
        df.A1 by df.B1 and the second with coordinates df.A2 by df.B2
        >>> agg = cvs.line(df, x=['A1', 'A2'], y=['B1', 'B2'], axis=0)  # doctest: +SKIP
        ... tf.spread(tf.shade(agg))

        Aggregate two lines across all rows where the lines share the same
        x coordinates. The first line will have coordinates df.A1 by df.B1
        and the second will have coordinates df.A1 by df.B2
        >>> agg = cvs.line(df, x='A1', y=['B1', 'B2'], axis=0)  # doctest: +SKIP
        ... tf.spread(tf.shade(agg))

        Aggregate 6 length-2 lines, one per row, where the ith line has
        coordinates [df.A1[i], df.A2[i]] by [df.B1[i], df.B2[i]]
        >>> agg = cvs.line(df, x=['A1', 'A2'], y=['B1', 'B2'], axis=1)  # doctest: +SKIP
        ... tf.spread(tf.shade(agg))

        Aggregate 6 length-4 lines, one per row, where the x coordinates
        of every line are [0, 1, 2, 3] and the y coordinates of the ith line
        are [df.A1[i], df.A2[i], df.B1[i], df.B2[i]].
        >>> agg = cvs.line(df,  # doctest: +SKIP
        ...                x=np.arange(4),
        ...                y=['A1', 'A2', 'B1', 'B2'],
        ...                axis=1)
        ... tf.spread(tf.shade(agg))

        Aggregate RaggedArrays of variable length lines, one per row
        (requires pandas >= 0.24.0)
        >>> df_ragged = pd.DataFrame({  # doctest: +SKIP
        ...    'A1': pd.array([
        ...        [1, 1.5], [2, 2.5, 3], [1.5, 2, 3, 4], [3.2, 4, 5]],
        ...        dtype='Ragged[float32]'),
        ...    'B1': pd.array([
        ...        [10, 12], [11, 14, 13], [10, 7, 9, 10], [7, 8, 12]],
        ...        dtype='Ragged[float32]'),
        ...    'group': pd.Categorical([0, 1, 2, 1])
        ... })
        ...
        ... agg = cvs.line(df_ragged, x='A1', y='B1', axis=1)
        ... tf.spread(tf.shade(agg))

        Aggregate RaggedArrays of variable length lines by group column,
        one per row (requires pandas >= 0.24.0)
        >>> agg = cvs.line(df_ragged, x='A1', y='B1',  # doctest: +SKIP
        ...                agg=ds.count_cat('group'), axis=1)
        ... tf.spread(tf.shade(agg))
        r   )	LineAxis0
LinesAxis1LinesAxis1XConstantLinesAxis1YConstantLineAxis0MultiLinesAxis1RaggedLineAxis1GeometryLinesXarrayCommonXLineNr   zgDo not specify values for both the line_width and 
antialias keyword arguments; use line_width instead.g      ?ri   )LineAxis1GeoPandasrk   rl   z"x array must have 1 dimension not    z#y array must have 2 dimensions not z/x must be one of the coordinate dimensions of yz
Invalid combination of x and y arguments to Canvas.line when axis=0.
    Received:
        x: {x}
        y: {y}
See docstring for more information on valid usagerQ   rH   z
Invalid combination of x and y arguments to Canvas.line when axis=1.
    Received:
        x: {x}
        y: {y}
See docstring for more information on valid usagezE
The axis argument to Canvas.line must be 0 or 1
    Received: {axis}axiszYAntialiased lines are not supported for CUDA-backed sources, so reverting to line_width=0z0 reduction not implemented for antialiased lines	antialias)Arn   r   r   r   r   r   r   r   r   rU   rdanyrK   ro   rp   rq   rr   r]   r^   rs   rt   ru   rv   datashader.glyphs.liner   rS   rx   r   strndimdimslistcoordsindex _broadcast_column_specificationsr   r\   rT   r&   ndarraycudf	DataFrame	dask_cudfwarningswarnset_line_widthantialiasedby	reductionrh   maxminsumsummary	_sum_zero_first_or_lastmeanmax_nmin_n_first_n_or_last_n_max_or_min_row_index_max_n_or_min_n_row_indexwherer.   ry   )r   rz   rQ   rH   r{   r   rR   
line_widthr   r   r   r   r   r   r   r   r   r]   r^   rP   r}   r   x_arry_arry_coord_dimsx_dim_indexorig_xorig_ynon_cat_aggs                                r"   linezCanvas.line   s   r	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	 1h777;&((CJ  	HqGH H H  	J +FM4F4W!X!X +*.,*B$,,*.,*B$,,-eWoug.NO))(33 +:fm6P#Q#Q +))(33&*&A&A&&I&II"V)EEEEEE**844 RRXRX LL SY S* S*+ + + (( <	+Z3-?-? <	+JqRUDVDV <	+1IE1IEzQ !Rej!R!RSSSzQ !Suz!S!STTT
"" !RSSS 122L&,,Q//K&&q![99EE FF3Aq99DAqqyyq63-00 9"1vsm449%IaOOEE T5M22 
9"1tUm44
9*N588U1XX>>EE$ &5
 6<Vv,,$v,, 6< 68 689 9 9 a$// 9Jq4-4P4P 9&JuQxxq::EE BJ// 9 dE]339//588<<EE T5M22 9 BJ//9//a!<<EE VSM22 
9"1vsm44
9,,Q22EE$ &5
 6<Vv,,$v,, 6< 68 689 9 9 ! "D))+ + + NNN*VT^*L*LN ) .8AT.U.U M/0 0 0 JZ((( 	\ K+ru-- 4)3k"&"&"&"*bl!27BHbh@U("*F,   \
 *K((ZZZ\ \ \ vtUC5;LMMMMr$   c           	        ddl m}m}m}	m}
m}m}m}m}m	}m
}m}m} ddlm} |
 |            }|||}}}t          |||          \  }}}|dk    r|t!          |t"          t$          f          r*t!          |t"          t$          f          r |||          }nt!          |t&          t(          f          rDt!          |t&          t(          f          r( |	t)          |          t)          |                    }nHt+          d                    t/          |          t/          |                              t!          |t"          t$          f          rGt!          |t"          t$          f          r+t!          |t"          t$          f          r ||||          }nt!          |t&          t(          f          rnt!          |t&          t(          f          rRt!          |t&          t(          f          r6 |
t)          |          t)          |          t)          |                    }nt+          d                    t/          |          t/          |          t/          |          	                    |dk    r|t!          |t&          t(          f          rDt!          |t&          t(          f          r( |t)          |          t)          |                    }ngt!          |t0          j                  r7t!          |t&          t(          f          r ||t)          |                    }nt!          |t&          t(          f          r5t!          |t0          j                  r |t)          |          |          }nt!          |t"          t$          f          r*t!          |t"          t$          f          r |||          }nt+          d
                    t/          |          t/          |                              t!          |t&          t(          f          rnt!          |t&          t(          f          rRt!          |t&          t(          f          r6 |t)          |          t)          |          t)          |                    }nt!          |t0          j                  rat!          |t&          t(          f          rEt!          |t&          t(          f          r) ||t)          |          t)          |                    }n<t!          |t&          t(          f          rOt!          |t0          j                  r5t!          |t0          j                  r |t)          |          ||          }nt!          |t"          t$          f          rFt!          |t"          t$          f          r*t!          |t"          t$          f          r ||||          }not+          d                    t/          |          t/          |          t/          |          	                    t+          d                    |                    t5          || ||          S )a  Compute a reduction by pixel, mapping data to pixels as a filled
        area region

        Parameters
        ----------
        source : pandas.DataFrame, dask.DataFrame, or xarray.DataArray/Dataset
            The input datasource.
        x, y : str or number or list or tuple or np.ndarray
            Specification of the x and y coordinates of each vertex of the
            line defining the starting edge of the area region.
            * str or number: Column labels in source
            * list or tuple: List or tuple of column labels in source
            * np.ndarray: When axis=1, a literal array of the
              coordinates to be used for every row
        agg : Reduction, optional
            Reduction to compute. Default is ``count()``.
        axis : 0 or 1, default 0
            Axis in source to draw lines along
            * 0: Draw area regions using data from the specified columns
                 across all rows in source
            * 1: Draw one area region per row in source using data from the
                 specified columns
        y_stack: str or number or list or tuple or np.ndarray or None
            Specification of the y coordinates of each vertex of the line
            defining the ending edge of the area region, where the x
            coordinate is given by the x argument described above.

            If y_stack is None, then the area region is filled to the y=0 line

            If y_stack is not None, then the form of y_stack must match the
            form of y.

        Examples
        --------
        Define a canvas and a pandas DataFrame with 6 rows
        >>> import pandas as pd  # doctest: +SKIP
        ... import numpy as np
        ... import datashader as ds
        ... from datashader import Canvas
        ... import datashader.transfer_functions as tf
        ... cvs = Canvas()
        ... df = pd.DataFrame({
        ...    'A1': [1, 1.5, 2, 2.5, 3, 4],
        ...    'A2': [1.6, 2.1, 2.9, 3.2, 4.2, 5],
        ...    'B1': [10, 12, 11, 14, 13, 15],
        ...    'B2': [11, 9, 10, 7, 8, 12],
        ... }, dtype='float64')

        Aggregate one area region across all rows, that starts with
        coordinates df.A1 by df.B1 and is filled to the y=0 line
        >>> agg = cvs.area(df, x='A1', y='B1',  # doctest: +SKIP
        ...                agg=ds.count(), axis=0)
        ... tf.shade(agg)

        Aggregate one area region across all rows, that starts with
        coordinates df.A1 by df.B1 and is filled to the line with coordinates
        df.A1 by df.B2
        >>> agg = cvs.area(df, x='A1', y='B1', y_stack='B2', # doctest: +SKIP
        ...                agg=ds.count(), axis=0)
        ... tf.shade(agg)

        Aggregate two area regions across all rows. The first starting
        with coordinates df.A1 by df.B1 and the second with coordinates
        df.A2 by df.B2. Both regions are filled to the y=0 line
        >>> agg = cvs.area(df, x=['A1', 'A2'], y=['B1', 'B2'],  # doctest: +SKIP
                           agg=ds.count(), axis=0)
        ... tf.shade(agg)

        Aggregate two area regions across all rows where the regions share the
        same x coordinates. The first region will start with coordinates
        df.A1 by df.B1 and the second will start with coordinates
        df.A1 by df.B2. Both regions are filled to the y=0 line
        >>> agg = cvs.area(df, x='A1', y=['B1', 'B2'], agg=ds.count(), axis=0)  # doctest: +SKIP
        ... tf.shade(agg)

        Aggregate 6 length-2 area regions, one per row, where the ith region
        starts with coordinates [df.A1[i], df.A2[i]] by [df.B1[i], df.B2[i]]
        and is filled to the y=0 line
        >>> agg = cvs.area(df, x=['A1', 'A2'], y=['B1', 'B2'],  # doctest: +SKIP
                           agg=ds.count(), axis=1)
        ... tf.shade(agg)

        Aggregate 6 length-4 area regions, one per row, where the
        starting x coordinates of every region are [0, 1, 2, 3] and
        the starting y coordinates of the ith region are
        [df.A1[i], df.A2[i], df.B1[i], df.B2[i]].  All regions are filled to
        the y=0 line
        >>> agg = cvs.area(df,  # doctest: +SKIP
        ...                x=np.arange(4),
        ...                y=['A1', 'A2', 'B1', 'B2'],
        ...                agg=ds.count(),
        ...                axis=1)
        ... tf.shade(agg)

        Aggregate RaggedArrays of variable length area regions, one per row.
        The starting coordinates of the ith region are df_ragged.A1 by
        df_ragged.B1 and the regions are filled to the y=0 line.
        (requires pandas >= 0.24.0)
        >>> df_ragged = pd.DataFrame({  # doctest: +SKIP
        ...    'A1': pd.array([
        ...        [1, 1.5], [2, 2.5, 3], [1.5, 2, 3, 4], [3.2, 4, 5]],
        ...        dtype='Ragged[float32]'),
        ...    'B1': pd.array([
        ...        [10, 12], [11, 14, 13], [10, 7, 9, 10], [7, 8, 12]],
        ...        dtype='Ragged[float32]'),
        ...    'B2': pd.array([
        ...        [6, 10], [9, 10, 18], [9, 5, 6, 8], [4, 5, 11]],
        ...        dtype='Ragged[float32]'),
        ...    'group': pd.Categorical([0, 1, 2, 1])
        ... })
        ...
        ... agg = cvs.area(df_ragged, x='A1', y='B1', agg=ds.count(), axis=1)
        ... tf.shade(agg)

        Instead of filling regions to the y=0 line, fill to the line with
        coordinates df_ragged.A1 by df_ragged.B2
        >>> agg = cvs.area(df_ragged, x='A1', y='B1', y_stack='B2', # doctest: +SKIP
        ...                agg=ds.count(), axis=1)
        ... tf.shade(agg)

        (requires pandas >= 0.24.0)
        r   )AreaToZeroAxis0AreaToLineAxis0AreaToZeroAxis0MultiAreaToLineAxis0MultiAreaToZeroAxis1AreaToLineAxis1AreaToZeroAxis1XConstantAreaToLineAxis1XConstantAreaToZeroAxis1YConstantAreaToLineAxis1YConstantAreaToZeroAxis1RaggedAreaToLineAxis1Raggedr   Nr   z
Invalid combination of x and y arguments to Canvas.area when axis=0.
    Received:
        x: {x}
        y: {y}
See docstring for more information on valid usager   z
Invalid combination of x, y, and y_stack arguments to Canvas.area when axis=0.
    Received:
        x: {x}
        y: {y}
        y_stack: {y_stack}
See docstring for more information on valid usage)rQ   rH   y_stackz
Invalid combination of x and y arguments to Canvas.area when axis=1.
    Received:
        x: {x}
        y: {y}
See docstring for more information on valid usagez
Invalid combination of x, y, and y_stack arguments to Canvas.area when axis=1.
    Received:
        x: {x}
        y: {y}
        y_stack: {y_stack}
See docstring for more information on valid usagezE
The axis argument to Canvas.area must be 0 or 1
    Received: {axis}r   )rn   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rp   r   r   r   r\   rK   rS   rT   r&   r   ry   )r   rz   rQ   rH   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   any_rdnr   r   orig_y_stackrP   s                           r"   areazCanvas.area  sB   v	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	/.....;'))C ()!W8AwGG1g199q63-00 /"1vsm44/+OAq11EE T5M22 
/ T5M22
/00q588DDEE$ &5
 6<Vq''T!WW 6< 6. 6./ / / q63-00 5"1vsm445"7VSM::5 ,OAq'::EE T5M22 5 T5M225 4-885 10a%((E'NN< <EE % &5 6<Vv,,v,, $\ 2 2 6< 64 64	5 	5 	5 QYYq4-00 /"1tUm44/+OE!HHeAhh??EE BJ// / T5M22/44QaAAEE T5M22 / BJ///44U1XXqAAEE VSM22 
/ VSM22
/11!Q77EE$ &5
 6<Vq''T!WW 6< 6. 6./ / / q4-00 5"1tUm445"7T5M::5 ,Oa%((E'NN< <EE BJ// 5 T5M225 4-885 54588U7^^5 5EE T5M22 5 BJ//5 "*555 54U1XXq'JJEE VSM22 5 VSM225 63-885 21!Q@@EE$ &5 6<Vv,,v,, $\ 2 2 6< 64 64	5 	5 	5  D))+ + + vtUC000r$   c                "   ddl m} ddlm} t          rht          |t          j        j                  rI| j        | j        nd}| j	        | j	        nd}|j
        t          | t          | f         } ||          }nwt          r&t          |t          j                  r ||          }nJ|                     |          x}	|	}ddlm}
  |
|          }nt!          dt#          |                     |
 |            }t%          || ||          S )a  Compute a reduction by pixel, mapping data to pixels as one or
        more filled polygons.

        Parameters
        ----------
        source : xarray.DataArray or Dataset
            The input datasource.
        geometry : str
            Column name of a PolygonsArray of the coordinates of each line.
        agg : Reduction, optional
            Reduction to compute. Default is ``any()``.

        Returns
        -------
        data : xarray.DataArray

        Examples
        --------
        >>> import datashader as ds  # doctest: +SKIP
        ... import datashader.transfer_functions as tf
        ... from spatialpandas.geometry import PolygonArray
        ... from spatialpandas import GeoDataFrame
        ... import pandas as pd
        ...
        ... polygons = PolygonArray([
        ...     # First Element
        ...     [[0, 0, 1, 0, 2, 2, -1, 4, 0, 0],  # Filled quadrilateral (CCW order)
        ...      [0.5, 1,  1, 2,  1.5, 1.5,  0.5, 1],     # Triangular hole (CW order)
        ...      [0, 2, 0, 2.5, 0.5, 2.5, 0.5, 2, 0, 2],  # Rectangular hole (CW order)
        ...      [2.5, 3, 3.5, 3, 3.5, 4, 2.5, 3],  # Filled triangle
        ...     ],
        ...
        ...     # Second Element
        ...     [[3, 0, 3, 2, 4, 2, 4, 0, 3, 0],  # Filled rectangle (CCW order)
        ...      # Rectangular hole (CW order)
        ...      [3.25, 0.25, 3.75, 0.25, 3.75, 1.75, 3.25, 1.75, 3.25, 0.25],
        ...     ]
        ... ])
        ...
        ... df = GeoDataFrame({'polygons': polygons, 'v': range(len(polygons))})
        ...
        ... cvs = ds.Canvas()
        ... agg = cvs.polygons(df, geometry='polygons', agg=ds.sum('v'))
        ... tf.shade(agg)
        r   PolygonGeomr   Nri   )GeopandasPolygonGeomzsource must be an instance of spatialpandas.GeoDataFrame, spatialpandas.dask.DaskGeoDataFrame, geopandas.GeoDataFrame or dask_geopandas.GeoDataFrame, not )rn   r   r   r   ro   rp   rq   rr   r]   r^   rs   rt   ru   rv   glyphs.polygonr   rK   rx   ry   )r   rz   rR   r{   r   r   r]   r^   rP   r}   r   s              r"   polygonszCanvas.polygons  sa   \ 	('''''...... 	DZ0B0STT 	D&*l&>dllLG&*l&>dllLG)%/5'?*JKFK))EE 
	Dz&-2LMM 
	DK))EE"&"="=f"E"EER%F<<<<<<((22EEC48LLC CD D D
 ;'))CvtUC000r$   c           
     d   ddl m}m}m} ddlm} t          |t                    r5||j        t          |j
                  d         }	n|j        }	||	g         }n@t          |t                    r|j        }	|                                }nt          d          | ||	          }||||	         j        \  }}n|r|st          d          ||         ||         }}
|
j        dk    s|j        dk    r0|j        |
j        k    r t          d|j        d	|
j        d
          |	-|j        &|j        |	k    rt          d|j        d|d          |j        dk    rr| j        t$          d         u }| j        t$          d         u }t)          j        |
t)          j        |
d         |
d         t/          |
                              }t)          j        |t)          j        |d         |d         t/          |                              }|r|r|r|r ||||	          }|                    ||||	| j        | j        | j        | j                  \  }}|r(|r&t;          j        |	          }t?          || ||          S |s|st?          || ||          S  ||||	          }t?          || ||          S  ||||	          }t?          || ||          S |j        dk    r ||||	          }t?          || ||          S t          d                     t          |j                                      )a  Samples a recti- or curvi-linear quadmesh by canvas size and bounds.

        Parameters
        ----------
        source : xarray.DataArray or Dataset
            The input datasource.
        x, y : str
            Column names for the x and y coordinates of each point.
        agg : Reduction, optional
            Reduction to compute. Default is ``mean()``. Note that agg is ignored when
            upsampling.

        Returns
        -------
        data : xarray.DataArray
        r   )QuadMeshRasterQuadMeshRectilinearQuadMeshCurvilinearr   Nr   zInvalid input typezDEither specify both x and y coordinatesor allow them to be inferred.z_Ensure that x- and y-coordinate arrays share the same dimensions. x-coordinates are indexed by z) dims while y-coordinates are indexed by z dims.DataArray name # does not match supplied reduction .rL   r   zcx- and y-coordinate arrays must have 1 or 2 dimensions.
    Received arrays with dimensions: {dims})r   )!rn   r   r   r   r   r   rp   r   columnr   	data_varsr   name
to_datasetrK   r   r   r`   r_   ra   r&   allcloselinspacelenis_upsampler]   r^   rZ   r[   r   	_upsamplery   rS   )r   rz   rQ   rH   r{   r   r   r   mean_rndr   yarrxarrxaxis_linearyaxis_lineareven_yspacingeven_xspacingrP   upsample_widthupsample_heights                      r"   quadmeshzCanvas.quadmesh  s   " 	UTTTTTTTTT 	100000fg&& 	3{cj0F,--a0zTF^FF	** 	3;D&&((FF1222;(4..C9$<$DAqq 	>! 	> = > > >AYq	dIMMTY]]	TY0F0F* #iii	4 5 5 5 J*J$&&*$kkk3330 1 1 1 9>>;,x*@@L;,x*@@LKbk$q'48SYY?? M Kbk$q'48SYY?? M  9 9 9= 9&q!T22272C2C1dDL$,)93 3/ " =o =,t,,C"64<<<' = ="64<<< 0/1d;;E"64<<< ,+Aq$77vtUC888Y!^^''1d33E64444 //5v$)__ 06 0& 0&' ' 'r$   Tc                   ddl m} ddlm} ddlm}	 |}
|6|dk    rd}n-|dk    rd	}n$t          d
                    ddg                    |
 |	||          }
t          |j	                  dk    }|r|j	        d         }n|j	        d         }| ||          }n|j
        ||_
        |
j	        }|d         |d         |dd         }}}t          |
|  ||||||          |          S )a
  Compute a reduction by pixel, mapping data to pixels as a triangle.

        >>> import datashader as ds
        >>> verts = pd.DataFrame({'x': [0, 5, 10],
        ...                         'y': [0, 10, 0],
        ...                         'weight': [1, 5, 3]},
        ...                        columns=['x', 'y', 'weight'])
        >>> tris = pd.DataFrame({'v0': [2], 'v1': [0], 'v2': [1]},
        ...                       columns=['v0', 'v1', 'v2'])
        >>> cvs = ds.Canvas(x_range=(verts.x.min(), verts.x.max()),
        ...                 y_range=(verts.y.min(), verts.y.max()))
        >>> untested = cvs.trimesh(verts, tris)

        Parameters
        ----------
        vertices : pandas.DataFrame, dask.DataFrame
            The input datasource for triangle vertex coordinates. These can be
            interpreted as the x/y coordinates of the vertices, with optional
            weights for value interpolation. Columns should be ordered
            corresponding to 'x', 'y', followed by zero or more (optional)
            columns containing vertex values. The rows need not be ordered.
            The column data types must be floating point or integer.
        simplices : pandas.DataFrame, dask.DataFrame
            The input datasource for triangle (simplex) definitions. These can
            be interpreted as rows of ``vertices``, aka positions in the
            ``vertices`` index. Columns should be ordered corresponding to
            'vertex0', 'vertex1', and 'vertex2'. Order of the vertices can be
            clockwise or counter-clockwise; it does not matter as long as the
            data is consistent for all simplices in the dataframe. The
            rows need not be ordered.  The data type for the first
            three columns in the dataframe must be integer.
        agg : Reduction, optional
            Reduction to compute. Default is ``mean()``.
        mesh : pandas.DataFrame, optional
            An ordered triangle mesh in tabular form, used for optimization
            purposes. This dataframe is expected to have come from
            ``datashader.utils.mesh()``. If this argument is not None, the first
            two arguments are ignored.
        interpolate : str, optional default=linear
            Method to use for interpolation between specified values. ``nearest``
            means to use a single value for the whole triangle, and ``linear``
            means to do bilinear interpolation of the pixels within each
            triangle (a weighted average of the vertex values). For
            backwards compatibility, also accepts ``interp=True`` for ``linear``
            and ``interp=False`` for ``nearest``.
        r   )	Trianglesr   )meshNrL   TnearestF.Invalid interpolate method: options include {}r      r   )weight_typeinterp)rn   r   r   r   utilsr   rK   rS   r   columnsr   ry   )r   vertices	simplicesr   r{   r   interpolater   mean_rdncreate_meshrz   verts_have_weights
weight_colcolsrQ   rH   weightss                    r"   trimeshzCanvas.trimeshz  so   ^ 	&%%%%%000000...... "h&&	)) !Q!X!Xi("* "* + + + > [955F !122Q6 	.!)!,JJ"*1-J;(:&&CCZ#CJ~Qa$qrr(g1vtYYq!WJ\6<&> &> &>?BD D 	Dr$   c
                   ||}||}ddg}
i ddt           j        dddt           j        dddt           j        dddt           j        dddt           j        dd	d	t           j        d	d
d
t           j        d
ddt           j        d}||
vr"t          d
                    |
                    t          |t          t          f          s$t          dt          |          j        z            d}t          |t           j                  r`t          |          |j        }}t          |t                    r5|3|j        |k    r(|j        d|d}t          d|j        d|d          t          |t                    rOt'          |j                  }|t          d|z            ||j        vrt+          d|d|d          ||         }||                                vrAt          d
                    t'          |                                                              ||         }|j        dvrt          d|j        z            t1          |          }|j        dd         \  }}||         j        ||         j        }}t7          |||          \  }}}}| |j        d,i |j        d         |i}t;          ||          }|+||k    }t<          j                             |||          }|}n3t=          j!        |j"        t<          j#                  rd}nt<          j$        }| j%        	||f| _%        | j&        	||f| _&        t          | j%        d         |          }t          | j&        d         |          }t          | j%        d         |          }t          | j&        d         |          }t          ||z
  | j%        d         | j%        d         z
  z  d          } t          ||z
  | j&        d         | j&        d         z
  z  d          }!t=          j'        | d          st=          j'        |!d          rt          d          t          tQ          tS          | j*        | z                      d          }"t          tQ          tS          | j+        |!z                      d          }#tY          ||||d                   \  }$}%tY          ||||d                   \  }&}'t[          |"|#|||          }(|j        dk    rh||&|'dz   |$|%dz   f         })|d v r|).                    d!          })t          |)t^          j0                  rtc          |)f||	d"|(}*nte          |)fi |(}*d}+n|dd|&|'dz   |$|%dz   f         })|d v r|).                    d!          })g },|)D ]O}-t          |-t^          j0                  rtc          |-f||	d"|(}-nte          |-fi |(}-|,3                    |-           Pt=          j4        |,          }*tk          |,          }+|"| j*        k    s|#| j+        k    r| j+        |#z
  }.| j*        |"z
  }/|| j%        d         z
  }0| j%        d         |z
  }1|0|1z   dk    r|0|0|1z   z  nd}2t          tQ          t=          j6        |/|2z                      d          }t          |/|z
  d          }| j+        |f| j+        |f}4}3|+dk    r|3|+fz   |4|+fz   }4}3t=          j7        |3||)j"                  }5t=          j7        |4||)j"                  }6|| j&        d         z
  }7| j&        d         |z
  }8|7|8z   dk    r|7|7|8z   z  nd}9t          tQ          t=          j6        |.|9z                      d          }t          |.|z
  d          }||"f||"f};}:|+dk    r|:|+fz   |;|+fz   };}:t=          j7        |:||)j"                  }<t=          j7        |;||)j"                  }=t          |*t^          j0                  rt^          j8        nt<          j8        }>|<j9        d         dk    r|<|*fn|*f},|=j9        d         dk    r|,|=fz  },tk          |,          dk    r |>|,d#          n|,d         }*|5j9        d         dk    r|5|*fn|*f},|6j9        d         dk    r|,|6fz  },tk          |,          dk    r |>|,d#          n|,d         }*|d         dk    r|*ddd$         }*|d         dk     r|*ddddd$f         }*t=          j:        ||g| j%                  ot=          j;        |          | j*        k    }?t=          j:        ||g| j&                  ot=          j;        |          | j+        k    }@|?r|}An\| j<        =                    | j%        | j*                  }B| j<        >                    |B| j*                  }A|d         dk     r|Addd$         }A|@r|}Cn\| j?        =                    | j&        | j+                  }D| j?        >                    |D| j+                  }C|d         dk    r|Cddd$         }C||A||Ci}E||g}Ft[          |d         | j%        | j&        %          }Gd&D ]}H|H|j@        v r|j@        |H         |Gd'<    nd'|Gvr(	 |j@        d(         d         |Gd'<   n# t          $ r Y nw xY w|*j        d)k    r:|*B                    g d*          }*|j        d         }I|jC        |I         |E|I<   |Ig|Fz   }Ft          |*|E|F|G+          S )-aO
  Sample a raster dataset by canvas size and bounds.

        Handles 2D or 3D xarray DataArrays, assuming that the last two
        array dimensions are the y- and x-axis that are to be
        resampled. If a 3D array is supplied a layer may be specified
        to resample to select the layer along the first dimension to
        resample.

        Missing values (those having the value indicated by the
        "nodata" attribute of the raster) are replaced with `NaN` if
        floats, and 0 if int.

        Also supports resampling out-of-core DataArrays backed by dask
        Arrays. By default it will try to maintain the same chunksize
        in the output array but a custom chunksize may be provided.
        If there are memory constraints they may be defined using the
        max_mem parameter, which determines how large the chunks in
        memory may be.

        Parameters
        ----------
        source : xarray.DataArray or xr.Dataset
            2D or 3D labelled array (if Dataset, the agg reduction must
            define the data variable).
        layer : float
            For a 3D array, value along the z dimension : optional default=None
        ds_method : str (optional)
            Grid cell aggregation method for a possible downsampling.
        us_method : str (optional)
            Grid cell interpolation method for a possible upsampling.
        nan_value : int or float, optional
            Optional nan_value which will be masked out when applying
            the resampling.
        agg : Reduction, optional default=mean()
            Resampling mode when downsampling raster. The supported
            options include: first, last, mean, mode, var, std, min,
            The agg can be specified as either a string name or as a
            reduction function, but note that the function object will
            be used only to extract the agg type (mean, max, etc.) and
            the optional column name; the hardcoded raster code
            supports only a fixed set of reductions and ignores the
            actual code of the provided agg.
        interpolate : str, optional  default=linear
            Resampling mode when upsampling raster.
            options include: nearest, linear.
        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
        -------
        data : xarray.Dataset
        Nr   rL   firstlastmoder   varstdr   r   r   zBExpected xarray DataArray or Dataset as the data source, found %s.()r   r   r   zsWhen supplying a Dataset the agg reduction must specify the variable to aggregate. Available data_vars include: %r.zSupplied reduction column zE not found in Dataset, expected one of the following data variables: z.Invalid aggregation method: options include {})r   r   zDRaster aggregation expects a 2D or 3D DataArray, found %s dimensionsr   )mask
fill_valuer   zCanvas x_range or y_range values do not match closely enough with the data source to be able to accurately rasterize. Please provide ranges that are more accurate.)wh	ds_method	us_methodr  r   )r  r  f)	chunksizemax_memr   r   )resr]   r^   )
_FillValuemissing_valuer  nodataNODATAr  
nodatavalsr   )r   r   r   )r   r   attrsr4   )Dr   r  r  r  r   r  r  r   r   rK   rS   rp   r   r   rx   r7   	Reductionr   r   r   r   KeyErrorkeysr   r   r   valuesr   selr   r&   mamasked_array
issubdtypedtypeintegernanr]   r^   iscloseintroundrZ   r[   r   dictastypedaArrayr   r   appenddstackr   ceilfullconcatenateshaper   sizer`   r#   r+   ra   r  	Exception	transposer   )Jr   rz   layerupsample_methoddownsample_method	nan_valuer{   r   r  r  upsample_methodsdownsample_methodsr   agg_reprr   r  r  ydimxdimxvalsyvalsleftbottomrighttoparrayr  r  xminyminxmaxymaxwidth_ratioheight_ratior  r  cmincmaxrminrmaxkwargssource_windowdatalayersarraysarr
num_height	num_widthlpadrpadlpctlshapershapeleft_pad	right_padtpadbpadtpcttshapebshapetop_pad
bottom_padconcatclose_xclose_yxsx_stysy_str   r   r  a	layer_dimsJ                                                                             r"   rasterzCanvas.raster  s   F !C'K%h/=gg =rx =$V=/1wv=$V=/1wv= %V= 02wv= $E	= 02ve	=
 $E=
 02ve= $E= 02ve= $E= 02ve= ...MTT " " # # # &9g"677 	6 :#F||45 6 6 6 c2<(( 	:s))SZC69-- :&2DK6))'*|||VVV< j"(+++xxx"9 : : : fg&& 
	$V-..I~  "DFO"P Q Q Q v///h8>			 K L L L F^F(--////MTT',,..//1 1 2 2 2&s+	;f$$ >@FL M M M v[%
dd|*F4L,?u#,UE3#?#? feS6:88Q 788FVS)) )#DE&&u4I&NNE"JJ]6<44 	 JJJ< <DL<"3<DL 4<?D))4<?F++4<?E**4<?C((4$;4<?T\!_+LMqQQD4KDLOdl1o,MNPQRR:k1%% 	NL!)D)D 	N M N N N E$/K788991==E$*\9::;;Q?? tUCF;;
d tUCF;;
dQ) +
D D D:??!$tAv+tDF{":;MN** - 4 4S 9 9-22 <.!-6   #=;;F;;FF!!!!T$q&[$tAv+"=>MN** - 4 4S 9 9F$ # #c28,, 51"'0'" " " "CC &c44V44Cc""""9V$$D[[F1(8#8#8)A-J!+I$,q/)D<?T)D+/$;??44$;''Ds279t#34455q99D	D(!,,E".58H%7PFFzz!'6)!3Vvi5Gwvz=3FGGH
M4GHHI$,q/)D<?T)D+/$;??44$;''Dc"'*t"34455q99Cc)1--F!1X{FFzz!'6)!3Vvi5Ggfj-2EFFG]5HIIJ'1$'A'AUR^^r~F(/a(81(<(<gt__4'F"Q&&:-'-0[[1__66&q))))&)D)1):Q)>)>h%%TGFq!A%%9,&-0[[1__66&q))))&)D q6A::":Dq6A::44R4=D +tUmT\::`rwu~~QUQ`?`+vsmT\::arwu~~QUQa?a 	BB;::4<YYD**4AAB1vzz"X 	BB;::4<IYZZD**41ABBB1vzz"XD"%d|Qt|LLL
 S 	 	AFL  "(,q/h ! 5  "(,|"<Q"?h    9>>>>))),,DAI &i 8F9;t#Df4uEEEEs   8j 
jjc                n    | j                             |           | j                            |           d S r>   )r`   r6   ra   )r   r]   r^   s      r"   validate_rangeszCanvas.validate_ranges  s4    W%%%W%%%%%r$   c                <    |dk    s|dk    rt          d          d S )Nr   z>Invalid size: plot_width and plot_height must be bigger than 0rJ   )r   widthheights      r"   validate_sizezCanvas.validate_size  s)    A::1]^^^ %r$   c                    |                      | j        | j                   |                     | j        | j                   dS )z7Check that parameter settings are valid for this objectN)rq  r]   r^   ru  rZ   r[   )r   s    r"   r6   zCanvas.validate  s=    T\4<8884?D,<=====r$   c           	        	 ddl }n# t          $ r d}Y nw xY w	 ddl}n# t          $ r d}Y nw xY w|rt          ||j                  s|r=t          ||j                  r'ddlm} ddlm}  ||           |d          k     rt          d          t          ||j                  r| j	        | j	        nt          j         t          j        f}| j        | j        nt          j         t          j        f}ddlm} |j                             ||d         |d         |d         |d                             }	|j        |	         }n=| j	        | j	        nd	}| j        | j        nd	}|j        t%          | t%          | f         }|S dS )
z
        Check if the specified source is a geopandas or dask-geopandas GeoDataFrame.
        If so, spatially filter the source and return it.
        If not, return None.
        r   N)Version)__version__z2.0.0z8Use of GeoPandas in Datashader requires Shapely >= 2.0.0)boxr   ri   )	geopandasImportErrordask_geopandasrp   ru   packaging.versionrx  shapelyry  r]   r&   infr^   rz  sindexqueryiloccxrt   )
r   rz   r{  r}  rx  shapely_versionr]   r^   rz  r  s
             r"   rv   zCanvas._source_from_geopandas  s   	 	 	 	III		"!!!!! 	" 	" 	"!NNN	"  	:fi.DEE 		",V^5P"Q"Q	 211111>>>>>>w'''''*:*:::!"\]]]&)"899 	E*.,*B$,,"&RTRXHY*.,*B$,,"&RTRXHY''''''++CC
GAJPQ
T[\]T^,_,_``U+*.,*B$,,*.,*B$,,5'?E7O#CDM4s     ..)rX   rX   NNrL   rL   )NNNN)NNNr   Nr   F)Nr   Nr>   )NNN)NNTN)r7   r8   r9   r:   rd   r~   r   r   r   r   r  r   r   ro  rq  ru  r6   rv   r4   r$   r"   rW   rW      s_         47'+3;0 0 0 0.1 .1 .1 .1` GK%*wN wN wN wNrm1 m1 m1 m1^E1 E1 E1 E1Nd' d' d' d'TRD RD RD RDl '!(ZF ZF ZF ZFx& & &_ _ _> > >
$ $ $ $ $r$   rW   Fr   c          	     x   t          | ||          \  } }|j        }|                    |           |                    |           |                                 t          j                    5  t          j        dd           t                              | |||||          cddd           S # 1 swxY w Y   dS )a  Compute an aggregate grouped by pixel sized bins.

    Aggregate input data ``source`` into a grid with shape and axis matching
    ``canvas``, mapping data to bins by ``glyph``, and aggregating by reduction
    ``agg``.

    Parameters
    ----------
    source : pandas.DataFrame, dask.DataFrame
        Input datasource
    canvas : Canvas
    glyph : Glyph
    agg : Reduction
    ignorez All-NaN (slice|axis) encounteredr   N)_bypixel_sanitisemeasurer6   r   catch_warningsfilterwarningsry   pipeline)rz   canvasrP   r{   r   dshapeschemas          r"   ry   ry     s    'vuc::NFF^F	NN6LL
OO 
	 	"	" Y Y*MNNNsiXXY Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Ys   -5B//B36B3c                   t          | t                    r-| j        dk    r"| j        sd| _        |                                 } t          | t
                    rt          | j                  dk    rt          | j	        
                                          t          | j        
                                          z   }t          |||          |                     fd|D                       } |                                 } t          | t          j                  s!t"          rt          | t"          j                  rt          | j        ||          t                    t          | j                  k     r{d }ddlm} t          ||          r!t+          | |j                 j        dd           }|          } |8t+          | |j                 j        dd           || |j                 j        _        t3          |           }nat          | t4          j                  rt7          |           \  }} n4t          | t
                    rt9          |           }nt;          d          | |fS )Nr   valuec                    g | ]}|v|	S r4   r4   ).0colcols_to_keeps     r"   
<listcomp>z%_bypixel_sanitise.<locals>.<listcomp>C  s#    "U"U"U3S=T=T3=T=T=Tr$   r   _sindexz)source must be a pandas or dask DataFrame)rp   r   r   r   reset_coordsr   r   r   r   r   r  r   _cols_to_keep	drop_varsto_dask_dataframepdr   r   r   r   r   getattrrR   rE  r  r   ddr   r   rK   )rz   rP   r{   r   r  r   r  r  s          @r"   r  r  :  sF   &)$$ ')9)9{ 	"!FK$$&&&'"" ,s6;'7'71'<'<v}))++,,tF4D4I4I4K4K/L/LL$WeS99!!"U"U"U"U'"U"U"UVV))++62<(( FF 88F %V^UC@@|s6>2222 F333333%-- P !7!=y$OOL)F"F5>28)TJJR7=u~&,4#F++	FBL	)	) F)&11	FG	$	$ F+F33DEEE6>r$   c                    t          d | D                       }|                                D ]}d||<   fd ||           d |                                D             S )z
    Return which columns from the supplied data source are kept as they are
    needed by the specified agg. Excludes any SpecialColumn.
    c                    i | ]}|d S )Fr4   )r  r  s     r"   
<dictcomp>z!_cols_to_keep.<locals>.<dictcomp>j  s    777e777r$   Tc                   t          |d          r|j        D ]} | |           d S t          |d          r&|j        D ]}|d t          j        j        fvrd| |<   d S |j        d t          j        j        fvrd| |j        <   d S d S )Nr  r   T)hasattrr  r   r   SpecialColumnRowIndexr   )r  r{   subaggr   recurses       r"   r  z_cols_to_keep.<locals>.recursen  s    3!! 	,* . .f----. .S)$$ 	,+ 0 0$(8(A!BBB+/L(0 0 Zb&6&?@@@'+L$$$ A@r$   c                    g | ]	\  }}||
S r4   r4   )r  r  keepits      r"   r  z!_cols_to_keep.<locals>.<listcomp>{  s!    BBBKC6BCBBBr$   )r)  required_columnsitems)r   rP   r{   r  r  r  s        @r"   r  r  e  s    
 77w77788L%%'' ! ! S	, 	, 	, 	, 	, GL#BB<#5#5#7#7BBBBr$   c                     d | D             }t          |          dk    r| S |                                t          fd| D                       S )Nc                d    h | ]-}t          |t          t          f          t          |          .S r4   )rp   r   r\   r   )r  rm  s     r"   	<setcomp>z3_broadcast_column_specifications.<locals>.<setcomp>  s1    DDD!z!dE]'C'CDs1vvDDDr$   r   c              3  `   K   | ](}t          |t          t          f          r|fz  n|V  )d S r>   )rp   r   r   )r  argr   s     r"   	<genexpr>z3_broadcast_column_specifications.<locals>.<genexpr>  sT       
 
 %S63-88ASFQJJc
 
 
 
 
 
r$   )r   popr\   )argslengthsr   s     @r"   r   r   ~  sq    DDtDDDG
7||qKKMM 
 
 
 

 
 
 
 
 	
r$   )4
__future__r   numbersr   mathr   r   numpyr&   pandasr  dask.dataframe	dataframer  
dask.arrayrE  r+  xarrayr   r   r   r	   r
   r   r   r   r   r   r   r   r   
resamplingr   r    r   r   r   r4  r   ro   r   r<   rC   r_   rU   rW   ry   r  r  r   r  r4   r$   r"   <module>r     s;   " " " " " "                                  % % % % % % % %                D D D D D D D D D D       < < < < < < < <      KKKK   DDD   III   MMMB B B B B B B BJ
 
 
 
 
 
 
 
M M M M Md M M M* %*,,wwyy99	H 	H 	HB B B B B B B BJ$ 6; Y Y Y Y Y8( ( (VC C C2

 

 

 :<<   s6   "A' 'A10A15A: :BBB BB