a
    DfA                    @   s  d dl Z d dlmZmZ d dlmZ d dlmZ d dl	Z
d dlmZ d dlmZ d dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlmZ zd dlmZ m!Z! W n e"y   e#e# Z!Z Y n0 dd	l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ dd
l,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJ ddlKmLZL ddlMmNZN ddlOmPZPmQZQ ee
jRZSeSedkZTG dd deQZUG dd deUZVG dd deVZWG dd deWZXG dd deUZYG dd deYZZG dd deVZ[G d d! d!eUZ\G d"d# d#e\eVZ]G d$d% d%e\Z^G d&d' d'eUZ_G d(d) d)eWZ`G d*d+ d+eWZaG d,d- d-eaZbG d.d/ d/ePZcG d0d1 d1eVZdG d2d3 d3eUZeG d4d5 d5eeecZfG d6d7 d7e)ZgG d8d9 d9ePZhG d:d; d;ehZiG d<d= d=ehZjd>d? ZkG d@dA dAe)ZlG dBdC dCele!ZmG dDdE dEele ZdFdG ZnG dHdI dIe)ZoG dJdK dKe)ZpG dLdM dMepZqG dNdO dOeqZrG dPdQ dQeqZseBereCesiep_tdS )R    N)CallableIterable)partial)color_lookup)Version)
bothmethod)directly_connect_edgeshammer_bundle   )CompositeOverlay	DimensionElement	NdOverlay	OperationOverlayStore)DaskInterfaceDatasetPandasInterfaceXArrayInterfacecuDFInterface)cast_array_to_int64cftime_to_timestampcftime_typesdatetime_types	dt_to_intget_param_values)RGBAreaContoursCurveGraphImage
ImageStackPathPointsPolygonsQuadMesh
RectanglesScatterSegmentsSpikesSpreadTriMesh)connect_tri_edges_pd)	PointerXY   )LinkableOperationResampleOperation2Dz0.15.1c                   @   s   e Zd ZdZejejeje	fe
 ddZejejejejejfdddZejdddd	Zejej
ejejejejejejejejejejd
ZedddZdd Zdd ZdS )AggregationOperationz
    AggregationOperation extends the ResampleOperation2D defining an
    aggregator parameter used to define a datashader Reduction.
    a  
        Datashader reduction function used for aggregating the data.
        The aggregator may also define a column to aggregate; if
        no column is defined the first value dimension of the element
        will be used. May also be defined as a string.)class_defaultdocNz
        Selector is a datashader reduction function used for selecting data.
        The selector only works with aggregators which selects an item from
        the original data. These selectors are min, max, first and last.z{kdims} Tz
        Prefix to prepend to value dimension name where {kdims}
        templates in the names of the input element key dimensions.r5   
allow_Noner6   )anycountfirstlastmodemeansumvarstdminmax	count_catc           	      C   s6  t rtjtjtjf}ntjtjf}t|trx|| jvrTt| j}t	d|d||dkrl| j| d}n| j|  }|
dd tg}|r2t|ddd	v r2t||s2|st	d
| j |d }t|tr|jjr|jjd j}n<|jr|jd j}n(t|tr|jd j}nt	d| j t||}|S )NzAggregation method 'z+' is not known; aggregator must be one of: rD   __temp__c                 S   s   | S N xrG   rG   k/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/holoviews/operation/datashader.py<lambda>       z6AggregationOperation._get_aggregator.<locals>.<lambda>columnF)rE   Nz5Could not find any elements to apply %s operation to.r   zCould not determine dimension to apply '%s' operation to. Declare the dimension to aggregate as part of the datashader aggregator.)ds15rdr:   r9   where
isinstancestr_agg_methodssorted
ValueErrortraverser   getattr__name__r-   nodesvdimsnamer   kdimstype)	clselementagg	add_fieldZ	agg_typesZagg_methodselementsZinner_elementfieldrG   rG   rJ   _get_aggregatorr   s@    



z$AggregationOperation._get_aggregatorc	                    s   |r
|j nd}|r|j nd}tjt||ftj||g||||id}
|dkrVd|	d< |dkrfd|	d< | jj|
fi |	 t|t	j
r|j|jdd	}||j}t fd
d|D |S  S )NrI   ydimscoordsr   r0   xdensityydensityFexpandedc                    s   i | ]
}| qS rG   rG   .0velrG   rJ   
<dictcomp>   rL   z3AggregationOperation._empty_agg.<locals>.<dictcomp>)r[   xr	DataArraynpfullnanpelement_typerQ   dsrD   dimension_valuesrM   get_dimensionr   )selfr_   rI   re   widthheightxsysagg_fnparamsxarrayvalsZdimrG   rp   rJ   
_empty_agg   s    zAggregationOperation._empty_aggc                    s  t t|||gdg|d}| jrHddd |d D }| jj|d}nd}d }	t|d	rf|j}	|j}t|t	j
rxd n|r|jnd t|j }
|
d
krt|jt	js|jn|jj t|d  fddd}n|
dkrt|j}nrvfdd|dD }|std|t|tjtjfrb|rD|  d}n
 d}|d j|dd}n|d | }nP|	r|	 d|
 }t| | |d}|
dv rd|_nt| |
 |
dd}||d< |S )Nr   )r\   datatypebounds_c                 s   s   | ]}t |V  qd S rF   )rR   rn   ZkdrG   rG   rJ   	<genexpr>   rL   z7AggregationOperation._get_agg_params.<locals>.<genexpr>r\   r\    	reductionZWhererZ   c                    s   |  kS rF   rG   rH   )colrG   rJ   rK      rL   z6AggregationOperation._get_agg_params.<locals>.<lambda>keyZSummaryc                    s   g | ]}| kr|qS rG   rG   rn   d)rM   rG   rJ   
<listcomp>   rL   z8AggregationOperation._get_agg_params.<locals>.<listcomp>rangeszjAggregation column '{}' not found on '{}' element. Ensure the aggregator references an existing dimension.z Countr   nodata )label)CountAny)r   r   )dictr   vdim_prefixjoinformathasattr
cat_columnr   rQ   rO   summaryrM   r]   rX   titleSpecialColumnselectorrT   listkeys
dimensionsrU   rz   r:   rD   cloner   r   )r}   r_   rI   re   r   r   r   Z	kdim_listr   categoryZagg_namerZ   rg   Z	vdim_nameZ	agg_labelrG   )r   rM   rJ   _get_agg_params   sP    


z$AggregationOperation._get_agg_params)T)rX   
__module____qualname____doc__paramClassSelectorrO   	Reductionr   rR   r:   
aggregatorrB   rC   r;   r<   r   Stringr   r9   r=   r>   r?   r@   rA   rD   rS   classmethodrd   r   r   rG   rG   rG   rJ   r3   L   s2   %r3   c                   @   s   e Zd ZejddddZdS )LineAggregationOperationN)r   Na  
        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.r5   r   r6   )rX   r   r   r   Number
line_widthrG   rG   rG   rJ   r      s   r   c                   @   s0   e Zd ZdZed	ddZd
ddZdd ZdS )	aggregatea?  
    aggregate implements 2D binning for any valid HoloViews Element
    type using datashader. I.e., this operation turns a HoloViews
    Element or overlay of Elements into an Image or an overlay of
    Images by rasterizing it. This allows quickly aggregating large
    datasets computing a fixed-sized representation independent
    of the original dataset size.

    By default it will simply count the number of values in each bin
    but other aggregators can be supplied implementing mean, max, min
    and other reduction operations.

    The bins of the aggregate are defined by the width and height and
    the x_range and y_range. If x_sampling or y_sampling are supplied
    the operation will ensure that a bin is no smaller than the minimum
    sampling distance by reducing the width and height when zoomed in
    beyond the minimum sampling distance.

    By default, the PlotSize stream is applied when this operation
    is used dynamically, which means that the height and width
    will automatically be set to match the inner dimensions of
    the linked plot.
    Nc              
      sX  g }t |tr|j}t|j}t|j}| dd }t |trdd}|jddD ]}|	| qRnt |t
rd}	|j D ]b\}
}| |\}}}	}||f}t|	 t |trֈ jf i tt|dd|
 |	  q~|	du rd}n||	j7 }|	j}n0t |tr2t |trdnd}|	t| |du sJt|dkrNd	S |\}}t|d
