Python bokeh.io.curdoc() Examples

The following are 25 code examples of bokeh.io.curdoc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.io , or try the search function .
Example #1
Source File: renderer.py    From holoviews with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def app(self_or_cls, plot, show=False, new_window=False, websocket_origin=None, port=0):
        """
        Creates a bokeh app from a HoloViews object or plot. By
        default simply attaches the plot to bokeh's curdoc and returns
        the Document, if show option is supplied creates an
        Application instance and displays it either in a browser
        window or inline if notebook extension has been loaded.  Using
        the new_window option the app may be displayed in a new
        browser tab once the notebook extension has been loaded.  A
        websocket origin is required when launching from an existing
        tornado server (such as the notebook) and it is not on the
        default port ('localhost:8888').
        """
        if isinstance(plot, HoloViewsPane):
            pane = plot
        else:
            pane = HoloViewsPane(plot, backend=self_or_cls.backend, renderer=self_or_cls,
                                 **self_or_cls._widget_kwargs())
        if new_window:
            return pane._get_server(port, websocket_origin, show=show)
        else:
            kwargs = {'notebook_url': websocket_origin} if websocket_origin else {}
            return pane.app(port=port, **kwargs) 
Example #2
Source File: plotlistener.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def _bokeh_cb_push_adds(self, bootstrap_document=None):
        if bootstrap_document is None:
            document = curdoc()
        else:
            document = bootstrap_document

        with self._lock:
            client = self._clients[document.session_context.id]
            updatepkg_df: pandas.DataFrame = self._datastore[self._datastore['index'] > client.last_data_index]

            # skip if we don't have new data
            if updatepkg_df.shape[0] == 0:
                return

            updatepkg = ColumnDataSource.from_df(updatepkg_df)

            client.push_adds(updatepkg, new_last_index=updatepkg_df['index'].iloc[-1]) 
Example #3
Source File: base.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_root(self, doc=None, comm=None):
        """
        Returns the root model and applies pre-processing hooks

        Arguments
        ---------
        doc: bokeh.Document
          Bokeh document the bokeh model will be attached to.
        comm: pyviz_comms.Comm
          Optional pyviz_comms when working in notebook

        Returns
        -------
        Returns the bokeh model corresponding to this panel object
        """
        doc = doc or _curdoc()
        if self._updates:
            root = self._get_model(doc, comm=comm)
        else:
            root = self.layout._get_model(doc, comm=comm)
        self._preprocess(root)
        ref = root.ref['id']
        state._views[ref] = (self, root, doc, comm)
        return root 
Example #4
Source File: main.py    From flight_review with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show_exception_page():
            """ show an error page in case of an unknown/unhandled exception """
            title = 'Internal Error'

            error_message = ('<h3>Internal Server Error</h3>'
                             '<p>Please open an issue on <a '
                             'href="https://github.com/PX4/flight_review/issues" target="_blank">'
                             'https://github.com/PX4/flight_review/issues</a> with a link '
                             'to this log.')
            div = Div(text=error_message, width=int(plot_width*0.9))
            plots = [widgetbox(div, width=int(plot_width*0.9))]
            curdoc().template_variables['internal_error'] = True
            return (title, error_message, plots)


        # check which plots to show 
Example #5
Source File: param.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_root(self, doc=None, comm=None):
        """
        Returns the root model and applies pre-processing hooks

        Arguments
        ---------
        doc: bokeh.Document
          Bokeh document the bokeh model will be attached to.
        comm: pyviz_comms.Comm
          Optional pyviz_comms when working in notebook

        Returns
        -------
        Returns the bokeh model corresponding to this panel object
        """
        doc = doc or _curdoc()
        root = self.layout.get_root(doc, comm)
        ref = root.ref['id']
        self._models[ref] = (root, None)
        state._views[ref] = (self, root, doc, comm)
        return root 
Example #6
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def update_data(self):
        controller = self.network.notes[0]
        notes_df = pd.DataFrame(self.network.notes[1]).reset_index()
        notes_df.columns = ["index", "notes"]
        notes = ColumnDataSource(notes_df)
        self.data_table.source.data.update(notes.data)
        curdoc().title = "Notes for {}".format(controller) 
Example #7
Source File: state.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def curdoc(self):
        if self._curdoc:
            return self._curdoc
        elif _curdoc().session_context:
            return _curdoc() 
