Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News Sign UpSign In
| Download

Jupyter notebook Programación para ingenieria con python & IPython.ipynb

Views: 462
Kernel: Python 2 (SageMath)
import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
x, y=1,2 x, y
(1, 2)
print(x==y)
False
print(x<y)
True
print(x>y)
False
print(x != y)
True
1 + 1j > 0 + 1j
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-9013fa957535> in <module>() ----> 1 1 + 1j > 0 + 1j TypeError: no ordering relation is defined for complex numbers
x = 10 y = 2 if x > y: print('x es mayor que y')
x es mayor que y
if x < y: print('x es menor que y') elif x == y: print('x es igual a y') else: print('x es mayor que y')
x es mayor que y
ii = 0 while ii < 5: print(ii) # ii = ii + 1 ii += 1 #if ii == 3: #break else: print('El bucle ha terminado')
0 1 2 3 4 El bucle ha terminado
for ii in 1, 0, 7: print(ii)
1 0 7
for nombre in "Juan", "Luis", "Carlos": print(nombre)
Juan Luis Carlos
for ii in 1, 0, 2, 8: print(ii) if ii == 2: pass else: print('El bucle ha llegado al final')
1 0 2 8 El bucle ha llegado al final
una_tupla = (1, 3, 3.0, 4+0j, '5') una_tupla
(1, 3, 3.0, (4+0j), '5')
una_lista=[1, 2, 3.0, 4+0j, '5'] una_lista
[1, 2, 3.0, (4+0j), '5']
una_tupla == una_lista
False
for elemento in una_tupla: print(elemento)
1 3 3.0 (4+0j) 5
1 in una_tupla
True
2 in una_lista
True
una_tupla[2]
3.0
una_tupla[0]
1
una_tupla[1]
3
una_tupla[-1]
'5'
una_tupla[2:4]
(3.0, (4+0j))
lista_anidada = [[1, 2],[3, 4]] lista_anidada
[[1, 2], [3, 4]]
Lista_anidada = [ [1, 2], [3, 4] ] Lista_anidada
[[1, 2], [3, 4]]
def function(x, y): pass
function
<function __main__.function>
def al_cuadrado(x): '''Funcion que eleva un numero al cuadrado''' y = x ** 2 return y
al_cuadrado(4)
16
al_cuadrado(5)
25
al_cuadrado?
def multiplica(x, y=1.0): """Multiuplica dos números, por defecto el primero por 1 """ return x * y
multiplica(2)
2.0
multiplica(4)
4.0
multiplica(2,3)
6
multiplica(1,y=1.0)
1.0
x
10
for ii in range(1, 3): print(ii)
1 2
4 % 3
1
def foo(x): """Funcion de prueba""" for ii in range(0, x): if ii % 3 == 0: print("El numero es multiplo de 3") elif ii % 5 == 0: print("El numero es multiplo de 5") else: print(ii) foo(8)
El numero es multiplo de 3 1 2 El numero es multiplo de 3 4 El numero es multiplo de 5 El numero es multiplo de 3 7
%load_ext pep8magic
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-73-6d157f8783bf> in <module>() ----> 1 get_ipython().magic(u'load_ext pep8magic') /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s) 2334 magic_name, _, magic_arg_s = arg_s.partition(' ') 2335 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) -> 2336 return self.run_line_magic(magic_name, magic_arg_s) 2337 2338 #------------------------------------------------------------------------- /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line) 2255 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2256 with self.builtin_trap: -> 2257 result = fn(*args,**kwargs) 2258 return result 2259 /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/magics/extension.pyc in load_ext(self, module_str) /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k) 191 # but it's overkill for just that one bit of state. 192 def magic_deco(arg): --> 193 call = lambda f, *a, **k: f(*a, **k) 194 195 if callable(arg): /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/magics/extension.pyc in load_ext(self, module_str) 64 if not module_str: 65 raise UsageError('Missing module name.') ---> 66 res = self.shell.extension_manager.load_extension(module_str) 67 68 if res == 'already loaded': /projects/sage/sage-6.9/local/lib/python2.7/site-packages/IPython/core/extensions.pyc in load_extension(self, module_str) 87 if module_str not in sys.modules: 88 with prepended_to_syspath(self.ipython_extension_dir): ---> 89 __import__(module_str) 90 mod = sys.modules[module_str] 91 if self._call_load_ipython_extension(mod): ImportError: No module named pep8magic
%pep8 if 6*9==42:print["Something Fundamentally wrong..."]
ERROR: Cell magic `%%pep8` not found.
import numpy
numpy.linalg.norm
<function numpy.linalg.linalg.norm>
import numpy as np
np.lookfor("solve")
Search results for 'solve' -------------------------- numpy.linalg.solve Solve a linear matrix equation, or system of linear scalar equations. numpy.linalg.lstsq Return the least-squares solution to a linear matrix equation. numpy.linalg.tensorsolve Solve the tensor equation ``a x = b`` for x. numpy.linalg._umath_linalg.solve solve the system a x = b, on the last two dimensions, broadcast to the rest. numpy.linalg._umath_linalg.solve1 solve the system a x = b, for b being a vector, broadcast in the outer dimensions. numpy.distutils.misc_util.njoin Join two or more pathname components + numpy.distutils.misc_util.minrelpath Resolve `..` and '.' from path. numpy.distutils.system_info.UmfpackNotFoundError UMFPACK sparse solver (http://www.cise.ufl.edu/research/sparse/umfpack/) numpy.linalg.pinv Compute the (Moore-Penrose) pseudo-inverse of a matrix. numpy.linalg.cholesky Cholesky decomposition. numpy.linalg.tensorinv Compute the 'inverse' of an N-dimensional array. numpy.linalg.LinAlgError Generic Python-exception-derived object raised by linalg functions. numpy.polynomial.hermite.hermfit Least squares fit of Hermite series to data. numpy.polynomial.laguerre.lagfit Least squares fit of Laguerre series to data. numpy.polynomial.legendre.legfit Least squares fit of Legendre series to data. numpy.polynomial.chebyshev.chebfit Least squares fit of Chebyshev series to data. numpy.polynomial.hermite_e.hermefit Least squares fit of Hermite series to data. numpy.polynomial.polynomial.polyfit Least-squares fit of a polynomial to data.
np.e
2.718281828459045
np.pi
3.141592653589793
np.log(2)
0.69314718055994529
np.array([1,2,3])
array([1, 2, 3])
np.array([1.,2.,3.])
array([ 1., 2., 3.])
a = np.array([1,2,3.0]) print(a.dtype)
float64
array([1, 2, "3"])
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-81daf8c61bdd> in <module>() ----> 1 array([1, 2, "3"]) NameError: name 'array' is not defined
np.array([1, 2, 3], dtype=float)
array([ 1., 2., 3.])
np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
a
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-60b725f10c9c> in <module>() ----> 1 a NameError: name 'a' is not defined
a.astype(int)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-14-56816b5d7e39> in <module>() ----> 1 a.astype(int) NameError: name 'a' is not defined

Motivo: eficiencia

  • Los bucles son costosos

  • Eliminar bucles: vectorizar operaciones

  • Los bucles se ejecutan en Python, las operaciones vectorizadas en C

  • Las operaciones entre arrays de Numpy se realizan elemento a elemento

Ejemplo:

aij=bij+cija_{ij}=b_{ij}+c_{ij}

N, M = 100, 100 a = np.empty(10000).reshape(N, M) b = np.random.rand(10000).reshape(N, M) c = np.random.rand(10000).reshape(N, M)
%%timeit for i in range(N): for j in range(M): a[i, j] = b[i, j] + c[i, j]
100 loops, best of 3: 16.6 ms per loop
%%timeit a = b + c
10000 loops, best of 3: 18.3 µs per loop
from _future_ import braces
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-19-7c68fb7ecb73> in <module>() ----> 1 from _future_ import braces ImportError: No module named _future_

Indexación de arrays

Una de las herramientas más importantes a la hora de trabajar con arrays es el indexado. Consiste en seleccionar elementos aislados o secciones de un array. Nosotros vamos a ver la indexación básica, pero existen trécnicas de indexación avanzada que convierten los arrays en herramientas potentísimas.

a = np.array([ [1,2,3], [4,5,6] ]) a
array([[1, 2, 3], [4, 5, 6]])

En Python

a[0][0]
1

En Numpy

a[0, 0]
1
a[0:2, 1:3]
array([[2, 3], [5, 6]])

Los índices se indican entre corchetes justo después del array. Recuerda que en Python la indexación empieza en 0. Si recuperamos el primer elemento de un array de dos dimensiones, obtnemos la primera fila.

a[0, 0:3:2]
array([1, 3])
a[0, ::2]
array([1, 3])

Creación de arrays

Muchos métodos y muy variados

  • A partir de datos existentes: array, copy

  • Unos y ceros: empty, eye, ones, zeros, *_like

  • Rangos: arrange, linspace, losçgspace, meshgrid

  • Aleatrorios: rand, randn

Unos y Ceros

  • empty(shape)crea un array con "basura", equivalente a no inicializarlo, ligeramente más rápido que zeros o ones

  • eye(N, M=None, k=0) crea un array con unos en una diagonal y ceros en el resto

  • identity(n) devuelve la matriz identidad

  • Las funciones *_like(a) construyen arrays con el mismo tamaño que uno dado

np.empty([3, 4])
array([[ 6.90608669e-310, 2.12986008e-316, 0.00000000e+000, 0.00000000e+000], [ 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000], [ 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
np.zeros([3, 4])
array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
np.ones([3, 4])
array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]])
np.identity(5)
array([[ 1., 0., 0., 0., 0.], [ 0., 1., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 1., 0.], [ 0., 0., 0., 0., 1.]])
np.identity(5).astype(int)
array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]])
i3 = np.identity(3) i3
array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]])
i3.shape
(3, 3)
np.ones(i3.shape)
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])
np.ones_like(i3)
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])

