Example #1
0
def test_application_doesnt_validate_document_due_to_env_var(check_integrity, monkeypatch):
    monkeypatch.setenv("BOKEH_VALIDATE_DOC", "false")
    a = Application()
    d = Document()
    d.add_root(figure())
    a.initialize_document(d)
    assert not check_integrity.called
Example #2
0
 def test_with_doc(self, test_plot, test_table):
     from bokeh.models import Button
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_table)
     assert beb._any([d], lambda x: isinstance(x, object)) is True
     assert beb._any([d], lambda x: isinstance(x, Button)) is False
Example #3
0
 def test_without_widgets(self, test_plot, test_glplot, test_table, test_widget):
     assert beb._use_widgets([test_plot]) is False
     assert beb._use_widgets([test_plot, test_glplot]) is False
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_glplot)
     assert beb._use_widgets([d]) is False
Example #4
0
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

    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 #5
0
 def test_width(self):
     p = figure(plot_width=200, plot_height=300)
     d = Document()
     d.add_root(p)
     util.set_single_plot_width_height(d, 400, None)
     assert p.plot_width == 400
     assert p.plot_height == 300
    def test_document_bad_on_session_destroyed_signature(self):
        doc = Document()

        def destroy(a, b):
            pass

        with pytest.raises(ValueError):
            doc.on_session_destroyed(destroy)
Example #7
0
 def test_layout(self):
     p = figure(plot_width=200, plot_height=300)
     d = Document()
     d.add_root(row(p))
     with pytest.warns(UserWarning) as warns:
         util.set_single_plot_width_height(d, 400, 500)
         assert len(warns) == 1
         assert warns[0].message.args[0] == _SIZE_WARNING
Example #8
0
def index():
    plot = figure()
    plot.circle([1,2], [3,4])
    document = Document()
    document.add_root(plot)

    session = push_session(document)
    script = autoload_server(None, session_id=session.id)

    return render_template('index.html', bokeh_script=script)
Example #9
0
    def test_compute_remove_root_patch(self):
        from bokeh.document import Document
        d = Document()
        root1 = SomeModelInTestDocument(foo=42)
        child1 = AnotherModelInTestDocument(bar=43)
        root1.child = child1
        d.add_root(root1)

        before = d.to_json()

        d.remove_root(root1)

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(references=[],
                        events= [
                            {'kind': 'RootRemoved',
                             'model': {'id': None,
                                       'type': 'SomeModelInTestDocument'}}
                        ])
        expected['events'][0]['model']['id'] = root1._id

        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual([], d2.roots)
Example #10
0
    def test_compute_add_root_patch(self):
        from bokeh.document import Document

        d = Document()
        root1 = SomeModelInTestDocument(foo=42)
        child1 = AnotherModelInTestDocument(bar=43)
        root1.child = child1
        d.add_root(root1)

        before = d.to_json()

        root2 = SomeModelInTestDocument(foo=57)
        d.add_root(root2)

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = {
            "references": [{"attributes": {"child": None, "foo": 57}, "id": None, "type": "SomeModelInTestDocument"}],
            "events": [{"kind": "RootAdded", "model": {"id": None, "type": "SomeModelInTestDocument"}}],
        }

        expected["references"][0]["id"] = root2._id
        expected["events"][0]["model"]["id"] = root2._id

        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual(2, len(d2.roots))
        self.assertEqual(42, d2.roots[0].foo)
        self.assertEqual(57, d2.roots[1].foo)
Example #11
0
    def test_compute_remove_root_patch(self):
        from bokeh.document import Document

        d = Document()
        root1 = SomeModelInTestDocument(foo=42)
        child1 = AnotherModelInTestDocument(bar=43)
        root1.child = child1
        d.add_root(root1)

        before = d.to_json()

        d.remove_root(root1)

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(
            references=[], events=[{"kind": "RootRemoved", "model": {"id": None, "type": "SomeModelInTestDocument"}}]
        )
        expected["events"][0]["model"]["id"] = root1._id

        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual([], d2.roots)
Example #12
0
    def go(self):

        """Displays the application"""

        document = Document()
        document.title = "UT330 UI"
        document.add_root(self.tabs)
        session = push_session(document)
        session.show()

        session.loop_until_closed()
Example #13
0
 def test_with_doc_in_child_raises_error(self):
     doc = Document()
     p1 = Model()
     p2 = SomeModelInTestObjects(child=Model())
     doc.add_root(p2.child)
     self.assertIs(p1.document, None)
     self.assertIs(p2.document, None)
     self.assertIs(p2.child.document, doc)
     with self.assertRaisesRegexp(RuntimeError, p2._id):
         with _ModelInDocument([p1, p2]):
             self.assertIsNot(p1.document, None)
             self.assertIsNot(p2.document, None)
             self.assertIs(p1.document, doc)
             self.assertIs(p2.document, doc)
Example #14
0
def get_bokeh_script(user, plot, suffix):
    from .models import UserSession

    document = Document()
    document.add_root(plot)
    document.title = suffix

    with closing(push_session(document)) as session:
        # Save the session id to a UserSession
        UserSession.objects.create(user=user, bokeh_session_id=session.id)
        # Get the script to pass into the template
        script = autoload_server(None, session_id=session.id)

    return script
    def test_document_on_session_destroyed(self):
        doc = Document()
        handler = bahd.DocumentLifecycleHandler()

        def destroy(session_context):
            assert doc is session_context._document
            session_context.status = 'Destroyed'

        doc.on_session_destroyed(destroy)

        session_context = MockSessionContext(doc)
        handler.on_session_destroyed(session_context)
        assert session_context.status == 'Destroyed'
        assert session_context._document.session_destroyed_callbacks == set()
