
    |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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 	 d dlZn# e$ r dZY nw xY wg dZ G d	 d
ej                  Z G d d          Zd Z d2dZ!d d d e!dZ"d Z#d Z$d Z%d Z&d Z'd Z(ddgedddddddf	d Z)d3d!Z*d4d$Z+ej,        d%             Z-ej,        d&             Z.ej,        d'             Z/d( Z0d) Z1e0e1d*Z2d5d-Z3 e
j4        d.d.d./          d6d0            Z5 e
j4        d.d.d./          d6d1            Z6dS )7    )annotations)IteratorBytesION)	fromarray)rgbSets1to3)nansum_missingngjit)Imagestackshadeset_backgroundspread	dynspreadc                  6    e Zd ZdZdZdZddZddZd Zd	 Z	d
S )r    F      lowerc                    | j         }t          rt          j        |          }|dk    rt          j        |          n|}t          |d          S )Nr   RGBA)datacupyasnumpynpflipudr   )selforiginr   arrs       Flib/python3.11/site-packages/datashader/transfer_functions/__init__.pyto_pilzImage.to_pil    sK    y 	&<%%D!'7!2!2biooof%%%    pngc                    t                      }|                     |                              ||           |                    d           |S Nr   )r   r"   saveseek)r   formatr   fps       r!   
to_bytesiozImage.to_bytesio'   sA    YYF  V,,,



	r#   c                N    |                                                                  S )z/Supports rich PNG display in a Jupyter notebook)r"   
_repr_png_)r   s    r!   r-   zImage._repr_png_-   s    {{}}'')))r#   c                @   ddl m} ddlm}  |            }|                                                     |d           dt          | j                  z   dz   d                     ||	                                          
                    d	                    z   }|S )
z0Supports rich HTML display in a Jupyter notebookr   r   )	b64encoder$   )r)   z!<img style="margin: auto; border:z
px solid" z!src='data:image/png;base64,{0}'/>zutf-8)ior   base64r/   r"   r'   strborderr)   getvaluedecode)r   r   r/   bhs        r!   _repr_html_zImage._repr_html_1   s     	$$$$$$GII1U+++3c$+6F6FFIYY3yy..55g>>??@ r#   N)r   )r$   r   )
__name__
__module____qualname__	__slots____array_priority__r3   r"   r+   r-   r8   r   r#   r!   r   r      sj        IF& & & &   * * *    r#   r   c                  $    e Zd ZdZd Zd Zd ZdS )Imagesz
    A list of HTML-representable objects to display in a table.
    Primarily intended for Image objects, but could be anything
    that has _repr_html_.
    c                P    |D ]}t          |d          sJ || _        d| _        dS )z@Makes an HTML table from a list of HTML-representable arguments.r8   N)hasattrimagesnum_cols)r   rB   is      r!   __init__zImages.__init__H   s<     	, 	,A1]++++++r#   c                    || _         | S )zk
        Set the number of columns to use in the HTML table.
        Returns self for convenience.
        )rC   )r   ns     r!   colszImages.colsO   s    
 r#   c                   g }d}d}| j         D ]}t          |d          r|j        |j        nd}|                    d|z   d                    |                                          z              |dz  }| j        %|| j        k    rd}|                    d	|z              d
|z   d                    |          z   dz   S )z@Supports rich display in a Jupyter notebook, using an HTML tabler   z#<tr style="background-color:white">nameN z"<td style="text-align: center"><b>z</b><br><br>{0}</td>r   z</tr>z5<table style="width:100%; text-align: center"><tbody>z</tr></tbody></table>)rB   rA   rJ   appendr)   r8   rC   join)r   htmlscoltrrD   labels         r!   r8   zImages._repr_html_W   s    4 	) 	)A#Af--L!&2D!&&"ELLAEI3::1==??KKL M M MFC}(S$--?-?WRZ(((JBNwwu~~ ;< 	<r#   N)r9   r:   r;   __doc__rE   rH   r8   r   r#   r!   r?   r?   A   sK             < < < < <r#   r?   c                    ddl m} | st          d          g }| D ]}}t          |t                    s/t          d                    t          |                              |s|                    |j	                   c|r|j	        |vrt          d          ~|
                    dd          }||
                    dd	                   }t          |           d
k    r| d         S t          j        | ddd} t          j        dd          5  t!          j        t!          j        |          d | D                       }ddd           n# 1 swxY w Y   t	          || d         j        | d         j        |          S )a  Combine images together, overlaying later images onto earlier ones.

    Parameters
    ----------
    imgs : iterable of Image
        The images to combine.
    how : str, optional
        The compositing operator to combine pixels. Default is `'over'`.
    r   )composite_op_lookupzNo images passed inExpected `Image`, got: `{0}`z,The stacked images must have the same shape.rJ   Nhowoverr   Fouter)copyrM   ignoredivideinvalidc                    g | ]	}|j         
S r   )r   ).0rD   s     r!   
<listcomp>zstack.<locals>.<listcomp>   s    %;%;%;af%;%;%;r#   coordsdimsrJ   )datashader.compositerT   
ValueError
isinstancer   	TypeErrorr)   typerL   shapegetlenxralignr   errstatetzreducefliprb   rc   )imgskwargsrT   shapesrD   rJ   opouts           r!   r   r   k   s    988888 0.///F M M!U## 	M:AA$q''JJKKK 	MMM!'"""" 	Mv--KLLL::fd##D	VZZv66	7B
4yyA~~Aw8TG444D	Hh	7	7	7 = =i%;%;d%;%;%;<<= = = = = = = = = = = = = = =T!W^$q',TJJJJs   2EEE   c                   t           r(t          | t           j                  rddlm} t           }n<t          | t
          j                  st          d          t
          j        }t
          }|7|                    |          r"|                    | t
          j	                  dfS || n| |          }|j
        t          k    s8|                    |j
        |j                  r|                                |k     r|                    |d          \  }}|d                                         |d                                         }	}|	|z
  }
|                    ||	dz             }|                    |
dz   d	
          }||||z
  <   t'          |          }np|                    ||          \  }}|dd         |dd         z   dz  }|dk    }|                    |          }|t'          |          k    r||         }||         }|                                }|t/          |d                   z  } || ||                              | j                  }||n|                    ||j	        |          |fS )a  Return a numpy array after histogram equalization.

    For use in `shade`.

    Parameters
    ----------
    data : ndarray
    mask : ndarray, optional
       Boolean array of missing points. Where True, the output will be `NaN`.
    nbins : int, optional
        Maximum number of bins to use. If data is of type boolean or integer
        this will determine when to switch from exact unique value counts to
        a binned histogram.

    Notes
    -----
    This function is adapted from the implementation in scikit-image [1]_.

    References
    ----------
    .. [1] http://scikit-image.org/docs/stable/api/skimage.exposure.html#equalize-hist
    r   )interpzdata must be an ndarrayNr   T)return_countsuint64dtype)bins   )r   rf   ndarray_cuda_utilsry   r   rg   all	full_likenanr~   bool
issubdtypeintegerptpuniqueitemarangezerosrk   	histogramcount_nonzerocumsumfloatreshaperi   where)r   masknbinsry   array_moduledata2valuescountsvminvmaxintervalbin_centershistdiscrete_levels	bin_edges	keep_maskcdfrv   s                     r!   eq_histr      sn   .  
4.. &&&&&&bj)) 1222L,,T22%%dBF33Q66LDDdD5kE {d|66u{LDXYY$yy{{U22%,,U$,GGAY^^%%vbz'8'8d9"))$Q77!!(1*H!=="VD[f++&00U0CCi "~	!""5:AX	&44Y??c$ii''	?D%i0K
++--C
c"g
C
&{C
(
(
0
0
<
<C,33L$6$6t\=Ms$S$SUdddr#   c                f    t          j        t          j        |t           j        |                     S N)r   log1pr   r   dms     r!   <lambda>r      s     28BHQ4J4J+K+K r#   c                H    t          j        |t           j        |           dz  S )NgUUUUUU?r   r   r   r   s     r!   r   r      s    BHQ,B,BT,J r#   c                B    t          j        |t           j        |           S r   r   r   s     r!   r   r      s    bhq"&!.D.D r#   )logcbrtlinearr   c                    t          |           r| S | t          v rt          |          S t          d                    |                     )Nz!Unknown interpolation method: {0})callable_interpolate_lookupre   r)   )rV   s    r!   _normalize_interpolate_howr      sI    }} (
	#	#	#"3''
8??DD
E
EEr#   c                    | t          d          d}dd|z  z
  }|| z  |z   }|dk    r/t          |d         ||d         |d         z
  z  z
  d          }|df}|S )Nz3interpolator did not return a valid discrete_levelsg9/tg      ?r   r   r   )re   max)r   spanr   cmultiple
lower_spans         r!   _rescale_discrete_levelsr      s{    NOOO 	Aac	A 1$H!||a8T!WtAw->#??CC
AKr#   c           
     <   t           r(t          | j        t           j                  r	ddlm}m}	 nddlm} t          j        }	| j	        dk    rt          d          t          |          }
| j        }t          |t          j                  r|                                }n|                                }t          j        |j        t          j                  r#| }|                    t          j                  }n+|j        j        dk    r|dk    }nt          j        |          }|                                rKt1          t          j        | j        j        t          j                  | j        | j        | j        |	          S |t          j        ||                    }n+t          j         ||j        
          d         } |||g|R   ||z  }t          j!        dd          5   |