Rangos

  • linespace(start, stop, num=50) devuelve números equiespaciados dentro de un intervalo

  • logspace(start, stop, num=50, base=10.0) devuelve numeros equiespaciados según una escala logarítmica

  • meshgrid(x1, x2, ...) devuelve matrices de n - coordenadas

np.linspace(0, 1, num=10)
array([ 0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444, 0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ])
np.logspace(0, 3, num=10, base=10.0)
array([ 1. , 2.15443469, 4.64158883, 10. , 21.5443469 , 46.41588834, 100. , 215.443469 , 464.15888336, 1000. ])
x = np.linspace(0, 1, num=4) y = np.linspace(0, 1, num=4) xx, yy = np.meshgrid(x, y)

Operaciones con arrays

Las funciones universales (ufunc) operan sobre arrays de NumPy elemento a elemento y siguiendo las reglas de broadcasting

  • Funciones matemáticas; sin, cos, sqrt, exp, ...

  • Operaciones lógicas: <, ~, ...

  • Funciones lógicas: all, any, isnan, allclose, ...

Nota: Las funciones de matematicas siempre devuelven el mismo tipo de datos de entrada

a = np.arange(2 * 3).reshape(2, 3) a
array([[0, 1, 2], [3, 4, 5]])
np.sqrt(a)
array([[ 0. , 1. , 1.41421356], [ 1.73205081, 2. , 2.23606798]])
import numpy as np
np.sqrt(np.arange(-3, 3))
/projects/sage/sage-6.9/local/lib/python2.7/site-packages/ipykernel/__main__.py:1: RuntimeWarning: invalid value encountered in sqrt if __name__ == '__main__':
array([ nan, nan, nan, 0. , 1. , 1.41421356])
# corrección para poder trabajar con el código anterior np.arange(-3, 3).astype(complex)
array([-3.+0.j, -2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j])
a = np.arange(6) b = np.ones(6).astype(int) a, b
(array([0, 1, 2, 3, 4, 5]), array([1, 1, 1, 1, 1, 1]))

