{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Using Interact\n", "\n", "In this lecture we will begin to learn about creating dashboard-type GUI with iPython widgets!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `interact` function (`ipywidgets.interact`) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython's widgets." ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Start with some imports!\n", "\n", "from __future__ import print_function\n", "from ipywidgets import interact, interactive, fixed\n", "import ipywidgets as widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "Please Note! The widgets in this notebook won't show up on NbViewer or GitHub renderings. To view the widgets and interact with them, you will need to download this notebook and run it with a Jupyter Notebook server.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic `interact`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At the most basic level, `interact` auto-generates UI controls for function arguments, and then calls the function with those arguments when you manipulate the controls interactively. To use `interact`, you need to define a function that you want to explore. Here is a function that prints its only argument `x`." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Very basic function\n", "def f(x):\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you pass this function as the first argument to `interact` along with an integer keyword argument (`x=10`), a slider is generated and bound to the function parameter. Note that the semicolon here just prevents an **out** cell from showing up." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "-8" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Generate a slider to interact with\n", "interact(f, x=10,);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you move the slider, the function is called, which prints the current value of `x`.\n", "\n", "If you pass `True` or `False`, `interact` will generate a check-box:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Booleans generate check-boxes\n", "interact(f, x=True);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you pass a string, `interact` will generate a text area." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "u'string'" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Strings generate text areas\n", "interact(f, x='Hi there!');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`interact` can also be used as a decorator. This allows you to define a function and interact with it in a single shot. As this example shows, `interact` also works with functions that have multiple arguments." ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(True, 1.1)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Using a decorator!\n", "@interact(x=True, y=1.0)\n", "def g(x, y):\n", " return (x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fixing arguments using `fixed`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are times when you may want to explore a function using `interact`, but fix one or more of its arguments to specific values. This can be accomplished by wrapping values with the `fixed` function." ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Again, a simple function\n", "def h(p, q):\n", " return (p, q)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we call `interact`, we pass `fixed(20)` for q to hold it fixed at a value of `20`." ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(13, 20)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(h, p=5, q=fixed(20));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that a slider is only produced for `p` as the value of `q` is fixed." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Widget abbreviations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you pass an integer-valued keyword argument of `10` (`x=10`) to `interact`, it generates an integer-valued slider control with a range of $[-10,+3\\times10]$. In this case, `10` is an *abbreviation* for an actual slider widget:\n", "\n", "```python\n", "IntSlider(min=-10,max=30,step=1,value=10)\n", "```\n", "\n", "In fact, we can get the same result if we pass this `IntSlider` as the keyword argument for `x`:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Can call the IntSlider to get more specific\n", "interact(f, x=widgets.IntSlider(min=-10,max=30,step=1,value=10));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This examples clarifies how `interact` process its keyword arguments:\n", "\n", "1. If the keyword argument is a `Widget` instance with a `value` attribute, that widget is used. Any widget with a `value` attribute can be used, even custom ones.\n", "2. Otherwise, the value is treated as a *widget abbreviation* that is converted to a widget before it is used.\n", "\n", "The following table gives an overview of different widget abbreviations:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", "
Keyword argumentWidget
`True` or `False`Checkbox
`'Hi there'`Text
`value` or `(min,max)` or `(min,max,step)` if integers are passedIntSlider
`value` or `(min,max)` or `(min,max,step)` if floats are passedFloatSlider
`('orange','apple')` or `{'one':1,'two':2}`Dropdown
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You have seen how the check-box and text-area widgets work above. Here, more details about the different abbreviations for sliders and drop-downs are given.\n", "\n", "If a 2-tuple of integers is passed `(min,max)`, an integer-valued slider is produced with those minimum and maximum values (inclusively). In this case, the default step size of `1` is used." ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Min,Max slider with Tuples\n", "interact(f, x=(0,4));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a 3-tuple of integers is passed `(min,max,step)`, the step size can also be set." ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# (min, max, step)\n", "interact(f, x=(0,8,2));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A float-valued slider is produced if the elements of the tuples are floats. Here the minimum is `0.0`, the maximum is `10.0` and step size is `0.1` (the default)." ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(f, x=(0.0,10.0));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The step size can be changed by passing a third element in the tuple." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4.99" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(f, x=(0.0,10.0,0.01));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For both integer and float-valued sliders, you can pick the initial value of the widget by passing a default keyword argument to the underlying Python function. Here we set the initial value of a float slider to `5.5`." ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5.5" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "@interact(x=(0.0,20.0,0.5))\n", "def h(x=5.5):\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dropdown menus are constructed by passing a tuple of strings. In this case, the strings are both used as the names in the drop-down menu UI and passed to the underlying Python function." ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "u'apples'" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(f, x=('apples','oranges'));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want a drop-down menu that passes non-string values to the Python function, you can pass a dictionary. The keys in the dictionary are used for the names in the drop-down menu UI and the values are the arguments that are passed to the underlying Python function." ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "20" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(f, x={'one': 10, 'two': 20});" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using function annotations with `interact`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you are using Python 3, you can also specify widget abbreviations using [function annotations](https://docs.python.org/3/tutorial/controlflow.html#function-annotations).\n", "\n", "\n", "### PYTHON 3\n", "Define a function with a checkbox widget abbreviation for the argument `x`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f(x:True): # python 3 only\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, because the widget abbreviation has already been defined, you can call `interact` with a single argument." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "interact(f);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PYTHON 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you are running Python 2, function annotations can be defined using the `@annotate` function." ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from IPython.utils.py3compat import annotate" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": false }, "outputs": [], "source": [ "@annotate(x=True)\n", "def f(x):\n", " return x" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(f);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## interactive" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to `interact`, IPython provides another function, `interactive`, that is useful when you want to reuse the widgets that are produced or access the data that is bound to the UI controls." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is a function that returns the sum of its two arguments." ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f(a, b):\n", " return a+b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike `interact`, `interactive` returns a `Widget` instance rather than immediately displaying the widget." ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [], "source": [ "w = interactive(f, a=10, b=20)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The widget is a `Box`, which is a container for other widgets." ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "ipywidgets.widgets.widget_box.Box" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(w)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The children of the `Box` are two integer-valued sliders produced by the widget abbreviations above." ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(,\n", " )" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w.children" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To actually display the widgets, you can use IPython's `display` function." ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "30" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import display\n", "display(w)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At this point, the UI controls work just like they would if `interact` had been used. You can manipulate them interactively and the function will be called. However, the widget instance returned by `interactive` also give you access to the current keyword arguments and return value of the underlying Python function.\n", "\n", "Here are the current keyword arguments. If you rerun this cell after manipulating the sliders, the values will have changed." ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'a': 10, 'b': 20}" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w.kwargs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is the current return value of the function." ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w.result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conclusion\n", "\n", "You should now have a basic understanding of how to use Interact in Jupyter Notebooks!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }