-
-
Notifications
You must be signed in to change notification settings - Fork 394
/
spaces.py
1883 lines (1571 loc) · 74.6 KB
/
spaces.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 itertools
import types
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
from itertools import groupby
from numbers import Number
from types import FunctionType
import numpy as np
import param
from ..streams import Params, Stream, streams_list_from_dict
from . import traversal, util
from .accessors import Opts, Redim
from .dimension import Dimension, ViewableElement
from .layout import AdjointLayout, Empty, Layout, Layoutable, NdLayout
from .ndmapping import NdMapping, UniformNdMapping, item_check
from .options import Store, StoreOptions
from .overlay import CompositeOverlay, NdOverlay, Overlay, Overlayable
class HoloMap(Layoutable, UniformNdMapping, Overlayable):
"""
A HoloMap is an n-dimensional mapping of viewable elements or
overlays. Each item in a HoloMap has an tuple key defining the
values along each of the declared key dimensions, defining the
discretely sampled space of values.
The visual representation of a HoloMap consists of the viewable
objects inside the HoloMap which can be explored by varying one
or more widgets mapping onto the key dimensions of the HoloMap.
"""
data_type = (ViewableElement, NdMapping, Layout)
def __init__(self, initial_items=None, kdims=None, group=None, label=None, **params):
super().__init__(initial_items, kdims, group, label, **params)
@property
def opts(self):
return Opts(self, mode='holomap')
def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
NdOverlay object(s) with supplied dimensions
"""
dimensions = self._valid_dimensions(dimensions)
if len(dimensions) == self.ndims:
with item_check(False):
return NdOverlay(self, **kwargs).reindex(dimensions)
else:
dims = [d for d in self.kdims if d not in dimensions]
return self.groupby(dims, group_type=NdOverlay, **kwargs)
def grid(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
GridSpace with supplied dimensions
"""
dimensions = self._valid_dimensions(dimensions)
if len(dimensions) == self.ndims:
with item_check(False):
return GridSpace(self, **kwargs).reindex(dimensions)
return self.groupby(dimensions, container_type=GridSpace, **kwargs)
def layout(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayout with supplied dimensions
"""
dimensions = self._valid_dimensions(dimensions)
if len(dimensions) == self.ndims:
with item_check(False):
return NdLayout(self, **kwargs).reindex(dimensions)
return self.groupby(dimensions, container_type=NdLayout, **kwargs)
def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used, e.g.:
obj.options(cmap='viridis', show_title=False)
If the object is nested the options must be qualified using
a type[.group][.label] specification, e.g.:
obj.options('Image', cmap='viridis', show_title=False)
or using:
obj.options({'Image': dict(cmap='viridis', show_title=False)})
Args:
*args: Sets of options to apply to object
Supports a number of formats including lists of Options
objects, a type[.group][.label] followed by a set of
keyword options to apply and a dictionary indexed by
type[.group][.label] specs.
backend (optional): Backend to apply options to
Defaults to current selected backend
clone (bool, optional): Whether to clone object
Options can be applied inplace with clone=False
**kwargs: Keywords of options
Set of options to apply to the object
Returns:
Returns the cloned object with the options applied
"""
data = dict([(k, v.options(*args, **kwargs))
for k, v in self.data.items()])
return self.clone(data)
def _split_overlays(self):
"Splits overlays inside the HoloMap into list of HoloMaps"
if not issubclass(self.type, CompositeOverlay):
return None, self.clone()
item_maps = {}
for k, overlay in self.data.items():
for key, el in overlay.items():
if key not in item_maps:
item_maps[key] = [(k, el)]
else:
item_maps[key].append((k, el))
maps, keys = [], []
for k, layermap in item_maps.items():
maps.append(self.clone(layermap))
keys.append(k)
return keys, maps
def _dimension_keys(self):
"""
Helper for __mul__ that returns the list of keys together with
the dimension labels.
"""
return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k))
for k in self.keys()]
def _dynamic_mul(self, dimensions, other, keys):
"""
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other.
"""
# If either is a HoloMap compute Dimension values
if not isinstance(self, DynamicMap) or not isinstance(other, DynamicMap):
keys = sorted((d, v) for k in keys for d, v in k)
grouped = {g: [v for _, v in group]
for g, group in groupby(keys, lambda x: x[0])}
dimensions = [d.clone(values=grouped[d.name]) for d in dimensions]
map_obj = None
# Combine streams
map_obj = self if isinstance(self, DynamicMap) else other
if isinstance(self, DynamicMap) and isinstance(other, DynamicMap):
self_streams = util.dimensioned_streams(self)
other_streams = util.dimensioned_streams(other)
streams = list(util.unique_iterator(self_streams+other_streams))
else:
streams = map_obj.streams
def dynamic_mul(*key, **kwargs):
key_map = {d.name: k for d, k in zip(dimensions, key)}
layers = []
try:
self_el = self.select(HoloMap, **key_map) if self.kdims else self[()]
layers.append(self_el)
except KeyError:
pass
try:
other_el = other.select(HoloMap, **key_map) if other.kdims else other[()]
layers.append(other_el)
except KeyError:
pass
return Overlay(layers)
callback = Callable(dynamic_mul, inputs=[self, other])
callback._is_overlay = True
if map_obj:
return map_obj.clone(callback=callback, shared_data=False,
kdims=dimensions, streams=streams)
else:
return DynamicMap(callback=callback, kdims=dimensions,
streams=streams)
def __mul__(self, other, reverse=False):
"""Overlays items in the object with another object
The mul (*) operator implements overlaying of different
objects. This method tries to intelligently overlay mappings
with differing keys. If the UniformNdMapping is mulled with a
simple ViewableElement each element in the UniformNdMapping is
overlaid with the ViewableElement. If the element the
UniformNdMapping is mulled with is another UniformNdMapping it
will try to match up the dimensions, making sure that items
with completely different dimensions aren't overlaid.
"""
if isinstance(other, HoloMap):
self_set = {d.name for d in self.kdims}
other_set = {d.name for d in other.kdims}
# Determine which is the subset, to generate list of keys and
# dimension labels for the new view
self_in_other = self_set.issubset(other_set)
other_in_self = other_set.issubset(self_set)
dims = [other.kdims, self.kdims] if self_in_other else [self.kdims, other.kdims]
dimensions = util.merge_dimensions(dims)
if self_in_other and other_in_self: # superset of each other
keys = self._dimension_keys() + other._dimension_keys()
super_keys = util.unique_iterator(keys)
elif self_in_other: # self is superset
dimensions = other.kdims
super_keys = other._dimension_keys()
elif other_in_self: # self is superset
super_keys = self._dimension_keys()
else: # neither is superset
raise Exception('One set of keys needs to be a strict subset of the other.')
if isinstance(self, DynamicMap) or isinstance(other, DynamicMap):
return self._dynamic_mul(dimensions, other, super_keys)
items = []
for dim_keys in super_keys:
# Generate keys for both subset and superset and sort them by the dimension index.
self_key = tuple(k for p, k in sorted(
[(self.get_dimension_index(dim), v) for dim, v in dim_keys
if dim in self.kdims]))
other_key = tuple(k for p, k in sorted(
[(other.get_dimension_index(dim), v) for dim, v in dim_keys
if dim in other.kdims]))
new_key = self_key if other_in_self else other_key
# Append SheetOverlay of combined items
if (self_key in self) and (other_key in other):
if reverse:
value = other[other_key] * self[self_key]
else:
value = self[self_key] * other[other_key]
items.append((new_key, value))
elif self_key in self:
items.append((new_key, Overlay([self[self_key]])))
else:
items.append((new_key, Overlay([other[other_key]])))
return self.clone(items, kdims=dimensions, label=self._label, group=self._group)
elif isinstance(other, self.data_type) and not isinstance(other, Layout):
if isinstance(self, DynamicMap):
def dynamic_mul(*args, **kwargs):
element = self[args]
if reverse:
return other * element
else:
return element * other
callback = Callable(dynamic_mul, inputs=[self, other])
callback._is_overlay = True
return self.clone(shared_data=False, callback=callback,
streams=util.dimensioned_streams(self))
items = [(k, other * v) if reverse else (k, v * other)
for (k, v) in self.data.items()]
return self.clone(items, label=self._label, group=self._group)
else:
return NotImplemented
def __lshift__(self, other):
"Adjoin another object to this one returning an AdjointLayout"
if isinstance(other, (ViewableElement, UniformNdMapping, Empty)):
return AdjointLayout([self, other])
elif isinstance(other, AdjointLayout):
return AdjointLayout(other.data+[self])
else:
raise TypeError(f'Cannot append {type(other).__name__} to a AdjointLayout')
def collate(self, merge_type=None, drop=None, drop_constant=False):
"""Collate allows reordering nested containers
Collation allows collapsing nested mapping types by merging
their dimensions. In simple terms in merges nested containers
into a single merged type.
In the simple case a HoloMap containing other HoloMaps can
easily be joined in this way. However collation is
particularly useful when the objects being joined are deeply
nested, e.g. you want to join multiple Layouts recorded at
different times, collation will return one Layout containing
HoloMaps indexed by Time. Changing the merge_type will allow
merging the outer Dimension into any other UniformNdMapping
type.
Args:
merge_type: Type of the object to merge with
drop: List of dimensions to drop
drop_constant: Drop constant dimensions automatically
Returns:
Collated Layout or HoloMap
"""
if drop is None:
drop = []
from .element import Collator
merge_type=merge_type if merge_type else self.__class__
return Collator(self, merge_type=merge_type, drop=drop,
drop_constant=drop_constant)()
def decollate(self):
"""Packs HoloMap of DynamicMaps into a single DynamicMap that returns an
HoloMap
Decollation allows packing a HoloMap of DynamicMaps into a single DynamicMap
that returns an HoloMap of simple (non-dynamic) elements. All nested streams
are lifted to the resulting DynamicMap, and are available in the `streams`
property. The `callback` property of the resulting DynamicMap is a pure,
stateless function of the stream values. To avoid stream parameter name
conflicts, the resulting DynamicMap is configured with
positional_stream_args=True, and the callback function accepts stream values
as positional dict arguments.
Returns:
DynamicMap that returns an HoloMap
"""
from .decollate import decollate
return decollate(self)
def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to which relabel will be applied
If applied to container allows applying relabeling to
contained objects up to the specified depth
Returns:
Returns relabelled object
"""
return super().relabel(label=label, group=group, depth=depth)
def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, individually=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (tuple optional): Lower and upper bounds of bins
adjoin (bool, optional): Whether to adjoin histogram
Returns:
AdjointLayout of HoloMap and histograms or just the
histograms
"""
if dimension is not None and not isinstance(dimension, list):
dimension = [dimension]
histmaps = [self.clone(shared_data=False) for _ in (dimension or [None])]
if individually:
map_range = None
else:
if dimension is None:
raise Exception("Please supply the dimension to compute a histogram for.")
map_range = self.range(kwargs['dimension'])
bin_range = map_range if bin_range is None else bin_range
style_prefix = 'Custom[<' + self.name + '>]_'
if issubclass(self.type, (NdOverlay, Overlay)) and 'index' not in kwargs:
kwargs['index'] = 0
for k, v in self.data.items():
hists = v.hist(adjoin=False, dimension=dimension,
bin_range=bin_range, num_bins=num_bins,
style_prefix=style_prefix, **kwargs)
if isinstance(hists, Layout):
for i, hist in enumerate(hists):
histmaps[i][k] = hist
else:
histmaps[0][k] = hists
if adjoin:
layout = self
for hist in histmaps:
layout = (layout << hist)
if issubclass(self.type, (NdOverlay, Overlay)):
layout.main_layer = kwargs['index']
return layout
elif len(histmaps) > 1:
return Layout(histmaps)
else:
return histmaps[0]
class Callable(param.Parameterized):
"""
Callable allows wrapping callbacks on one or more DynamicMaps
allowing their inputs (and in future outputs) to be defined.
This makes it possible to wrap DynamicMaps with streams and
makes it possible to traverse the graph of operations applied
to a DynamicMap.
Additionally, if the memoize attribute is True, a Callable will
memoize the last returned value based on the arguments to the
function and the state of all streams on its inputs, to avoid
calling the function unnecessarily. Note that because memoization
includes the streams found on the inputs it may be disabled if the
stream requires it and is triggering.
A Callable may also specify a stream_mapping which specifies the
objects that are associated with interactive (i.e. linked) streams
when composite objects such as Layouts are returned from the
callback. This is required for building interactive, linked
visualizations (for the backends that support them) when returning
Layouts, NdLayouts or GridSpace objects. When chaining multiple
DynamicMaps into a pipeline, the link_inputs parameter declares
whether the visualization generated using this Callable will
inherit the linked streams. This parameter is used as a hint by
the applicable backend.
The mapping should map from an appropriate key to a list of
streams associated with the selected object. The appropriate key
may be a type[.group][.label] specification for Layouts, an
integer index or a suitable NdLayout/GridSpace key. For more
information see the DynamicMap tutorial at holoviews.org.
"""
callable = param.Callable(default=None, constant=True, allow_refs=False, doc="""
The callable function being wrapped.""")
inputs = param.List(default=[], constant=True, doc="""
The list of inputs the callable function is wrapping. Used
to allow deep access to streams in chained Callables.""")
operation_kwargs = param.Dict(default={}, constant=True, doc="""
Potential dynamic keyword arguments associated with the
operation.""")
link_inputs = param.Boolean(default=True, doc="""
If the Callable wraps around other DynamicMaps in its inputs,
determines whether linked streams attached to the inputs are
transferred to the objects returned by the Callable.
For example the Callable wraps a DynamicMap with an RangeXY
stream, this switch determines whether the corresponding
visualization should update this stream with range changes
originating from the newly generated axes.""")
memoize = param.Boolean(default=True, doc="""
Whether the return value of the callable should be memoized
based on the call arguments and any streams attached to the
inputs.""")
operation = param.Callable(default=None, doc="""
The function being applied by the Callable. May be used
to record the transform(s) being applied inside the
callback function.""")
stream_mapping = param.Dict(default={}, constant=True, doc="""
Defines how streams should be mapped to objects returned by
the Callable, e.g. when it returns a Layout.""")
def __init__(self, callable, **params):
super().__init__(callable=callable,
**dict(params, name=util.callable_name(callable)))
self._memoized = {}
self._is_overlay = False
self.args = None
self.kwargs = None
self._stream_memoization = self.memoize
@property
def argspec(self):
return util.argspec(self.callable)
@property
def noargs(self):
"Returns True if the callable takes no arguments"
noargs = util.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
return self.argspec == noargs
def clone(self, callable=None, **overrides):
"""Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object
"""
old = {k: v for k, v in self.param.values().items()
if k not in ['callable', 'name']}
params = dict(old, **overrides)
callable = self.callable if callable is None else callable
return self.__class__(callable, **params)
def __call__(self, *args, **kwargs):
"""Calls the callable function with supplied args and kwargs.
If enabled uses memoization to avoid calling function
unnecessarily.
Args:
*args: Arguments passed to the callable function
**kwargs: Keyword arguments passed to the callable function
Returns:
Return value of the wrapped callable function
"""
# Nothing to do for callbacks that accept no arguments
kwarg_hash = kwargs.pop('_memoization_hash_', ())
(self.args, self.kwargs) = (args, kwargs)
if isinstance(self.callable, param.rx):
return self.callable.rx.value
elif not args and not kwargs and not any(kwarg_hash):
return self.callable()
inputs = [i for i in self.inputs if isinstance(i, DynamicMap)]
streams = []
for stream in [s for i in inputs for s in get_nested_streams(i)]:
if stream not in streams: streams.append(stream)
memoize = self._stream_memoization and not any(s.transient and s._triggering for s in streams)
values = tuple(tuple(sorted(s.hashkey.items())) for s in streams)
key = args + kwarg_hash + values
hashed_key = util.deephash(key) if self.memoize else None
if hashed_key is not None and memoize and hashed_key in self._memoized:
return self._memoized[hashed_key]
if self.argspec.varargs is not None:
# Missing information on positional argument names, cannot promote to keywords
pass
elif len(args) != 0: # Turn positional arguments into keyword arguments
pos_kwargs = {k:v for k,v in zip(self.argspec.args, args)}
ignored = range(len(self.argspec.args),len(args))
if len(ignored):
self.param.warning('Ignoring extra positional argument {}'.format(', '.join(f'{i}' for i in ignored)))
clashes = set(pos_kwargs.keys()) & set(kwargs.keys())
if clashes:
self.param.warning(
f'Positional arguments {list(clashes)!r} overridden by keywords')
args, kwargs = (), dict(pos_kwargs, **kwargs)
try:
ret = self.callable(*args, **kwargs)
except KeyError:
# KeyError is caught separately because it is used to signal
# invalid keys on DynamicMap and should not warn
raise
except Exception as e:
posstr = ', '.join([f'{el!r}' for el in self.args]) if self.args else ''
kwstr = ', '.join(f'{k}={v!r}' for k,v in self.kwargs.items())
argstr = ', '.join([el for el in [posstr, kwstr] if el])
message = ("Callable raised \"{e}\".\n"
"Invoked as {name}({argstr})")
self.param.warning(message.format(name=self.name, argstr=argstr, e=repr(e)))
raise
if hashed_key is not None:
self._memoized = {hashed_key : ret}
return ret
class Generator(Callable):
"""
Generators are considered a special case of Callable that accept no
arguments and never memoize.
"""
callable = param.ClassSelector(default=None, class_ = types.GeneratorType,
constant=True, doc="""
The generator that is wrapped by this Generator.""")
@property
def argspec(self):
return util.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
def __call__(self):
try:
return next(self.callable)
except StopIteration:
raise
except Exception:
msg = 'Generator {name} raised the following exception:'
self.param.warning(msg.format(name=self.name))
raise
def get_nested_dmaps(dmap):
"""Recurses DynamicMap to find DynamicMaps inputs
Args:
dmap: DynamicMap to recurse to look for DynamicMap inputs
Returns:
List of DynamicMap instances that were found
"""
if not isinstance(dmap, DynamicMap):
return []
dmaps = [dmap]
for o in dmap.callback.inputs:
dmaps.extend(get_nested_dmaps(o))
return list(set(dmaps))
def get_nested_streams(dmap):
"""Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found
"""
return list({s for dmap in get_nested_dmaps(dmap) for s in dmap.streams})
@contextmanager
def dynamicmap_memoization(callable_obj, streams):
"""
Determine whether the Callable should have memoization enabled
based on the supplied streams (typically by a
DynamicMap). Memoization is disabled if any of the streams require
it it and are currently in a triggered state.
"""
memoization_state = bool(callable_obj._stream_memoization)
callable_obj._stream_memoization &= not any(s.transient and s._triggering for s in streams)
try:
yield
finally:
callable_obj._stream_memoization = memoization_state
class periodic:
"""
Implements the utility of the same name on DynamicMap.
Used to defined periodic event updates that can be started and
stopped.
"""
_periodic_util = util.periodic
def __init__(self, dmap):
self.dmap = dmap
self.instance = None
def __call__(self, period, count=None, param_fn=None, timeout=None, block=True):
"""Periodically trigger the streams on the DynamicMap.
Run a non-blocking loop that updates the stream parameters using
the event method. Runs count times with the specified period. If
count is None, runs indefinitely.
Args:
period: Timeout between events in seconds
count: Number of events to trigger
param_fn: Function returning stream updates given count
Stream parameter values should be returned as dictionary
timeout: Overall timeout in seconds
block: Whether the periodic callbacks should be blocking
"""
if self.instance is not None and not self.instance.completed:
raise RuntimeError('Periodic process already running. '
'Wait until it completes or call '
'stop() before running a new periodic process')
def inner(i):
kwargs = {} if param_fn is None else param_fn(i)
if kwargs:
self.dmap.event(**kwargs)
else:
Stream.trigger(self.dmap.streams)
instance = self._periodic_util(period, count, inner,
timeout=timeout, block=block)
instance.start()
self.instance = instance
def stop(self):
"Stop the periodic process."
self.instance.stop()
def __str__(self):
return "<holoviews.core.spaces.periodic method>"
class DynamicMap(HoloMap):
"""
A DynamicMap is a type of HoloMap where the elements are dynamically
generated by a callable. The callable is invoked with values
associated with the key dimensions or with values supplied by stream
parameters.
"""
# Declare that callback is a positional parameter (used in clone)
__pos_params = ['callback']
kdims = param.List(default=[], constant=True, doc="""
The key dimensions of a DynamicMap map to the arguments of the
callback. This mapping can be by position or by name.""")
callback = param.ClassSelector(class_=Callable, constant=True, doc="""
The callable used to generate the elements. The arguments to the
callable includes any number of declared key dimensions as well
as any number of stream parameters defined on the input streams.
If the callable is an instance of Callable it will be used
directly, otherwise it will be automatically wrapped in one.""")
streams = param.List(default=[], constant=True, doc="""
List of Stream instances to associate with the DynamicMap. The
set of parameter values across these streams will be supplied as
keyword arguments to the callback when the events are received,
updating the streams. Can also be supplied as a dictionary that
maps parameters or panel widgets to callback argument names that
will then be automatically converted to the equivalent list
format.""")
cache_size = param.Integer(default=500, bounds=(1, None), doc="""
The number of entries to cache for fast access. This is an LRU
cache where the least recently used item is overwritten once
the cache is full.""")
positional_stream_args = param.Boolean(default=False, constant=True, doc="""
If False, stream parameters are passed to the callback as keyword arguments.
If True, stream parameters are passed to callback as positional arguments.
Each positional argument is a dict containing the contents of a stream.
The positional stream arguments follow the positional arguments for each kdim,
and they are ordered to match the order of the DynamicMap's streams list.
""")
def __init__(self, callback, initial_items=None, streams=None, **params):
streams = (streams or [])
if isinstance(streams, dict):
streams = streams_list_from_dict(streams)
# If callback is a parameterized method and watch is disabled add as stream
if param.parameterized.resolve_ref(callback):
streams.append(callback)
elif (params.get('watch', True) and (util.is_param_method(callback, has_deps=True) or
(isinstance(callback, FunctionType) and hasattr(callback, '_dinfo')))):
streams.append(callback)
if isinstance(callback, types.GeneratorType):
callback = Generator(callback)
elif not isinstance(callback, Callable):
callback = Callable(callback)
valid, invalid = Stream._process_streams(streams)
if invalid:
msg = ('The supplied streams list contains objects that '
'are not Stream instances: {objs}')
raise TypeError(msg.format(objs = ', '.join(f'{el!r}' for el in invalid)))
super().__init__(initial_items, callback=callback, streams=valid, **params)
if self.callback.noargs:
prefix = 'DynamicMaps using generators (or callables without arguments)'
if self.kdims:
raise Exception(prefix + ' must be declared without key dimensions')
if len(self.streams)> 1:
raise Exception(prefix + ' must have either streams=[] or a single, '
+ 'stream instance without any stream parameters')
if self._stream_parameters() != []:
raise Exception(prefix + ' cannot accept any stream parameters')
if self.positional_stream_args:
self._posarg_keys = None
else:
self._posarg_keys = util.validate_dynamic_argspec(
self.callback, self.kdims, self.streams
)
# Set source to self if not already specified
for stream in self.streams:
if stream.source is None:
stream.source = self
if isinstance(stream, Params):
for p in stream.parameters:
if isinstance(p.owner, Stream) and p.owner.source is None:
p.owner.source = self
self.periodic = periodic(self)
self._current_key = None
@property
def opts(self):
return Opts(self, mode='dynamicmap')
@property
def redim(self):
return Redim(self, mode='dynamic')
@property
def unbounded(self):
"""
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of these key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
"""
unbounded_dims = []
# Dimensioned streams do not need to be bounded
stream_params = set(self._stream_parameters())
for kdim in self.kdims:
if str(kdim) in stream_params:
continue
if kdim.values:
continue
if None in kdim.range:
unbounded_dims.append(str(kdim))
return unbounded_dims
@property
def current_key(self):
"""Returns the current key value."""
return self._current_key
def _stream_parameters(self):
return util.stream_parameters(
self.streams, no_duplicates=not self.positional_stream_args
)
def _initial_key(self):
"""
Construct an initial key for based on the lower range bounds or
values on the key dimensions.
"""
key = []
undefined = []
stream_params = set(self._stream_parameters())
for kdim in self.kdims:
if str(kdim) in stream_params:
key.append(None)
elif kdim.default is not None:
key.append(kdim.default)
elif kdim.values:
if all(util.isnumeric(v) for v in kdim.values):
key.append(sorted(kdim.values)[0])
else:
key.append(kdim.values[0])
elif kdim.range[0] is not None:
key.append(kdim.range[0])
else:
undefined.append(kdim)
if undefined:
msg = ('Dimension(s) {undefined_dims} do not specify range or values needed '
'to generate initial key')
undefined_dims = ', '.join(f'{str(dim)!r}' for dim in undefined)
raise KeyError(msg.format(undefined_dims=undefined_dims))
return tuple(key)
def _validate_key(self, key):
"""
Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range.
"""
if key == () and len(self.kdims) == 0: return ()
key = util.wrap_tuple(key)
assert len(key) == len(self.kdims)
for ind, val in enumerate(key):
kdim = self.kdims[ind]
low, high = util.max_range([kdim.range, kdim.soft_range])
if util.is_number(low) and util.isfinite(low):
if val < low:
raise KeyError(f"Key value {val} below lower bound {low}")
if util.is_number(high) and util.isfinite(high):
if val > high:
raise KeyError(f"Key value {val} above upper bound {high}")
def event(self, **kwargs):
"""Updates attached streams and triggers events
Automatically find streams matching the supplied kwargs to
update and trigger events on them.
Args:
**kwargs: Events to update streams with
"""
if self.callback.noargs and self.streams == []:
self.param.warning(
'No streams declared. To update a DynamicMaps using '
'generators (or callables without arguments) use streams=[Next()]')
return
if self.streams == []:
self.param.warning('No streams on DynamicMap, calling event '
'will have no effect')
return
stream_params = set(self._stream_parameters())
invalid = [k for k in kwargs.keys() if k not in stream_params]
if invalid:
msg = 'Key(s) {invalid} do not correspond to stream parameters'
raise KeyError(msg.format(invalid = ', '.join(f'{i!r}' for i in invalid)))
streams = []
for stream in self.streams:
contents = stream.contents
applicable_kws = {k:v for k,v in kwargs.items()
if k in set(contents.keys())}
if not applicable_kws and contents:
continue
streams.append(stream)
rkwargs = util.rename_stream_kwargs(stream, applicable_kws, reverse=True)
stream.update(**rkwargs)
Stream.trigger(streams)
def _style(self, retval):
"Applies custom option tree to values return by the callback."
from ..util import opts
if self.id not in Store.custom_options():
return retval
spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])
return opts.apply_groups(retval, options=spec)
def _execute_callback(self, *args):
"Executes the callback with the appropriate args and kwargs"
self._validate_key(args) # Validate input key
# Additional validation needed to ensure kwargs don't clash
kdims = [kdim.name for kdim in self.kdims]
kwarg_items = [s.contents.items() for s in self.streams]
hash_items = tuple(tuple(sorted(s.hashkey.items())) for s in self.streams)+args
flattened = [(k,v) for kws in kwarg_items for (k,v) in kws
if k not in kdims]
if self.positional_stream_args:
kwargs = {}
args = args + tuple([s.contents for s in self.streams])
elif self._posarg_keys:
kwargs = dict(flattened, **dict(zip(self._posarg_keys, args)))
args = ()
else:
kwargs = dict(flattened)
if not isinstance(self.callback, Generator):
kwargs['_memoization_hash_'] = hash_items
with dynamicmap_memoization(self.callback, self.streams):
retval = self.callback(*args, **kwargs)
return self._style(retval)
def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object.
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects returned by the DynamicMap a simple
format may be used, e.g.:
obj.options(cmap='viridis', show_title=False)
If the object is nested the options must be qualified using
a type[.group][.label] specification, e.g.:
obj.options('Image', cmap='viridis', show_title=False)