Funciones Lógicas

  • mayor que:">"

  • menor que:"<"

a < b
array([ True, False, False, False, False, False], dtype=bool)
np.any(a < b)
True
np.all(a < b)
False
a = np.arange(6).astype(float) b = np.ones(6) a, b
(array([ 0., 1., 2., 3., 4., 5.]), array([ 1., 1., 1., 1., 1., 1.]))
a < b
array([ True, False, False, False, False, False], dtype=bool)
np.any(a < b)
True
a = np.arange(6).astype(float) b = np.ones(6) a, b
(array([ 0., 1., 2., 3., 4., 5.]), array([ 1., 1., 1., 1., 1., 1.]))

Funciones de comparación

Las comparaciones devuelven un array de booleanos:

  • isclose(...)

  • allclose(...)

# isclose compara los arrays # rtol, ejemplo rtol=1e-6. Tolerancia np.isclose(a, b, rtol=1e-6)
array([False, True, False, False, False, False], dtype=bool)
np.allclose(a, b, rtol=1e-6)
False
a = np.arange(2 * 3).reshape(2, 3) a
array([[0, 1, 2], [3, 4, 5]])
np.sqrt(a)
array([[ 0. , 1. , 1.41421356], [ 1.73205081, 2. , 2.23606798]])

Ejercicios

