Python IPython.display.clear_output() Examples

The following are 30 code examples of IPython.display.clear_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 IPython.display , or try the search function .
Example #1
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def plot(self, show=True):
        kwargs = {
            e["encoding"]: _get_plot_command(e) for e in self.settings["encodings"]
        }
        kwargs = {k: v for k, v in kwargs.items() if v is not None}

        mark_opts = {k: v for k, v in self.settings["mark"].items()}
        mark = mark_opts.pop("mark")
        Chart_mark = getattr(altair.Chart(self.df), mark)
        self.chart = Chart_mark(**mark_opts).encode(**kwargs)
        if show and self.show:
            clear_output()
            display("Updating...")
            with io.StringIO() as f:
                self.chart.save(f, format="svg")
                f.seek(0)
                html = f.read()
            clear_output()
            display(self.controller)
            display(SVG(html)) 
Example #2
Source File: stdinput.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def get_display_progress_fn(showProgress):
    """
    Create and return a progress-displaying function if `showProgress == True`
    and it's run within an interactive environment.
    """

    def _is_interactive():
        import __main__ as main
        return not hasattr(main, '__file__')

    if _is_interactive() and showProgress:
        try:
            from IPython.display import clear_output

            def _display_progress(i, N, filename):
                _time.sleep(0.001); clear_output()
                print("Loading %s: %.0f%%" % (filename, 100.0 * float(i) / float(N)))
                _sys.stdout.flush()
        except:
            def _display_progress(i, N, f): pass
    else:
        def _display_progress(i, N, f): pass

    return _display_progress 
Example #3
Source File: Reinforcement Learning DQN.py    From ML_CIA with MIT License 6 votes vote down vote up
def plot_durations():
    plt.figure(2)
    plt.clf()
    durations_t = torch.tensor(episode_durations, dtype=torch.float)
    plt.title('Training...')
    plt.xlabel('Episode')
    plt.ylabel('Duration')
    plt.plot(durations_t.numpy())
    # Take 100 episode averages and plot them too
    if len(durations_t) >= 100:
        means = durations_t.unfold(0, 100, 1).mean(1).view(-1)
        means = torch.cat((torch.zeros(99), means))
        plt.plot(means.numpy())

    plt.pause(0.001)
    if is_ipython:
        display.clear_output(wait=True)
        display.display(plt.gcf())

#%% Training loop 
Example #4
Source File: animation.py    From drawSvg with MIT License 6 votes vote down vote up
def __init__(self, draw_func=None, out_file=None,
                 jupyter=False, pause=False, clear=True, delay=0, disable=False,
                 video_args=None, _patch_delay=0.05):
        self.jupyter = jupyter
        self.disable = disable
        if self.jupyter and not self.disable:
            from IPython import display
            self._jupyter_clear_output = display.clear_output
            self._jupyter_display = display.display
            callback = self.draw_jupyter_frame
        else:
            callback = None
        self.anim = Animation(draw_func, callback=callback)
        self.out_file = out_file
        self.pause = pause
        self.clear = clear
        self.delay = delay
        if video_args is None:
            video_args = {}
        self.video_args = video_args
        self._patch_delay = _patch_delay 
Example #5
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def interactive_output(f, controls):
    """Connect widget controls to a function.

    This function does not generate a user interface for the widgets (unlike `interact`).
    This enables customisation of the widget user interface layout.
    The user interface layout must be defined and displayed manually.
    """

    out = Output()
    def observer(change):
        kwargs = {k:v.value for k,v in controls.items()}
        show_inline_matplotlib_plots()
        with out:
            clear_output(wait=True)
            f(**kwargs)
            show_inline_matplotlib_plots()
    for k,w in controls.items():
        w.observe(observer, 'value')
    show_inline_matplotlib_plots()
    observer(None)
    return out 
Example #6
Source File: interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def interactive_output(f, controls):
    """Connect widget controls to a function.

    This function does not generate a user interface for the widgets (unlike `interact`).
    This enables customisation of the widget user interface layout.
    The user interface layout must be defined and displayed manually.
    """

    out = Output()
    def observer(change):
        kwargs = {k:v.value for k,v in controls.items()}
        show_inline_matplotlib_plots()
        with out:
            clear_output(wait=True)
            f(**kwargs)
            show_inline_matplotlib_plots()
    for k,w in controls.items():
        w.observe(observer, 'value')
    show_inline_matplotlib_plots()
    observer(None)
    return out 
