Voici un code Python complet pour explorer l'interpolation spline cubique avec différents paramètres :
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline, splrep, splev
from scipy.interpolate import interp1d
def demo_spline_cubique():
# Données d'exemple
x_data = np.array([0, 1, 2, 3, 4, 5])
y_data = np.array([0, 1, 4, 2, 3, 1])
# Points pour l'interpolation (plus dense)
x_interp = np.linspace(0, 5, 100)
# Configuration de la figure
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('Interpolation Spline Cubique - Différents Paramètres', fontsize=16)
# 1. Conditions aux limites (boundary conditions)
ax = axes[0, 0]
# Natural spline (dérivée seconde nulle aux extrémités)
cs_natural = CubicSpline(x_data, y_data, bc_type='natural')
y_natural = cs_natural(x_interp)
# Not-a-knot (continuité de la dérivée troisième)
cs_not_a_knot = CubicSpline(x_data, y_data, bc_type='not-a-knot')
y_not_a_knot = cs_not_a_knot(x_interp)
# Clamped (dérivées premières spécifiées aux extrémités)
cs_clamped = CubicSpline(x_data, y_data, bc_type=((1, 0.5), (1, -0.5)))
y_clamped = cs_clamped(x_interp)
ax.plot(x_data, y_data, 'ko', markersize=8, label='Points de données')
ax.plot(x_interp, y_natural, 'b-', label='Natural')
ax.plot(x_interp, y_not_a_knot, 'r--', label='Not-a-knot')
ax.plot(x_interp, y_clamped, 'g:', label='Clamped')
ax.set_title('Conditions aux limites')
ax.legend()
ax.grid(True, alpha=0.3)
# 2. Extrapolation
ax = axes[0, 1]
x_extrap = np.linspace(-1, 6, 100)
# Sans extrapolation (défaut)
cs_no_extrap = CubicSpline(x_data, y_data, extrapolate=False)
y_no_extrap = cs_no_extrap(x_extrap)
# Avec extrapolation
cs_extrap = CubicSpline(x_data, y_data, extrapolate=True)
y_extrap = cs_extrap(x_extrap)
ax.plot(x_data, y_data, 'ko', markersize=8, label='Points de données')
ax.plot(x_extrap, y_no_extrap, 'b-', label='Sans extrapolation')
ax.plot(x_extrap, y_extrap, 'r--', label='Avec extrapolation')
ax.axvline(x=0, color='gray', linestyle=':', alpha=0.5)
ax.axvline(x=5, color='gray', linestyle=':', alpha=0.5)
ax.set_title('Extrapolation')
ax.legend()
ax.grid(True, alpha=0.3)
# 3. Comparaison avec interpolation linéaire
ax = axes[0, 2]
# Interpolation linéaire
f_linear = interp1d(x_data, y_data, kind='linear')
y_linear = f_linear(x_interp)
# Spline cubique
cs = CubicSpline(x_data, y_data)
y_cubic = cs(x_interp)
ax.plot(x_data, y_data, 'ko', markersize=8, label='Points de données')
ax.plot(x_interp, y_linear, 'b-', label='Linéaire')
ax.plot(x_interp, y_cubic, 'r-', label='Spline cubique')
ax.set_title('Spline vs Linéaire')
ax.legend()
ax.grid(True, alpha=0.3)
# 4. Dérivées
ax = axes[1, 0]
cs = CubicSpline(x_data, y_data)
y_interp = cs(x_interp)
y_deriv1 = cs(x_interp, 1) # Première dérivée
y_deriv2 = cs(x_interp, 2) # Deuxième dérivée
ax.plot(x_interp, y_interp, 'b-', label='f(x)')
ax.plot(x_interp, y_deriv1, 'r--', label="f'(x)")
ax.plot(x_interp, y_deriv2, 'g:', label="f''(x)")
ax.plot(x_data, y_data, 'ko', markersize=8)
ax.set_title('Fonction et ses dérivées')
ax.legend()
ax.grid(True, alpha=0.3)
# 5. Effet du lissage avec splrep/splev
ax = axes[1, 1]
# Ajout de bruit aux données
np.random.seed(42)
y_noisy = y_data + 0.3 * np.random.randn(len(y_data))
# Sans lissage
tck_no_smooth = splrep(x_data, y_noisy, s=0)
y_no_smooth = splev(x_interp, tck_no_smooth)
# Avec lissage
tck_smooth = splrep(x_data, y_noisy, s=2)
y_smooth = splev(x_interp, tck_smooth)
ax.plot(x_data, y_noisy, 'ko', markersize=8, label='Données bruitées')
ax.plot(x_interp, y_no_smooth, 'r-', label='Sans lissage (s=0)')
ax.plot(x_interp, y_smooth, 'b--', label='Avec lissage (s=2)')
ax.set_title('Effet du lissage')
ax.legend()
ax.grid(True, alpha=0.3)
# 6. Différents degrés de polynômes
ax = axes[1, 2]
# Interpolation avec différents degrés
f_linear = interp1d(x_data, y_data, kind='linear')
f_quadratic = interp1d(x_data, y_data, kind='quadratic')
f_cubic = interp1d(x_data, y_data, kind='cubic')
y_lin = f_linear(x_interp)
y_quad = f_quadratic(x_interp)
y_cub = f_cubic(x_interp)
ax.plot(x_data, y_data, 'ko', markersize=8, label='Points de données')
ax.plot(x_interp, y_lin, 'b-', label='Linéaire')
ax.plot(x_interp, y_quad, 'g--', label='Quadratique')
ax.plot(x_interp, y_cub, 'r:', label='Cubique')
ax.set_title('Différents degrés')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def demo_parametres_detailles():
"""Démonstration détaillée des paramètres"""
print("=== PARAMÈTRES DE L'INTERPOLATION SPLINE CUBIQUE ===\n")
print("1. SCIPY.INTERPOLATE.CUBICSPLINE")
print(" - x, y : points de données")
print(" - axis : axe le long duquel interpoler")
print(" - bc_type : conditions aux limites")
print(" * 'not-a-knot' (défaut) : continuité de la 3e dérivée")
print(" * 'natural' : dérivée seconde nulle aux extrémités")
print(" * 'clamped' : dérivée première spécifiée")
print(" * 'periodic' : fonction périodique")
print(" - extrapolate : True/False pour extrapolation\n")
print("2. SCIPY.INTERPOLATE.SPLREP/SPLEV")
print(" - x, y : points de données")
print(" - w : poids des points")
print(" - s : facteur de lissage (0 = interpolation exacte)")
print(" - k : degré de la spline (1-5, défaut=3)")
print(" - xb, xe : limites du domaine\n")
print("3. SCIPY.INTERPOLATE.INTERP1D")
print(" - kind : 'linear', 'quadratic', 'cubic', etc.")
print(" - fill_value : valeur pour extrapolation")
print(" - bounds_error : erreur si hors limites\n")
# Exécution des démonstrations
if __name__ == "__main__":
demo_parametres_detailles()
demo_spline_cubique()
Ce code vous montre :
Les différents types de conditions aux limites : natural, not-a-knot, clamped, qui affectent le comportement aux extrémités de la courbe.
L'extrapolation : comment la spline se comporte en dehors des points de données.
La comparaison avec l'interpolation linéaire : pour voir la différence de lissage.
Les dérivées : la spline cubique permet de calculer facilement les dérivées première et seconde.
Le lissage : avec des données bruitées, vous pouvez ajuster le paramètre de lissage.
Différents degrés de polynômes : comparaison entre interpolation linéaire, quadratique et cubique.
Les paramètres principaux que vous pouvez ajuster sont les conditions aux limites (bc_type), l'extrapolation (extrapolate), et le facteur de lissage (s avec splrep). Chacun influence significativement la forme de la courbe résultante.