Python bokeh.document.Document() Examples

The following are 27 code examples of bokeh.document.Document(). 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.document , 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: bokeh_webapp.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def start(self, ioloop=None):
        """Serves a backtrader result as a Bokeh application running on a web server"""
        def make_document(doc: Document):
            if self._on_session_destroyed is not None:
                doc.on_session_destroyed(self._on_session_destroyed)

            # set document title
            doc.title = self._title

            # set document template
            env = Environment(loader=PackageLoader('backtrader_plotting.bokeh', 'templates'))
            doc.template = env.get_template(self._html_template)
            doc.template_variables['stylesheet'] = utils.generate_stylesheet(self._scheme)

            # get root model
            model = self._model_factory_fnc(doc)
            doc.add_root(model)

        self._run_server(make_document, ioloop=ioloop, port=self._port) 
Example #3
Source File: stream.py    From memex-explorer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, crawl_name, num_urls=DEFAULT_NUM_URLS):
        """
        Create a NutchUrlTrails instance for visualizing a running Nutch crawl in real-time using Bokeh
        :param name: The name of the crawl (as identified by the queue)
        :param num_urls: The number of URLs to display in the visualization
        :return: A NutchUrLTrails instance
        """
        self.crawl_name = crawl_name
        self.num_urls = num_urls
        self.open_urls = {}
        self.closed_urls = {}
        self.old_segments = None
        self.old_circles = None
        
        self.session = Session()
        self.session.use_doc(self.crawl_name)
        self.document = Document()

        con = Connection()

        exchange = Exchange(EXCHANGE_NAME, 'direct', durable=False)
        queue = Queue(crawl_name, exchange=exchange, routing_key=crawl_name)
        self.queue = con.SimpleQueue(name=queue) 
Example #4
Source File: ui.py    From nlp-architect with Apache License 2.0 6 votes vote down vote up
def serve_absa_ui() -> None:
    """Main function for serving UI application.
    """

    def _doc_modifier(doc: Document) -> None:
        grid = _create_ui_components()
        doc.add_root(grid)

    print("Opening Bokeh application on http://localhost:5006/")
    server = Server(
        {"/": _doc_modifier},
        websocket_max_message_size=5000 * 1024 * 1024,
        extra_patterns=[
            (
                "/style/(.*)",
                StaticFileHandler,
                {"path": os.path.normpath(join(SOLUTION_DIR, "/style"))},
            )
        ],
    )
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start() 
Example #5
Source File: absa_solution.py    From nlp-architect with Apache License 2.0 6 votes vote down vote up
def serve_absa_ui() -> None:
    """Main function for serving UI application.
    """

    def _doc_modifier(doc: Document) -> None:
        grid = _create_ui_components()
        doc.add_root(grid)

    print("Opening Bokeh application on http://localhost:5006/")
    server = Server(
        {"/": _doc_modifier},
        websocket_max_message_size=5000 * 1024 * 1024,
        extra_patterns=[
            (
                "/style/(.*)",
                StaticFileHandler,
                {"path": os.path.normpath(join(SOLUTION_DIR, "/style"))},
            )
        ],
    )
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start() 
Example #6
Source File: test_master_app.py    From estimagic with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_master_app():
    # just testing that this does not raise an Error
    doc = Document()
    current_dir_path = Path(__file__).resolve().parent
    name_to_path = {
        "db1": current_dir_path / "db1.db",
        "db2": current_dir_path / "db2.db",
    }
    master_app.master_app(doc=doc, database_name_to_path=name_to_path, session_data={})


# not testing _create_section_to_elements()

# not testing name_to_bokeh_row_elements

