Example #1
0
def TrajectorySliderView(traj, frame=0, **kwargs):
    """IPython notebook widget for viewing trajectories in the browser with
    an interactiver slider.

    Parameters
    ----------
    traj : Trajectory
        Trajectory for which you want the viewer.
    frame : int, default=0
        Frame to set the slider to by default
    kwargs : string
        See TrajectoryView for all available options.

    See Also
    --------
    TrajectoryView: IPython notebook widget for displaying trajectories in the
    browser with WebGL.
    """
    widget = TrajectoryView(traj, frame=frame, **kwargs)

    def slide(frame):
        widget.frame = frame

    s = IntSlider(min=0, max=traj.n_frames - 1, value=frame)
    slider = interactive(slide, frame=s)
    
    container = Box()
    container.children = [widget, slider] 

    return container
Example #2
0
File: gui.py Project: Acellera/htmd
def show_progressbar(bar, show_eta=True, force=False):
    """ shows given bar either using an ipython widget, if in
    interactive session or simply use the string format of it and print it
    to stdout.

    Parameters
    ----------
    bar : instance of pyemma.util.progressbar.ProgressBar
    show_eta : bool (optional)

    """
    currtime = time.time()
    if bar.lastupdate is not None and not force:
        dtlastupdate = currtime - bar.lastupdate
    else:
        dtlastupdate = 9999
    #if not (str(config['show_progress_bars']) == 'True' and __is_tty_or_interactive_session() and dtlastupdate > 0.5):
    if not (__is_tty_or_interactive_session() and dtlastupdate > 0.5):
        return
    bar.lastupdate = currtime

    # note: this check ensures we have IPython.display and so on.
    if ipython_notebook_session:
        # create IPython widgets on first call
        if not hasattr(bar, 'widget'):
            box = Box()
            text = Text()
            progress_widget = IntProgress()

            box.children = [text, progress_widget]
            bar.widget = box
            widget = box

            # make it visible once
            display(box)

            # update css for a more compact view
            progress_widget._css = [
                ("div", "margin-top", "0px")
            ]
            progress_widget.height = "8px"
        else:
            widget = bar.widget

        # update widgets slider value and description text
        desc = bar.description
        desc += ':\t({}/{})'.format(bar.numerator, bar.denominator)
        if show_eta:
            desc += ':\tETA:' + bar._generate_eta(bar._eta.eta_seconds)
        assert isinstance(widget.children[0], Text)
        assert isinstance(widget.children[1], IntProgress)
        widget.children[0].placeholder = desc
        widget.children[1].value = bar.percent
    else:
        sys.stdout.write("\r" + str(bar))
        sys.stdout.flush()
Example #3
0
def show_progressbar(bar, show_eta=True, force=False):
    """ shows given bar either using an ipython widget, if in
    interactive session or simply use the string format of it and print it
    to stdout.

    Parameters
    ----------
    bar : instance of pyemma.util.progressbar.ProgressBar
    show_eta : bool (optional)

    """
    currtime = time.time()
    if bar.lastupdate is not None and not force:
        dtlastupdate = currtime - bar.lastupdate
    else:
        dtlastupdate = 9999
    #if not (str(config['show_progress_bars']) == 'True' and __is_tty_or_interactive_session() and dtlastupdate > 0.5):
    if not (__is_tty_or_interactive_session() and dtlastupdate > 0.5):
        return
    bar.lastupdate = currtime

    # note: this check ensures we have IPython.display and so on.
    if ipython_notebook_session:
        # create IPython widgets on first call
        if not hasattr(bar, 'widget'):
            box = Box()
            text = Text()
            progress_widget = IntProgress()

            box.children = [text, progress_widget]
            bar.widget = box
            widget = box

            # make it visible once
            display(box)

            # update css for a more compact view
            progress_widget._css = [("div", "margin-top", "0px")]
            progress_widget.height = "8px"
        else:
            widget = bar.widget

        # update widgets slider value and description text
        desc = bar.description
        desc += ':\t({}/{})'.format(bar.numerator, bar.denominator)
        if show_eta:
            desc += ':\tETA:' + bar._generate_eta(bar._eta.eta_seconds)
        assert isinstance(widget.children[0], Text)
        assert isinstance(widget.children[1], IntProgress)
        widget.children[0].placeholder = desc
        widget.children[1].value = bar.percent
    else:
        sys.stdout.write("\r" + str(bar))
        sys.stdout.flush()