Example #7
Source File: widget_output.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def capture(self, clear_output=False, *clear_args, **clear_kwargs):
        """
        Decorator to capture the stdout and stderr of a function.

        Parameters
        ----------

        clear_output: bool
            If True, clear the content of the output widget at every
            new function call. Default: False

        wait: bool
            If True, wait to clear the output until new output is
            available to replace it. This is only used if clear_output
            is also True.
            Default: False
        """
        def capture_decorator(func):
            @wraps(func)
            def inner(*args, **kwargs):
                if clear_output:
                    self.clear_output(*clear_args, **clear_kwargs)
                with self:
                    return func(*args, **kwargs)
            return inner
        return capture_decorator 
Example #8
Source File: utils.py    From keras-tuner with Apache License 2.0 5 votes vote down vote up
def try_clear():
    if IS_NOTEBOOK:
        display.clear_output()
    else:
        print() 
Example #9
Source File: interact.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def on_destroy_all_windows(self):
        pass
        #clear_output() 
Example #10
Source File: interact.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def on_create_window (self, wnd_name):
        pass
        #clear_output() 
Example #11
Source File: widget_base.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def show_ui_ct():
    print('正在初始化界面元素,请稍后...')
    from abupy import ABuStrUtil
    go_on = True

    try:
        if ABuStrUtil.str_is_cn(str(ABuStrUtil.__file__)):
            # 检测到运行环境路径中含有中文,严重错误,将出错,使用中文警告
            msg = u'严重错误!当前运行环境下有中文路径,abu将无法正常运行!请不要使用中文路径名称, 当前环境为{}'.format(
                ABuStrUtil.to_unicode(str(ABuStrUtil.__file__)))
            import logging
            logging.info(msg)
            go_on = False
    except:
        # 如果是其它编码的字符路径会进到这里
        import logging
        msg = 'error!non English characters in the current running environment,abu will not work properly!'
        logging.info(msg)
        go_on = False
    yield go_on

    if go_on:
        from IPython.display import clear_output
        clear_output()
        # import time
        # 这里sleep(0.3)防止有些版本clear_output把下面要展示的清除了,也不能使用clear_output的wait参数,有些浏览器卡死
        # time.sleep(0.3) 
Example #12
Source File: widget_output.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clear_output(self, *pargs, **kwargs):
        """
        Clear the content of the output widget.

        Parameters
        ----------

        wait: bool
            If True, wait to clear the output until new output is
            available to replace it. Default: False
        """
        with self:
            clear_output(*pargs, **kwargs)

    # PY3: Force passing clear_output and clear_kwargs as kwargs 
Example #13
Source File: utilities.py    From Separate_to_Adapt with MIT License 5 votes vote down vote up
def __init__(self, log_dir, clear=False):
        if clear:
            os.system('rm %s -r'%log_dir)
        tl.files.exists_or_mkdir(log_dir)
        self.writer = tf.summary.FileWriter(log_dir)
        self.step = 0
        self.log_dir = log_dir 
Example #14
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update(self, *args):
        """
        Call the interact function and update the output widget with
        the result of the function call.

        Parameters
        ----------
        *args : ignored
            Required for this method to be used as traitlets callback.
        """
        self.kwargs = {}
        if self.manual:
            self.manual_button.disabled = True
        try:
            show_inline_matplotlib_plots()
            with self.out:
                if self.clear_output:
                    clear_output(wait=True)
                for widget in self.kwargs_widgets:
                    value = widget.get_interact_value()
                    self.kwargs[widget._kwarg] = value
                self.result = self.f(**self.kwargs)
                show_inline_matplotlib_plots()
                if self.auto_display and self.result is not None:
                    display(self.result)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                self.log.warn("Exception in interact callback: %s", e, exc_info=True)
            else:
                ip.showtraceback()
        finally:
            if self.manual:
                self.manual_button.disabled = False

    # Find abbreviations 
