Example #1
0
 def test_model_in_empty_document_context_manager_is_used(self):
     m = mock.MagicMock(name='_ModelInEmptyDocument')
     plot1 = figure()
     curdoc().add_root(plot1)
     with mock.patch('bokeh.embed._ModelInEmptyDocument', m):
         embed.notebook_div(plot1)
     m.assert_called_once_with(plot1)
Example #2
0
 def test_model_in_empty_document_context_manager_is_used(self):
     m = mock.MagicMock(name='_ModelInEmptyDocument')
     plot1 = figure()
     curdoc().add_root(plot1)
     with mock.patch('bokeh.embed._ModelInEmptyDocument', m):
         embed.notebook_div(plot1)
     m.assert_called_once_with(plot1)
Example #3
0
 def figure_data(self, plot, fmt='html', **kwargs):
     if not bokeh_lt_011:
         doc = Document()
         doc.add_root(plot.state)
         comms_target = str(uuid.uuid4())
         doc.last_comms_target = comms_target
         div = notebook_div(plot.state, comms_target)
         return div
     else:
         return notebook_div(plot.state)
Example #4
0
 def figure_data(self, plot, fmt='html', **kwargs):
     if not bokeh_lt_011:
         doc_handler = add_to_document(plot.state)
         with doc_handler:
             doc = doc_handler._doc
             comms_target = str(uuid.uuid4())
             doc.last_comms_target = comms_target
             div = notebook_div(plot.state, comms_target)
         plot.document = doc
         return div
     else:
         return notebook_div(plot.state)
Example #5
0
 def figure_data(self, plot, fmt='html', **kwargs):
     if not bokeh_lt_011:
         doc_handler = add_to_document(plot.state)
         with doc_handler:
             doc = doc_handler._doc
             comms_target = str(uuid.uuid4())
             doc.last_comms_target = comms_target
             div = notebook_div(plot.state, comms_target)
         plot.document = doc
         return div
     else:
         return notebook_div(plot.state)
Example #6
0
def show(obj, title='test', filename=False, server=False, notebook=False, **kws):
    """ 'shows' a plot object, by auto-raising the window or tab
    displaying the current plot (for file/server output modes) or displaying
    it in an output cell (IPython notebook).

    Args:
        obj (Widget/Plot object, optional): it accepts a plot object and just shows it.

    """
    if filename:
        if filename is True:
            filename = "untitled"
        else:
            filename = filename

        with open(filename, "w") as f:
            f.write(file_html(obj.doc, INLINE, title))
        print("Wrote %s" % filename)
        view(filename)

    elif filename is False and server is False and notebook is False:
        print("You have to provide a filename (filename='foo.html' or"
              " .filename('foo.html')) to save your plot.")

    if server:
        obj.session.store_document(obj.doc)
        link = obj.session.object_link(obj.doc.context)
        view(link)

    if notebook:
        from bokeh.embed import notebook_div
        for plot in obj._plots:
            publish_display_data({'text/html': notebook_div(plot)})
Example #7
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:
         if bokeh_version > '0.12.9':
             js, div, _ = notebook_content(model, comm_id)
             html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
             div = encode_utf8(html)
             doc.hold()
         else:
             div = notebook_div(model, comm_id)
     except:
         logger.disabled = False
         raise
     logger.disabled = False
     plot.document = doc
     return div
Example #8
0
 def figure_data(self, plot, fmt="html", **kwargs):
     if not old_bokeh:
         doc = Document()
         doc.add_root(plot.state)
         plot.set_root(plot.state)
         plot.set_document(doc)
     return notebook_div(plot.state)
    def show(self):
        "Main show function, it shows the plot in file, server and notebook outputs."
        global _notebook_loaded

        if self.filename:
            if self.filename is True:
                filename = "untitled"
            else:
                filename = self.filename
            with open(filename, "w") as f:
                f.write(file_html(self.doc, INLINE, self.title))
            print("Wrote %s" % filename)
            view(filename)
        elif self.filename is False and self.server is False and self.notebook is False:
            print("You have a provide a filename (filename='foo' or"
                  " .filename('foo')) to save your plot.")

        if self.server:
            self.session.use_doc(self.servername)
            self.session.load_document(self.doc)
            self.session.show(self.plot)

        if self.notebook:
            from bokeh.embed import notebook_div
            publish_display_data({'text/html': notebook_div(self.plot)})