# not testing _setup_tabs 
Example #7
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_set_up_linked_change_stream_on_server_doc(self):
        obj = Curve([])
        stream = RangeXY(source=obj)
        server_doc = bokeh_renderer.server_doc(obj)
        self.assertIsInstance(server_doc, Document)
        self.assertEqual(len(bokeh_renderer.last_plot.callbacks), 1)
        cb = bokeh_renderer.last_plot.callbacks[0]
        self.assertIsInstance(cb, RangeXYCallback)
        self.assertEqual(cb.streams, [stream])
        x_range = bokeh_renderer.last_plot.handles['x_range']
        self.assertIn(cb.on_change, x_range._callbacks['start'])
        self.assertIn(cb.on_change, x_range._callbacks['end'])
        y_range = bokeh_renderer.last_plot.handles['y_range']
        self.assertIn(cb.on_change, y_range._callbacks['start'])
        self.assertIn(cb.on_change, y_range._callbacks['end']) 
Example #8
Source File: bokeh_handler.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def with_workspaces(handler):
    @with_request
    @wraps(handler)
    def wrapper(doc: Document):
        doc.user_workspace = get_user_workspace(doc.request)
        doc.app_workspace = get_app_workspace(doc.request)
        return handler(doc)
    return wrapper 
Example #9
Source File: bokeh_handler.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def with_request(handler):
    @wraps(handler)
    def wrapper(doc: Document):
        bokeh_request = doc.session_context.request
        bokeh_request.pop('scheme')
        django_request = HttpRequest()
        for k, v in bokeh_request.items():
            setattr(django_request, k, v)
        doc.request = django_request
        return handler(doc)
    return wrapper 
Example #10
Source File: test_bokeh_handler.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_workspaces_to_document_handler(doc: Document):
    return doc.user_workspace, doc.app_workspace 
Example #11
Source File: test_bokeh_handler.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def bokeh_to_http_request_handler(doc: Document):
    return doc.request 
Example #12
Source File: plot.py    From blocks-extras with MIT License 5 votes vote down vote up
def __init__(self, document_name, server_url=None, start_server=False,
                 clear_document=True, **kwargs):
        self.document_name = document_name
        self.server_url = (config.bokeh_server if server_url is None
                           else server_url)
        self.start_server = start_server
        self.sub = self._start_server_process() if self.start_server else None
        self.session = Session(root_url=self.server_url)
        self.document = Document()
        self._setup_document(clear_document)
        super(PlottingExtension, self).__init__(**kwargs) 
Example #13
Source File: notebook.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show_embed(panel, max_states=1000, max_opts=3, json=False,
               json_prefix='', save_path='./', load_path=None,
               progress=True, states={}):
    """
    Renders a static version of a panel in a notebook by evaluating
    the set of states defined by the widgets in the model. Note
    this will only work well for simple apps with a relatively
    small state space.

    Arguments
    ---------
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    json: boolean (default=True)
      Whether to export the data to json files
    json_prefix: str (default='')
      Prefix for JSON filename
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    progress: boolean (default=False)
      Whether to report progress
    states: dict (default={})
      A dictionary specifying the widget values to embed for each widget
    """
    from IPython.display import publish_display_data
    from ..config import config

    doc = Document()
    comm = Comm()
    with config.set(embed=True):
        model = panel.get_root(doc, comm)
        embed_state(panel, model, doc, max_states, max_opts,
                    json, json_prefix, save_path, load_path, progress,
                    states)
    publish_display_data(*render_model(model)) 
Example #14
Source File: model.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bokeh_repr(obj, depth=0, ignored=None):
    """
    Returns a string repr for a bokeh model, useful for recreating
    panel objects using pure bokeh.
    """
    if ignored is None:
        ignored = _DEFAULT_IGNORED_REPR

    from ..viewable import Viewable
    if isinstance(obj, Viewable):
        obj = obj.get_root(Document())

    r = ""
    cls = type(obj).__name__
    properties = sorted(obj.properties_with_values(False).items())
    props = []
    for k, v in properties:
        if k in ignored:
            continue
        if isinstance(v, Model):
            v = '%s()' % type(v).__name__
        else:
            v = repr(v)
        if len(v) > 30:
            v = v[:30] + '...'
        props.append('%s=%s' % (k, v))
    props = ', '.join(props)
    if isinstance(obj, Box):
        r += '{cls}(children=[\n'.format(cls=cls)
        for obj in obj.children:
            r += textwrap.indent(bokeh_repr(obj, depth=depth+1) + ',\n', '  ')
        r += '], %s)' % props
    else:
        r += '{cls}({props})'.format(cls=cls,  props=props)
    return r 