Example #15
Source File: plot_utils.py    From RotateNetworks with MIT License 5 votes vote down vote up
def plot_test_acc(plot_handles):
    plt.legend(handles=plot_handles, loc="center right")
    plt.xlabel("Iterations")
    plt.ylabel("Test Accuracy")
    plt.ylim(0,1)
    display.display(plt.gcf())
    display.clear_output(wait=True) 
Example #16
Source File: utilities.py    From Transferable-Adversarial-Training with MIT License 5 votes vote down vote up
def clear_output():
    def clear():
        return
    try:
        from IPython.display import clear_output as clear
    except ImportError as e:
        pass
    import os
    def cls():
        os.system('cls' if os.name == 'nt' else 'clear')

    clear()
    cls() 
Example #17
Source File: utilities.py    From Transferable-Adversarial-Training with MIT License 5 votes vote down vote up
def __init__(self, log_dir, clear=False):
        if clear:
            os.system('rm %s -r'%log_dir)
        tl.files.exists_or_mkdir(log_dir)
        self.writer = tf.summary.FileWriter(log_dir)
        self.step = 0
        self.log_dir = log_dir 
Example #18
Source File: ontologysearch.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def init_display(self):
        # clear_output()
        self.wResults.visible = False
        self.wSearchButton.visible = True 
Example #19
Source File: utilities.py    From Separate_to_Adapt with MIT License 5 votes vote down vote up
def clear_output():
    def clear():
        return
    try:
        from IPython.display import clear_output as clear
    except ImportError as e:
        pass
    import os
    def cls():
        os.system('cls' if os.name == 'nt' else 'clear')

    clear()
    cls() 
Example #20
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _add_dim(self, button):
        i = len(self.controller.children) - 1
        encoding = _get_encodings()[i]
        shelf = self._create_shelf(i=i)
        kids = self.controller.children
        teens = list(kids)[:-1] + [shelf] + [list(kids)[-1]]
        self.controller.children = teens

        # clear_output()
        # display(self.controller)
        self.settings["encodings"] += [{"encoding": encoding}]
        self.plot(self.settings) 
Example #21
Source File: interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def update(self, *args):
        """
        Call the interact function and update the output widget with
        the result of the function call.

        Parameters
        ----------
        *args : ignored
            Required for this method to be used as traitlets callback.
        """
        self.kwargs = {}
        if self.manual:
            self.manual_button.disabled = True
        try:
            show_inline_matplotlib_plots()
            with self.out:
                if self.clear_output:
                    clear_output(wait=True)
                for widget in self.kwargs_widgets:
                    value = widget.get_interact_value()
                    self.kwargs[widget._kwarg] = value
                self.result = self.f(**self.kwargs)
                show_inline_matplotlib_plots()
                if self.auto_display and self.result is not None:
                    display(self.result)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                self.log.warn("Exception in interact callback: %s", e, exc_info=True)
            else:
                ip.showtraceback()
        finally:
            if self.manual:
                self.manual_button.disabled = False

    # Find abbreviations 
Example #22
Source File: widget_output.py    From pySINDy with MIT License 5 votes vote down vote up
def capture(self, clear_output=False, *clear_args, **clear_kwargs):
        """
        Decorator to capture the stdout and stderr of a function.

        Parameters
        ----------

        clear_output: bool
            If True, clear the content of the output widget at every
            new function call. Default: False

        wait: bool
            If True, wait to clear the output until new output is
            available to replace it. This is only used if clear_output
            is also True.
            Default: False
        """
        def capture_decorator(func):
            @wraps(func)
            def inner(*args, **kwargs):
                if clear_output:
                    self.clear_output(*clear_args, **clear_kwargs)
                with self:
                    return func(*args, **kwargs)
            return inner
        return capture_decorator 
Example #23
Source File: widget_output.py    From pySINDy with MIT License 5 votes vote down vote up
def clear_output(self, *pargs, **kwargs):
        """
        Clear the content of the output widget.

        Parameters
        ----------

        wait: bool
            If True, wait to clear the output until new output is
            available to replace it. Default: False
        """
        with self:
            clear_output(*pargs, **kwargs)

    # PY3: Force passing clear_output and clear_kwargs as kwargs 
