-
-
Notifications
You must be signed in to change notification settings - Fork 394
/
datashader.py
2035 lines (1713 loc) · 81.3 KB
/
datashader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
from collections.abc import Callable, Iterable
from functools import partial
import dask.dataframe as dd
import datashader as ds
import datashader.reductions as rd
import datashader.transfer_functions as tf
import numpy as np
import pandas as pd
import param
import xarray as xr
from datashader.colors import color_lookup
from packaging.version import Version
from param.parameterized import bothmethod
try:
from datashader.bundling import (
directly_connect_edges as connect_edges,
hammer_bundle,
)
except ImportError:
hammer_bundle, connect_edges = object, object
from ..core import (
CompositeOverlay,
Dimension,
Element,
NdOverlay,
Operation,
Overlay,
Store,
)
from ..core.data import (
DaskInterface,
Dataset,
PandasInterface,
XArrayInterface,
cuDFInterface,
)
from ..core.util import (
cast_array_to_int64,
cftime_to_timestamp,
cftime_types,
datetime_types,
dt_to_int,
get_param_values,
)
from ..element import (
RGB,
Area,
Contours,
Curve,
Graph,
Image,
ImageStack,
Path,
Points,
Polygons,
QuadMesh,
Rectangles,
Scatter,
Segments,
Spikes,
Spread,
TriMesh,
)
from ..element.util import connect_tri_edges_pd
from ..streams import PointerXY
from .resample import LinkableOperation, ResampleOperation2D
ds_version = Version(ds.__version__)
ds15 = ds_version >= Version('0.15.1')
ds16 = ds_version >= Version('0.16.0')
class AggregationOperation(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
}
@classmethod
def _get_aggregator(cls, element, agg, add_field=True):
if ds15:
agg_types = (rd.count, rd.any, rd.where)
else:
agg_types = (rd.count, rd.any)
if isinstance(agg, str):
if agg not in cls._agg_methods:
agg_methods = sorted(cls._agg_methods)
raise ValueError(f"Aggregation method '{agg!r}' is not known; "
f"aggregator must be one of: {agg_methods!r}")
if agg == 'count_cat':
agg = cls._agg_methods[agg]('__temp__')
else:
agg = cls._agg_methods[agg]()
elements = element.traverse(lambda x: x, [Element])
if (add_field and getattr(agg, 'column', False) in ('__temp__', None) and
not isinstance(agg, agg_types)):
if not elements:
raise ValueError('Could not find any elements to apply '
f'{cls.__name__} operation to.')
inner_element = elements[0]
if isinstance(inner_element, TriMesh) and inner_element.nodes.vdims:
field = inner_element.nodes.vdims[0].name
elif inner_element.vdims:
field = inner_element.vdims[0].name
elif isinstance(element, NdOverlay):
field = element.kdims[0].name
else:
raise ValueError("Could not determine dimension to apply "
f"'{cls.__name__}' operation to. Declare the dimension "
"to aggregate as part of the datashader "
"aggregator.")
agg = type(agg)(field)
return agg
def _empty_agg(self, element, x, y, width, height, xs, ys, agg_fn, **params):
x = x.name if x else 'x'
y = y.name if x else 'y'
xarray = xr.DataArray(np.full((height, width), np.nan),
dims=[y, x], coords={x: xs, y: ys})
if width == 0:
params['xdensity'] = 1
if height == 0:
params['ydensity'] = 1
el = self.p.element_type(xarray, **params)
if isinstance(agg_fn, ds.count_cat):
vals = element.dimension_values(agg_fn.column, expanded=False)
dim = element.get_dimension(agg_fn.column)
return NdOverlay({v: el for v in vals}, dim)
return el
def _get_agg_params(self, element, x, y, agg_fn, bounds):
params = dict(get_param_values(element), kdims=[x, y],
datatype=['xarray'], bounds=bounds)
if self.vdim_prefix:
kdim_list = '_'.join(str(kd) for kd in params['kdims'])
vdim_prefix = self.vdim_prefix.format(kdims=kdim_list)
else:
vdim_prefix = ''
category = None
if hasattr(agg_fn, 'reduction'):
category = agg_fn.cat_column
agg_fn = agg_fn.reduction
if isinstance(agg_fn, rd.summary):
column = None
else:
column = agg_fn.column if agg_fn else None
agg_name = type(agg_fn).__name__.title()
if agg_name == "Where":
# Set the first item to be the selector column.
col = agg_fn.column if not isinstance(agg_fn.column, rd.SpecialColumn) else agg_fn.selector.column
vdims = sorted(params["vdims"], key=lambda x: x != col)
# TODO: Should we add prefix to all of the where columns.
elif agg_name == "Summary":
vdims = list(agg_fn.keys)
elif column:
dims = [d for d in element.dimensions('ranges') if d == column]
if not dims:
raise ValueError(
f"Aggregation column '{column}' not found on '{element}' element. "
"Ensure the aggregator references an existing dimension."
)
if isinstance(agg_fn, (ds.count, ds.count_cat)):
if vdim_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)
elif category:
agg_label = f'{category} {agg_name}'
vdims = Dimension(f'{vdim_prefix}{agg_label}', label=agg_label)
if agg_name in ('Count', 'Any'):
vdims.nodata = 0
else:
vdims = Dimension(f'{vdim_prefix}{agg_name}', label=agg_name, nodata=0)
params['vdims'] = vdims
return params
class LineAggregationOperation(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.""")
class aggregate(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.
"""
@classmethod
def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths
kdims = list(obj.kdims)
vdims = list(obj.vdims)
dims = obj.dimensions()[:2]
if isinstance(obj, Path):
glyph = 'line'
for p in obj.split(datatype='dataframe'):
paths.append(p)
elif isinstance(obj, CompositeOverlay):
element = None
for key, el in obj.data.items():
x, y, element, glyph = cls.get_agg_data(el)
dims = (x, y)
df = PandasInterface.as_dframe(element)
if isinstance(obj, NdOverlay):
df = df.assign(**dict(zip(obj.dimensions('key', True), key)))
paths.append(df)
if element is None:
dims = None
else:
kdims += element.kdims
vdims = element.vdims
elif isinstance(obj, Element):
glyph = 'line' if isinstance(obj, Curve) else 'points'
paths.append(PandasInterface.as_dframe(obj))
if dims is None or len(dims) != 2:
return None, None, None, None
else:
x, y = dims
if len(paths) > 1:
if glyph == 'line':
path = paths[0][:1]
if isinstance(path, dd.DataFrame):
path = path.compute()
empty = path.copy()
empty.iloc[0, :] = (np.nan,) * empty.shape[1]
paths = [elem for p in paths for elem in (p, empty)][:-1]
if all(isinstance(path, dd.DataFrame) for path in paths):
df = dd.concat(paths)
else:
paths = [p.compute() if isinstance(p, dd.DataFrame) else p for p in paths]
df = pd.concat(paths)
else:
df = paths[0] if paths else pd.DataFrame([], columns=[x.name, y.name])
if category and df[category].dtype.name != 'category':
df[category] = df[category].astype('category')
is_custom = isinstance(df, dd.DataFrame) or cuDFInterface.applies(df)
if any((not is_custom and len(df[d.name]) and isinstance(df[d.name].values[0], cftime_types)) or
df[d.name].dtype.kind in ["M", "u"] for d in (x, y)):
df = df.copy()
for d in (x, y):
vals = df[d.name]
if not is_custom and len(vals) and isinstance(vals.values[0], cftime_types):
vals = cftime_to_timestamp(vals, 'ns')
elif vals.dtype.kind == 'M':
vals = vals.astype('datetime64[ns]')
elif vals.dtype == np.uint64:
raise TypeError(f"Dtype of uint64 for column {d.name} is not supported.")
elif vals.dtype.kind == 'u':
pass # To convert to int64
else:
continue
df[d.name] = cast_array_to_int64(vals)
return x, 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)
if hasattr(agg_fn, 'cat_column'):
category = agg_fn.cat_column
else:
category = agg_fn.column if isinstance(agg_fn, ds.count_cat) else None
if overlay_aggregate.applies(element, agg_fn, line_width=self.p.line_width):
params = dict(
{p: v for p, v in self.param.values().items() if p != 'name'},
dynamic=False, **{p: v for p, v in self.p.items()
if p not in ('name', 'dynamic')})
return overlay_aggregate(element, **params)
if element._plot_id in self._precomputed:
x, y, data, glyph = self._precomputed[element._plot_id]
else:
x, y, data, glyph = self.get_agg_data(element, category)
if self.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))
if x is None or y is None or width == 0 or height == 0:
return self._empty_agg(element, x, y, width, height, xs, ys, agg_fn, **params)
elif getattr(data, "interface", None) is not DaskInterface and not len(data):
empty_val = 0 if isinstance(agg_fn, ds.count) else np.nan
xarray = xr.DataArray(np.full((height, width), empty_val),
dims=[y.name, x.name], coords={x.name: xs, y.name: ys})
return self.p.element_type(xarray, **params)
cvs = ds.Canvas(plot_width=width, plot_height=height,
x_range=x_range, y_range=y_range)
agg_kwargs = {}
if self.p.line_width and glyph == 'line' and ds_version >= Version('0.14.0'):
agg_kwargs['line_width'] = self.p.line_width
dfdata = PandasInterface.as_dframe(data)
cvs_fn = getattr(cvs, glyph)
if sel_fn:
if isinstance(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 = [s for s in agg if s not in _ignore]
params["vdims"] = [*params["vdims"], *sel_vdims]
else:
agg = self._apply_datashader(dfdata, cvs_fn, agg_fn, agg_kwargs, x, y)
if 'x_axis' in agg.coords and 'y_axis' in agg.coords:
agg = agg.rename({'x_axis': x, 'y_axis': y})
if xtype == 'datetime':
agg[x.name] = agg[x.name].astype('datetime64[ns]')
if ytype == 'datetime':
agg[y.name] = agg[y.name].astype('datetime64[ns]')
if isinstance(agg, xr.Dataset) or agg.ndim == 2:
# Replacing x and y coordinates to avoid numerical precision issues
eldata = agg if ds_version > Version('0.5.0') else (xs, ys, agg.data)
return self.p.element_type(eldata, **params)
else:
params['vdims'] = list(map(str, agg.coords[agg_fn.column].data))
return ImageStack(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/8439
with warnings.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 = ds15 and isinstance(agg_fn, ds.where) and isinstance(agg_fn.column, rd.SpecialColumn)
is_summary_index = isinstance(agg_fn, ds.summary) and "index" in agg
if is_where_index or is_summary_index:
if is_where_index:
data = agg.data
agg = agg.to_dataset(name="index")
else: # summary index
data = agg.index.data
neg1 = data == -1
for col in dfdata.columns:
if col in agg.coords:
continue
val = dfdata[col].values[data]
if val.dtype.kind == 'f':
val[neg1] = np.nan
elif isinstance(val.dtype, pd.CategoricalDtype):
val = val.to_numpy()
val[neg1] = "-"
elif val.dtype.kind == "O":
val[neg1] = "-"
elif val.dtype.kind == "M":
val[neg1] = np.datetime64("NaT")
else:
val = val.astype(np.float64)
val[neg1] = np.nan
agg[col] = ((y.name, x.name), val)
return agg
class curve_aggregate(aggregate):
"""
Optimized aggregation for Curve objects by setting the default
of the aggregator to self_intersect=False to be more consistent
with the appearance of non-aggregated curves.
"""
aggregator = param.ClassSelector(class_=(rd.Reduction, rd.summary, str),
default=rd.count(self_intersect=False), 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.""")
class overlay_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.
"""
@classmethod
def applies(cls, element, agg_fn, line_width=None):
return (isinstance(element, NdOverlay) and
(element.type is not Curve or line_width is None) and
((isinstance(agg_fn, (ds.count, ds.sum, ds.mean, ds.any)) and
(agg_fn.column is None or agg_fn.column not in element.kdims)) or
(isinstance(agg_fn, ds.count_cat) and agg_fn.column in element.kdims)))
def _process(self, element, key=None):
agg_fn = self._get_aggregator(element, self.p.aggregator)
if not self.applies(element, agg_fn, line_width=self.p.line_width):
raise ValueError(
'overlay_aggregate only handles aggregation of NdOverlay types '
'with count, sum or mean reduction.'
)
# Compute overall bounds
dims = element.last.dimensions()[0:2]
ndims = len(dims)
if ndims == 1:
x, y = dims[0], None
else:
x, y = dims
info = 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: v for k, v in dict(self.param.values(),
**self.p).items()
if k in aggregate.param},
x_range=(x0, x1), y_range=(y0, y1))
bbox = (x0, y0, x1, y1)
# Optimize categorical counts by aggregating them individually
if isinstance(agg_fn, ds.count_cat):
agg_params.update(dict(dynamic=False, aggregator=ds.count()))
agg_fn1 = aggregate.instance(**agg_params)
if element.ndims == 1:
grouped = element
else:
grouped = element.groupby(
[agg_fn.column], container_type=NdOverlay,
group_type=NdOverlay
)
groups = []
for k, el in grouped.items():
if width == 0 or height == 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)))
return grouped.clone(groups)
# Create aggregate instance for sum, count operations, breaking mean
# into two aggregates
column = agg_fn.column or 'Count'
if isinstance(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 = None
is_sum = isinstance(agg_fn, ds.sum)
is_any = isinstance(agg_fn, ds.any)
# Accumulate into two aggregates and mask
agg, agg2, mask = None, None, None
for v in element:
# Compute aggregates and mask
new_agg = agg_fn1.process_element(v, None)
if is_sum:
new_mask = np.isnan(new_agg.data[column].values)
new_agg.data = new_agg.data.fillna(0)
if agg_fn2:
new_agg2 = agg_fn2.process_element(v, None)
if agg is None:
agg = new_agg
if is_sum: mask = new_mask
if agg_fn2: agg2 = new_agg2
else:
if is_any:
agg.data |= new_agg.data
else:
agg.data += new_agg.data
if is_sum: mask &= new_mask
if agg_fn2: agg2.data += new_agg2.data
# Divide sum by count to compute mean
if agg2 is not None:
agg2.data.rename({'Count': agg_fn.column}, inplace=True)
with np.errstate(divide='ignore', invalid='ignore'):
agg.data /= agg2.data
# Fill masked with with NaNs
if is_sum:
agg.data[column].values[mask] = np.nan
return agg.clone(bounds=bbox)
class area_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 = None
if not self.p.y_range:
y0, y1 = element.range(1)
if len(element.vdims) > 1:
y0, _ = element.range(2)
elif y0 >= 0:
y0 = 0
elif y1 <= 0:
y1 = 0
default = (y0, y1)
ystack = element.vdims[1].name if len(element.vdims) > 1 else None
info = 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))
if width == 0 or height == 0:
return self._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)
if xtype == "datetime":
agg[x.name] = agg[x.name].astype('datetime64[ns]')
return self.p.element_type(agg, **params)
class spread_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)
if df is element.data:
df = df.copy()
pos, neg = element.vdims[1:3] if len(element.vdims) > 2 else element.vdims[1:2]*2
yvals = 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)
return super()._process(area, key=None)
class spikes_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], None
spike_length = 0.5 if self.p.spike_length is None else self.p.spike_length
if element.vdims and self.p.spike_length is None:
x, y = element.dimensions()[:2]
rename_dict = {'x': x.name, 'y':y.name}
if not self.p.y_range:
y0, y1 = element.range(1)
if y0 >= 0:
default = (0, y1)
elif y1 <= 0:
default = (y0, 0)
else:
default = (y0, y1)
else:
default = None
else:
x, y = element.kdims[0], None
default = (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 = [] if agg_fn.column is None else [agg_fn.column]
if y is None:
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']
if not self.p.expand: height = 1
else:
df = element.dframe([x, y]+value_cols).copy()
df['y0'] = np.array(0, df.dtypes[y.name])
yagg = ['y0', y.name]
if xtype == '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))
if width == 0 or height == 0:
return self._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 = {}
if ds_version >= Version('0.14.0'):
agg_kwargs['line_width'] = self.p.line_width
rename_dict = {k: v for k, v in rename_dict.items() if k != v}
agg = cvs.line(df, x.name, yagg, agg_fn, axis=1, **agg_kwargs).rename(rename_dict)
if xtype == "datetime":
agg[x.name] = agg[x.name].astype('datetime64[ns]')
return self.p.element_type(agg, **params)
class geom_aggregate(AggregationOperation):
"""
Baseclass for aggregation of Geom elements.
"""
__abstract = True
def _aggregate(self, cvs, df, x0, y0, x1, y1, agg):
raise NotImplementedError
def _process(self, element, key=None):
agg_fn = self._get_aggregator(element, self.p.aggregator)
x0d, y0d, x1d, y1d = element.kdims
info = 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)
if xtype == 'datetime' or ytype == 'datetime':
df = df.copy()
if xtype == '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]'))
if ytype == '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]'))
if isinstance(agg_fn, ds.count_cat) and df[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))
if width == 0 or height == 0:
return self._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]
if xtype == "datetime":
agg[xdim] = agg[xdim].astype('datetime64[ns]')
if ytype == "datetime":
agg[ydim] = agg[ydim].astype('datetime64[ns]')
params['kdims'] = [xdim, ydim]
if agg.ndim == 2:
# Replacing x and y coordinates to avoid numerical precision issues
eldata = agg if ds_version > Version('0.5.0') else (xs, ys, agg.data)
return self.p.element_type(eldata, **params)
else:
layers = {}
for c in agg.coords[agg_fn.column].data:
cagg = agg.sel(**{agg_fn.column: c})
eldata = cagg if ds_version > Version('0.5.0') else (xs, ys, cagg.data)
layers[c] = self.p.element_type(eldata, **params)
return NdOverlay(layers, kdims=[element.get_dimension(agg_fn.column)])
class segments_aggregate(geom_aggregate, LineAggregationOperation):
"""
Aggregates Segments elements.
"""
def _aggregate(self, cvs, df, x0, y0, x1, y1, agg_fn):
agg_kwargs = {}
if ds_version >= Version('0.14.0'):
agg_kwargs['line_width'] = self.p.line_width
return cvs.line(df, [x0, x1], [y0, y1], agg_fn, axis=1, **agg_kwargs)
class rectangle_aggregate(geom_aggregate):
"""
Aggregates Rectangle elements.
"""
def _aggregate(self, cvs, df, x0, y0, x1, y1, agg_fn):
return cvs.area(df, x=[x0, x1], y=y0, y_stack=y1, agg=agg_fn, axis=1)
class regrid(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.kdims
dims = [y.name, x.name]
irregular = any(element.interface.irregular(element, d)
for d in dims)
if irregular:
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 = {}
for i, vd in enumerate(element.vdims):
if element.interface is XArrayInterface:
if element.interface.packed(element):
xarr = element.data[..., i]
else:
xarr = element.data[vd.name]
if 'datetime' in (xtype, ytype):
xarr = xarr.copy()
if dims != xarr.dims and not irregular:
xarr = xarr.transpose(*dims)
elif irregular:
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)
if xtype == "datetime":
xarr[x.name] = [dt_to_int(v, 'ns') for v in xarr[x.name].values]
if ytype == "datetime":
xarr[y.name] = [dt_to_int(v, 'ns') for v in xarr[y.name].values]
arrays[vd.name] = xarr
return arrays
def _process(self, element, key=None):
if ds_version <= Version('0.5.0'):
raise RuntimeError('regrid operation requires datashader>=0.6.0')
# Compute coords, anges and size
x, y = element.kdims
coords = tuple(element.dimension_values(d, expanded=False) for d in [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.interpolation or None
if interp == 'bilinear': interp = 'linear'
if not (self.p.upsample or interp is None) and self.p.target is None:
(x0, x1), (y0, y1) = element.range(0), element.range(1)
if isinstance(x0, datetime_types):
x0, x1 = dt_to_int(x0, 'ns'), dt_to_int(x1, 'ns')
if isinstance(y0, datetime_types):
y0, y1 = dt_to_int(y0, 'ns'), dt_to_int(y1, 'ns')
exspan, eyspan = (x1-x0), (y1-y0)
if np.isfinite(exspan) and exspan > 0 and xspan > 0:
width = max([min([int((xspan/exspan) * len(coords[0])), width]), 1])
else:
width = 0
if np.isfinite(eyspan) and eyspan > 0 and yspan > 0:
height = max([min([int((yspan/eyspan) * len(coords[1])), height]), 1])
else:
height = 0
xunit = float(xspan)/width if width else 0
yunit = float(yspan)/height if height else 0
xs, 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))
if width == 0 or height == 0:
if width == 0:
params['xdensity'] = 1
if height == 0:
params['ydensity'] = 1
return element.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 dimension
regridded = {}
arrays = self._get_xarrays(element, coords, xtype, ytype)
agg_fn = self._get_aggregator(element, self.p.aggregator, add_field=False)
for vd, xarr in arrays.items():
rarray = cvs.raster(xarr, upsample_method=interp,
downsample_method=agg_fn)
# Convert datetime coordinates
if xtype == "datetime":
rarray[x.name] = rarray[x.name].astype('datetime64[ns]')
if ytype == "datetime":
rarray[y.name] = rarray[y.name].astype('datetime64[ns]')
regridded[vd] = rarray
regridded = xr.Dataset(regridded)
return element.clone(regridded, datatype=['xarray']+element.datatype, **params)
class contours_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))
@classmethod
def _get_aggregator(cls, element, agg, add_field=True):
if not element.vdims and agg.column is None and not isinstance(agg, (rd.count, rd.any)):
return ds.any()
return super()._get_aggregator(element, agg, add_field)
class trimesh_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):
from datashader.utils import mesh
if element.vdims and getattr(agg, 'column', None) not in element.nodes.vdims:
simplex_dims = [0, 1, 2, 3]
vert_dims = [0, 1]
elif element.nodes.vdims:
simplex_dims = [0, 1, 2]
vert_dims = [0, 1, 3]
else:
raise ValueError("Cannot shade TriMesh without value dimension.")
datatypes = [element.interface.datatype, element.nodes.interface.datatype]
if set(datatypes) == {'dask'}:
dims, node_dims = element.dimensions(), element.nodes.dimensions()
simplices = element.data[[dims[sd].name for sd in simplex_dims]]
verts = element.nodes.data[[node_dims[vd].name for vd in vert_dims]]
else:
if 'dask' in datatypes:
if datatypes[0] == 'dask':
p, n = 'simplexes', 'vertices'
else: