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 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 #6
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 #7
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 #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)
    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