def make_correlation_datatable(correl_df): """ the input datframe must have columns ['Target (as string)', 'Hedge (as string)', 'Correlation ( as float )'] :param correl_df: :return: """ correl_df.reset_index(inplace=True) source = ColumnDataSource(correl_df) target_ts_asset = sorted(correl_df["Target"].unique()) hedge_ts_asset = sorted(correl_df["Hedge"].unique()) columns = [ TableColumn(field="Target", title="Target Timeseries", formatter=StringFormatter(font_style="bold", text_color='red')), TableColumn(field="Hedge", title="Hedge Timeseries", formatter=StringFormatter(font_style="bold", text_color='blue')), TableColumn(field="Correlation", title="Correlation", formatter=StringFormatter(font_style="bold", text_color='darkgreen')) ] data_table = DataTable(source=source, columns=columns, editable=False, width=1000) plot = Plot(title=Title( text="Correlations, Target vs. Hedge Timeseries)", align="center"), x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs correlation_glyph = Circle(x="index", y="Correlation", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) target_glyph = Circle(x="index", y="Target", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hedge_glyph = Circle(x="index", y="Hedge", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) correlation = plot.add_glyph(source, correlation_glyph) target = plot.add_glyph(source, target_glyph) hedge = plot.add_glyph(source, hedge_glyph) # Add the tools tooltips = [("Correlation", "@Correlation"), ("Target", "@Target"), ("Hedge", "@Hedge")] correlation_hover_tool = HoverTool(renderers=[correlation], tooltips=tooltips) target_hover_tool = HoverTool(renderers=[target], tooltips=tooltips) hedge_hover_tool = HoverTool(renderers=[hedge], tooltips=tooltips) select_tool = BoxSelectTool(renderers=[target, hedge, correlation], dimensions='width') plot.add_tools(target_hover_tool, hedge_hover_tool, correlation_hover_tool, select_tool) layout = Column(plot, data_table) the_doc = Document() the_doc.add_root(layout) return the_doc
def test_interactive_streams(self): ys = np.arange(10) scatter1 = hv.Scatter(ys) scatter2 = hv.Scatter(ys) scatter3 = hv.Scatter(ys) # Single stream on the first scatter rangexy1 = RangeXY(source=scatter1) # Multiple streams of the same type on second scatter boundsxy2a = BoundsXY(source=scatter2) boundsxy2b = BoundsXY(source=scatter2) # Multiple streams of different types on third scatter rangexy3 = RangeXY(source=scatter3) boundsxy3 = BoundsXY(source=scatter3) selection1d3 = Selection1D(source=scatter3) # Build layout and layout Pane layout = scatter1 + scatter2 + scatter3 layout_pane = pn.pane.HoloViews(layout, backend='plotly') # Get plotly pane reference doc = Document() comm = Comm() layout_pane.get_root(doc, comm) _, plotly_pane = next(iter(layout_pane._plots.values())) # Simulate zoom and check that RangeXY streams updated accordingly plotly_pane.viewport = { 'xaxis.range': [1, 3], 'yaxis.range': [2, 4], 'xaxis2.range': [3, 5], 'yaxis2.range': [4, 6], 'xaxis3.range': [5, 7], 'yaxis3.range': [6, 8], } self.assertEqual(rangexy1.x_range, (1, 3)) self.assertEqual(rangexy1.y_range, (2, 4)) self.assertEqual(rangexy3.x_range, (5, 7)) self.assertEqual(rangexy3.y_range, (6, 8)) plotly_pane.viewport = None self.assertIsNone(rangexy1.x_range) self.assertIsNone(rangexy1.y_range) self.assertIsNone(rangexy3.x_range) self.assertIsNone(rangexy3.y_range) # Simulate box selection and check that BoundsXY and Selection1D streams # update accordingly # Box select on second subplot plotly_pane.selected_data = { 'points': [], 'range': { 'x2': [10, 20], 'y2': [11, 22] } } self.assertEqual(boundsxy2a.bounds, (10, 11, 20, 22)) self.assertEqual(boundsxy2b.bounds, (10, 11, 20, 22)) # Box selecrt on third subplot plotly_pane.selected_data = { 'points': [ {'curveNumber': 2, 'pointNumber': 0}, {'curveNumber': 2, 'pointNumber': 3}, {'curveNumber': 2, 'pointNumber': 7}, ], 'range': { 'x3': [0, 5], 'y3': [1, 6] } } self.assertEqual(boundsxy3.bounds, (0, 1, 5, 6)) self.assertEqual(selection1d3.index, [0, 3, 7]) # bounds streams on scatter 2 are None self.assertIsNone(boundsxy2a.bounds) self.assertIsNone(boundsxy2b.bounds) # Clear selection plotly_pane.selected_data = None self.assertIsNone(boundsxy3.bounds) self.assertIsNone(boundsxy2a.bounds) self.assertIsNone(boundsxy2b.bounds) self.assertEqual(selection1d3.index, [])
def test_doc_set(self) -> None: s = bis.State() d = Document() s.document = d assert isinstance(s.document, Document) assert s.document == d
def test_combine_ignores_all(self) -> None: doc = Document() e = bde.DocumentPatchedEvent(doc, "setter", "invoker") e2 = bde.DocumentPatchedEvent(doc, "setter", "invoker") assert e.combine(e2) == False
def test_combine_ignores_different_attr(self) -> None: doc = Document() e = bde.ModelChangedEvent(doc, "model", "attr", "new") e2 = bde.ModelChangedEvent(doc, "model", "attr2", "new2") assert e.combine(e2) == False
def test_render_explicit_server_doc_element(self): obj = Curve([]) doc = Document() server_doc = bokeh_renderer.server_doc(obj, doc) self.assertIs(server_doc, doc) self.assertIs(bokeh_renderer.last_plot.document, doc)
def test_init(self) -> None: doc = Document() e = bde.DocumentPatchedEvent(doc, "setter", "invoker") assert e.document == doc assert e.setter == "setter" assert e.callback_invoker == "invoker"
#%% load LUTs x_kde = np.linspace(-3.9, 3.9, 400) # should load from file... dbw = 0.002 # this too bws = np.arange( 0.01, 2.0 + dbw, dbw) # and this stuff. too make sure the LUT and slider match up kdes = np.loadtxt('lut_kde.csv', delimiter=',') x_hist_all = np.loadtxt('hist_bincenters.txt', delimiter=',') hist_counts_all = np.loadtxt('hist_counts.txt', delimiter=',') #%% bokeh prepare data doc = Document() # create fresh Document set_curdoc(doc) #> initial data bw0 = 0.07 ibw0 = 30 # 0.01 + 30*0.002 #counts_hist, x_hist = calcHist(bw0) #source_hist = ColumnDataSource({'x': x_hist, 'counts': counts_hist, 'bw': bw0*np.ones(x_hist.shape)}) x_hist_lut_dict = {} # could be combined with the next one hist_counts_lut_dict = {} kde_dict = {'x': x_kde} for i, bw in enumerate(bws): k = '{:.3f}'.format(bw)
theme = Theme(json=yaml.safe_load(""" attrs: Plot: outline_line_color: !!null Axis: axis_line_color: !!null major_tick_line_color: !!null axis_label_text_font_style: "bold" axis_label_text_font_size: "10pt" Grid: grid_line_dash: "dashed" Text: text_baseline: "middle" text_align: "center" text_font_size: "9pt" """)) doc = Document(theme=theme) doc.add_root(plot) if __name__ == "__main__": from bokeh.embed import file_html from bokeh.util.browser import view doc.validate() filename = "file_html.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, plot.title.text)) print("Wrote %s" % filename) view(filename)
def components(self, obj, fmt=None, comm=True, **kwargs): """ Returns data and metadata dictionaries containing HTML and JS components to include render in app, notebook, or standalone document. """ if isinstance(obj, Plot): plot = obj else: plot, fmt = self._validate(obj, fmt) data, metadata = {}, {} if isinstance(plot, Viewable): registry = list(Stream.registry.items()) objects = plot.object.traverse(lambda x: x) dynamic, streams = False, False for source in objects: dynamic |= isinstance(source, DynamicMap) streams |= any( src is source or (src._plot_id is not None and src._plot_id == source._plot_id) for src, streams in registry for s in streams) embed = (not (dynamic or streams or self.widget_mode == 'live') or config.embed) # This part should be factored out in Panel and then imported # here for HoloViews 2.0, which will be able to require a # recent Panel version. if embed or config.comms == 'default': comm = self.comm_manager.get_server_comm() if comm else None doc = Document() with config.set(embed=embed): model = plot.layout._render_model(doc, comm) if embed: return render_model(model, comm) args = (model, doc, comm) if panel_version > '0.9.3': from panel.models.comm_manager import CommManager ref = model.ref['id'] manager = CommManager(comm_id=comm.id, plot_id=ref) client_comm = self.comm_manager.get_client_comm( on_msg=partial(plot._on_msg, ref, manager), on_error=partial(plot._on_error, ref), on_stdout=partial(plot._on_stdout, ref)) manager.client_comm_id = client_comm.id args = args + (manager, ) return render_mimebundle(*args) # Handle rendering object as ipywidget widget = ipywidget(plot, combine_events=True) if hasattr(widget, '_repr_mimebundle_'): return widget._repr_mimebundle() plaintext = repr(widget) if len(plaintext) > 110: plaintext = plaintext[:110] + '…' data = { 'text/plain': plaintext, } if widget._view_name is not None: data['application/vnd.jupyter.widget-view+json'] = { 'version_major': 2, 'version_minor': 0, 'model_id': widget._model_id } if config.comms == 'vscode': # Unfortunately VSCode does not yet handle _repr_mimebundle_ from IPython.display import display display(data, raw=True) return {'text/html': '<div style="display: none"></div>'}, {} return data, {} else: html = self._figure_data(plot, fmt, as_script=True, **kwargs) data['text/html'] = html return (data, {MIME_TYPES['jlab-hv-exec']: metadata})
def test_setter(self) -> None: obj = ClassWithDocRef() assert obj.document is None d = Document() obj.document = d assert obj.document is d
def get_plot(self_or_cls, obj, doc=None, renderer=None, comm=None, **kwargs): """ Given a HoloViews Viewable return a corresponding plot instance. """ if isinstance(obj, DynamicMap) and obj.unbounded: dims = ', '.join('%r' % dim for dim in obj.unbounded) msg = ('DynamicMap cannot be displayed without explicit indexing ' 'as {dims} dimension(s) are unbounded. ' '\nSet dimensions bounds with the DynamicMap redim.range ' 'or redim.values methods.') raise SkipRendering(msg.format(dims=dims)) # Initialize DynamicMaps with first data item initialize_dynamic(obj) if not renderer: renderer = self_or_cls if not isinstance(self_or_cls, Renderer): renderer = self_or_cls.instance() if not isinstance(obj, Plot): if not displayable(obj): obj = collate(obj) initialize_dynamic(obj) with disable_pipeline(): obj = Compositor.map(obj, mode='data', backend=self_or_cls.backend) plot_opts = dict(self_or_cls.plot_options(obj, self_or_cls.size), **kwargs) if isinstance(obj, AdjointLayout): obj = Layout(obj) plot = self_or_cls.plotting_class(obj)(obj, renderer=renderer, **plot_opts) defaults = [kd.default for kd in plot.dimensions] init_key = tuple(v if d is None else d for v, d in zip(plot.keys[0], defaults)) plot.update(init_key) else: plot = obj # Trigger streams which were marked as requiring an update triggers = [] for p in plot.traverse(): if not hasattr(p, '_trigger'): continue for trigger in p._trigger: if trigger not in triggers: triggers.append(trigger) p._trigger = [] for trigger in triggers: Stream.trigger([trigger]) if isinstance(self_or_cls, Renderer): self_or_cls.last_plot = plot if comm: plot.comm = comm if comm or self_or_cls.mode == 'server': if doc is None: doc = Document() if self_or_cls.notebook_context else curdoc() plot.document = doc return plot
def test_hold_bad_policy(self) -> None: d = Document() cm = bdc.DocumentCallbackManager(d) with pytest.raises(ValueError): cm.hold("junk") # type: ignore [arg-type]
def make_example_datatable(): source = ColumnDataSource(mpg) print(source.column_names) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True, width=1000) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(source, cty_glyph) hwy = plot.add_glyph(source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = Column(plot, data_table) doc = Document() doc.add_root(layout) return doc
def test_setting_built_in_theme_error(self): obj = Model() doc = Document() doc.add_root(obj) with pytest.raises(ValueError): doc.theme = 1337
#CloseButton.on_click(close_session) CloseButton.callback = close_browser_js TextBox.on_change("value", update_textbox) def set_message(text): global MessageBox MessageBox.text = text layout = column(MessageBox, TextBox, CloseButton) oldcurdoc = bio.curdoc() currentstate = bio.curstate() TheDoc = Document(title="NewDoc") TheDoc.add_root(layout) def get_function_name(stackpos=1): ''' call me to get your name :return: name of the calling function ''' # my_name = inspect.stack()[0][3] caller = inspect.stack()[stackpos][3] return caller def session_update(): msg = get_function_name() msg += "\n%s" % (session.id, )
def document(): return Document()
def test_application_validates_document_by_default(check_integrity): a = Application() d = Document() d.add_root(figure()) a.initialize_document(d) assert check_integrity.called
def _repr_html_(self): self.doc = Document() for m in self.p.references(): m._document = None self.doc.add_root(self.p) return bokeh_notebook_div(self)
def test_doc_set(): s = state.State() d = Document() s.document = d assert isinstance(s.document, Document) assert s.document == d
def test_to_serializable(self) -> None: doc = Document() s = Serializer() e = bde.DocumentPatchedEvent(doc, "setter", "invoker") with pytest.raises(NotImplementedError): s.encode(e)
def test_application_validates_document_by_default(self, check_integrity: MagicMock) -> None: a = baa.Application() d = Document() d.add_root(figure()) a.initialize_document(d) assert check_integrity.called
def test_combine_ignores_except_title_changd_event(self) -> None: doc = Document() e = bde.ModelChangedEvent(doc, "model", "attr", "new") e2 = bde.DocumentPatchedEvent(doc, "setter", "invoker") assert e.combine(e2) == False
def test_set_curdoc_sets_curstate(): d = Document() bid.set_curdoc(d) assert curstate().document is d
def test_combine_ignores_all(self) -> None: doc = Document() e = bde.SessionCallbackAdded(doc, "setter") e2 = bde.SessionCallbackAdded(doc, "setter") assert e.combine(e2) == False
def get_document(self, docid): json_objs = self.pull(docid) doc = Document(json_objs) doc.docid = docid return doc
from __future__ import print_function from numpy import pi, arange, sin, cos from bokeh.util.browser import view from bokeh.document import Document from bokeh.models.glyphs import Circle from bokeh.models import (Plot, DataRange1d, LinearAxis, Grid, ColumnDataSource, PanTool, WheelZoomTool) from bokeh.client import push_session document = Document() session = push_session(document) x = arange(-2 * pi, 2 * pi, 0.1) y = sin(x) r = (cos(x) + 1) * 6 + 6 source = ColumnDataSource(data=dict(x=x, y=y, r=r)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=80) circle = Circle(x="x", y="y", size="r", fill_color="red", line_color="black") plot.add_glyph(source, circle) xaxis = LinearAxis() plot.add_layout(xaxis, 'below')
def test_setting_built_in_theme_missing(self): obj = Model() doc = Document() doc.add_root(obj) with pytest.raises(ValueError): doc.theme = 'some_theme_i_guess'
x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Diamond(x="x", y="y", size="sizes", line_color="#1c9099", line_width=2, fill_color=None) plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) doc = Document() doc.add_root(plot) show(plot)
def bokeh_json_string(self): """ Get a json string only for used bokeh figures. """ t_doc = Document(title=curdoc().title) for element in self._bokeh_figs: t_doc.add_root(element.plot_obj) return t_doc.to_json_string()