Example #24
Source File: experiment.py    From pymeasure with MIT License 5 votes vote down vote up
def update_plot(self):
        """Update the plots in the plots list with new data from the experiment.data
        pandas dataframe."""
        try:
            tasks = []
            self.data
            for plot in self.plots:
                ax = plot['ax']
                if plot['type'] == 'plot':
                    x, y = plot['args'][0], plot['args'][1]
                    if type(y) == str:
                        y = [y]
                    for yname, line in zip(y, ax.lines):
                        self.update_line(ax, line, x, yname)
                if plot['type'] == 'pcolor':
                    x, y, z = plot['x'], plot['y'], plot['z']
                    update_pcolor(ax, x, y, z)

            display.clear_output(wait=True)
            display.display(*self.figs)
            time.sleep(0.1)
        except KeyboardInterrupt:
            display.clear_output(wait=True)
            display.display(*self.figs)
            self._user_interrupt = True 
Example #25
Source File: experiment.py    From pymeasure with MIT License 5 votes vote down vote up
def plot_live(self, *args, **kwargs):
        """Live plotting loop for jupyter notebook, which automatically updates
        (an) in-line matplotlib graph(s). Will create a new plot as specified by input
        arguments, or will update (an) existing plot(s)."""
        if self.wait_for_data():
            if not (self.plots):
                self.plot(*args, **kwargs)
            while not self.worker.should_stop():
                self.update_plot()
            display.clear_output(wait=True)
            if self.worker.is_alive():
                self.worker.terminate()
            self.scribe.stop() 
Example #26
Source File: __init__.py    From paramnb with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update_trait(self, p_name, p_value, widget=None):
        p_obj = self.parameterized.params(p_name)
        widget = self._widgets[p_name] if widget is None else widget
        if isinstance(p_value, tuple):
            p_value, size = p_value

            if isinstance(size, tuple) and len(size) == 2:
                if isinstance(widget, ipywidgets.Image):
                    widget.width = size[0]
                    widget.height = size[1]
                else:
                    widget.layout.min_width = '%dpx' % size[0]
                    widget.layout.min_height = '%dpx' % size[1]

        if isinstance(widget, Output):
            if isinstance(p_obj, HTMLView) and p_value:
                p_value = HTML(p_value)
            with widget:
                # clear_output required for JLab support
                # in future handle.update(p_value) should be sufficient
                handle = self._display_handles.get(p_name)
                if handle:
                    clear_output(wait=True)
                    handle.display(p_value)
                else:
                    handle = display(p_value, display_id=p_name+self._id)
                    self._display_handles[p_name] = handle
        else:
            widget.value = p_value 
Example #27
Source File: inference.py    From ffn with Apache License 2.0 5 votes vote down vote up
def UpdateFromPIL(self, new_img):
    from io import BytesIO
    from IPython import display
    display.clear_output(wait=True)
    image = BytesIO()
    new_img.save(image, format='png')
    display.display(display.Image(image.getvalue())) 
Example #28
Source File: ryutils.py    From pyradi with MIT License 4 votes vote down vote up
def update_progress(progress, bar_length=20):
    """Simple text-based progress bar for Jupyter notebooks.

    Note that clear_output, and hence this function wipes the entire cell output, 
    including previous output and widgets.

    Usage:

    import pyradi.ryutils as ryutils
    import time
    print('before')
    #Replace this with a real computation
    number_of_elements = 100
    for i in range(number_of_elements):
        time.sleep(0.1) 
        # progress must be a float between 0 and 1
        ryutils.update_progress((i+1) / number_of_elements,bar_length=40)
    print('after')

    source:

    https://mikulskibartosz.name/how-to-display-a-progress-bar-in-jupyter-notebook-47bd4c2944bf
    https://ipython.org/ipython-doc/3/api/generated/IPython.display.html#IPython.display.clear_output
    Wait to clear the output until new output is available to replace it.
    """
    from IPython.display import clear_output
    
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
    if progress < 0:
        progress = 0
    if progress >= 1:
        progress = 1
    block = int(round(bar_length * progress))
    clear_output(wait = True)
    text = "Progress: [{0}] {1:.1f}%".format( "#" * block + "-" * (bar_length - block), progress * 100)
    print(text)