Example #10
0
    def show(self):
        """Main show function.

        It shows the plot in file, server and notebook outputs.
        """
        if self.filename:
            if self.filename is True:
                filename = "untitled"
            else:
                filename = self.filename
            with open(filename, "w") as f:
                f.write(file_html(self.doc, INLINE, self.title))
            print("Wrote %s" % filename)
            view(filename)
        elif self.filename is False and self.server is False and self.notebook is False:
            print("You have a provide a filename (filename='foo.html' or"
                  " .filename('foo.html')) to save your plot.")

        if self.server:
            self.session.store_document(self.doc)
            link = self.session.object_link(self.doc.context)
            view(link)

        if self.notebook:
            from bokeh.embed import notebook_div
            for plot in self._plots:
                publish_display_data({'text/html': notebook_div(plot)})
Example #11
0
def notebook_show(obj, doc, target):
    """
    Displays bokeh output inside a notebook and returns a CommsHandle.
    """
    publish_display_data({'text/html': notebook_div(obj, target)})
    handle = _CommsHandle(get_comms(target), doc, doc.to_json())
    return handle
Example #12
0
def show(obj, title='test', filename=False, server=False, notebook=False, **kws):
    """ 'shows' a plot object, by auto-raising the window or tab
    displaying the current plot (for file/server output modes) or displaying
    it in an output cell (IPython notebook).

    Args:
        obj (Widget/Plot object, optional): it accepts a plot object and just shows it.

    """
    if filename:
        if filename is True:
            filename = "untitled"
        else:
            filename = filename

        with open(filename, "w") as f:
            f.write(file_html(obj.doc, INLINE, title))
        print("Wrote %s" % filename)
        view(filename)

    elif filename is False and server is False and notebook is False:
        print("You have to provide a filename (filename='foo.html' or"
              " .filename('foo.html')) to save your plot.")

    if server:
        obj.session.store_document(obj.doc)
        link = obj.session.object_link(obj.doc.context)
        view(link)

    if notebook:
        from bokeh.embed import notebook_div
        for plot in obj._plots:
            publish_display_data({'text/html': notebook_div(plot)})
Example #13
0
 def figure_data(self, plot, fmt='html', **kwargs):
     if not old_bokeh:
         doc = Document()
         doc.add_root(plot.state)
         plot.set_root(plot.state)
         plot.set_document(doc)
     return notebook_div(plot.state)
Example #14
0
    def test_notebook_div(self, mock_notebook_content):
        (script, div, doc) = ("(function(){})()", "<div></div>", "doc")
        mock_notebook_content.return_value = (script, div, doc)

        notebook_div = embed.notebook_div(_embed_test_plot)

        expected_notebook_div = NOTEBOOK_DIV.render(plot_script=script, plot_div=div)

        self.assertEqual(notebook_div, expected_notebook_div)
Example #15
0
 def figure_data(self, plot, fmt='html', **kwargs):
     doc_handler = add_to_document(plot.state)
     with doc_handler:
         doc = doc_handler._doc
         comm_id = plot.comm.id if plot.comm else None
         div = notebook_div(plot.state, comm_id)
     plot.document = doc
     doc.add_root(plot.state)
     return div
Example #16
0
    def test_div_attrs(self):
        r = embed.notebook_div(_embed_test_plot)
        html = bs4.BeautifulSoup(r)
        divs = html.findAll(name="div")
        self.assertEqual(len(divs), 1)

        div = divs[0]
        self.assertTrue(set(div.attrs), set(["class", "id"]))
        self.assertEqual(div.attrs["class"], ["plotdiv"])
        self.assertEqual(div.text, "")
Example #17
0
    def test_div_attrs(self):
        r = embed.notebook_div(_embed_test_plot)
        html = bs4.BeautifulSoup(r)
        divs = html.findAll(name='div')
        self.assertEqual(len(divs), 1)

        div = divs[0]
        self.assertTrue(set(div.attrs), set(['class', 'id']))
        self.assertEqual(div.attrs['class'], ['plotdiv'])
        self.assertEqual(div.text, "")
Example #18
0
    def test_div_attrs(self):
        r = embed.notebook_div(_embed_test_plot)
        html = bs4.BeautifulSoup(r)
        divs = html.findAll(name='div')
        self.assertEqual(len(divs), 1)

        div = divs[0]
        self.assertTrue(set(div.attrs), set(['class', 'id']))
        self.assertEqual(div.attrs['class'], ['plotdiv', 'bk-plot'])
        self.assertEqual(div.text, "")
Example #19
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
     div = notebook_div(model, comm_id)
     plot.document = doc
     return div