Example #4
0
def show_progressbar(bar, show_eta=True):
    """ shows given bar either using an ipython widget, if in
    interactive session or simply use the string format of it and print it
    to stdout.

    Parameters
    ----------
    bar : instance of pyemma.util.progressbar.ProgressBar
    show_eta : bool (optional)

    """
    if not (str(config['show_progress_bars']) == 'True' and
            is_interactive_session):
        return

    # note: this check ensures we have IPython.display and so on.
    if ipython_notebook_session and isinstance(bar, ProgressBar):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', DeprecationWarning)
            # create IPython widgets on first call
            if not hasattr(bar, 'widget'):

                box = Box()
                text = Text()
                progress_widget = IntProgress()

                box.children = [text, progress_widget]
                bar.widget = box
                widget = box

                # make it visible once
                display(box)
                # box.visible=True

                # update css for a more compact view
                progress_widget._css = [
                    ("div", "margin-top", "0px")
                ]
                progress_widget.height = "8px"
            else:
                widget = bar.widget

            # update widgets slider value and description text
            desc = bar.description
            if show_eta:
                desc += ':\tETA:' + bar._generate_eta(bar._eta.eta_seconds)
            assert isinstance(widget.children[0], Text)
            assert isinstance(widget.children[1], IntProgress)
            widget.children[0].placeholder = desc
            widget.children[1].value = bar.percent
    else:
        sys.stdout.write("\r" + str(bar))
        sys.stdout.flush()
Example #5
0
 def _repr_html_(self):
     box = Box()
     box.children = [self.value_text, self.vary_checkbox,
                     self.min_text, self.min_checkbox,
                     self.max_text, self.max_checkbox]
     display(box)
     box.add_class('hbox')
Example #6
0
 def _repr_html_(self):
     display(self.models_menu)
     button_box = Box()
     button_box.children = [self.fit_button, self.guess_button]
     display(button_box)
     button_box.add_class('hbox')
     for pw in self.param_widgets:
         display(pw)
     self.plot()
Example #7
0
def interactive(__interact_f, **kwargs):
    """Build a group of widgets to interact with a function."""
    f = __interact_f
    co = kwargs.pop('clear_output', True)
    kwargs_widgets = []
    container = Box()
    container.result = None
    container.args = []
    container.kwargs = dict()
    kwargs = kwargs.copy()

    new_kwargs = _find_abbreviations(f, 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.
    getcallargs(f, **{n: v for n, v, _ in new_kwargs})
    # Now build the widgets from the abbreviations.
    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))

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

    # Build the callback
    def call_f(name, old, new):
        container.kwargs = {}
        for widget in kwargs_widgets:
            value = widget.value
            container.kwargs[widget.description] = value
        if co:
            clear_output(wait=True)
        try:
            container.result = f(**container.kwargs)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                container.log.warn("Exception in interact callback: %s",
                                   e,
                                   exc_info=True)
            else:
                ip.showtraceback()

    # Wire up the widgets
    for widget in kwargs_widgets:
        widget.on_trait_change(call_f, 'value')

    container.on_displayed(lambda _: call_f(None, None, None))

    return container
Example #8
0
def interactive(__interact_f, **kwargs):
    """Build a group of widgets to interact with a function."""
    f = __interact_f
    co = kwargs.pop('clear_output', True)
    kwargs_widgets = []
    container = Box()
    container.result = None
    container.args = []
    container.kwargs = dict()
    kwargs = kwargs.copy()

    new_kwargs = _find_abbreviations(f, 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.
    getcallargs(f, **{n:v for n,v,_ in new_kwargs})
    # Now build the widgets from the abbreviations.
    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))

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

    # Build the callback
    def call_f(name, old, new):
        container.kwargs = {}
        for widget in kwargs_widgets:
            value = widget.value
            container.kwargs[widget.description] = value
        if co:
            clear_output(wait=True)
        try:
            container.result = f(**container.kwargs)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                container.log.warn("Exception in interact callback: %s", e, exc_info=True)
            else:
                ip.showtraceback()

    # Wire up the widgets
    for widget in kwargs_widgets:
        widget.on_trait_change(call_f, 'value')

    container.on_displayed(lambda _: call_f(None, None, None))

    return container
