Python ipywidgets.Output() Examples

The following are 21 code examples of ipywidgets.Output(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .
Example #1
Source File: library.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def circuit_diagram_widget() -> wid.Box:
    """Create a circuit diagram widget.

    Returns:
        Output widget.
    """
    # The max circuit height corresponds to a 20Q circuit with flat
    # classical register.
    top_out = wid.Output(layout=wid.Layout(width='100%',
                                           height='auto',
                                           max_height='1000px',
                                           overflow='hidden scroll',))

    top = wid.Box(children=[top_out], layout=wid.Layout(width='100%', height='auto'))

    return top 
Example #2
Source File: pylab.py    From ipyvolume with MIT License 5 votes vote down vote up
def _screenshot_data(
    timeout_seconds=10,
    output_widget=None,
    format="png",
    width=None,
    height=None,
    fig=None,
    headless=False,
    devmode=False,
):
    if fig is None:
        fig = gcf()
    else:
        assert isinstance(fig, ipv.Figure)
    if headless:
        tempdir = tempfile.mkdtemp()
        tempfile_ = os.path.join(tempdir, 'headless.html')
        save(tempfile_, offline=True, scripts_path=tempdir, devmode=devmode)
        import ipyvolume.headless

        data = ipyvolume.headless._screenshot_data("file://" + tempfile_)
        if data is None:
            raise ValueError('Error capturing data from headless browser')
    else:
        if output_widget is None:
            output_widget = ipywidgets.Output()
            display(output_widget)
        # use lists to avoid globals
        done = [False]
        data = [None]

        def screenshot_handler(image_data):
            with output_widget:
                # print("data")
                # print(data)
                done[0] = True
                data[0] = image_data

        fig.on_screenshot(screenshot_handler)
        try:
            fig.screenshot(width=width, height=height, mime_type="image/" + format)
            t0 = time.time()
            timeout = False
            ipython = IPython.get_ipython()
            while (not done[0]) and not timeout:
                ipython.kernel.do_one_iteration()
                with output_widget:
                    time.sleep(0.05)
                    timeout = (time.time() - t0) > timeout_seconds
            with output_widget:
                if timeout and not done[0]:
                    raise ValueError("timed out, no image data returned")
        finally:
            with output_widget:
                fig.on_screenshot(screenshot_handler, remove=True)
        data = data[0]
    data = data[data.find(",") + 1 :]
    return base64.b64decode(data) 
Example #3
Source File: job.py    From QuLab with MIT License 5 votes vote down vote up
def __init__(self,
                 work,
                 args=(),
                 kw={},
                 max=100,
                 title=None,
                 tags=None,
                 comment='',
                 auto_save=None,
                 no_bar=False):
        title = work.__name__ if title is None else title
        self.ctx = contextvars.copy_context()
        self.parent = self.ctx.get(current_job, None)
        if auto_save is None:
            self.auto_save = True if self.parent is None else False
        else:
            self.auto_save = auto_save
        self.data = DataCollector(title, tags=tags, comment=comment, job=self)
        self.bar = ProgressBar(max=max, description=title, hiden=no_bar)
        self.out = widgets.Output()
        display(self.out)
        self.work_code = None
        code = compile(inspect.getsource(work),
                       f'defintion of {work.__name__}', 'single')
        for c in code.co_consts:
            if isinstance(c, type(code)) and c.co_name == work.__name__:
                self.work_code = c
                break
        self.work = work
        self.args = args
        self.kw = kw 
Example #4
Source File: widget.py    From captum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, **kwargs):
        super(CaptumInsights, self).__init__(**kwargs)
        self.insights_config = self.visualizer.get_insights_config()
        self.out = widgets.Output()
        with self.out:
            print("Captum Insights widget created.") 