Example #20
0
def _show_zeppelin_doc_with_state(obj, state, notebook_handle):
    if notebook_handle:
        raise ValueError("Zeppelin doesn't support notebook_handle.")
    if _isAfterBokeh1210:
        (script, div, cell_doc) = notebook_content(obj)
        print("%html " + div)
        print('%html ' + '<script type="text/javascript">' + script + "</script>")
    else:
        print("%html " + notebook_div(obj))

    return None
Example #21
0
    def __init__(self, bokeh_plot, callback, throttle=100, **kwargs):
        """
        The callback function should have the signature:

        fn(x_range=(xmin, xmax), y_range=(ymin, ymax), w, h, **kwargs)

        and return a PIL image object.  Any kwargs provided here will
        be passed to the callback each time.

        The throttle parameter allows control over how many times the
        callback will get executed when there are frequent closely
        spaced events.        
        """

        self.p = bokeh_plot
        self.callback = callback
        self.kwargs = kwargs

        # Initialize RGBA image glyph and datasource
        w, h = self.p.plot_width, self.p.plot_height
        xmin, xmax = self.p.x_range.start, self.p.x_range.end
        ymin, ymax = self.p.y_range.start, self.p.y_range.end
        dw, dh = xmax-xmin, ymax-ymin
        image = self.callback(x_range=(xmin, xmax), y_range=(ymin, ymax), w=w, h=h, **self.kwargs)

        self.ds = ColumnDataSource(data=dict(image=[image.data], x=[xmin],
                                             y=[ymin], dw=[dw], dh=[dh]))
        self.p.image_rgba(source=self.ds, image='image', x='x', y='y',
                          dw='dw', dh='dh', dilate=False)

        # Register callback on the class with unique reference
        cls = type(self)
        self.ref = str(uuid.uuid4())
        cls._callbacks[self.ref] = self

        # Generate python callback command
        cmd = cls.cmd_template.format(module=cls.__module__,
                                      cls=cls.__name__, ref=self.ref)

        # Initialize callback
        cb_code = cls.jscode.format(plot_id=self.p._id, cmd=cmd,
                                    ref=self.ref.replace('-', '_'),
                                    throttle=throttle)
        cb_args = dict(x_range=self.p.x_range, y_range=self.p.y_range)
        callback = CustomJS(args=cb_args, code=cb_code)
        self.p.x_range.callback = callback
        self.p.y_range.callback = callback

        # Initialize document
        doc_handler = add_to_document(self.p)
        with doc_handler:
            self.doc = doc_handler._doc
            self.div = notebook_div(self.p, self.ref)
        self.comms = None
Example #22
0
    def init_bokeh_table(self):
        time_format = bokeh_tables.NumberFormatter(format='0,0.00000')

        name_template = ('<a id="function<%= ids %>", style="cursor:pointer">'
                         '<%- names %></a>')
        name_format = (bokeh_tables.
                       HTMLTemplateFormatter(template=name_template))

        time_plot_template = ('<svg width="100" height="10">'
                              '<rect width="<%= plot_inline_times%>"'
                              'height="10" style="fill:rgb(255, 0, 0);"/>'
                              '<rect x="<%= plot_inline_times%>"'
                              'width="<%= plot_extra_times %>"'
                              'height="10" style="fill:rgb(255, 160, 160);"/>'
                              '</svg>')
        time_plot_format = (bokeh_tables.
                            HTMLTemplateFormatter(template=time_plot_template))

        columns = [bokeh_tables.TableColumn(title="Function",
                                            field="names",
                                            formatter=name_format),
                   bokeh_tables.TableColumn(title="Total time (s)",
                                            field="times",
                                            formatter=time_format,
                                            default_sort="descending"),
                   bokeh_tables.TableColumn(title="Inline time (s)",
                                            field="inlinetimes",
                                            formatter=time_format,
                                            default_sort="descending"),
                   bokeh_tables.TableColumn(title="Time plot",
                                            sortable=False,
                                            formatter=time_plot_format)]

        bokeh_table = bokeh_tables.DataTable(source=self.table_data,
                                             columns=columns,
                                             # Would be nice if width could
                                             # be automatic but this appears
                                             # to be broken in firefox and
                                             # chrome.
                                             width=620,
                                             height=27 + 15 * 25,
                                             selectable=False,
                                             row_headers=False)

        self.bokeh_table = bokeh_table

        comms_target = bokeh_util.serialization.make_id()
        self.bokeh_comms_target = comms_target
        self.bokeh_table_div = notebook_div(hplot(bokeh_table), comms_target)