kr|dkr|d dd
 }t |tjr| }| tjfjd
  jdddf< fdd|D dd }tdd |D rt | ndd |D }t! | n$|r|d nt!jg |j"|j"gd |r^ | j#j"dkr^ | $d |< t  tjptt%& t' fdd||fD r   ||fD ]} |j" }st|rt |j(d t)rt*|d}nP|j#j+dkr|$d}n6|j#tj,krt-d|j" dn|j#j+dkrnqt.| |j"< q||t/ ||d|fS )z{
        Reduces any Overlay or NdOverlay of Elements into a single
        xarray Dataset that can be aggregated.
        Nr
   line	dataframer   r   Tpoints)NNNNr0   r   c                    s   g | ]}| fD ]}|qqS rG   rG   )rn   rx   elem)emptyrG   rJ   r   4  rL   z*aggregate.get_agg_data.<locals>.<listcomp>c                 s   s   | ]}t |tjV  qd S rF   )rQ   dd	DataFrame)rn   pathrG   rG   rJ   r   5  rL   z)aggregate.get_agg_data.<locals>.<genexpr>c                 S   s$   g | ]}t |tjr| n|qS rG   )rQ   r   r   compute)rn   rx   rG   rG   rJ   r   8  rL   columnsr   c                 3   sJ   | ]B} r0t  |j r0t |j jd  tp@ |j jjdv V  qdS )r   )MuN)lenr[   rQ   valuesr   dtypekindr   )df	is_customrG   rJ   r   @  s   *nsr   datetime64[ns]zDtype of uint64 for column z is not supported.r   r\   rZ   )0rQ   r!   Z	edgepathsr   r\   rZ   r   r$   splitappendr   dataitemsget_agg_datar   	as_dframer   Zassignr   zipr   r    r   r   r   r   copyru   rw   shapeilocallconcatpdr[   r   astyper   appliesr9   r   r   r   r   Zuint64	TypeErrorr   r   )r^   objr   pathsr\   rZ   rg   glyphrx   r_   r   rq   rI   re   r   r   r   rG   )r   r   r   rJ   r     s|    





"

 $

"zaggregate.get_agg_datac           !   
      s  |  || jj}t| jdd }t|dr0|j}nt|tjrB|j	nd }t
j||| jjdrtdd | j  D fddidd | j D }t
|fi |S |j| jv r| j|j \}}}	}
n| ||\}}}	}
| jjr|||	|
f| j|j< | |||\\}}\}}\}}\}}| ||||||\\\}}\}}\}}| ||||||||f}|d u s|d u s|d	ks|d	kr| j||||||||fi |S t|	d
d turt|	st|tjrd	ntj}tjt ||f||j!|j!g|j!||j!|id}| jj"|fi |S tj#||||d}i }| jjr`|
dkr`t$t%dkr`| jj|d< t&'|	}t||
}|rt|d t(t)fr|d g|d< tj*f i t)|d d	 |dt+|i}| ,||||||}g |d d  fdd|D }g |d ||d< n| ,||||||}d|j-v rNd|j-v rN|.||d}|dkrn||j! /d||j!< |dkr||j! /d||j!< t|tj0s|j1dkrt$t%dkr|n
|||j2f} | jj"| fi |S t3|j-|j	 j2|d< t4|fi |S d S )Nr   r   r   c                 S   s   i | ]\}}|d kr||qS r[   rG   rn   rx   ro   rG   rG   rJ   rr   ^  rL   z&aggregate._process.<locals>.<dictcomp>dynamicFc                 S   s   i | ]\}}|d vr||qS ))r[   r   rG   r   rG   rG   rJ   rr   _  s   r   	interfacerf   Z
plot_widthZplot_heightx_rangey_ranger   0.14.0r   rZ   indexc                    s   g | ]}| vr|qS rG   rG   rn   s_ignorerG   rJ   r     rL   z&aggregate._process.<locals>.<listcomp>x_axisy_axis)r   r   datetimer   r
   0.5.0)5rd   rx   r   rW   r   r   rQ   rz   rD   rM   overlay_aggregater   r   r   r   r   r   _plot_id_precomputedr   
precompute_get_sampling_dt_transformr   r   r   r   r:   ru   rw   rs   rt   rv   r[   ry   Canvas
ds_versionr   r   r   r   rR   r   rP   _apply_datashaderrh   renamer   r   ndimr   r   r#   )!r}   r_   r   r   Zsel_fnr   r   rI   re   r   r   r   r   r   r   r~   r   xtypeytypex0x1y0y1Z	empty_valr   cvs
agg_kwargsdfdatacvs_fnZsum_aggr`   Z	sel_vdimseldatarG   r   rJ   _processT  st    
&(( "

*

zaggregate._processc                 C   sz  t  : t jddtd |||j|j|fi |}W d    n1 sH0    Y  tont|tjont|j	t
j}t|tjod|v }	|s|	rv|r|j}
|jdd}n|jj}
|
dk}|jD ]}||jv rq|| j|
 }|jjdkrtj||< nnt|jtjr| }d||< nL|jjd	kr,d||< n4|jjd
krJtd||< n|tj}tj||< |j|jf|f||< q|S )Nignorezcasting datetime64)actionmessager   r   r   r   f-Or   ZNaT)warningscatch_warningsfilterwarningsFutureWarningr[   rN   rQ   rz   rP   rM   rO   r   r   r   Z
to_datasetr   r   rh   r   r   r   ru   rw   r   ZCategoricalDtypeZto_numpyZ
datetime64r   float64)r}   r
  r  r   r	  rI   re   r`   Zis_where_indexZis_summary_indexr   Zneg1r   valrG   rG   rJ   r     s>    
8





zaggregate._apply_datashader)N)N)rX   r   r   r   r   r   r  r   rG   rG   rG   rJ   r      s
   M
Gr   c                   @   s(   e Zd ZdZedddZdddZdS )	r   a  
    Optimized aggregation for NdOverlay objects by aggregating each
    Element in an NdOverlay individually avoiding having to concatenate
    items in the NdOverlay. Works by summing sum and count aggregates and
    applying appropriate masking for NaN values. Mean aggregation
    is also supported by dividing sum and count aggregates. count_cat
    aggregates are grouped by the categorical dimension and a separate
    aggregate for each category is generated.
    Nc                 C   sd   t |tob|jtus|d u obt |tjtjtjtjfrL|j	d u pb|j	|j
vpbt |tjob|j	|j
v S rF   )rQ   r   r]   r    rz   r:   r?   r>   r9   rM   r\   rD   )r^   r_   r   r   rG   rG   rJ   r     s    
zoverlay_aggregate.appliesc           (      C   s  |  || jj}| j||| jjds,td|j dd }t|}|dkr^|d d  }}n|\}}| 	||||}|\\}	}
\}}\}}\}}| 
|	|
||||\\\}}\}}}tdd t| j fi | j D ||f||fd}||||f}t|tjr|td	t d
 tjf i |}|jdkr@|}n|j|jgttd}g }| D ]l\}}|dks||dkr| |||||||t }|||f n"||}|||j|j|df q`||S |jpd}t|tjr.tjf i t|t|d}tjf i t|t d}ntjf i |}d }t|tj} t|tj }!d\}}"}#|D ]}$|!|$d }%| rt"#|%j| j}&|%j$d|%_|r|!|$d }'|d u r|%}| r|&}#|r |'}"nL|!r| j|%jO  _n| j|%j7  _| r
|#|&M }#|rh|" j|'j7  _qh|"d ur|"jj%d|jidd t"j&ddd  | j|"j  _W d    n1 sz0    Y  | rt"j'|j| j|#< |j|dS )Nr   z`overlay_aggregate only handles aggregation of NdOverlay types with count, sum or mean reduction.r   r
   r0   c                 S   s    i | ]\}}|t jv r||qS rG   )r   r   rn   kro   rG   rG   rJ   rr     s   