Example #5
Source File: pubsub.py    From jupyter-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def subscribe(topic, msg_type, callback):
    """
    Subscribes to a specific topic in another thread, but redirects output!

    @param topic The topic
    @param msg_type The message type
    @param callback The callback

    @return Jupyter output widget
    """

    if subscriber_registry.get(topic):
        print("Removing previous callback, only one redirection possible right now", file=sys.stderr)
        subscriber_registry[topic].unregister()

    out = widgets.Output(layout={'border': '1px solid gray'})
    subscriber_registry[topic] = rospy.Subscriber(topic, msg_type, callback)
    output_registry[topic] = out

    btn = widgets.Button(description='Stop')

    def stop_start_subscriber(x):
        if output_registry.get(topic) is not None:
            subscriber_registry[topic].unregister()
            del output_registry[topic]
            btn.description = 'Start'
        else:
            output_registry[topic] = out
            subscriber_registry[topic] = rospy.Subscriber(topic, msg_type, callback)
            btn.description = 'Stop'

    btn.on_click(stop_start_subscriber)
    btns = widgets.HBox((btn, ))
    vbox = widgets.VBox((btns, out))
    return vbox 
Example #6
Source File: ipy.py    From jupyter-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def thread_cell(line, cell, local_ns=None):
        t = Thread(target=executor, args=(cell, globals(), sys._getframe(2).f_locals))
        out = widgets.Output(layout={'border': '1px solid gray'})
        output_registry[t.name] = out
        t.start()
        return out 
Example #7
Source File: plot.py    From meshplot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, data, view, s):
        if data == None:
            self.rows = []
            self.hboxes = []
        else:
            self.rows = data.rows

        if s[0] != 1 or s[1] != 1:
            if data == None: # Intialize subplot array
                cnt = 0
                for r in range(s[0]):
                    row = []
                    for c in range(s[1]):
                        row.append(Output())
                        cnt += 1
                    self.rows.append(row)

                for r in self.rows:
                    hbox = HBox(r)
                    if rendertype == "JUPYTER":
                        display(hbox)
                    self.hboxes.append(hbox)

            out = self.rows[int(s[2]/s[1])][s[2]%s[1]]
            if rendertype == "JUPYTER":
                with out:
                    display(view._renderer)
            self.rows[int(s[2]/s[1])][s[2]%s[1]] = view 
Example #8
Source File: replay.py    From jupyter-cadquery with Apache License 2.0 5 votes vote down vote up
def __init__(self, debug, cad_width, height):
        self.debug_output = Output()
        self.debug = debug
        self.cad_width = cad_width
        self.height = height
        self.view = None 
Example #9
Source File: pylab.py    From ipyvolume with MIT License 5 votes vote down vote up
def savefig(
    filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False
):
    """Save the figure to an image file.

    :param str filename: must have extension .png, .jpeg or .svg
    :param int width: the width of the image in pixels
    :param int height: the height of the image in pixels
    :type fig: ipyvolume.widgets.Figure or None
    :param fig: if None use the current figure
    :param float timeout_seconds: maximum time to wait for image data to return
    :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data
    :param bool headless: if True, use headless chrome to save figure
    :param bool devmode: if True, attempt to get index.js from local js/dist folder
    """
    __, ext = os.path.splitext(filename)
    format = ext[1:]
    assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
    with open(filename, "wb") as f:
        f.write(
            _screenshot_data(
                timeout_seconds=timeout_seconds,
                output_widget=output_widget,
                format=format,
                width=width,
                height=height,
                fig=fig,
                headless=headless,
                devmode=devmode,
            )
        ) 
Example #10
Source File: pylab.py    From ipyvolume with MIT License 5 votes vote down vote up
def screenshot(
    width=None,
    height=None,
    format="png",
    fig=None,
    timeout_seconds=10,
    output_widget=None,
    headless=False,
    devmode=False,
):
    """Save the figure to a PIL.Image object.

    :param int width: the width of the image in pixels
    :param int height: the height of the image in pixels
    :param format: format of output data (png, jpeg or svg)
    :type fig: ipyvolume.widgets.Figure or None
    :param fig: if None use the current figure
    :type timeout_seconds: int
    :param timeout_seconds: maximum time to wait for image data to return
    :type output_widget: ipywidgets.Output
    :param output_widget: a widget to use as a context manager for capturing the data
    :param bool headless: if True, use headless chrome to take screenshot
    :param bool devmode: if True, attempt to get index.js from local js/dist folder
    :return: PIL.Image

    """
    assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
    data = _screenshot_data(
        timeout_seconds=timeout_seconds,
        output_widget=output_widget,
        format=format,
        width=width,
        height=height,
        fig=fig,
        headless=headless,
        devmode=devmode,
    )
    f = StringIO(data)
    return PIL.Image.open(f) 
