/
reactive.py
1772 lines (1554 loc) · 68.3 KB
/
reactive.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
"""
Declares Syncable and Reactive classes which provides baseclasses
for Panel components which sync their state with one or more bokeh
models rendered on the frontend.
"""
from __future__ import annotations
import datetime as dt
import difflib
import logging
import re
import sys
import textwrap
from collections import Counter, defaultdict, namedtuple
from functools import partial
from pprint import pformat
from typing import (
TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Mapping, Optional, Set,
Tuple, Type, Union,
)
import bleach
import numpy as np
import param
from bokeh.core.property.descriptors import UnsetValueError
from bokeh.model import DataModel
from param.parameterized import ParameterizedMetaclass, Watcher
from .io.document import unlocked
from .io.model import hold
from .io.notebook import push
from .io.state import set_curdoc, state
from .models.reactive_html import (
DOMEvent, ReactiveHTML as _BkReactiveHTML, ReactiveHTMLParser,
)
from .util import edit_readonly, escape, updating
from .viewable import Layoutable, Renderable, Viewable
if TYPE_CHECKING:
import pandas as pd
from bokeh.document import Document
from bokeh.events import Event
from bokeh.model import Model
from bokeh.models.sources import DataDict, Patches
from pyviz_comms import Comm
from .layout.base import Panel
from .links import Callback, JSLinkTarget, Link
log = logging.getLogger('panel.reactive')
_fields = tuple(Watcher._fields+('target', 'links', 'transformed', 'bidirectional_watcher'))
LinkWatcher: Tuple = namedtuple("Watcher", _fields) # type: ignore
class Syncable(Renderable):
"""
Syncable is an extension of the Renderable object which can not
only render to a bokeh model but also sync the parameters on the
object with the properties on the model.
In order to bi-directionally link parameters with bokeh model
instances the _link_params and _link_props methods define
callbacks triggered when either the parameter or bokeh property
values change. Since there may not be a 1-to-1 mapping between
parameter and the model property the _process_property_change and
_process_param_change may be overridden to apply any necessary
transformations.
"""
# Timeout if a notebook comm message is swallowed
_timeout: ClassVar[int] = 20000
# Timeout before the first event is processed
_debounce: ClassVar[int] = 50
# Property changes which should not be debounced
_priority_changes: ClassVar[List[str]] = []
# Any parameters that require manual updates handling for the models
# e.g. parameters which affect some sub-model
_manual_params: ClassVar[List[str]] = []
# Mapping from parameter name to bokeh model property name
_rename: ClassVar[Mapping[str, str | None]] = {}
# Allows defining a mapping from model property name to a JS code
# snippet that transforms the object before serialization
_js_transforms: ClassVar[Mapping[str, str]] = {}
# Transforms from input value to bokeh property value
_source_transforms: ClassVar[Mapping[str, str | None]] = {}
_target_transforms: ClassVar[Mapping[str, str | None]] = {}
__abstract = True
def __init__(self, **params):
super().__init__(**params)
# Useful when updating model properties which trigger potentially
# recursive events
self._updating = False
# A dictionary of current property change events
self._events = {}
# Any watchers associated with links between two objects
self._links = []
self._link_params()
# A dictionary of bokeh property changes being processed
self._changing = {}
# Sets up watchers to process manual updates to models
if self._manual_params:
self.param.watch(self._update_manual, self._manual_params)
#----------------------------------------------------------------
# Model API
#----------------------------------------------------------------
def _process_property_change(self, msg: Dict[str, Any]) -> Dict[str, Any]:
"""
Transform bokeh model property changes into parameter updates.
Should be overridden to provide appropriate mapping between
parameter value and bokeh model change. By default uses the
_rename class level attribute to map between parameter and
property names.
"""
inverted = {v: k for k, v in self._rename.items()}
return {inverted.get(k, k): v for k, v in msg.items()}
def _process_param_change(self, msg: Dict[str, Any]) -> Dict[str, Any]:
"""
Transform parameter changes into bokeh model property updates.
Should be overridden to provide appropriate mapping between
parameter value and bokeh model change. By default uses the
_rename class level attribute to map between parameter and
property names.
"""
properties = {self._rename.get(k) or k: v for k, v in msg.items()
if self._rename.get(k, False) is not None}
if 'width' in properties and self.sizing_mode is None:
properties['min_width'] = properties['width']
if 'height' in properties and self.sizing_mode is None:
properties['min_height'] = properties['height']
return properties
@property
def _linkable_params(self) -> List[str]:
"""
Parameters that can be linked in JavaScript via source
transforms.
"""
return [p for p in self._synced_params if self._rename.get(p, False) is not None
and self._source_transforms.get(p, False) is not None] + ['loading']
@property
def _synced_params(self) -> List[str]:
"""
Parameters which are synced with properties using transforms
applied in the _process_param_change method.
"""
ignored = ['default_layout', 'loading']
return [p for p in self.param if p not in self._manual_params+ignored]
def _init_params(self) -> Dict[str, Any]:
return {k: v for k, v in self.param.values().items()
if k in self._synced_params and v is not None}
def _link_params(self) -> None:
params = self._synced_params
if params:
watcher = self.param.watch(self._param_change, params)
self._callbacks.append(watcher)
def _link_props(
self, model: Model, properties: List[str] | List[Tuple[str, str]],
doc: Document, root: Model, comm: Optional[Comm] = None
) -> None:
from .config import config
ref = root.ref['id']
if config.embed:
return
for p in properties:
if isinstance(p, tuple):
_, p = p
m = model
if '.' in p:
*subpath, p = p.split('.')
for sp in subpath:
m = getattr(m, sp)
else:
subpath = None
if comm:
m.on_change(p, partial(self._comm_change, doc, ref, comm, subpath))
else:
m.on_change(p, partial(self._server_change, doc, ref, subpath))
def _manual_update(
self, events: Tuple[param.parameterized.Event, ...], model: Model, doc: Document,
root: Model, parent: Optional[Model], comm: Optional[Comm]
) -> None:
"""
Method for handling any manual update events, i.e. events triggered
by changes in the manual params.
"""
def _update_manual(self, *events: param.parameterized.Event) -> None:
for ref, (model, parent) in self._models.items():
if ref not in state._views or ref in state._fake_roots:
continue
viewable, root, doc, comm = state._views[ref]
if comm or state._unblocked(doc):
with unlocked():
self._manual_update(events, model, doc, root, parent, comm)
if comm and 'embedded' not in root.tags:
push(doc, comm)
else:
cb = partial(self._manual_update, events, model, doc, root, parent, comm)
if doc.session_context:
doc.add_next_tick_callback(cb)
else:
cb()
def _apply_update(
self, events: Dict[str, param.parameterized.Event], msg: Dict[str, Any],
model: Model, ref: str
) -> None:
if ref not in state._views or ref in state._fake_roots:
return
viewable, root, doc, comm = state._views[ref]
if comm or not doc.session_context or state._unblocked(doc):
with unlocked():
self._update_model(events, msg, root, model, doc, comm)
if comm and 'embedded' not in root.tags:
push(doc, comm)
else:
cb = partial(self._update_model, events, msg, root, model, doc, comm)
doc.add_next_tick_callback(cb)
def _update_model(
self, events: Dict[str, param.parameterized.Event], msg: Dict[str, Any],
root: Model, model: Model, doc: Document, comm: Optional[Comm]
) -> None:
ref = root.ref['id']
self._changing[ref] = attrs = []
for attr, value in msg.items():
# Bokeh raises UnsetValueError if the value is Undefined.
try:
model_val = getattr(model, attr)
except UnsetValueError:
attrs.append(attr)
continue
if not model.lookup(attr).property.matches(model_val, value):
attrs.append(attr)
try:
model.update(**msg)
finally:
changing = [
attr for attr in self._changing.get(ref, [])
if attr not in attrs
]
if changing:
self._changing[ref] = changing
elif ref in self._changing:
del self._changing[ref]
def _cleanup(self, root: Model | None) -> None:
super()._cleanup(root)
if root is None:
return
ref = root.ref['id']
self._models.pop(ref, None)
comm, client_comm = self._comms.pop(ref, (None, None))
if comm:
try:
comm.close()
except Exception:
pass
if client_comm:
try:
client_comm.close()
except Exception:
pass
def _param_change(self, *events: param.parameterized.Event) -> None:
msgs = []
for event in events:
msg = self._process_param_change({event.name: event.new})
if msg:
msgs.append(msg)
named_events = {event.name: event for event in events}
msg = {k: v for msg in msgs for k, v in msg.items()}
if not msg:
return
for ref, (model, _) in self._models.copy().items():
self._apply_update(named_events, msg, model, ref)
def _process_events(self, events: Dict[str, Any]) -> None:
self._log('received events %s', events)
busy = state.busy
with edit_readonly(state):
state.busy = True
events = self._process_property_change(events)
try:
with edit_readonly(self):
self_events = {k: v for k, v in events.items() if '.' not in k}
self.param.update(**self_events)
for k, v in self_events.items():
if '.' not in k:
continue
*subpath, p = k.split('.')
obj = self
for sp in subpath:
obj = getattr(obj, sp)
with edit_readonly(obj):
obj.param.update(**{p: v})
except Exception:
if len(events)>1:
msg_end = f" changing properties {pformat(events)} \n"
elif len(events)==1:
msg_end = f" changing property {pformat(events)} \n"
else:
msg_end = "\n"
log.exception(f'Callback failed for object named "{self.name}"{msg_end}')
raise
finally:
self._log('finished processing events %s', events)
with edit_readonly(state):
state.busy = busy
def _process_bokeh_event(self, doc: Document, event: Event) -> None:
self._log('received bokeh event %s', event)
busy = state.busy
with edit_readonly(state):
state.busy = True
try:
with set_curdoc(doc):
self._process_event(event)
finally:
self._log('finished processing bokeh event %s', event)
with edit_readonly(state):
state.busy = busy
async def _change_coroutine(self, doc: Document) -> None:
if state._thread_pool:
state._thread_pool.submit(self._change_event, doc)
else:
with set_curdoc(doc):
self._change_event(doc)
async def _event_coroutine(self, doc: Document, event) -> None:
if state._thread_pool:
state._thread_pool.submit(self._process_bokeh_event, doc, event)
else:
self._process_bokeh_event(doc, event)
def _change_event(self, doc: Document) -> None:
events = self._events
self._events = {}
with set_curdoc(doc):
self._process_events(events)
def _schedule_change(self, doc: Document, comm: Comm | None) -> None:
with hold(doc, comm=comm):
self._change_event(doc)
def _comm_change(
self, doc: Document, ref: str, comm: Comm | None, subpath: str,
attr: str, old: Any, new: Any
) -> None:
if subpath:
attr = f'{subpath}.{attr}'
if attr in self._changing.get(ref, []):
self._changing[ref].remove(attr)
return
self._events.update({attr: new})
if state._thread_pool:
state._thread_pool.submit(self._schedule_change, doc, comm)
else:
self._schedule_change(doc, comm)
def _comm_event(self, doc: Document, event: Event) -> None:
if state._thread_pool:
state._thread_pool.submit(self._process_bokeh_event, doc, event)
else:
self._process_bokeh_event(doc, event)
def _register_events(self, *event_names: str, model: Model, doc: Document, comm: Comm | None) -> None:
for event_name in event_names:
method = self._comm_event if comm else self._server_event
model.on_event(event_name, partial(method, doc))
def _server_event(self, doc: Document, event: Event) -> None:
if doc.session_context and not state._unblocked(doc):
doc.add_next_tick_callback(
partial(self._event_coroutine, doc, event) # type: ignore
)
else:
self._comm_event(doc, event)
def _server_change(
self, doc: Document, ref: str, subpath: str, attr: str,
old: Any, new: Any
) -> None:
if subpath:
attr = f'{subpath}.{attr}'
if attr in self._changing.get(ref, []):
self._changing[ref].remove(attr)
return
processing = bool(self._events)
self._events.update({attr: new})
if processing:
return
if doc.session_context:
cb = partial(self._change_coroutine, doc)
if attr in self._priority_changes:
doc.add_next_tick_callback(cb) # type: ignore
else:
doc.add_timeout_callback(cb, self._debounce) # type: ignore
else:
self._change_event(doc)
class Reactive(Syncable, Viewable):
"""
Reactive is a Viewable object that also supports syncing between
the objects parameters and the underlying bokeh model either via
the defined pyviz_comms.Comm type or using bokeh server.
In addition it defines various methods which make it easy to link
the parameters to other objects.
"""
#----------------------------------------------------------------
# Public API
#----------------------------------------------------------------
def link(
self, target: param.Parameterized, callbacks: Optional[Dict[str, str | Callable]]=None,
bidirectional: bool=False, **links: str
) -> Watcher:
"""
Links the parameters on this `Reactive` object to attributes on the
target `Parameterized` object.
Supports two modes, either specify a
mapping between the source and target object parameters as keywords or
provide a dictionary of callbacks which maps from the source
parameter to a callback which is triggered when the parameter
changes.
Arguments
---------
target: param.Parameterized
The target object of the link.
callbacks: dict | None
Maps from a parameter in the source object to a callback.
bidirectional: bool
Whether to link source and target bi-directionally
**links: dict
Maps between parameters on this object to the parameters
on the supplied object.
"""
if links and callbacks:
raise ValueError('Either supply a set of parameters to '
'link as keywords or a set of callbacks, '
'not both.')
elif not links and not callbacks:
raise ValueError('Declare parameters to link or a set of '
'callbacks, neither was defined.')
elif callbacks and bidirectional:
raise ValueError('Bidirectional linking not supported for '
'explicit callbacks. You must define '
'separate callbacks for each direction.')
_updating = []
def link_cb(*events):
for event in events:
if event.name in _updating: continue
_updating.append(event.name)
try:
if callbacks:
callbacks[event.name](target, event)
else:
setattr(target, links[event.name], event.new)
finally:
_updating.pop(_updating.index(event.name))
params = list(callbacks) if callbacks else list(links)
cb = self.param.watch(link_cb, params)
bidirectional_watcher = None
if bidirectional:
_reverse_updating = []
reverse_links = {v: k for k, v in links.items()}
def reverse_link(*events):
for event in events:
if event.name in _reverse_updating: continue
_reverse_updating.append(event.name)
try:
setattr(self, reverse_links[event.name], event.new)
finally:
_reverse_updating.remove(event.name)
bidirectional_watcher = target.param.watch(reverse_link, list(reverse_links))
link_args = tuple(cb)
# Compatibility with Param versions where precedence is dropped
# from iterator for backward compatibility with older Panel versions
if 'precedence' in Watcher._fields and len(link_args) < len(Watcher._fields):
link_args += (cb.precedence,)
link = LinkWatcher(*(link_args+(target, links, callbacks is not None, bidirectional_watcher)))
self._links.append(link)
return cb
def controls(self, parameters: List[str] = [], jslink: bool = True, **kwargs) -> 'Panel':
"""
Creates a set of widgets which allow manipulating the parameters
on this instance. By default all parameters which support
linking are exposed, but an explicit list of parameters can
be provided.
Arguments
---------
parameters: list(str)
An explicit list of parameters to return controls for.
jslink: bool
Whether to use jslinks instead of Python based links.
This does not allow using all types of parameters.
kwargs: dict
Additional kwargs to pass to the Param pane(s) used to
generate the controls widgets.
Returns
-------
A layout of the controls
"""
from .layout import Tabs, WidgetBox
from .param import Param
from .widgets import LiteralInput
if parameters:
linkable = parameters
elif jslink:
linkable = self._linkable_params
else:
linkable = list(self.param)
params = [p for p in linkable if p not in Viewable.param]
controls = Param(self.param, parameters=params, default_layout=WidgetBox,
name='Controls', **kwargs)
layout_params = [p for p in linkable if p in Viewable.param]
if 'name' not in layout_params and self._rename.get('name', False) is not None and not parameters:
layout_params.insert(0, 'name')
style = Param(self.param, parameters=layout_params, default_layout=WidgetBox,
name='Layout', **kwargs)
if jslink:
for p in params:
widget = controls._widgets[p]
widget.jslink(self, value=p, bidirectional=True)
if isinstance(widget, LiteralInput):
widget.serializer = 'json'
for p in layout_params:
widget = style._widgets[p]
widget.jslink(self, value=p, bidirectional=p != 'loading')
if isinstance(widget, LiteralInput):
widget.serializer = 'json'
if params and layout_params:
return Tabs(controls.layout[0], style.layout[0])
elif params:
return controls.layout[0]
return style.layout[0]
def jscallback(self, args: Dict[str, Any]={}, **callbacks: str) -> Callback:
"""
Allows defining a JS callback to be triggered when a property
changes on the source object. The keyword arguments define the
properties that trigger a callback and the JS code that gets
executed.
Arguments
----------
args: dict
A mapping of objects to make available to the JS callback
**callbacks: dict
A mapping between properties on the source model and the code
to execute when that property changes
Returns
-------
callback: Callback
The Callback which can be used to disable the callback.
"""
from .links import Callback
return Callback(self, code=callbacks, args=args)
def jslink(
self, target: JSLinkTarget , code: Dict[str, str] = None, args: Optional[Dict] = None,
bidirectional: bool = False, **links: str
) -> Link:
"""
Links properties on the this Reactive object to those on the
target Reactive object in JS code.
Supports two modes, either specify a
mapping between the source and target model properties as
keywords or provide a dictionary of JS code snippets which
maps from the source parameter to a JS code snippet which is
executed when the property changes.
Arguments
----------
target: panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned
The target to link the value to.
code: dict
Custom code which will be executed when the widget value
changes.
args: dict
A mapping of objects to make available to the JS callback
bidirectional: boolean
Whether to link source and target bi-directionally
**links: dict
A mapping between properties on the source model and the
target model property to link it to.
Returns
-------
link: GenericLink
The GenericLink which can be used unlink the widget and
the target model.
"""
if links and code:
raise ValueError('Either supply a set of properties to '
'link as keywords or a set of JS code '
'callbacks, not both.')
elif not links and not code:
raise ValueError('Declare parameters to link or a set of '
'callbacks, neither was defined.')
if args is None:
args = {}
from .links import Link, assert_source_syncable, assert_target_syncable
mapping = code or links
assert_source_syncable(self, mapping)
if isinstance(target, Syncable) and code is None:
assert_target_syncable(self, target, mapping)
return Link(self, target, properties=links, code=code, args=args,
bidirectional=bidirectional)
TData = Union['pd.DataFrame', 'DataDict']
class SyncableData(Reactive):
"""
A baseclass for components which sync one or more data parameters
with the frontend via a ColumnDataSource.
"""
selection = param.List(default=[], class_=int, doc="""
The currently selected rows in the data.""")
# Parameters which when changed require an update of the data
_data_params: ClassVar[List[str]] = []
_rename: ClassVar[Mapping[str, str | None]] = {'selection': None}
__abstract = True
def __init__(self, **params):
super().__init__(**params)
self._data = None
self._processed = None
self.param.watch(self._validate, self._data_params)
if self._data_params:
self.param.watch(self._update_cds, self._data_params)
self.param.watch(self._update_selected, 'selection')
self._validate()
self._update_cds()
def _validate(self, *events: param.parameterized.Event) -> None:
"""
Allows implementing validation for the data parameters.
"""
def _get_data(self) -> Tuple[TData, 'DataDict']:
"""
Implemented by subclasses converting data parameter(s) into
a ColumnDataSource compatible data dictionary.
Returns
-------
processed: object
Raw data after pre-processing (e.g. after filtering)
data: dict
Dictionary of columns used to instantiate and update the
ColumnDataSource
"""
def _update_column(self, column: str, array: np.ndarray | List) -> None:
"""
Implemented by subclasses converting changes in columns to
changes in the data parameter.
Parameters
----------
column: str
The name of the column to update.
array: numpy.ndarray
The array data to update the column with.
"""
data = getattr(self, self._data_params[0])
data[column] = array
if self._processed is not None:
self._processed[column] = array
def _update_data(self, data: TData) -> None:
self.param.update(**{self._data_params[0]: data})
def _manual_update(
self, events: Tuple[param.parameterized.Event, ...], model: Model,
doc: Document, root: Model, parent: Optional[Model], comm: Comm
) -> None:
for event in events:
if event.type == 'triggered' and self._updating:
continue
elif hasattr(self, '_update_' + event.name):
getattr(self, '_update_' + event.name)(model)
@updating
def _update_cds(self, *events: param.parameterized.Event) -> None:
self._processed, self._data = self._get_data()
msg = {'data': self._data}
named_events = {event.name: event for event in events}
for ref, (m, _) in self._models.items():
self._apply_update(named_events, msg, m.source, ref)
@updating
def _update_selected(
self, *events: param.parameterized.Event, indices: Optional[List[int]] = None
) -> None:
indices = self.selection if indices is None else indices
msg = {'indices': indices}
named_events = {event.name: event for event in events}
for ref, (m, _) in self._models.items():
self._apply_update(named_events, msg, m.source.selected, ref)
def _apply_stream(self, ref: str, model: Model, stream: 'DataDict', rollover: Optional[int]) -> None:
self._changing[ref] = ['data']
try:
model.source.stream(stream, rollover)
finally:
del self._changing[ref]
@updating
def _stream(self, stream: 'DataDict', rollover: Optional[int] = None) -> None:
self._processed, _ = self._get_data()
for ref, (m, _) in self._models.items():
if ref not in state._views or ref in state._fake_roots:
continue
viewable, root, doc, comm = state._views[ref]
if comm or not doc.session_context or state._unblocked(doc):
with unlocked():
m.source.stream(stream, rollover)
if comm and 'embedded' not in root.tags:
push(doc, comm)
else:
cb = partial(self._apply_stream, ref, m, stream, rollover)
doc.add_next_tick_callback(cb)
def _apply_patch(self, ref: str, model: Model, patch: 'Patches') -> None:
self._changing[ref] = ['data']
try:
model.source.patch(patch)
finally:
del self._changing[ref]
@updating
def _patch(self, patch: 'Patches') -> None:
for ref, (m, _) in self._models.items():
if ref not in state._views or ref in state._fake_roots:
continue
viewable, root, doc, comm = state._views[ref]
if comm or not doc.session_context or state._unblocked(doc):
with unlocked():
m.source.patch(patch)
if comm and 'embedded' not in root.tags:
push(doc, comm)
else:
cb = partial(self._apply_patch, ref, m, patch)
doc.add_next_tick_callback(cb)
def _update_manual(self, *events: param.parameterized.Event) -> None:
"""
Skip events triggered internally
"""
processed_events = []
for e in events:
if e.name == self._data_params[0] and e.type == 'triggered' and self._updating:
continue
processed_events.append(e)
super()._update_manual(*processed_events)
def stream(
self, stream_value: 'pd.DataFrame' | 'pd.Series' | Dict,
rollover: Optional[int] = None, reset_index: bool = True
) -> None:
"""
Streams (appends) the `stream_value` provided to the existing
value in an efficient manner.
Arguments
---------
stream_value: (pd.DataFrame | pd.Series | Dict)
The new value(s) to append to the existing value.
rollover: (int | None, default=None)
A maximum column size, above which data from the start of
the column begins to be discarded. If None, then columns
will continue to grow unbounded.
reset_index (bool, default=True):
If True and the stream_value is a DataFrame, then its index
is reset. Helps to keep the index unique and named `index`.
Raises
------
ValueError: Raised if the stream_value is not a supported type.
Examples
--------
Stream a Series to a DataFrame
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> stream_value = pd.Series({"x": 4, "y": "d"})
>>> obj.stream(stream_value)
>>> obj.value.to_dict("list")
{'x': [1, 2, 4], 'y': ['a', 'b', 'd']}
Stream a Dataframe to a Dataframe
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> stream_value = pd.DataFrame({"x": [3, 4], "y": ["c", "d"]})
>>> obj.stream(stream_value)
>>> obj.value.to_dict("list")
{'x': [1, 2, 3, 4], 'y': ['a', 'b', 'c', 'd']}
Stream a Dictionary row to a DataFrame
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> tabulator = DataComponent(value)
>>> stream_value = {"x": 4, "y": "d"}
>>> obj.stream(stream_value)
>>> obj.value.to_dict("list")
{'x': [1, 2, 4], 'y': ['a', 'b', 'd']}
Stream a Dictionary of Columns to a Dataframe
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> stream_value = {"x": [3, 4], "y": ["c", "d"]}
>>> obj.stream(stream_value)
>>> obj.value.to_dict("list")
{'x': [1, 2, 3, 4], 'y': ['a', 'b', 'c', 'd']}
"""
if 'pandas' in sys.modules:
import pandas as pd
else:
pd = None # type: ignore
if pd and isinstance(stream_value, pd.DataFrame):
if isinstance(self._processed, dict):
self.stream(stream_value.to_dict(), rollover)
return
if reset_index:
value_index_start = self._processed.index.max() + 1
stream_value = stream_value.reset_index(drop=True)
stream_value.index += value_index_start
combined = pd.concat([self._processed, stream_value])
if rollover is not None:
combined = combined.iloc[-rollover:]
with param.discard_events(self):
self._update_data(combined)
try:
self._updating = True
self.param.trigger(self._data_params[0])
finally:
self._updating = False
self._stream(stream_value, rollover)
elif pd and isinstance(stream_value, pd.Series):
if isinstance(self._processed, dict):
self.stream({k: [v] for k, v in stream_value.to_dict().items()}, rollover)
return
value_index_start = self._processed.index.max() + 1
self._processed.loc[value_index_start] = stream_value
with param.discard_events(self):
self._update_data(self._processed)
self._stream(self._processed.iloc[-1:], rollover)
elif isinstance(stream_value, dict):
if isinstance(self._processed, dict):
if not all(col in stream_value for col in self._data):
raise ValueError("Stream update must append to all columns.")
for col, array in stream_value.items():
combined = np.concatenate([self._data[col], array])
if rollover is not None:
combined = combined[-rollover:]
self._update_column(col, combined)
self._stream(stream_value, rollover)
else:
try:
stream_value = pd.DataFrame(stream_value)
except ValueError:
stream_value = pd.Series(stream_value)
self.stream(stream_value)
else:
raise ValueError("The stream value provided is not a DataFrame, Series or Dict!")
def patch(self, patch_value: 'pd.DataFrame' | 'pd.Series' | Dict) -> None:
"""
Efficiently patches (updates) the existing value with the `patch_value`.
Arguments
---------
patch_value: (pd.DataFrame | pd.Series | Dict)
The value(s) to patch the existing value with.
Raises
------
ValueError: Raised if the patch_value is not a supported type.
Examples
--------
Patch a DataFrame with a Dictionary row.
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> patch_value = {"x": [(0, 3)]}
>>> obj.patch(patch_value)
>>> obj.value.to_dict("list")
{'x': [3, 2], 'y': ['a', 'b']}
Patch a Dataframe with a Dictionary of Columns.
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> patch_value = {"x": [(slice(2), (3,4))], "y": [(1,'d')]}
>>> obj.patch(patch_value)
>>> obj.value.to_dict("list")
{'x': [3, 4], 'y': ['a', 'd']}
Patch a DataFrame with a Series. Please note the index is used in the update.
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> patch_value = pd.Series({"index": 1, "x": 4, "y": "d"})
>>> obj.patch(patch_value)
>>> obj.value.to_dict("list")
{'x': [1, 4], 'y': ['a', 'd']}
Patch a Dataframe with a Dataframe. Please note the index is used in the update.
>>> value = pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})
>>> obj = DataComponent(value)
>>> patch_value = pd.DataFrame({"x": [3, 4], "y": ["c", "d"]})
>>> obj.patch(patch_value)
>>> obj.value.to_dict("list")
{'x': [3, 4], 'y': ['c', 'd']}
"""
if self._processed is None or isinstance(patch_value, dict):
self._patch(patch_value)
return
if 'pandas' in sys.modules:
import pandas as pd
else:
pd = None # type: ignore
data = getattr(self, self._data_params[0])
patch_value_dict: Patches = {}
if pd and isinstance(patch_value, pd.DataFrame):
for column in patch_value.columns:
patch_value_dict[column] = []
for index in patch_value.index:
patch_value_dict[column].append((index, patch_value.loc[index, column]))
self.patch(patch_value_dict)
elif pd and isinstance(patch_value, pd.Series):
if "index" in patch_value: # Series orient is row
patch_value_dict = {
k: [(patch_value["index"], v)] for k, v in patch_value.items()
}
patch_value_dict.pop("index")
else: # Series orient is column
patch_value_dict = {
patch_value.name: [(index, value) for index, value in patch_value.items()]
}
self.patch(patch_value_dict)
elif isinstance(patch_value, dict):
for k, v in patch_value.items():