Example #1
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 #2
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 #3
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
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #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_compute_two_attribute_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()

        root1.foo = 47
        child1.bar = 57

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(
            references=[],
            events=[
                {
                    "attr": u"bar",
                    "kind": "ModelChanged",
                    "model": {"id": None, "type": "AnotherModelInTestDocument"},
                    "new": 57,
                },
                {
                    "attr": u"foo",
                    "kind": "ModelChanged",
                    "model": {"id": None, "type": "SomeModelInTestDocument"},
                    "new": 47,
                },
            ],
        )
        expected["events"][0]["model"]["id"] = child1._id
        expected["events"][1]["model"]["id"] = root1._id

        # order is undefined, so fix our expectation if needed
        self.assertEqual(2, len(patch["events"]))
        if patch["events"][0]["model"]["type"] == "AnotherModelInTestDocument":
            pass
        else:
            tmp = expected["events"][0]
            expected["events"][0] = expected["events"][1]
            expected["events"][1] = tmp

        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual(root1.foo, d2.roots[0].foo)
        self.assertEqual(root1.child.bar, d2.roots[0].child.bar)
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
Example #15
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 #16
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 #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 test_compute_two_attribute_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()

        root1.foo=47
        child1.bar=57

        after = d.to_json()

        patch = Document._compute_patch_between_json(before, after)

        expected = dict(references=[],
                        events=[
                            {'attr': u'bar',
                             'kind': 'ModelChanged',
                             'model': {'id': None,
                                       'type': 'AnotherModelInTestDocument'},
                             'new': 57},
                            {'attr': u'foo',
                             'kind': 'ModelChanged',
                             'model': {'id': None,
                                       'type': 'SomeModelInTestDocument'},
                             'new': 47}
                            ])
        expected['events'][0]['model']['id'] = child1._id
        expected['events'][1]['model']['id'] = root1._id

        # order is undefined, so fix our expectation if needed
        self.assertEqual(2, len(patch['events']))
        if patch['events'][0]['model']['type'] == 'AnotherModelInTestDocument':
            pass
        else:
            tmp = expected['events'][0]
            expected['events'][0] = expected['events'][1]
            expected['events'][1] = tmp

        self.assertDictEqual(expected, patch)

        d2 = Document.from_json(before)
        d2.apply_json_patch(patch)
        self.assertEqual(root1.foo, d2.roots[0].foo)
        self.assertEqual(root1.child.bar, d2.roots[0].child.bar)
Example #19
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 #20
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 #21
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 #22
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 #23
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)
Example #24
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 #25
0
        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
            now = datetime.now()
            env = Environment(loader=PackageLoader('btplotting', 'templates'))
            templ = env.get_template(self._html_template)
            templ.globals['now'] = now.strftime('%Y-%m-%d %H:%M:%S')
            doc.template = templ
            doc.template_variables['stylesheet'] = generate_stylesheet(
                self._scheme)
            model = self._model_factory_fnc(doc)
            doc.add_root(model)
Example #26
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 #27
0
    def test_get_one_by_name(self) -> None:
        d = Document()
        dm = d.models
        assert len(dm) == 0

        m1 = Div(name="foo")
        m2 = Div(name="foo")
        m3 = Div(name="bar")

        d.add_root(m1)
        d.add_root(m2)
        d.add_root(m3)

        with pytest.raises(ValueError):
            dm.get_one_by_name("foo")
        assert dm.get_one_by_name("bar") is m3
        assert dm.get_one_by_name("baz") is None
Example #28
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)
Example #29
0
        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)
Example #30
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 #31
0
    def modify_document(self, doc: Document) -> None:
        plots = []
        line_renderers = []  # type: List
        for watchers in self._line_watchers:
            plot = figure(plot_width=350,
                          plot_height=350,
                          x_axis_label='time',
                          x_axis_type='datetime',
                          y_axis_label='value')
            for i, line_watcher in enumerate(watchers):
                data_source = line_watcher.make_data_source()
                plot.step('time',
                          'value',
                          source=data_source,
                          mode='after',
                          legend=line_watcher.sensor.name,
                          color=PALETTE[i])
            plot.legend.location = 'top_left'
            plots.append(plot)
            line_renderers.extend(plot.x_range.renderers)
        # Create a single data range so that all line plots show the same time window
        data_range = DataRange1d()
        data_range.renderers = line_renderers
        data_range.follow = 'end'
        data_range.default_span = timedelta(seconds=1)
        data_range.follow_interval = timedelta(seconds=120)
        for plot in plots:
            plot.x_range = data_range

        for histogram_watcher in self._histogram_watchers:
            plot = figure(plot_width=350,
                          plot_height=350,
                          x_axis_label=histogram_watcher.sensor.name,
                          y_axis_label='frequency')
            data_source = histogram_watcher.make_data_source()
            plot.quad(top='top',
                      bottom='bottom',
                      left='left',
                      right='right',
                      source=data_source)
            plots.append(plot)

        doc.add_root(gridplot(plots, ncols=3))
        logger.debug('Created document with %d plots', len(plots))
        self._docs.add(doc)
Example #32
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 test_compute_add_root_patch():
    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 = bdu.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

    assert expected == patch

    d2 = Document.from_json(before)
    d2.apply_json_patch(patch)
    assert len(d2.roots) == 2
    assert d2.roots[0].foo == 42
    assert d2.roots[1].foo == 57
Example #34
0
    def test_theming_a_document_before_adding_root(self) -> None:
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        assert 'hello' == obj.string
        doc.theme = theme
        assert doc.theme is theme
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.add_root(obj)
        assert 'w00t' == obj.string
        doc.remove_root(obj)
        assert 'hello' == obj.string
        assert [('string', 'hello', 'w00t'),
                ('string', 'w00t', 'hello')] == changes['calls']
Example #35
0
def modify_doc(doc: Document):
    source = ColumnDataSource(data=data_holder.get_data())

    _keys = data_holder.get_keys()
    plot = figure(plot_height=600,
                  plot_width=1200,
                  title='Sequence Diagram',
                  x_axis_type='datetime',
                  y_range=_keys,
                  tools="xwheel_zoom,xpan,box_zoom,hover,reset",
                  active_scroll="xwheel_zoom",
                  active_drag="xpan")

    glyph = HBar(y="who",
                 left="t_start_ms",
                 right="t_end_ms",
                 height=0.4,
                 fill_color="green",
                 fill_alpha=0.2)
    plot.add_glyph(source, glyph)

    labels = LabelSet(x="t_start_ms",
                      y="who",
                      text="func",
                      text_font_size="8pt",
                      source=source,
                      text_align='left')
    plot.add_layout(labels)

    plot.hover.tooltips = [
        ("func", "@func"),
        ("in", "@in"),
        ("out", "@out"),
        # ("msg", "@msg"),
    ]

    def callback():
        #source.stream(new_data=data_holder.get_data(), rollover=1000) # todo: how to use stream
        source.data = ColumnDataSource(data=data_holder.get_data()).data

    doc.add_periodic_callback(callback, 1000)

    doc.add_root(plot)
Example #36
0
    def test_theming_a_document_before_adding_root(self):
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        self.assertEqual('hello', obj.string)
        doc.theme = theme
        self.assertIs(doc.theme, theme)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.add_root(obj)
        self.assertEqual('w00t', obj.string)
        doc.remove_root(obj)
        self.assertEqual('hello', obj.string)
        self.assertEqual([('string', 'hello', 'w00t'),
                          ('string', 'w00t', 'hello')], changes['calls'])
Example #37
0
    def test_setting_document_theme_to_none(self):
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        doc.add_root(obj)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.theme = theme
        self.assertEqual('w00t', obj.string)
        # setting to None reverts to default theme
        doc.theme = None
        self.assertIsNot(doc.theme, None)
        self.assertEqual('hello', obj.string)
        self.assertEqual([('string', 'hello', 'w00t'),
                          ('string', 'w00t', 'hello')], changes['calls'])