Example #15
Source File: model.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_to_doc(obj, doc, hold=False):
    """
    Adds a model to the supplied Document removing it from any existing Documents.
    """
    # Add new root
    remove_root(obj)
    doc.add_root(obj)
    if doc._hold is None and hold:
        doc.hold() 
Example #16
Source File: conftest.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def document():
    return Document() 
Example #17
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_set_up_linked_event_stream_on_server_doc(self):
        obj = Curve([])
        stream = PlotReset(source=obj)
        server_doc = bokeh_renderer.server_doc(obj)
        self.assertIsInstance(server_doc, Document)
        cb = bokeh_renderer.last_plot.callbacks[0]
        self.assertIsInstance(cb, ResetCallback)
        self.assertEqual(cb.streams, [stream])
        plot = bokeh_renderer.last_plot.state
        self.assertIn(cb.on_event, plot._event_callbacks['reset']) 
Example #18
Source File: testserver.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #19
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 #20
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 #21
Source File: renderer.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def html(self, obj, fmt=None, css=None, resources='CDN', **kwargs):
        """
        Renders plot or data structure and wraps the output in HTML.
        The comm argument defines whether the HTML output includes
        code to initialize a Comm, if the plot supplies one.
        """
        plot, fmt =  self._validate(obj, fmt)
        figdata, _ = self(plot, fmt, **kwargs)
        if isinstance(resources, basestring):
            resources = resources.lower()
        if css is None: css = self.css

        if isinstance(plot, Viewable):
            doc = Document()
            plot._render_model(doc)
            if resources == 'cdn':
                resources = CDN
            elif resources == 'inline':
                resources = INLINE
            return file_html(doc, resources)
        elif fmt in ['html', 'json']:
            return figdata
        else:
            if fmt == 'svg':
                figdata = figdata.encode("utf-8")
            elif fmt == 'pdf' and 'height' not in css:
                _, h = self.get_size(plot)
                css['height'] = '%dpx' % (h*self.dpi*1.15)

        if isinstance(css, dict):
            css = '; '.join("%s: %s" % (k, v) for k, v in css.items())
        else:
            raise ValueError("CSS must be supplied as Python dictionary")

        b64 = base64.b64encode(figdata).decode("utf-8")
        (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
        src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
        html = tag.format(src=src, mime_type=mime_type, css=css)
        return html 
Example #22
Source File: stream.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_plot(crawl_name):
    session = Session()
    document = Document()
    session.use_doc(crawl_name)
    session.load_document(document)

    if document.context.children:
        plot = document.context.children[0]
    else:
        output_server(crawl_name)
        # TODO: Remove these when Bokeh is upgraded
        # placeholders or Bokeh can't inject properly
        current = np.datetime64(datetime.now())
        xdr = Range1d(current, current + 1)
        ydr = ["urls"]

        # styling suggested by Bryan
        plot = figure(title="Crawler Monitor", tools="hover",
                      x_axis_type="datetime", y_axis_location="right", x_range=xdr, y_range=ydr,
                      width=1200, height=600)
        plot.toolbar_location = None
        plot.xgrid.grid_line_color = None

        # temporarily turn these off
        plot.ygrid.grid_line_color = None
        plot.xaxis.minor_tick_line_color = None
        plot.xaxis.major_tick_line_color = None
        plot.xaxis.major_label_text_font_size = '0pt'
        plot.yaxis.minor_tick_line_color = None
        plot.yaxis.major_tick_line_color = None
        plot.yaxis.major_label_text_font_size = '0pt'

    document.add(plot)
    session.store_document(document)
    script = autoload_server(plot, session)

    #TODO: Looks like a Bokeh bug, probably not repeatable with current code
    script = script.replace("'modelid': u'", "'modelid': '")
    return script 
Example #23
Source File: plotlistener.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _bokeh_cb_build_root_model(self, doc: Document):
        client = LiveClient(doc,
                            self._bokeh_cb_push_adds,
                            self._create_bokeh,
                            self._bokeh_cb_push_adds,
                            self._cerebro.runningstrats[self.p.strategyidx],
                            lookback=self.p.lookback)

        with self._lock:
            self._clients[doc.session_context.id] = client

        self._bokeh_cb_push_adds(doc)

        return client.model 
Example #24
Source File: liveclient.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, doc: Document, push_fnc, bokeh_fac: callable, push_data_fnc:callable, strategy: bt.Strategy, figurepage_idx: int = 0, lookback: int = 20):
        self._slider_aspectratio = None
        self._push_data_fnc = push_data_fnc
        self._push_fnc = push_fnc
        self._figurepage_idx = figurepage_idx
        self.last_data_index = -1
        self._lookback = lookback
        self._strategy = strategy
        self._current_group = None
        self.document = doc

        self._bokeh_fac = bokeh_fac
        self._bokeh = None

        bokeh = self._bokeh_fac()  # temporary bokeh object to get tradingdomains and scheme
        self._scheme = copy(bokeh.p.scheme)  # preserve original scheme as originally provided by the user

        tradingdomains = bokeh.list_tradingdomains(strategy)
        self._current_group = tradingdomains[0]
        self._select_tradingdomain = Select(value=self._current_group, options=tradingdomains)
        self._select_tradingdomain.on_change('value', self._on_select_group)

        btn_refresh_analyzers = Button(label='Refresh Analyzers', width=100)
        btn_refresh_analyzers.on_click(self._on_click_refresh_analyzers)

        td_label = Div(text="Trading Domain:", margin=(9, 5, 15, 5))
        controls = row(children=[td_label, self._select_tradingdomain, btn_refresh_analyzers])
        self.model = column(children=[controls, Tabs(tabs=[])], sizing_mode=self._scheme.plot_sizing_mode)

        # append meta tab
        meta = Div(text=metadata.get_metadata_div(strategy))
        self._panel_metadata = Panel(child=meta, title="Meta")

        self._refreshmodel() 
