##// END OF EJS Templates
Add 'on_demand' option to interact() so that long-running functions can be started only when explicitly requested
Gordon Ball -
Show More
@@ -1,257 +1,269 b''
1 1 """Interact with functions using widgets."""
2 2
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2013, the IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 from __future__ import print_function
16 16
17 17 try: # Python >= 3.3
18 18 from inspect import signature, Parameter
19 19 except ImportError:
20 20 from IPython.utils.signatures import signature, Parameter
21 21 from inspect import getcallargs
22 22
23 23 from IPython.core.getipython import get_ipython
24 24 from IPython.html.widgets import (Widget, TextWidget,
25 25 FloatSliderWidget, IntSliderWidget, CheckboxWidget, DropdownWidget,
26 ContainerWidget, DOMWidget)
26 ContainerWidget, DOMWidget, ButtonWidget)
27 27 from IPython.display import display, clear_output
28 28 from IPython.utils.py3compat import string_types, unicode_type
29 29 from IPython.utils.traitlets import HasTraits, Any, Unicode
30 30
31 31 empty = Parameter.empty
32 32
33 33 #-----------------------------------------------------------------------------
34 34 # Classes and Functions
35 35 #-----------------------------------------------------------------------------
36 36
37 37
38 38 def _matches(o, pattern):
39 39 """Match a pattern of types in a sequence."""
40 40 if not len(o) == len(pattern):
41 41 return False
42 42 comps = zip(o,pattern)
43 43 return all(isinstance(obj,kind) for obj,kind in comps)
44 44
45 45
46 46 def _get_min_max_value(min, max, value=None, step=None):
47 47 """Return min, max, value given input values with possible None."""
48 48 if value is None:
49 49 if not max > min:
50 50 raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))
51 51 value = min + abs(min-max)/2
52 52 value = type(min)(value)
53 53 elif min is None and max is None:
54 54 if value == 0.0:
55 55 min, max, value = 0.0, 1.0, 0.5
56 56 elif value == 0:
57 57 min, max, value = 0, 1, 0
58 58 elif isinstance(value, (int, float)):
59 59 min, max = (-value, 3*value) if value > 0 else (3*value, -value)
60 60 else:
61 61 raise TypeError('expected a number, got: %r' % value)
62 62 else:
63 63 raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))
64 64 if step is not None:
65 65 # ensure value is on a step
66 66 r = (value - min) % step
67 67 value = value - r
68 68 return min, max, value
69 69
70 70 def _widget_abbrev_single_value(o):
71 71 """Make widgets from single values, which can be used as parameter defaults."""
72 72 if isinstance(o, string_types):
73 73 return TextWidget(value=unicode_type(o))
74 74 elif isinstance(o, dict):
75 75 return DropdownWidget(values=o)
76 76 elif isinstance(o, bool):
77 77 return CheckboxWidget(value=o)
78 78 elif isinstance(o, float):
79 79 min, max, value = _get_min_max_value(None, None, o)
80 80 return FloatSliderWidget(value=o, min=min, max=max)
81 81 elif isinstance(o, int):
82 82 min, max, value = _get_min_max_value(None, None, o)
83 83 return IntSliderWidget(value=o, min=min, max=max)
84 84 else:
85 85 return None
86 86
87 87 def _widget_abbrev(o):
88 88 """Make widgets from abbreviations: single values, lists or tuples."""
89 89 float_or_int = (float, int)
90 90 if isinstance(o, (list, tuple)):
91 91 if o and all(isinstance(x, string_types) for x in o):
92 92 return DropdownWidget(values=[unicode_type(k) for k in o])
93 93 elif _matches(o, (float_or_int, float_or_int)):
94 94 min, max, value = _get_min_max_value(o[0], o[1])
95 95 if all(isinstance(_, int) for _ in o):
96 96 cls = IntSliderWidget
97 97 else:
98 98 cls = FloatSliderWidget
99 99 return cls(value=value, min=min, max=max)
100 100 elif _matches(o, (float_or_int, float_or_int, float_or_int)):
101 101 step = o[2]
102 102 if step <= 0:
103 103 raise ValueError("step must be >= 0, not %r" % step)
104 104 min, max, value = _get_min_max_value(o[0], o[1], step=step)
105 105 if all(isinstance(_, int) for _ in o):
106 106 cls = IntSliderWidget
107 107 else:
108 108 cls = FloatSliderWidget
109 109 return cls(value=value, min=min, max=max, step=step)
110 110 else:
111 111 return _widget_abbrev_single_value(o)
112 112
113 113 def _widget_from_abbrev(abbrev, default=empty):
114 114 """Build a Widget instance given an abbreviation or Widget."""
115 115 if isinstance(abbrev, Widget) or isinstance(abbrev, fixed):
116 116 return abbrev
117
117
118 118 widget = _widget_abbrev(abbrev)
119 119 if default is not empty and isinstance(abbrev, (list, tuple, dict)):
120 120 # if it's not a single-value abbreviation,
121 121 # set the initial value from the default
122 122 try:
123 123 widget.value = default
124 124 except Exception:
125 125 # ignore failure to set default
126 126 pass
127 127 if widget is None:
128 128 raise ValueError("%r cannot be transformed to a Widget" % (abbrev,))
129 129 return widget
130 130
131 131 def _yield_abbreviations_for_parameter(param, kwargs):
132 132 """Get an abbreviation for a function parameter."""
133 133 name = param.name
134 134 kind = param.kind
135 135 ann = param.annotation
136 136 default = param.default
137 137 not_found = (name, empty, empty)
138 138 if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
139 139 if name in kwargs:
140 140 value = kwargs.pop(name)
141 141 elif ann is not empty:
142 142 value = ann
143 143 elif default is not empty:
144 144 value = default
145 145 else:
146 146 yield not_found
147 147 yield (name, value, default)
148 148 elif kind == Parameter.VAR_KEYWORD:
149 149 # In this case name=kwargs and we yield the items in kwargs with their keys.
150 150 for k, v in kwargs.copy().items():
151 151 kwargs.pop(k)
152 152 yield k, v, empty
153 153
154 154 def _find_abbreviations(f, kwargs):
155 155 """Find the abbreviations for a function and kwargs passed to interact."""
156 156 new_kwargs = []
157 157 for param in signature(f).parameters.values():
158 158 for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
159 159 if value is empty:
160 160 raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
161 161 new_kwargs.append((name, value, default))
162 162 return new_kwargs
163 163
164 164 def _widgets_from_abbreviations(seq):
165 165 """Given a sequence of (name, abbrev) tuples, return a sequence of Widgets."""
166 166 result = []
167 167 for name, abbrev, default in seq:
168 168 widget = _widget_from_abbrev(abbrev, default)
169 169 if not widget.description:
170 170 widget.description = name
171 171 result.append(widget)
172 172 return result
173 173
174 174 def interactive(__interact_f, **kwargs):
175 175 """Build a group of widgets to interact with a function."""
176 176 f = __interact_f
177 177 co = kwargs.pop('clear_output', True)
178 on_demand = kwargs.pop('on_demand', False)
178 179 kwargs_widgets = []
179 180 container = ContainerWidget()
180 181 container.result = None
181 182 container.args = []
182 183 container.kwargs = dict()
183 184 kwargs = kwargs.copy()
184 185
185 186 new_kwargs = _find_abbreviations(f, kwargs)
186 187 # Before we proceed, let's make sure that the user has passed a set of args+kwargs
187 188 # that will lead to a valid call of the function. This protects against unspecified
188 189 # and doubly-specified arguments.
189 190 getcallargs(f, **{n:v for n,v,_ in new_kwargs})
190 191 # Now build the widgets from the abbreviations.
191 192 kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))
192 193
193 194 # This has to be done as an assignment, not using container.children.append,
194 195 # so that traitlets notices the update. We skip any objects (such as fixed) that
195 196 # are not DOMWidgets.
196 197 c = [w for w in kwargs_widgets if isinstance(w, DOMWidget)]
198
199 # If we are only to run the function on demand, add a button to request this
200 if on_demand:
201 on_demand_button = ButtonWidget(description="Run %s" % f.__name__)
202 c.append(on_demand_button)
197 203 container.children = c
198 204
199 205 # Build the callback
200 def call_f(name, old, new):
206 def call_f(name=None, old=None, new=None):
201 207 container.kwargs = {}
202 208 for widget in kwargs_widgets:
203 209 value = widget.value
204 210 container.kwargs[widget.description] = value
205 211 if co:
206 212 clear_output(wait=True)
207 213 try:
208 214 container.result = f(**container.kwargs)
209 215 except Exception as e:
210 216 ip = get_ipython()
211 217 if ip is None:
212 218 container.log.warn("Exception in interact callback: %s", e, exc_info=True)
213 219 else:
214 220 ip.showtraceback()
215 221
216 222 # Wire up the widgets
217 for widget in kwargs_widgets:
218 widget.on_trait_change(call_f, 'value')
223 # If we are doing on demand running, the callback is only triggered by the button
224 # Otherwise, it is triggered for every trait change received
225 # On-demand running also suppresses running the fucntion with the initial parameters
226 if on_demand:
227 on_demand_button.on_click(call_f)
228 else:
229 for widget in kwargs_widgets:
230 widget.on_trait_change(call_f, 'value')
219 231
220 container.on_displayed(lambda _: call_f(None, None, None))
232 container.on_displayed(lambda _: call_f(None, None, None))
221 233
222 234 return container
223 235
224 236 def interact(__interact_f=None, **kwargs):
225 237 """interact(f, **kwargs)
226
238
227 239 Interact with a function using widgets."""
228 240 # positional arg support in: https://gist.github.com/8851331
229 241 if __interact_f is not None:
230 242 # This branch handles the cases:
231 243 # 1. interact(f, **kwargs)
232 244 # 2. @interact
233 245 # def f(*args, **kwargs):
234 246 # ...
235 247 f = __interact_f
236 248 w = interactive(f, **kwargs)
237 249 f.widget = w
238 250 display(w)
239 251 return f
240 252 else:
241 253 # This branch handles the case:
242 254 # @interact(a=30, b=40)
243 255 # def f(*args, **kwargs):
244 256 # ...
245 257 def dec(f):
246 258 w = interactive(f, **kwargs)
247 259 f.widget = w
248 260 display(w)
249 261 return f
250 262 return dec
251 263
252 264 class fixed(HasTraits):
253 265 """A pseudo-widget whose value is fixed and never synced to the client."""
254 266 value = Any(help="Any Python object")
255 267 description = Unicode('', help="Any Python object")
256 268 def __init__(self, value, **kwargs):
257 269 super(fixed, self).__init__(value=value, **kwargs)
General Comments 0
You need to be logged in to leave comments. Login now