Algorithmes avec Numpy¶

Marc BUFFAT, dpt mécanique, Université Lyon 1 et [1]

Rappels sur les vecteurs numpy¶

Génération de tableaux

  • liste de valeurs
  • valeurs constantes
  • liste de valeurs équi-réparties
  • valeurs aléatoires
In [28]:
import numpy as np
## BEGIN SOLUTION
X = np.array([1,2,3,4])
n = 10
X = np.ones(10)
print(X)
X = np.linspace(0,1,11)
print(X)
X = np.arange(11)/10.
print(X)
X = 1-2*np.random.rand(11)
print(X)
## END SOLUTION
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
[ 0.16562619  0.84984178 -0.35845808 -0.44110587  0.40773216  0.33588114
  0.09532665 -0.0571162   0.3649131  -0.113637    0.89881505]

Sélections de valeurs¶

  • sélection intervalle deb:fin:pas
  • sélection avec une condition
  • accès aux indices
  • adressage indirect : liste d'indices
In [29]:
X = 1-2*np.random.rand(11)
print(X[::])
[ 0.52292901 -0.51488077  0.91578568 -0.09987739 -0.83243055  0.6492485
  0.6437185  -0.64774017  0.29049721  0.15191003 -0.95772094]
In [30]:
n = 11
X = 2-4*np.random.rand(n)
print(X)
[-0.3105191   1.51186253 -0.95438364 -0.94603449  1.50517692 -1.76544599
  0.94351177 -1.66360124 -1.33597164 -1.3941285  -1.17236811]