||          }d }t          |tD          tF          f          r|\  }}|^t          j$        | |t          j%                  }t          j        |          t          j&        |          f}|r|tO          ||          }n2|dk    rt          d           |
d|d         |d         z
  gd          }d d d            n# 1 swxY w Y   t          |tP                    rtE          |          }t          |tF                    r*t          |d         tR                    rtE          |          }t          |tD                    rt          j         tE          tU          tW          tX          |                               \  }}}t          j-        |d         |d         t]          |                    }t          j/         |	|||d          d                              t          j0                  }t          j/         |	|||d          d                              t          j0                  }t          j/         |	|||d          d                              t          j0                  }t          j$        t          j        |          d|                              t          j0                  }t          j1        ||||g          }nLt          |tR                    st          |tF                    r4tY          |          }t          j2        ||dz             }t          j-        |d         |d         t]          |                    }t          j3        |j        |d         t          j0        
          }t          j3        |j        |d         t          j0        
          }t          j3        |j        |d         t          j0        
          }t          j/         |	|||dd          d                              t          j0                  }t          j1        ||||g          }nti          |          r||d         z
  |d         |d         z
  z  }t           r.t          |t           j                  rt          j5        |          } ||d          }t          j$        t          j        |          d|                              t          j0                  |d d d d df<   n/tm          d7                    tq          |                              |9                    t          j                  :                    |j                  }t           r.t          |t           j                  rt          j5        |          }t1          || j        | j        |          S )Nr   )masked_clip_2dry   r   r   agg must be 2Dur   )ri   r~   )rb   rc   attrsrJ   r}   rZ   )r]   r\   r   +span is not (yet) valid to use with eq_hist   )leftFrY   r   rightT)bytes   zVExpected `cmap` of `matplotlib.colors.Colormap`, `list`, `str`, or `tuple`; got: '{0}'ra   );r   rf   r   r   r   r   ry   
_cpu_utilsr   ndimre   r   daArraycomputerY   r   r~   bool_astypeint8kindisnanr   r   r   ri   uint32rb   rc   r   nanminarrayrn   listtupler   r   nanmaxr   r   r2   zipmapr   linspacerk   
nan_to_numuint8dstackr   fullr   r   rg   r)   rh   viewr   )aggcmaprV   alphar   	min_alpharJ   rescale_discrete_levelsr   ry   interpolaterr   r   offsetr   masked_datarspangspanbspanrgr6   argbacoloraspanscaled_dataimgs                               r!   _interpolater      s    
38T\22 777777777......
x1}})***-c22L8D$!! ||~~yy{{ 
}TZ** "u{{27##:?c!!19DD8D>>D xxzz @RXCHN$&I/ / /7:z(#)$@ @ @ 	@
 |4;''$dj111!4tT)D)))) 	FND	Xh	7	7	7 ; ;|D$''dT5M** 	)$(!D/ <(D5$77K9[))29[+A+AAD& G?+F/FFi !!NOOO<DGd1g$5 6::D); ; ; ; ; ; ; ; ; ; ; ; ; ; ;, $!! Dzz$ :d1gs#;#; Dzz$ T htCS$,@'A'ABBue{47DGSYY77M&&tU===EJJJQQRTRZ[[M&&tU===EJJJQQRTRZ[[M&&tU===EJJJQQRTRZ[[HRXd^^Q..55bh??y!Q1&&	D#		 T*T5"9"9 TD			)U1W--{47DGSZZ88GDJa999GDJa999GDJa999M&&tU#FFFUSSSZZ[][cddy!Q1&&	$ Td1g~Q$q'(9: 	4J{DL99 	4,{33KtKt,,,+!6!65AAHHRRQQQ1W @@FtDzz@R@RT T 	T ))BI


&
&tz
2
2C  
3--  l3SZchTBBBBs   *CJ88J<?J<c	                *   t           r,t          | j        t           j                  rt           j        }	nt
          j        }	| j        dk    st          d          | j        | j	        d                  }
t          |
          st          t          j        | j        dd         t
          j                  | j	        d d         t          | j	        d         | j        | j	        d                  f| j	        d         | j        | j	        d                  fg          |          S t          d	          t          t                    st          t#          |
                    t                    t          |
          k     r0t          d
t                     dt          |
           d          fd|
