NBViewer: http://goo.gl/xkXHp
Repo: https://github.com/damianavila/SciPyConAr_Python_Cientifico
Twitter: @damian_avila
Es una poderosa herramienta para la computación científica interactiva y exploratoria.
(ipython_dev)damian@damian-Inspiron-1110:~$ ipython notebook --pylab=inline
2013-05-10 12:11:26.912 [NotebookApp] Using existing profile dir: u'/home/damian/.config/ipython/profile_default'
2013-05-10 12:11:26.937 [NotebookApp] Using MathJax from CDN: http://cdn.mathjax.org/mathjax/latest/MathJax.js
2013-05-10 12:11:26.984 [NotebookApp] The port 8888 is already in use, trying another random port.
2013-05-10 12:11:26.985 [NotebookApp] Serving notebooks from local directory: /home/damian
2013-05-10 12:11:26.985 [NotebookApp] The IPython Notebook is running at: http://127.0.0.1:8888/
2013-05-10 12:11:26.986 [NotebookApp] Use Control-C to stop this server and shut down all kernels.
Se ha abierto una nueva ventana en la sesión actual del navegador.
y ejecutando un hola mundo:
print "Hola SciPyConAr"
Hola SciPyConAr
a = 1
a
1
La representación de los objetos es más legible:
data = {i : randn() for i in range(7)}
data
{0: -0.08057896750097586, 1: -0.6802589019979545, 2: 0.22168682127462605, 3: -1.067514067534686, 4: 0.6134211871726604, 5: 0.8228547005819703, 6: -0.76406633821424}
>>> from numpy.random import randn
>>> data = {i : randn() for i in range(7)}
>>> print data
{0: -1.3788695837223246, 1: 0.3432611139093174, 2: -0.832721033326183, 3: 0.5240879360829318, 4: 1.8363136524671757, 5: -1.3419464857663135, 6: -0.3929985586677686}
Facundo = 1
Facultad = 8
Fa = 4
Busqueda de variables en el espacio de nombres: variable_de_interés<TAB>
:
Fa
Acceso a métodos y atributos, por ejemplo, objeto_de_interés.<TAB>
:
lista = [1, 2, 3, 4, 5]
lista.
Lo mismo para los módulos, por ejemplo, modulo_de_interés.<TAB>
:
import datetime
datetime.
datetime._
Incluso para directorios, por ejemplo, carpeta_de_interés/<TAB>
:
!ls # pequeño truco para pasar comandos a consola...
images SciPyConAr_NumPy.ipynb nbconvert SciPyConAr_Python_Cientifico.ipynb SciPyConAr_Final.ipynb SciPyConAr_SciPy.ipynb SciPyConAr_Herramientas.ipynb scripts SciPyConAr_IPython.ipynb stockholm_td_adj.dat SciPyConAr_Matplotlib.ipynb
scripts/
lista?
Apliquemoslo a una función propia:
def suma(a, b):
"""
Demo de una función que suma cosas...
"""
return a + b
suma?
suma??
El "?" También puede servirnos para la busqueda en el espacio de nombres de IPython:
np.*lin*?
Con el comando %run
podemos ejecutar cualquier archivo .py
en un espacio de nombres limpio, sin imports
ni variables
definidas (a menos que corramos %run -i
).
Demo:
!mkdir temporal/
!touch temporal/mi_programa.py
!ls temporal/
!cat temporal/mi_programa.py
%%bash
mkdir temporal/
touch temporal/mi_programa.py
ls temporal/
mi_programa.py
!cat temporal/mi_programa.py
%%file temporal/mi_programa.py
def mi_funcion(x, y):
"""
Demo
"""
return x / y
x = 4
y = 2
resultado = mi_funcion(x, y)
Overwriting temporal/mi_programa.py
!cat temporal/mi_programa.py
def mi_funcion(x, y): """ Demo """ return x / y x = 4 y = 2 resultado = mi_funcion(x, y)
%run temporal/mi_programa.py
resultado
2
%%file temporal/mi_programa.py
def mi_funcion(x, y):
"""
Demo
"""
return x / y
x = 4
y = 0
resultado = mi_funcion(x, y)
Overwriting temporal/mi_programa.py
%run temporal/mi_programa.py
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) /home/damian/Desarrollos/To_PR/CONTRIBUTING/ipython/IPython/utils/py3compat.pyc in execfile(fname, *where) 181 else: 182 filename = fname --> 183 __builtin__.execfile(filename, *where) /home/damian/Python Conferences/ScipyConAr/tutorial/temporal/mi_programa.py in <module>() 8 y = 0 9 ---> 10 resultado = mi_funcion(x, y) /home/damian/Python Conferences/ScipyConAr/tutorial/temporal/mi_programa.py in mi_funcion(x, y) 3 Demo 4 """ ----> 5 return x / y 6 7 x = 4 ZeroDivisionError: integer division or modulo by zero
Los magics son comandos que facilitan las tareas más comunes y/o permiten interaccionar y controlar IPython.
Se reconocen por estar precedidos por %
(line-magics) o %%
(cell-magics).
Explicación detallada, tenemos un magic para ello: %magic
:
%magic
%lsmagic # si queremos listar todas las magics disponibles
Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cd %clear %colors %config %connect_info %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %install_default_config %install_ext %install_profiles %killbgscripts %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %lsmagic %macro %magic %man %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %run %save %sc %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%capture %%file %%html %%javascript %%latex %%perl %%prun %%pypy %%python %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit Automagic is ON, % prefix IS NOT needed for line magics.
%quickref # referencia rápida
quickref # si %automagic está ON
OK, usemos una magic (%timeit
) a modo de ejemplo:
%timeit?
m = np.random.randn(100, 100) # matriz de números aleatorios de 100 x 100
m
array([[-0.06020434, -0.32094883, -2.8624218 , ..., 0.57308841, -1.16990583, 0.678494 ], [ 0.5683235 , 1.410277 , -0.6028256 , ..., 1.75015083, 0.77766807, -0.32679313], [-0.92895948, -0.47488372, 0.21802094, ..., 1.29741317, -0.43273401, -0.25958936], ..., [-1.40861355, 0.413932 , -1.04962884, ..., 1.33899788, 0.7225967 , -1.60642745], [ 0.44397859, -0.65452681, -1.15851033, ..., 0.51260205, -0.6491627 , -0.07737892], [-0.91616426, -1.14552903, -0.52188168, ..., 1.76185015, 0.19011891, -0.37910311]])
%timeit np.dot(m, m) # multiplicación vectorial de matrices
100 loops, best of 3: 2.87 ms per loop
%timeit -n 1000 -r 10 np.dot(m, m) # las magics aceptan parámetros
1000 loops, best of 10: 2.89 ms per loop
Algunas magics
de uso frecuente que aun no hemos comentado:
%who
Fa Facultad Facundo a data lista m mi_funcion resultado x y
%who_ls
['Fa', 'Facultad', 'Facundo', 'a', 'data', 'lista', 'm', 'mi_funcion', 'resultado', 'x', 'y']
%whos
Variable Type Data/Info ---------------------------------- Fa int 4 Facultad int 8 Facundo int 1 a int 1 data dict n=7 lista list n=5 m ndarray 100x100: 10000 elems, type `float64`, 80000 bytes mi_funcion function <function mi_funcion at 0xa1635a4> resultado int 2 x int 4 y int 0
%xdel resultado
%who
NameError: name 'resultado' is not defined Fa Facultad Facundo a data lista m mi_funcion x y
%reset
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
m
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-39-69b64623f86d> in <module>() ----> 1 m NameError: name 'm' is not defined
Nota: %paste
y %cpaste
son magics
con uso frecuente en la consola de IPython.
magics
muy útiles.¶%qtconsole
%pylab
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
Inputs
y Outputs
:
2**4
16
_
16
foo = "bar"
foo
'bar'
_i65
u'foo = "bar"\nfoo'
_65
'bar'
foo = "baz"
foo
'baz'
exec _i76
foo
'bar'
Note: Logging magics
(%logstart
, %logstate
, %logstop
, %logon
y %logoff
) son útiles en la consola de IPython.
Usamos el signo de exclamación (!
) para enviar el comando a la consola del sistema:
!pwd
/home/damian/Python Conferences/ScipyConAr/tutorial
Incluso podemos capturar el output en una variable (en forma de una lista)
mes = !cal
este_mes = mes[0]
este_mes
' Mayo 2013 '
Pueden utilizarse variables definidas en el espacio de nombres actual, precediéndolas con el signo $
:
ipy_notebooks = '*.ipynb'
!ls
images SciPyConAr_NumPy.ipynb nbconvert SciPyConAr_Python_Cientifico.ipynb SciPyConAr_Final.ipynb SciPyConAr_SciPy.ipynb SciPyConAr_Herramientas.ipynb scripts SciPyConAr_IPython.ipynb stockholm_td_adj.dat SciPyConAr_Matplotlib.ipynb temporal
!ls $ipy_notebooks
SciPyConAr_Final.ipynb SciPyConAr_NumPy.ipynb SciPyConAr_Herramientas.ipynb SciPyConAr_Python_Cientifico.ipynb SciPyConAr_IPython.ipynb SciPyConAr_SciPy.ipynb SciPyConAr_Matplotlib.ipynb
Asimismo puedo establecer "apodos" o %alias
de la siguiente forma:
%alias ld ls -l
ld
total 6164 drwxrwxr-x 2 damian damian 4096 may 14 21:23 images/ drwxrwxr-x 11 damian damian 4096 may 15 18:58 nbconvert/ -rw-rw-r-- 1 damian damian 3204 may 16 10:52 SciPyConAr_Final.ipynb -rw-rw-r-- 1 damian damian 670721 may 15 00:14 SciPyConAr_Herramientas.ipynb -rw-rw-r-- 1 damian damian 40040 may 16 11:54 SciPyConAr_IPython.ipynb -rw-rw-r-- 1 damian damian 1515011 may 16 10:45 SciPyConAr_Matplotlib.ipynb -rw-rw-r-- 1 damian damian 66141 may 13 16:23 SciPyConAr_NumPy.ipynb -rw-rw-r-- 1 damian damian 20162 may 16 10:52 SciPyConAr_Python_Cientifico.ipynb -rw-rw-r-- 1 damian damian 1103360 may 16 10:48 SciPyConAr_SciPy.ipynb drwxrwxr-x 2 damian damian 4096 may 16 11:03 scripts/ -rw-rw-r-- 1 damian damian 2864946 may 10 08:35 stockholm_td_adj.dat drwxrwxr-x 2 damian damian 4096 may 16 11:23 temporal/
El %alias
puede incluso contener varios comandos separados por (;
):
%alias l_clases (cd /home/damian/Bioestadistica/Clases; ls)
l_clases
Bioestadistica - Clase 10.pdf Bioestadistica - Clase 4.pdf Bioestadistica - Clase 11.pdf Bioestadistica - Clase 5.pdf Bioestadistica - Clase 12.pdf Bioestadistica - Clase 6.pdf Bioestadistica - Clase 1.pdf Bioestadistica - Clase 7.pdf Bioestadistica - Clase 2.pdf Bioestadistica - Clase 8.pdf Bioestadistica - Clase 3.pdf Bioestadistica - Clase 9.pdf
Puedo usar marcadores para directorios de uso recurrente:
%bookmark clases /home/damian/Bioestadistica/Clases/
%cd clases
(bookmark:clases) -> /home/damian/Bioestadistica/Clases/ /home/damian/Bioestadistica/Clases
!ls
Bioestadistica - Clase 10.pdf Bioestadistica - Clase 4.pdf Bioestadistica - Clase 11.pdf Bioestadistica - Clase 5.pdf Bioestadistica - Clase 12.pdf Bioestadistica - Clase 6.pdf Bioestadistica - Clase 1.pdf Bioestadistica - Clase 7.pdf Bioestadistica - Clase 2.pdf Bioestadistica - Clase 8.pdf Bioestadistica - Clase 3.pdf Bioestadistica - Clase 9.pdf
%debug
(post-mortem debugger, lo inicializás después de la aparición de una excepción).%pdb
(inicializa el debugger después de cada excepción).%prun
o %run -p
(profiling en general).%lprun
(profiling por linea, necesita de line-profiler).