2014-02-02 08:06:40 +08:00
|
|
|
"""Interact with functions using widgets."""
|
2014-01-23 03:39:13 +08:00
|
|
|
|
2015-01-15 05:44:29 +08:00
|
|
|
# Copyright (c) IPython Development Team.
|
2014-01-23 03:39:13 +08:00
|
|
|
# Distributed under the terms of the Modified BSD License.
|
|
|
|
|
2014-02-02 08:06:40 +08:00
|
|
|
from __future__ import print_function
|
|
|
|
|
2014-02-01 08:04:58 +08:00
|
|
|
try: # Python >= 3.3
|
|
|
|
from inspect import signature, Parameter
|
|
|
|
except ImportError:
|
|
|
|
from IPython.utils.signatures import signature, Parameter
|
2014-02-02 08:06:40 +08:00
|
|
|
from inspect import getcallargs
|
2014-02-01 08:04:58 +08:00
|
|
|
|
2014-02-08 08:51:10 +08:00
|
|
|
from IPython.core.getipython import get_ipython
|
2014-07-19 03:47:33 +08:00
|
|
|
from IPython.html.widgets import (Widget, Text,
|
|
|
|
FloatSlider, IntSlider, Checkbox, Dropdown,
|
2014-08-26 16:25:38 +08:00
|
|
|
Box, Button, DOMWidget)
|
2014-01-23 03:39:13 +08:00
|
|
|
from IPython.display import display, clear_output
|
|
|
|
from IPython.utils.py3compat import string_types, unicode_type
|
2014-02-21 14:36:42 +08:00
|
|
|
from IPython.utils.traitlets import HasTraits, Any, Unicode
|
2014-02-17 07:11:39 +08:00
|
|
|
|
|
|
|
empty = Parameter.empty
|
2014-01-23 03:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _matches(o, pattern):
|
2014-02-02 08:06:40 +08:00
|
|
|
"""Match a pattern of types in a sequence."""
|
2014-01-23 03:39:13 +08:00
|
|
|
if not len(o) == len(pattern):
|
|
|
|
return False
|
|
|
|
comps = zip(o,pattern)
|
|
|
|
return all(isinstance(obj,kind) for obj,kind in comps)
|
|
|
|
|
|
|
|
|
2014-02-07 04:43:59 +08:00
|
|
|
def _get_min_max_value(min, max, value=None, step=None):
|
2014-01-31 02:06:36 +08:00
|
|
|
"""Return min, max, value given input values with possible None."""
|
|
|
|
if value is None:
|
|
|
|
if not max > min:
|
|
|
|
raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))
|
|
|
|
value = min + abs(min-max)/2
|
|
|
|
value = type(min)(value)
|
|
|
|
elif min is None and max is None:
|
|
|
|
if value == 0.0:
|
|
|
|
min, max, value = 0.0, 1.0, 0.5
|
|
|
|
elif value == 0:
|
|
|
|
min, max, value = 0, 1, 0
|
2014-02-07 09:00:44 +08:00
|
|
|
elif isinstance(value, (int, float)):
|
2014-02-02 08:06:40 +08:00
|
|
|
min, max = (-value, 3*value) if value > 0 else (3*value, -value)
|
2014-01-31 02:06:36 +08:00
|
|
|
else:
|
2014-02-01 08:04:58 +08:00
|
|
|
raise TypeError('expected a number, got: %r' % value)
|
2014-01-31 02:06:36 +08:00
|
|
|
else:
|
|
|
|
raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))
|
2014-02-07 09:00:44 +08:00
|
|
|
if step is not None:
|
2014-02-07 04:43:59 +08:00
|
|
|
# ensure value is on a step
|
|
|
|
r = (value - min) % step
|
|
|
|
value = value - r
|
2014-01-23 03:39:13 +08:00
|
|
|
return min, max, value
|
|
|
|
|
2014-02-01 08:04:58 +08:00
|
|
|
def _widget_abbrev_single_value(o):
|
2014-02-07 09:00:44 +08:00
|
|
|
"""Make widgets from single values, which can be used as parameter defaults."""
|
2014-01-23 03:39:13 +08:00
|
|
|
if isinstance(o, string_types):
|
2014-07-19 03:47:33 +08:00
|
|
|
return Text(value=unicode_type(o))
|
2014-01-23 03:39:13 +08:00
|
|
|
elif isinstance(o, dict):
|
2014-07-19 03:47:33 +08:00
|
|
|
return Dropdown(values=o)
|
2014-01-23 03:39:13 +08:00
|
|
|
elif isinstance(o, bool):
|
2014-07-19 03:47:33 +08:00
|
|
|
return Checkbox(value=o)
|
2014-01-23 03:39:13 +08:00
|
|
|
elif isinstance(o, float):
|
2014-01-31 02:06:36 +08:00
|
|
|
min, max, value = _get_min_max_value(None, None, o)
|
2014-07-19 03:47:33 +08:00
|
|
|
return FloatSlider(value=o, min=min, max=max)
|
2014-01-23 03:39:13 +08:00
|
|
|
elif isinstance(o, int):
|
2014-01-31 02:06:36 +08:00
|
|
|
min, max, value = _get_min_max_value(None, None, o)
|
2014-07-19 03:47:33 +08:00
|
|
|
return IntSlider(value=o, min=min, max=max)
|
2014-02-02 08:06:40 +08:00
|
|
|
else:
|
|
|
|
return None
|
2014-02-01 08:04:58 +08:00
|
|
|
|
|
|
|
def _widget_abbrev(o):
|
|
|
|
"""Make widgets from abbreviations: single values, lists or tuples."""
|
2014-02-07 09:00:44 +08:00
|
|
|
float_or_int = (float, int)
|
2014-01-23 03:39:13 +08:00
|
|
|
if isinstance(o, (list, tuple)):
|
2014-02-07 09:00:44 +08:00
|
|
|
if o and all(isinstance(x, string_types) for x in o):
|
2014-07-19 03:47:33 +08:00
|
|
|
return Dropdown(values=[unicode_type(k) for k in o])
|
2014-02-07 09:00:44 +08:00
|
|
|
elif _matches(o, (float_or_int, float_or_int)):
|
2014-02-07 04:43:59 +08:00
|
|
|
min, max, value = _get_min_max_value(o[0], o[1])
|
2014-02-07 09:00:44 +08:00
|
|
|
if all(isinstance(_, int) for _ in o):
|
2014-07-19 03:47:33 +08:00
|
|
|
cls = IntSlider
|
2014-02-07 09:00:44 +08:00
|
|
|
else:
|
2014-07-19 03:47:33 +08:00
|
|
|
cls = FloatSlider
|
2014-02-07 09:00:44 +08:00
|
|
|
return cls(value=value, min=min, max=max)
|
|
|
|
elif _matches(o, (float_or_int, float_or_int, float_or_int)):
|
|
|
|
step = o[2]
|
|
|
|
if step <= 0:
|
|
|
|
raise ValueError("step must be >= 0, not %r" % step)
|
|
|
|
min, max, value = _get_min_max_value(o[0], o[1], step=step)
|
|
|
|
if all(isinstance(_, int) for _ in o):
|
2014-07-19 03:47:33 +08:00
|
|
|
cls = IntSlider
|
2014-02-07 09:00:44 +08:00
|
|
|
else:
|
2014-07-19 03:47:33 +08:00
|
|
|
cls = FloatSlider
|
2014-02-07 09:00:44 +08:00
|
|
|
return cls(value=value, min=min, max=max, step=step)
|
2014-02-01 08:04:58 +08:00
|
|
|
else:
|
|
|
|
return _widget_abbrev_single_value(o)
|
|
|
|
|
2014-02-17 07:11:39 +08:00
|
|
|
def _widget_from_abbrev(abbrev, default=empty):
|
|
|
|
"""Build a Widget instance given an abbreviation or Widget."""
|
2014-02-07 04:34:23 +08:00
|
|
|
if isinstance(abbrev, Widget) or isinstance(abbrev, fixed):
|
2014-02-02 08:06:40 +08:00
|
|
|
return abbrev
|
2014-06-25 22:49:56 +08:00
|
|
|
|
2014-02-02 08:06:40 +08:00
|
|
|
widget = _widget_abbrev(abbrev)
|
2014-02-21 14:36:42 +08:00
|
|
|
if default is not empty and isinstance(abbrev, (list, tuple, dict)):
|
2014-02-17 07:11:39 +08:00
|
|
|
# if it's not a single-value abbreviation,
|
|
|
|
# set the initial value from the default
|
|
|
|
try:
|
|
|
|
widget.value = default
|
2014-02-21 14:36:42 +08:00
|
|
|
except Exception:
|
|
|
|
# ignore failure to set default
|
2014-02-17 07:11:39 +08:00
|
|
|
pass
|
2014-02-01 08:04:58 +08:00
|
|
|
if widget is None:
|
2014-02-07 09:01:01 +08:00
|
|
|
raise ValueError("%r cannot be transformed to a Widget" % (abbrev,))
|
2014-02-01 08:04:58 +08:00
|
|
|
return widget
|
|
|
|
|
2014-02-07 04:32:21 +08:00
|
|
|
def _yield_abbreviations_for_parameter(param, kwargs):
|
2014-02-02 08:06:40 +08:00
|
|
|
"""Get an abbreviation for a function parameter."""
|
|
|
|
name = param.name
|
|
|
|
kind = param.kind
|
|
|
|
ann = param.annotation
|
|
|
|
default = param.default
|
2014-02-17 07:11:39 +08:00
|
|
|
not_found = (name, empty, empty)
|
|
|
|
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
|
2014-02-02 08:06:40 +08:00
|
|
|
if name in kwargs:
|
2014-02-17 07:11:39 +08:00
|
|
|
value = kwargs.pop(name)
|
2014-02-02 08:06:40 +08:00
|
|
|
elif ann is not empty:
|
2014-02-17 07:11:39 +08:00
|
|
|
value = ann
|
2014-02-02 08:06:40 +08:00
|
|
|
elif default is not empty:
|
2014-02-17 07:11:39 +08:00
|
|
|
value = default
|
2014-02-02 08:06:40 +08:00
|
|
|
else:
|
2014-02-07 04:32:21 +08:00
|
|
|
yield not_found
|
2014-02-17 07:11:39 +08:00
|
|
|
yield (name, value, default)
|
2014-02-02 08:06:40 +08:00
|
|
|
elif kind == Parameter.VAR_KEYWORD:
|
|
|
|
# In this case name=kwargs and we yield the items in kwargs with their keys.
|
|
|
|
for k, v in kwargs.copy().items():
|
|
|
|
kwargs.pop(k)
|
2014-02-17 07:11:39 +08:00
|
|
|
yield k, v, empty
|
2014-01-23 03:39:13 +08:00
|
|
|
|
2014-02-07 04:32:21 +08:00
|
|
|
def _find_abbreviations(f, kwargs):
|
|
|
|
"""Find the abbreviations for a function and kwargs passed to interact."""
|
2014-02-02 08:06:40 +08:00
|
|
|
new_kwargs = []
|
|
|
|
for param in signature(f).parameters.values():
|
2014-02-17 07:11:39 +08:00
|
|
|
for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
|
|
|
|
if value is empty:
|
2014-02-02 08:06:40 +08:00
|
|
|
raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
|
2014-02-17 07:11:39 +08:00
|
|
|
new_kwargs.append((name, value, default))
|
2014-02-07 04:32:21 +08:00
|
|
|
return new_kwargs
|
2014-02-02 08:06:40 +08:00
|
|
|
|
|
|
|
def _widgets_from_abbreviations(seq):
|
|
|
|
"""Given a sequence of (name, abbrev) tuples, return a sequence of Widgets."""
|
|
|
|
result = []
|
2014-02-17 07:11:39 +08:00
|
|
|
for name, abbrev, default in seq:
|
|
|
|
widget = _widget_from_abbrev(abbrev, default)
|
2014-05-09 02:12:02 +08:00
|
|
|
if not widget.description:
|
|
|
|
widget.description = name
|
2015-01-20 08:01:18 +08:00
|
|
|
widget._kwarg = name
|
2014-02-02 08:06:40 +08:00
|
|
|
result.append(widget)
|
|
|
|
return result
|
|
|
|
|
2014-02-07 04:32:21 +08:00
|
|
|
def interactive(__interact_f, **kwargs):
|
2015-01-22 04:25:28 +08:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2014-02-07 04:32:21 +08:00
|
|
|
f = __interact_f
|
2014-01-23 03:39:13 +08:00
|
|
|
co = kwargs.pop('clear_output', True)
|
2014-09-23 03:23:51 +08:00
|
|
|
manual = kwargs.pop('__manual', False)
|
2014-02-02 08:06:40 +08:00
|
|
|
kwargs_widgets = []
|
2014-08-14 04:19:27 +08:00
|
|
|
container = Box()
|
2014-01-23 03:39:13 +08:00
|
|
|
container.result = None
|
2014-02-02 08:06:40 +08:00
|
|
|
container.args = []
|
2014-01-31 02:06:36 +08:00
|
|
|
container.kwargs = dict()
|
2014-02-02 08:06:40 +08:00
|
|
|
kwargs = kwargs.copy()
|
|
|
|
|
2014-02-07 04:32:21 +08:00
|
|
|
new_kwargs = _find_abbreviations(f, kwargs)
|
2014-02-02 08:06:40 +08:00
|
|
|
# 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.
|
2014-02-17 07:11:39 +08:00
|
|
|
getcallargs(f, **{n:v for n,v,_ in new_kwargs})
|
2014-02-02 08:06:40 +08:00
|
|
|
# Now build the widgets from the abbreviations.
|
|
|
|
kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))
|
|
|
|
|
2014-02-01 08:04:58 +08:00
|
|
|
# This has to be done as an assignment, not using container.children.append,
|
2014-02-07 04:34:23 +08:00
|
|
|
# so that traitlets notices the update. We skip any objects (such as fixed) that
|
2014-02-02 14:57:58 +08:00
|
|
|
# are not DOMWidgets.
|
2014-02-07 04:32:21 +08:00
|
|
|
c = [w for w in kwargs_widgets if isinstance(w, DOMWidget)]
|
2014-06-25 22:49:56 +08:00
|
|
|
|
|
|
|
# If we are only to run the function on demand, add a button to request this
|
2014-09-23 03:23:51 +08:00
|
|
|
if manual:
|
|
|
|
manual_button = Button(description="Run %s" % f.__name__)
|
|
|
|
c.append(manual_button)
|
2014-02-02 14:57:58 +08:00
|
|
|
container.children = c
|
2014-01-23 04:12:58 +08:00
|
|
|
|
2014-01-23 03:39:13 +08:00
|
|
|
# Build the callback
|
2014-06-25 22:49:56 +08:00
|
|
|
def call_f(name=None, old=None, new=None):
|
2014-02-07 08:59:53 +08:00
|
|
|
container.kwargs = {}
|
2014-02-02 08:06:40 +08:00
|
|
|
for widget in kwargs_widgets:
|
2014-01-23 03:39:13 +08:00
|
|
|
value = widget.value
|
2015-01-20 08:01:18 +08:00
|
|
|
container.kwargs[widget._kwarg] = value
|
2014-01-23 03:39:13 +08:00
|
|
|
if co:
|
|
|
|
clear_output(wait=True)
|
2014-09-23 03:23:51 +08:00
|
|
|
if manual:
|
|
|
|
manual_button.disabled = True
|
2014-02-08 08:51:10 +08:00
|
|
|
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()
|
2014-06-27 01:25:52 +08:00
|
|
|
finally:
|
2014-09-23 03:23:51 +08:00
|
|
|
if manual:
|
|
|
|
manual_button.disabled = False
|
2014-01-23 03:39:13 +08:00
|
|
|
|
|
|
|
# Wire up the widgets
|
2014-09-23 03:23:51 +08:00
|
|
|
# If we are doing manual running, the callback is only triggered by the button
|
2014-06-25 22:49:56 +08:00
|
|
|
# Otherwise, it is triggered for every trait change received
|
2015-01-22 04:25:28 +08:00
|
|
|
# On-demand running also suppresses running the function with the initial parameters
|
2014-09-23 03:23:51 +08:00
|
|
|
if manual:
|
|
|
|
manual_button.on_click(call_f)
|
2014-06-25 22:49:56 +08:00
|
|
|
else:
|
|
|
|
for widget in kwargs_widgets:
|
|
|
|
widget.on_trait_change(call_f, 'value')
|
2014-01-23 03:39:13 +08:00
|
|
|
|
2014-06-25 22:49:56 +08:00
|
|
|
container.on_displayed(lambda _: call_f(None, None, None))
|
2014-01-23 03:39:13 +08:00
|
|
|
|
|
|
|
return container
|
|
|
|
|
2014-02-07 04:32:21 +08:00
|
|
|
def interact(__interact_f=None, **kwargs):
|
2015-01-21 09:51:04 +08:00
|
|
|
"""
|
|
|
|
Displays interactive widgets which are tied to a function.
|
|
|
|
Expects the first argument to be a function. Parameters to this function are
|
2015-01-22 04:25:28 +08:00
|
|
|
widget abbreviations passed in as keyword arguments (**kwargs). Can be used
|
|
|
|
as a decorator (see examples).
|
2015-01-21 09:51:04 +08:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2015-01-22 04:25:28 +08:00
|
|
|
f : __interact_f with interactive widget attached to it.
|
2015-01-21 09:51:04 +08:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
__interact_f : function
|
|
|
|
The function to which the interactive widgets are tied. The **kwargs
|
|
|
|
should match the function signature. Passed to :func:`interactive()`
|
|
|
|
**kwargs : various, optional
|
2015-01-22 04:25:28 +08:00
|
|
|
An interactive widget is created for each keyword argument that is a
|
|
|
|
valid widget abbreviation. Passed to :func:`interactive()`
|
2015-01-21 09:51:04 +08:00
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
Renders an interactive text field that shows the greeting with the passed in
|
|
|
|
text.
|
2014-06-25 22:49:56 +08:00
|
|
|
|
2015-01-21 09:51:04 +08:00
|
|
|
1. Invocation of interact as a function
|
|
|
|
def greeting(text="World"):
|
|
|
|
print "Hello {}".format(text)
|
|
|
|
interact(greeting, text="IPython Widgets")
|
|
|
|
|
|
|
|
2. Invocation of interact as a decorator
|
|
|
|
@interact
|
|
|
|
def greeting(text="World"):
|
|
|
|
print "Hello {}".format(text)
|
|
|
|
|
|
|
|
3. Invocation of interact as a decorator with named parameters
|
|
|
|
@interact(text="IPython Widgets")
|
|
|
|
def greeting(text="World"):
|
|
|
|
print "Hello {}".format(text)
|
|
|
|
|
|
|
|
Renders an interactive slider widget and prints square of number.
|
|
|
|
|
|
|
|
1. Invocation of interact as a function
|
|
|
|
def square(num=1):
|
|
|
|
print "{} squared is {}".format(num, num*num)
|
|
|
|
interact(square, num=5)
|
|
|
|
|
|
|
|
2. Invocation of interact as a decorator
|
|
|
|
@interact
|
|
|
|
def square(num=2):
|
|
|
|
print "{} squared is {}".format(num, num*num)
|
|
|
|
|
|
|
|
3. Invocation of interact as a decorator with named parameters
|
|
|
|
@interact(num=5)
|
|
|
|
def square(num=2):
|
|
|
|
print "{} squared is {}".format(num, num*num)
|
|
|
|
"""
|
2014-02-07 04:32:21 +08:00
|
|
|
# positional arg support in: https://gist.github.com/8851331
|
|
|
|
if __interact_f is not None:
|
2015-01-21 09:51:04 +08:00
|
|
|
# This branch handles the cases 1 and 2
|
2014-02-07 04:32:21 +08:00
|
|
|
# 1. interact(f, **kwargs)
|
2014-02-02 10:34:28 +08:00
|
|
|
# 2. @interact
|
|
|
|
# def f(*args, **kwargs):
|
|
|
|
# ...
|
2014-02-07 04:32:21 +08:00
|
|
|
f = __interact_f
|
|
|
|
w = interactive(f, **kwargs)
|
2015-01-15 05:44:29 +08:00
|
|
|
try:
|
|
|
|
f.widget = w
|
|
|
|
except AttributeError:
|
|
|
|
# some things (instancemethods) can't have attributes attached,
|
|
|
|
# so wrap in a lambda
|
|
|
|
f = lambda *args, **kwargs: __interact_f(*args, **kwargs)
|
|
|
|
f.widget = w
|
2014-02-02 10:34:28 +08:00
|
|
|
display(w)
|
2014-02-07 09:01:33 +08:00
|
|
|
return f
|
2014-02-02 10:34:28 +08:00
|
|
|
else:
|
2015-01-21 09:51:04 +08:00
|
|
|
# This branch handles the case 3
|
2014-02-07 04:32:21 +08:00
|
|
|
# @interact(a=30, b=40)
|
2014-02-02 10:34:28 +08:00
|
|
|
# def f(*args, **kwargs):
|
|
|
|
# ...
|
|
|
|
def dec(f):
|
2015-01-15 05:44:29 +08:00
|
|
|
return interact(f, **kwargs)
|
2014-02-02 10:34:28 +08:00
|
|
|
return dec
|
2014-02-02 08:06:40 +08:00
|
|
|
|
2014-09-23 03:23:51 +08:00
|
|
|
def interact_manual(__interact_f=None, **kwargs):
|
|
|
|
"""interact_manual(f, **kwargs)
|
2014-08-26 16:37:32 +08:00
|
|
|
|
|
|
|
As `interact()`, generates widgets for each argument, but rather than running
|
|
|
|
the function after each widget change, adds a "Run" button and waits for it
|
|
|
|
to be clicked. Useful if the function is long-running and has several
|
|
|
|
parameters to change.
|
|
|
|
"""
|
2014-09-23 03:23:51 +08:00
|
|
|
return interact(__interact_f, __manual=True, **kwargs)
|
2014-08-26 16:37:32 +08:00
|
|
|
|
2014-02-07 04:34:23 +08:00
|
|
|
class fixed(HasTraits):
|
|
|
|
"""A pseudo-widget whose value is fixed and never synced to the client."""
|
2014-02-02 14:57:58 +08:00
|
|
|
value = Any(help="Any Python object")
|
|
|
|
description = Unicode('', help="Any Python object")
|
|
|
|
def __init__(self, value, **kwargs):
|
2014-02-07 04:34:23 +08:00
|
|
|
super(fixed, self).__init__(value=value, **kwargs)
|