Example #23
0
    def test_div_attrs(self):
        r = embed.notebook_div(_embed_test_plot)
        html = bs4.BeautifulSoup(r)
        divs = html.findAll(name='div')
        self.assertEqual(len(divs), 2)

        div = divs[0]
        self.assertEqual(set(div.attrs), set(['class']))
        self.assertEqual(div.attrs['class'], ['bk-root'])
        self.assertEqual(div.text, '\n\n')

        div = divs[1]
        self.assertEqual(set(div.attrs), set(['id', 'class']))
        self.assertEqual(div.attrs['class'], ['bk-plotdiv'])
        self.assertEqual(div.text, '')
Example #24
0
    def test_div_attrs(self):
        r = embed.notebook_div(_embed_test_plot)
        html = bs4.BeautifulSoup(r)
        divs = html.findAll(name='div')
        self.assertEqual(len(divs), 2)

        div = divs[0]
        self.assertEqual(set(div.attrs), set(['class']))
        self.assertEqual(div.attrs['class'], ['bk-root'])
        self.assertEqual(div.text, '\n\n')

        div = divs[1]
        self.assertEqual(set(div.attrs), set(['id', 'class']))
        self.assertEqual(div.attrs['class'], ['bk-plotdiv'])
        self.assertEqual(div.text, '')
Example #25
0
    def __init__(self, bokeh_plot, callback, throttle=500, **kwargs):
        self.p = bokeh_plot
        self.callback = callback
        self.kwargs = kwargs
        self.ref = str(uuid.uuid4())
        self.comms_handle = None
        self.throttle = throttle

        # Initialize the image and callback
        self.ds, self.renderer = self._init_image()
        callback = self._init_callback()
        self.p.x_range.callback = callback
        self.p.y_range.callback = callback

        # Initialize document
        doc_handler = add_to_document(self.p)
        with doc_handler:
            self.doc = doc_handler._doc
            self.div = notebook_div(self.p, self.ref)
Example #26
0
    def show(self):
        """Main show function.

        It shows the plot in file, server and notebook outputs.
        """
        # Add to document and session
        if self._options.server:
            if self._options.server is True:
                self._servername = "untitled_chart"
            else:
                self._servername = self._options.server

            self._session.use_doc(self._servername)
            self._session.load_document(self._doc)

        if not self._doc._current_plot == self:
            self._doc._current_plot = self
            self._doc.add(self)

        if self._options.filename:
            if self._options.filename is True:
                filename = "untitled"
            else:
                filename = self._options.filename

            with open(filename, "w") as f:
                f.write(file_html(self._doc, INLINE, self.title))
            print("Wrote %s" % filename)
            view(filename)
        elif self._options.filename is False and \
                        self._options.server is False and \
                        self._options.notebook is False:
            print("You must provide a filename (filename='foo.html' or"
                  " .filename('foo.html')) to save your plot.")

        if self._options.server:
            self.session.store_document(self._doc)
            link = self._session.object_link(self._doc.context)
            view(link)

        if self._options.notebook:
            from bokeh.embed import notebook_div
            publish_display_data({'text/html': notebook_div(self)})
Example #27
0
    def __init__(self, bokeh_plot, callback, throttle=500, **kwargs):
        self.p = bokeh_plot
        self.callback = callback
        self.kwargs = kwargs
        self.ref = str(uuid.uuid4())
        self.comms_handle = None
        self.throttle = throttle

        # Initialize the image and callback
        self.ds, self.renderer = self._init_image()
        callback = self._init_callback()
        self.p.x_range.callback = callback
        self.p.y_range.callback = callback

        # Initialize document
        doc_handler = add_to_document(self.p)
        with doc_handler:
            self.doc = doc_handler._doc
            self.div = notebook_div(self.p, self.ref)
Example #28
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
Example #29
0
    def show(self):
        """Main show function.

        It shows the plot in file, server and notebook outputs.
        """
        # Add to document and session
        if self._options.server:
            if self._options.server is True:
                self._servername = "untitled_chart"
            else:
                self._servername = self._options.server

            self._session.use_doc(self._servername)
            self._session.load_document(self._doc)

        if not self._doc._current_plot == self:
            self._doc._current_plot = self
            self._doc.add_root(self)

        if self._options.filename:
            if self._options.filename is True:
                filename = "untitled"
            else:
                filename = self._options.filename

            with open(filename, "w") as f:
                f.write(file_html(self._doc, INLINE, self.title))
            print("Wrote %s" % filename)
            view(filename)
        elif self._options.filename is False and \
                        self._options.server is False and \
                        self._options.notebook is False:
            print("You must provide a filename (filename='foo.html' or"
                  " .filename('foo.html')) to save your plot.")

        if self._options.server:
            self.session.store_document(self._doc)
            link = self._session.object_link(self._doc.context)
            view(link)

        if self._options.notebook:
            from bokeh.embed import notebook_div
            publish_display_data({'text/html': notebook_div(self)})