z.overlay_aggregate._process.<locals>.<dictcomp>)r   r   F)r   r   )Zcontainer_typeZ
group_typer   r   )r   )NNNT)Zinplacer  )divideinvalid)(rd   rx   r   r   r   rU   r<   r   r   r   r   r   r   r   r   rQ   rz   rD   updater:   r   instancendimsgroupbyrM   r   r   r   r   r   r>   r?   r9   Zprocess_elementru   isnanZfillnar   Zerrstaterw   )(r}   r_   r   r   rg   r!  rI   re   infor   r   r   r   r~   r   r  r  r  r  r  r  r   Z
agg_paramsZbboxZagg_fn1Zgroupedgroupsr  rq   r`   rM   Zagg_fn2Zis_sumZis_anyZagg2maskro   Znew_aggZnew_maskZnew_agg2rG   rG   rJ   r    s    $




0zoverlay_aggregate._process)N)N)rX   r   r   r   r   r   r  rG   rG   rG   rJ   r     s   
r   c                   @   s   e Zd ZdZdddZdS )area_aggregatez
    Aggregates Area elements by filling the area between zero and
    the y-values if only one value dimension is defined and the area
    between the curves if two are provided.
    Nc              
   C   s  |  d d \}}| || jj}d }| jjs~|d\}}t|jdkr\|d\}}	n|dkrjd}n|dkrvd}||f}t|jdkr|jd jnd }
| j	|||d|d}|\\}}\}}\}}\}}| 
||||||\\\}}\}}\}}t|}tj||||d}| ||||||||f}|dks>|dkr^| j||||||||fi |S |j||j|j|d|
d}|dkr||j d||j< | jj|fi |S )	Nr
   r0   r   r  r5   r   )axisy_stackr   r   )r   rd   rx   r   r   ranger   rZ   r[   r   r   r   r   rz   r   r   r   arear   ry   )r}   r_   r   rI   re   r   r5   r  r  r   Zystackr$  r   r   r   r   r~   r   r  r  r  r  r   r  r   r`   rG   rG   rJ   r  <  s6    (
 
zarea_aggregate._process)NrX   r   r   r   r  rG   rG   rG   rJ   r'  5  s   r'  c                       s"   e Zd ZdZd fdd	Z  ZS )spread_aggregatezd
    Aggregates Spread elements by filling the area between the lower
    and upper error band.
    Nc           
         s   |  d d \}}t|}||ju r0| }t|jdkrL|jdd n|jdd d \}}||j }|||j  ||j< |||j  |d< |j||dg|jdd   t	d}	t
 j|	d dS )Nr
   r0      Z_lower)rZ   new_typer   )r   r   r   r   r   r   rZ   r[   r   r   superr  )
r}   r_   r   rI   re   r   posnegZyvalsr,  	__class__rG   rJ   r  h  s    

2
"zspread_aggregate._process)N)rX   r   r   r   r  __classcell__rG   rG   r4  rJ   r.  b  s   r.  c                   @   s8   e Zd ZdZejddddZejdddZdd	d
ZdS )spikes_aggregatez
    Aggregates Spikes elements by drawing individual line segments
    over the entire y_range if no value dimension is defined and
    between zero and the y-value if one is defined.
    NTzf
      If numeric, specifies the length of each spike, overriding the
      vdims values (if present).r7   g        z1
      The offset of the lower end of each spike.r5   r6   c              
   C   s  |  || jj}|jd d  }}| jjd u r0dn| jj}|jr| jjd u r| d d \}}|j|jd}| jjs|	d\}}	|dkrd|	f}
q|	dkr|df}
q||	f}
qd }
n6|jd d  }}t
| jjt
| jj| f}
d|ji}| j|||d|
d}|\\}}\}}\}}\}}| ||||||\\\}}\}}	\}}|jd u rTg n|jg}|d u r||g|  }td}t
| jj|d	< t
| jj| |d
< d	d
g}| jjsd}n8|||g|  }td|j|j |d	< d	|jg}|dkrt||j d||j< | ||||||||	f}|dksH|dkrh| j||||||||fi |S tj||||d}i }ttdkr| jj|d< dd | D }|j ||j||fddi|!|}|dkr||j d||j< | jj"|fi |S )Nr         ?r
   rI   re   r0   rI   r(  re   r  r  r   r   r   r   r   c                 S   s   i | ]\}}||kr||qS rG   rG   r  rG   rG   rJ   rr     rL   z-spikes_aggregate._process.<locals>.<dictcomp>r)  )#rd   rx   r   r\   spike_lengthrZ   r   r[   r   r+  floatoffsetr   r   rM   dframer   r   expandru   arraydtypesr   r   r   r   rz   r   r   r   r   r   r   r   ry   )r}   r_   r   r   rI   re   r;  rename_dictr  r  r5   r$  r   r   r   r   r~   r   r  r  r  r  Z
value_colsr   Zyaggr   r  r	  r`   rG   rG   rJ   r    sb    




(


 $
zspikes_aggregate._process)N)	rX   r   r   r   r   r   r;  r=  r  rG   rG   rG   rJ   r7  w  s   r7  c                   @   s&   e Zd ZdZdZdd ZdddZdS )	geom_aggregatez5
    Baseclass for aggregation of Geom elements.
    Tc                 C   s   t d S rF   NotImplementedError)r}   r  r   r  r  r  r  r`   rG   rG   rJ   
_aggregate  s    zgeom_aggregate._aggregateNc              
   C   s  |  || jj}|j\}}}}| j|||g||gdd}|\\}	}
\}}\}}\}}| |	|
||||\\\}}\}}\}}|j|}|dks|dkr| }|dkrt	||j
 d||j
< t	||j
 d||j
< |dkrt	||j
 d||j
< t	||j
 d||j
< t|tjrR||j jj
dkrR||j d||j< | ||||||||f}|dks|dkr| j||||||||fi |S tj|||	|
d}| |||j
|j
|j
|j
|}t|jd d d d d	 \}}|dkr|| d||< |dkr(|| d||< ||g|d
< |jdkrrttdkrR|n
|||jf}| jj|fi |S i }|j|j jD ]R}|jf i |j|i}ttdkr|n
|||jf}| jj|fi |||< qt|||jgdS d S )Nr0   )r  r   r   r   r   r   r
   r   r\   r   r   ) rd   rx   r   r\   r   r   r   r   r   r   r[   r   rQ   rz   rD   rM   r   r   r   r   rF  r   rg   r  r   r   r   ry   rh   selr   r|   )r}   r_   r   r   Zx0dZy0dZx1dZy1dr$  r   r   r   r   r~   r   r  r  r  r  r  r  r   r   r  r`   xdimydimr  layersccaggrG   rG   rJ   r    sL    (
"  

zgeom_aggregate._process)N)rX   r   r   r   Z_geom_aggregate__abstractrF  r  rG   rG   rG   rJ   rC    s   rC  c                   @   s   e Zd ZdZdd ZdS )segments_aggregatez'
    Aggregates Segments elements.
    c           	      C   s@   i }t tdkr| jj|d< |j|||g||g|fddi|S )Nr   r   r)  r0   )r   r   rx   r   r   )	r}   r  r   r  r  r  r  r   r	  rG   rG   rJ   rF    s    zsegments_aggregate._aggregateNrX   r   r   r   rF  rG   rG   rG   rJ   rM    s   rM  c                   @   s   e Zd ZdZdd ZdS )rectangle_aggregatez(
    Aggregates Rectangle elements.
    c                 C   s   |j |||g|||ddS )Nr0   )rI   re   r*  r`   r)  )r,  )r}   r  r   r  r  r  r  r   rG   rG   rJ   rF    s    zrectangle_aggregate._aggregateNrN  rG   rG   rG   rJ   rO    s   rO  c                   @   sn   e Zd ZdZeje ejej	e
fdZejdddZejdg ddd	Zejdd
dZdd ZdddZdS )regrida  
    regrid allows resampling a HoloViews Image type using specified
    up- and downsampling functions defined using the aggregator and
    interpolation parameters respectively. By default upsampling is
    disabled to avoid unnecessarily upscaling an image that has to be
    sent to the browser. Also disables expanding the image beyond its
    original bounds avoiding unnecessarily padding the output array
    with NaN values.
    r5   r4   Fa  
       Whether the x_range and y_range should be allowed to expand
       beyond the extent of the data.  Setting this value to True is
       useful for the case where you want to ensure a certain size of
       output grid, e.g. if you are doing masking or other arithmetic
       on the grids.  A value of False ensures that the grid is only
       just as large as it needs to be to contain the data, which will
       be faster and use less memory if the resulting aggregate is
       being overlaid on a much larger background.r8  nearest)linearrR  bilinearNFz
        Interpolation methodr5   objectsr6   a  
        Whether to allow upsampling if the source array is smaller
        than the requested array. Setting this value to True will
        enable upsampling using the interpolation method, when the
        requested width and height are larger than what is available
        on the source grid. If upsampling is disabled (the default)
        the width and height are clipped to what is available on the
        source array.c                    s   j \}}|j|jg}t fdd|D }|rR|jd|d f|jd|d fi}	n|j|d |j|d i}	i }
t jD ]\}} jtu r j r jd|f }n j|j }d||fv r|	 }||j
kr|s|j| }nH|r j|dd	}tj||	d
dgd}n j|dd	}tj||	|d}|dkrPdd ||j jD ||j< |dkrvdd ||j jD ||j< ||
|j< qx|
S )Nc                 3   s   | ]} j  |V  qd S rF   )r   	irregularr   r_   rG   rJ   r   @  s   z&regrid._get_xarrays.<locals>.<genexpr>)re   rI   r   r0   .r   FZflatre   rI   rh   rg   c                 S   s   g | ]}t |d qS r   r   rm   rG   rG   rJ   r   Z  rL   z'regrid._get_xarrays.<locals>.<listcomp>c                 S   s   g | ]}t |d qS r[  r\  rm   rG   rG   rJ   r   \  rL   )r\   r[   r9   	enumeraterZ   r   r   packedr   r   rg   	transposer{   rs   rt   r   )r}   r_   rh   r  r  rI   re   rg   rW  Z
coord_dictarraysivdxarrarrrG   rX  rJ   _get_xarrays=  s>    