Example #8
Source File: callbacks.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self):
        if self._cb is not None:
            raise RuntimeError('Periodic callback has already started.')
        self._start_time = time.time()
        if _curdoc().session_context:
            self._doc = _curdoc()
            self._cb = self._doc.add_periodic_callback(self._periodic_callback, self.period)
        else:
            from tornado.ioloop import PeriodicCallback
            self._cb = PeriodicCallback(self._periodic_callback, self.period)
            self._cb.start() 
Example #9
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_server_doc_element(self):
        obj = Curve([])
        doc = bokeh_renderer.server_doc(obj)
        self.assertIs(doc, curdoc())
        self.assertIs(bokeh_renderer.last_plot.document, curdoc()) 
Example #10
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        Store.current_backend = self.previous_backend
        bokeh_renderer.last_plot = None
        Callback._callbacks = {}
        with param.logging_level('ERROR'):
            Renderer.notebook_context = self.nbcontext
        state.curdoc = None
        curdoc().clear()
        time.sleep(1) 
Example #11
Source File: renderer.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs):
        """
        Given a HoloViews Viewable return a corresponding plot instance.
        Allows supplying a document attach the plot to, useful when
        combining the bokeh model with another plot.
        """
        plot = super(BokehRenderer, self_or_cls).get_plot(obj, doc, renderer, **kwargs)
        if plot.document is None:
            plot.document = Document() if self_or_cls.notebook_context else curdoc()
        plot.document.theme = self_or_cls.theme
        return plot 
Example #12
Source File: renderer.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def server_doc(self_or_cls, obj, doc=None):
        """
        Get a bokeh Document with the plot attached. May supply
        an existing doc, otherwise bokeh.io.curdoc() is used to
        attach the plot to the global document instance.
        """
        if not isinstance(obj, HoloViewsPane):
            obj = HoloViewsPane(obj, renderer=self_or_cls, backend=self_or_cls.backend,
                                **self_or_cls._widget_kwargs())
        return obj.layout.server_doc(doc) 
Example #13
Source File: plot.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def theme(name):
    """Set color theme.

    :param name: name of theme

    >>> import arlpy.plot
    >>> arlpy.plot.theme('dark')
    """
    if name == 'dark':
        name = 'dark_minimal'
        set_colors(dark_palette)
    elif name == 'light':
        name = 'light_minimal'
        set_colors(light_palette)
    _bio.curdoc().theme = name 
Example #14
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def stop_update_data(self):
        doc = curdoc()
        try:
            doc.remove_periodic_callback(self._pcb)
        except:
            pass
        if self._recurring_update.is_running:
            self._recurring_update.stop()
            while self._recurring_update.is_running:
                pass
        try:
            doc.remove_next_tick_callback(self._ntcb)
        except (ValueError, RuntimeError):
            pass  # Already gone 
Example #15
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plan_update_data(self):
        doc = curdoc()
        if self._update_complete == True:
            self._update_complete = False
            self._ntcb = doc.add_next_tick_callback(self.update_data) 
Example #16
Source File: vrep_costar_stack.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def animate():
    if button.label == ' Play':
        button.label = ' Pause'
        curdoc().add_periodic_callback(animate_update, 10)
    else:
        button.label = ' Play'
        curdoc().remove_periodic_callback(animate_update) 
Example #17
Source File: stack_player.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def animate():
    if button.label == ' Play':
        button.label = ' Pause'
        curdoc().add_periodic_callback(animate_update, 10)
    else:
        button.label = ' Play'
        curdoc().remove_periodic_callback(animate_update) 
Example #18
Source File: plotlistener.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _bokeh_cb_push_patches(self):
        document = curdoc()
        session_id = document.session_context.id
        with self._lock:
            client: LiveClient = self._clients[session_id]

            patch_pkgs = self._patch_pkgs[session_id]
            self._patch_pkgs[session_id] = []
            client.push_patches(patch_pkgs) 
Example #19
Source File: liveclient.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _on_select_group(self, a, old, new):
        _logger.info(f"Switching logic group to {new}...")
        self._current_group = new
        doc = curdoc()
        doc.hold()
        self._refreshmodel()
        doc.unhold()

        self._push_data_fnc(doc)

        _logger.info(f"Switching logic group finished") 
Example #20
Source File: renderer.py    From holoviews with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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)
            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

        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 