Ejercicio 1

  1. Crear un array z1 3x4 lleno de ceros de tipo entero.

  2. Crear un array z2 3x4 lleno de ceros salvo la primera fila que serán todo unos.

  3. Crear un array z3 3x4 lleno de ceros salvo la última fila que será el rango entre 5 y 8

z1 = np.zeros([3, 4]).astype(int) z1
array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
z1[0,:]=1 z2 = z1 z2
array([[1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
z3 = np.zeros([3, 4]) z3[2, :] = np.arange(5, 9) z3
array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 5., 6., 7., 8.]])
b = np.zeros((3, 4)) b[-1] = np.arange(5, 9) b[:, -1] = np.arange(6, 9) b
array([[ 0., 0., 0., 6.], [ 0., 0., 0., 7.], [ 5., 6., 7., 8.]])

Ejercicio 2

  1. Crear un vector de 10 elementos, siendo los impares unos y los pares doses.

  2. Crea un "tablero de ajedrez", con unos en las casillas negras y ceros en las blancas

v = np.ones(10) v[1::2]=2 v
array([ 1., 2., 1., 2., 1., 2., 1., 2., 1., 2.])
tablero = np.zeros([8, 8]) tablero[1::2, ::2] = 1 tablero[::2, 1::2] = 1 tablero
array([[ 0., 1., 0., 1., 0., 1., 0., 1.], [ 1., 0., 1., 0., 1., 0., 1., 0.], [ 0., 1., 0., 1., 0., 1., 0., 1.], [ 1., 0., 1., 0., 1., 0., 1., 0.], [ 0., 1., 0., 1., 0., 1., 0., 1.], [ 1., 0., 1., 0., 1., 0., 1., 0.], [ 0., 1., 0., 1., 0., 1., 0., 1.], [ 1., 0., 1., 0., 1., 0., 1., 0.]])

Parte 3 - Visualizacion con matplotlib

¿Qué es matplotlib?

  • Estándar de facto para visualización en Python

  • Pretende ser similar a las funciones de visualización de MATLAB

  • Diferenferentes forma de usarla: interfaz pyplot<code> y orientadea a objetos

Lo primero que vamos a hacer es activar el modo inline - de ésta manera las figuras aparecerán automáticamente incrustadas en el notebook.