D             }t%          |	t#          |           \  }}} | j        | j	        d         f| j	        d d         z    }|j                            g d          }t          |t(          j                  r|                                }|                                }t1          j                    5  t1          j        dd           |t          j        |          n|}d d d            n# 1 swxY w Y   t          j        d          5  |dk    r||z  }n|dk     r|| z  }|j        j        dk    r|	d||dk     <   d d d            n# 1 swxY w Y   t?          |d          }d|t          j         |          <   t          j        dd          5  |!                    |          |z  "                    t
          j#                  }|!                    |          |z  "                    t
          j#                  }|!                    |          |z  "                    t
          j#                  }d d d            n# 1 swxY w Y   t          j         |           }t          j$        |d          }t          j        dd          5  |!                    |          |z  "                    t
          j#                  }|!                    |          |z  "                    t
          j#                  }|!                    |          |z  "                    t
          j#                  }d d d            n# 1 swxY w Y   t          j$        |d          dk    }t          j%        |||          }t          j%        |||          }t          j%        |||          }t?          |d          }t          j         |          }tM          ||||||||          }t          j'        ||||g          (                    t
          j                  )                    |j                  } t           r.t          | t           j                  rt          j*        |           } t          | | j	        d d         t          | j	        d         | j        | j	        d                  f| j	        d         | j        | j	        d                  fg          |          S )Nr   zagg must be 3Dr{   r   r   r}   r   rc   rb   rJ   zXColor key must be provided, with at least as many colors as there are categorical fieldszInsufficient colors provided (z() for the categorical fields available ()c                :    g | ]}t          |                   S r   r   r_   r   	color_keys     r!   r`   z_colorize.<locals>.<listcomp>t  %    ...Ac)A,...r#   )r   r   r   rZ   All-NaN slice encounteredr]   r   )axisr[   )+r   rf   r   r   r   r   r   re   indexesrc   rk   r   r   ri   r   dictrb   r   r   	transposer   r   r   rY   warningscatch_warningsfilterwarningsr   rn   r~   r   r
   r   dotr   r   sumr   _interpolate_alphar   r   r   r   )!r   r   rV   r   r   r   rJ   color_baseliner   r   catscolorsrsgsbsagg_tr   
color_databaselinecolor_totalr   r   r6   
color_mask	cmask_sumr2g2b2missing_colorstotalr   r   r   s!    `                               r!   	_colorizer  Z  s    
38T\22 
8q==)***;sx|$Dt99 ORXci!nBI>>>SXcrc] (1+sz#(1+'>?(1+sz#(1+'>?"B C CIMO O O 	O
  B C C 	Ci&& /T9--..	
9~~D		!! ;#i.. ; ;.1$ii; ; ; < < 	< /......FUCL))JBB CMSXb\OCHRaRL8:E:			**D$!! ||~~J 
	 	"	" W W*FGGG,:,B29Z(((W W W W W W W W W W W W W W W 
X	&	&	& ' 'a<<("JJ\\8)#J C''N,F%&Jz!|$' ' ' ' ' ' ' ' ' ' ' ' ' ' ' !!444K!"Jrx~~ 
Hh	7	7	7 > >^^B+33BH==^^B+33BH==^^B+33BH==> > > > > > > > > > > > > > > (4..Jz***I	Hh	7	7	7 = =nnR  *2228<<nnR  *2228<<nnR  *2228<<= = = = = = = = = = = = = = =
 VJQ///14N
Q''A
Q''A
Q''A4a(((E8E??D4c5$	KbccAY1a|$$))")44<<QWEEF &
64<00 &f%%hssmhqk3:chqk#:;hqk3:chqk#:;      sJ   5.J//J36J34LLLB PPPB S<<T T c                   t           r*t          | t           j                  rddlm}m}	 t           }
nddlm}	 t          j        }t          }
|t          j	                    5  t          j
        dd           t          j        |          }d d d            n# 1 swxY w Y   |j        j        dk    rb|dk    r\||dk    z  }t          j        |          s||dk                                             }t          j        | |t          j                  } t%          |          ||z
  |          }d }t          |t&          t(          f          r|\  }}t          j	                    5  t          j
        dd           t          j        |                                          t          j        |                                          g}d d d            n# 1 swxY w Y   |r|t/          ||          }n |d	k    rt1          d
          t          j        || j                  d         }|j        j        dk    rBt          j        |          dk    r*||dk    z  }t          j        | |t          j                  } |	||g|R    t%          |          ||z
  |          }t          |t&          t(          f          r|d         } t%          |          d|d         |d         z
  gd          }t          |t&          t(          f          r|d         }|
                    |          } ||||
                    ||g          dd          }t          j        |d                              t          j                  }|S )Nr   )ry   r   r   rZ   r   r   r   z All-NaN (slice|axis) encounteredr   r   r}   r   r   Fr   )r   rf   r   r   ry   r   r   r   r  r  r  r   r~   r   r   minr   r   r   r   r   r   r   r   re   r   hstackr   r   r   )r   r  r   rV   r   r   r   r   ry   r   r   r   a_scaledr   	norm_spana_floatr   s                    r!   r	  r	    s    
4.. 77777777...... |$&& 	& 	&#H.JKKKYu%%F	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& ;s""v{{5A:&D 6$<< 0uqy)--//HdUE2622E2-c2256>4HHhu.. 	1(0%Ho $&& 	Q 	Q#H.QRRR8,,1133RYx5H5H5M5M5O5OPI	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q # 	M'B0)LLI ) JKKK $dj111!4;s""ry'7'71'<'<5A:&DHdUE2622Eud*T****2-c2256>4HHhu.. 	#{H3.s33QQ$q'8I4JANN	i$// 	%!!I
 ##I..I fXy,*<*<i=O*P*PWX`cdddG
gE***11"(;;AHs%   !*BBB&A"GGGc                
   t           r3t          | j        t           j                  rt           }t           j        }nt
          }t
          j        }| j        dk    st          d          t          t                    st          d          | j        }t          |t          j
                  r|                                }                                }fd|D             }	t          |t          |	           \  }
}}|                    |          |j        z  }|                    ||j                  }|                    ||j                  }|                    ||j                  }|                    ||j                  }|                    ||j                  }|                    ||j                  }t'          |          D ]1\  }}||k    }d||<   |
|         ||<   ||         ||<   ||         ||<   2|                                }||                    |          n|}t          j        d          5  |d	k    r||z  }n|d	k     r|| z  }|j        j        d
k    r|	d	||d	k     <   d d d            n# 1 swxY w Y   d	||                    |          <   |                                s||d d <   ||d d <   ||d d <   |d	k    }|                    |||          }|                    |||          }|                    |||          }t          j        t          j        |          d	|                              t
          j                  }|                    ||||g                              |j                                       |j!                  }t           r3t          | j        t           j                  rt          j"        |          }tG          || j$        | j%        |          S )Nr   r   z*Color key must be provided as a dictionaryc                :    g | ]}t          |                   S r   r   r   s     r!   r`   z,_apply_discrete_colorkey.<locals>.<listcomp>  r   r#   r}   r   rZ   r   r   r   r   )&r   rf   r   r   r   r   r   re   r  r   r   r   keysr   r   
