[docs]classAggregationOperation(ResampleOperation2D):""" AggregationOperation extends the ResampleOperation2D defining an aggregator parameter used to define a datashader Reduction. """aggregator=param.ClassSelector(class_=(rd.Reduction,rd.summary,str),default=rd.count(),doc=""" 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.""")selector=param.ClassSelector(class_=(rd.min,rd.max,rd.first,rd.last),default=None,doc=""" 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.""")vdim_prefix=param.String(default='{kdims} ',allow_None=True,doc=""" Prefix to prepend to value dimension name where {kdims} templates in the names of the input element key dimensions.""")_agg_methods={'any':rd.any,'count':rd.count,'first':rd.first,'last':rd.last,'mode':rd.mode,'mean':rd.mean,'sum':rd.sum,'var':rd.var,'std':rd.std,'min':rd.min,'max':rd.max,'count_cat':rd.count_cat}@classmethoddef_get_aggregator(cls,element,agg,add_field=True):ifds15:agg_types=(rd.count,rd.any,rd.where)else:agg_types=(rd.count,rd.any)ifisinstance(agg,str):ifaggnotincls._agg_methods:agg_methods=sorted(cls._agg_methods)raiseValueError(f"Aggregation method '{agg!r}' is not known; "f"aggregator must be one of: {agg_methods!r}")ifagg=='count_cat':agg=cls._agg_methods[agg]('__temp__')else:agg=cls._agg_methods[agg]()elements=element.traverse(lambdax:x,[Element])if(add_fieldandgetattr(agg,'column',False)in('__temp__',None)andnotisinstance(agg,agg_types)):ifnotelements:raiseValueError('Could not find any elements to apply ''%s operation to.'%cls.__name__)inner_element=elements[0]ifisinstance(inner_element,TriMesh)andinner_element.nodes.vdims:field=inner_element.nodes.vdims[0].nameelifinner_element.vdims:field=inner_element.vdims[0].nameelifisinstance(element,NdOverlay):field=element.kdims[0].nameelse:raiseValueError("Could not determine dimension to apply ""'%s' operation to. Declare the dimension ""to aggregate as part of the datashader ""aggregator."%cls.__name__)agg=type(agg)(field)returnaggdef_empty_agg(self,element,x,y,width,height,xs,ys,agg_fn,**params):x=x.nameifxelse'x'y=y.nameifxelse'y'xarray=xr.DataArray(np.full((height,width),np.nan),dims=[y,x],coords={x:xs,y:ys})ifwidth==0:params['xdensity']=1ifheight==0:params['ydensity']=1el=self.p.element_type(xarray,**params)ifisinstance(agg_fn,ds.count_cat):vals=element.dimension_values(agg_fn.column,expanded=False)dim=element.get_dimension(agg_fn.column)returnNdOverlay({v:elforvinvals},dim)returneldef_get_agg_params(self,element,x,y,agg_fn,bounds):params=dict(get_param_values(element),kdims=[x,y],datatype=['xarray'],bounds=bounds)ifself.vdim_prefix:kdim_list='_'.join(str(kd)forkdinparams['kdims'])vdim_prefix=self.vdim_prefix.format(kdims=kdim_list)else:vdim_prefix=''category=Noneifhasattr(agg_fn,'reduction'):category=agg_fn.cat_columnagg_fn=agg_fn.reductionifisinstance(agg_fn,rd.summary):column=Noneelse:column=agg_fn.columnifagg_fnelseNoneagg_name=type(agg_fn).__name__.title()ifagg_name=="Where":# Set the first item to be the selector column.col=agg_fn.columnifnotisinstance(agg_fn.column,rd.SpecialColumn)elseagg_fn.selector.columnvdims=sorted(params["vdims"],key=lambdax:x!=col)# TODO: Should we add prefix to all of the where columns.elifagg_name=="Summary":vdims=list(agg_fn.keys)elifcolumn:dims=[dfordinelement.dimensions('ranges')ifd==column]ifnotdims:raiseValueError("Aggregation column '{}' not found on '{}' element. ""Ensure the aggregator references an existing ""dimension.".format(column,element))ifisinstance(agg_fn,(ds.count,ds.count_cat)):ifvdim_prefix:vdim_name=f'{vdim_prefix}{column} Count'else:vdim_name=f'{column} Count'vdims=dims[0].clone(vdim_name,nodata=0)else:vdims=dims[0].clone(vdim_prefix+column)elifcategory:agg_label=f'{category}{agg_name}'vdims=Dimension(f'{vdim_prefix}{agg_label}',label=agg_label)ifagg_namein('Count','Any'):vdims.nodata=0else:vdims=Dimension(f'{vdim_prefix}{agg_name}',label=agg_name,nodata=0)params['vdims']=vdimsreturnparams
[docs]classLineAggregationOperation(AggregationOperation):line_width=param.Number(default=None,bounds=(0,None),doc=""" 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.""")
[docs]classaggregate(LineAggregationOperation):""" 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. """
[docs]@classmethoddefget_agg_data(cls,obj,category=None):""" Reduces any Overlay or NdOverlay of Elements into a single xarray Dataset that can be aggregated. """paths=[]ifisinstance(obj,Graph):obj=obj.edgepathskdims=list(obj.kdims)vdims=list(obj.vdims)dims=obj.dimensions()[:2]ifisinstance(obj,Path):glyph='line'forpinobj.split(datatype='dataframe'):paths.append(p)elifisinstance(obj,CompositeOverlay):element=Noneforkey,elinobj.data.items():x,y,element,glyph=cls.get_agg_data(el)dims=(x,y)df=PandasInterface.as_dframe(element)ifisinstance(obj,NdOverlay):df=df.assign(**dict(zip(obj.dimensions('key',True),key)))paths.append(df)ifelementisNone:dims=Noneelse:kdims+=element.kdimsvdims=element.vdimselifisinstance(obj,Element):glyph='line'ifisinstance(obj,Curve)else'points'paths.append(PandasInterface.as_dframe(obj))ifdimsisNoneorlen(dims)!=2:returnNone,None,None,Noneelse:x,y=dimsiflen(paths)>1:ifglyph=='line':path=paths[0][:1]ifisinstance(path,dd.DataFrame):path=path.compute()empty=path.copy()empty.iloc[0,:]=(np.nan,)*empty.shape[1]paths=[elemforpinpathsforelemin(p,empty)][:-1]ifall(isinstance(path,dd.DataFrame)forpathinpaths):df=dd.concat(paths)else:paths=[p.compute()ifisinstance(p,dd.DataFrame)elsepforpinpaths]df=pd.concat(paths)else:df=paths[0]ifpathselsepd.DataFrame([],columns=[x.name,y.name])ifcategoryanddf[category].dtype.name!='category':df[category]=df[category].astype('category')is_custom=isinstance(df,dd.DataFrame)orcuDFInterface.applies(df)ifany((notis_customandlen(df[d.name])andisinstance(df[d.name].values[0],cftime_types))ordf[d.name].dtype.kindin["M","u"]fordin(x,y)):df=df.copy()fordin(x,y):vals=df[d.name]ifnotis_customandlen(vals)andisinstance(vals.values[0],cftime_types):vals=cftime_to_timestamp(vals,'ns')elifvals.dtype.kind=='M':vals=vals.astype('datetime64[ns]')elifvals.dtype==np.uint64:raiseTypeError(f"Dtype of uint64 for column {d.name} is not supported.")elifvals.dtype.kind=='u':pass# To convert to int64else:continuedf[d.name]=cast_array_to_int64(vals)returnx,y,Dataset(df,kdims=kdims,vdims=vdims),glyph
def_process(self,element,key=None):agg_fn=self._get_aggregator(element,self.p.aggregator)sel_fn=getattr(self.p,"selector",None)ifhasattr(agg_fn,'cat_column'):category=agg_fn.cat_columnelse:category=agg_fn.columnifisinstance(agg_fn,ds.count_cat)elseNoneifoverlay_aggregate.applies(element,agg_fn,line_width=self.p.line_width):params=dict({p:vforp,vinself.param.values().items()ifp!='name'},dynamic=False,**{p:vforp,vinself.p.items()ifpnotin('name','dynamic')})returnoverlay_aggregate(element,**params)ifelement._plot_idinself._precomputed:x,y,data,glyph=self._precomputed[element._plot_id]else:x,y,data,glyph=self.get_agg_data(element,category)ifself.p.precompute:self._precomputed[element._plot_id]=x,y,data,glyph(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=self._get_sampling(element,x,y)((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)params=self._get_agg_params(element,x,y,agg_fn,(x0,y0,x1,y1))ifxisNoneoryisNoneorwidth==0orheight==0:returnself._empty_agg(element,x,y,width,height,xs,ys,agg_fn,**params)elifgetattr(data,"interface",None)isnotDaskInterfaceandnotlen(data):empty_val=0ifisinstance(agg_fn,ds.count)elsenp.nanxarray=xr.DataArray(np.full((height,width),empty_val),dims=[y.name,x.name],coords={x.name:xs,y.name:ys})returnself.p.element_type(xarray,**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)agg_kwargs={}ifself.p.line_widthandglyph=='line'andds_version>=Version('0.14.0'):agg_kwargs['line_width']=self.p.line_widthdfdata=PandasInterface.as_dframe(data)cvs_fn=getattr(cvs,glyph)ifsel_fn:ifisinstance(params["vdims"],(Dimension,str)):params["vdims"]=[params["vdims"]]sum_agg=ds.summary(**{str(params["vdims"][0]):agg_fn,"index":ds.where(sel_fn)})agg=self._apply_datashader(dfdata,cvs_fn,sum_agg,agg_kwargs,x,y)_ignore=[*params["vdims"],"index"]sel_vdims=[sforsinaggifsnotin_ignore]params["vdims"]=[*params["vdims"],*sel_vdims]else:agg=self._apply_datashader(dfdata,cvs_fn,agg_fn,agg_kwargs,x,y)if'x_axis'inagg.coordsand'y_axis'inagg.coords:agg=agg.rename({'x_axis':x,'y_axis':y})ifxtype=='datetime':agg[x.name]=agg[x.name].astype('datetime64[ns]')ifytype=='datetime':agg[y.name]=agg[y.name].astype('datetime64[ns]')ifisinstance(agg,xr.Dataset)oragg.ndim==2:# Replacing x and y coordinates to avoid numerical precision issueseldata=aggifds_version>Version('0.5.0')else(xs,ys,agg.data)returnself.p.element_type(eldata,**params)else:params['vdims']=list(agg.coords[agg_fn.column].data)returnImageStack(agg,**params)def_apply_datashader(self,dfdata,cvs_fn,agg_fn,agg_kwargs,x,y):# Suppress numpy warning emitted by dask:# https://github.com/dask/dask/issues/8439withwarnings.catch_warnings():warnings.filterwarnings(action='ignore',message='casting datetime64',category=FutureWarning)agg=cvs_fn(dfdata,x.name,y.name,agg_fn,**agg_kwargs)is_where_index=ds15andisinstance(agg_fn,ds.where)andisinstance(agg_fn.column,rd.SpecialColumn)is_summary_index=isinstance(agg_fn,ds.summary)and"index"inaggifis_where_indexoris_summary_index:ifis_where_index:data=agg.dataagg=agg.to_dataset(name="index")else:# summary indexdata=agg.index.dataneg1=data==-1forcolindfdata.columns:ifcolinagg.coords:continueval=dfdata[col].values[data]ifval.dtype.kind=='f':val[neg1]=np.nanelifisinstance(val.dtype,pd.CategoricalDtype):val=val.to_numpy()val[neg1]="-"elifval.dtype.kind=="O":val[neg1]="-"elifval.dtype.kind=="M":val[neg1]=np.datetime64("NaT")else:val=val.astype(np.float64)val[neg1]=np.nanagg[col]=((y.name,x.name),val)returnagg
[docs]classoverlay_aggregate(aggregate):""" 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. """@classmethoddefapplies(cls,element,agg_fn,line_width=None):return(isinstance(element,NdOverlay)and(element.typeisnotCurveorline_widthisNone)and((isinstance(agg_fn,(ds.count,ds.sum,ds.mean,ds.any))and(agg_fn.columnisNoneoragg_fn.columnnotinelement.kdims))or(isinstance(agg_fn,ds.count_cat)andagg_fn.columninelement.kdims)))def_process(self,element,key=None):agg_fn=self._get_aggregator(element,self.p.aggregator)ifnotself.applies(element,agg_fn,line_width=self.p.line_width):raiseValueError('overlay_aggregate only handles aggregation of NdOverlay types ''with count, sum or mean reduction.')# Compute overall boundsdims=element.last.dimensions()[0:2]ndims=len(dims)ifndims==1:x,y=dims[0],Noneelse:x,y=dimsinfo=self._get_sampling(element,x,y,ndims)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=info((x0,x1),(y0,y1)),_=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)agg_params=dict({k:vfork,vindict(self.param.values(),**self.p).items()ifkinaggregate.param},x_range=(x0,x1),y_range=(y0,y1))bbox=(x0,y0,x1,y1)# Optimize categorical counts by aggregating them individuallyifisinstance(agg_fn,ds.count_cat):agg_params.update(dict(dynamic=False,aggregator=ds.count()))agg_fn1=aggregate.instance(**agg_params)ifelement.ndims==1:grouped=elementelse:grouped=element.groupby([agg_fn.column],container_type=NdOverlay,group_type=NdOverlay)groups=[]fork,elingrouped.items():ifwidth==0orheight==0:agg=self._empty_agg(el,x,y,width,height,xs,ys,ds.count())groups.append((k,agg))else:agg=agg_fn1(el)groups.append((k,agg.clone(agg.data,bounds=bbox)))returngrouped.clone(groups)# Create aggregate instance for sum, count operations, breaking mean# into two aggregatescolumn=agg_fn.columnor'Count'ifisinstance(agg_fn,ds.mean):agg_fn1=aggregate.instance(**dict(agg_params,aggregator=ds.sum(column)))agg_fn2=aggregate.instance(**dict(agg_params,aggregator=ds.count()))else:agg_fn1=aggregate.instance(**agg_params)agg_fn2=Noneis_sum=isinstance(agg_fn,ds.sum)is_any=isinstance(agg_fn,ds.any)# Accumulate into two aggregates and maskagg,agg2,mask=None,None,Noneforvinelement:# Compute aggregates and masknew_agg=agg_fn1.process_element(v,None)ifis_sum:new_mask=np.isnan(new_agg.data[column].values)new_agg.data=new_agg.data.fillna(0)ifagg_fn2:new_agg2=agg_fn2.process_element(v,None)ifaggisNone:agg=new_aggifis_sum:mask=new_maskifagg_fn2:agg2=new_agg2else:ifis_any:agg.data|=new_agg.dataelse:agg.data+=new_agg.dataifis_sum:mask&=new_maskifagg_fn2:agg2.data+=new_agg2.data# Divide sum by count to compute meanifagg2isnotNone:agg2.data.rename({'Count':agg_fn.column},inplace=True)withnp.errstate(divide='ignore',invalid='ignore'):agg.data/=agg2.data# Fill masked with with NaNsifis_sum:agg.data[column].values[mask]=np.nanreturnagg.clone(bounds=bbox)
[docs]classarea_aggregate(AggregationOperation):""" 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. """def_process(self,element,key=None):x,y=element.dimensions()[:2]agg_fn=self._get_aggregator(element,self.p.aggregator)default=Noneifnotself.p.y_range:y0,y1=element.range(1)iflen(element.vdims)>1:y0,_=element.range(2)elify0>=0:y0=0elify1<=0:y1=0default=(y0,y1)ystack=element.vdims[1].nameiflen(element.vdims)>1elseNoneinfo=self._get_sampling(element,x,y,ndim=2,default=default)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=info((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)df=PandasInterface.as_dframe(element)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)params=self._get_agg_params(element,x,y,agg_fn,(x0,y0,x1,y1))ifwidth==0orheight==0:returnself._empty_agg(element,x,y,width,height,xs,ys,agg_fn,**params)agg=cvs.area(df,x.name,y.name,agg_fn,axis=0,y_stack=ystack)ifxtype=="datetime":agg[x.name]=agg[x.name].astype('datetime64[ns]')returnself.p.element_type(agg,**params)
[docs]classspread_aggregate(area_aggregate):""" Aggregates Spread elements by filling the area between the lower and upper error band. """def_process(self,element,key=None):x,y=element.dimensions()[:2]df=PandasInterface.as_dframe(element)ifdfiselement.data:df=df.copy()pos,neg=element.vdims[1:3]iflen(element.vdims)>2elseelement.vdims[1:2]*2yvals=df[y.name]df[y.name]=yvals+df[pos.name]df['_lower']=yvals-df[neg.name]area=element.clone(df,vdims=[y,'_lower']+element.vdims[3:],new_type=Area)returnsuper()._process(area,key=None)
[docs]classspikes_aggregate(LineAggregationOperation):""" 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. """spike_length=param.Number(default=None,allow_None=True,doc=""" If numeric, specifies the length of each spike, overriding the vdims values (if present).""")offset=param.Number(default=0.,doc=""" The offset of the lower end of each spike.""")def_process(self,element,key=None):agg_fn=self._get_aggregator(element,self.p.aggregator)x,y=element.kdims[0],Nonespike_length=0.5ifself.p.spike_lengthisNoneelseself.p.spike_lengthifelement.vdimsandself.p.spike_lengthisNone:x,y=element.dimensions()[:2]rename_dict={'x':x.name,'y':y.name}ifnotself.p.y_range:y0,y1=element.range(1)ify0>=0:default=(0,y1)elify1<=0:default=(y0,0)else:default=(y0,y1)else:default=Noneelse:x,y=element.kdims[0],Nonedefault=(float(self.p.offset),float(self.p.offset+spike_length))rename_dict={'x':x.name}info=self._get_sampling(element,x,y,ndim=1,default=default)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=info((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)value_cols=[]ifagg_fn.columnisNoneelse[agg_fn.column]ifyisNone:df=element.dframe([x]+value_cols).copy()y=Dimension('y')df['y0']=float(self.p.offset)df['y1']=float(self.p.offset+spike_length)yagg=['y0','y1']ifnotself.p.expand:height=1else:df=element.dframe([x,y]+value_cols).copy()df['y0']=np.array(0,df.dtypes[y.name])yagg=['y0',y.name]ifxtype=='datetime':df[x.name]=cast_array_to_int64(df[x.name].astype('datetime64[ns]'))params=self._get_agg_params(element,x,y,agg_fn,(x0,y0,x1,y1))ifwidth==0orheight==0:returnself._empty_agg(element,x,y,width,height,xs,ys,agg_fn,**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)agg_kwargs={}ifds_version>=Version('0.14.0'):agg_kwargs['line_width']=self.p.line_widthrename_dict={k:vfork,vinrename_dict.items()ifk!=v}agg=cvs.line(df,x.name,yagg,agg_fn,axis=1,**agg_kwargs).rename(rename_dict)ifxtype=="datetime":agg[x.name]=agg[x.name].astype('datetime64[ns]')returnself.p.element_type(agg,**params)
[docs]classgeom_aggregate(AggregationOperation):""" Baseclass for aggregation of Geom elements. """__abstract=Truedef_aggregate(self,cvs,df,x0,y0,x1,y1,agg):raiseNotImplementedErrordef_process(self,element,key=None):agg_fn=self._get_aggregator(element,self.p.aggregator)x0d,y0d,x1d,y1d=element.kdimsinfo=self._get_sampling(element,[x0d,x1d],[y0d,y1d],ndim=1)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=info((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)df=element.interface.as_dframe(element)ifxtype=='datetime'orytype=='datetime':df=df.copy()ifxtype=='datetime':df[x0d.name]=cast_array_to_int64(df[x0d.name].astype('datetime64[ns]'))df[x1d.name]=cast_array_to_int64(df[x1d.name].astype('datetime64[ns]'))ifytype=='datetime':df[y0d.name]=cast_array_to_int64(df[y0d.name].astype('datetime64[ns]'))df[y1d.name]=cast_array_to_int64(df[y1d.name].astype('datetime64[ns]'))ifisinstance(agg_fn,ds.count_cat)anddf[agg_fn.column].dtype.name!='category':df[agg_fn.column]=df[agg_fn.column].astype('category')params=self._get_agg_params(element,x0d,y0d,agg_fn,(x0,y0,x1,y1))ifwidth==0orheight==0:returnself._empty_agg(element,x0d,y0d,width,height,xs,ys,agg_fn,**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)agg=self._aggregate(cvs,df,x0d.name,y0d.name,x1d.name,y1d.name,agg_fn)xdim,ydim=list(agg.dims)[:2][::-1]ifxtype=="datetime":agg[xdim]=agg[xdim].astype('datetime64[ns]')ifytype=="datetime":agg[ydim]=agg[ydim].astype('datetime64[ns]')params['kdims']=[xdim,ydim]ifagg.ndim==2:# Replacing x and y coordinates to avoid numerical precision issueseldata=aggifds_version>Version('0.5.0')else(xs,ys,agg.data)returnself.p.element_type(eldata,**params)else:layers={}forcinagg.coords[agg_fn.column].data:cagg=agg.sel(**{agg_fn.column:c})eldata=caggifds_version>Version('0.5.0')else(xs,ys,cagg.data)layers[c]=self.p.element_type(eldata,**params)returnNdOverlay(layers,kdims=[element.get_dimension(agg_fn.column)])
[docs]classregrid(AggregationOperation):""" 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. """aggregator=param.ClassSelector(default=rd.mean(),class_=(rd.Reduction,rd.summary,str))expand=param.Boolean(default=False,doc=""" 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.""")interpolation=param.ObjectSelector(default='nearest',objects=['linear','nearest','bilinear',None,False],doc=""" Interpolation method""")upsample=param.Boolean(default=False,doc=""" 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.""")def_get_xarrays(self,element,coords,xtype,ytype):x,y=element.kdimsdims=[y.name,x.name]irregular=any(element.interface.irregular(element,d)fordindims)ifirregular:coord_dict={x.name:(('y','x'),coords[0]),y.name:(('y','x'),coords[1])}else:coord_dict={x.name:coords[0],y.name:coords[1]}arrays={}fori,vdinenumerate(element.vdims):ifelement.interfaceisXArrayInterface:ifelement.interface.packed(element):xarr=element.data[...,i]else:xarr=element.data[vd.name]if'datetime'in(xtype,ytype):xarr=xarr.copy()ifdims!=xarr.dimsandnotirregular:xarr=xarr.transpose(*dims)elifirregular:arr=element.dimension_values(vd,flat=False)xarr=xr.DataArray(arr,coords=coord_dict,dims=['y','x'])else:arr=element.dimension_values(vd,flat=False)xarr=xr.DataArray(arr,coords=coord_dict,dims=dims)ifxtype=="datetime":xarr[x.name]=[dt_to_int(v,'ns')forvinxarr[x.name].values]ifytype=="datetime":xarr[y.name]=[dt_to_int(v,'ns')forvinxarr[y.name].values]arrays[vd.name]=xarrreturnarraysdef_process(self,element,key=None):ifds_version<=Version('0.5.0'):raiseRuntimeError('regrid operation requires datashader>=0.6.0')# Compute coords, anges and sizex,y=element.kdimscoords=tuple(element.dimension_values(d,expanded=False)fordin[x,y])info=self._get_sampling(element,x,y)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=info# Disable upsampling by clipping size and ranges(xstart,xend),(ystart,yend)=(x_range,y_range)xspan,yspan=(xend-xstart),(yend-ystart)interp=self.p.interpolationorNoneifinterp=='bilinear':interp='linear'ifnot(self.p.upsampleorinterpisNone)andself.p.targetisNone:(x0,x1),(y0,y1)=element.range(0),element.range(1)ifisinstance(x0,datetime_types):x0,x1=dt_to_int(x0,'ns'),dt_to_int(x1,'ns')ifisinstance(y0,datetime_types):y0,y1=dt_to_int(y0,'ns'),dt_to_int(y1,'ns')exspan,eyspan=(x1-x0),(y1-y0)ifnp.isfinite(exspan)andexspan>0andxspan>0:width=max([min([int((xspan/exspan)*len(coords[0])),width]),1])else:width=0ifnp.isfinite(eyspan)andeyspan>0andyspan>0:height=max([min([int((yspan/eyspan)*len(coords[1])),height]),1])else:height=0xunit=float(xspan)/widthifwidthelse0yunit=float(yspan)/heightifheightelse0xs,ys=(np.linspace(xstart+xunit/2.,xend-xunit/2.,width),np.linspace(ystart+yunit/2.,yend-yunit/2.,height))# Compute bounds (converting datetimes)((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)params=dict(bounds=(x0,y0,x1,y1))ifwidth==0orheight==0:ifwidth==0:params['xdensity']=1ifheight==0:params['ydensity']=1returnelement.clone((xs,ys,np.zeros((height,width))),**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)# Apply regridding to each value dimensionregridded={}arrays=self._get_xarrays(element,coords,xtype,ytype)agg_fn=self._get_aggregator(element,self.p.aggregator,add_field=False)forvd,xarrinarrays.items():rarray=cvs.raster(xarr,upsample_method=interp,downsample_method=agg_fn)# Convert datetime coordinatesifxtype=="datetime":rarray[x.name]=rarray[x.name].astype('datetime64[ns]')ifytype=="datetime":rarray[y.name]=rarray[y.name].astype('datetime64[ns]')regridded[vd]=rarrayregridded=xr.Dataset(regridded)returnelement.clone(regridded,datatype=['xarray']+element.datatype,**params)
[docs]classcontours_rasterize(aggregate):""" Rasterizes the Contours element by weighting the aggregation by the iso-contour levels if a value dimension is defined, otherwise default to any aggregator. """aggregator=param.ClassSelector(default=rd.mean(),class_=(rd.Reduction,rd.summary,str))@classmethoddef_get_aggregator(cls,element,agg,add_field=True):ifnotelement.vdimsandagg.columnisNoneandnotisinstance(agg,(rd.count,rd.any)):returnds.any()returnsuper()._get_aggregator(element,agg,add_field)
[docs]classtrimesh_rasterize(aggregate):""" 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. """aggregator=param.ClassSelector(default=rd.mean(),class_=(rd.Reduction,rd.summary,str))interpolation=param.ObjectSelector(default='bilinear',objects=['bilinear','linear',None,False],doc=""" The interpolation method to apply during rasterization.""")def_precompute(self,element,agg):fromdatashader.utilsimportmeshifelement.vdimsandgetattr(agg,'column',None)notinelement.nodes.vdims:simplex_dims=[0,1,2,3]vert_dims=[0,1]elifelement.nodes.vdims:simplex_dims=[0,1,2]vert_dims=[0,1,3]else:raiseValueError("Cannot shade TriMesh without value dimension.")datatypes=[element.interface.datatype,element.nodes.interface.datatype]ifset(datatypes)=={'dask'}:dims,node_dims=element.dimensions(),element.nodes.dimensions()simplices=element.data[[dims[sd].nameforsdinsimplex_dims]]verts=element.nodes.data[[node_dims[vd].nameforvdinvert_dims]]else:if'dask'indatatypes:ifdatatypes[0]=='dask':p,n='simplexes','vertices'else:p,n='vertices','simplexes'self.param.warning(f"TriMesh {p} were provided as dask DataFrame but {n} ""were not. Datashader will not use dask to parallelize ""rasterization unless both are provided as dask ""DataFrames.")simplices=element.dframe(simplex_dims)verts=element.nodes.dframe(vert_dims)forc,dtypeinzip(simplices.columns[:3],simplices.dtypes):ifdtype.kind!='i':simplices[c]=simplices[c].astype('int')mesh=mesh(verts,simplices)ifhasattr(mesh,'persist'):mesh=mesh.persist()return{'mesh':mesh,'simplices':simplices,'vertices':verts}def_precompute_wireframe(self,element,agg):ifhasattr(element,'_wireframe'):segments=element._wireframe.dataelse:segments=connect_tri_edges_pd(element)element._wireframe=Dataset(segments,datatype=['dataframe','dask'])return{'segments':segments}def_process(self,element,key=None):ifisinstance(element,TriMesh):x,y=element.nodes.kdims[:2]else:x,y=element.kdimsinfo=self._get_sampling(element,x,y)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=infoagg=self.p.aggregatorinterp=self.p.interpolationorNoneprecompute=self.p.precomputeifinterp=='linear':interp='bilinear'wireframe=Falseif(not(element.vdimsor(isinstance(element,TriMesh)andelement.nodes.vdims)))andds_version<=Version('0.6.9'):self.p.aggregator=ds.any()ifisinstance(agg,ds.any)oragg=='any'elseds.count()returnaggregate._process(self,element,key)elif((notinterpand(isinstance(agg,(ds.any,ds.count))oraggin['any','count']))ornot(element.vdimsorelement.nodes.vdims)):wireframe=Trueprecompute=False# TriMesh itself caches wireframeifisinstance(agg,(ds.any,ds.count)):agg=self._get_aggregator(element,self.p.aggregator)else:agg=ds.any()elifgetattr(agg,'column',None)isNone:agg=self._get_aggregator(element,self.p.aggregator)ifelement._plot_idinself._precomputed:precomputed=self._precomputed[element._plot_id]elifwireframe:precomputed=self._precompute_wireframe(element,agg)else:precomputed=self._precompute(element,agg)bounds=(x_range[0],y_range[0],x_range[1],y_range[1])params=self._get_agg_params(element,x,y,agg,bounds)ifwidth==0orheight==0:ifwidth==0:params['xdensity']=1ifheight==0:params['ydensity']=1returnImage((xs,ys,np.zeros((height,width))),**params)ifwireframe:segments=precomputed['segments']else:simplices=precomputed['simplices']pts=precomputed['vertices']mesh=precomputed['mesh']ifprecompute:self._precomputed={element._plot_id:precomputed}cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)ifwireframe:rename_dict={k:vfork,vinzip("xy",(x.name,y.name))ifk!=v}agg=cvs.line(segments,x=['x0','x1','x2','x0'],y=['y0','y1','y2','y0'],axis=1,agg=agg).rename(rename_dict)else:interpolate=bool(self.p.interpolation)agg=cvs.trimesh(pts,simplices,agg=agg,interp=interpolate,mesh=mesh)returnImage(agg,**params)
[docs]classquadmesh_rasterize(trimesh_rasterize):""" Rasterize the QuadMesh element using the supplied aggregator. Simply converts to a TriMesh and lets trimesh_rasterize handle the actual rasterization. """def_precompute(self,element,agg):ifds_version<=Version('0.7.0'):returnsuper()._precompute(element.trimesh(),agg)def_process(self,element,key=None):ifds_version<=Version('0.7.0'):returnsuper()._process(element,key)ifelement.interface.datatype!='xarray':element=element.clone(datatype=['xarray'])data=element.datax,y=element.kdimsagg_fn=self._get_aggregator(element,self.p.aggregator)info=self._get_sampling(element,x,y)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=infoifxtype=='datetime':data[x.name]=data[x.name].astype('datetime64[ns]').astype('int64')ifytype=='datetime':data[y.name]=data[y.name].astype('datetime64[ns]').astype('int64')# Compute bounds (converting datetimes)((x0,x1),(y0,y1)),(xs,ys)=self._dt_transform(x_range,y_range,xs,ys,xtype,ytype)params=dict(get_param_values(element),datatype=['xarray'],bounds=(x0,y0,x1,y1))ifwidth==0orheight==0:returnself._empty_agg(element,x,y,width,height,xs,ys,agg_fn,**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)vdim=getattr(agg_fn,'column',element.vdims[0].name)agg=cvs.quadmesh(data[vdim],x.name,y.name,agg_fn)xdim,ydim=list(agg.dims)[:2][::-1]ifxtype=="datetime":agg[xdim]=agg[xdim].astype('datetime64[ns]')ifytype=="datetime":agg[ydim]=agg[ydim].astype('datetime64[ns]')returnImage(agg,**params)
[docs]classshade(LinkableOperation):""" 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. """alpha=param.Integer(default=255,bounds=(0,255),doc=""" 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.""")cmap=param.ClassSelector(class_=(Iterable,Callable,dict),doc=""" 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.""")color_key=param.ClassSelector(class_=(Iterable,Callable,dict),doc=""" 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.""")cnorm=param.ClassSelector(default='eq_hist',class_=(str,Callable),doc=""" 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.""")clims=param.NumericTuple(default=None,length=2,doc=""" Min and max data values to use for colormap interpolation, when wishing to override autoranging. """)min_alpha=param.Number(default=40,bounds=(0,255),doc=""" 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..""")rescale_discrete_levels=param.Boolean(default=True,doc=""" 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.""")
[docs]@classmethoddefconcatenate(cls,overlay):""" Concatenates an NdOverlay of Image types into a single 3D xarray Dataset. """ifnotisinstance(overlay,NdOverlay):raiseValueError('Only NdOverlays can be concatenated')xarr=xr.concat([v.data.transpose()forvinoverlay.values()],pd.Index(overlay.keys(),name=overlay.kdims[0].name))params=dict(get_param_values(overlay.last),vdims=overlay.last.vdims,kdims=overlay.kdims+overlay.last.kdims)returnDataset(xarr.transpose(),datatype=['xarray'],**params)
[docs]@classmethoddefuint32_to_uint8(cls,img):""" Cast uint32 RGB image to 4 uint8 channels. """returnnp.flipud(img.view(dtype=np.uint8).reshape(img.shape+(4,)))
[docs]@classmethoddefuint32_to_uint8_xr(cls,img):""" Cast uint32 xarray DataArray to 4 uint8 channels. """new_array=img.values.view(dtype=np.uint8).reshape(img.shape+(4,))coords=dict(list(img.coords.items())+[('band',[0,1,2,3])])returnxr.DataArray(new_array,coords=coords,dims=img.dims+('band',))
[docs]@classmethoddefrgb2hex(cls,rgb):""" Convert RGB(A) tuple to hex. """iflen(rgb)>3:rgb=rgb[:-1]return"#{:02x}{:02x}{:02x}".format(*(int(v*255)forvinrgb))
@classmethoddefto_xarray(cls,element):ifissubclass(element.interface,XArrayInterface):returnelementdata=tuple(element.dimension_values(kd,expanded=False)forkdinelement.kdims)vdims=list(element.vdims)# Override nodata temporarilyelement.vdims[:]=[vd.clone(nodata=None)forvdinelement.vdims]try:data+=tuple(element.dimension_values(vd,flat=False)forvdinelement.vdims)finally:element.vdims[:]=vdimsdtypes=[dtfordtinelement.datatypeifdt!='xarray']returnelement.clone(data,datatype=['xarray']+dtypes,bounds=element.bounds,xdensity=element.xdensity,ydensity=element.ydensity)def_process(self,element,key=None):element=element.map(self.to_xarray,Image)ifisinstance(element,NdOverlay):bounds=element.last.boundsxdensity=element.last.xdensityydensity=element.last.ydensityelement=self.concatenate(element)elifisinstance(element,Overlay):returnelement.map(partial(shade._process,self),[Element])else:xdensity=element.xdensityydensity=element.ydensitybounds=element.boundskdims=element.kdimsifisinstance(element,ImageStack):vdim=element.vdimsarray=element.dataifhasattr(array,"to_array"):array=array.to_array("z")array=array.transpose(*[kdim.nameforkdiminkdims],...)else:vdim=element.vdims[0].namearray=element.data[vdim]shade_opts=dict(how=self.p.cnorm,min_alpha=self.p.min_alpha,alpha=self.p.alpha)ifds_version>=Version('0.14.0'):shade_opts['rescale_discrete_levels']=self.p.rescale_discrete_levels# Compute shading options depending on whether# it is a categorical or regular aggregateifelement.ndims>2orisinstance(element,ImageStack):kdims=element.kdimsifisinstance(element,ImageStack)elseelement.kdims[1:]categories=array.shape[-1]ifnotself.p.color_key:passelifisinstance(self.p.color_key,dict):shade_opts['color_key']=self.p.color_keyelifisinstance(self.p.color_key,Iterable):shade_opts['color_key']=[cfor_,cinzip(range(categories),self.p.color_key)]else:colors=[self.p.color_key(s)forsinnp.linspace(0,1,categories)]shade_opts['color_key']=map(self.rgb2hex,colors)elifnotself.p.cmap:passelifisinstance(self.p.cmap,Callable):colors=[self.p.cmap(s)forsinnp.linspace(0,1,256)]shade_opts['cmap']=map(self.rgb2hex,colors)elifisinstance(self.p.cmap,str):ifself.p.cmap.startswith('#')orself.p.cmapincolor_lookup:shade_opts['cmap']=self.p.cmapelse:from..plotting.utilimportprocess_cmapshade_opts['cmap']=process_cmap(self.p.cmap)else:shade_opts['cmap']=self.p.cmapifself.p.clims:shade_opts['span']=self.p.climselifds_version>Version('0.5.0')andself.p.cnorm!='eq_hist':shade_opts['span']=element.range(vdim)params=dict(get_param_values(element),kdims=kdims,bounds=bounds,vdims=RGB.vdims[:],xdensity=xdensity,ydensity=ydensity)withwarnings.catch_warnings():warnings.filterwarnings('ignore',r'invalid value encountered in true_divide')ifnp.isnan(array.data).all():xd,yd=kdims[:2]arr=np.zeros(array.data.shape[:2]+(4,),dtype=np.uint8)coords={xd.name:element.data.coords[xd.name],yd.name:element.data.coords[yd.name],'band':[0,1,2,3]}img=xr.DataArray(arr,coords=coords,dims=(yd.name,xd.name,'band'))returnRGB(img,**params)else:img=tf.shade(array,**shade_opts)returnRGB(self.uint32_to_uint8_xr(img),**params)
[docs]classgeometry_rasterize(LineAggregationOperation):""" Rasterizes geometries by converting them to spatialpandas. """aggregator=param.ClassSelector(default=rd.mean(),class_=(rd.Reduction,rd.summary,str))@classmethoddef_get_aggregator(cls,element,agg,add_field=True):if(not(element.vdimsorisinstance(agg,str))andagg.columnisNoneandnotisinstance(agg,(rd.count,rd.any))):returnds.count()returnsuper()._get_aggregator(element,agg,add_field)def_process(self,element,key=None):agg_fn=self._get_aggregator(element,self.p.aggregator)xdim,ydim=element.kdimsinfo=self._get_sampling(element,xdim,ydim)(x_range,y_range),(xs,ys),(width,height),(xtype,ytype)=infox0,x1=x_rangey0,y1=y_rangeparams=self._get_agg_params(element,xdim,ydim,agg_fn,(x0,y0,x1,y1))ifwidth==0orheight==0:returnself._empty_agg(element,xdim,ydim,width,height,xs,ys,agg_fn,**params)cvs=ds.Canvas(plot_width=width,plot_height=height,x_range=x_range,y_range=y_range)ifelement._plot_idinself._precomputed:data,col=self._precomputed[element._plot_id]else:if'spatialpandas'notinelement.interface.datatype:element=element.clone(datatype=['spatialpandas'])data=element.datacol=element.interface.geo_column(data)ifself.p.precompute:self._precomputed[element._plot_id]=(data,col)ifisinstance(agg_fn,ds.count_cat)anddata[agg_fn.column].dtype.name!='category':data[agg_fn.column]=data[agg_fn.column].astype('category')agg_kwargs=dict(geometry=col,agg=agg_fn)ifisinstance(element,Polygons):agg=cvs.polygons(data,**agg_kwargs)elifisinstance(element,Path):ifself.p.line_widthandds_version>=Version('0.14.0'):agg_kwargs['line_width']=self.p.line_widthagg=cvs.line(data,**agg_kwargs)elifisinstance(element,Points):agg=cvs.points(data,**agg_kwargs)rename_dict={k:vfork,vinzip("xy",(xdim.name,ydim.name))ifk!=v}agg=agg.rename(rename_dict)ifagg.ndim==2:returnself.p.element_type(agg,**params)else:layers={}forcinagg.coords[agg_fn.column].data:cagg=agg.sel(**{agg_fn.column:c})layers[c]=self.p.element_type(cagg,**params)returnNdOverlay(layers,kdims=[element.get_dimension(agg_fn.column)])
[docs]classrasterize(AggregationOperation):""" 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. """aggregator=param.ClassSelector(class_=(rd.Reduction,rd.summary,str),default='default')interpolation=param.ObjectSelector(default='default',objects=['default','linear','nearest','bilinear',None,False],doc=""" The interpolation method to apply during rasterization. Default depends on element type""")_transforms=[(Image,regrid),(Polygons,geometry_rasterize),(lambdax:(isinstance(x,(Path,Points))and'spatialpandas'inx.interface.datatype),geometry_rasterize),(TriMesh,trimesh_rasterize),(QuadMesh,quadmesh_rasterize),(lambdax:(isinstance(x,NdOverlay)andissubclass(x.type,(Scatter,Points,Curve,Path))),aggregate),(Spikes,spikes_aggregate),(Area,area_aggregate),(Spread,spread_aggregate),(Segments,segments_aggregate),(Rectangles,rectangle_aggregate),(Contours,contours_rasterize),(Graph,aggregate),(Scatter,aggregate),(Points,aggregate),(Curve,aggregate),(Path,aggregate),(type(None),shade)# To handle parameters of datashade]__instance_params=set()__instance_kwargs={}
def_process(self,element,key=None):# Potentially needs traverse to find element types first?all_allowed_kws=set()all_supplied_kws=set()instance_params=dict(self.__instance_kwargs,**{k:getattr(self,k)forkinself.__instance_params})forpredicate,transforminself._transforms:merged_param_values=dict(instance_params,**self.p)# If aggregator or interpolation are 'default', pop parameter so# datashader can choose the default aggregator itselfforkin['aggregator','interpolation']:ifmerged_param_values.get(k,None)=='default':merged_param_values.pop(k)op_params=dict({k:vfork,vinmerged_param_values.items()ifnot(visNoneandk=='aggregator')},dynamic=False)extended_kws=dict(op_params,**self.p.extra_keywords())all_supplied_kws|=set(extended_kws)all_allowed_kws|=set(transform.param)# Collect union set of consumed. Versus union of available.op=transform.instance(**{k:vfork,vinextended_kws.items()ifkintransform.param})op._precomputed=self._precomputedelement=element.map(op,predicate)self._precomputed=op._precomputedunused_params=list(all_supplied_kws-all_allowed_kws)ifunused_params:self.param.warning('Parameter(s) [%s] not consumed by any element rasterizer.'%', '.join(unused_params))returnelement
[docs]classdatashade(rasterize,shade):""" 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. """def_process(self,element,key=None):agg=rasterize._process(self,element,key)shaded=shade._process(self,agg,key)returnshaded
[docs]classstack(Operation):""" The stack operation allows compositing multiple RGB Elements using the defined compositing operator. """compositor=param.ObjectSelector(objects=['add','over','saturate','source'],default='over',doc=""" Defines how the compositing operation combines the images""")defuint8_to_uint32(self,element):img=np.dstack([element.dimension_values(d,flat=False)fordinelement.vdims])ifimg.shape[2]==3:# alpha channel not includedalpha=np.ones(img.shape[:2])ifimg.dtype.name=='uint8':alpha=(alpha*255).astype('uint8')img=np.dstack([img,alpha])ifimg.dtype.name!='uint8':img=(img*255).astype(np.uint8)N,M,_=img.shapereturnimg.view(dtype=np.uint32).reshape((N,M))def_process(self,overlay,key=None):ifnotisinstance(overlay,CompositeOverlay):returnoverlayeliflen(overlay)==1:returnoverlay.lastifisinstance(overlay,NdOverlay)elseoverlay.get(0)imgs=[]forrgbinoverlay:ifnotisinstance(rgb,RGB):raiseTypeError("The stack operation expects elements of type RGB, ""not '%s'."%type(rgb).__name__)rgb=rgb.rgbdims=[kd.nameforkdinrgb.kdims][::-1]coords={kd.name:rgb.dimension_values(kd,False)forkdinrgb.kdims}imgs.append(tf.Image(self.uint8_to_uint32(rgb),coords=coords,dims=dims))try:imgs=xr.align(*imgs,join='exact')exceptValueErrorase:raiseValueError('RGB inputs to the stack operation could not be aligned; ''ensure they share the same grid sampling.')fromestacked=tf.stack(*imgs,how=self.p.compositor)arr=shade.uint32_to_uint8(stacked.data)[::-1]data=(coords[dims[1]],coords[dims[0]],arr[:,:,0],arr[:,:,1],arr[:,:,2])ifarr.shape[-1]==4:data=data+(arr[:,:,3],)returnrgb.clone(data,datatype=[rgb.interface.datatype]+rgb.datatype)
[docs]classSpreadingOperation(LinkableOperation):""" 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. """how=param.ObjectSelector(default='source'ifds_version<=Version('0.11.1')elseNone,objects=[None,'source','over','saturate','add','max','min'],doc=""" 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.""")shape=param.ObjectSelector(default='circle',objects=['circle','square'],doc=""" The shape to spread by. Options are 'circle' [default] or 'square'.""")_per_element=True@classmethoddefuint8_to_uint32(cls,img):shape=img.shapeflat_shape=np.multiply.reduce(shape[:2])ifshape[-1]==3:img=np.dstack([img,np.ones(shape[:2],dtype='uint8')*255])rgb=img.reshape((flat_shape,4)).view('uint32').reshape(shape[:2])returnrgbdef_apply_spreading(self,array):"""Apply the spread function using the indicated parameters."""raiseNotImplementedErrordef_preprocess_rgb(self,element):rgbarray=np.dstack([element.dimension_values(vd,flat=False)forvdinelement.vdims])ifrgbarray.dtype.kind=='f':rgbarray=rgbarray*255returntf.Image(self.uint8_to_uint32(rgbarray.astype('uint8')))def_process(self,element,key=None):ifisinstance(element,RGB):rgb=element.rgbdata=self._preprocess_rgb(rgb)elifisinstance(element,Image):data=element.clone(datatype=['xarray']).data[element.vdims[0].name]else:raiseValueError('spreading can only be applied to Image or RGB Elements. ''Received object of type %s'%str(type(element)))kwargs={}array=self._apply_spreading(data)ifisinstance(element,RGB):img=datashade.uint32_to_uint8(array.data)[::-1]new_data={kd.name:rgb.dimension_values(kd,expanded=False)forkdinrgb.kdims}vdims=rgb.vdims+[rgb.alpha_dimension]iflen(rgb.vdims)==3elsergb.vdimskwargs['vdims']=vdimsnew_data[tuple(vd.nameforvdinvdims)]=imgelse:new_data=arrayreturnelement.clone(new_data,xdensity=element.xdensity,ydensity=element.ydensity,**kwargs)
[docs]classspread(SpreadingOperation):""" 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 """px=param.Integer(default=1,doc=""" Number of pixels to spread on all sides.""")def_apply_spreading(self,array):returntf.spread(array,px=self.p.px,how=self.p.how,shape=self.p.shape)
[docs]classdynspread(SpreadingOperation):""" 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 """max_px=param.Integer(default=3,doc=""" Maximum number of pixels to spread on all sides.""")threshold=param.Number(default=0.5,bounds=(0,1),doc=""" 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.""")def_apply_spreading(self,array):returntf.dynspread(array,max_px=self.p.max_px,threshold=self.p.threshold,how=self.p.how,shape=self.p.shape)
[docs]defsplit_dataframe(path_df):""" Splits a dataframe of paths separated by NaNs into individual dataframes. """splits=np.where(path_df.iloc[:,0].isnull())[0]+1return[dffordfinnp.split(path_df,splits)iflen(df)>1]
class_connect_edges(Operation):split=param.Boolean(default=False,doc=""" Determines whether bundled edges will be split into individual edges or concatenated with NaN separators.""")def_bundle(self,position_df,edges_df):raiseNotImplementedError('_connect_edges is an abstract baseclass ''and does not implement any actual bundling.')def_process(self,element,key=None):index=element.nodes.kdims[2].namerename_edges={d.name:vford,vinzip(element.kdims[:2],['source','target'])}rename_nodes={d.name:vford,vinzip(element.nodes.kdims[:2],['x','y'])}position_df=element.nodes.redim(**rename_nodes).dframe([0,1,2]).set_index(index)edges_df=element.redim(**rename_edges).dframe([0,1])paths=self._bundle(position_df,edges_df)paths=paths.rename(columns={v:kfork,vinrename_nodes.items()})paths=split_dataframe(paths)ifself.p.splitelse[paths]returnelement.clone((element.data,element.nodes,paths))
[docs]classbundle_graph(_connect_edges,hammer_bundle):""" 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. """def_bundle(self,position_df,edges_df):fromdatashader.bundlingimporthammer_bundlereturnhammer_bundle.__call__(self,position_df,edges_df,**self.p)
[docs]classdirectly_connect_edges(_connect_edges,connect_edges):""" Given a Graph object will directly connect all nodes. """def_bundle(self,position_df,edges_df):returnconnect_edges.__call__(self,position_df,edges_df)
defidentity(x):returnx
[docs]classinspect_mask(Operation):""" 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. """pixels=param.Integer(default=3,doc=""" Size of the mask that should match the pixels parameter used in the associated inspection operation.""")streams=param.ClassSelector(default=[PointerXY],class_=(dict,list))x=param.Number(default=0)y=param.Number(default=0)@classmethoddef_distance_args(cls,element,x_range,y_range,pixels):ycount,xcount=element.interface.shape(element,gridded=True)x_delta=abs(x_range[1]-x_range[0])/xcounty_delta=abs(y_range[1]-y_range[0])/ycountreturn(x_delta*pixels,y_delta*pixels)def_process(self,raster,key=None):ifisinstance(raster,RGB):raster=raster[...,raster.vdims[-1]]x_range,y_range=raster.range(0),raster.range(1)xdelta,ydelta=self._distance_args(raster,x_range,y_range,self.p.pixels)x,y=self.p.x,self.p.yreturnself._indicator(raster.kdims,x,y,xdelta,ydelta)def_indicator(self,kdims,x,y,xdelta,ydelta):rect=np.array([(x-xdelta/2,y-ydelta/2),(x+xdelta/2,y-ydelta/2),(x+xdelta/2,y+ydelta/2),(x-xdelta/2,y+ydelta/2)])data={(str(kdims[0]),str(kdims[1])):rect}returnPolygons(data,kdims=kdims)
[docs]classinspect(Operation):""" Generalized inspect operation that detects the appropriate indicator type. """pixels=param.Integer(default=3,doc=""" 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.""")null_value=param.Number(default=0,doc=""" 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.""")value_bounds=param.NumericTuple(default=None,length=2,allow_None=True,doc=""" 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.""")hits=param.DataFrame(default=pd.DataFrame(),allow_None=True)max_indicators=param.Integer(default=1,doc=""" 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.""")transform=param.Callable(default=identity,doc=""" 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.""")# Stream values and overridesstreams=param.ClassSelector(default=dict(x=PointerXY.param.x,y=PointerXY.param.y),class_=(dict,list))x=param.Number(default=0,doc="x-position to inspect.")y=param.Number(default=0,doc="y-position to inspect.")_dispatch={}@propertydefmask(self):returninspect_mask.instance(pixels=self.p.pixels)def_update_hits(self,event):self.hits=event.obj.hits
def_process(self,raster,key=None):input_type=self._get_input_type(raster.pipeline.operations)inspect_operation=self._dispatch[input_type]ifself._opisNone:self._op=inspect_operation.instance()self._op.param.watch(self._update_hits,'hits')elifnotisinstance(self._op,inspect_operation):raiseValueError("Cannot reuse inspect instance on different ""datashader input type.")self._op.p=self.preturnself._op._process(raster)def_get_input_type(self,operations):foropinoperations:output_type=getattr(op,'output_type',None)ifoutput_typeisnotNone:ifoutput_typein[el[0]forelinrasterize._transforms]:# Datashader output types that are also input types e.g for regridifissubclass(output_type,(Image,RGB)):continuereturnoutput_typeraiseRuntimeError('Could not establish input element type ''for datashader pipeline in the inspect operation.')
[docs]classinspect_base(inspect):""" Given datashaded aggregate (Image) output, return a set of (hoverable) points sampled from those near the cursor. """def_process(self,raster,key=None):self._validate(raster)ifisinstance(raster,RGB):raster=raster[...,raster.vdims[-1]]x_range,y_range=raster.range(0),raster.range(1)xdelta,ydelta=self._distance_args(raster,x_range,y_range,self.p.pixels)x,y=self.p.x,self.p.yval=raster[x-xdelta:x+xdelta,y-ydelta:y+ydelta].reduce(function=np.nansum)ifnp.isnan(val):val=self.p.null_valueif((self.p.value_boundsandnot(self.p.value_bounds[0]<val<self.p.value_bounds[1]))orval==self.p.null_value):result=self._empty_df(raster.dataset)else:masked=self._mask_dataframe(raster,x,y,xdelta,ydelta)result=self._sort_by_distance(raster,masked,x,y)self.hits=resultdf=self.p.transform(result)returnself._element(raster,df.iloc[:self.p.max_indicators])@classmethoddef_distance_args(cls,element,x_range,y_range,pixels):ycount,xcount=element.interface.shape(element,gridded=True)x_delta=abs(x_range[1]-x_range[0])/xcounty_delta=abs(y_range[1]-y_range[0])/ycountreturn(x_delta*pixels,y_delta*pixels)@classmethoddef_empty_df(cls,dataset):if'dask'indataset.interface.datatype:returndataset.data._meta.iloc[:0]elifdataset.interface.datatypein['pandas','geopandas','spatialpandas']:returndataset.data.head(0)returndataset.iloc[:0].dframe()@classmethoddef_mask_dataframe(cls,raster,x,y,xdelta,ydelta):""" Mask the dataframe around the specified x and y position with the given x and y deltas """ds=raster.datasetx0,x1,y0,y1=x-xdelta,x+xdelta,y-ydelta,y+ydeltaif'spatialpandas'inds.interface.datatype:df=ds.data.cx[x0:x1,y0:y1]returndf.compute()ifhasattr(df,'compute')elsedfxdim,ydim=raster.kdimsquery={xdim.name:(x0,x1),ydim.name:(y0,y1)}returnds.select(**query).dframe()@classmethoddef_validate(cls,raster):pass@classmethoddef_vdims(cls,raster,df):ds=raster.datasetif'spatialpandas'inds.interface.datatype:coords=[ds.interface.geo_column(ds.data)]else:coords=[kd.nameforkdinraster.kdims]return[colforcolindf.columnsifcolnotincoords]
[docs]classinspect_points(inspect_base):@classmethoddef_element(cls,raster,df):returnPoints(df,kdims=raster.kdims,vdims=cls._vdims(raster,df))@classmethoddef_sort_by_distance(cls,raster,df,x,y):""" Returns a dataframe of hits within a given mask around a given spatial location, sorted by distance from that location. """ds=raster.dataset.clone(df)xs,ys=(ds.dimension_values(kd)forkdinraster.kdims)dx,dy=xs-x,ys-ydistances=pd.Series(dx*dx+dy*dy)returndf.iloc[distances.argsort().values]
[docs]classinspect_polygons(inspect_base):@classmethoddef_validate(cls,raster):if'spatialpandas'notinraster.dataset.interface.datatype:raiseValueError("inspect_polygons only supports spatialpandas datatypes.")@classmethoddef_element(cls,raster,df):polygons=Polygons(df,kdims=raster.kdims,vdims=cls._vdims(raster,df))ifStore.loaded_backends()!=[]:returnpolygons.opts(color_index=None)else:returnpolygons@classmethoddef_sort_by_distance(cls,raster,df,x,y):""" Returns a dataframe of hits within a given mask around a given spatial location, sorted by distance from that location. """xs,ys=[],[]forgeomindf.geometry.array:gxs,gys=geom.flat_values[::2],geom.flat_values[1::2]ifnotlen(gxs):xs.append(np.nan)ys.append(np.nan)else:xs.append((np.min(gxs)+np.max(gxs))/2)ys.append((np.min(gys)+np.max(gys))/2)dx,dy=np.array(xs)-x,np.array(ys)-ydistances=pd.Series(dx*dx+dy*dy)returndf.iloc[distances.argsort().values]