Example #30
0
    def __init__(self, bokeh_plot, callback, throttle=100, **kwargs):
        self.p = bokeh_plot
        self.callback = callback
        self.kwargs = kwargs

        # Initialize RGBA image glyph and datasource
        w, h = self.p.plot_width, self.p.plot_height
        xmin, xmax = self.p.x_range.start, self.p.x_range.end
        ymin, ymax = self.p.y_range.start, self.p.y_range.end
        dw, dh = xmax-xmin, ymax-ymin
        image = self.callback((xmin, xmax), (ymin, ymax), w, h, **self.kwargs)

        self.ds = ColumnDataSource(data=dict(image=[image.img], x=[xmin],
                                             y=[ymin], dw=[dw], dh=[dh]))
        self.p.image_rgba(source=self.ds, image='image', x='x', y='y',
                          dw='dw', dh='dh', dilate=False)

        # Register callback on the class with unique reference
        cls = type(self)
        self.ref = str(uuid.uuid4())
        cls._callbacks[self.ref] = self

        # Generate python callback command
        cmd = cls.cmd_template.format(module=cls.__module__,
                                      cls=cls.__name__, ref=self.ref)

        # Initialize callback
        cb_code = cls.jscode.format(plot_id=self.p._id, cmd=cmd,
                                    ref=self.ref.replace('-', '_'),
                                    throttle=throttle)
        cb_args = dict(x_range=self.p.x_range, y_range=self.p.y_range)
        callback = CustomJS(args=cb_args, code=cb_code)
        self.p.x_range.callback = callback
        self.p.y_range.callback = callback

        # Initialize document
        doc_handler = add_to_document(self.p)
        with doc_handler:
            self.doc = doc_handler._doc
            self.div = notebook_div(self.p, self.ref)
        self.comms = None
Example #31
0
def bokeh_notebook_div(image):
    """"
    Generates an HTML div to embed in the notebook.

    Parameters
    ----------
    image: InteractiveImage
        InteractiveImage instance with a plot

    Returns
    -------
    div: str
        HTML string containing the bokeh plot to be displayed
    """
    if bokeh_version > "0.12.9":
        js, div, _ = notebook_content(image.p, image.ref)
        div = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
        # Ensure events are held until an update is triggered
        image.doc.hold()
    else:
        div = notebook_div(image.p, image.ref)
    return div
Example #32
0
def bokeh_notebook_div(image):
    """"
    Generates an HTML div to embed in the notebook.

    Parameters
    ----------
    image: InteractiveImage
        InteractiveImage instance with a plot

    Returns
    -------
    div: str
        HTML string containing the bokeh plot to be displayed
    """
    if bokeh_version > '0.12.9':
        js, div, _ = notebook_content(image.p, image.ref)
        html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
        div = encode_utf8(html)
        # Ensure events are held until an update is triggered
        image.doc.hold() 
    else:
        div = notebook_div(image.p, image.ref)
    return div