Example #21
Source File: BokehRenderer.py    From BAC0 with GNU Lesser General Public License v3.0 4 votes vote down vote up
def update_data(self):
        self._log.debug("Update Data")
        doc = curdoc()
        # self.organize_data()
        if self._last_time_list:
            if self._last_time_list != self.s.keys():
                self._list_have_changed = True
                self.stop_update_data()
                # doc.add_next_tick_callback(self.modify_document)
                self.modify_document(doc)
            else:
                self._list_have_changed = False

        l = []
        for each in self.p.renderers:
            l.append(each.name)

            # for each in self.lst_of_trends:
            #    df = pd.DataFrame(each)
            #    df = df.reset_index()
            #    df['name'] = each.name
            #    df['units'] = str(each.units)
            #    df['time_s'] = df['index'].apply(str)

            #    try:
            #        df = df.fillna(method='ffill').fillna(
            #            method='bfill').replace(['inactive', 'active'], [0, 1])
            #    except TypeError:
            #        df = df.fillna(method='ffill').fillna(method='bfill')

            index = l.index(each.name)
        #    renderer = self.p.renderers[index]
        #    new_data = {}
        #    new_data['name'] = df['name']
        #    new_data['x'] = df['index']
        #    new_data['y'] = df[each.name]
        #    if each.states == 'binary':
        #        new_data['units'] = [each.units[int(x)] for x in df[each.name]]
        #    elif each.states == 'multistates':
        #        new_data['units'] = [
        #            each.units[int(math.fabs(x-1))] for x in df[each.name]]
        #    else:
        #        new_data['units'] = df['units']
        #    new_data['time'] = df['time_s']
        #    renderer.data_source.data = new_data
        try:
            new_data = self.build_data_sources()
            for each in self.lst_of_trends:
                self.sources[each.name].data = new_data[each.name].data

        except KeyError:
            self._log.warning(
                "Problem updating {} on chart, will try again next time.".format(
                    each.name
                )
            )

        else:
            self._last_time_list = self.s.keys()
            # self.start_update_data()
            self._update_complete = True 
Example #22
Source File: plot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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':
            from bokeh.io import curdoc
            thread = threading.current_thread()
            thread_id = thread.ident if thread else None
            if (curdoc() is not self.document or (state._thread_id is not None and
                thread_id != state._thread_id)):
                # 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 = [] 
Example #23
Source File: vrep_costar_stack.py    From costar_plan with Apache License 2.0 4 votes vote down vote up
def next_example(files, action):
    """ load the next example in the dataset
    """
    global file_textbox, button, button_next, button_prev, index, vrep_viz, data, numpy_data
    print("next clicked")
    file_textbox.value = "Processing..."
    renderer = hv.renderer('bokeh')
    if action == 'next':
        index = (index + 1) % len(files)
    else:
        index = (index - 1) % len(files)
    #print("it ", iterator)
    print("index before check", index)
    index = check_errors(files, index, action)
    print("index after check", index)
    print("len", len(files))

    file_name = files[index]
    data, numpy_data = load_example(file_name_list[index])
    rgb_images = numpy_data['rgb_images']
    frame_indices = numpy_data['frame_indices']
    gripper_status = numpy_data['gripper_status']
    action_status = numpy_data['action_status']
    gripper_action_label = numpy_data['gripper_action_label']
    gripper_action_goal_idx = numpy_data['gripper_action_goal_idx']
    print("image loaded")
    print("action goal idx", gripper_action_goal_idx)
    height = int(rgb_images[0].shape[0])
    width = int(rgb_images[0].shape[1])
    start = 0
    end = len(rgb_images)
    print(end)

    def slider_update(attrname, old, new):
        plot.update(slider.value)

    slider = Slider(start=start, end=end, value=0, step=1, title="Frame", width=width)
    slider.on_change('value', slider_update)

    holomap = generate_holo_map(rgb_images, height, width)
    print("generated holomap")
    plot = renderer.get_plot(holomap)
    print("plot rendered")
    gripper_plot, action_plot, gripper_action_plot = load_data_plot(renderer, frame_indices, gripper_status, action_status, gripper_action_label, height, width)
    print("plot loaded..")
    plot_list = [[plot.state], [gripper_plot.state], [action_plot.state]]

    widget_list = [[slider, button, button_prev, button_next], [file_textbox]]

    # "gripper_action" plot, labels based on the gripper opening and closing
    plot_list.append([gripper_action_plot.state])
    layout_child = layout(plot_list + widget_list, sizing_mode='fixed')
    curdoc().clear()
    file_textbox.value = file_name.split("\\")[-1]
    #curdoc().remove_root(layout_child)
    #layout_root.children[0] = layout_child
    curdoc().add_root(layout_child)

