Example #1
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 #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_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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #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)
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 #12
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 #13
0
def save_holoviews(fpath,
                   obj,
                   save_components=False,
                   save_doc=False,
                   save_html=True,
                   save_pickle=False,
                   save_item=False):
    from holoviews.core.io import Pickler
    import holoviews as hv
    obj.opts(title="")

    if fpath.endswith('.html'):
        fpath = ".".join(fpath.split(".")[:-1])

    if save_pickle:
        print("saving {}.hvz".format(fpath))
        with open(fpath + '.hvz', 'wb') as f:
            Pickler.save(obj, f)

    if save_item:
        print("saving {}-item.json".format(fpath))
        from bokeh.embed import json_item
        p = hv.render(obj, backend='bokeh')
        item_json = json_item(p)
        with open(fpath + '-item.json', 'w') as f:
            json.dump(item_json, f, indent=2)

    if save_doc:
        print("saving {}-doc.json".format(fpath))
        from bokeh.document import Document
        p = hv.render(obj, backend='bokeh')
        doc = Document()
        doc.add_root(p)
        doc_json = doc.to_json()
        with open(fpath + '-doc.json', 'w') as f:
            json.dump(doc_json, f, indent=2)

    if save_components:
        print("saving {}.{{script|div}}".format(fpath))
        from bokeh.embed import components
        p = hv.render(obj, backend='bokeh')
        script, div = components(p)
        with open(fpath + '.script', 'w') as f:
            f.write(script)
        with open(fpath + '.div', 'w') as f:
            f.write(div)

    if save_html:
        print("saving {}.html".format(fpath))
        hv.save(obj, fpath + ".html")
Example #14
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