/
plot.py
1941 lines (1676 loc) · 80.2 KB
/
plot.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
"""
Public API for all plots supported by HoloViews, regardless of
plotting package or backend. Every plotting classes must be a subclass
of this Plot baseclass.
"""
import uuid
import warnings
from collections import Counter, defaultdict, OrderedDict
from functools import partial
from itertools import groupby, product
import numpy as np
import param
from panel.config import config
from panel.io.document import unlocked
from panel.io.notebook import push
from panel.io.state import state
from pyviz_comms import JupyterComm
from ..selection import NoOpSelectionDisplay
from ..core import util, traversal
from ..core.data import Dataset, disable_pipeline
from ..core.element import Element, Element3D
from ..core.overlay import Overlay, CompositeOverlay
from ..core.layout import Empty, NdLayout, Layout
from ..core.options import Store, Compositor, SkipRendering, lookup_options
from ..core.overlay import NdOverlay
from ..core.spaces import HoloMap, DynamicMap
from ..core.util import stream_parameters, isfinite
from ..element import Table, Graph
from ..streams import Stream, RangeXY, RangeX, RangeY
from ..util.transform import dim
from .util import (
get_dynamic_mode, initialize_unbounded, dim_axis_label,
attach_streams, traverse_setter, get_nested_streams,
compute_overlayable_zorders, get_nested_plot_frame,
split_dmap_overlay, get_axis_padding, get_range, get_minimum_span,
get_plot_frame, scale_fontsize, dynamic_update
)
class Plot(param.Parameterized):
"""
Base class of all Plot classes in HoloViews, designed to be
general enough to use any plotting package or backend.
"""
backend = None
# A list of style options that may be supplied to the plotting
# call
style_opts = []
# Sometimes matplotlib doesn't support the common aliases.
# Use this list to disable any invalid style options
_disabled_opts = []
def __init__(self, renderer=None, root=None, **params):
params = {k: v for k, v in params.items()
if k in self.param}
super().__init__(**params)
self.renderer = renderer if renderer else Store.renderers[self.backend].instance()
self._force = False
self._comm = None
self._document = None
self._root = None
self._pane = None
self._triggering = []
self._trigger = []
self.set_root(root)
@property
def state(self):
"""
The plotting state that gets updated via the update method and
used by the renderer to generate output.
"""
raise NotImplementedError
def set_root(self, root):
"""
Sets the root model on all subplots.
"""
if root is None:
return
for plot in self.traverse(lambda x: x):
plot._root = root
@property
def root(self):
if self._root:
return self._root
elif 'plot' in self.handles and self.top_level:
return self.state
else:
return None
@property
def document(self):
return self._document
@document.setter
def document(self, doc):
if (doc and hasattr(doc, 'on_session_destroyed') and
self.root is self.handles.get('plot') and
not isinstance(self, GenericAdjointLayoutPlot)):
doc.on_session_destroyed(self._session_destroy)
if self._document:
if isinstance(self._document.callbacks._session_destroyed_callbacks, set):
self._document.callbacks._session_destroyed_callbacks.discard(self._session_destroy)
else:
self._document.callbacks._session_destroyed_callbacks.pop(self._session_destroy, None)
self._document = doc
if self.subplots:
for plot in self.subplots.values():
if plot is not None:
plot.document = doc
@property
def pane(self):
return self._pane
@pane.setter
def pane(self, pane):
if (config.console_output != 'disable' and self.root and
self.root.ref['id'] not in state._handles and
isinstance(self.comm, JupyterComm)):
from IPython.display import display
handle = display(display_id=uuid.uuid4().hex)
state._handles[self.root.ref['id']] = (handle, [])
self._pane = pane
if self.subplots:
for plot in self.subplots.values():
if plot is not None:
plot.pane = pane
if plot is None or not plot.root:
continue
for cb in getattr(plot, 'callbacks', []):
if hasattr(pane, '_on_error') and getattr(cb, 'comm', None):
cb.comm._on_error = partial(pane._on_error, plot.root.ref['id'])
elif self.root:
for cb in getattr(self, 'callbacks', []):
if hasattr(pane, '_on_error') and getattr(cb, 'comm', None):
cb.comm._on_error = partial(pane._on_error, self.root.ref['id'])
@property
def comm(self):
return self._comm
@comm.setter
def comm(self, comm):
self._comm = comm
if self.subplots:
for plot in self.subplots.values():
if plot is not None:
plot.comm = comm
def initialize_plot(self, ranges=None):
"""
Initialize the matplotlib figure.
"""
raise NotImplementedError
def update(self, key):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
return self.state
def cleanup(self):
"""
Cleans up references to the plot on the attached Stream
subscribers.
"""
plots = self.traverse(lambda x: x, [Plot])
for plot in plots:
if not isinstance(plot, (GenericCompositePlot, GenericElementPlot, GenericOverlayPlot)):
continue
for stream in set(plot.streams):
stream._subscribers = [
(p, subscriber) for p, subscriber in stream._subscribers
if not util.is_param_method(subscriber) or
util.get_method_owner(subscriber) not in plots
]
def _session_destroy(self, session_context):
self.cleanup()
def refresh(self, **kwargs):
"""
Refreshes the plot by rerendering it and then pushing
the updated data if the plot has an associated Comm.
"""
if self.renderer.mode == 'server' and not state._unblocked(self.document):
# If we do not have the Document lock, schedule refresh as callback
self._triggering += [s for p in self.traverse(lambda x: x, [Plot])
for s in getattr(p, 'streams', []) if s._triggering]
if self.document and self.document.session_context:
self.document.add_next_tick_callback(self.refresh)
return
# Ensure that server based tick callbacks maintain stream triggering state
for s in self._triggering:
s._triggering = True
try:
traverse_setter(self, '_force', True)
key = self.current_key if self.current_key else self.keys[0]
dim_streams = [stream for stream in self.streams
if any(c in self.dimensions for c in stream.contents)]
stream_params = stream_parameters(dim_streams)
key = tuple(None if d in stream_params else k
for d, k in zip(self.dimensions, key))
stream_key = util.wrap_tuple_streams(key, self.dimensions, self.streams)
self._trigger_refresh(stream_key)
if self.top_level:
self.push()
except Exception as e:
raise e
finally:
# Reset triggering state
for s in self._triggering:
s._triggering = False
self._triggering = []
def _trigger_refresh(self, key):
"Triggers update to a plot on a refresh event"
# Update if not top-level, batched or an ElementPlot
if not self.top_level or isinstance(self, GenericElementPlot):
with unlocked():
self.update(key)
def push(self):
"""
Pushes plot updates to the frontend.
"""
root = self._root
if (root and self.pane is not None and
root.ref['id'] in self.pane._plots):
child_pane = self.pane._plots[root.ref['id']][1]
else:
child_pane = None
if self.renderer.backend != 'bokeh' and child_pane is not None:
child_pane.object = self.renderer.get_plot_state(self)
elif (self.renderer.mode != 'server' and root and
'embedded' not in root.tags and self.document and self.comm):
push(self.document, self.comm)
@property
def id(self):
return self.comm.id if self.comm else id(self.state)
def __len__(self):
"""
Returns the total number of available frames.
"""
raise NotImplementedError
@classmethod
def lookup_options(cls, obj, group):
return lookup_options(obj, group, cls.backend)
class PlotSelector:
"""
Proxy that allows dynamic selection of a plotting class based on a
function of the plotted object. Behaves like a Plot class and
presents the same parameterized interface.
"""
_disabled_opts = []
def __init__(self, selector, plot_classes, allow_mismatch=False):
"""
The selector function accepts a component instance and returns
the appropriate key to index plot_classes dictionary.
"""
self.selector = selector
self.plot_classes = OrderedDict(plot_classes)
interface = self._define_interface(self.plot_classes.values(), allow_mismatch)
self.style_opts, self.plot_options = interface
def selection_display(self, obj):
plt_class = self.get_plot_class(obj)
return getattr(plt_class, 'selection_display', None)
def _define_interface(self, plots, allow_mismatch):
parameters = [{k:v.precedence for k,v in plot.param.params().items()
if ((v.precedence is None) or (v.precedence >= 0))}
for plot in plots]
param_sets = [set(params.keys()) for params in parameters]
if not allow_mismatch and not all(pset == param_sets[0] for pset in param_sets):
raise Exception("All selectable plot classes must have identical plot options.")
styles= [plot.style_opts for plot in plots]
if not allow_mismatch and not all(style == styles[0] for style in styles):
raise Exception("All selectable plot classes must have identical style options.")
plot_params = {p: v for params in parameters for p, v in params.items()}
return [s for style in styles for s in style], plot_params
def __call__(self, obj, **kwargs):
plot_class = self.get_plot_class(obj)
return plot_class(obj, **kwargs)
def get_plot_class(self, obj):
key = self.selector(obj)
if key not in self.plot_classes:
msg = "Key %s returned by selector not in set: %s"
raise Exception(msg % (key, ', '.join(self.plot_classes.keys())))
return self.plot_classes[key]
def __setattr__(self, label, value):
try:
return super().__setattr__(label, value)
except Exception:
raise Exception("Please set class parameters directly on classes %s"
% ', '.join(str(cls) for cls in self.__dict__['plot_classes'].values()))
def params(self):
return self.plot_options
@property
def param(self):
return self.plot_options
class DimensionedPlot(Plot):
"""
DimensionedPlot implements a number of useful methods
to compute dimension ranges and titles containing the
dimension values.
"""
fontsize = param.Parameter(default=None, allow_None=True, doc="""
Specifies various font sizes of the displayed text.
Finer control is available by supplying a dictionary where any
unmentioned keys revert to the default sizes, e.g:
{'ticks':20, 'title':15,
'ylabel':5, 'xlabel':5, 'zlabel':5,
'legend':8, 'legend_title':13}
You can set the font size of 'zlabel', 'ylabel' and 'xlabel'
together using the 'labels' key.""")
fontscale = param.Number(default=None, doc="""
Scales the size of all fonts.""")
#Allowed fontsize keys
_fontsize_keys = ['xlabel','ylabel', 'zlabel', 'clabel', 'labels',
'xticks', 'yticks', 'zticks', 'cticks', 'ticks',
'minor_xticks', 'minor_yticks', 'minor_ticks',
'title', 'legend', 'legend_title',
]
show_title = param.Boolean(default=True, doc="""
Whether to display the plot title.""")
title = param.String(default="{label} {group}\n{dimensions}", doc="""
The formatting string for the title of this plot, allows defining
a label group separator and dimension labels.""")
normalize = param.Boolean(default=True, doc="""
Whether to compute ranges across all Elements at this level
of plotting. Allows selecting normalization at different levels
for nested data containers.""")
projection = param.Parameter(default=None, doc="""
Allows supplying a custom projection to transform the axis
coordinates during display. Example projections include '3d'
and 'polar' projections supported by some backends. Depending
on the backend custom, projection objects may be supplied.""")
def __init__(self, keys=None, dimensions=None, layout_dimensions=None,
uniform=True, subplot=False, adjoined=None, layout_num=0,
style=None, subplots=None, dynamic=False, **params):
self.subplots = subplots
self.adjoined = adjoined
self.dimensions = dimensions
self.layout_num = layout_num
self.layout_dimensions = layout_dimensions
self.subplot = subplot
self.keys = keys if keys is None else list(keys)
self.uniform = uniform
self.dynamic = dynamic
self.drawn = False
self.handles = {}
self.group = None
self.label = None
self.current_frame = None
self.current_key = None
self.ranges = {}
self._updated = False # Whether the plot should be marked as updated
super().__init__(**params)
def __getitem__(self, frame):
"""
Get the state of the Plot for a given frame number.
"""
if isinstance(frame, int) and frame > len(self):
self.param.warning(f"Showing last frame available: {len(self)}")
if not self.drawn: self.handles['fig'] = self.initialize_plot()
if not isinstance(frame, tuple):
frame = self.keys[frame]
self.update_frame(frame)
return self.state
def _get_frame(self, key):
"""
Required on each MPLPlot type to get the data corresponding
just to the current frame out from the object.
"""
pass
def matches(self, spec):
"""
Matches a specification against the current Plot.
"""
if callable(spec) and not isinstance(spec, type): return spec(self)
elif isinstance(spec, type): return isinstance(self, spec)
else:
raise ValueError("Matching specs have to be either a type or a callable.")
def traverse(self, fn=None, specs=None, full_breadth=True):
"""
Traverses any nested DimensionedPlot returning a list
of all plots that match the specs. The specs should
be supplied as a list of either Plot types or callables,
which should return a boolean given the plot class.
"""
accumulator = []
matches = specs is None
if not matches:
for spec in specs:
matches = self.matches(spec)
if matches: break
if matches:
accumulator.append(fn(self) if fn else self)
# Assumes composite objects are iterables
if hasattr(self, 'subplots') and self.subplots:
for el in self.subplots.values():
if el is None:
continue
accumulator += el.traverse(fn, specs, full_breadth)
if not full_breadth: break
return accumulator
def _frame_title(self, key, group_size=2, separator='\n'):
"""
Returns the formatted dimension group strings
for a particular frame.
"""
if self.layout_dimensions is not None:
dimensions, key = zip(*self.layout_dimensions.items())
elif not self.dynamic and (not self.uniform or len(self) == 1) or self.subplot:
return ''
else:
key = key if isinstance(key, tuple) else (key,)
dimensions = self.dimensions
dimension_labels = [dim.pprint_value_string(k) for dim, k in
zip(dimensions, key)]
groups = [', '.join(dimension_labels[i*group_size:(i+1)*group_size])
for i in range(len(dimension_labels))]
return util.bytes_to_unicode(separator.join(g for g in groups if g))
def _format_title(self, key, dimensions=True, separator='\n'):
label, group, type_name, dim_title = self._format_title_components(
key, dimensions=True, separator='\n'
)
title = util.bytes_to_unicode(self.title).format(
label=util.bytes_to_unicode(label),
group=util.bytes_to_unicode(group),
type=type_name,
dimensions=dim_title
)
return title.strip(' \n')
def _format_title_components(self, key, dimensions=True, separator='\n'):
"""
Determine components of title as used by _format_title method.
To be overridden in child classes.
Return signature: (label, group, type_name, dim_title)
"""
return (self.label, self.group, type(self).__name__, '')
def _get_fontsize_defaults(self):
"""
Should returns default fontsize for the following keywords:
* ticks
* minor_ticks
* label
* title
* legend
* legend_title
However may also provide more specific defaults for
specific axis label or ticks, e.g. clabel or xticks.
"""
return {}
def _fontsize(self, key, label='fontsize', common=True):
if not self.fontsize and not self.fontscale:
return {}
elif not isinstance(self.fontsize, dict) and self.fontsize is not None and common:
return {label: scale_fontsize(self.fontsize, self.fontscale)}
fontsize = self.fontsize if isinstance(self.fontsize, dict) else {}
unknown_keys = set(fontsize.keys()) - set(self._fontsize_keys)
if unknown_keys:
msg = "Popping unknown keys %r from fontsize dictionary.\nValid keys: %r"
self.param.warning(msg % (list(unknown_keys), self._fontsize_keys))
for key in unknown_keys: fontsize.pop(key, None)
defaults = self._get_fontsize_defaults()
size = None
if key in fontsize:
size = fontsize[key]
elif key in ['zlabel', 'ylabel', 'xlabel', 'clabel']:
size = fontsize.get('labels', defaults.get(key, defaults.get('label')))
elif key in ['xticks', 'yticks', 'zticks', 'cticks']:
size = fontsize.get('ticks', defaults.get(key, defaults.get('ticks')))
elif key in ['minor_xticks', 'minor_yticks']:
size = fontsize.get('minor_ticks', defaults.get(key, defaults.get('minor_ticks')))
elif key in ('legend', 'legend_title', 'title'):
size = defaults.get(key)
if size is None:
return {}
return {label: scale_fontsize(size, self.fontscale)}
def compute_ranges(self, obj, key, ranges):
"""
Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either per frame or
over the whole animation) and finally compute the dimension
ranges in each group. The new set of ranges is returned.
"""
prev_frame = getattr(self, 'prev_frame', None)
all_table = all(isinstance(el, Table) for el in obj.traverse(lambda x: x, [Element]))
if obj is None or not self.normalize or all_table:
return OrderedDict()
# Get inherited ranges
ranges = self.ranges if ranges is None else {k: dict(v) for k, v in ranges.items()}
# Get element identifiers from current object and resolve
# with selected normalization options
norm_opts = self._get_norm_opts(obj)
# Traverse displayed object if normalization applies
# at this level, and ranges for the group have not
# been supplied from a composite plot
return_fn = lambda x: x if isinstance(x, Element) else None
for group, (axiswise, framewise, robust) in norm_opts.items():
axiswise = (not getattr(self, 'shared_axes', True)) or (axiswise)
elements = []
# Skip if ranges are cached or already computed by a
# higher-level container object.
framewise = framewise or self.dynamic or len(elements) == 1
if not framewise: # Traverse to get all elements
elements = obj.traverse(return_fn, [group])
elif key is not None: # Traverse to get elements for each frame
frame = self._get_frame(key)
elements = [] if frame is None else frame.traverse(return_fn, [group])
# Only compute ranges if not axiswise on a composite plot
# or not framewise on a Overlay or ElementPlot
if (not (axiswise and not isinstance(obj, HoloMap)) or
(not framewise and isinstance(obj, HoloMap))):
self._compute_group_range(group, elements, ranges, framewise,
axiswise, robust, self.top_level,
prev_frame)
self.ranges.update(ranges)
return ranges
def _get_norm_opts(self, obj):
"""
Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictionary.
Returns a dictionary of normalization options for each
element in the tree.
"""
norm_opts = {}
# Get all elements' type.group.label specs and ids
type_val_fn = lambda x: (x.id, (type(x).__name__, util.group_sanitizer(x.group, escape=False),
util.label_sanitizer(x.label, escape=False))) \
if isinstance(x, Element) else None
element_specs = {(idspec[0], idspec[1]) for idspec in obj.traverse(type_val_fn)
if idspec is not None}
# Group elements specs by ID and override normalization
# options sequentially
key_fn = lambda x: -1 if x[0] is None else x[0]
id_groups = groupby(sorted(element_specs, key=key_fn), key_fn)
for gid, element_spec_group in id_groups:
gid = None if gid == -1 else gid
group_specs = [el for _, el in element_spec_group]
backend = self.renderer.backend
optstree = Store.custom_options(
backend=backend).get(gid, Store.options(backend=backend))
# Get the normalization options for the current id
# and match against customizable elements
for opts in optstree:
path = tuple(opts.path.split('.')[1:])
applies = any(path == spec[:i] for spec in group_specs
for i in range(1, 4))
if applies and 'norm' in opts.groups:
nopts = opts['norm'].options
popts = opts['plot'].options
if 'axiswise' in nopts or 'framewise' in nopts or 'clim_percentile' in popts:
norm_opts.update({path: (nopts.get('axiswise', False),
nopts.get('framewise', False),
popts.get('clim_percentile', False))})
element_specs = [spec for _, spec in element_specs]
norm_opts.update({spec: (False, False, False) for spec in element_specs
if not any(spec[:i] in norm_opts.keys() for i in range(1, 4))})
return norm_opts
@classmethod
def _merge_group_ranges(cls, ranges):
hard_range = util.max_range(ranges['hard'], combined=False)
soft_range = util.max_range(ranges['soft'])
robust_range = util.max_range(ranges.get('robust', []))
data_range = util.max_range(ranges['data'])
combined = util.dimension_range(data_range[0], data_range[1],
hard_range, soft_range)
dranges = {'data': data_range, 'hard': hard_range,
'soft': soft_range, 'combined': combined,
'robust': robust_range, 'values': ranges}
if 'factors' in ranges:
all_factors = ranges['factors']
factor_dtypes = {fs.dtype for fs in all_factors} if all_factors else []
dtype = list(factor_dtypes)[0] if len(factor_dtypes) == 1 else None
expanded = [v for fctrs in all_factors for v in fctrs]
if dtype is not None:
try:
# Try to keep the same dtype
expanded = np.array(expanded, dtype=dtype)
except Exception:
pass
dranges['factors'] = util.unique_array(expanded)
return dranges
@classmethod
def _compute_group_range(cls, group, elements, ranges, framewise,
axiswise, robust, top_level, prev_frame):
# Iterate over all elements in a normalization group
# and accumulate their ranges into the supplied dictionary.
elements = [el for el in elements if el is not None]
data_ranges = {}
robust_ranges = {}
categorical_dims = []
for el in elements:
for el_dim in el.dimensions('ranges'):
if hasattr(el, 'interface'):
if isinstance(el, Graph) and el_dim in el.nodes.dimensions():
dtype = el.nodes.interface.dtype(el.nodes, el_dim)
else:
dtype = el.interface.dtype(el, el_dim)
elif hasattr(el, '__len__') and len(el):
dtype = el.dimension_values(el_dim).dtype
else:
dtype = None
if all(util.isfinite(r) for r in el_dim.range):
data_range = (None, None)
elif dtype is not None and dtype.kind in 'SU':
data_range = ('', '')
elif isinstance(el, Graph) and el_dim in el.kdims[:2]:
data_range = el.nodes.range(2, dimension_range=False)
elif el_dim.values:
ds = Dataset(el_dim.values, el_dim)
data_range = ds.range(el_dim, dimension_range=False)
else:
data_range = el.range(el_dim, dimension_range=False)
data_ranges[(el, el_dim)] = data_range
if dtype is not None and dtype.kind == 'uif' and robust:
percentile = 2 if isinstance(robust, bool) else robust
robust_ranges[(el, el_dim)] = (
dim(el_dim, np.nanpercentile, percentile).apply(el),
dim(el_dim, np.nanpercentile, percentile).apply(el)
)
if (any(isinstance(r, str) for r in data_range) or
(el_dim.type is not None and issubclass(el_dim.type, str)) or
(dtype is not None and dtype.kind in 'SU')):
categorical_dims.append(el_dim)
prev_ranges = ranges.get(group, {})
group_ranges = OrderedDict()
for el in elements:
if isinstance(el, (Empty, Table)): continue
opts = cls.lookup_options(el, 'style')
plot_opts = cls.lookup_options(el, 'plot')
opt_kwargs = dict(opts.kwargs, **plot_opts.kwargs)
if not opt_kwargs.get('apply_ranges', True):
continue
# Compute normalization for color dim transforms
for k, v in opt_kwargs.items():
if not isinstance(v, dim) or ('color' not in k and k != 'magnitude'):
continue
if isinstance(v, dim) and v.applies(el):
dim_name = repr(v)
if dim_name in prev_ranges and not framewise:
continue
values = v.apply(el, all_values=True)
factors = None
if values.dtype.kind == 'M':
drange = values.min(), values.max()
elif util.isscalar(values):
drange = values, values
elif values.dtype.kind in 'US':
factors = util.unique_array(values)
elif len(values) == 0:
drange = np.NaN, np.NaN
else:
try:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
drange = (np.nanmin(values), np.nanmax(values))
except Exception:
factors = util.unique_array(values)
if dim_name not in group_ranges:
group_ranges[dim_name] = {
'id': [], 'data': [], 'hard': [], 'soft': []
}
if factors is not None:
if 'factors' not in group_ranges[dim_name]:
group_ranges[dim_name]['factors'] = []
group_ranges[dim_name]['factors'].append(factors)
else:
group_ranges[dim_name]['data'].append(drange)
group_ranges[dim_name]['id'].append(id(el))
# Compute dimension normalization
for el_dim in el.dimensions('ranges'):
dim_name = el_dim.name
if dim_name in prev_ranges and not framewise:
continue
data_range = data_ranges[(el, el_dim)]
if dim_name not in group_ranges:
group_ranges[dim_name] = {
'id': [], 'data': [], 'hard': [], 'soft': [], 'robust': []
}
group_ranges[dim_name]['data'].append(data_range)
group_ranges[dim_name]['hard'].append(el_dim.range)
group_ranges[dim_name]['soft'].append(el_dim.soft_range)
if (el, el_dim) in robust_ranges:
group_ranges[dim_name]['robust'].append(robust_ranges[(el, el_dim)])
if el_dim in categorical_dims:
if 'factors' not in group_ranges[dim_name]:
group_ranges[dim_name]['factors'] = []
if el_dim.values not in ([], None):
values = el_dim.values
elif el_dim in el:
if isinstance(el, Graph) and el_dim in el.kdims[:2]:
# Graph start/end normalization should include all node indices
values = el.nodes.dimension_values(2, expanded=False)
else:
values = el.dimension_values(el_dim, expanded=False)
elif isinstance(el, Graph) and el_dim in el.nodes:
values = el.nodes.dimension_values(el_dim, expanded=False)
if (isinstance(values, np.ndarray) and values.dtype.kind == 'O' and
all(isinstance(v, (np.ndarray)) for v in values)):
values = np.concatenate(values) if len(values) else []
factors = util.unique_array(values)
group_ranges[dim_name]['factors'].append(factors)
group_ranges[dim_name]['id'].append(id(el))
# Avoid merging ranges with non-matching types
group_dim_ranges = defaultdict(dict)
for gdim, values in group_ranges.items():
matching = True
for t, rs in values.items():
if t in ('factors', 'id'):
continue
matching &= (
len({'date' if isinstance(v, util.datetime_types) else 'number'
for rng in rs for v in rng if util.isfinite(v)}) < 2
)
if matching:
group_dim_ranges[gdim] = values
# Merge ranges across elements
dim_ranges = []
for gdim, values in group_dim_ranges.items():
dranges = cls._merge_group_ranges(values)
dim_ranges.append((gdim, dranges))
# Merge local ranges into global range dictionary
if prev_ranges and not (top_level or axiswise) and framewise and prev_frame is not None:
# Partially update global ranges with local changes
prev_ids = prev_frame.traverse(lambda o: id(o))
for d, dranges in dim_ranges:
values = prev_ranges.get(d, {}).get('values', None)
if values is None or 'id' not in values:
for g, drange in dranges.items():
if d not in prev_ranges:
prev_ranges[d] = {}
prev_ranges[d][g] = drange
continue
ids = values.get('id')
# Filter out ranges of updated elements and append new ranges
merged = {}
for g, drange in dranges['values'].items():
filtered = [r for i, r in zip(ids, values[g]) if i not in prev_ids]
filtered += drange
merged[g] = filtered
prev_ranges[d] = cls._merge_group_ranges(merged)
elif prev_ranges and not (framewise and (top_level or axiswise)):
# Combine local with global range
for d, dranges in dim_ranges:
for g, drange in dranges.items():
prange = prev_ranges.get(d, {}).get(g, None)
if prange is None:
if d not in prev_ranges:
prev_ranges[d] = {}
prev_ranges[d][g] = drange
elif g in ('factors', 'values'):
prev_ranges[d][g] = drange
else:
prev_ranges[d][g] = util.max_range([prange, drange],
combined=g=='hard')
else:
# Override global range
ranges[group] = OrderedDict(dim_ranges)
@classmethod
def _traverse_options(cls, obj, opt_type, opts, specs=None, keyfn=None, defaults=True):
"""
Traverses the supplied object getting all options in opts for
the specified opt_type and specs. Also takes into account the
plotting class defaults for plot options. If a keyfn is
supplied the returned options will be grouped by the returned
keys.
"""
def lookup(x):
"""
Looks up options for object, including plot defaults.
keyfn determines returned key otherwise None key is used.
"""
options = cls.lookup_options(x, opt_type)
selected = {o: options.options[o]
for o in opts if o in options.options}
if opt_type == 'plot' and defaults:
plot = Store.registry[cls.backend].get(type(x))
selected['defaults'] = {o: getattr(plot, o) for o in opts
if o not in selected and hasattr(plot, o)}
key = keyfn(x) if keyfn else None
return (key, selected)
# Traverse object and accumulate options by key
traversed = obj.traverse(lookup, specs)
options = OrderedDict()
default_opts = defaultdict(lambda: defaultdict(list))
for key, opts in traversed:
defaults = opts.pop('defaults', {})
if key not in options:
options[key] = {}
for opt, v in opts.items():
if opt not in options[key]:
options[key][opt] = []
options[key][opt].append(v)
for opt, v in defaults.items():
default_opts[key][opt].append(v)
# Merge defaults into dictionary if not explicitly specified
for key, opts in default_opts.items():
for opt, v in opts.items():
if opt not in options[key]:
options[key][opt] = v
return options if keyfn else options[None]
def _get_projection(cls, obj):
"""
Uses traversal to find the appropriate projection
for a nested object. Respects projections set on
Overlays before considering Element based settings,
before finally looking up the default projection on
the plot type. If more than one non-None projection
type is found an exception is raised.
"""
isoverlay = lambda x: isinstance(x, CompositeOverlay)
element3d = obj.traverse(lambda x: x, [Element3D])
if element3d:
return '3d'
opts = cls._traverse_options(obj, 'plot', ['projection'],
[CompositeOverlay, Element],
keyfn=isoverlay)
from_overlay = not all(p is None for p in opts.get(True, {}).get('projection', []))
projections = opts.get(from_overlay, {}).get('projection', [])
custom_projs = [p for p in projections if p is not None]
if len(set(custom_projs)) > 1:
raise Exception("An axis may only be assigned one projection type")
return custom_projs[0] if custom_projs else None
def update(self, key):
if len(self) == 1 and ((key == 0) or (key == self.keys[0])) and not self.drawn:
return self.initialize_plot()
item = self.__getitem__(key)
self.traverse(lambda x: setattr(x, '_updated', True))
return item
def __len__(self):
"""
Returns the total number of available frames.
"""
return len(self.keys)
class CallbackPlot:
backend = None
def _construct_callbacks(self):
"""
Initializes any callbacks for streams which have defined
the plotted object as a source.
"""
source_streams = []
cb_classes = set()
registry = list(Stream.registry.items())
callbacks = Stream._callbacks[self.backend]
for source in self.link_sources:
streams = [
s for src, streams in registry for s in streams
if src is source or (src._plot_id is not None and
src._plot_id == source._plot_id)]
cb_classes |= {(callbacks[type(stream)], stream) for stream in streams
if type(stream) in callbacks and stream.linked
and stream.source is not None}
cbs = []
sorted_cbs = sorted(cb_classes, key=lambda x: id(x[0]))
for cb, group in groupby(sorted_cbs, lambda x: x[0]):
cb_streams = [s for _, s in group]
for cb_stream in cb_streams:
if cb_stream not in source_streams:
source_streams.append(cb_stream)
cbs.append(cb(self, cb_streams, source))
return cbs, source_streams
@property
def link_sources(self):
"Returns potential Link or Stream sources."
if isinstance(self, GenericOverlayPlot):
zorders = []
elif self.batched:
zorders = list(range(self.zorder, self.zorder+len(self.hmap.last)))
else:
zorders = [self.zorder]
if isinstance(self, GenericOverlayPlot) and not self.batched:
sources = []
elif not self.static or isinstance(self.hmap, DynamicMap):
sources = [o for i, inputs in self.stream_sources.items()
for o in inputs if i in zorders]
else:
sources = [self.hmap.last]
return sources
class GenericElementPlot(DimensionedPlot):