empty_liker   
zeros_liker   	enumeraterY   r   rn   r~   r   r   anyr   r   r   r   r   r   ri   r   r   rc   rb   )r   r   r   rJ   r
  moduler   agg_datar  r  r  r  r  r   r   r   r6   r  r  r  rD   r   
value_maskr  r  r  r   r   s    `                          r!   _apply_discrete_colorkeyr,    s%     
38T\22 
8q==)*** 	:i#>#>EFFFxH(BH%% &##%%>>D.......FUCL))JBBX&&3D$fl33A$fl33A$fl33A			4v|		4	4B			4v|		4	4B			4v|		4	4B$  1]
ZA:A:A:J -;,Bv}}Z(((H	X	&	&	& + +a<<("JJ\\8)#J C''N,F)*JzA~&+ + + + + + + + + + + + + + + &'Jv||D!!">> !!!!!!!!!1_N^R++A^R++A^R++A 	$E**11"(;;A]]Aq!Q<((--fm<<DDQWMMF &
38T\22 &f%%h
   s   	4J		JJ	lightbluedarkbluer   r   (   Fc
                   t          | t          j                  st          d          || j        n|}d|cxk    rdk    rn nd|cxk    rdk    sn t          d| d| d          |	r|dk    rd	}	| j        d
k    r@|(t          |t                    rt          | ||||          S t          | |||||||	          S | j        dk    rt          | ||||||||		  	        S t          d          )a$  Convert a DataArray to an image by choosing an RGBA pixel color for each value.

    Requires a DataArray with a single data dimension, here called the
    "value", indexed using either 2D or 3D coordinates.

    For a DataArray with 2D coordinates, the RGB channels are computed
    from the values by interpolated lookup into the given colormap
    ``cmap``.  The A channel is then set to the given fixed ``alpha``
    value for all non-zero values, and to zero for all zero values.
    A dictionary ``color_key`` that specifies categories (values in ``agg``)
    and corresponding colors can be provided to support discrete coloring
    2D aggregates, i.e aggregates with a single category per pixel,
    with no mixing. The A channel is set the given ``alpha`` value for all
    pixels in the categories specified in ``color_key``, and to zero otherwise.

    DataArrays with 3D coordinates are expected to contain values
    distributed over different categories that are indexed by the
    additional coordinate. Such an array would reduce to the
    2D-coordinate case if collapsed across the categories (e.g. if one
    did ``aggc.sum(dim='cat')`` for a categorical dimension ``cat``).
    The RGB channels for the uncollapsed, 3D case are mixed from separate
    values over all categories. They are computed by averaging the colors
    in the provided ``color_key`` (with one color per category),
    weighted by the array's value for that category.
    The A channel is then computed from the array's total value
    collapsed across all categories at that location, ranging from the
    specified ``min_alpha`` to the maximum alpha value (255).

    Parameters
    ----------
    agg : DataArray
    cmap : list of colors or matplotlib.colors.Colormap, optional
        The colormap to use for 2D agg arrays. Can be either a list of
        colors (specified either by name, RGBA hexcode, or as a tuple
        of ``(red, green, blue)`` values.), or a matplotlib colormap
        object.  Default is ``["lightblue", "darkblue"]``.
    color_key : dict or iterable
        The colors to use for a categorical agg array. In 3D case, it can be
        either a ``dict`` mapping from field name to colors, or an
        iterable of colors in the same order as the record fields,
        and including at least that many distinct colors. In 2D case,
        ``color_key`` must be a ``dict`` where all keys are categories,
        and values are corresponding colors. Number of categories does not
        necessarily equal to the number of unique values in the agg DataArray.
    how : str or callable, optional
        The interpolation method to use, for the ``cmap`` of a 2D
        DataArray or the alpha channel of a 3D DataArray. Valid
        strings are 'eq_hist' [default], 'cbrt' (cube root), 'log'
        (logarithmic), and 'linear'. Callables take 2 arguments - a
        2-dimensional array of magnitudes at each pixel, and a boolean
        mask array indicating missingness. They should return a numeric
        array of the same shape, with ``NaN`` values where the mask was
        True.
    alpha : int, optional
        Value between 0 - 255 representing the alpha value to use for
        colormapped pixels that contain data (i.e. non-NaN values).
        Also used as the maximum alpha value when alpha is indicating
        data value, such as for single colors or categorical plots.
        Regardless of this value, ``NaN`` values are set to be fully
        transparent when doing colormapping.
    min_alpha : float, optional
        The minimum alpha value to use for non-empty pixels when
        alpha is indicating data value, 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. Note that ``min_alpha``
        will not take any effect when doing discrete categorical coloring
        for 2D case as the aggregate can have only a single value to denote
        the category.
    span : list of min-max range, optional
        Min and max data values to use for 2D colormapping,
        and 3D alpha interpolation, when wishing to override autoranging.
    name : string name, optional
        Optional string name to give to the Image object to return,
        to label results for display.
    color_baseline : float or None
        Baseline for calculating how categorical data mixes to
        determine the color of a pixel. The color for each category is
        weighted by how far that category's value is above this
        baseline value, out of the total sum across all categories'
        values. A value of zero is appropriate for counts and for
        other physical quantities for which zero is a meaningful
        reference; each category then contributes to the final color
        in proportion to how much each category contributes to the
        final sum.  However, if values can be negative or if they are
        on an interval scale where values e.g. twice as far from zero
        are not twice as high (such as temperature in Fahrenheit), then
        you will need to provide a suitable baseline value for use in
        calculating color mixing.  A value of None (the default) means
        to take the minimum across the entire aggregate array, which
        is safe but may not weight the colors as you expect; any
        categories with values near this baseline will contribute
        almost nothing to the final color. As a special case, if the
        only data present in a pixel is at the baseline level, the
        color will be an evenly weighted average of all such
        categories with data (to avoid the color being undefined in
        this case).
    rescale_discrete_levels : boolean, optional
        If ``how='eq_hist`` and there are only a few discrete values,
        then ``rescale_discrete_levels=True`` 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
        ``how!=`eq_hist``. Default is False.
    z!agg must be instance of DataArrayNr   r   zmin_alpha (z) and alpha (z) must be between 0 and 255r   Fr   r   z!agg must use 2D or 3D coordinates)rf   rl   	DataArrayrg   rJ   re   r   r  r,  r   r  )
r   r   r   rV   r   r   r   rJ   r
  r   s
             r!   r   r   L  sT   V c2<(( =;<<<|388D)""""s"""""e):):):):s):):):):ayaauaaabbb (3)#3#3"'
x1}} Z	4%@%@ +Yt^    T3tY 79 9 9	QieT9dN02 2 	2 <===r#   c                   ddl m} t          | t                    s/t	          d                    t          |                               || j        n|}|| S t          j	        t          |          dz                                 d          d         } || j        |          }t          || j        | j        |          S )a  Return a new image, with the background set to `color`.

    Parameters
    ----------
    img : Image
    color : color name or tuple, optional
        The background color. Can be specified either by name, hexcode, or as a
        tuple of ``(red, green, blue)`` values.
    r   )rW   rU   N)r   r   ra   )rd   rW   rf   r   rg   r)   rh   rJ   r   r   r   r   r   rb   rc   )r   r   rJ   rW   
backgroundr   s         r!   r   r     s     *)))))c5!! J6==d3iiHHIII|388D}
#e**v-..33H==a@J4*%%DcjsxdCCCCr#   r   circlec                B    t           t          j                  s/t          d                    t                                         t           t                    }| j        n|}Ht          |t                    r|dk     rt          d          |dk    r S t          |         |          ndt          t          j                  r;j        dk    r0j        d         j        d         k    rj        d         dz  dk    st          d          ||rd	nd
}j        d         }|dz   j        dd         \  }}	|dz  z   |	dz  z   f j        t          j        t          j        fv }
|
rt          j        ndt(          r=t           j        t(          j                  rt)          j         j                   _        |rt/          ||          n7|
rt1          ||          n$t3          || j        t          j        k              fdt7           j                  dk    r            }n9t          j         fdt;           j        d                   D                       }                     | j         j         |          S )as  Spread pixels in an image.

    Spreading expands each pixel 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.

    Parameters
    ----------
    img : Image or other DataArray
    px : int, optional
        Number of pixels to spread on all sides
    shape : str, optional
        The shape to spread by. Options are 'circle' [default] or 'square'.
    how : str, optional
        The name of the compositing operator to use when combining
        pixels. Default of None uses 'over' operator for Image objects
        and 'add' operator otherwise.
    mask : ndarray, shape (M, M), optional
        The mask to spread over. If provided, this mask is used instead of
        generating one based on `px` and `shape`. Must be a square array
        with odd dimensions. Pixels are spread from the center of the mask to
        locations where the mask is True.
    name : string name, optional
        Optional string name to give to the Image object to return,
        to label results for display.
    z#Expected `xr.DataArray`, got: `{0}`Nr   z``px`` must be an integer >= 0r   r   z@mask must be a square 2 dimensional ndarray with odd dimensions.r   rW   addc                    t          j        | j                  } | j        |           |  f                                         S )Nr}   )r   r   r~   r   rY   )layerbufextra