zregrid._get_xarraysNc           &         s  t tdkrtd j\}}t fdd||fD }|  ||}|\\}}\}	}
\}}\}}|| \}}\}}|| ||  }}| jjpd }|dkrd}| jjs:|d u s:| jj	d u r: 
d 
d \}}\}}t|tr t|d	t|d	 }}t|tr"t|d	t|d	 }}|| ||  }}t|r~|dkr~|dkr~ttt|| t|d  |gdg}nd}t|r|dkr|dkrttt|| t|d  |gdg}nd}|rt|| nd}|rt|| nd}t||d
  ||d
  |t||d
  ||d
  | }	}
| |||	|
||\\\}}\}}\}	}
t||||fd}|dks|dkr|dkrd|d< |dkrd|d<  j|	|
t||fffi |S tj||||d}i } |  |||}!| j | jjdd}"|! D ]b\}#}$|j |$||"d}%|dkrH|%|j! "d|%|j!< |dkrh|%|j! "d|%|j!< |%| |#< qt#$| }  j| fddg j% i|S )Nr   z+regrid operation requires datashader>=0.6.0c                 3   s   | ]} j |d dV  qdS Frk   Nr{   r   rX  rG   rJ   r   g  rL   z"regrid._process.<locals>.<genexpr>rT  rS  r   r0   r   g       @r  ri   rj   r   F)ra   )Zupsample_methodZdownsample_methodr   r   r   r   )&r   r   RuntimeErrorr\   tupler   rx   interpolationupsampletargetr+  rQ   r   r   ru   isfiniterC   rB   intr   r<  linspacer   r   r   zerosrz   r   re  rd   r   r   rasterr[   r   rs   r   r   )&r}   r_   r   rI   re   rh   r$  r   r   r   r   r~   r   r  r  ZxstartZxendZystartZyendZxspanZyspaninterpr  r  r  r  ZexspanZeyspanZxunitZyunitr   r  Z	regriddedr`  r   rb  rc  ZrarrayrG   rX  rJ   r  a  sj    
" * *(

"


zregrid._process)N)rX   r   r   r   r   r   rO   r>   r   r   rR   r   Booleanr?  ObjectSelectorrj  rk  re  r  rG   rG   rG   rJ   rP    s   


	$rP  c                       sB   e Zd ZdZeje ejej	e
fdZed fdd	Z  ZS )contours_rasterizez
    Rasterizes the Contours element by weighting the aggregation by
    the iso-contour levels if a value dimension is defined, otherwise
    default to any aggregator.
    rQ  Tc                    s:   |j s*|jd u r*t|tjtjfs*t S t |||S rF   )	rZ   rM   rQ   rO   r:   r9   rz   r1  rd   r^   r_   r`   ra   r4  rG   rJ   rd     s    "z"contours_rasterize._get_aggregator)T)rX   r   r   r   r   r   rO   r>   r   r   rR   r   r   rd   r6  rG   rG   r4  rJ   ru    s   
ru  c                   @   sZ   e Zd ZdZeje ejej	e
fdZejdg dddZdd Zd	d
 ZdddZdS )trimesh_rasterizez
    Rasterize the TriMesh element using the supplied aggregator. If
    the TriMesh nodes or edges define a value dimension, will plot
    filled and shaded polygons; otherwise returns a wiremesh of the
    data.
    rQ  rT  )rT  rS  NFz@
        The interpolation method to apply during rasterization.rU  c                    s  ddl m} |jr8t|dd |jjvr8g d}ddg}n"|jjrRg d}g d}ntd|jj|jjjg}t|d	hkr|	 |j	   |j
 fd
d|D  }|jj
fdd|D  }nXd	|v r|d d	krd\}	}
nd\}	}
| jd|	 d|
 d ||}|j|}t|jd d |jD ](\}}|jdkr0|| d||< q0|||}t|drx| }|||dS )Nr   )meshrM   r   r0   r
   r/  r0   r   r0   r
   )r   r0   r/  z-Cannot shade TriMesh without value dimension.daskc                    s   g | ]} | j qS rG   r   )rn   sd)rg   rG   rJ   r     rL   z1trimesh_rasterize._precompute.<locals>.<listcomp>c                    s   g | ]} | j qS rG   r   rn   rb  )	node_dimsrG   rJ   r     rL   )	simplexesvertices)r  r  zTriMesh z% were provided as dask DataFrame but zq were not. Datashader will not use dask to parallelize rasterization unless both are provided as dask DataFrames.r/  ra  rn  persist)rx  	simplicesr  )Zdatashader.utilsrx  rZ   rW   rY   rU   r   r   setr   r   r   warningr>  r   r   rA  r   r   r   r  )r}   r_   r`   rx  Zsimplex_dimsZ	vert_dimsZ	datatypesr  Zvertsrx   nrK  r   rG   )rg   r~  rJ   _precompute  s@    





ztrimesh_rasterize._precomputec                 C   s6   t |dr|jj}nt|}t|ddgd|_d|iS )N
_wireframer   r{  r   segments)r   r  r   r.   r   )r}   r_   r`   r  rG   rG   rJ   _precompute_wireframe  s
    

z'trimesh_rasterize._precompute_wireframeNc                 C   s  t |tr |jjd d \}}n
|j\}}| |||}|\\}}\}}	\}
}\}}| jj}| jjpfd }| jj}|dkr|d}d}|j	st |tr|jj	st
tdkrt |tjs|dkrt nt | j_t| ||S |st |tjtjfs|dv s|j	sF|jj	sFd}d}t |tjtjfr<| || jj}nt }n"t|d	d d u rh| || jj}|j| jv r| j|j }n |r| ||}n| ||}|d
 |d
 |d |d f}| |||||}|
d
ks|d
kr*|
d
krd|d< |d
kr
d|d< t||	t||
fffi |S |r:|d }n|d }|d }|d }|rd|j|i| _tj|
|||d}|rdd td|j|jfD }|j|g dg dd|d|}n t | jj}|j!|||||d}t|fi |S )Nr
   rS  rT  Fz0.6.9r9   )r9   r:   TrM   r   r0   ri   rj   r  r  r  rx  r   c                 S   s   i | ]\}}||kr||qS rG   rG   r  rG   rG   rJ   rr   -  rL   z.trimesh_rasterize._process.<locals>.<dictcomp>xy)r  r  Zx2r  )r  r  y2r  )rI   re   r)  r`   )r`   rr  rx  )"rQ   r-   rY   r\   r   rx   r   rj  r   rZ   r   r   rz   r9   r:   r   r  rd   rW   r   r   r  r  r   r"   ru   rp  r   r   r[   r   r   booltrimesh)r}   r_   r   rI   re   r$  r   r   r   r   r~   r   r  r  r`   rr  r   Z	wireframeZprecomputedr   r   r  r  Zptsrx  r  rB  ZinterpolaterG   rG   rJ   r    sz    

$(
 

ztrimesh_rasterize._process)N)rX   r   r   r   r   r   rO   r>   r   r   rR   r   rt  rj  r  r  r  rG   rG   rG   rJ   rw    s   
(rw  c                       s.   e Zd ZdZ fddZd fdd	Z  ZS )quadmesh_rasterizez
    Rasterize the QuadMesh element using the supplied aggregator.
    Simply converts to a TriMesh and lets trimesh_rasterize
    handle the actual rasterization.
    c                    s"   t tdkrt | |S d S )N0.7.0)r   r   r1  r  r  )r}   r_   r`   r4  rG   rJ   r  @  s    zquadmesh_rasterize._precomputeNc              	      s  t tdkrt ||S |jjdkr4|jdgd}|j}|j\}}| 	|| j