Example #16
0
 def test_with_doc_in_child_raises_error(self):
     doc = Document()
     p1 = Model()
     p2 = SomeModelInTestObjects(child=Model())
     doc.add_root(p2.child)
     assert p1.document is None
     assert p2.document is None
     assert p2.child.document is doc
     with pytest.raises(RuntimeError):
         with bes._ModelInDocument([p1, p2]):
             assert p1.document is not None
             assert p2.document is not None
             assert p1.document is doc
             assert p2.document is doc
Example #17
0
def get_bokeh_script(plot):

    from .models import UserSession

    document = Document()
    document.add_root(plot)

    with closing(push_session(document, url=bokeh_url)) as session:
        # Save the session id
        UserSession.objects.create(user=User.objects.get(),
                                   bokehSessionId=session.id)
        # Get the script to pass into the template
        script = autoload_server(None, session_id=session.id, url=bokeh_url)

    return script
Example #18
0
    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.
        """
        if doc is None:
            doc = Document() if self_or_cls.notebook_context else curdoc()

        if self_or_cls.notebook_context:
            curdoc().theme = self_or_cls.theme
        doc.theme = self_or_cls.theme
        plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer, **kwargs)
        plot.document = doc
        return plot
Example #19
0
    def create_session_if_needed(self, session_id, request=None):
        # this is because empty session_ids would be "falsey" and
        # potentially open up a way for clients to confuse us
        if len(session_id) == 0:
            raise ProtocolError("Session ID must not be empty")

        if session_id not in self._sessions and \
           session_id not in self._pending_sessions:
            future = self._pending_sessions[session_id] = gen.Future()

            doc = Document()


            session_context = BokehSessionContext(session_id,
                                                  self.server_context,
                                                  doc)
            # using private attr so users only have access to a read-only property
            session_context._request = request

            # expose the session context to the document
            # use the _attribute to set the public property .session_context
            doc._session_context = session_context


            try:
                yield yield_for_all_futures(self._application.on_session_created(session_context))
            except Exception as e:
                log.error("Failed to run session creation hooks %r", e, exc_info=True)

            self._application.initialize_document(doc)

            session = ServerSession(session_id, doc, io_loop=self._loop)
            del self._pending_sessions[session_id]
            self._sessions[session_id] = session
            session_context._set_session(session)
            self._session_contexts[session_id] = session_context

            # notify anyone waiting on the pending session
            future.set_result(session)

        if session_id in self._pending_sessions:
            # another create_session_if_needed is working on
            # creating this session
            session = yield self._pending_sessions[session_id]
        else:
            session = self._sessions[session_id]

        raise gen.Return(session)
Example #20
0
def feature_scatterplot(fset_path, features_to_plot):
    """Create scatter plot of feature set.

    Parameters
    ----------
    fset_path : str
        Path to feature set to be plotted.
    features_to_plot : list of str
        List of feature names to be plotted.

    Returns
    -------
    (str, str)
        Returns (docs_json, render_items) json for the desired plot.
    """
    fset, data = featurize.load_featureset(fset_path)
    fset = fset[features_to_plot]
    colors = cycle(palette[5])
    plots = np.array([[figure(width=300, height=200)
                       for j in range(len(features_to_plot))]
                      for i in range(len(features_to_plot))])

    for (j, i), p in np.ndenumerate(plots):
        if (j == i == 0):
            p.title.text = "Scatterplot matrix"
        p.circle(fset.values[:,i], fset.values[:,j], color=next(colors))
        p.xaxis.minor_tick_line_color = None
        p.yaxis.minor_tick_line_color = None
        p.ygrid[0].ticker.desired_num_ticks = 2
        p.xgrid[0].ticker.desired_num_ticks = 4
        p.outline_line_color = None
        p.axis.visible = None

    plot = gridplot(plots.tolist(), ncol=len(features_to_plot), mergetools=True, responsive=True, title="Test")

    # Convert plot to json objects necessary for rendering with bokeh on the
    # frontend
    render_items = [{'docid': plot._id, 'elementid': make_id()}]

    doc = Document()
    doc.add_root(plot)
    docs_json_inner = doc.to_json()
    docs_json = {render_items[0]['docid']: docs_json_inner}

    docs_json = serialize_json(docs_json)
    render_items = serialize_json(render_items)

    return docs_json, render_items
Example #21
0
    def test_entire_doc_is_not_used(self):
        from bokeh.document import Document
        from bokeh.models import Button

        fig = figure()
        fig.x([0], [0])

        button = Button(label="Button")

        d = Document()
        d.add_root(fig)
        d.add_root(button)
        out = bes.file_html([fig], CDN)

        # this is a very coarse test but it will do
        assert "bokeh-widgets" not in out
Example #22
0
def compute_static_patch(document, models, json=None):
    """
    Computes a patch to update an existing document without
    diffing the json first, making it suitable for static updates
    between arbitrary frames. Note that this only supports changed
    attributes and will break if new models have been added since
    the plot was first created.
    """
    references = refs(json if json else document.to_json())
    requested_updates = [m.ref['id'] for m in models]

    value_refs = {}
    events = []
    update_types = defaultdict(list)
    for ref_id, obj in references.items():
        if ref_id not in requested_updates:
            continue
        if obj['type'] in MODEL_PRIORITY:
            priority = MODEL_PRIORITY.index(obj['type'])
        else:
            priority = float('inf')
        for key, val in obj['attributes'].items():
            event = Document._event_for_attribute_change(references,
                                                         obj, key, val,
                                                         value_refs)
            events.append((priority, event))
            update_types[obj['type']].append(key)
    events = [delete_refs(e, LOCATIONS, IGNORED_MODELS)
              for _, e in sorted(events, key=lambda x: x[0])]
    value_refs = {ref_id: delete_refs(val, LOCATIONS, IGNORED_MODELS)
                  for ref_id, val in value_refs.items()}
    references = [val for val in value_refs.values()
                  if val is not None]
    return dict(events=events, references=references)
Example #23
0
        def wrapper(*args, **kwargs):
            document = Document()
            session = Session(name=url, root_url=url)
            session.use_doc(document.docid)
            session.load_document(document)
            session.publish()
            document.autoadd = False
            document.autostore = False

            obj = func(*args, **kwargs)
            obj._docid = session.docid
            obj._root_url = session.root_url

            document.add(obj)
            session.store_document(document)
            return obj
Example #24
0
 def test_uses_precedent_from_child(self):
     doc = Document()
     p1 = Model()
     p2 = SomeModelInTestObjects(child=Model())
     doc.add_root(p2.child)
     self.assertIs(p1.document, None)
     self.assertIs(p2.document, None)
     self.assertIs(p2.child.document, doc)
     with _ModelInDocument([p1, p2]):
         self.assertIsNot(p1.document, None)
         self.assertIsNot(p2.document, None)
         self.assertIs(p1.document, doc)
         self.assertIs(p2.document, doc)
     self.assertIs(p1.document, None)
     self.assertIs(p2.document, None)
     self.assertIsNot(p2.child.document, None)
     self.assertIs(p2.child.document, doc)
Example #25
0
 def test_uses_precedent(self):
     # it's deliberate that the doc is on p2, so _ModelInDocument
     # has to be smart about looking for a doc anywhere in the list
     # before it starts inventing new documents
     doc = Document()
     p1 = Model()
     p2 = Model()
     doc.add_root(p2)
     self.assertIs(p1.document, None)
     self.assertIsNot(p2.document, None)
     with _ModelInDocument([p1, p2]):
         self.assertIsNot(p1.document, None)
         self.assertIsNot(p2.document, None)
         self.assertIs(p1.document, doc)
         self.assertIs(p2.document, doc)
     self.assertIs(p1.document, None)
     self.assertIsNot(p2.document, None)
    def test_document_on_session_destroyed_calls_multiple(self):
        doc = Document()

        def increment(session_context):
            session_context.counter += 1

        doc.on_session_destroyed(increment)

        def increment_by_two(session_context):
            session_context.counter += 2

        doc.on_session_destroyed(increment_by_two)

        handler = bahd.DocumentLifecycleHandler()
        session_context = MockSessionContext(doc)
        handler.on_session_destroyed(session_context)
        assert session_context.counter == 3, 'DocumentLifecycleHandler did not call all callbacks'
Example #27
0
 def test_uses_precedent(self):
     # it's deliberate that the doc is on p2, so _ModelInDocument
     # has to be smart about looking for a doc anywhere in the list
     # before it starts inventing new documents
     doc = Document()
     p1 = Model()
     p2 = Model()
     doc.add_root(p2)
     assert p1.document is None
     assert p2.document is not None
     with bes._ModelInDocument([p1, p2]):
         assert p1.document is not None
         assert p2.document is not None
         assert p1.document is doc
         assert p2.document is doc
     assert p1.document is None
     assert p2.document is not None
Example #28
0
    def test_compute_one_attribute_patch(self):
        from bokeh.document import Document

        d = Document()
        root1 = SomeModelInTestDocument(foo=42)
        child1 = SomeModelInTestDocument(foo=43)
        root1.child = child1
        d.add_root(root1)

        before = d.to_json()

        root1.foo = 47

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(references=[],
                        events=[
                            {'attr': u'foo',
                             'kind': 'ModelChanged',
                             'model': {'id': None,
                                       'type': 'SomeModelInTestDocument'},
                             'new': 47}
                        ])
        expected['events'][0]['model']['id'] = root1._id
        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual(root1.foo, d2.roots[0].foo)
Example #29
0
    def test_compute_one_attribute_patch(self):
        from bokeh.document import Document

        d = Document()
        root1 = SomeModelInTestDocument(foo=42)
        child1 = SomeModelInTestDocument(foo=43)
        root1.child = child1
        d.add_root(root1)

        before = d.to_json()

        root1.foo = 47

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(
            references=[],
            events=[
                {
                    "attr": u"foo",
                    "kind": "ModelChanged",
                    "model": {"id": None, "type": "SomeModelInTestDocument"},
                    "new": 47,
                }
            ],
        )
        expected["events"][0]["model"]["id"] = root1._id
        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual(root1.foo, d2.roots[0].foo)
Example #30
0
 def plot_code_iterator(self):
     """
     Iterator over the single bokeh plot
     :return: Tuple of js-script code for the plot and number of invalid
     values
     """
     for index, dummy in enumerate(self.__conf.filter_args):
         if self.__index is not None and self.__index != index:
             continue
         document = Document()
         document.title = self.__conf.description
         self.__factors, self.__values, num_invalid = \
             self.create_x_y_values(index)
         plot = self.__create_control_chart_hist(index)
         document.add_root(plot)
         session_id = self.__save_user_session(document, index)
         script = autoload_server(None, session_id=session_id)
         yield script, num_invalid
    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})
Example #32
0
    xaxis = CategoricalAxis()
    xaxis.major_label_text_font_size = "8pt"
    xaxis.major_label_standoff = 0
    xaxis.major_tick_line_color = None
    xaxis.axis_line_color = None
    plot.add_layout(xaxis, 'above')

    hover_tool = HoverTool(plot=plot,
                           renderers=[rect_renderer],
                           tooltips=[("Holiday", "@month_holidays")])
    plot.tools.append(hover_tool)

    return plot


months = [[make_calendar(2014, 3 * i + j + 1) for j in range(3)]
          for i in range(4)]
grid = gridplot(toolbar_location=None, children=months)

doc = Document()
doc.add_root(grid)

if __name__ == "__main__":
    doc.validate()
    filename = "calendars.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Calendar 2014"))
    print("Wrote %s" % filename)
    view(filename)
Example #33
0
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group])

document = Document()
document.add_root(vbox)
session = push_session(document)
session.show()

if __name__ == "__main__":
    session.loop_until_closed()
Example #34
0
def document():
    return Document()
Example #35
0
 def test_setting_built_in_theme_missing(self):
     obj = SomeModel()
     doc = Document()
     doc.add_root(obj)
     with pytest.raises(ValueError):
         doc.theme = 'some_theme_i_guess'
from math import sqrt, pi
import pandas as pd

from ldadata import data

from bokeh.models import ColumnDataSource, LinearAxis, CategoricalAxis, Plot, DataRange1d, FactorRange, GlyphRenderer, TapTool
from bokeh.models.glyphs import Circle, Text, Rect
from bokeh.models.widgets import TextInput, Button, Slider, HBox, VBox

from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.session import Session
from bokeh.browserlib import view

document = Document()
session = Session()
session.use_doc('ldavis_server')
session.load_document(document)

print("MDSPLOT")

R = data["R"]

mds = pd.DataFrame.from_dict(data["mdsDat"])
lam = pd.DataFrame.from_dict(data["tinfo"])

barDefault2 = lam[lam.Category == "Default"]

mdswidth = 530
mdsheight = 530
    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
Example #38
0
plot = Plot(title=None,
            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 = Ray(x="x",
            y="y",
            length="l",
            angle=-2.0,
            line_color="#fb8072",
            line_width=3)
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(plot)

show(plot)
Example #39
0
    line_source = ColumnDataSource(dict(
        x=data.dist,
        y=data.alt,
    ))

    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    plot.x_range = DataRange1d()
    plot.y_range = DataRange1d()

    return plot


data = prep_data(obiszow_mtb_xcm)

trail = trail_map(data)
altitude = altitude_profile(data)

layout = VBox(children=[altitude, trail])

doc = Document()
doc.add(layout)

if __name__ == "__main__":
    filename = "trail.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Trail map and altitude profile"))
    print("Wrote %s" % filename)
    view(filename)
Example #40
0
                  w="w1",
                  h="h1",
                  anchor="center",
                  global_alpha=0.2)
plot.add_glyph(source, image1)

image2 = ImageURL(url="url", x="x2", y="y2", w=20, h=20, anchor="top_left")
plot.add_glyph(source, image2)

image3 = ImageURL(url=dict(value=url), x=200, y=-100, anchor="bottom_right")
plot.add_glyph(source, image3)

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)

if __name__ == "__main__":
    filename = "image_url.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Image URL Example"))
    print("Wrote %s" % filename)
    view(filename)
Example #41
0
def test_doc_set():
    s = state.State()
    d = Document()
    s.document = d
    assert isinstance(s.document, Document)
    assert s.document == d
Example #42
0
 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 #43
0
    angle = half_tooth(planet_teeth)

    for i, j in [(+1, 0), (0, +1), (-1, 0), (0, -1)]:
        glyph = Gear(x=radius * i,
                     y=radius * j,
                     module=module,
                     teeth=planet_teeth,
                     angle=angle,
                     fill_color=fill_color[1],
                     line_color=line_color)
        plot.add_glyph(glyph)

    return plot


doc = Document()
doc.add_root(sample_gear())

classical = classical_gear(5, 52, 24)
epicyclic = epicyclic_gear(5, 24, 12)

doc.add_root(classical)
doc.add_root(epicyclic)

if __name__ == "__main__":
    filename = "gears.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Gears"))
    print("Wrote %s" % filename)
    view(filename)
Example #44
0
 def test_setting_built_in_theme_error(self):
     obj = SomeModel()
     doc = Document()
     doc.add_root(obj)
     with pytest.raises(ValueError):
         doc.theme = 1337
Example #45
0
def define_plot(
    doc: Document,
    rt_client: _StreamingClient,
    channels: list,
    tribe: RealTimeTribe,
    inventory: Inventory,
    detections: list,
    map_options: dict,
    plot_options: dict,
    plot_length: float,
    update_interval: int,
    data_color: str = "grey",
    lowcut: float = 1.0,
    highcut: float = 10.0,
    offline: bool = False,
):
    """
    Set up a bokeh plot for real-time plotting.

    Defines a moving data stream and a map.

    Parameters
    ----------
    doc
        Bokeh document to edit - usually called as a partial
    rt_client
        RealTimeClient streaming data
    channels
        Channels to plot
    tribe
        Tribe to plot
    inventory
        Inventory to plot
    detections
        Detections to plot - should be a list that is updated in place.
    map_options
        Dictionary of options for the map
    plot_options
        Dictionary of options for plotting in general
    plot_length
        Length of data plot
    update_interval
        Update frequency in seconds
    data_color
        Colour to data stream
    lowcut
        Lowcut for filtering data stream
    highcut
        Highcut for filtering data stream
    offline
        Flag to set time-stamps to data time-stamps if True, else timestamps
        will be real-time
    """
    # Set up the data source
    Logger.info("Getting stream to define plot")
    stream = rt_client.stream.copy().split().detrend()
    if lowcut and highcut:
        stream.filter("bandpass", freqmin=lowcut, freqmax=highcut)
        title = "Streaming data: {0}-{1} Hz bandpass".format(lowcut, highcut)
    elif lowcut:
        stream.filter("highpass", lowcut)
        title = "Streaming data: {0} Hz highpass".format(lowcut)
    elif highcut:
        stream.filter("lowpass", highcut)
        title = "Streaming data: {0} Hz lowpass".format(highcut)
    else:
        title = "Raw streaming data"
    stream.merge()
    Logger.info(f"Have the stream: \n{stream}")

    template_lats, template_lons, template_alphas, template_ids = (
        [], [], [], [])
    for template in tribe:
        try:
            origin = (template.event.preferred_origin() or
                      template.event.origins[0])
        except IndexError:
            continue
        template_lats.append(origin.latitude)
        template_lons.append(origin.longitude % 360)
        template_alphas.append(0)
        template_ids.append(template.event.resource_id.id.split("/")[-1])

    station_lats, station_lons, station_ids = ([], [], [])
    for network in inventory:
        for station in network:
            station_lats.append(station.latitude)
            station_lons.append(station.longitude % 360)
            station_ids.append(station.code)

    # Get plot bounds in web mercator
    Logger.info("Defining map")
    transformer = Transformer.from_crs(
        "epsg:4326", "epsg:3857", always_xy=True)
    try:
        min_lat, min_lon, max_lat, max_lon = (
            min(template_lats + station_lats),
            min(template_lons + station_lons),
            max(template_lats + station_lats),
            max(template_lons + station_lons))
    except ValueError as e:
        Logger.error(e)
        Logger.info("Setting map bounds to NZ")
        min_lat, min_lon, max_lat, max_lon = (-47., 165., -34., 179.9)
    Logger.info(f"Map bounds: {min_lon}, {min_lat} - {max_lon}, {max_lat}")
    bottom_left = transformer.transform(min_lon, min_lat)
    top_right = transformer.transform(max_lon, max_lat)
    map_x_range = (bottom_left[0], top_right[0])
    map_y_range = (bottom_left[1], top_right[1])

    template_x, template_y = ([], [])
    for lon, lat in zip(template_lons, template_lats):
        _x, _y = transformer.transform(lon, lat)
        template_x.append(_x)
        template_y.append(_y)

    station_x, station_y = ([], [])
    for lon, lat in zip(station_lons, station_lats):
        _x, _y = transformer.transform(lon, lat)
        station_x.append(_x)
        station_y.append(_y)

    template_source = ColumnDataSource({
        'y': template_y, 'x': template_x,
        'lats': template_lats, 'lons': template_lons,
        'template_alphas': template_alphas, 'id': template_ids})
    station_source = ColumnDataSource({
        'y': station_y, 'x': station_x,
        'lats': station_lats, 'lons': station_lons, 'id': station_ids})

    Logger.info("Allocated data sources")
    trace_sources = {}
    trace_data_range = {}
    # Allocate empty arrays
    for channel in channels:
        tr = stream.select(id=channel)[0]
        times = np.arange(
            tr.stats.starttime.datetime,
            (tr.stats.endtime + tr.stats.delta).datetime,
            step=dt.timedelta(seconds=tr.stats.delta))
        data = tr.data
        trace_sources.update(
            {channel: ColumnDataSource({'time': times, 'data': data})})
        trace_data_range.update({channel: (data.min(), data.max())})

    # Set up the map to go on the left side
    Logger.info("Adding features to map")
    map_plot = figure(
        title="Template map", x_range=map_x_range, y_range=map_y_range,
        x_axis_type="mercator", y_axis_type="mercator", **map_options)
    url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png'
    attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL"
    map_plot.add_tile(WMTSTileSource(url=url, attribution=attribution))
    map_plot.circle(
        x="x", y="y", source=template_source, fill_color="firebrick",
        line_color="grey", line_alpha=.2,
        fill_alpha="template_alphas", size=10)
    map_plot.triangle(
        x="x", y="y", size=10, source=station_source, color="blue", alpha=1.0)

    # Set up the trace plots
    Logger.info("Setting up streaming plot")
    trace_plots = []
    if not offline:
        now = dt.datetime.utcnow()
    else:
        now = max([tr.stats.endtime for tr in stream]).datetime
    p1 = figure(
        y_axis_location="right", title=title,
        x_range=[now - dt.timedelta(seconds=plot_length), now],
        plot_height=int(plot_options["plot_height"] * 1.2),
        **{key: value for key, value in plot_options.items()
           if key != "plot_height"})
    p1.yaxis.axis_label = None
    p1.xaxis.axis_label = None
    p1.min_border_bottom = 0
    p1.min_border_top = 0
    if len(channels) != 1:
        p1.xaxis.major_label_text_font_size = '0pt'
    p1_line = p1.line(
        x="time", y='data', source=trace_sources[channels[0]],
        color=data_color, line_width=1)
    legend = Legend(items=[(channels[0], [p1_line])])
    p1.add_layout(legend, 'right')

    datetick_formatter = DatetimeTickFormatter(
        days=["%m/%d"], months=["%m/%d"],
        hours=["%m/%d %H:%M:%S"], minutes=["%m/%d %H:%M:%S"],
        seconds=["%m/%d %H:%M:%S"], hourmin=["%m/%d %H:%M:%S"],
        minsec=["%m/%d %H:%M:%S"])
    p1.xaxis.formatter = datetick_formatter

    # Add detection lines
    Logger.info("Adding detection artists")
    detection_source = _get_pick_times(detections, channels[0])
    detection_source.update(
        {"pick_values": [[
            int(min(stream.select(id=channels[0])[0].data) * .9),
            int(max(stream.select(id=channels[0])[0].data) * .9)]
            for _ in detection_source['picks']]})
    detection_sources = {channels[0]: ColumnDataSource(detection_source)}
    detection_lines = MultiLine(
        xs="picks", ys="pick_values", line_color="red", line_dash="dashed",
        line_width=1)
    p1.add_glyph(detection_sources[channels[0]], detection_lines)

    trace_plots.append(p1)

    if len(channels) > 1:
        for i, channel in enumerate(channels[1:]):
            p = figure(
                x_range=p1.x_range,
                y_axis_location="right", **plot_options)
            p.yaxis.axis_label = None
            p.xaxis.axis_label = None
            p.min_border_bottom = 0
            # p.min_border_top = 0
            p_line = p.line(
                x="time", y="data", source=trace_sources[channel],
                color=data_color, line_width=1)
            legend = Legend(items=[(channel, [p_line])])
            p.add_layout(legend, 'right')
            p.xaxis.formatter = datetick_formatter

            # Add detection lines
            detection_source = _get_pick_times(detections, channel)
            detection_source.update(
                {"pick_values": [[
                    int(min(stream.select(id=channel)[0].data) * .9),
                    int(max(stream.select(id=channel)[0].data) * .9)]
                    for _ in detection_source['picks']]})
            detection_sources.update({
                channel: ColumnDataSource(detection_source)})
            detection_lines = MultiLine(
                xs="picks", ys="pick_values", line_color="red",
                line_dash="dashed", line_width=1)
            p.add_glyph(detection_sources[channel], detection_lines)

            trace_plots.append(p)
            if i != len(channels) - 2:
                p.xaxis.major_label_text_font_size = '0pt'
    plots = gridplot([[map_plot, column(trace_plots)]])

    previous_timestamps = {
        channel: stream.select(id=channel)[0].stats.endtime
        for channel in channels}
    
    def update():
        Logger.debug("Plot updating")
        _stream = rt_client.stream.split().detrend()
        if lowcut and highcut:
            _stream.filter("bandpass", freqmin=lowcut, freqmax=highcut)
        elif lowcut:
            _stream.filter("highpass", lowcut)
        elif highcut:
            _stream.filter("lowpass", highcut)
        _stream.merge()

        for _i, _channel in enumerate(channels):
            try:
                _tr = _stream.select(id=_channel)[0]
            except IndexError:
                Logger.debug("No channel for {0}".format(_channel))
                continue
            new_samples = int(_tr.stats.sampling_rate * (
                    previous_timestamps[_channel] - _tr.stats.endtime))
            if new_samples == 0:
                Logger.debug("No new data for {0}".format(_channel))
                continue
            _new_data = _tr.slice(
                starttime=previous_timestamps[_channel])
            new_times = np.arange(
                _new_data.stats.starttime.datetime,
                (_tr.stats.endtime + _tr.stats.delta).datetime,
                step=dt.timedelta(seconds=_tr.stats.delta))
            new_data = {'time': new_times[1:], 'data': _new_data.data[1:]}
            Logger.debug("Channl: {0}\tNew times: {1}\t New data: {2}".format(
                _tr.id, new_data["time"].shape, new_data["data"].shape))
            trace_sources[_channel].stream(
                new_data=new_data,
                rollover=int(plot_length * _tr.stats.sampling_rate))
            new_picks = _get_pick_times(detections, _channel)
            new_picks.update({
                'pick_values': [
                    [int(np.nan_to_num(
                        trace_sources[_channel].data['data']).max() * .9),
                     int(np.nan_to_num(
                         trace_sources[_channel].data['data']).min() * .9)]
                    for _ in new_picks['picks']]})
            detection_sources[_channel].data = new_picks
            previous_timestamps.update({_channel: _tr.stats.endtime})
            Logger.debug("New data plotted for {0}".format(_channel))
        if not offline:
            now = dt.datetime.utcnow()
        else:
            try:
                now = max([tr.stats.endtime for tr in _stream]).datetime
            except ValueError:
                return
        trace_plots[0].x_range.start = now - dt.timedelta(seconds=plot_length)
        trace_plots[0].x_range.end = now
        _update_template_alphas(
            detections, tribe, decay=plot_length, now=now,
            datastream=template_source)
    Logger.info("Adding callback")
    doc.add_periodic_callback(update, update_interval)
    doc.title = "EQcorrscan Real-time plotter"
    doc.add_root(plots)
    Logger.info("Plot defined")
Example #46
0
    data=dict(
        lat=df['Latitude'],
        lon=df['Longitude'],
    )
)

circle = Circle(x="lon", y="lat", size=5, fill_alpha=0.5, fill_color="magenta", line_alpha=0.3, line_color="black")
plot.add_glyph(source, circle)

slider = Slider(start=0, end=6, value=1, step=1, title="Weekdays")

pan = PanTool()
wheel_zoom = WheelZoomTool()
box_select = BoxSelectTool()

plot.add_tools(pan, wheel_zoom, box_select)
overlay = BoxSelectionOverlay(tool=box_select)
plot.add_layout(overlay)

# layout = vform(slider, plot)

doc = Document()
# doc.add(slider)
doc.add(plot, slider)

if __name__ == "__main__":
    filename = "maps.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Google Maps Example"))
    print("Wrote %s" % filename)
    view(filename)
Example #47
0
 def _doc_modifier(doc: Document) -> None:
     grid = _create_ui_components()
     doc.add_root(grid)
Example #48
0
        plot.add_glyph(text_source, text)

    return plot


xattrs = ["petal_length", "petal_width", "sepal_width", "sepal_length"]
yattrs = list(reversed(xattrs))
plots = []

for y in yattrs:
    row = []
    for x in xattrs:
        xax = (y == yattrs[-1])
        yax = (x == xattrs[0])
        text = x if (x == y) else None
        plot = make_plot(x, y, xax, yax, text)
        row.append(plot)
    plots.append(row)

grid = GridPlot(children=plots)

doc = Document()
doc.add_root(grid)

if __name__ == "__main__":
    filename = "iris_splom.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Iris Data SPLOM"))
    print("Wrote %s" % filename)
    view(filename)
Example #49
0
    CategoricalAxis(axis_label='Date',
                    major_label_orientation=pi / 2,
                    **axis_defaults), 'below')

bk_page.children = [
    Div(text=bk_section0_text, sizing_mode='scale_both'),
    Div(text=bk_section1_text1, sizing_mode='scale_both'),
    plot_kf,
    Div(text=bk_section1_text2, sizing_mode='scale_both'),
    plot_kc,
    Div(text=bk_section1_text3, sizing_mode='scale_both'),
    plot_sc,
    Div(text=bk_section1_text4, sizing_mode='scale_both'),
    plot_dc,
    Div(text=bk_section2_text1, sizing_mode='scale_both'),
    pop_dt,
    Div(text=bk_section3_text1, sizing_mode='scale_both'),
    Div(text=bk_section3_text2, sizing_mode='scale_both'),
    Div(text=bk_section3_text3, sizing_mode='scale_both'),
    plot_tm,
    Div(text=bk_section3_text4, sizing_mode='scale_both'),
]

doc = Document()
doc.add_root(bk_page)
doc.validate()
filename = 'index.html'
with open(filename, "w") as f:
    f.write(file_html(doc, INLINE, "New York Times - Climate Change"))
view(filename)
Example #50
0
        )
        plot.add_glyph(text_source, text)

    return plot

xattrs = ["petal_length", "petal_width", "sepal_width", "sepal_length"]
yattrs = list(reversed(xattrs))
plots = []

for y in yattrs:
    row = []
    for x in xattrs:
        xax = (y == yattrs[-1])
        yax = (x == xattrs[0])
        text = x if (x==y) else None
        plot = make_plot(x, y, xax, yax, text)
        row.append(plot)
    plots.append(row)

grid = GridPlot(children=plots, title="iris_splom")

doc = Document()
doc.add(grid)

if __name__ == "__main__":
    filename = "iris_splom.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Iris Data SPLOM"))
    print("Wrote %s" % filename)
    view(filename)
Example #51
0
class DataTables(object):

    def __init__(self):
        self.document = Document()
        self.manufacturer_filter = None
        self.model_filter = None
        self.transmission_filter = None
        self.drive_filter = None
        self.class_filter = None

        self.source = ColumnDataSource()
        self.update_data()

        self.document.add_root((self.create()))
        self.session = push_session(self.document)

    def create(self):
        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())

        manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:", value="All", options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:", value="All", options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:", value="All", options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        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=self.source, columns=columns, editable=True)

        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(self.source, cty_glyph)
        hwy = plot.add_glyph(self.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)


        controls = VBox(children=[
            manufacturer_select, model_select, transmission_select,
             drive_select, class_select])
        top_panel = HBox(children=[controls, plot])
        layout = VBox(children=[top_panel, data_table])

        return layout

    def on_manufacturer_change(self, attr, _, value):
        self.manufacturer_filter = None if value == "All" else value
        self.update_data()

    def on_model_change(self, attr, _, value):
        self.model_filter = None if value == "All" else value
        self.update_data()

    def on_transmission_change(self, attr, _, value):
        self.transmission_filter = None if value == "All" else value
        self.update_data()

    def on_drive_change(self, attr, _, value):
        self.drive_filter = None if value == "All" else value
        self.update_data()

    def on_class_change(self, attr, _, value):
        self.class_filter = None if value == "All" else value
        self.update_data()

    def update_data(self):
        df = mpg
        if self.manufacturer_filter:
            df = df[df["manufacturer"] == self.manufacturer_filter]
        if self.model_filter:
            df = df[df["model"] == self.model_filter]
        if self.transmission_filter:
            df = df[df["trans"] == self.transmission_filter]
        if self.drive_filter:
            df = df[df["drv"] == self.drive_filter]
        if self.class_filter:
            df = df[df["class"] == self.class_filter]
        self.source.data = ColumnDataSource.from_df(df)

    def run(self, do_view=False, poll_interval=0.5):
        if do_view:
            self.session.show()

        self.session.loop_until_closed()
Example #52
0
class Population(object):

    year = 2010
    location = "World"

    def __init__(self):
        from bokeh.models import ColumnDataSource
        from bokeh.document import Document
        from bokeh.session import Session
        from bokeh.sampledata.population import load_population

        self.document = Document()
        self.session = Session()
        self.session.use_doc('population_reveal')
        self.session.load_document(self.document)

        self.df = load_population()
        self.source_pyramid = ColumnDataSource(data=dict())

        # just render at the initialization
        self._render()

    def _render(self):
        self.pyramid_plot()
        self.create_layout()
        self.document.add(self.layout)
        self.update_pyramid()

    def pyramid_plot(self):
        from bokeh.models import (Plot, DataRange1d, LinearAxis, Grid,
                                  Legend, SingleIntervalTicker)
        from bokeh.models.glyphs import Quad

        xdr = DataRange1d(sources=[self.source_pyramid.columns("male"),
                                   self.source_pyramid.columns("female")])
        ydr = DataRange1d(sources=[self.source_pyramid.columns("groups")])

        self.plot = Plot(title="Widgets", x_range=xdr, y_range=ydr,
                         plot_width=600, plot_height=600)

        xaxis = LinearAxis()
        self.plot.add_layout(xaxis, 'below')
        yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5))
        self.plot.add_layout(yaxis, 'left')

        self.plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
        self.plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        male_quad = Quad(left="male", right=0, bottom="groups", top="shifted",
                         fill_color="#3B8686")
        male_quad_glyph = self.plot.add_glyph(self.source_pyramid, male_quad)

        female_quad = Quad(left=0, right="female", bottom="groups", top="shifted",
                           fill_color="#CFF09E")
        female_quad_glyph = self.plot.add_glyph(self.source_pyramid, female_quad)

        self.plot.add_layout(Legend(legends=dict(Male=[male_quad_glyph],
                                                 Female=[female_quad_glyph])))

    def on_year_change(self, obj, attr, old, new):
        self.year = int(new)
        self.update_pyramid()

    def on_location_change(self, obj, attr, old, new):
        self.location = new
        self.update_pyramid()

    def create_layout(self):
        from bokeh.models.widgets import Select, HBox, VBox

        years = list(map(str, sorted(self.df.Year.unique())))
        locations = sorted(self.df.Location.unique())

        year_select = Select(title="Year:", value="2010", options=years)
        location_select = Select(title="Location:", value="World", options=locations)

        year_select.on_change('value', self.on_year_change)
        location_select.on_change('value', self.on_location_change)

        controls = HBox(year_select, location_select)
        self.layout = VBox(controls, self.plot)

    def update_pyramid(self):
        pyramid = self.df[(self.df.Location == self.location) & (self.df.Year == self.year)]

        male = pyramid[pyramid.Sex == "Male"]
        female = pyramid[pyramid.Sex == "Female"]

        total = male.Value.sum() + female.Value.sum()

        male_percent = -male.Value / total
        female_percent = female.Value / total

        groups = male.AgeGrpStart.tolist()
        shifted = groups[1:] + [groups[-1] + 5]

        self.source_pyramid.data = dict(
            groups=groups,
            shifted=shifted,
            male=male_percent,
            female=female_percent,
        )
        self.session.store_document(self.document)
Example #53
0
from __future__ import print_function

from numpy import pi, arange, sin, cos

from bokeh.browserlib 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"
)
Example #54
0
from bokeh.session import Session
from bokeh.widgets import (
    VBox,
    HBox,
    Paragraph,
    Icon,
    Button,
    Toggle,
    Dropdown,
    CheckboxGroup,
    RadioGroup,
    CheckboxButtonGroup,
    RadioButtonGroup,
)

document = Document()
session = Session()
session.use_doc('buttons_server')
session.load_document(document)


def button_handler():
    print("button_handler: click")
    session.store_document(document)


def toggle_handler(active):
    print("toggle_handler: %s" % active)
    session.store_document(document)

Example #55
0
from __future__ import print_function

import numpy as np
import sympy as sy

from bokeh.client import push_session
from bokeh.document import Document
from bokeh.models.glyphs import Line
from bokeh.models import Plot, Range1d, LinearAxis, ColumnDataSource, Grid, Legend
from bokeh.models.widgets import Slider, TextInput, Dialog
from bokeh.models.layouts import WidgetBox, Column

document = Document()
session = push_session(document)

xs = sy.Symbol('x')
expr = sy.exp(-xs) * sy.sin(xs)
order = 1


def taylor(fx, xs, order, x_range=(0, 1), n=200):
    x0, x1 = x_range
    x = np.linspace(float(x0), float(x1), n)

    fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
    tx = fx.series(xs, n=order).removeO()

    if tx.is_Number:
        ty = np.zeros_like(x)
        ty.fill(float(tx))
    else:
Example #56
0
from __future__ import print_function

import numpy as np

from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid, Circle, VBox, HBox, Button, TapTool
from bokeh.document import Document
from bokeh.session import Session
from bokeh.browserlib import view

document = Document()
session = Session()
session.use_doc('linked_tap_server')
session.load_document(document)

N = 9

x = np.linspace(-2, 2, N)
y = x**2

source1 = ColumnDataSource(dict(x=x, y=y, size=[20] * N))
xdr1 = DataRange1d()
ydr1 = DataRange1d()
plot1 = Plot(title="Plot1",
             x_range=xdr1,
             y_range=ydr1,
             plot_width=400,
             plot_height=400)
plot1.tools.append(TapTool(plot=plot1))
plot1.add_glyph(source1, Circle(x="x", y="y", size="size", fill_color="red"))

source2 = ColumnDataSource(dict(x=x, y=y, color=["blue"] * N))
Example #57
0
    http://localhost:8000/widget.html

"""
from __future__ import print_function

