In this notebook, we are going to have a look at some simple methods to make Python function interactive with the help of the ipywidgets
package.
%pylab inline
from ipywidgets import *
We now know how to plot a mathematical function.
t=linspace(0,2*pi,100);
plot(t,sin(t))
Let us create a function that plots a sine wave with a given frequency!
def freki(omega):
plot(t,sin(omega*t))
freki(2.0)
Here comes the magic. The interact()
function makes our previous function interactive.
interact(freki,omega=(0,10,0.1));
Let us observe now how the interact()
construction works. Let us now define a very simple function!
def func(x):
print(x)
interact
is a function that expects a function as its first parameter, and it expects the input parameters of this function as keyword arguments. It returns a widget, that can be of multiple type, but its aim is to serve the func function. It gives an input parameter to func, runs it, then waits for the user to change the state of the widget. If we gave integers in brackets to the keyword argument, we get a slider going through integer numbers between these two values.
interact(func,x=(0,10));
If we set a bool
to a keyword argument, we get a checkbox.
Ha egy bool
értéket adunk meg, akkor egy pipálható dobozt:
interact(func,x=False);
If we give an arbitrary list, we get a dropdown menu.
interact(func,x=['hétfő','kedd','szerda']);
If the numbers are not integers in the brackets, or at least one of them is not integer, we get a float slider.
interact(func,x=(0,10,0.1));
The following examples show some possible cases, even with more precise specification such as Checkbox()
:
interact(func,x=IntSlider(min=0,max=10,step=2,value=2,description='integer slider x='));
interact(func,x=FloatSlider(min=0,max=10,step=0.01,value=2,description='float slider x='));
interact(func,x=Dropdown(options=['Monday','Tuesday','Wednesday'],description='dropdown x='));
interact(func,x=Checkbox());
interact(func,x=Text());
If a function takes long to evaluate, then we may use interact_manual
instead of interact
. This is going to run the function only when a button is pushed.
interact_manual(func,x=(0,10));
A bit more on widgets can be found here. Let us now have a look at a multivariate interact!
t=linspace(0,2*pi,100);
def oszci(A,omega,phi,c):
plot(t,A*sin(omega*t+phi),color=c)
plot(pi,A*sin(omega*pi+phi),'o')
xlim(0,2*pi)
ylim(-3,3)
xlabel('$t$',fontsize=20)
ylabel(r'$A\,\sin(\omega t+\varphi)$',fontsize=20)
grid(True)
interact(oszci,
A =FloatSlider(min=1,max=2,step=0.1,value=2,description='A'),
omega=FloatSlider(min=0,max=10,step=0.1,value=2,description=r'$\omega$'),
phi =FloatSlider(min=0,max=2*pi,step=0.1,value=0,description=r'$\varphi$'),
c =Dropdown(options=['red','green','blue','darkcyan'],description='szín'));