Example #25
Source File: test_monitoring_app.py    From estimagic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_monitoring_app():
    """Integration test that no Error is raised when calling the monitoring app."""
    doc = Document()
    database_name = "test_db"
    current_dir_path = Path(__file__).resolve().parent
    session_data = {"last_retrieved": 0, "database_path": current_dir_path / "db1.db"}

    monitoring.monitoring_app(
        doc=doc, database_name=database_name, session_data=session_data
    ) 
Example #26
Source File: testdynamic.py    From holoviews with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_update_dynamic_map_with_stream(self):
        ys = np.arange(10)

        # Build stream
        Scale = Stream.define('Scale', scale=1.0)
        scale_stream = Scale()

        # Build DynamicMap
        def build_scatter(scale):
            return hv.Scatter(ys * scale)

        dmap = hv.DynamicMap(build_scatter, streams=[scale_stream])

        # Create HoloViews Pane using panel so that we can access the plotly pane
        # used to display the plotly figure
        dmap_pane = pn.pane.HoloViews(dmap, backend='plotly')

        # Call get_root to force instantiation of internal plots/models
        doc = Document()
        comm = Comm()
        dmap_pane.get_root(doc, comm)

        # Get reference to the plotly pane
        _, plotly_pane = next(iter(dmap_pane._plots.values()))

        # Check initial data
        data = plotly_pane.object['data']
        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['type'], 'scatter')
        np.testing.assert_equal(data[0]['y'], ys)

        # Watch object for changes
        fn = Mock()
        plotly_pane.param.watch(fn, 'object')

        # Update stream
        scale_stream.event(scale=2.0)

        # Check that figure object was updated
        data = plotly_pane.object['data']
        np.testing.assert_equal(data[0]['y'], ys * 2.0)

        # Check that object callback was triggered
        fn.assert_called_once()
        args, kwargs = fn.call_args_list[0]
        event = args[0]
        self.assertIs(event.obj, plotly_pane)
        self.assertIs(event.new, plotly_pane.object) 
Example #27
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