j}| |||}|\\}}	\}
}\}}\}}|dkr||j dd||j< |dkr||j dd||j< | ||	|
|||\\\}}\}}\}
}tt|dg||||fd}|dks|dkr>| j||||||
||fi |S tj||||	d	}t|d
|jd j}||| |j|j|}t|jd d d d d \}}|dkr|| d||< |dkr|| d||< t|fi |S )Nr  r   r   r   r   int64)r   r   r   r   rM   r
   r   )r   r   r1  r  r   r   r   r   r\   rd   rx   r   r   r[   r   r   r   r   r   rz   r   rW   rZ   Zquadmeshr   rg   r"   )r}   r_   r   r   rI   re   r   r$  r   r   r   r   r~   r   r  r  r  r  r  r  r   r  vdimr`   rH  rI  r4  rG   rJ   r  D  s@    

  

zquadmesh_rasterize._process)N)rX   r   r   r   r  r  r6  rG   rG   r4  rJ   r  9  s   r  c                   @   s   e Zd ZdZejddddZejee	e
fddZejee	e
fddZejd	ee	fd
dZejddddZejddddZejdddZedd Zedd Zedd Zedd Zedd Zd!dd ZdS )"shadea  
    shade applies a normalization function followed by colormapping to
    an Image or NdOverlay of Images, returning an RGB Element.
    The data must be in the form of a 2D or 3D DataArray, but NdOverlays
    of 2D Images will be automatically converted to a 3D array.

    In the 2D case data is normalized and colormapped, while a 3D
    array representing categorical aggregates will be supplied a color
    key for each category. The colormap (cmap) for the 2D case may be
    supplied as an Iterable or a Callable.
       )r   r  z
        Value between 0 - 255 representing the alpha value to use for
        colormapped pixels that contain data (i.e. non-NaN values).
        Regardless of this value, ``NaN`` values are set to be fully
        transparent when doing colormapping.r   aS  
        Iterable or callable which returns colors as hex colors
        or web color names (as defined by datashader), to be used
        for the colormap of single-layer datashader output.
        Callable type must allow mapping colors between 0 and 1.
        The default value of None reverts to Datashader's default
        colormap.)r4   r6   z
        Iterable or callable that returns colors as hex colors, to
        be used for the color key of categorical datashader output.
        Callable type must allow mapping colors for supplied values
        between 0 and 1.eq_histz
        The normalization operation applied before colormapping.
        Valid options include 'linear', 'log', 'eq_hist', 'cbrt',
        and any valid transfer function that accepts data, mask, nbins
        arguments.)r5   r4   r6   Nr
   zz
        Min and max data values to use for colormap interpolation, when
        wishing to override autoranging.
        )r5   lengthr6   (   a   
        The minimum alpha value to use for non-empty pixels when doing
        colormapping, in [0, 255].  Use a higher value to avoid
        undersaturation, i.e. poorly visible low-value datapoints, at
        the expense of the overall dynamic range..Ta  
        If ``cnorm='eq_hist`` and there are only a few discrete values,
        then ``rescale_discrete_levels=True`` (the default) decreases
        the lower limit of the autoranged span so that the values are
        rendering towards the (more visible) top of the ``cmap`` range,
        thus avoiding washout of the lower values.  Has no effect if
        ``cnorm!=`eq_hist``. Set this value to False if you need to
        match historical unscaled behavior, prior to HoloViews 1.14.4.r8  c                 C   s~   t |tstdtdd | D tj| |j	d j
d}tt|j|jj|j	|jj	 d}t| fddgi|S )	zc
        Concatenates an NdOverlay of Image types into a single 3D
        xarray Dataset.
        z#Only NdOverlays can be concatenatedc                 S   s   g | ]}|j  qS rG   )r   r_  rm   rG   rG   rJ   r     rL   z%shade.concatenate.<locals>.<listcomp>r   r   )rZ   r\   r   r   )rQ   r   rU   rs   r   r   r   Indexr   r\   r[   r   r   r<   rZ   r   r_  )r^   overlayrc  r   rG   rG   rJ   concatenate  s    

zshade.concatenatec                 C   s    t |jt jd|jd S )z<
        Cast uint32 RGB image to 4 uint8 channels.
        r      )ru   Zflipudviewuint8reshaper   )r^   imgrG   rG   rJ   uint32_to_uint8  s    zshade.uint32_to_uint8c                 C   sR   |j jtjd|jd }tt|j	 dg dfg }t
j|||jd dS )zC
        Cast uint32 xarray DataArray to 4 uint8 channels.
        r  r  bandry  )r  rZ  )r   r  ru   r  r  r   r   r   rh   r   rs   rt   rg   )r^   r  Z	new_arrayrh   rG   rG   rJ   uint32_to_uint8_xr  s     zshade.uint32_to_uint8_xrc                 C   s,   t |dkr|dd }djdd |D  S )z.
        Convert RGB(A) tuple to hex.
        r/  Nr   z#{:02x}{:02x}{:02x}c                 s   s   | ]}t |d  V  qdS )r  N)rn  rm   rG   rG   rJ   r     rL   z shade.rgb2hex.<locals>.<genexpr>)r   r   )r^   rgbrG   rG   rJ   rgb2hex  s    zshade.rgb2hexc              
      s   t  jtr S t fdd jD }t j}dd  jD  jd d < z.|t fdd jD 7 }W | jd d < n| jd d < 0 dd  jD } j|dg|  j	 j
 jdS )	Nc                 3   s   | ]} j |d dV  qdS rf  rg  r   rX  rG   rJ   r     s   z"shade.to_xarray.<locals>.<genexpr>c                 S   s   g | ]}|j d dqS )Nr   )r   r}  rG   rG   rJ   r     rL   z#shade.to_xarray.<locals>.<listcomp>c                 3   s   | ]} j |d dV  qdS )FrY  Nrg  r}  rX  rG   rJ   r     s   c                 S   s   g | ]}|d kr|qS )r   rG   )rn   dtrG   rG   rJ   r     rL   r   )r   r   ri   rj   )
issubclassr   r   ri  r\   r   rZ   r   r   r   ri   rj   )r^   r_   r   rZ   rA  rG   rX  rJ   	to_xarray  s$    
 zshade.to_xarrayc                    s  |  jt}t|tr<|jj}|jj}|jj} 	|}n2t|t
r\| ttj tgS |j}|j}|j}|j}t|tr|j}|j}t|dr|d}|jg dd |D dR  }n|jd j}|j| }t jj jj jjd}	ttdkr jj|	d	< |jd
ks t|trt|tr2|jn|jdd  }|j d }
 jj!sVn|t jj!trt jj!|	d< n^t jj!t"rdd t#t$|
 jj!D |	d< n, fddt%&dd|
D }t  j'||	d< n jj(snt jj(t)r fddt%&dddD }t  j'||	d< nft jj(t*rx jj(+dsL jj(t,v rZ jj(|	d< nd
dl-m.} | jj(|	d< n jj(|	d<  jj/r jj/|	d< n*ttdkrƈ jjdkr|$||	d< tt0|||t1jd d  ||d}t23  t24dd t%5|j6 r|d d
 \}}t%j7|jj d d
 d t%j8d}|j|jj9|j |j|jj9|j dg di}t:j;|||j|jdfd}t1|fi |W  d    S t<j|fi |	}W d    n1 s0    Y  t1 =|fi |S ) Nto_arrayzc                 S   s   g | ]
}|j qS rG   r   )rn   ZkdimrG   rG   rJ   r      rL   z"shade._process.<locals>.<listcomp>.r   )how	min_alphaalphar   rescale_discrete_levelsr
   r0   r   	color_keyc                 S   s   g | ]\}}|qS rG   rG   )rn   r   rK  rG   rG   rJ   r     rL   c                    s   g | ]} j |qS rG   )rx   r  r   r}   rG   rJ   r     rL   c                    s   g | ]} j |qS rG   )rx   cmapr   r  rG   rJ   r     rL      r  #)process_cmapspanr   r  )r\   r   rZ   ri   rj   r  z(invalid value encountered in true_divider  r  r  ry  rZ  )>mapr  r"   rQ   r   r<   r   ri   rj   r  r   r   r  r  r   r\   r#   rZ   r   r   r  r_  r[   r   rx   cnormr  r  r   r   r  r!  r   r  r   r   r+  ru   ro  r  r  r   rR   
startswithr   Zplotting.utilr  climsr   r   r  r  r  r#  r   rp  r  rh   rs   rt   tfr  )r}   r_   r   r   ri   rj   r\   r  r@  Z
shade_opts
categoriescolorsr  r   ZxdZydrd  rh   r  rG   r  rJ   r    s    




 
 





 2zshade._process)N)rX   r   r   r   r   Integerr  r   r   r   r   r  r  rR   r  NumericTupler  r   r  rs  r  r   r  r  r  r  r  r  rG   rG   rG   rJ   r  n  s,   	


	
	
r  c                       sL   e Zd ZdZeje ejej	e
fdZed	 fdd	Zd
ddZ  ZS )geometry_rasterizezD
    Rasterizes geometries by converting them to spatialpandas.
    rQ  Tc                    sD   |j s4t|ts4|jd u r4t|tjtjfs4t S t 	|||S rF   )
rZ   rQ   rR   rM   rO   r:   r9   rz   r1  rd   rv  r4  rG   rJ   rd   H  s    z"geometry_rasterize._get_aggregatorNc              
   C   s  |  || jj}|j\}}| |||}|\\}}\}	}
\}}\}}|\}}|\}}| ||||||||f}|dks~|dkr| j||||||	|
|fi |S tj||||d}|j	| j
v r| j
|j	 \}}n,d|jjvr|jdgd}|j}|j|}| jjr||f| j
|j	< t|tjrL||j jjdkrL||j d||j< t||d}t|trx|j|fi |}nbt|tr| jjrttdkr| jj|d< |j|fi |}nt|tr|j |fi |}d	d
 t!d|j|jfD }|"|}|j#dkr | jj$|fi |S i }|j%|j jD ]4}|j&f i |j|i}| jj$|fi |||< q2t'||(|jgdS d S )Nr   r   spatialpandasr   r   )geometryr`   r   r   c                 S   s   i | ]\}}||kr||qS rG   rG   r  rG   rG   rJ   rr   v  rL   z/geometry_rasterize._process.<locals>.<dictcomp>r  r
   r   ))rd   rx   r   r\   r   r   r   rz   r   r   r   r   r   r   r   