Example #9
0
def __attached_to_ipy_notebook():
    # first determine which IPython version we have (eg. ipywidgets or ipy3 deprecated,
    # then try to instanciate a widget to determine if we're interactive (raises, if not).
    ipy_widget_version = __ipy_widget_version()

    if ipy_widget_version is None:
        return False

    if ipy_widget_version == 4:
        from ipywidgets import Box
    elif ipy_widget_version == 3:
        from IPython.html.widgets import Box
    # FIXME: this unfortunately does not raise if frontend is QT...
    try:
        Box()
    except:
        return False
    else:
        return True
Example #10
0
def interactive(__interact_f, **kwargs):
    """
    Builds a group of interactive widgets tied to a function and places the
    group into a Box container.

    Returns
    -------
    container : a Box instance containing multiple widgets

    Parameters
    ----------
    __interact_f : function
        The function to which the interactive widgets are tied. The **kwargs
        should match the function signature.
    **kwargs : various, optional
        An interactive widget is created for each keyword argument that is a
        valid widget abbreviation.
    """
    f = __interact_f
    co = kwargs.pop('clear_output', True)
    manual = kwargs.pop('__manual', False)
    kwargs_widgets = []
    container = Box(_dom_classes=['widget-interact'])
    container.result = None
    container.args = []
    container.kwargs = dict()
    kwargs = kwargs.copy()

    new_kwargs = _find_abbreviations(f, 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.
    getcallargs(f, **{n: v for n, v, _ in new_kwargs})
    # Now build the widgets from the abbreviations.
    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))

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

    # If we are only to run the function on demand, add a button to request this
    if manual:
        manual_button = Button(description="Run %s" % f.__name__)
        c.append(manual_button)
    container.children = c

    # Build the callback
    def call_f(name=None, old=None, new=None):
        container.kwargs = {}
        for widget in kwargs_widgets:
            value = widget.value
            container.kwargs[widget._kwarg] = value
        if co:
            clear_output(wait=True)
        if manual:
            manual_button.disabled = True
        try:
            container.result = f(**container.kwargs)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                container.log.warn("Exception in interact callback: %s",
                                   e,
                                   exc_info=True)
            else:
                ip.showtraceback()
        finally:
            if manual:
                manual_button.disabled = False

    # 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 manual:
        manual_button.on_click(call_f)
    else:
        for widget in kwargs_widgets:
            widget.on_trait_change(call_f, 'value')

        container.on_displayed(lambda _: call_f(None, None, None))

    return container
Example #11
0
def interactive(__interact_f, **kwargs):
    """Build a group of widgets to interact with a function."""
    f = __interact_f
    co = kwargs.pop('clear_output', True)
    manual = kwargs.pop('__manual', False)
    kwargs_widgets = []
    container = Box()
    container.result = None
    container.args = []
    container.kwargs = dict()
    kwargs = kwargs.copy()

    new_kwargs = _find_abbreviations(f, 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.
    getcallargs(f, **{n:v for n,v,_ in new_kwargs})
    # Now build the widgets from the abbreviations.
    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))

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

    # If we are only to run the function on demand, add a button to request this
    if manual:
        manual_button = Button(description="Run %s" % f.__name__)
        c.append(manual_button)
    container.children = c

    # Build the callback
    def call_f(name=None, old=None, new=None):
        container.kwargs = {}
        for widget in kwargs_widgets:
            value = widget.value
            container.kwargs[widget.description] = value
        if co:
            clear_output(wait=True)
        if manual:
            manual_button.disabled = True
        try:
            container.result = f(**container.kwargs)
        except Exception as e:
            ip = get_ipython()
            if ip is None:
                container.log.warn("Exception in interact callback: %s", e, exc_info=True)
            else:
                ip.showtraceback()
        finally:
            if manual:
                manual_button.disabled = False

    # 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 fucntion with the initial parameters
    if manual:
        manual_button.on_click(call_f)
    else:
        for widget in kwargs_widgets:
            widget.on_trait_change(call_f, 'value')

        container.on_displayed(lambda _: call_f(None, None, None))

    return container