%matplotlib inline
import numpy as np import matplotlib.pyplot as plt

Interfaz pyplot

  • Función plot: listas o arrays

  • Personalización de lineas, colores, leyendas

  • Otros tipos de gráficas: scatter, contour, fill_between<code>

  • Cómo pintar un afunción en 1D, en 2D

  • plt.savefig<code>

import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.plot([1, -1, 0, 3, -1]) plt.show()
Image in a Jupyter notebook
import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.plot([0,0.1,0.2,0.5,0.6],[1, -1, 0, 3, -1])
[<matplotlib.lines.Line2D at 0x7fddd6549210>]
Image in a Jupyter notebook

f(x)=ex2f(x) = e^{-x^{2}}

def f(x): return np.exp(-x ** 2)
x = np.linspace(-1, 5, num=30)
plt.plot(x, f(x),'og',label = "Funcion f(x)") plt.xlabel('Eje x') plt.ylabel("$f(x)$") plt.grid(True) plt.legend() plt.title('$E = mc^{2}$') plt.show()
Image in a Jupyter notebook

Interfaz orientada a objetos

x
array([-1. , -0.79310345, -0.5862069 , -0.37931034, -0.17241379, 0.03448276, 0.24137931, 0.44827586, 0.65517241, 0.86206897, 1.06896552, 1.27586207, 1.48275862, 1.68965517, 1.89655172, 2.10344828, 2.31034483, 2.51724138, 2.72413793, 2.93103448, 3.13793103, 3.34482759, 3.55172414, 3.75862069, 3.96551724, 4.17241379, 4.37931034, 4.5862069 , 4.79310345, 5. ])
f(x)
array([ 3.67879441e-01, 5.33117686e-01, 7.09185234e-01, 8.65994832e-01, 9.70710971e-01, 9.98811646e-01, 9.43400884e-01, 8.17952307e-01, 6.50996579e-01, 4.75607235e-01, 3.18960733e-01, 1.96356377e-01, 1.10961373e-01, 5.75595853e-02, 2.74083260e-02, 1.19802640e-02, 4.80694649e-03, 1.77048075e-03, 5.98593712e-04, 1.85777072e-04, 5.29262471e-05, 1.38410522e-05, 3.32266179e-06, 7.32187295e-07, 1.48107572e-07, 2.75011817e-08, 4.68753445e-09, 7.33426522e-10, 1.05338655e-10, 1.38879439e-11])

Interfaz orientada a objetos

  • fig, axes = plt.subplots<code>

  • Diferencias de conceptos

fig, axes = plt.subplots() axes.plot(x, f(x), 'ro', label = 'Funcion F(x)') axes.set_xlim(-2, 4) axes.set_ylim(-1, 2) axes.grid(True) fig.savefig("grafica2.png")
Image in a Jupyter notebook
fig, axes = plt.subplots(1, 2, sharey=True) axes[0].plot(x, f(x), color="g") axes[0].set_xlabel("Eje x") axes[0].grid(True) axes[1].plot(x, -f(x), 'r-.') axes[1].set_xlabel("Eje x de la grafica derecha") axes[1].grid(True)
Image in a Jupyter notebook
x = np.random.randn(100) y = np.random.randn(100) s = 200 * np.random.randn(100) c = np.random.randn(100) plt.scatter(x, y, s, c, cmap=plt.cm.BrBG_r)
<matplotlib.collections.PathCollection at 0x7fdda5babd50>
Image in a Jupyter notebook
axes
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fdda67f3310>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fdda679c690>], dtype=object)
plt.plot(np.sin(x)) plt.show()
Image in a Jupyter notebook
x = np.linspace(0, 10) line = plt.plot(x, np.sin(x), '--', linewidth=2) plt.show()
Image in a Jupyter notebook

Clase 10 (video 10)

g(x,y)=cos(x)+sen(y)2\large g(x, y) = cos(x) + sen(y)^2