Example #38
0
    def test_len(self) -> None:
        d = Document()
        dm = d.models
        assert len(dm) == 0

        r1 = Row(children=[Div()])
        r2 = Row(children=[Div(), Div()])

        d.add_root(r1)
        assert len(dm) == 2

        d.add_root(r2)
        assert len(dm) == 5

        d.remove_root(r1)
        assert len(dm) == 3

        d.remove_root(r2)
        assert len(dm) == 0
Example #39
0
 def figure_data(self, plot, fmt='html', doc=None, **kwargs):
     model = plot.state
     doc = Document() if doc is None else doc
     for m in model.references():
         m._document = None
     doc.add_root(model)
     comm_id = plot.comm.id if plot.comm else None
     # Bokeh raises warnings about duplicate tools and empty subplots
     # but at the holoviews level these are not issues
     logger = logging.getLogger(bokeh.core.validation.check.__file__)
     logger.disabled = True
     try:
         div = notebook_div(model, comm_id)
     except:
         logger.disabled = False
         raise
     logger.disabled = False
     plot.document = doc
     return div
def dco_intergrate(sorted_group_dict_top):
    # 构建图表数据结构。 按照每行两个图(1个线上,1个线下)的结构去存储。
    plot_list = []
    for x in sorted_group_dict_top:
        #     print(x)
        data = x[1]
        p1, p2 = make_plot(data)
        plot_list.append([p1, p2])

    grid = gridplot(plot_list, toolbar_location=None)
    div = Div(text="""
    <h1>Data review tools</h1>
    <p>快速审阅数据的整体情况。</p>
    <p>左边是线上数据,右边是原始数据。</p>
    """)

    doc = Document()
    doc.add_root(column(div, grid, sizing_mode="scale_width"))
    return doc
Example #41
0
    def test_setting_document_theme_to_none(self) -> None:
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        doc.add_root(obj)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.theme = theme
        assert 'w00t' == obj.string
        # setting to None reverts to default theme
        doc.theme = None
        assert doc.theme is not None
        assert 'hello' == obj.string
        assert [('string', 'hello', 'w00t'),
                ('string', 'w00t', 'hello')] == changes['calls']
Example #42
0
class BokehDocument(InstancesMixin):
    def __init__(self, title='Live Trending'):
        self.document = Document(title=title)
        self.plots = []
        logging.getLogger("requests").setLevel(logging.INFO)
        logging.getLogger("bokeh").setLevel(logging.INFO)

    def add_plot(self, new_plot, linked_x_axis=True):
        self.document.clear()
        new_plot.x_range.bounds = None
        new_plot.y_range.bounds = None
        for key, plot in enumerate(self.plots):
            if new_plot.title == plot.title:
                self.plots.pop(key)
                self.plots.append(new_plot)
                break
        else:
            self.plots.append(new_plot)
        if linked_x_axis:
            for plot in self.plots[1:]:
                plot.x_range = self.plots[0].x_range
                plot.x_range.bounds = None
                plot.y_range.bounds = None

        if len(self.plots) > 1:
            number_of_rows = int(round(len(self.plots) / 2))
            rows = []
            number_of_columns = 2
            i = 0
            for each in range(number_of_rows):
                rows.append(
                    list(plot for plot in self.plots[i:i + number_of_columns]))
                i += number_of_columns
            layout = gridplot(rows)
        else:
            print('Layout...')
            layout = VBox(children=self.plots)

        self.document.add_root(layout)

    def add_periodic_callback(self, cb, update=100):
        self.document.add_periodic_callback(cb, update)