from numpy import pi

from bokeh.document import Document
from bokeh.client import push_session
from bokeh.embed import autoload_server
from bokeh.models import (Plot, DataRange1d, LinearAxis, CategoricalAxis,
                          Legend, HBox, VBox, ColumnDataSource, Grid, Line,
                          SingleIntervalTicker, Quad, Select, FactorRange)
from bokeh.sampledata.population import load_population

document = Document()

session = push_session(document)

df = load_population()
revision = 2012

year = 2010
location = "World"

years = [str(x) for x in sorted(df.Year.unique())]
locations = sorted(df.Location.unique())

source_pyramid = ColumnDataSource(data=dict())

Example #58
0
    plot.add_layout(
        Label(x=500,
              y=320,
              x_units='screen',
              y_units='screen',
              text='Replace GOOGLE_API_KEY with your own key',
              text_color='red',
              text_align='center'))

plot.title.text = "Cities of the world with a population over 5,000 people."

circle = Circle(x="lng",
                y="lat",
                size=5,
                line_color=None,
                fill_color='firebrick',
                fill_alpha=0.2)
plot.add_glyph(ColumnDataSource(data), circle)
plot.add_tools(PanTool(), WheelZoomTool())

doc = Document()
doc.add_root(plot)

if __name__ == "__main__":
    doc.validate()
    filename = "maps_cities.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Google Maps - World cities Example"))
    print("Wrote %s" % filename)
    view(filename)
Example #59
0
            text_area,
            select,
            multi_select,
            multi_choice,
            slider,
            range_slider,
            date_slider,
            date_range_slider,
            spinner,
            color_picker,
            date_picker,
            paragraph,
            div,
            pre_text,
        ]),
        tabs,
    ]),
    table,
])

doc = Document()
doc.add_root(widgets)

if __name__ == "__main__":
    doc.validate()
    filename = "widgets.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Widgets"))
    print("Wrote %s" % filename)
    view(filename)
Example #60
0
    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    plot.add_tools(HoverTool())

    tab = Panel(child=plot, title=title, closable=True)

    return tab


def make_tabs(objs):
    return Tabs(tabs=[make_tab(title, obj) for title, obj in objs], width=600)


layout = Column(children=[
    Paragraph(text="Only Image and ImageRGBA glyphs are not demonstrated."),
    make_tabs(glyphs),
    make_tabs(markers)
])

doc = Document()
doc.add_root(layout)

if __name__ == "__main__":
    doc.validate()
    filename = "glyphs.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Glyphs"))
    print("Wrote %s" % filename)
    view(filename)