x = np.linspace(-2, 2) y = np.linspace(-2, 2) xx, yy = np.meshgrid(x, y)
def g(x,y): return np.cos(x)+np.sin(y) ** 2
zz = g(xx, yy)
fig, axes = plt.subplots() axes.contour(xx, yy, zz)
<matplotlib.contour.QuadContourSet instance at 0x7fdda5b48f80>
Image in a Jupyter notebook
fig, axes = plt.subplots() axes.contour(xx, yy, zz, [-1,0,1])
<matplotlib.contour.QuadContourSet instance at 0x7fdda8fcef38>
Image in a Jupyter notebook
fig, axes = plt.subplots() axes.contour(xx, yy, zz,cmap=plt.cm.autumn)
<matplotlib.contour.QuadContourSet instance at 0x7fdda5bbb5f0>
Image in a Jupyter notebook
fig, axes = plt.subplots() axes.contourf(xx, yy, zz, cmap=plt.cm.autumn)
<matplotlib.contour.QuadContourSet instance at 0x7fdda64743f8>
Image in a Jupyter notebook
fig, axes = plt.subplots() axes.contourf(xx, yy, zz, np.linspace(-1,1), cmap=plt.cm.autumn)
<matplotlib.contour.QuadContourSet instance at 0x7fdda62c4488>
Image in a Jupyter notebook

Ejemplo con datos reales

!type temperatura.csv
temperatura.csv: not found
datos = np.loadtxt('temperatura.csv', usecols=(1,2,3), skiprows=2, delimiter=',') print(datos)
[[ 26. 10. 36.] [ 25. 10. 39.] [ 24. 10. 41.] [ 23. 10. 35.] [ 23. 10. 44.] [ 22. 11. 50.] [ 23. 10. 44.] [ 23. 10. 44.] [ 21. 10. 49.] [ 21. 11. 53.] [ 21. 11. 53.] [ 20. 10. 52.] [ 20. 10. 52.] [ 20. 10. 52.] [ 19. 10. 56.] [ 20. 11. 56.] [ 22. 11. 40.] [ 21. 11. 53.] [ 22. 11. 50.] [ 24. 11. 44.] [ 25. 11. 41.] [ 27. 10. 34.] [ 28. 10. 32.] [ 29. 10. 30.] [ 31. 10. 27.] [ 31. 9. 25.] [ 32. 9. 24.] [ 33. 9. 14.] [ 32. 9. 24.] [ 33. 8. 21.] [ 33. 8. 21.] [ 33. 8. 21.] [ 33. 7. 20.] [ 34. 7. 19.] [ 34. 6. 17.] [ 34. 7. 19.] [ 34. 7. 19.] [ 34. 6. 17.] [ 34. 6. 17.] [ 34. 6. 17.] [ 34. 7. 10.] [ 33. 7. 20.] [ 33. 7. 20.] [ 33. 7. 20.] [ 32. 8. 22.] [ 31. 8. 24.] [ 31. 9. 25.] [ 30. 9. 27.] [ 30. 9. 27.]]
fig, axes = plt.subplots() x = np.arange(len(datos[:, 1])) axes.plot(x, datos[:, 1], 'r') axes.plot(x, datos[:, 2],'b')
[<matplotlib.lines.Line2D at 0x7fdda572b090>]
Image in a Jupyter notebook
fig, axes = plt.subplots() x = np.arange(len(datos[:, 1])) temp_media = (datos[:, 1] + datos[:, 2])/2 axes.plot(x, datos[:, 1], 'r') axes.plot(x, datos[:, 2],'b') axes.plot(x, temp_media, 'k')

Parte 4 - SciPy

¿Qué es SciPy?

  • Conjunto de paquetes para computación Científica en general

  • Integración, optimización, interpolación, procesamiento de señales digitales, estadísticas

  • Normalmente interfaces a programas muy utilizados escritos en Fortran, o C++

