/
spaces.py
1184 lines (1014 loc) · 48.5 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 numbers import Number
from itertools import groupby
from functools import partial
import numpy as np
import param
from . import traversal, util
from .dimension import OrderedDict, Dimension, ViewableElement
from .layout import Layout, AdjointLayout, NdLayout
from .ndmapping import UniformNdMapping, NdMapping, item_check
from .overlay import Overlay, CompositeOverlay, NdOverlay, Overlayable
from .options import Store, StoreOptions
class HoloMap(UniformNdMapping, Overlayable):
"""
A HoloMap can hold any number of DataLayers indexed by a list of
dimension values. It also has a number of properties, which can find
the x- and y-dimension limits and labels.
"""
data_type = (ViewableElement, NdMapping, Layout)
def overlay(self, dimensions=None, **kwargs):
"""
Splits the UniformNdMapping along a specified number of dimensions and
overlays items in the split out Maps.
Shows all HoloMap data When no dimensions are specified.
"""
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):
"""
GridSpace takes a list of one or two dimensions, and lays out the containing
Views along these axes in a GridSpace.
Shows all HoloMap data When no dimensions are specified.
"""
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):
"""
GridSpace takes a list of one or two dimensions, and lays out the containing
Views along these axes in a GridSpace.
Shows all HoloMap data When no dimensions are specified.
"""
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 split_overlays(self):
"""
Given a UniformNdMapping of Overlays of N layers, split out the layers into
N separate Maps.
"""
if not issubclass(self.type, CompositeOverlay):
return None, self.clone()
item_maps = OrderedDict()
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 = dict([(g, [v for _, v in group])
for g, group in groupby(keys, lambda x: x[0])])
dimensions = [d(values=grouped[d.name]) for d in dimensions]
map_obj = None
map_obj = self if isinstance(self, DynamicMap) else other
def dynamic_mul(*key, **kwargs):
layers = []
try:
if isinstance(self, DynamicMap):
safe_key = () if not self.kdims else key
_, self_el = util.get_dynamic_item(self, dimensions, safe_key)
if self_el is not None:
layers.append(self_el)
else:
layers.append(self[key])
except KeyError:
pass
try:
if isinstance(other, DynamicMap):
safe_key = () if not other.kdims else key
_, other_el = util.get_dynamic_item(other, dimensions, safe_key)
if other_el is not None:
layers.append(other_el)
else:
layers.append(other[key])
except KeyError:
pass
return Overlay(layers)
callback = Callable(callable_function=dynamic_mul, inputs=[self, other])
if map_obj:
return map_obj.clone(callback=callback, shared_data=False,
kdims=dimensions, streams=[])
else:
return DynamicMap(callback=callback, kdims=dimensions)
def __mul__(self, other):
"""
The mul (*) operator implements overlaying of different Views.
This method tries to intelligently overlay Maps 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):
items.append((new_key, self[self_key] * other[other_key]))
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):
if isinstance(self, DynamicMap):
def dynamic_mul(*args, **kwargs):
element = self[args]
return element * other
callback = Callable(callable_function=dynamic_mul,
inputs=[self, other])
return self.clone(shared_data=False, callback=callback,
streams=[])
items = [(k, v * other) for (k, v) in self.data.items()]
return self.clone(items, label=self._label, group=self._group)
else:
return NotImplemented
def __add__(self, obj):
return Layout.from_values([self, obj])
def __lshift__(self, other):
if isinstance(other, (ViewableElement, UniformNdMapping)):
return AdjointLayout([self, other])
elif isinstance(other, AdjointLayout):
return AdjointLayout(other.data+[self])
else:
raise TypeError('Cannot append {0} to a AdjointLayout'.format(type(other).__name__))
def collate(self, merge_type=None, drop=[], drop_constant=False):
"""
Collation allows collapsing nested HoloMaps by merging
their dimensions. 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.
Specific dimensions may be dropped if they are redundant
by supplying them in a list. Enabling drop_constant allows
ignoring any non-varying dimensions during collation.
"""
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 collapse(self, dimensions=None, function=None, spreadfn=None, **kwargs):
"""
Allows collapsing one of any number of key dimensions
on the HoloMap. Homogenous Elements may be collapsed by
supplying a function, inhomogenous elements are merged.
"""
from .operation import MapOperation
if not dimensions:
dimensions = self.kdims
if not isinstance(dimensions, list): dimensions = [dimensions]
if self.ndims > 1 and len(dimensions) != self.ndims:
groups = self.groupby([dim for dim in self.kdims
if dim not in dimensions])
elif all(d in self.kdims for d in dimensions):
groups = HoloMap([(0, self)])
else:
raise KeyError("Supplied dimensions not found.")
collapsed = groups.clone(shared_data=False)
for key, group in groups.items():
if isinstance(function, MapOperation):
collapsed[key] = function(group, **kwargs)
else:
group_data = [el.data for el in group]
args = (group_data, function, group.last.kdims)
if hasattr(group.last, 'interface'):
col_data = group.type(group.table().aggregate(group.last.kdims, function, spreadfn, **kwargs))
else:
data = group.type.collapse_data(*args, **kwargs)
col_data = group.last.clone(data)
collapsed[key] = col_data
return collapsed if self.ndims > 1 else collapsed.last
def sample(self, samples=[], bounds=None, **sample_values):
"""
Sample each Element in the UniformNdMapping by passing either a list of
samples or a tuple specifying the number of regularly spaced
samples per dimension. Alternatively, a single sample may be
requested using dimension-value pairs. Optionally, the bounds
argument can be used to specify the bounding extent from which
the coordinates are to regularly sampled. Regular sampling
assumes homogenous and regularly sampled data.
For 1D sampling, the shape is simply as the desired number of
samples (and not a tuple). The bounds format for 1D sampling
is the tuple (lower, upper) and the tuple (left, bottom,
right, top) for 2D sampling.
"""
dims = self.last.ndims
if isinstance(samples, tuple) or np.isscalar(samples):
if dims == 1:
xlim = self.last.range(0)
lower, upper = (xlim[0], xlim[1]) if bounds is None else bounds
edges = np.linspace(lower, upper, samples+1)
linsamples = [(l+u)/2.0 for l,u in zip(edges[:-1], edges[1:])]
elif dims == 2:
(rows, cols) = samples
if bounds:
(l,b,r,t) = bounds
else:
l, r = self.last.range(0)
b, t = self.last.range(1)
xedges = np.linspace(l, r, cols+1)
yedges = np.linspace(b, t, rows+1)
xsamples = [(lx+ux)/2.0 for lx,ux in zip(xedges[:-1], xedges[1:])]
ysamples = [(ly+uy)/2.0 for ly,uy in zip(yedges[:-1], yedges[1:])]
Y,X = np.meshgrid(ysamples, xsamples)
linsamples = zip(X.flat, Y.flat)
else:
raise NotImplementedError("Regular sampling not implemented "
"for high-dimensional Views.")
samples = list(util.unique_iterator(self.last.closest(linsamples)))
sampled = self.clone([(k, view.sample(samples, **sample_values))
for k, view in self.data.items()])
return sampled.table()
def reduce(self, dimensions=None, function=None, **reduce_map):
"""
Reduce each Element in the HoloMap using a function supplied
via the kwargs, where the keyword has to match a particular
dimension in the Elements.
"""
from ..element import Table
reduced_items = [(k, v.reduce(dimensions, function, **reduce_map))
for k, v in self.items()]
if not isinstance(reduced_items[0][1], Table):
params = dict(util.get_param_values(self.last),
kdims=self.kdims, vdims=self.last.vdims)
return Table(reduced_items, **params)
return self.clone(reduced_items).table()
def relabel(self, label=None, group=None, depth=1):
# Identical to standard relabel method except for default depth of 1
return super(HoloMap, self).relabel(label=label, group=group, depth=depth)
def hist(self, num_bins=20, bin_range=None, adjoin=True, individually=True, **kwargs):
histmaps = [self.clone(shared_data=False) for _ in
kwargs.get('dimension', range(1))]
if individually:
map_range = None
else:
if 'dimension' not in kwargs:
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, bin_range=bin_range,
individually=individually, 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
else:
if len(histmaps) > 1:
return Layout.from_values(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 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.
A Callable may also specify a stream_mapping which allows
specifying which objects to attached linked streams to on
callbacks which return composite objects like (Nd)Layout and
GridSpace objects. The mapping should map between an integer index
or a type[.group][.label] specification and lists of streams
matching the object.
"""
callable_function = param.Callable(default=lambda x: x, doc="""
The callable function being wrapped.""")
inputs = param.List(default=[], doc="""
The list of inputs the callable function is wrapping.""")
def __init__(self, callable_function=None, stream_mapping={}, **params):
if callable_function is not None:
params['callable_function'] = callable_function
super(Callable, self).__init__(**params)
self._memoized = {}
self.stream_mapping = stream_mapping
def __call__(self, *args, **kwargs):
inputs = [i for i in self.inputs if isinstance(i, DynamicMap)]
streams = [s for i in inputs for s in get_nested_streams(i)]
values = tuple(tuple(sorted(s.contents.items())) for s in streams)
key = args + tuple(sorted(kwargs.items())) + values
hashed_key = util.deephash(key)
ret = self._memoized.get(hashed_key, None)
if hashed_key and ret is None:
ret = self.callable_function(*args, **kwargs)
self._memoized = {hashed_key : ret}
return ret
def get_nested_streams(dmap):
"""
Get all (potentially nested) streams from DynamicMap with Callable
callback.
"""
layer_streams = list(dmap.streams)
if not isinstance(dmap.callback, Callable):
return list(set(layer_streams))
for o in dmap.callback.inputs:
if isinstance(o, DynamicMap):
layer_streams += get_nested_streams(o)
return list(set(layer_streams))
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']
callback = param.ClassSelector(class_=Callable, 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=[], 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.""" )
cache_size = param.Integer(default=500, 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.""")
sampled = param.Boolean(default=False, doc="""
Allows defining a DynamicMap without defining the dimension
bounds or values. The DynamicMap may then be explicitly sampled
via getitem or the sampling is determined during plotting by a
HoloMap with fixed sampling.
""")
def __init__(self, callback, initial_items=None, **params):
if not isinstance(callback, Callable):
callback = Callable(callable_function=callback)
super(DynamicMap, self).__init__(initial_items, callback=callback, **params)
# Set source to self if not already specified
for stream in self.streams:
if stream.source is None:
stream.source = self
def _initial_key(self):
"""
Construct an initial key for based on the lower range bounds or
values on the key dimensions.
"""
key = []
undefined = []
for kdim in self.kdims:
if kdim.values:
key.append(kdim.values[0])
elif kdim.range:
key.append(kdim.range[0])
else:
undefined.append(kdim)
if undefined:
raise KeyError('dimensions do not specify a range or values, '
'cannot supply initial key' % ', '.join(undefined))
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.
"""
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 low is not np.NaN:
if val < low:
raise StopIteration("Key value %s below lower bound %s"
% (val, low))
if high is not np.NaN:
if val > high:
raise StopIteration("Key value %s above upper bound %s"
% (val, high))
def event(self, trigger=True, **kwargs):
"""
This method allows any of the available stream parameters
(renamed as appropriate) to be updated in an event.
"""
stream_params = set(util.stream_parameters(self.streams))
for k in stream_params - set(kwargs.keys()):
raise KeyError('Key %r does not correspond to any stream parameter')
updated_streams = []
for stream in self.streams:
applicable_kws = {k:v for k,v in kwargs.items()
if k in set(stream.contents.keys())}
rkwargs = util.rename_stream_kwargs(stream, applicable_kws, reverse=True)
stream.update(**dict(rkwargs, trigger=False))
updated_streams.append(stream)
if updated_streams and trigger:
updated_streams[0].trigger(updated_streams)
def _style(self, retval):
"""
Use any applicable OptionTree of the DynamicMap to apply options
to the return values of the callback.
"""
if self.id not in Store.custom_options():
return retval
spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])
return retval(spec)
def _execute_callback(self, *args):
"""
Execute the callback, validating both the input key and output
key where applicable.
"""
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]
flattened = [(k,v) for kws in kwarg_items for (k,v) in kws
if k not in kdims]
retval = self.callback(*args, **dict(flattened))
return self._style(retval)
def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides):
"""
Clone method to adapt the slightly different signature of
DynamicMap that also overrides Dimensioned clone to avoid
checking items if data is unchanged.
"""
if data is None and shared_data:
data = self.data
return super(UniformNdMapping, self).clone(overrides.pop('callback', self.callback),
shared_data, new_type,
*(data,) + args, **overrides)
def reset(self):
"""
Return a cleared dynamic map with a cleared cached
"""
self.data = OrderedDict()
return self
def _cross_product(self, tuple_key, cache, data_slice):
"""
Returns a new DynamicMap if the key (tuple form) expresses a
cross product, otherwise returns None. The cache argument is a
dictionary (key:element pairs) of all the data found in the
cache for this key.
Each key inside the cross product is looked up in the cache
(self.data) to check if the appropriate element is
available. Otherwise the element is computed accordingly.
The data_slice may specify slices into each value in the
the cross-product.
"""
if not any(isinstance(el, (list, set)) for el in tuple_key):
return None
if len(tuple_key)==1:
product = tuple_key[0]
else:
args = [set(el) if isinstance(el, (list,set))
else set([el]) for el in tuple_key]
product = itertools.product(*args)
data = []
for inner_key in product:
key = util.wrap_tuple(inner_key)
if key in cache:
val = cache[key]
else:
val = self._execute_callback(*key)
if data_slice:
val = self._dataslice(val, data_slice)
data.append((key, val))
product = self.clone(data)
if data_slice:
from ..util import Dynamic
return Dynamic(product, operation=lambda obj: obj[data_slice],
shared_data=True)
return product
def _slice_bounded(self, tuple_key, data_slice):
"""
Slices bounded DynamicMaps by setting the soft_ranges on
key dimensions and applies data slice to cached and dynamic
values.
"""
slices = [el for el in tuple_key if isinstance(el, slice)]
if any(el.step for el in slices):
raise Exception("DynamicMap slices cannot have a step argument")
elif len(slices) not in [0, len(tuple_key)]:
raise Exception("Slices must be used exclusively or not at all")
elif not slices:
return None
sliced = self.clone(self)
for i, slc in enumerate(tuple_key):
(start, stop) = slc.start, slc.stop
if start is not None and start < sliced.kdims[i].range[0]:
raise Exception("Requested slice below defined dimension range.")
if stop is not None and stop > sliced.kdims[i].range[1]:
raise Exception("Requested slice above defined dimension range.")
sliced.kdims[i].soft_range = (start, stop)
if data_slice:
if not isinstance(sliced, DynamicMap):
return self._dataslice(sliced, data_slice)
else:
from ..util import Dynamic
if len(self):
slices = [slice(None) for _ in range(self.ndims)] + list(data_slice)
sliced = super(DynamicMap, sliced).__getitem__(tuple(slices))
return Dynamic(sliced, operation=lambda obj: obj[data_slice],
shared_data=True)
return sliced
def __getitem__(self, key):
"""
Return an element for any key chosen key. Also allows for usual
deep slicing semantics by slicing values in the cache and
applying the deep slice to newly generated values.
"""
# Split key dimensions and data slices
sample = False
if key is Ellipsis:
return self
elif isinstance(key, (list, set)) and all(isinstance(v, tuple) for v in key):
map_slice, data_slice = key, ()
sample = True
else:
map_slice, data_slice = self._split_index(key)
tuple_key = util.wrap_tuple_streams(map_slice, self.kdims, self.streams)
# Validation
if not sample:
sliced = self._slice_bounded(tuple_key, data_slice)
if sliced is not None:
return sliced
# Cache lookup
try:
dimensionless = util.dimensionless_contents(get_nested_streams(self),
self.kdims, no_duplicates=False)
if dimensionless:
raise KeyError('Using dimensionless streams disables DynamicMap cache')
cache = super(DynamicMap,self).__getitem__(key)
except KeyError as e:
cache = None
# If the key expresses a cross product, compute the elements and return
product = self._cross_product(tuple_key, cache.data if cache else {}, data_slice)
if product is not None:
return product
# Not a cross product and nothing cached so compute element.
if cache is not None: return cache
val = self._execute_callback(*tuple_key)
if data_slice:
val = self._dataslice(val, data_slice)
self._cache(tuple_key, val)
return val
def select(self, selection_specs=None, **kwargs):
"""
Allows slicing or indexing into the DynamicMap objects by
supplying the dimension and index/slice as key value
pairs. Select descends recursively through the data structure
applying the key dimension selection and applies to dynamically
generated items by wrapping the callback.
The selection may also be selectively applied to specific
objects by supplying the selection_specs as an iterable of
type.group.label specs, types or functions.
"""
if selection_specs is not None and not isinstance(selection_specs, (list, tuple)):
selection_specs = [selection_specs]
selection = super(DynamicMap, self).select(selection_specs, **kwargs)
def dynamic_select(obj):
if selection_specs is not None:
matches = any(obj.matches(spec) for spec in selection_specs)
else:
matches = True
if matches:
return obj.select(**kwargs)
return obj
if not isinstance(selection, DynamicMap):
return dynamic_select(selection)
else:
from ..util import Dynamic
return Dynamic(selection, operation=dynamic_select,
shared_data=True)
def _cache(self, key, val):
"""
Request that a key/value pair be considered for caching.
"""
cache_size = (1 if util.dimensionless_contents(self.streams, self.kdims)
else self.cache_size)
if len(self) >= cache_size:
first_key = next(k for k in self.data)
self.data.pop(first_key)
self.data[key] = val
def relabel(self, label=None, group=None, depth=1):
"""
Assign a new label and/or group to an existing LabelledData
object, creating a clone of the object with the new settings.
"""
relabelled = super(DynamicMap, self).relabel(label, group, depth)
if depth > 0:
from ..util import Dynamic
def dynamic_relabel(obj):
return obj.relabel(group=group, label=label, depth=depth-1)
return Dynamic(relabelled, shared_data=True, operation=dynamic_relabel)
return relabelled
def redim(self, specs=None, **dimensions):
"""
Replaces existing dimensions in an object with new dimensions
or changing specific attributes of a dimensions. Dimension
mapping should map between the old dimension name and a
dictionary of the new attributes, a completely new dimension
or a new string name.
"""
redimmed = super(DynamicMap, self).redim(specs, **dimensions)
from ..util import Dynamic
def dynamic_redim(obj):
return obj.redim(specs, **dimensions)
return Dynamic(redimmed, shared_data=True, operation=dynamic_redim)
def collate(self):
"""
Collation allows collapsing DynamicMaps with invalid nesting
hierarchies. This is particularly useful when defining
DynamicMaps returning an (Nd)Layout or GridSpace
type. Collating will split the DynamicMap into of individual
DynamicMaps. Note that the composite object has to be of
consistent length and types for this to work
correctly. Associating streams with specific viewables in the
returned container declare a stream_mapping on the DynamicMap
Callable during instantiation.
"""
# Initialize
if self.last is not None:
pass
else:
self[self._initial_key()]
if isinstance(self.last, HoloMap):
# Get nested kdims and streams
streams = list(self.streams)
if isinstance(self.last, DynamicMap):
dimensions = [d(values=self.last.dimension_values(d.name))
for d in self.last.kdims]
streams += self.last.streams
stream_kwargs = set()
for stream in streams:
contents = set(stream.contents())
if stream_kwargs & contents:
raise KeyError('Cannot collate DynamicMaps with clashing '
'stream parameters.')
else:
dimensions = self.last.kdims
kdims = self.kdims+dimensions
# Define callback
def collation_cb(*args, **kwargs):
return self[args[:self.ndims]][args[self.ndims:]]
callback = Callable(collation_cb, inputs=[self])
return self.clone(shared_data=False, callback=callback,
kdims=kdims, streams=streams)
elif isinstance(self.last, (Layout, NdLayout, GridSpace)):
# Expand Layout/NdLayout
from ..util import Dynamic
new_item = self.last.clone(shared_data=False)
# Get stream mapping from callback
remapped_streams = []
streams = self.callback.stream_mapping
for i, (k, v) in enumerate(self.last.data.items()):
vstreams = streams.get(i, [])
if not vstreams:
if isinstance(self.last, Layout):
for l in range(len(k)):
path = '.'.join(k[:l])
if path in streams:
vstreams = streams[path]
break
else:
vstreams = streams.get(k, [])
if any(s in remapped_streams for s in vstreams):
raise ValueError(
"The stream_mapping supplied on the Callable "
"is ambiguous please supply more specific Layout "
"path specs.")
remapped_streams += vstreams
# Define collation callback
def collation_cb(*args, **kwargs):
return self[args][kwargs['collation_key']]
callback = Callable(partial(collation_cb, collation_key=k),
inputs=[self])
vdmap = self.clone(callback=callback, shared_data=False,
streams=vstreams)
# Remap source of streams
for stream in vstreams:
if stream.source is self:
stream.source = vdmap
new_item[k] = vdmap
unmapped_streams = [repr(stream) for stream in self.streams
if (stream.source is self) and
(stream not in remapped_streams)
and stream.linked]
if unmapped_streams:
raise ValueError(
'The following streams are set to be automatically '
'linked to a plot, but no stream_mapping specifying '
'which item in the (Nd)Layout to link it to was found:\n%s'
% ', '.join(unmapped_streams)
)
return new_item
else:
self.warning('DynamicMap does not need to be collated.')
return dmap
def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs):
"""
Implements a dynamic version of a groupby, which will
intelligently expand either the inner or outer dimensions
depending on whether the container_type or group_type is dynamic.
To apply a groupby to a DynamicMap the dimensions, which are
expanded into a non-dynamic type must define a fixed sampling
via the values attribute.
Using the dynamic groupby makes it incredibly easy to generate
dynamic views into a high-dimensional space while taking
advantage of the capabilities of NdOverlay, GridSpace and
NdLayout types to visualize more than one Element at a time.
"""
if dimensions is None:
dimensions = self.kdims
if not isinstance(dimensions, (list, tuple)):
dimensions = [dimensions]
container_type = container_type if container_type else type(self)
group_type = group_type if group_type else type(self)
outer_kdims = [self.get_dimension(d) for d in dimensions]
inner_kdims = [d for d in self.kdims if not d in outer_kdims]
outer_dynamic = issubclass(container_type, DynamicMap)
inner_dynamic = issubclass(group_type, DynamicMap)
if ((not outer_dynamic and any(not d.values for d in outer_kdims)) or
(not inner_dynamic and any(not d.values for d in inner_kdims))):
raise Exception('Dimensions must specify sampling via '
'values to apply a groupby')
if outer_dynamic:
def outer_fn(*outer_key):
if inner_dynamic:
def inner_fn(*inner_key):
outer_vals = zip(outer_kdims, util.wrap_tuple(outer_key))
inner_vals = zip(inner_kdims, util.wrap_tuple(inner_key))
inner_sel = [(k.name, v) for k, v in inner_vals]
outer_sel = [(k.name, v) for k, v in outer_vals]
return self.select(**dict(inner_sel+outer_sel))
return self.clone([], callback=inner_fn, kdims=inner_kdims)
else:
dim_vals = [(d.name, d.values) for d in inner_kdims]
dim_vals += [(d.name, [v]) for d, v in
zip(outer_kdims, util.wrap_tuple(outer_key))]
return group_type(self.select(**dict(dim_vals))).reindex(inner_kdims)
if outer_kdims:
return self.clone([], callback=outer_fn, kdims=outer_kdims)
else:
return outer_fn(())
else:
outer_product = itertools.product(*[self.get_dimension(d).values
for d in dimensions])
groups = []
for outer in outer_product:
outer_vals = [(d.name, [o]) for d, o in zip(outer_kdims, outer)]
if inner_dynamic or not inner_kdims:
def inner_fn(outer_vals, *key):
inner_dims = zip(inner_kdims, util.wrap_tuple(key))
inner_vals = [(d.name, k) for d, k in inner_dims]
return self.select(**dict(outer_vals+inner_vals)).last
if inner_kdims:
group = self.clone(callback=partial(inner_fn, outer_vals),
kdims=inner_kdims)
else:
group = inner_fn(outer_vals, ())
groups.append((outer, group))
else:
inner_vals = [(d.name, self.get_dimension(d).values)
for d in inner_kdims]
group = group_type(self.select(**dict(outer_vals+inner_vals)).reindex(inner_kdims))
groups.append((outer, group))
return container_type(groups, kdims=outer_kdims)
def grid(self, dimensions=None, **kwargs):
return self.groupby(dimensions, container_type=GridSpace, **kwargs)
def layout(self, dimensions=None, **kwargs):
return self.groupby(dimensions, container_type=NdLayout, **kwargs)
def overlay(self, dimensions=None, **kwargs):
if dimensions is None:
dimensions = self.kdims
else:
if not isinstance(dimensions, (list, tuple)):
dimensions = [dimensions]
dimensions = [self.get_dimension(d, strict=True)
for d in dimensions]
dims = [d for d in self.kdims if d not in dimensions]