fill_valuekernelr   padded_shapes     r!   apply_kernelzspread.<locals>.apply_kernel$  sY    glJekBBBuz4%%%5%<v-.33555r#   c                @    g | ]} d d d d |f                   S r   r   )r_   categoryr>  r   s     r!   r`   zspread.<locals>.<listcomp>,  sF     = = =$ &c!!!AAAh,&788 = = =r#   r   )!rf   rl   r1  rg   r)   rh   r   rJ   intre   _mask_lookupr   r   r   ri   r~   r   float32float64r   r   r   r   _build_spread_kernel_build_float_kernel_build_int_kernelr   rk   r   range	__class__rc   rb   )r   pxri   rV   r   rJ   is_imagewMN
float_typerv   r>  r:  r;  r<  r=  s   `   `       @@@@@r!   r   r     s   6 c2<(( Q=DDT#YYOOPPP#u%%H|388D|"c"" 	?b1ff=>>>77JE"2&&rz** EtyA~~jmtz!},,A1Ba1G1G + , , 	, { +ffe
1AFE9RaR=DAq%KQuW-Lrz2:66J%,1J *
38T\22 *<)) C%c844	 C$S!,,"339	+ABB6 6 6 6 6 6 6 6 6
 39~~ql3i = = = = =(-cil(;(;= = = > > ==38CJT=JJJr#   c                t    ddl m}m}  || d           || dz            t          fd            }|S )7Build a spreading kernel for a given composite operatorr   rT   validate_operatorFrK  _arrc                   | j         \  }}t          |          D ]}t          |          D ]}| ||f         }t                    D ]w}t                    D ]e}	|||	f         rYr|dk    r|||z   |	|z   f         }
n3r|||z   |	|z   f         dk    r|}
n ||||z   |	|z   f                   }
|
|||z   |	|z   f<   fxd S r&   )ri   rH  )r    r   rv   rM  rN  yxelrD   jresultignore_zeros	mask_sizeru   s              r!   
stencilledz%_build_int_kernel.<locals>.stencilled9  s)   y1q 	7 	7A1XX 7 7AYy)) 	7 	7A"9-- 7 71: 7+ CA),QUAE\):!- C#a!eQUl2CQ2F2F)+)+BAE1q5L0A)B)B06CAq1u-7	77	7 	7r#   rd   rT   rS  r   )rV   r]  r\  rT   rS  r^  ru   s    ``   @r!   rG  rG  2  sy     LKKKKKKKcE****	S6\	*B
7 7 7 7 7 7 U7 r#   c                p    ddl m}m}  || d           || dz            t          fd            }|S )rQ  r   rR  FrT  rU  c                   | j         \  }}t          |          D ]}t          |          D ]}| ||f         }t                    D ]}t                    D ]}}	|||	f         rqt          j        |          r|||z   |	|z   f         }
n?t          j        |||z   |	|z   f                   r|}
n ||||z   |	|z   f                   }
|
|||z   |	|z   f<   ~d S r   )ri   rH  r   r   )r    r   rv   rM  rN  rW  rX  rY  rD   rZ  r[  r]  ru   s              r!   r^  z'_build_float_kernel.<locals>.stencilledS  s)   y1q 	7 	7A1XX 7 7AYy)) 	7 	7A"9-- 7 71: 7!x|| C),QUAE\):!##a!eQUl*;!<!< C)+)+BAE1q5L0A)B)B06CAq1u-7	77	7 	7r#   r_  )rV   r]  rT   rS  r^  ru   s    `   @r!   rF  rF  L  ss     LKKKKKKKcE****	S6\	*B
7 7 7 7 7 U7 r#   c                x    ddl m}m}  || d           || rdndz            t          fd            }|S )rQ  r   rR  TrT  rK   rU  c                   | j         \  }}|j         d         }t          |          D ]}t          |          D ]}| ||f         }ot          |          dz	  dz  }	 ot          j        |           }
|	s|
rt          |          D ]r}t          |          D ]`}|||f         rT|dk    r|||z   ||z   f         }|||z   ||z   f         dk    r|}n ||||z   ||z   f                   }||||z   ||z   f<   asd S )Nr      r   )ri   rH  rA  r   r   )r    r   rv   rM  rN  rL  rW  rX  rY  process_imageprocess_arrayrD   rZ  r[  rK  ru   s                 r!   r<  z$_build_spread_kernel.<locals>.kerneln  sY   y1JqMq 	; 	;A1XX ; ;AY ( Ds2ww"}.C%- E4D  ;M ;"1XX 
; 
;!&q 	; 	;A#AqDz ;#%q55-0QA->F#&q1ua!e|#4a#7#7-/FF-/RCAq1u4E-F-FF4:AE1q5L 1	;;	; 	;r#   r_  )rV   rK  rT   rS  r<  ru   s    `   @r!   rE  rE  f  s|     LKKKKKKKcD))))	S($>BB?	@B
; ; ; ; ; U;* Mr#   c                `    t          |           } d| z  dz   }t          j        ||fd          S )z9Produce a square mask with sides of length ``2 * px + 1``r   r   r   r}   )rA  r   ones)rJ  rL  s     r!   _square_maskri    s3    	RB	B
A7Aq6((((r#   c                    t          j        |  | dz   d          }t          j        t          j        |dz  |dddf         dz  z             | dz   k    dd          S )	z8Produce a circular mask with a diameter of ``2 * r + 1``r   i4r}   r   N      ?TF)r   r   r   sqrt)r   rX  s     r!   _circle_maskrn    s^    
	1"a!e4(((A8BGAqD1QQQW:q=011QsU:D%HHHr#   )squarer4  rl  r   c                ^   t          | t                    }d|cxk    rdk    sn t          d          t          |t                    r|dk     rt          d          | j        t
          j        t
          j        fv }t          r=t          | j	        t          j
                  rt          j        | j	                  | _	        d}t          d|dz             D ]}	|	}|rt          | j	        |	dz            }