geo_columnr   rQ   rD   rM   r   r[   r   r   r&   polygonsr$   r   r   r   r   r%   r   r   r   r  ry   rh   rG  r   r|   )r}   r_   r   r   rH  rI  r$  r   r   r   r   r~   r   r  r  r  r  r  r  r   r  r   r   r	  r`   rB  rJ  rK  rL  rG   rG   rJ   r  O  sP    
 
"
zgeometry_rasterize._process)T)N)rX   r   r   r   r   r   rO   r>   r   r   rR   r   r   rd   r  r6  rG   rG   r4  rJ   r  @  s   
r  c                       s   e Zd ZdZejejeje	fddZ
ejdg dddZeefeefdd efeefeefd	d efeefeefeefeefeefe e!fe"efe#efe$efe%efe&efe'd
e(fgZ)e* Z+i Z,e- fddZ.dddZ/  Z0S )	rasterizea  
    Rasterize is a high-level operation that will rasterize any
    Element or combination of Elements, aggregating them with the supplied
    aggregator and interpolation method.

    The default aggregation method depends on the type of Element but
    usually defaults to the count of samples in each bin. Other
    aggregators can be supplied implementing mean, max, min and other
    reduction operations.

    The bins of the aggregate are defined by the width and height and
    the x_range and y_range. If x_sampling or y_sampling are supplied
    the operation will ensure that a bin is no smaller than the minimum
    sampling distance by reducing the width and height when zoomed in
    beyond the minimum sampling distance.

    By default, the PlotSize and RangeXY streams are applied when this
    operation is used dynamically, which means that the width, height,
    x_range and y_range will automatically be set to match the inner
    dimensions of the linked plot and the ranges of the axes.
    r5   )r4   r5   )r5   rS  rR  rT  NFzh
        The interpolation method to apply during rasterization.
        Default depends on element typerU  c                 C   s   t | ttfod| jjv S )Nr  )rQ   r$   r%   r   r   rH   rG   rG   rJ   rK     s   zrasterize.<lambda>c                 C   s   t | tot| jttttfS rF   )rQ   r   r  r]   r)   r%   r    r$   rH   rG   rG   rJ   rK     s   
Nc                    s`   t |t j  fdd| D }t jf i |}t ||_ fdd| D |_|S )Nc                    s    i | ]\}}| j v r||qS rG   r   r  )self_or_clsrG   rJ   rr     rL   z&rasterize.instance.<locals>.<dictcomp>c                    s   i | ]\}}| v r||qS rG   rG   r  )kwargsrG   rJ   rr     rL   )r  r   r   r1  r   _rasterize__instance_params_rasterize__instance_kwargs)r  r   Zinst_paramsinstr4  )r  r  rJ   r     s    
zrasterize.instancec                    s(  t  }t  }t jfi  fdd jD } jD ]\}t|fi  j}dD ]}||d dkrR|| qRtdd | D dd}	t|	fi  j	 }
|t |
O }|t j
O }jf i fdd|
 D } j|_|||}|j _q4t|| }|r$ j
d	d
|  |S )Nc                    s   i | ]}|t  |qS rG   )rW   )rn   r  r  rG   rJ   rr     rL   z&rasterize._process.<locals>.<dictcomp>)r   rj  r5   c                 S   s&   i | ]\}}|d u r|dks||qS )Nr   rG   r  rG   rG   rJ   rr     s   F)r   c                    s    i | ]\}}| j v r||qS rG   r  r  )	transformrG   rJ   rr     s   
z9Parameter(s) [%s] not consumed by any element rasterizer.z, )r  r   r  r  _transformsrx   getpopr   Zextra_keywordsr   r   r   r  r   r  r   )r}   r_   r   Zall_allowed_kwsZall_supplied_kwsZinstance_params	predicateZmerged_param_valuesr  Z	op_paramsZextended_kwsopZunused_paramsrG   )r}   r  rJ   r    s8    "
zrasterize._process)N)1rX   r   r   r   r   r   rO   r   r   rR   r   rt  rj  r"   rP  r&   r  r-   rw  r'   r  r   r+   r7  r   r'  r,   r.  r*   rM  r(   rO  r   ru  r!   r)   r%   r    r$   r]   r  r  r  r  r  r   r   r  r6  rG   rG   r4  rJ   r    sF   