Example #12
0
    def __init__(self,
                 model,
                 opt,
                 maxiters,
                 verbose=False,
                 current_iteration=0,
                 ipython_notebook=True,
                 clear_after_finish=False):
        self.verbose = verbose
        if self.verbose:
            self.model = model
            self.iteration = current_iteration
            self.p_iter = self.iteration
            self.maxiters = maxiters
            self.len_maxiters = len(str(maxiters))
            self.opt_name = opt.opt_name
            self.model.add_observer(self, self.print_status)
            self.status = 'running'
            self.clear = clear_after_finish

            self.update()

            try:
                from IPython.display import display
                from IPython.html.widgets import IntProgress, HTML, Box, VBox, HBox, FlexBox
                self.text = HTML(width='100%')
                self.progress = IntProgress(min=0, max=maxiters)
                #self.progresstext = Text(width='100%', disabled=True, value='0/{}'.format(maxiters))
                self.model_show = HTML()
                self.ipython_notebook = ipython_notebook
            except:
                # Not in Ipython notebook
                self.ipython_notebook = False

            if self.ipython_notebook:
                left_col = VBox(children=[self.progress, self.text],
                                padding=2,
                                width='40%')
                right_col = Box(children=[self.model_show],
                                padding=2,
                                width='60%')
                self.hor_align = FlexBox(children=[left_col, right_col],
                                         width='100%',
                                         orientation='horizontal')

                display(self.hor_align)

                try:
                    self.text.set_css('width', '100%')
                    left_col.set_css({
                        'padding': '2px',
                        'width': "100%",
                    })

                    right_col.set_css({
                        'padding': '2px',
                    })

                    self.hor_align.set_css({
                        'width': "100%",
                    })

                    self.hor_align.remove_class('vbox')
                    self.hor_align.add_class('hbox')

                    left_col.add_class("box-flex1")
                    right_col.add_class('box-flex0')

                except:
                    pass

                #self.text.add_class('box-flex2')
                #self.progress.add_class('box-flex1')
            else:
                self.exps = exponents(self.fnow, self.current_gradient)
                print('Running {} Code:'.format(self.opt_name))
                print('  {3:7s}   {0:{mi}s}   {1:11s}    {2:11s}'.format(
                    "i", "f", "|g|", "runtime", mi=self.len_maxiters))
Example #13
0
    def __init__(self, model, opt, maxiters, verbose=False, current_iteration=0, ipython_notebook=True, clear_after_finish=False):
        self.verbose = verbose
        if self.verbose:
            self.model = model
            self.iteration = current_iteration
            self.p_iter = self.iteration
            self.maxiters = maxiters
            self.len_maxiters = len(str(maxiters))
            self.opt_name = opt.opt_name
            self.model.add_observer(self, self.print_status)
            self.status = 'running'
            self.clear = clear_after_finish

            self.update()

            try:
                from IPython.display import display
                from IPython.html.widgets import IntProgress, HTML, Box, VBox, HBox, FlexBox
                self.text = HTML(width='100%')
                self.progress = IntProgress(min=0, max=maxiters)
                #self.progresstext = Text(width='100%', disabled=True, value='0/{}'.format(maxiters))
                self.model_show = HTML()
                self.ipython_notebook = ipython_notebook
            except:
                # Not in Ipython notebook
                self.ipython_notebook = False

            if self.ipython_notebook:
                left_col = VBox(children=[self.progress, self.text], padding=2, width='40%')
                right_col = Box(children=[self.model_show], padding=2, width='60%')
                self.hor_align = FlexBox(children = [left_col, right_col], width='100%', orientation='horizontal')

                display(self.hor_align)

                try:
                    self.text.set_css('width', '100%')
                    left_col.set_css({
                             'padding': '2px',
                             'width': "100%",
                             })

                    right_col.set_css({
                             'padding': '2px',
                             })

                    self.hor_align.set_css({
                             'width': "100%",
                             })

                    self.hor_align.remove_class('vbox')
                    self.hor_align.add_class('hbox')

                    left_col.add_class("box-flex1")
                    right_col.add_class('box-flex0')

                except:
                    pass

                #self.text.add_class('box-flex2')
                #self.progress.add_class('box-flex1')
            else:
                self.exps = exponents(self.fnow, self.current_gradient)
                print('Running {} Code:'.format(self.opt_name))
                print('  {3:7s}   {0:{mi}s}   {1:11s}    {2:11s}'.format("i", "f", "|g|", "runtime", mi=self.len_maxiters))