nt          | j                  dk    rt!          | j	        ||	dz            }
n^|r&t          j        t          j        |                     n| dk    }t          j        |dd          }t!          |j	        d|	dz            }
|
|k    r|dz
  } n|dk    rt)          | ||||	          S | S )
aX  Spread pixels in an image dynamically based on the image density.

    Spreading expands each pixel 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.  Spreading starts at 1 pixel, and stops when the fraction
    of adjacent non-empty pixels reaches the specified threshold, or
    the max_px is reached, whichever comes first.

    Parameters
    ----------
    img : Image
    threshold : float, optional
        A tuning parameter in [0, 1], with higher values giving more
        spreading.
    max_px : int, optional
        Maximum number of pixels to spread on all sides.
    shape : str, optional
        The shape to spread by. Options are 'circle' [default] or 'square'.
    how : str, optional
        The name of the compositing operator to use when combining
        pixels. Default of None uses 'over' operator for Image objects
        and 'add' operator otherwise.
    r   r   zthreshold must be in [0, 1]zmax_px must be >= 0r   r   )r   r~   F)ri   rV   rJ   )rf   r   re   rA  r~   r   rC  rD  r   r   r   r   rH  _rgb_densityrk   ri   _array_densitylogical_notr   r  r   )r   	thresholdmax_pxri   rV   rJ   rK  rO  px_rJ  densitymasked	flat_masks                r!   r   r     s   4 #u%%H	Q6777fc"" 0fqjj.///rz2:66J *
38T\22 *<))	CAvz""   	B"38RT22GG^^q  $SXz2a4@@GG6@PR^BHSMM222saxFvAX>>>I$Y^UBqDAAGYACE  Avvc3e4@@@@
r#   T)nopythonnogilcachec           
     J   | j         \  }}dx}}t          d|          D ]}t          d|          D ]}| ||f         }	|rt          j        |	          r|s|	dk    r|dz  }d}
t          t	          d||z
            t          ||z   dz   |                    D ]m}t          t	          d||z
            t          ||z   dz   |                    D ]5}|rt          j        | ||f                   r|s| ||f         dk    r|
dz  }
6n|
dk    r|dz  }|r||z  nt          j        S )zCompute a density heuristic of an array.

    The density is a number in [0, 1], and indicates the normalized mean number
    of non-empty pixels that have neighbors in the given px radius.
    r   r   )ri   rH  r   r   r   r  inf)r    rO  rJ  rM  rN  cnthas_neighborsrW  rX  rY  	neighborsrD   rZ  s                r!   rr  rr    ss    9DAqC-1a[[ ' 'q! 	' 	'AQTB 	'28B<< 	' 	'Aq	"3q!b&>>3q2vz13E3EFF + +A"3q!b&>>3q2vz13E3EFF + +' +QT0C0C +!++03AqD	Q%NI+ Q;;!Q&M	' !$/=/r#   c           
        | j         \  }}dx}}t          d|          D ]}t          d|          D ]}| ||f         dz	  dz  r|dz  }d}t          t          d||z
            t          ||z   dz   |                    D ]O}	t          t          d||z
            t          ||z   dz   |                    D ]}
| |	|
f         dz	  dz  r|dz  }P|dk    r|dz  }|r||z  nt          j        S )zCompute a density heuristic of an image.

    The density is a number in [0, 1], and indicates the normalized mean number
    of non-empty pixels that have neighbors in the given px radius.
    r   rd  r   r   )ri   rH  r   r  r   r~  )r    rJ  rM  rN  r  r  rW  rX  r  rD   rZ  s              r!   rq  rq    s8    9DAqC-1a[[ 
' 
'q! 		' 		'AAqD	R3& 'q	"3q!b&>>3q2vz13E3EFF + +A"3q!b&>>3q2vz13E3EFF + +1IOs2 +%NI+ Q;;!Q&M		' !$/=/r#   )Nrw   )NN)r   r4  NNN)rl  r   r4  NN)r   )7
__future__r   collections.abcr   r0   r   r  numpyr   numbanbtoolzro   xarrayrl   
dask.arrayr   r   	PIL.Imager   datashader.colorsr   r	   datashader.utilsr
   r   r   	Exception__all__r1  r   r?   r   r   r   r   r   r   r  r	  r,  r   r   r   memoizerG  rF  rE  ri  rn  rB  r   jitrr  rq  r   r#   r!   <module>r     s   " " " " " " $ $ $ $ $ $                                    + + + + + + + + 2 2 2 2 2 2 2 2KKKK   DDD O
N
N" " " " "BL " " "L&< &< &< &< &< &< &< &<TK K KB=e =e =e =eD LKJJ!D!D")+ + F F F  "jC jC jCZX X XvC C CLN N Nb !*-sbt$uA> A> A> A>HD D D D,IK IK IK IKX   2   2   @) ) )I I I '&( (7 7 7 7t T...0 0 0 /.00 T...0 0 0 /.0 0 0s   A	 	AA