r  c                   @   s   e Zd ZdZdddZdS )	datashadea  
    Applies the aggregate and shade operations, aggregating all
    elements in the supplied object and then applying normalization
    and colormapping the aggregated data returning RGB elements.

    See aggregate and shade operations for more details.
    Nc                 C   s    t | ||}t| ||}|S rF   )r  r  r  )r}   r_   r   r`   ZshadedrG   rG   rJ   r    s    zdatashade._process)Nr-  rG   rG   rG   rJ   r    s   r  c                   @   s6   e Zd ZdZejg ddddZdd Zdd	d
ZdS )stackzr
    The stack operation allows compositing multiple RGB Elements using
    the defined compositing operator.
    )addoversaturatesourcer  zB
        Defines how the compositing operation combines the images)rV  r5   r6   c                    s   t  fdd jD }|jd dkrdt |jd d }|jjdkrV|d d}t ||g}|jjdkr|d t j}|j\}}}|j	t j
d||fS )Nc                    s   g | ]} j |d dqS FrY  rg  r   rX  rG   rJ   r     s   z)stack.uint8_to_uint32.<locals>.<listcomp>r
   r/  r  r  r  )ru   dstackrZ   r   onesr   r[   r   r  r  uint32r  )r}   r_   r  r  Nr   r   rG   rX  rJ   uint8_to_uint32  s    zstack.uint8_to_uint32Nc           
   
      s  t |ts|S t|dkr4t |tr*|jS |dS g }|D ]p t  ts\tdt j	  j
 dd  jD d d d } fdd jD }|tj|  ||d	 q<ztj|d
di}W n. ty } ztd|W Y d }~n
d }~0 0 tj|d| jji}t|jd d d }||d  ||d  |d d d d df |d d d d df |d d d d df f}	|jd dkr|	|d d d d df f }	 j|	 jjg j dS )Nr0   r   z;The stack operation expects elements of type RGB, not '%s'.c                 S   s   g | ]
}|j qS rG   r   r   rG   rG   rJ   r      rL   z"stack._process.<locals>.<listcomp>r   c                    s   i | ]}|j  |d qS )Fr[   r{   r   r  rG   rJ   rr   !  s   z"stack._process.<locals>.<dictcomp>rZ  r   exactzaRGB inputs to the stack operation could not be aligned; ensure they share the same grid sampling.r  r
   r  r/  r   )rQ   r   r   r   r<   r  r   r   r]   rX   r  r\   r   r  r"   r  rs   ZalignrU   r  rx   
compositorr  r  r   r   r   r   r   )
r}   r  r   Zimgsrg   rh   eZstackedrd  r   rG   r  rJ   r    s<    


((zstack._process)N)	rX   r   r   r   r   rt  r  r  r  rG   rG   rG   rJ   r    s   
r  c                   @   sr   e Zd ZdZejeedkr dndg dddZejddd	gd
dZ	dZ
edd Zdd Zdd ZdddZdS )SpreadingOperationz
    Spreading expands each pixel in an Image based Element a certain
    number of pixels on all sides according to a given shape, merging
    pixels using a specified compositing operator. This can be useful
    to make sparse plots more visible.
    z0.11.1r  N)Nr  r  r  r  rC   rB   z
        The name of the compositing operator to use when combining
        pixels. Default of None uses 'over' operator for RGB elements
        and 'add' operator for aggregate arrays.rU  ZcircleZsquarezL
        The shape to spread by. Options are 'circle' [default] or 'square'.Tc                 C   sp   |j }tj|d d }|d dkrJt|tj|d d ddd g}||dfd|d d }|S )	Nr
   r   r/  r  r  r  r  r  )r   ru   multiplyreducer  r  r  r  )r^   r  r   Z
flat_shaper  rG   rG   rJ   r  I  s    $"z"SpreadingOperation.uint8_to_uint32c                 C   s   t dS )z9Apply the spread function using the indicated parameters.NrD  r}   r@  rG   rG   rJ   _apply_spreadingR  s    z#SpreadingOperation._apply_spreadingc                    sD   t  fdd jD }|jjdkr.|d }t| |dS )Nc                    s   g | ]} j |d dqS r  rg  r}  rX  rG   rJ   r   W  s   z6SpreadingOperation._preprocess_rgb.<locals>.<listcomp>r  r  r  )	ru   r  rZ   r   r   r  r"   r  r   )r}   r_   ZrgbarrayrG   rX  rJ   _preprocess_rgbV  s    z"SpreadingOperation._preprocess_rgbc           	         s   t |tr|j |  }n<t |trD|jdgdj|jd j }nt	dt
t| i }| |}t |trt|jd d d } fdd jD }t jdkr j jg n j}||d	< ||td
d |D < n|}|j|f|j|jd|S )Nr   r   r   zRspreading can only be applied to Image or RGB Elements. Received object of type %sr   c                    s   i | ]}|j  j|d dqS )Frk   r  r   r  rG   rJ   rr   k  s   z/SpreadingOperation._process.<locals>.<dictcomp>r/  rZ   c                 s   s   | ]}|j V  qd S rF   r   r}  rG   rG   rJ   r   q  rL   z.SpreadingOperation._process.<locals>.<genexpr>)ri   rj   )rQ   r   r  r  r"   r   r   rZ   r[   rU   rR   r]   r  r  r  r\   r   Zalpha_dimensionri  ri   rj   )	r}   r_   r   r   r  r@  r  Znew_datarZ   rG   r  rJ   r  ]  s0    





"zSpreadingOperation._process)N)rX   r   r   r   r   rt  r   r   r  r   Z_per_elementr   r  r  r  r  rG   rG   rG   rJ   r  5  s   
r  c                   @   s&   e Zd ZdZejdddZdd ZdS )spreada}  
    Spreading expands each pixel in an Image based Element a certain
    number of pixels on all sides according to a given shape, merging
    pixels using a specified compositing operator. This can be useful
    to make sparse plots more visible.

    See the datashader documentation for more detail:

    http://datashader.org/api.html#datashader.transfer_functions.spread
    r0   z1
        Number of pixels to spread on all sides.r8  c                 C   s   t j|| jj| jj| jjdS )N)pxr  r   )r  r  rx   r  r  r   r  rG   rG   rJ   r    s    zspread._apply_spreadingN)rX   r   r   r   r   r  r  r  rG   rG   rG   rJ   r  y  s   r  c                   @   s6   e Zd ZdZejdddZejddddZd	d
 Z	dS )	dynspreada  
    Spreading expands each pixel in an Image based Element a certain
    number of pixels on all sides according to a given shape, merging
    pixels using a specified compositing operator. This can be useful
    to make sparse plots more visible. Dynamic spreading determines
    how many pixels to spread based on a density heuristic.

    See the datashader documentation for more detail:

    http://datashader.org/api.html#datashader.transfer_functions.dynspread
    r/  z9
        Maximum number of pixels to spread on all sides.r8  r9  )r   r0   a  
        When spreading, determines how far to spread.
        Spreading starts at 1 pixel, and stops when the fraction
        of adjacent non-empty pixels reaches this threshold.
        Higher values give more spreading, up to the max_px
        allowed.r   c                 C   s$   t j|| jj| jj| jj| jjdS )N)max_px	thresholdr  r   )r  r  rx   r  r  r  r   r  rG   rG   rJ   r    s    zdynspread._apply_spreadingN)
rX   r   r   r   r   r  r  r   r  r  rG   rG   rG   rJ   r    s   r  c                 C   s:   t | jdddf  d d }dd t | |D S )zW
    Splits a dataframe of paths separated by NaNs into individual
    dataframes.
    Nr   r0   c                 S   s   g | ]}t |d kr|qS )r0   )r   )rn   r   rG   rG   rJ   r     rL   z#split_dataframe.<locals>.<listcomp>)ru   rP   r   Zisnullr   )Zpath_dfsplitsrG   rG   rJ   split_dataframe  s    $r  c                   @   s,   e Zd ZejdddZdd Zd	ddZdS )
_connect_edgesFzz
        Determines whether bundled edges will be split into individual edges
        or concatenated with NaN separators.r8  c                 C   s   t dd S )NzS_connect_edges is an abstract baseclass and does not implement any actual bundling.rD  r}   position_dfedges_dfrG   rG   rJ   _bundle  s    z_connect_edges._bundleNc           	      C   s   |j jd j}dd t|jd d ddgD }dd t|j jd d ddgD }|j jf i |g d	|}|jf i |d
dg}| ||}|jdd |	 D d}| j
jrt|n|g}||j|j |fS )Nr
   c                 S   s   i | ]\}}|j |qS rG   r   rn   r   ro   rG   rG   rJ   rr     rL   z+_connect_edges._process.<locals>.<dictcomp>r  rl  c                 S   s   i | ]\}}|j |qS rG   r   r  rG   rG   rJ   rr     rL   rI   re   rz  r   r0   c                 S   s   i | ]\}}||qS rG   rG   r  rG   rG   rJ   rr     rL   r   )rY   r\   r[   r   Zredimr>  Z	set_indexr  r   r   rx   r   r  r   r   )	r}   r_   r   r   Zrename_edgesZrename_nodesr  r  r   rG   rG   rJ   r    s    "$"z_connect_edges._process)N)rX   r   r   r   rs  r   r  r  rG   rG   rG   rJ   r    s   r  c                   @   s   e Zd ZdZdd ZdS )bundle_graphz
    Iteratively group edges and return as paths suitable for datashading.

    Breaks each edge into a path with multiple line segments, and
    iteratively curves this path to bundle edges into groups.
    c                 C   s$   ddl m} |j| ||fi | jS )Nr   )r	   )datashader.bundlingr	   __call__rx   )r}   r  r  r	   rG   rG   rJ   r    s    zbundle_graph._bundleNrX   r   r   r   r  rG   rG   rG   rJ   r    s   r  c                   @   s   e Zd ZdZdd ZdS )r   z?
    Given a Graph object will directly connect all nodes.
    c                 C   s   t | ||S rF   )connect_edgesr  r  rG   rG   rJ   r    s    zdirectly_connect_edges._bundleNr  rG   rG   rG   rJ   r     s   r   c                 C   s   | S rF   rG   rH   rG   rG   rJ   identity  rL   r  c                   @   sh   e Zd ZdZejdddZejege	e
fdZejddZejddZedd	 ZdddZdd Zd
S )inspect_maskz
    Operation used to display the inspection mask, for use with other
    inspection operations. Can be used directly but is more commonly
    constructed using the mask property of the corresponding inspector
    operation.
    r/  zs
       Size of the mask that should match the pixels parameter used in
       the associated inspection operation.r8  rQ  r   )r5   c           	      C   sT   |j j|dd\}}t|d |d  | }t|d |d  | }|| || fS NT)Zgriddedr0   r   r   r   abs	r^   r_   r   r   pixelsZycountZxcountZx_deltaZy_deltarG   rG   rJ   _distance_args  s    zinspect_mask._distance_argsNc           	      C   sp   t |tr|d|jd f }|d|d }}| |||| jj\}}| jj| jj }}| 	|j
||||S )N.r   r   r0   )rQ   r   rZ   r+  r  rx   r   rI   re   
_indicatorr\   )	r}   rq  r   r   r   xdeltaydeltarI   re   rG   rG   rJ   r    s    
zinspect_mask._processc              	   C   s   t ||d  ||d  f||d  ||d  f||d  ||d  f||d  ||d  fg}t|d t|d f|i}t||dS )Nr
   r   r0   r   )ru   r@  rR   r&   )r}   r\   rI   re   r  r  Zrectr   rG   rG   rJ   r    s
    0,zinspect_mask._indicator)N)rX   r   r   r   r   r  r   r   r/   r   r   streamsr   rI   re   r   r  r  r  rG   rG   rG   rJ   r    s   

r  c                       s   e Zd ZdZejdddZejdddZej	ddd	d
dZ
eje d	dZejdddZejeddZejeejjejjdeefdZejdddZejdddZi Zedd Zdd Ze fddZdddZdd Z   Z!S )inspectzX
    Generalized inspect operation that detects the appropriate indicator
    type.
    r/  z
       Number of pixels in data space around the cursor point to search
       for hits in. The hit within this box mask that is closest to the
       cursor's position is displayed.r8  r   a   
       Value of raster which indicates no hits. For instance zero for
       count aggregator (default) and commonly NaN for other (float)
       aggregators. For RGBA images, the alpha channel is used which means
       zero alpha acts as the null value.Nr
   Tz
       If not None, a numeric bounds for the pixel under the cursor in
       order for hits to be computed. Useful for count aggregators where
       a value of (1,1000) would make sure no more than a thousand
       samples will be searched.)r5   r  r8   r6   )r5   r8   r0   a@  
       Maximum number of indicator elements to display within the mask
       of size pixels. Points are prioritized by distance from the
       cursor point. This means that the default value of one shows the
       single closest sample to the cursor. Note that this limit is not
       applies to the hits parameter.z
      Function that transforms the hits dataframe before it is passed to
      the Points element. Can be used to customize the value dimensions
      e.g. to implement custom hover behavior.r:  rQ  zx-position to inspect.zy-position to inspect.c                 C   s   t j| jjdS )N)r   )r  r   rx   r   r  rG   rG   rJ   r&  8  s    zinspect.maskc                 C   s   |j j| _d S rF   )r   hits)r}   eventrG   rG   rJ   _update_hits<  s    zinspect._update_hitsc                    s   t  jf i |}d |_|S rF   )r1  r   _op)r  r   r  r4  rG   rJ   r   ?  s    zinspect.instancec                 C   sj   |  |jj}| j| }| jd u r@| | _| jj| jd nt	| j|sTt
d| j| j_| j|S )Nr  zACannot reuse inspect instance on different datashader input type.)_get_input_typeZpipeline
operations	_dispatchr
  r   r   Zwatchr	  rQ   rU   rx   r  )r}   rq  r   Z
input_typeZinspect_operationrG   rG   rJ   r  E  s    



zinspect._processc                 C   sV   |D ]D}t |dd }|d ur|dd tjD v rt|ttfr@q|  S qtdd S )Noutput_typec                 S   s   g | ]}|d  qS )r   rG   )rn   rq   rG   rG   rJ   r   U  rL   z+inspect._get_input_type.<locals>.<listcomp>zXCould not establish input element type for datashader pipeline in the inspect operation.)rW   r  r  r  r"   r   rh  )r}   r  r  r  rG   rG   rJ   r  Q  s    
zinspect._get_input_type)N)"rX   r   r   r   r   r  r   r   
null_valuer  value_boundsr   r   r  max_indicatorsr   r  r  r   r   r/   rI   re   r   r  r  propertyr&  r	  r   r   r  r  r6  rG   rG   r4  rJ   r    s,   

r  c                   @   sV   e Zd ZdZdddZedd Zedd Zed	d
 Zedd Z	edd Z
dS )inspect_basez
    Given datashaded aggregate (Image) output, return a set of
    (hoverable) points sampled from those near the cursor.
    Nc                 C   s>  |  | t|tr&|d|jd f }|d|d }}| |||| jj\}}| jj| jj	 }}||| || || || f j
tjd}	t|	r| jj}	| jjr| jjd |	  k r| jjd k rn n|	| jjkr| |j}
n"| |||||}| ||||}
|
| _| j|
}| ||jd | jj S )N.r   r   r0   )function)	_validaterQ   r   rZ   r+  r  rx   r   rI   re   r  ru   Znansumr#  r  r  	_empty_dfdataset_mask_dataframe_sort_by_distancer  r  _elementr   r  )r}   rq  r   r   r   r  r  rI   re   r  resultZmaskedr   rG   rG   rJ   r  e  s,    

.



zinspect_base._processc           	      C   sT   |j j|dd\}}t|d |d  | }t|d |d  | }|| || fS r  r  r  rG   rG   rJ   r  |  s    zinspect_base._distance_argsc                 C   sH   d|j jv r|jjjd d S |j jdv r6|jdS |jd d  S )Nr{  r   )pandasZ	geopandasr  )r   r   r   Z_metar   headr>  )r^   r  rG   rG   rJ   r    s
    zinspect_base._empty_dfc                 C   s   |j }|| || || || f\}}}	}
d|jjv rd|jj|||	|
f }t|dr`| S |S |j\}}|j||f|j|	|
fi}|j	f i |
 S )zp
        Mask the dataframe around the specified x and y position with
        the given x and y deltas
        r  r   )r  r   r   r   Zcxr   r   r\   r[   selectr>  )r^   rq  rI   re   r  r  rz   r  r  r  r  r   rH  rI  queryrG   rG   rJ   r    s    $