Example #43
0
def sea_surface_handler(doc: Document) -> None:
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type="datetime", y_range=(0, 25), y_axis_label="Temperature (Celsius)",
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line("time", "temperature", source=source)

    def callback(attr: str, old: Any, new: Any) -> None:
        if new == 0:
            data = df
        else:
            data = df.rolling(f"{new}D").mean()
        source.data = dict(ColumnDataSource(data=data).data)

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change("value", callback)

    doc.theme = theme
    doc.add_root(column(slider, plot))
Example #44
0
 def test_with_plaintext(self, test_plot, test_glplot, test_table, test_widget, test_mathtext, test_plaintext) -> None:
     assert beb._use_mathjax([test_plaintext]) is False
     assert beb._use_mathjax([test_plot, test_plaintext]) is False
     assert beb._use_mathjax([test_plot, test_glplot, test_plaintext]) is False
     assert beb._use_mathjax([test_plot, test_widget, test_plaintext]) is False
     assert beb._use_mathjax([test_plot, test_widget, test_table, test_plaintext]) is False
     assert beb._use_mathjax([test_plot, test_mathtext, test_plaintext]) is True
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_table)
     d.add_root(test_widget)
     d.add_root(test_plaintext)
     assert beb._use_mathjax([d]) is False
Example #45
0
def splom(data_csv):
    # read csv
    colors = []  # 0 for original, 1 for aug
    scores = []
    with open(data_csv, newline='') as csvfile:
        datareader = csv.reader(csvfile)
        index = 0
        for row in datareader:
            if "Generated" in row[0]:
                colors.append('red')
            else:
                colors.append('blue')
            scores.append(row[2:])
    scores = np.array(scores)

    # make splom
    plots = []
    for y in range(len(scores[0])):
        row = []
        for x in range(len(scores[0])):
            xax = (y == len(scores[0]) - 1)
            yax = (x == 0)
            xscores = [float(item) for item in list(scores[:, x])]
            yscores = [float(item) for item in list(scores[:, y])]
            source = ColumnDataSource(dict(x=xscores, y=yscores,
                                           colors=colors))
            plot = make_plot(source, x, y, xax, yax)
            row.append(plot)
        plots.append(row)

    grid = gridplot(plots)

    doc = Document()
    doc.add_root(grid)

    doc.validate()
    filename = "augmentation_splom.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Data SPLOM"))
    print("Wrote %s" % filename)
    view(filename)
Example #46
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 #47
0
class BokehDocument(InstancesMixin):
    def __init__(self, title = 'Live Trending'):
        self.document = Document(title = title)
        self.plots = []
        logging.getLogger("requests").setLevel(logging.INFO)
        logging.getLogger("bokeh").setLevel(logging.INFO)
        
    def add_plot(self, new_plot, linked_x_axis = True):
        self.document.clear()
        new_plot.x_range.bounds = None
        new_plot.y_range.bounds = None
        for key, plot in enumerate(self.plots):
            if new_plot.title == plot.title:
                self.plots.pop(key)
                self.plots.append(new_plot)
                break
        else:
            self.plots.append(new_plot)
        if linked_x_axis:
            for plot in self.plots[1:]:
                plot.x_range = self.plots[0].x_range
                plot.x_range.bounds = None
                plot.y_range.bounds = None
                
        if len(self.plots) > 1:
            number_of_rows = int(round(len(self.plots) / 2))
            rows = []
            number_of_columns = 2
            i = 0
            for each in range(number_of_rows):
                rows.append(list(plot for plot in self.plots[i:i+number_of_columns]))
                i += number_of_columns
            layout = gridplot(rows)
        else:
            print('Layout...')
            layout = VBox(children=self.plots)            

        self.document.add_root(layout)
        
    def add_periodic_callback(self, cb, update = 100):
        self.document.add_periodic_callback(cb,update)