Example #11
Source File: plot.py    From K3D-jupyter with MIT License 5 votes vote down vote up
def display(self, **kwargs):
        """Show plot inside ipywidgets.Output()."""
        output = widgets.Output()

        with output:
            display(self, **kwargs)

        self.outputs.append(output)

        display(output) 
Example #12
Source File: pylab.py    From ipyvolume with MIT License 5 votes vote down vote up
def movie(
    f="movie.mp4",
    function=_change_azimuth_angle,
    fps=30,
    frames=30,
    endpoint=False,
    cmd_template_ffmpeg="ffmpeg -y -r {fps} -i {tempdir}/frame-%5d.png -vcodec h264 -pix_fmt yuv420p {filename}",
    cmd_template_gif="convert -delay {delay} {loop} {tempdir}/frame-*.png {filename}",
    gif_loop=0,
):
    """Create a movie out of many frames in e.g. mp4 or gif format.

    If the filename ends in `.gif`, `convert` is used to convert all frames to an animated gif using the `cmd_template_gif`
    template. Otherwise `ffmpeg is assumed to know the file format`.

    Example:

    >>> def set_angles(fig, i, fraction):
    >>>     fig.angley = fraction*np.pi*2
    >>> # 4 second movie, that rotates around the y axis
    >>> p3.movie('test2.gif', set_angles, fps=20, frames=20*4,
            endpoint=False)

    Note that in the example above we use `endpoint=False` to avoid to first and last frame to be the same

    :param str f: filename out output movie (e.g. 'movie.mp4' or 'movie.gif')
    :param function: function called before each frame with arguments (figure, framenr, fraction)
    :param fps: frames per seconds
    :param int frames: total number of frames
    :param bool endpoint: if fraction goes from [0, 1] (inclusive) or [0, 1) (endpoint=False is useful for loops/rotatations)
    :param str cmd_template_ffmpeg: template command when running ffmpeg (non-gif ending filenames)
    :param str cmd_template_gif: template command when running imagemagick's convert (if filename ends in .gif)
    :param gif_loop: None for no loop, otherwise the framenumber to go to after the last frame
    :return: the temp dir where the frames are stored
    """
    movie_filename = f
    tempdir = tempfile.mkdtemp()
    output = ipywidgets.Output()
    display(output)
    fig = gcf()
    for i in range(frames):
        with output:
            fraction = i / (frames - 1.0 if endpoint else frames)
            function(fig, i, fraction)
            frame_filename = os.path.join(tempdir, "frame-%05d.png" % i)
            savefig(frame_filename, output_widget=output)
    with output:
        if movie_filename.endswith(".gif"):
            if gif_loop is None:
                loop = ""
            else:
                loop = "-loop %d" % gif_loop
            delay = 100 / fps
            cmd = cmd_template_gif.format(delay=delay, loop=loop, tempdir=tempdir, filename=movie_filename)
        else:
            cmd = cmd_template_ffmpeg.format(fps=fps, tempdir=tempdir, filename=movie_filename)
        print(cmd)
        os.system(cmd)
    return tempdir 
Example #13
Source File: library.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def properties_widget(circuit: QuantumCircuit) -> wid.VBox:
    """Create a HTML table widget with header for a given quantum circuit.

    Args:
        circuit: Input quantum circuit.

    Returns:
        Output widget.
    """
    properties = wid.VBox(children=[property_label,
                                    circuit_data_table(circuit)],
                          layout=wid.Layout(width='40%',
                                            height='auto'))
    return properties 
Example #14
Source File: nbwidgets.py    From msticpy with MIT License 5 votes vote down vote up
def __init__(
        self,
        alerts: pd.DataFrame,
        action: Callable[..., None] = None,
        columns: List[str] = None,
        auto_display: bool = False,
    ):
        """
        Create a new instance of AlertSelector.

        Parameters
        ----------
        alerts : pd.DataFrame
            DataFrame of alerts.
        action : Callable[..., None], optional
            Optional function to execute for each selected alert.
            (the default is None)
        columns : List[str], optional
            Override the default column names to use from `alerts`
            (the default is ['StartTimeUtc', 'AlertName',
            'CompromisedEntity', 'SystemAlertId'])
        auto_display : bool, optional
            Whether to display on instantiation (the default is False)

        """
        self._w_output = widgets.Output(layout={"border": "1px solid black"})
        super().__init__(alerts, action, columns, auto_display) 