Example #33
0
 def test_return_type(self):
     r = embed.notebook_div(_embed_test_plot)
     self.assertTrue(isinstance(r, str))
    def doRenderChart(self):        
        def genMarkup(chartFigure):
            s = chartFigure[0] if isinstance(chartFigure, tuple) else chartFigure
            d = chartFigure[1] if isinstance(chartFigure, tuple) else ''
            return self.env.from_string("""
                    <script class="pd_save">
                    function setChartScript() {{
                        if (!window.Bokeh) {{
                            setTimeout(setChartScript, 250)
                        }} else {{
                            var d = document.getElementById("pd-bkchartdiv-{p}")
                            if (d){{
                                var el = document.createElement('div')
                                el.innerHTML = `{chartScript}`
                                var chartscript = el.childNodes[1]
                                var s = document.createElement("script")
                                s.innerHTML = chartscript.innerHTML
                                d.parentNode.insertBefore(s, d)
                            }}
                        }}
                    }}
                    if (!window.Bokeh && !window.autoload){{
                        window.autoload=true;
                        {loadJS}
                    }}
                    setChartScript()
                    </script>
                    <div style="padding:5px" id="pd-bkchartdiv-{p}">{chartDiv}</div>
                    {{%for message in messages%}}
                        <div>{{{{message}}}}</div>
                    {{%endfor%}}
                """.format(chartScript=s.replace('</script>', '<\/script>'), chartDiv=d, loadJS=self.getLoadJS(), p=self.getPrefix())
            ).render(messages=self.messages)

        minBkVer = (0,12,9)
        if BokehBaseDisplay.bokeh_version < minBkVer:
            raise Exception("""
                <div>Incorrect version of Bokeh detected. Expected {0} or greater, got {1}</div>
                <div>Please upgrade by using the following command: <b>!pip install --user --upgrade bokeh</b></div>
            """.format(minBkVer, BokehBaseDisplay.bokeh_version))
        clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true"
        if not clientHasBokeh:          
            output_notebook(hide_banner=True)
        charts = self.createBokehChart()

        if not isinstance(charts, list):
            # charts.add_tools(ResizeTool())
            #bokeh 0.12.5 has a non backward compatible change on the title field. It is now of type Title
            #following line is making sure that we are still working with 0.12.4 and below
            if hasattr(charts, "title") and hasattr(charts.title, "text"):
                charts.title.text = self.options.get("title", "")
            else:
                charts.title = self.options.get("title", "")
            charts.plot_width = int(self.getPreferredOutputWidth() - 10 )
            charts.plot_height = int(self.getPreferredOutputHeight() - 10  )
            charts.grid.grid_line_alpha=0.3
            return genMarkup(notebook_div(charts))
        else:
            from bokeh.layouts import gridplot
            ncols = 2
            nrows = len(charts)/2 + len(charts)%2
            
            w = self.getPreferredOutputWidth()/ncols if len(charts) > 1 else self.getPreferredOutputWidth()
            h = w * self.getHeightWidthRatio() if len(charts) > 1 else self.getPreferredOutputHeight()
            for chart in charts:
                chart.plot_width = int(w - 5)
                chart.plot_height = int (h - 5)

            return genMarkup(notebook_div(gridplot(charts, ncols=ncols)))
Example #35
0
 def test_result_attrs(self):
     r = embed.notebook_div(_embed_test_plot)
     html = bs4.BeautifulSoup(r)
     scripts = html.findAll(name='script')
     self.assertEqual(len(scripts), 1)
     self.assertTrue(scripts[0].attrs, {'type': 'text/javascript'})
Example #36
0
 def test_return_type(self):
     r = embed.notebook_div(_embed_test_plot)
     self.assertTrue(isinstance(r, str))
Example #37
0
 def snapshot(self, name='bokeh_scatter'):
     html = notebook_div(self.plot)
     widget = shaoscript('html$N=' + name)
     widget.value = html
     return widget
Example #38
0
def plot_pulse_files(fileNames, firstSeqNum=0):
    '''
    plot_pulse_files(fileNames, firstSeqNum=0)

    Helper function to plot a list of AWG files.  In an iPython notebook the plots will be in line with
    dynamic updating.  For iPython consoles a static html file will be generated with the firstSeqNum.
    '''
    #If we only go one filename turn it into a list
    if isinstance(fileNames, str):
        fileNames = [fileNames]

    wfs = {}
    dataDict = {}
    lineNames = []
    title = ""

    for fileName in sorted(fileNames):

        #Assume a naming convention path/to/file/SequenceName-AWGName.h5
        AWGName = (os.path.split(
            os.path.splitext(fileName)[0])[1]).split('-')[1]
        #Strip any _ suffix
        if '_' in AWGName:
            AWGName = AWGName[:AWGName.index('_')]

        title += os.path.split(os.path.splitext(fileName)[0])[1] + "; "

        wfs[AWGName] = read_sequence_file(Libraries.instrumentLib[AWGName],
                                          fileName)

        for (k, seqs) in sorted(wfs[AWGName].items()):
            if not all_zero_seqs(seqs):
                lineNames.append(AWGName + '-' + k)
                dataDict[lineNames[-1] + "_x"] = np.arange(
                    len(seqs[firstSeqNum]))
                dataDict[lineNames[-1]] = seqs[firstSeqNum] + 2 * (
                    len(lineNames) - 1)

    #Remove trailing semicolon from title
    title = title[:-2]

    source = bk.ColumnDataSource(data=dataDict)
    figH = bk.figure(title=title,
                     plot_width=1000,
                     y_range=(-1, len(dataDict) + 1))

    #Colorbrewer2 qualitative Set3 (http://colorbrewer2.org)
    colours = [
        "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462",
        "#b3de69", "#fccde5", "#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f"
    ]

    for ct, k in enumerate(lineNames):
        figH.line(k + "_x",
                  k,
                  source=source,
                  color=colours[ct % len(colours)],
                  line_width=2,
                  legend=k)

    if in_ipynb():
        #Setup inline plotting with slider updating of data

        def update_plot(_, seqNum):
            for ct, k in enumerate(lineNames):
                AWGName, chName = k.split('-')
                source.data[k + "_x"] = np.arange(
                    len(wfs[AWGName][chName][seqNum - 1]))
                source.data[k] = wfs[AWGName][chName][seqNum - 1] + 2 * ct
            source.push_notebook()

        #widgets.interact(update_plot, seqNum=(1, len(wfs[AWGName]["ch1"])), div=widgets.HTMLWidget(value=notebook_div(figH)))

        slider = widgets.IntSlider(value=firstSeqNum + 1,
                                   min=1,
                                   max=len(wfs[AWGName]["ch1"]),
                                   step=1,
                                   description="Sequence (of {}):".format(
                                       len(seqs)))
        slider.on_trait_change(update_plot, 'value')
        plotBox = widgets.HTML(value=notebook_div(figH))
        appBox = widgets.Box()
        appBox.children = [slider, plotBox]
        display(appBox)

    else:
        #Otherwise dump to a static file
        bk.show(figH)