%matplotlib inline
import numpy as np import matplotlib.pyplot as plt

**Integración Numérica**

from scipy import integrate

f(x)=ex2f(x)=e^{-x^{2}}

def f(x): return np.exp(-x ** 2)
integrate.quad(f, 0, 5)
(0.8862269254513955, 2.3183115159980698e-14)

f(x)=Aex2f(x)=Ae^{-x^{2}}

def f(x, A): return A * np.exp(-x ** 2)
integrate.quad(f, 0, 5, args=1.0)
(0.8862269254513955, 2.3183115159980698e-14)

f(x)=eBx2f(x)=e^{-Bx^{2}}

def f(x, A, B): return A * np.exp(-B * x ** 2)
integrate.quad(f, 0, 5, args=(1.0, 1.0))
(0.8862269254513955, 2.3183115159980698e-14)

**Ecuaciones diferenciales ordinarias (EDO's)**

y+y=0y'+y=0

y=f(y)y'=f(y)

def f(y, t): return -y
y0 = 1.0
t = np.linspace(0, 3)
sol = integrate.odeint(f, y0, t)
plt.plot(t, sol)
[<matplotlib.lines.Line2D at 0x7fc3b60d4e50>]
Image in a Jupyter notebook

y+y=0y'' + y=0

f(y)=(yy)=(yy)=(yy)f(y) = \begin{pmatrix}{y}\\{y'}\end{pmatrix}'=\begin{pmatrix}{y'}\\{y''}\end{pmatrix}=\begin{pmatrix}{y'}\\{-y}\end{pmatrix}

def f(y, t): return np.array([y[1], -y[0]])
t = np.linspace(0, 10)
y0 = np.array([1.0, 0.0])
sol = integrate.odeint(f, y0, t)
sol
array([[ 1. , 0. ], [ 0.97924752, -0.20266792], [ 0.91785142, -0.39692413], [ 0.81835993, -0.57470602], [ 0.68490246, -0.72863476], [ 0.52301813, -0.85232155], [ 0.33942597, -0.94063276], [ 0.14174595, -0.98990306], [-0.06181722, -0.99808747], [-0.26281468, -0.96484631], [-0.45290402, -0.89155926], [-0.6241956 , -0.78126807], [-0.76957997, -0.6385504 ], [-0.88302297, -0.46932972], [-0.95981615, -0.28062952], [-0.99677219, -0.0802818 ], [-0.99235725, 0.12339801], [-0.94675456, 0.32195619], [-0.86185686, 0.5071516 ], [-0.74118783, 0.6712977 ], [-0.58975583, 0.80758162], [-0.41384604, 0.9103469 ], [-0.22075958, 0.97532827], [-0.01851051, 0.99982868], [ 0.18450685, 0.98283125], [ 0.37986625, 0.92504144], [ 0.55945933, 0.82885784], [ 0.71583207, 0.69827252], [ 0.84249423, 0.53870543], [ 0.93418871, 0.35677939], [ 0.98710972, 0.16004524], [ 0.99906079, -0.04333159], [ 0.96954589, -0.24490994], [ 0.89979002, -0.43632331], [ 0.79268841, -0.60962711], [ 0.65268629, -0.75762836], [ 0.48559446, -0.87418429], [ 0.29834805, -0.95445723], [ 0.09871872, -0.99511547], [-0.10500794, -0.99447148], [-0.30437624, -0.952552 ], [-0.49111143, -0.87109689], [-0.65746306, -0.75348693], [-0.79652672, -0.60460354], [-0.90253057, -0.43062609], [-0.97107493, -0.23877553], [-0.99931487, -0.0370146 ], [-0.98607829, 0.16628263], [-0.93191456, 0.36267831], [-0.83907176, 0.54402103]])
plt.plot(t, sol[:, 0])
[<matplotlib.lines.Line2D at 0x7fc3b5f31150>]
Image in a Jupyter notebook
plt.plot(t, sol[:, 0]) # posicion plt.plot(t, sol[:, 1], '--') # velocidad
[<matplotlib.lines.Line2D at 0x7fc3b5cea350>]
Image in a Jupyter notebook
plt.plot(t, sol)
[<matplotlib.lines.Line2D at 0x7fc3b5cb3050>, <matplotlib.lines.Line2D at 0x7fc3b5cb32d0>]
Image in a Jupyter notebook

Ecuaciones algebraicas no lineales

import numpy as np from scipy import optimize

M=Eesin(E) M = E - e sin(E)

F(E)=Eesin(E)M F(E) = E - e sin(E) - M

def F(E, e, M): return E - e * np.sin(E) - M
sol = optimize.root(F, 0.1, args=(0.016, 0.1)) sol
status: 1 success: True qtf: array([ 2.84494650e-15]) nfev: 5 r: array([-0.98408255]) fun: array([ 0.]) x: array([ 0.10162317]) message: 'The solution converged.' fjac: array([[-1.]])
sol.x
array([ 0.10162317])

Interpolacion

from scipy import interpolate
import numpy as np from scipy.interpolate import barycentric_interpolate def runge(x): """Función de Runge""" return 1 / (1 + x ** 2) N = 11 # Nodos de interpolación xp = np.arange(11) - 5 # -5, -4, -3, ..., 3, 4, 5 fp = runge(xp) x = np.linspace(-5, 5, num=1000) y = barycentric_interpolate(xp, fp, x)
%matplotlib inline import matplotlib.pyplot as plt l, = plt.plot(x, y) plt.plot(x, runge(x), '--', c=l.get_color()) plt.plot(xp, fp, 'o', c=l.get_color()) leg = plt.legend(['Interpolacion', 'Real']) leg.get_frame().set_facecolor('#fafafa')
Image in a Jupyter notebook
<html lang="en"> <head> <meta charset="UTF-8"> <title>Matching Game p3</title> <style> img {position: absolute} #leftSide, #rightSide {position: absolute; width: 500; height: 500;} #rightSide { left: 500px; border-left: 1px solid black; background:lightblue; } </style> <script> function generateFaces() { var top_position = 15, left_position = 20; var width = 80, height = 80; var numberOfFaces = 5; var theLeftSide = document.getElementById("leftSide"); for (var index = 0; index < numberOfFaces; index++) { // alert("hola") var the_img = document.createElement("img"); // image src the_img.src="smile.png"; // set position for the img ramdomly var random_pos_top = Math.random() * 400; var random_pos_left = Math.random() * 400; random_pos_top = Math.floor(random_pos_top); random_pos_left = Math.floor(random_pos_left); the_img.style.top = random_pos_top + "px"; the_img.style.left = random_pos_left + "px"; the_img.style.width = width + "px"; the_img.style.height = height + "px"; // Add the newly created image to the leftSide div using appendChild() theLeftSide.appendChild(the_img); }; var theRightSide = document.getElementById("rightSide"); // Cloning var leftSideImages = theLeftSide.cloneNode(true); // Delrying lastChild leftSideImages.removeChild(leftSideImages.lastChild); // Adding images theRightSide.appendChild(leftSideImages); // 4th PART var theBody = document.getElementsByTagName("body")[0]; // Event Handler theLeftSide.lastChild.onclick = function nextLevel(event){ event.stopPropagation(); numberOfFaces += 5; generateFaces(); }; // Event Handler theBody.onclick = function gameOver() { alert("Game Over!"); theBody.onclick = null; theLeftSide.lastChild.onclick = null; }; } </script> </head> <body onload="generateFaces()"> <h1>Matching Game</h1> <p>Click on the extra dmiling face on the left</p> <div id="leftSide">L</div> <div id="rightSide">R</div> </body> </html>
File "<ipython-input-2-6b459e340c1b>", line 1 <html lang="en"> ^ SyntaxError: invalid syntax