In [31]:
# selection de valeur: intervalle, conditions (valeur positive)
## BEGIN SOLUTION
n = X.size
print(X[0:n//2])
print(X[n//2:])
#
print(X[[3,0,1]])
# valeurs positives
print(X[X>0])
print(X.mean(),X.min(),X.max())
## END SOLUTION
[-0.3105191   1.51186253 -0.95438364 -0.94603449  1.50517692]
[-1.76544599  0.94351177 -1.66360124 -1.33597164 -1.3941285  -1.17236811]
[-0.94603449 -0.3105191   1.51186253]
[1.51186253 1.50517692 0.94351177]
-0.5074455894511868 -1.7654459942499958 1.5118625315569343
In [32]:
# acces aux indices avec fonction np.where , np.armin, np.argmax
## BEGIN SOLUTION
print(np.argmax(X), X[np.argmax(X)])
print(np.where(X>0),X[np.where(X>0)])
## END SOLUTION
1 1.5118625315569343
(array([1, 4, 6]),) [1.51186253 1.50517692 0.94351177]

Calcul avec des vecteurs¶

  • opérations mathématiques (terme à terme)
    • + - * / **
  • fonctions mathématiques (dans np)
    • sin , cos, exp, log, log10, power, sqrt, tan, arctan, arctan2
  • constantes :
    • pi, e
In [33]:
## BEGIN SOLUTION
X = np.linspace(-1,1,101)
Y = 4*X**3 - 2*X
## END SOLUTION
In [57]:
# verification
np.log(np.e), np.log10(10)
Out[57]:
(1.0, 1.0)

Documentation Numpy¶

  • sites web ooficiel: site https://numpy.org ou https://scipy.org
  • ollama: https://iagpu2-streamlit.univ-lyon1.fr/ollama/?&cours=MGC2028L&mode=question
  • online

exemple : fonction arctan2

In [59]:
np.arctan2?
Call signature:  np.arctan2(*args, **kwargs)
Type:            ufunc
String form:     <ufunc 'arctan2'>
File:            /var/lib/jupyterhub/venvs/py3.9/lib/python3.9/site-packages/numpy/__init__.py
Docstring:      
arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.

The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is
the signed angle in radians between the ray ending at the origin and
passing through the point (1,0), and the ray ending at the origin and
passing through the point (`x2`, `x1`).  (Note the role reversal: the
"`y`-coordinate" is the first function parameter, the "`x`-coordinate"
is the second.)  By IEEE convention, this function is defined for
`x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see
Notes for specific values).

This function is not defined for complex-valued arguments; for the
so-called argument of complex values, use `angle`.

Parameters
----------
x1 : array_like, real-valued
    `y`-coordinates.
x2 : array_like, real-valued
    `x`-coordinates.
    If ``x1.shape != x2.shape``, they must be broadcastable to a common
    shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or None,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``, locations within it where the condition is False will
    remain uninitialized.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
angle : ndarray
    Array of angles in radians, in the range ``[-pi, pi]``.
    This is a scalar if both `x1` and `x2` are scalars.

See Also
--------
arctan, tan, angle

Notes
-----
*arctan2* is identical to the `atan2` function of the underlying
C library.  The following special values are defined in the C
standard: [1]_

====== ====== ================
`x1`   `x2`   `arctan2(x1,x2)`
====== ====== ================
+/- 0  +0     +/- 0
+/- 0  -0     +/- pi
 > 0   +/-inf +0 / +pi
 < 0   +/-inf -0 / -pi
+/-inf +inf   +/- (pi/4)
+/-inf -inf   +/- (3*pi/4)
====== ====== ================

Note that +0 and -0 are distinct floating point numbers, as are +inf
and -inf.

References
----------
.. [1] ISO/IEC standard 9899:1999, "Programming language C."

Examples
--------
Consider four points in different quadrants:

>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135.,  -45.,   45.,  135.])

Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:

>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([0.        , 3.14159265, 0.78539816])
Class docstring:
Functions that operate element by element on whole arrays.

To see the documentation for a specific ufunc, use `info`.  For
example, ``np.info(np.sin)``.  Because ufuncs are written in C
(for speed) and linked into Python with NumPy's ufunc facility,
Python's help() function finds this page whenever help() is called
on a ufunc.

A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

**Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``

Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

The broadcasting rules are:

* Dimensions of length 1 may be prepended to either array.
* Arrays may be repeated along dimensions of length 1.

Parameters
----------
*x : array_like
    Input arrays.
out : ndarray, None, or tuple of ndarray and None, optional
    Alternate array object(s) in which to put the result; if provided, it
    must have a shape that the inputs broadcast to. A tuple of arrays
    (possible only as a keyword argument) must have length equal to the
    number of outputs; use None for uninitialized outputs to be
    allocated by the ufunc.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``, locations within it where the condition is False will
    remain uninitialized.
**kwargs
    For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
r : ndarray or tuple of ndarray
    `r` will have the shape that the arrays in `x` broadcast to; if `out` is
    provided, it will be returned. If not, `r` will be allocated and
    may contain uninitialized values. If the function has more than one
    output, then the result will be a tuple of arrays.

Recherche d'erreur¶

  • utilisation de print
  • utilisation d'ollama
    • https://iagpu2-streamlit.univ-lyon1.fr/ollama/?&cours=MGC2028L&mode=code1
In [34]:
def minimum(f,a,b,eps):
    while (b-a) > eps :
        x1 = (a+b)/2.
        x2 = (a+x1)/2.
        x3 = (x1+b)/2.
        if f(x2)<f(a) and f(x2)<f(x1):
            b = x1
        elif f(x3)<f(x1) and f(x3)<f(b):
            a = x1
        else :
            a = x2
            b = x3
        return (a+b)/2.

Exemple: étude de fonction et calcul de racine¶

Soit la courbe cubique $y=P(x)$ avec

$$ P(x) = 4x^3 - 2x $$

Pour une valeur de $R$ donnée, on cherche à déterminer la valeur de $x$ telle que $P(x)=R$, c.a.d la racine de l'équation $P(x)=R$, i.e. $$ \mbox{Trouvez }x\in\mathcal{R} \mbox{ t.q. } P(x)=R $$

Attention: ce problème peut admettre une ou plusieurs solutions.

Analyse du problème¶

Géométriquement, le problème revient à déterminer l'intersection de la courbe $y=P(x)$ avec la droite horizontale $y=R$.

On trace donc la courbe $y=P(x)$ et la droite $y=R$ pour $R=1.0$

On calcule ensuite la valeur de la racine avec la fonction fsolve de la bibliothèque scipy.optimize.

Attention on doit choisir une point de départ proche de la racine que l'on souhaite calculer !

In [35]:
# tracer
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-1,1,101)
Y = 4*X**3 - 2*X
### BEGIN SOLUTION
R = 1.0
plt.figure(figsize=(10,8))
plt.plot(X,Y,label='y=P(x)')
plt.plot([X[0],X[-1]],[R,R],'--',label='y=R')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title("etude des racines de P(x)=R");
### END SOLUTION

Utilisation de fsolve¶

In [38]:
from scipy.optimize import fsolve
# definition fonction
## BEGIN SOLUTION
Pr = lambda x : 4*x**3 - 2*x - R
# intervalle d'étude
x0 = 0.75
#x0 = 0.0
#x0 = -0.75
xr = fsolve(Pr,x0)
print(xr,Pr(xr))
## END SOLUTION
[0.88464618] [-1.22346577e-13]

Utilisation algorithme de dichotomie¶

fonction dichotomie(f,a,b,eps)

  • comment l'utiliser dans notre cas ?
In [39]:
def dichotomie(f,a,b,eps):
    while (b-a) > eps:
        xm = (a+b)/2
        if f(a)*f(xm) < 0. :
            b = xm
        else :
            a = xm
    return (a+b)/2
In [40]:
### BEGIN SOLUTION
# definition fonction
Pr = lambda x : 4*x**3 - 2*x - R
# intervalle d'étude
x0 = 0.5
x1 = 1.0
print("verification: ",Pr(x0),Pr(x1))
xr = dichotomie(Pr,x0,x1,1.e-5)
print(xr,Pr(xr))
### END SOLUTION
verification:  -1.5 1.0
0.8846473693847656 8.812271155012041e-06

Tracer de la solution¶

  • tracer figure avec axes, label, ..
  • sauvegarde
  • commentaire
In [12]:
### BEGIN SOLUTION
R = 1.0
plt.rc('font', family='serif', size='16')
plt.figure(figsize=(10,8))
plt.plot(X,Y,label='y=P(x)')
plt.plot([X[0],X[-1]],[R,R],'--',label='y=R')
plt.plot([xr],[Pr(xr)+R],'o',markersize=10,label='racine')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title("étude des racines de P(x)=R");
plt.savefig("fig1.png")
### END SOLUTION

Analyse des résultats¶

Pour calculer une approximation numérique de la solution de l'équation: $$ 4 x^3 - 2 x = R $$ pour une valeur de R fixée ($R=1.0$), on utilise la méthode de dichotomie, en définissant une fonction Pr(x) dont la racine est la solution recherchée : $$ Pr(x) = 4 x^3 - 2 x - R $$ En choisissant un intervalle $[x_0,x_1]=[0.5,1.]$ où se trouve la racine. On vérifie que la racine est bien dans l'intervalle puisque $Pr(x_0)\,Pr(x_1) < 0 $.

Pour $\epsilon = 10^{-5}$ , la fonction dichotomie fournit bien l'approximation $xr = 0.8846$ avec une précision de $10^{-5}$ puisque $Pr(xr) \approx 9. 10^{-6}$

On vérifie enfin, sur le tracé de la fonction $P(x) = 4 x^3 - 2 x$ , que la courbe admet une intersection unique avec la droite $y=R$ sur l'intervalle $[0.5,1.0]$ et que ce point d'intersection a comme coordonnées $(xr, P(xr))$

Algorithme: combinaison linéaire¶

On considère une combinaison linéaire de 3 vecteurs de $R^n$ : $ \mathbf{U}, \mathbf{V},\mathbf{W}$

$$ \mathbf{C} = \alpha \mathbf{U} + \beta \mathbf{V} + \gamma \mathbf{W} $$

on veut calculer les composantes de $\mathbf{C}$ dans $R^n$ de façon générique

Algorithmes

  1. utilisation de boucles
  2. notation vectorielle
  3. notation matricielle

Généralisation à p vecteurs

In [41]:
n = 4
U = np.array([4.0,1.0,1.0,1.0])
V = np.array([1.0,3.0,0.0,1.0])
W = np.array([0.0,1.0,5.0,1.0])
alpha = 1.0
beta  = 2.0
gamma = -2.0
In [42]:
## BEGIN SOLUTION
C = np.zeros(n)
for i in range(n):
    C[i] = alpha*U[i] + beta*V[i] + gamma*W[i]
print(C)
C = alpha*U + beta*V + gamma*W
print(C)
X = np.array([alpha,beta,gamma])
A = np.array([U,V,W]).transpose()
C = A @ X
print(C)
## END SOLUTION
[ 6.  5. -9.  1.]
[ 6.  5. -9.  1.]
[ 6.  5. -9.  1.]
In [43]:
# boucle
C = np.zeros(n)
for i in range(n):
    C[i] = alpha*U[i] + beta*V[i] + gamma*W[i]
print(C)
[ 6.  5. -9.  1.]
In [44]:
# vecteur
C = alpha*U + beta*V + gamma *W
print(C)
[ 6.  5. -9.  1.]
In [45]:
# matrice
X = np.array([alpha,beta,gamma])
A = np.array([U,V,W]).transpose()
C = A @ X
print(C)
[ 6.  5. -9.  1.]

généralisation avec p vecteurs¶

In [46]:
# généralisation à p vecteurs
n = 10
p = 4
# coefficients
X = np.random.rand(p) + 1.0
print("X=",X)
# liste des vecteurs
L = [ np.random.rand(n) for k in range(p) ]
print("L=",L)
X= [1.65123443 1.93725241 1.42268021 1.45455044]
L= [array([0.58782702, 0.75097635, 0.94196825, 0.28769923, 0.85093602,
       0.23756304, 0.74866502, 0.81182219, 0.56719361, 0.71808547]), array([0.73769772, 0.33030193, 0.7664352 , 0.66929496, 0.04646652,
       0.14986859, 0.6607092 , 0.09063694, 0.8858358 , 0.11867431]), array([0.868195  , 0.71575289, 0.94702767, 0.84114281, 0.53182796,
       0.95949772, 0.51110313, 0.89468554, 0.23019455, 0.54674508]), array([0.43014989, 0.49302645, 0.64886017, 0.02808204, 0.65795293,
       0.36609529, 0.05681344, 0.11697828, 0.06112285, 0.20676857])]
In [20]:
## BEGIN SOLUTION
A = np.array(L).transpose()
C = A@X
print(C)
## END SOLUTION
[3.89558496 1.80507714 3.01179094 1.49808905 1.53744493 3.84206245
 1.291285   3.0423061  3.90102042 2.83361122]

Application: changement de base dans $R^3$¶

Les vecteurs de la combinaison linéaires sont des vecteurs orthonormés qui forment une base de $R^3$

exemple: coordonnées polaires

On considère un repère mobile $R_1=(u,v,w)) obtenu par rotation d'un angle $\theta$ autour de Y à partir du référentiel fixe $R_0=(x,y,z)$

On considère un point Pm de coordonnées $(2,1,2)$ et on veut calculer ces coordonnées dans $R_0$ (résultat dans Pf).

On calculera la matrice de changement de base R

vérification

  • calculer le déterminant de R, son inverse et sa transposée.
  • calculer la transformation inverse (Pf vers Pm)
In [49]:
from IPython.display import display
theta = np.pi/3
# dans le référentiel mobile
Pm = np.array([2,1,2])
## BEGIN SOLUTION
U = np.array([np.cos(theta),0,-np.sin(theta)])
V = np.array([0.,1.,0.])
W = np.array([np.sin(theta),0, np.cos(theta)])
print("U,V,W=",U,V,W)

print("Pm:",Pm)
# position référentiel fixe
R = np.array([U,V,W]).transpose()
print("R="); display(R)  
Pf = R @ Pm
print("Pf:",Pf)
## END SOLUTION
U,V,W= [ 0.5        0.        -0.8660254] [0. 1. 0.] [0.8660254 0.        0.5      ]
Pm: [2 1 2]
R=
array([[ 0.5      ,  0.       ,  0.8660254],
       [ 0.       ,  1.       ,  0.       ],
       [-0.8660254,  0.       ,  0.5      ]])
Pf: [ 2.73205081  1.         -0.73205081]
In [50]:
# verification
## BEGIN SOLUTION
print("det R=",np.linalg.det(R))
Rinv = np.linalg.inv(R)
print("Rinv="); display(Rinv)
print("Rt  ="); display(R.transpose())
# vérification
Pm = R.transpose() @ Pf
print("Pm:",Pm)
#
print("R.Rt="); 
display(R@R.transpose())
display(R @ np.linalg.inv(R))
## END SOLUTION
det R= 1.0
Rinv=
array([[ 0.5      , -0.       , -0.8660254],
       [ 0.       ,  1.       ,  0.       ],
       [ 0.8660254,  0.       ,  0.5      ]])
Rt  =
array([[ 0.5      ,  0.       , -0.8660254],
       [ 0.       ,  1.       ,  0.       ],
       [ 0.8660254,  0.       ,  0.5      ]])
Pm: [2. 1. 2.]
R.Rt=
array([[ 1.00000000e+00,  0.00000000e+00, -1.48741681e-17],
       [ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
       [-1.48741681e-17,  0.00000000e+00,  1.00000000e+00]])
array([[ 1.00000000e+00,  0.00000000e+00, -1.48741681e-17],
       [ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
       [-7.03853194e-17,  0.00000000e+00,  1.00000000e+00]])

Algorithme : dérivation numérique¶

Pour une fonction $f(x)$ on peut approximer la dérivée par un calcul d'accroissement

$$ f'(x) \approx \frac{f(x+dx) - f(x)}{dx}$$

Si on connait la valeur de la fonction $Y_i$ en des points $X_i$

$$ f'(X_i) \approx \frac{Y_{i+1} - Y_i}{X_{i+1}-X_i}$$

application

  • approximation de la dérivée, dérivée seconde
  • précision en comparant avec la valeur exacte
In [51]:
F   = lambda x: np.sin(x)*np.cos(2*x)
dF  = lambda x: np.cos(x)*np.cos(2*x)-2*np.sin(x)*np.sin(2*x)
d2F = lambda x: -np.sin(x)*np.cos(2*x) -2*np.cos(x)*np.sin(2*x) - 2*np.cos(x)*np.sin(2*x) -4*np.sin(x)*np.cos(2*x)
#
N = 21
# N = 201
# tracer de la fonction
## BEGIN SOLUTION
X = np.linspace(0,2*np.pi,N)
Y = F(X)
plt.figure(figsize=(12,8))
plt.plot(X,Y,'-x')
plt.title("Fonction étudiée F(x)");
## END SOLUTION
In [52]:
# calcul de la dérivée numérique et la tracer avec l'erreur
## BEGIN SOLUTION
dY = (Y[1:] - Y[0:-1])/(X[1:] - X[0:-1])
plt.figure(figsize=(12,8))
plt.subplot(1,2,1)
plt.plot(X[:-1],dY,label='approx.')
plt.plot(X,dF(X),label='exacte')
plt.title("Dérivée")
plt.legend()
plt.subplot(1,2,2)
plt.plot(X[:-1],dY-dF(X[:-1]))
plt.title("Erreur")
## END SOLUTION
Out[52]:
Text(0.5, 1.0, 'Erreur')
In [53]:
# calcul de la dérivée seconde numérique et la tracer avec l'erreur
## BEGIN SOLUTION
d2Y = (dY[1:] - dY[0:-1])/(X[1:-1] - X[0:-2])
plt.figure(figsize=(12,8))
plt.subplot(1,2,1)
plt.plot(X[:-2],d2Y,label='approx.')
plt.plot(X,d2F(X),label='exacte')
plt.title("Dérivée seconde")
plt.legend()
plt.subplot(1,2,2)
plt.plot(X[:-2],d2Y-d2F(X[:-2]))
plt.title("Erreur")
## END SOLUTION
Out[53]:
Text(0.5, 1.0, 'Erreur')

FIN¶