Example #39
0
def plot_pulse_files(fileNames, firstSeqNum=0):
    '''
    plot_pulse_files(fileNames, firstSeqNum=0)

    Helper function to plot a list of AWG files.  In an iPython notebook the plots will be in line with
    dynamic updating.  For iPython consoles a static html file will be generated with the firstSeqNum.
    '''
    #If we only go one filename turn it into a list
    if isinstance(fileNames, str):
        fileNames = [fileNames]

    wfs = {}
    dataDict = {}
    lineNames = []
    title = ""

    import Libraries # prevent circular import

    for fileName in sorted(fileNames):

        #Assume a naming convention path/to/file/SequenceName-AWGName.h5
        AWGName = (os.path.split(os.path.splitext(fileName)[0])[1]).split('-')[1]
        #Strip any _ suffix
        if '_' in AWGName:
            AWGName = AWGName[:AWGName.index('_')]

        title += os.path.split(os.path.splitext(fileName)[0])[1] + "; "

        wfs[AWGName] = Libraries.instrumentLib[AWGName].read_sequence_file(fileName)

        for (k,seqs) in sorted(wfs[AWGName].items()):
            if not all_zero_seqs(seqs):
                lineNames.append(AWGName + '-' + k)
                dataDict[lineNames[-1] + "_x"] = np.arange(len(seqs[firstSeqNum]))
                dataDict[lineNames[-1]] = seqs[firstSeqNum] + 2*(len(lineNames)-1)

    #Remove trailing semicolon from title
    title = title[:-2]

    source = bk.ColumnDataSource(data=dataDict)
    figH = bk.figure(title=title, plot_width=1000, y_range=(-1,len(dataDict)+1))
    figH.background_fill = config.plotBackground
    if config.gridColor:
        figH.xgrid.grid_line_color = config.gridColor
        figH.ygrid.grid_line_color = config.gridColor

    # Colobrewer2 qualitative Set1 (http://colorbrewer2.org)
    colours = [
        "#e41a1c",
        "#377eb8",
        "#4daf4a",
        "#984ea3",
        "#ff7f00",
        "#ffff33",
        "#a65628",
        "#f781bf",
        "#999999"
    ]

    for ct,k in enumerate(lineNames):
        figH.line(k+"_x", k, source=source, color=colours[ct%len(colours)], line_width=2, legend=k)

    if in_ipynb():
        #Setup inline plotting with slider updating of data

        def update_plot(_, seqNum):
            for ct,k in enumerate(lineNames):
                AWGName, chName = k.split('-')
                source.data[k+"_x"] = np.arange(len(wfs[AWGName][chName][seqNum-1]))
                source.data[k] = wfs[AWGName][chName][seqNum-1] + 2*ct
            source.push_notebook()

        #widgets.interact(update_plot, seqNum=(1, len(wfs[AWGName]["ch1"])), div=widgets.HTMLWidget(value=notebook_div(figH)))
        if 'ch1' in wfs[AWGName].keys():
            chkey = "ch1"
        else:
            chkey = "ch3"
        slider = widgets.IntSlider(value=firstSeqNum+1, min=1, max=len(wfs[AWGName][chkey]), step=1, description="Sequence (of {}):".format(len(seqs)))
        slider.on_trait_change(update_plot, 'value')
        plotBox = widgets.HTML(value=notebook_div(figH))
        appBox = widgets.Box()
        appBox.children = [slider, plotBox]
        display(appBox)

    else:
        #Otherwise dump to a static file
        bk.show(figH)