#iterator = iter(file_name_list) 
Example #24
Source File: stack_player.py    From costar_plan with Apache License 2.0 4 votes vote down vote up
def next_image(files, action):
    global file_textbox, button, button_next, button_prev, index
    print("next clicked")
    file_textbox.value = "Processing..."
    renderer = hv.renderer('bokeh')
    if action == 'next':
        index=(index + 1) % len(files)
    else:
        index=(index - 1) % len(files)
    #print("it ", iterator)
    print("index before check",index)
    index = check_errors(files, index, action)
    print("index after check", index)
    print("len", len(files))

    file_name = files[index]
    rgb_images, frame_indices, gripper_status, action_status, gripper_action_label, gripper_action_goal_idx = process_image(file_name)
    print("image loaded")
    print("action goal idx", gripper_action_goal_idx)
    height = int(rgb_images[0].shape[0])
    width = int(rgb_images[0].shape[1])
    start = 0
    end = len(rgb_images) - 1
    print(' End Index of RGB images: ' + str(end))

    def slider_update(attrname, old, new):
        plot.update(slider.value)

    slider = Slider(start=start, end=end, value=0, step=1, title="Frame", width=width)
    slider.on_change('value', slider_update)

    holomap = generate_holo_map(rgb_images, height, width)
    print("generated holomap")
    plot = renderer.get_plot(holomap)
    print("plot rendered")
    gripper_plot, action_plot, gripper_action_plot = load_data_plot(renderer, frame_indices, gripper_status, action_status, gripper_action_label, height, width)
    print("plot loaded..")
    plot_list = [[plot.state], [gripper_plot.state], [action_plot.state]]

    widget_list = [[slider, button, button_prev, button_next], [file_textbox]]

    # "gripper_action" plot, labels based on the gripper opening and closing
    plot_list.append([gripper_action_plot.state])
    layout_child = layout(plot_list + widget_list, sizing_mode='fixed')
    curdoc().clear()
    file_textbox.value = file_name.split("\\")[-1]
    #curdoc().remove_root(layout_child)
    #layout_root.children[0] = layout_child
    curdoc().add_root(layout_child)

#iterator = iter(file_name_list) 
Example #25
Source File: base.py    From panel with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _init_doc(self, doc=None, comm=None, title=None, notebook=False, location=True):
        doc = doc or _curdoc()
        title = title or 'Panel Application'
        doc.title = title
        col = Column()
        preprocess_root = col.get_root(doc, comm)
        ref = preprocess_root.ref['id']
        for name, (obj, tags) in self._render_items.items():
            model = obj.get_root(doc, comm)
            mref = model.ref['id']
            doc.on_session_destroyed(obj._server_destroy)
            for sub in obj.select(Viewable):
                submodel = sub._models.get(mref)
                if submodel is None:
                    continue
                sub._models[ref] = submodel
                if isinstance(sub, HoloViews) and mref in sub._plots:
                    sub._plots[ref] = sub._plots.get(mref)
            col.objects.append(obj)
            obj._documents[doc] = model
            model.name = name
            model.tags = tags
            self._apply_root(name, model, tags)
            for o in obj.select():
                self._apply_modifiers(o, mref)
            add_to_doc(model, doc, hold=bool(comm))

        state._fake_roots.append(ref)
        state._views[ref] = (col, preprocess_root, doc, comm)

        if location:
            from ..io.location import Location
            if isinstance(location, Location):
                loc = location
            elif doc in state._locations:
                loc = state.location
            else:
                loc = Location()
            state._locations[doc] = loc
            loc_model = loc._get_model(doc, preprocess_root)
            loc_model.name = 'location'
            #doc.add_root(loc_model)

        col._preprocess(preprocess_root)
        col._documents[doc] = preprocess_root
        doc.on_session_destroyed(col._server_destroy)

        if notebook:
            doc.template = self.nb_template
        else:
            doc.template = self.template
        doc._template_variables.update(self._render_variables)
        return doc