##############################################################################
## 
Example #29
Source File: interaction.py    From pySINDy with MIT License 4 votes vote down vote up
def __init__(self, __interact_f, __options={}, **kwargs):
        VBox.__init__(self, _dom_classes=['widget-interact'])
        self.result = None
        self.args = []
        self.kwargs = {}

        self.f = f = __interact_f
        self.clear_output = kwargs.pop('clear_output', True)
        self.manual = __options.get("manual", False)
        self.manual_name = __options.get("manual_name", "Run Interact")
        self.auto_display = __options.get("auto_display", False)

        new_kwargs = self.find_abbreviations(kwargs)
        # Before we proceed, let's make sure that the user has passed a set of args+kwargs
        # that will lead to a valid call of the function. This protects against unspecified
        # and doubly-specified arguments.
        try:
            check_argspec(f)
        except TypeError:
            # if we can't inspect, we can't validate
            pass
        else:
            getcallargs(f, **{n:v for n,v,_ in new_kwargs})
        # Now build the widgets from the abbreviations.
        self.kwargs_widgets = self.widgets_from_abbreviations(new_kwargs)

        # This has to be done as an assignment, not using self.children.append,
        # so that traitlets notices the update. We skip any objects (such as fixed) that
        # are not DOMWidgets.
        c = [w for w in self.kwargs_widgets if isinstance(w, DOMWidget)]

        # If we are only to run the function on demand, add a button to request this.
        if self.manual:
            self.manual_button = Button(description=self.manual_name)
            c.append(self.manual_button)

        self.out = Output()
        c.append(self.out)
        self.children = c

        # Wire up the widgets
        # If we are doing manual running, the callback is only triggered by the button
        # Otherwise, it is triggered for every trait change received
        # On-demand running also suppresses running the function with the initial parameters
        if self.manual:
            self.manual_button.on_click(self.update)

            # Also register input handlers on text areas, so the user can hit return to
            # invoke execution.
            for w in self.kwargs_widgets:
                if isinstance(w, Text):
                    w.on_submit(self.update)
        else:
            for widget in self.kwargs_widgets:
                widget.observe(self.update, names='value')

            self.on_displayed(self.update)

    # Callback function 
Example #30
Source File: interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, __interact_f, __options={}, **kwargs):
        VBox.__init__(self, _dom_classes=['widget-interact'])
        self.result = None
        self.args = []
        self.kwargs = {}

        self.f = f = __interact_f
        self.clear_output = kwargs.pop('clear_output', True)
        self.manual = __options.get("manual", False)
        self.manual_name = __options.get("manual_name", "Run Interact")
        self.auto_display = __options.get("auto_display", False)

        new_kwargs = self.find_abbreviations(kwargs)
        # Before we proceed, let's make sure that the user has passed a set of args+kwargs
        # that will lead to a valid call of the function. This protects against unspecified
        # and doubly-specified arguments.
        try:
            check_argspec(f)
        except TypeError:
            # if we can't inspect, we can't validate
            pass
        else:
            getcallargs(f, **{n:v for n,v,_ in new_kwargs})
        # Now build the widgets from the abbreviations.
        self.kwargs_widgets = self.widgets_from_abbreviations(new_kwargs)

        # This has to be done as an assignment, not using self.children.append,
        # so that traitlets notices the update. We skip any objects (such as fixed) that
        # are not DOMWidgets.
        c = [w for w in self.kwargs_widgets if isinstance(w, DOMWidget)]

        # If we are only to run the function on demand, add a button to request this.
        if self.manual:
            self.manual_button = Button(description=self.manual_name)
            c.append(self.manual_button)

        self.out = Output()
        c.append(self.out)
        self.children = c

        # Wire up the widgets
        # If we are doing manual running, the callback is only triggered by the button
        # Otherwise, it is triggered for every trait change received
        # On-demand running also suppresses running the function with the initial parameters
        if self.manual:
            self.manual_button.on_click(self.update)

            # Also register input handlers on text areas, so the user can hit return to
            # invoke execution.
            for w in self.kwargs_widgets:
                if isinstance(w, Text):
                    w.on_submit(self.update)
        else:
            for widget in self.kwargs_widgets:
                widget.observe(self.update, names='value')

            self.on_displayed(self.update)

    # Callback function