Example #48
0
    def test_plot_dict_returned_when_wrap_plot_info_is_false(self, mock_make_id):
        doc = Document()
        plot1 = figure()
        plot1.circle([], [])
        doc.add_root(plot1)

        plot2 = figure()
        plot2.circle([], [])
        doc.add_root(plot2)

        expected_plotdict_1 = RenderRoot(elementid="ID", id="ID")
        expected_plotdict_2 = RenderRoot(elementid="ID", id="ID")

        _, plotdict = bes.components(plot1, wrap_plot_info=False)
        assert plotdict == expected_plotdict_1

        _, plotids = bes.components((plot1, plot2), wrap_plot_info=False)
        assert plotids == (expected_plotdict_1, expected_plotdict_2)

        _, plotiddict = bes.components({'p1': plot1, 'p2': plot2}, wrap_plot_info=False)
        assert plotiddict == {'p1': expected_plotdict_1, 'p2': expected_plotdict_2}
Example #49
0
    def test_plot_dict_returned_when_wrap_plot_info_is_false(self, mock_make_id):
        doc = Document()
        plot1 = figure()
        plot1.circle([], [])
        doc.add_root(plot1)

        plot2 = figure()
        plot2.circle([], [])
        doc.add_root(plot2)

        expected_plotdict_1 = RenderRoot(elementid="ID", id="ID")
        expected_plotdict_2 = RenderRoot(elementid="ID", id="ID")

        _, plotdict = bes.components(plot1, wrap_plot_info=False)
        assert plotdict == expected_plotdict_1

        _, plotids = bes.components((plot1, plot2), wrap_plot_info=False)
        assert plotids == (expected_plotdict_1, expected_plotdict_2)

        _, plotiddict = bes.components({'p1': plot1, 'p2': plot2}, wrap_plot_info=False)
        assert plotiddict == {'p1': expected_plotdict_1, 'p2': expected_plotdict_2}
Example #50
0
    def test_destroy(self) -> None:
        d = Document()
        dm = d.models
        assert len(dm) == 0

        m1 = Div()
        m2 = Div()
        m3 = Div()

        d.add_root(m1)
        d.add_root(m2)
        d.add_root(m3)
        for m in [m1, m2, m3]:
            assert m._document is d

        assert dm.destroy() is None

        assert not hasattr(dm, "_models")
        assert not hasattr(dm, "_models_by_name")

        for m in [m1, m2, m3]:
            assert m._document is None
Example #51
0
 def test_theming_a_document_before_adding_root(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             }
         }
     })
     obj = ThemedModel()
     doc = Document()
     assert 'hello' == obj.string
     doc.theme = theme
     assert doc.theme is theme
     changes = dict(calls=[])
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     doc.add_root(obj)
     assert 'w00t' == obj.string
     doc.remove_root(obj)
     assert 'hello' == obj.string
     assert [('string', 'hello', 'w00t'), ('string', 'w00t', 'hello')] == changes['calls']
Example #52
0
 def test_setting_document_theme_to_none(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             }
         }
     })
     obj = ThemedModel()
     doc = Document()
     doc.add_root(obj)
     changes = dict(calls=[])
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     doc.theme = theme
     assert 'w00t' == obj.string
     # setting to None reverts to default theme
     doc.theme = None
     assert doc.theme is not None
     assert 'hello' == obj.string
     assert [('string', 'hello', 'w00t'), ('string', 'w00t', 'hello')] == changes['calls']
Example #53
0
 def test_with_mathstring(self, test_plot, test_glplot, test_table, test_widget, test_mathtext,
         test_mathstring_axis_label, test_mathstring_major_label_overrides) -> None:
     assert beb._use_mathjax([test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_glplot, test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_widget, test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_widget, test_table, test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_mathtext, test_mathstring_axis_label]) is True
     assert beb._use_mathjax([test_plot, test_mathstring_major_label_overrides]) is True
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_table)
     d.add_root(test_widget)
     d.add_root(test_mathstring_axis_label)
     assert beb._use_mathjax([d]) is True