Example #15
Source File: transfer_function_editor.py    From K3D-jupyter with MIT License 5 votes vote down vote up
def display(self, **kwargs):
        output = widgets.Output()

        with output:
            display(self, **kwargs)

        self.outputs.append(output)

        display(output) 
Example #16
Source File: plot.py    From K3D-jupyter with MIT License 5 votes vote down vote up
def close(self):
        """Remove plot from all its ipywidgets.Output()-s."""
        for output in self.outputs:
            output.clear_output()

        self.outputs = [] 
Example #17
Source File: library.py    From qiskit-terra with Apache License 2.0 4 votes vote down vote up
def qasm_widget(circuit: QuantumCircuit) -> wid.VBox:
    """Generate a QASM widget with header for a quantum circuit.

    Args:
        circuit: Input quantum circuit.

    Returns:
        Output widget.

    Raises:
        ImportError: If pygments is not installed
    """
    if not HAS_PYGMENTS:
        raise ImportError("pygments>2.4 must be installed for to use the qasm "
                          'widget. To install run "pip install pygments"')
    qasm_code = circuit.qasm()
    code = pygments.highlight(qasm_code, OpenQASMLexer(),
                              HtmlFormatter())

    html_style = HtmlFormatter(style=QasmHTMLStyle).get_style_defs('.highlight')

    code_style = """
    <style>
     .highlight
                {
                    font-family: monospace;
                    font-size: 14px;
                    line-height: 1.7em;
                }
     .highlight .err { color: #000000; background-color: #FFFFFF }
    %s
    </style>
    """ % html_style

    out = wid.HTML(code_style+code,
                   layout=wid.Layout(max_height='500px',
                                     height='auto',
                                     overflow='scroll scroll'))

    out_label = wid.HTML("<p style='{}'>OpenQASM</p>".format(head_style),
                         layout=wid.Layout(margin='0px 0px 10px 0px'))

    qasm = wid.VBox(children=[out_label, out],
                    layout=wid.Layout(height='auto', max_height='500px', width='60%',
                                      margin='0px 0px 0px 20px'))

    qasm._code_length = len(qasm_code.split('\n'))
    return qasm 
