def _bokeh_reset(filename=None): curstate().reset() if filename: if not filename.endswith('.html'): filename += '.html' output_file(filename, title=filename) elif IS_JUPYTER_NOTEBOOK: curstate().output_notebook()
def test__get_save_args_default_resources() -> None: state = curstate() state.reset() state.output_file("filename") assert state.file is not None state.file.resources = INLINE _, resources, _ = bis._get_save_args(curstate(), "filename", None, "title") assert resources == INLINE
def test__get_save_args_default_title() -> None: state = curstate() state.reset() state.output_file("filename", title="title") assert state.file is not None assert state.file.title == "title" _, _, title = bis._get_save_args(curstate(), "filename", "inline", None) assert title == "title"
def test__get_save_args_explicit_resources() -> None: _, resources, _ = bis._get_save_args(curstate(), "filename", "inline", "title") assert resources.mode == "inline" # TODO: == Resources(mode="inline") _, resources, _ = bis._get_save_args(curstate(), "filename", INLINE, "title") assert resources == INLINE
def test_show_doesnt_duplicate_if_already_there(m): curstate().reset() assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document.roots == [p] bis.show(p) assert curstate().document.roots == [p]
def test_show_with_default_args(mock__show_with_state): curstate().reset() default_kwargs = dict(browser=None, new="tab", notebook_handle=False) p = Plot() bis.show(p, **default_kwargs) assert mock__show_with_state.call_count == 1 assert mock__show_with_state.call_args[0] == (p, curstate(), None, "tab") assert mock__show_with_state.call_args[1] == {'notebook_handle': False} assert p in curdoc().roots
def test_show_doesn_not_adds_obj_to_curdoc(m): curstate().reset() assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document.roots == []
def test_show_with_explicit_args(mock__show_with_state): curstate().reset() kwargs = dict(browser="browser", new="new", notebook_handle=True) p = Plot() bis.show(p, **kwargs) assert mock__show_with_state.call_count == 1 assert mock__show_with_state.call_args[0] == (p, curstate(), "browser", "new") assert mock__show_with_state.call_args[1] == {'notebook_handle': True} assert p in curdoc().roots
def test__get_save_args_missing_title(mock_warn): curstate().reset() filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", None) assert title == "Bokeh Plot" assert mock_warn.call_count == 1 assert mock_warn.call_args[0] == ( "save() called but no title was supplied and output_file(...) was never called, using default title 'Bokeh Plot'", ) assert mock_warn.call_args[1] == {}
def test__get_save_args_explicit_filename() -> None: filename, _, _ = bis._get_save_args(curstate(), "filename", "inline", "title") assert filename == "filename" filename, _, _ = bis._get_save_args(curstate(), Path("some") / "path" / "filename", "inline", "title") assert filename == Path("some") / "path" / "filename"
def test_show_doesn_not_adds_obj_to_curdoc(m) -> None: curstate().reset() assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document.roots == []
def test__get_save_args_missing_resources(mock_warn: MagicMock) -> None: curstate().reset() _, resources, _ = bis._get_save_args(curstate(), "filename", None, "title") assert resources.mode == "cdn" assert mock_warn.call_count == 1 assert mock_warn.call_args[0] == ( "save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN", ) assert mock_warn.call_args[1] == {}
def test__get_save_args_default_resources() -> None: state = curstate() state.reset() state.output_file("filename", mode="inline") assert state.file is not None assert state.file.resources.mode == "inline" r = state.file.resources _, resources, _ = bis._get_save_args(curstate(), "filename", None, "title") assert resources == r
def test__get_save_args_missing_resources(mock_warn): from bokeh.resources import CDN curstate().reset() filename, resources, title = bis._get_save_args(curstate(), "filename", None, "title") assert resources == CDN assert mock_warn.call_count == 1 assert mock_warn.call_args[0] == ( "save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN", ) assert mock_warn.call_args[1] == {}
def test_show_with_app(mock_run_notebook_hook): curstate().reset() app = Application() output_notebook() bis.show(app, notebook_url="baz") assert curstate().notebook_type == "jupyter" assert mock_run_notebook_hook.call_count == 1 assert mock_run_notebook_hook.call_args[0][0] == curstate().notebook_type assert mock_run_notebook_hook.call_args[0][1:] == ("app", app, curstate(), "baz") assert mock_run_notebook_hook.call_args[1] == {}
def _bokeh_reset(filename=None): curstate().reset() # Test if we are in Jupyter notebook if IS_JUPYTER_NOTEBOOK: curstate().output_notebook() elif filename: if not filename.endswith('.html'): filename += '.html' output_file(filename, title=filename) print('OUTPUT FILE.')
def test_curstate(): cs = bis.curstate() assert cs is bis._STATE print(bis.State) assert isinstance(cs, bis.State) cs2 = bis.curstate() assert cs is cs2 old_STATE = bis._STATE bis._STATE = None cs3 = bis.curstate() assert cs3 is bis._STATE assert isinstance(cs3, bis.State) assert cs3 is not cs2 bis._STATE = old_STATE
def visualize(profilers, file_path=None, show=True, save=True, mode=None, **kwargs): """Visualize the results of profiling in a bokeh plot. If multiple profilers are passed in, the plots are stacked vertically. Parameters ---------- profilers : profiler or list Profiler or list of profilers. file_path : string, optional Name of the plot output file. show : boolean, optional If True (default), the plot is opened in a browser. save : boolean, optional If True (default), the plot is saved to disk. mode : str, optional Mode passed to bokeh.output_file() **kwargs Other keyword arguments, passed to bokeh.figure. These will override all defaults set by visualize. Returns ------- The completed bokeh plot object. """ bp = import_required("bokeh.plotting", _BOKEH_MISSING_MSG) from bokeh.io import state if not state.curstate().notebook: file_path = file_path or "profile.html" bp.output_file(file_path, mode=mode) if not isinstance(profilers, list): profilers = [profilers] figs = [prof._plot(**kwargs) for prof in profilers] # Stack the plots if len(figs) == 1: p = figs[0] else: top = figs[0] for f in figs[1:]: f.x_range = top.x_range f.title = None f.min_border_top = 20 f.plot_height -= 30 for f in figs[:-1]: f.xaxis.axis_label = None f.min_border_bottom = 20 f.plot_height -= 30 for f in figs: f.min_border_left = 75 f.min_border_right = 75 p = bp.gridplot([[f] for f in figs]) if show: bp.show(p) if file_path and save: bp.save(p) return p
def test__get_save_args_default_title() -> None: curstate().reset() curstate().output_file("filename") curstate().file['title'] = "title" filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", None) assert title == "title"
def test__get_save_args_default_resources() -> None: curstate().reset() curstate().output_file("filename") curstate().file['resources'] = "resources" filename, resources, title = bis._get_save_args(curstate(), "filename", None, "title") assert resources == "resources"
def doRender(self, handlerId): clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true" if not clientHasBokeh: output_notebook(hide_banner=True) data = self.entity.getNextData() if data is None: return x = None y = None if isinstance(data, (list, np.ndarray)): x = list( range(self.windowSize) ) if self.glyphRenderer is None else self.glyphRenderer.data_source.data[ 'x'] y = data if self.glyphRenderer is None else self._concatArrays( self.glyphRenderer.data_source.data['y'], data) if len(y) < self.windowSize: y = [0] * (self.windowSize - len(y)) + y elif len(y) > self.windowSize: y = self._delWindowElements(y) elif isinstance(data, pandas.core.frame.DataFrame): pd = pd.drop(pd.index[[0]]) #pd.index = list(range(len(pd.index))) pd['x'] = list(range(len(pd.index))) else: x = data[0] y = data[1] if self.glyphRenderer is None: self.glyphRenderer = self.createGlyphRenderer(self.figure, x, y) else: self.updateGlyphRenderer(self.figure, self.glyphRenderer) if self.glyphRenderer is None: print("Error: no glyphRenderer found") return self.glyphRenderer.data_source.data['x'] = x self.glyphRenderer.data_source.data['y'] = y if not self.comms_handle: state = curstate() doc = state.document if self.figure not in doc.roots: doc.add_root(self.figure) self.comms_handle = show_doc(self.figure, state, notebook_handle=True) else: push_notebook(handle=self.comms_handle)
def test__save_helper(mock_file_html, mock_io_open): obj = Plot() filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", "title") bis._save_helper(obj, filename, resources, title) assert mock_file_html.call_count == 1 assert mock_file_html.call_args[0] == (obj, resources) assert mock_file_html.call_args[1] == {"title": "title"} assert mock_io_open.call_count == 1 assert mock_io_open.call_args[0] == (filename,) assert mock_io_open.call_args[1] == {"mode":"w", "encoding":"utf-8"}
def test__save_helper(mock_file_html, mock_io_open): obj = Plot() filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", "title") bis._save_helper(obj, filename, resources, title, None) assert mock_file_html.call_count == 1 assert mock_file_html.call_args[0] == (obj, resources) assert mock_file_html.call_args[1] == dict(title="title", template=None) assert mock_io_open.call_count == 1 assert mock_io_open.call_args[0] == (filename,) assert mock_io_open.call_args[1] == dict(mode="w", encoding="utf-8")
def test__save_helper(mock_file_html, mock_io_open): obj = Plot() filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", "title") bis._save_helper(obj, filename, resources, title, None) assert mock_file_html.call_count == 1 assert mock_file_html.call_args[0] == (obj, resources) assert mock_file_html.call_args[1] == dict(title="title", template=None) assert mock_io_open.call_count == 1 assert mock_io_open.call_args[0] == (filename, ) assert mock_io_open.call_args[1] == dict(mode="w", encoding="utf-8")
def test__save_helper(mock_file_html: MagicMock, mock_open: MagicMock) -> None: obj = Plot() filename, resources, title = bis._get_save_args(curstate(), "filename", "inline", "title") bis._save_helper(obj, filename, resources, title, None) assert mock_file_html.call_count == 1 assert mock_file_html.call_args[0] == (obj, resources) assert mock_file_html.call_args[1] == dict(title="title", template=FILE, theme=None) assert mock_open.call_count == 1 assert mock_open.call_args[0] == (filename, ) assert mock_open.call_args[1] == dict(mode="w", encoding="utf-8")
def doRender(self, handlerId): clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true" if not clientHasBokeh: output_notebook(hide_banner=True) data = self.entity.getNextData() if data is None: return x = None y = None if isinstance(data, (list,np.ndarray)): x = list(range(self.windowSize)) if self.glyphRenderer is None else self.glyphRenderer.data_source.data['x'] y = data if self.glyphRenderer is None else self._concatArrays(self.glyphRenderer.data_source.data['y'],data) if len(y) < self.windowSize: y = [0]*(self.windowSize-len(y)) + y elif len(y) > self.windowSize: y = self._delWindowElements(y) elif isinstance(data, pandas.core.frame.DataFrame): pd = pd.drop(pd.index[[0]]) #pd.index = list(range(len(pd.index))) pd['x'] = list(range(len(pd.index))) else: x = data[0] y = data[1] if self.glyphRenderer is None: self.glyphRenderer = self.createGlyphRenderer( self.figure, x, y ) else: self.updateGlyphRenderer( self.figure, self.glyphRenderer) if self.glyphRenderer is None: print("Error: no glyphRenderer found") return self.glyphRenderer.data_source.data['x'] = x self.glyphRenderer.data_source.data['y'] = y if not self.comms_handle: state = curstate() doc = state.document if self.figure not in doc.roots: doc.add_root(self.figure) self.comms_handle = show_doc(self.figure, state, notebook_handle=True) else: push_notebook(handle = self.comms_handle)
def set_display_settings(): """Enable notebook output settings if running in a jupyter notebook""" from IPython.core.getipython import get_ipython from ipykernel.zmqshell import ZMQInteractiveShell from bokeh.io import output_notebook from bokeh.resources import Resources from bokeh.io.state import curstate ipython_instance = get_ipython() if ipython_instance is not None: if isinstance(ipython_instance, ZMQInteractiveShell): _IPYTHON_INSTANCE = True # Defer to previous call to ``output_notebook`` so that users # can specify their own notebook type and Bokeh resources if curstate().notebook_type is None: # Inline resources uses bokeh.js from the local version. # This enables offline usage. output_notebook(Resources('inline'), hide_banner=True)
def __spawn_server(self): bslg = logging.getLogger('bokeh.server.util') bsll = bslg.getEffectiveLevel() bslg.setLevel(logging.ERROR) self._server_info['application'] = app = Application( FunctionHandler(self.__entry_point)) self._server_info['server'] = srv = Server( {'/': app}, io_loop=IOLoop.instance(), port=0, allow_websocket_origin=['*']) self._server_info['server_id'] = srv_id = uuid4().hex curstate().uuid_to_server[srv_id] = srv srv_addr = srv.address if srv.address else socket.gethostbyname( socket.gethostname()) self._server_info['server_url'] = 'http://{}:{}/'.format( srv_addr, srv.port) srv.start() bslg.setLevel(bsll)
def _show_zeppelin_app_with_state(app, state, notebook_url): logging.basicConfig() from tornado.ioloop import IOLoop from bokeh.server.server import Server loop = IOLoop.current() server = Server({"/": app}, io_loop=loop, port=0, allow_websocket_origin=[notebook_url]) server_id = uuid.uuid4().hex if _isAfterBokeh1210: from bokeh.io.state import curstate curstate().uuid_to_server[server_id] = server else: bokeh.io._state.uuid_to_server[server_id] = server server.start() url = 'http://%s:%d%s' % (notebook_url.split(':')[0], server.port, "/") script = server_document(url) div_html = "<div class='bokeh_class' id='{divid}'>{script}</div>" print('%html ' + div_html.format(script=script, divid=server_id))
def test__get_save_args_default_title(): curstate().reset() curstate().output_file("filename") curstate().file['title'] = "title" filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", None) assert title == "title"
def test_reset_output(mock_reset): # might create a new one, which also calls reset original_call_count = curstate().reset.call_count bio.reset_output() assert curstate().reset.call_count == original_call_count + 1
def test_set_curdoc_sets_curstate(): d = Document() bid.set_curdoc(d) assert curstate().document is d
def test_curdoc_from_curstate(): assert bid.curdoc() is curstate().document
def test_show_adds_obj_to_document_if_not_already_there(m): curstate().reset() assert curstate().document.roots == [] p = Plot() bis.show(p) assert p in curstate().document.roots
def test_reset_output(mock_reset): # might create a new one, which also calls reset original_call_count = curstate().reset.call_count bio.reset_output() assert curstate().reset.call_count == original_call_count+1
def test__get_save_args_default_resources(): curstate().reset() curstate().output_file("filename") curstate().file['resources'] = "resources" filename, resources, title = bis._get_save_args(curstate(), "filename", None, "title") assert resources == "resources"
def visualize(profilers, file_path=None, show=True, save=True, **kwargs): """Visualize the results of profiling in a bokeh plot. If multiple profilers are passed in, the plots are stacked vertically. Parameters ---------- profilers : profiler or list Profiler or list of profilers. file_path : string, optional Name of the plot output file. show : boolean, optional If True (default), the plot is opened in a browser. save : boolean, optional If True (default), the plot is saved to disk. **kwargs Other keyword arguments, passed to bokeh.figure. These will override all defaults set by visualize. Returns ------- The completed bokeh plot object. """ bp = import_required('bokeh.plotting', _BOKEH_MISSING_MSG) import bokeh if LooseVersion(bokeh.__version__) >= "0.12.10": from bokeh.io import state in_notebook = state.curstate().notebook else: from bokeh.io import _state in_notebook = _state._notebook if not in_notebook: file_path = file_path or "profile.html" bp.output_file(file_path) if not isinstance(profilers, list): profilers = [profilers] figs = [prof._plot(**kwargs) for prof in profilers] # Stack the plots if len(figs) == 1: p = figs[0] else: top = figs[0] for f in figs[1:]: f.x_range = top.x_range f.title = None f.min_border_top = 20 f.plot_height -= 30 for f in figs[:-1]: f.xaxis.axis_label = None f.min_border_bottom = 20 f.plot_height -= 30 for f in figs: f.min_border_left = 75 f.min_border_right = 75 p = bp.gridplot([[f] for f in figs]) if show: bp.show(p) if file_path and save: bp.save(p) return p
def test__get_save_args_default_filename(): curstate().reset() curstate().output_file("filename") filename, resources, title = bis._get_save_args(curstate(), None, "resources", "title") assert filename == "filename"
def test__get_save_args_explicit_resources(): filename, resources, title = bis._get_save_args(curstate(), "filename", "resources", "title") assert resources == "resources"