zinspect_base._mask_dataframec                 C   s   d S rF   rG   r^   rq  rG   rG   rJ   r    s    zinspect_base._validatec                    sH   |j }d|jjv r$|j|jg ndd |jD   fdd|jD S )Nr  c                 S   s   g | ]
}|j qS rG   r   r   rG   rG   rJ   r     rL   z'inspect_base._vdims.<locals>.<listcomp>c                    s   g | ]}| vr|qS rG   rG   )rn   r   rh   rG   rJ   r     rL   )r  r   r   r  r   r\   r   )r^   rq  r   rz   rG   r!  rJ   _vdims  s
    zinspect_base._vdims)N)rX   r   r   r   r  r   r  r  r  r  r"  rG   rG   rG   rJ   r  _  s   




r  c                   @   s$   e Zd Zedd Zedd ZdS )inspect_pointsc                 C   s   t ||j| ||dS )Nr   )r%   r\   r"  )r^   rq  r   rG   rG   rJ   r    s    zinspect_points._elementc           
         s\   |j |  fdd|jD \}}|| ||  }}t|| ||  }	|j|	 j S )
        Returns a dataframe of hits within a given mask around a given
        spatial location, sorted by distance from that location.
        c                 3   s   | ]}  |V  qd S rF   rg  r   rz   rG   rJ   r     rL   z3inspect_points._sort_by_distance.<locals>.<genexpr>)r  r   r\   r   Seriesr   argsortr   )
r^   rq  r   rI   re   r   r   dxdy	distancesrG   r%  rJ   r    s
    z inspect_points._sort_by_distanceN)rX   r   r   r   r  r  rG   rG   rG   rJ   r#    s   
r#  c                   @   s0   e Zd Zedd Zedd Zedd ZdS )inspect_polygonsc                 C   s   d|j jjvrtdd S )Nr  z7inspect_polygons only supports spatialpandas datatypes.)r  r   r   rU   r   rG   rG   rJ   r    s    zinspect_polygons._validatec                 C   s8   t ||j| ||d}t g kr0|jd dS |S d S )Nr   )Zcolor_index)r&   r\   r"  r   Zloaded_backendsopts)r^   rq  r   r  rG   rG   rJ   r    s    zinspect_polygons._elementc                 C   s   g g  }}|j jD ]}|jddd |jddd  }}	t|sZ|tj |tj q|t|t| d  |t|	t|	 d  qt|| t||  }
}t	
|
|
 ||  }|j| j S )r$  Nr
   r0   )r  r@  Zflat_valuesr   r   ru   rw   rB   rC   r   r&  r   r'  r   )r^   rq  r   rI   re   r   r   ZgeomZgxsZgysr(  r)  r*  rG   rG   rJ   r    s    
" z"inspect_polygons._sort_by_distanceN)rX   r   r   r   r  r  r  rG   rG   rG   rJ   r+    s   

r+  )ur  collections.abcr   r   	functoolsr   Zdask.dataframer   r   Z
datashaderrz   Zdatashader.reductionsZ
reductionsrO   Zdatashader.transfer_functionsZtransfer_functionsr  numpyru   r  r   r   r   rs   Zdatashader.colorsr   Zpackaging.versionr   Zparam.parameterizedr   r  r   r  r	   ImportErrorobjectcorer   r   r   r   r   r   r   Z	core.datar   r   r   r   r   Z	core.utilr   r   r   r   r   r   r_   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   Zelement.utilr.   r  r/   Zresampler1   r2   __version__r   rN   r3   r   r   r   r'  r.  r7  rC  rM  rO  rP  ru  rw  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r+  r  rG   rG   rG   rJ   <module>   s   $	 L
  Vs-M=
  5 SDi8D		&WJ$