Example #18
Source File: library.py    From qiskit-terra with Apache License 2.0 4 votes vote down vote up
def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML:
    """Create a HTML table widget for a given quantum circuit.

    Args:
        circuit: Input quantum circuit.

    Returns:
        Output widget.
    """

    ops = circuit.count_ops()

    num_nl = circuit.num_nonlocal_gates()

    html = "<table>"
    html += """<style>
table {
    font-family: "IBM Plex Sans", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
    border-left: 2px solid #212121;
}

th {
    text-align: left;
    padding: 5px 5px 5px 5px;
    width: 100%;
    background-color: #3700BE;
    color: #fff;
    font-size: 16px;
    border-left: 2px solid #3700BE;
}

td {
    font-family: "IBM Plex Mono", monospace;
    text-align: left;
    padding: 5px 5px 5px 5px;
    width: 100%;
    font-size: 13px;
    font-weight: medium;
}

tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
    html += "<tr><th>{}</th><th></tr>".format(circuit.name)
    html += "<tr><td>Width</td><td>{}</td></tr>".format(circuit.width())
    html += "<tr><td>Depth</td><td>{}</td></tr>".format(circuit.depth())
    html += "<tr><td>Total Gates</td><td>{}</td></tr>".format(sum(ops.values()))
    html += "<tr><td>Non-local Gates</td><td>{}</td></tr>".format(num_nl)
    html += "</table>"

    out_wid = wid.HTML(html)
    return out_wid 
Example #19
Source File: nbwidgets.py    From msticpy with MIT License 4 votes vote down vote up
def __init__(
        self,
        description: str = "Select an item",
        item_list: List[str] = None,
        action: Callable[..., None] = None,
        item_dict: Mapping[str, str] = None,
        auto_display: bool = False,
        height: str = "100px",
        width: str = "50%",
        display_filter: bool = True,
    ):
        """
        Select an item from a list or dict.

        Parameters
        ----------
        description : str, optional
            The widget label to display.
            (the default is 'Select an item')
        item_list : List[str], optional
            A `list` of items to select from (the default is None)
        item_dict : Mapping[str, str], optional
            A `dict` of items to select from. When using `item_dict`
            the keys are displayed as the selectable items and value
            corresponding to the selected key is set as the `value`
            property.
            (the default is None)
        action : Callable[..., None], optional
            function to call when item selected (passed a single
            parameter - the value of the currently selected item)
            (the default is None)
        auto_display : bool, optional
            Whether to display on instantiation (the default is False)
        height : str, optional
            Selection list height (the default is '100px')
        width : str, optional
            Selection list width (the default is '50%')
        display_filter : bool, optional
            Whether to display item filter (the default is True)

        """
        self._w_output = widgets.Output(layout={"border": "1px solid black"})

        super().__init__(
            description=description,
            item_list=item_list,
            item_dict=item_dict,
            action=action,
            auto_display=auto_display,
            height=height,
            width=width,
            display_filter=display_filter,
        ) 
Example #20
Source File: api.py    From captum with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _serve_colab(self, blocking=False, debug=False, port=None):
        from IPython.display import display, HTML
        from captum.insights.server import start_server
        import ipywidgets as widgets

        # TODO: Output widget only captures beginning of server logs. It seems
        # the context manager isn't respected when the web server is run on a
        # separate thread. We should fix to display entirety of the logs
        out = widgets.Output()
        with out:
            port = start_server(self, blocking=blocking, debug=debug, _port=port)
        shell = """
            <div id="root"></div>
            <script>
            (function() {
              document.querySelector("base").href = "http://localhost:%PORT%";
              function reloadScriptsAndCSS(root) {
                // Referencing TensorBoard's method for reloading scripts,
                // we remove and reinsert each script
                for (const script of root.querySelectorAll("script")) {
                  const newScript = document.createElement("script");
                  newScript.type = script.type;
                  if (script.src) {
                    newScript.src = script.src;
                  }
                  if (script.textContent) {
                    newScript.textContent = script.textContent;
                  }
                  root.appendChild(newScript);
                  script.remove();
                }
                // A similar method is used to reload styles
                for (const link of root.querySelectorAll("link")) {
                  const newLink = document.createElement("link");
                  newLink.rel = link.rel;
                  newLink.href = link.href;
                  document.querySelector("head").appendChild(newLink);
                  link.remove();
                }
              }
              const root = document.getElementById("root");
              fetch(".")
                .then(x => x.text())
                .then(html => void (root.innerHTML = html))
                .then(() => reloadScriptsAndCSS(root));
            })();
            </script>
        """.replace(
            "%PORT%", str(port)
        )
        html = HTML(shell)
        display(html)
        display(out) 
Example #21
Source File: sankey_data.py    From floweaver with MIT License 4 votes vote down vote up
def to_widget(self, width=700, height=500, margins=None,
                  align_link_types=False, link_label_format='', 
                  link_label_min_width=5, debugging=False):

        if SankeyWidget is None:
            raise RuntimeError('ipysankeywidget is required')

        if margins is None:
            margins = {
                'top': 25,
                'bottom': 10,
                'left': 130,
                'right': 130,
            }

        value = self.to_json(format='widget')
        widget = SankeyWidget(nodes=value['nodes'],
                              links=value['links'],
                              order=value['order'],
                              groups=value['groups'],
                              align_link_types=align_link_types,
                              linkLabelFormat=link_label_format,
                              linkLabelMinWidth=link_label_min_width,
                              layout=Layout(width=str(width), height=str(height)),
                              margins=margins)

        if debugging:
            output = Output()
            def callback(_, d):
                with output:
                    clear_output()
                if not d:
                    return
                link = [l for l in self.links
                        if l.source == d['source']
                        and l.target == d['target']
                        and l.type == d['type']]
                assert len(link) == 1
                link = link[0]
                with output:
                    display('Flows in dataset contributing to this link:')
                    if self.dataset:
                        display(self.dataset._table.loc[link.original_flows])
                    else:
                        display(link.original_flows)
            widget.on_link_clicked(callback)
            return VBox([widget, output])
        else:
            return widget