Example #54
0
def _plot_to_json(plot):
    """Convert plot to JSON objects necessary for rendering with `bokehJS`.
    Parameters
    ----------
    plot : bokeh.plotting.figure.Figure
        Bokeh plot object to be rendered.
    Returns
    -------
    (str, str)
        Returns (docs_json, render_items) json for the desired plot.
    """
    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)
    custom_model_js = bundle_all_models()

    return docs_json, render_items, custom_model_js
Example #55
0
 def test_setting_document_theme_to_none(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             }
         }
     })
     obj = ThemedModel()
     doc = Document()
     doc.add_root(obj)
     changes = dict(calls=[])
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     doc.theme = theme
     self.assertEqual('w00t', obj.string)
     # setting to None reverts to default theme
     doc.theme = None
     self.assertIsNot(doc.theme, None)
     self.assertEqual('hello', obj.string)
     self.assertEqual([('string', 'hello', 'w00t'),
                       ('string', 'w00t', 'hello')], changes['calls'])
Example #56
0
    def test_seen(self) -> None:
        d = Document()
        dm = d.models
        assert len(dm) == 0

        m1 = Div(id="m1")
        m2 = Div(id="m2")

        d.add_root(m1)
        d.add_root(m2)

        assert not dm.seen("m1")
        assert not dm.seen("m2")

        d.remove_root(m2)

        assert not dm.seen("m1")
        assert dm.seen("m2")

        d.remove_root(m1)

        assert dm.seen("m1")
        assert dm.seen("m2")
Example #57
0
 def test_without_gl(self, test_plot, test_glplot, test_table, test_widget):
     assert beb._use_gl([test_plot]) is False
     assert beb._use_gl([test_plot, test_table]) is False
     assert beb._use_gl([test_plot, test_widget]) is False
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_table)
     d.add_root(test_widget)
     assert beb._use_gl([d]) is False
Example #58
0
def spotify_graph_handler(doc: Document) -> None:
    plot_handler = PlotHandler()

    def playlist_input_handler(attr, old, new):
        root_layout = curdoc().get_model_by_name('main_layout')
        sub_layouts = root_layout.children
        sub_layouts[-1] = plot_handler.get_plot(RequestType.Playlist, new)

    playlist_input = TextInput(value="", title="Playlist:")
    playlist_input.on_change("value", playlist_input_handler)

    def artist_input_handler(attr, old, new):
        root_layout = curdoc().get_model_by_name('main_layout')
        sub_layouts = root_layout.children
        sub_layouts[-1] = plot_handler.get_plot(RequestType.SingleArtist, new)

    artist_input = TextInput(value="", title="Artist:")
    artist_input.on_change("value", artist_input_handler)

    doc.add_root(
        column(playlist_input,
               artist_input,
               plot_handler.plot,
               name='main_layout'))
Example #59
0
    def test_recompute(self) -> None:
        d = Document()
        dm = d.models
        assert len(dm) == 0

        r1 = Row(children=[Div(id="d1", name="dr1")])
        r2 = Row(children=[Div(id="d2", name="dr2"), Div(id="d3", name="dr2")])

        d.add_root(r1)
        d.add_root(r2)

        assert set(dm._models_by_name._dict) == {"dr1", "dr2"}

        for m in dm:
            assert m._document is d

        d.remove_root(r1)
        for m in dm:
            assert m._document is d

        assert r1._document is None
        assert r1.children[0]._document is None

        assert set(dm._models_by_name._dict) == {"dr2"}
Example #60
0
 def test_with_tables(self, test_plot, test_glplot, test_table, test_widget) -> None:
     assert beb._use_tables([test_table]) is True
     assert beb._use_tables([test_table, test_plot]) is True
     assert beb._use_tables([test_table, test_plot, test_glplot]) is True
     assert beb._use_tables([test_table, test_widget, test_table, test_glplot]) is True
     d = Document()
     d.add_root(test_plot)
     d.add_root(test_table)
     d.add_root(test_widget)
     d.add_root(test_glplot)
     assert beb._use_tables([d]) is True