Example #40
0
    def doRenderChart(self):
        def genMarkup(chartFigure):
            s = chartFigure[0] if isinstance(chartFigure,
                                             tuple) else chartFigure
            d = chartFigure[1] if isinstance(chartFigure, tuple) else ''
            return self.env.from_string("""
                    <script class="pd_save">
                    function setChartScript() {{
                        if (!window.Bokeh) {{
                            setTimeout(setChartScript, 250)
                        }} else {{
                            var d = document.getElementById("pd-bkchartdiv-{p}")
                            if (d){{
                                var el = document.createElement('div')
                                el.innerHTML = `{chartScript}`
                                var chartscript = el.childNodes[1]
                                var s = document.createElement("script")
                                s.innerHTML = chartscript.innerHTML
                                d.parentNode.insertBefore(s, d)
                            }}
                        }}
                    }}
                    if (!window.Bokeh && !window.autoload){{
                        window.autoload=true;
                        {loadJS}
                    }}
                    setChartScript()
                    </script>
                    <div style="padding:5px" id="pd-bkchartdiv-{p}">{chartDiv}</div>
                    {{%for message in messages%}}
                        <div>{{{{message}}}}</div>
                    {{%endfor%}}
                """.format(chartScript=s.replace('</script>', '<\/script>'),
                           chartDiv=d,
                           loadJS=self.getLoadJS(),
                           p=self.getPrefix())).render(messages=self.messages)

        minBkVer = (0, 12, 9)
        if BokehBaseDisplay.bokeh_version < minBkVer:
            raise Exception("""
                <div>Incorrect version of Bokeh detected. Expected {0} or greater, got {1}</div>
                <div>Please upgrade by using the following command: <b>!pip install --user --upgrade bokeh</b></div>
            """.format(minBkVer, BokehBaseDisplay.bokeh_version))
        clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true"
        if not clientHasBokeh:
            output_notebook(hide_banner=True)
        charts = self.createBokehChart()

        if not isinstance(charts, list):
            # charts.add_tools(ResizeTool())
            #bokeh 0.12.5 has a non backward compatible change on the title field. It is now of type Title
            #following line is making sure that we are still working with 0.12.4 and below
            if hasattr(charts, "title") and hasattr(charts.title, "text"):
                charts.title.text = self.options.get("title", "")
            else:
                charts.title = self.options.get("title", "")
            charts.plot_width = int(self.getPreferredOutputWidth() - 10)
            charts.plot_height = int(self.getPreferredOutputHeight() - 10)
            charts.grid.grid_line_alpha = 0.3
            return genMarkup(notebook_div(charts))
        else:
            from bokeh.layouts import gridplot
            ncols = 2
            nrows = len(charts) / 2 + len(charts) % 2

            w = self.getPreferredOutputWidth() / ncols if len(
                charts) > 1 else self.getPreferredOutputWidth()
            h = w * self.getHeightWidthRatio() if len(
                charts) > 1 else self.getPreferredOutputHeight()
            for chart in charts:
                chart.plot_width = int(w - 5)
                chart.plot_height = int(h - 5)

            return genMarkup(
                notebook_div(gridplot(charts, ncols=ncols, nrows=nrows)))
Example #41
0
 def snapshot(self, name='bokeh_scatter'):
   html =  notebook_div(self.plot)
   widget = shaoscript('html$N='+name)
   widget.value = html
   return widget
Example #42
0
 def test_result_attrs(self):
     r = embed.notebook_div(_embed_test_plot)
     html = bs4.BeautifulSoup(r)
     scripts = html.findAll(name='script')
     self.assertEqual(len(scripts), 1)
     self.assertTrue(scripts[0].attrs, {'type': 'text/javascript'})
Example #43
0
 def figure_data(self, plot, fmt='html', **kwargs):
     return notebook_div(plot.state)
Example #44
0
 def figure_data(self, plot, fmt='html', **kwargs):
     return notebook_div(plot.state)