Python devient de plus en plus une alternative à Matlab.
Pourquoi ?
"Ten reasons Python rocks for science": https://www.stat.washington.edu/~hoytak/blog/whypython.html
On verra ici :
introduction à la programmation scientifique et l'utilisation de vecteurs/matrices
import numpy as np
a = np.random.random(1000)
print(type(a))
print(a[:10])
print("-->",a.min(),a.max(),a.mean())
from numpy import cos
c = cos(a)
print(c[:10])
(a+a)[:10]
c = np.array(a)
c = c.reshape(5,200)
print(c[0,9],a[9])
print()
print(c[:,2:4])
c[:,2:4].ravel()
c = np.arange(0.,1.,0.05)
c
c = np.linspace(0,1.,21)
c
np.zeros((2,2))
np.ones((2,2))
np.eye(3)
attention aux références -> différent des listes
a = c[1:-1]
c[1] = -1
print(a[:10])
c[0] = 0
a = np.zeros(c.shape)
# ou
#a[:] = c
a[...] = c
c[0] = 2
print(a[:10])
# version 1
ia1 = np.argwhere((a>.55) | (a<0.))
print(a[ia1].ravel())
# Version 2
print(a[(a<0.) | (a>0.55)])
Calculer l'approximation de $\pi$ avec la formule de Wallis: $$ \pi = 2\prod_{i=1}^{\infty} \frac{4i^2}{4i^2-1}$$
import numpy as np
a = np.arange(10000)+1
b = 4.*a*a
c = b/(b-1.)
wallis = 2*np.cumprod(c)[-1]
print(wallis)
Moyenne glissante
from numpy import sin
%pylab inline
x = np.linspace(-20,20,1000)
a = sin(x/2.) + np.random.normal(scale=0.2,size=1000)
figure = pylab.plot(x,a)
c = np.array(a)
c[1:-1] += a[:-2] + a[2:]
c[1:-1] *= 1./3
pylab.plot(x,c)
l'opération plus générale (convolution) -> existe dans scipy: convolve, et smooth
a = np.arange(100)
a = a.reshape(10,10)
a
a+10
a[:2,0:3]
b = np.arange(10)-5
print(b)
a+b
x = np.linspace(0.,5.,6)
y = np.linspace(0.,3.,4)
(X,Y) = np.meshgrid(x,y)
print("%s\n\n%s"%(X,Y))
a = X*X + Y*Y
a
x*x+y*y
Traitement du signal en python : Scipy, une surcouche de numpy
Plusieurs librairies python (ou avec interface python) pour l'image
plusieurs librairies disponibles
#Exemple
import networkx as nx
# graphe aléatoire
G = nx.random_geometric_graph(150, 0.12)
pos = nx.get_node_attributes(G, 'pos')
dists = [(x - 0.5)**2 + (y - 0.5)**2 for x, y in pos.values()]
ncenter = np.argmin(dists)
p = nx.single_source_shortest_path_length(G, ncenter)
pylab.figure()
nx.draw_networkx_edges(G, pos, alpha=0.4)
nx.draw_networkx_nodes(G, pos, nodelist=p.keys(),
node_size=120, alpha=0.5,
node_color=list(p.values()), cmap=pylab.cm.hot)
pylab.show()
pandas: surcouche de numpy pour "émuler" R
import pandas as pds
a = pds.DataFrame({'pib':numpy.random.normal(size=5),'pop':5+numpy.random.normal(size=5)})
a
a[a["pib"]>0]
figure = a.boxplot()
"Ten reasons Python rocks for science": https://www.stat.washington.edu/~hoytak/blog/whypython.html