File:Detection pics scipy signal find peaks.svg
Summary
| Description |
Français : Détection des pics avec l'outil find_peaks de scipy (Python).
Voir auss https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html#scipy.signal.find_peaks
English: Detection of peaks with the find_peaks tool of scipy (Python).
See also https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html#scipy.signal.find_peaks |
| Date | |
| Source | Own work |
| Author | Cdang |
| Other versions | Noiseless curves: File:Exemple superposition de pics large et etroit.svg; use of the Savitzky-Golay algorithm: File:Detection pics savitzky golay.svg |
Source code
Creation of the data file.
Python code
#!/usr/bin/python3
# coding: utf-8
"""nom : creationDonnees.py
auteur : User:cdang
date de création : 2023-04-19
dates de modification :
— 2023-04-20 : ajout de la courbe lissée et des cordes sur la sortie graphique
----------------------------------------------------------------------------
version de Python : 3
module requis : NumPy, Pandas
----------------------------------------------------------------------------
Objectif : crée un fichier de données, nuage de points (x, y) pour tester le programme de recherche de pics.
Entrées
-------
Paramètres de la fonction générant le nuage de points (codé en dur).
Sorties
-------
Un fichier CSV de deux colonnes correspondant aux coordonnées x et y des point d'une courbe
(nombres réels convertis en chaînes de caractères).
"""
import numpy as np
import pandas as pd
# ****************
# ****************
# ** Paramètres **
# ****************
# ****************
facteurSigma = 0.03/np.sqrt(2*np.pi) # rapport entre la hauteur et la largeur d'un pic
x1 = 0.3 ; h1 = 0.5 # position et hauteur des pics
x2 = 0.75 ; h2 = 0.1
x3 = 0.8 ; h3 = 1
epsilon = 0.01 # amplitude du bruit
n = 200 # nombre de points
# chemin d'accès et nom du fichier à créer
chemin = "~/dummypath/"
nomFichier = "donnees.csv"
# **************
# **************
# ** Fonction **
# **************
# **************
def f(x, mu, sigma):
"""Fonction pour générer un pic.
Entrées :
— x : vecteur de réels (abscisses) ;
— mu : réel, position du pic ;
— sigma : réel, écart type de la fonction gaussienne.
Sortie : y, vecteur de réels (ordonnées) de même dimension que x.
y = 1/(σ × √(2π)) × exp((x - μ)²/(2σ²))."""
unSurSigma = 1/sigma
y = (unSurSigma*facteurSigma)*np.exp(-0.5*unSurSigma*unSurSigma*(x - mu)*(x - mu))
return y
# *************************
# *************************
# ** Programme principal **
# *************************
# *************************
X = np.linspace(0, 1, n)
Y = f(X, x1, facteurSigma/h1) + f(X, x2, facteurSigma/h2) + f(X, x3, facteurSigma/h3) + epsilon*np.random.normal(X)
resultat = pd.DataFrame(np.concatenate((X.reshape(-1, 1), Y.reshape(-1, 1)), axis=1))
resultat.to_csv(chemin+nomFichier)
Data processing.
Python code
#!/usr/bin/python3
# coding: utf-8
"""nom : detcectionPics.py
auteur : User:cdang
date de création : 2023-04-21
dates de modification :
----------------------------------------------------------------------------
version de Python : 3
module requis : NumPy, Matplotlib, SciPy, Pandas
----------------------------------------------------------------------------
Objectif : détecte les pics à partir d'une courbe, sous la forme d'un nuage de poins (x, y).
Entrées
-------
Fichier CSV, paramètres de filtrage (codés en dur).
Sorties
-------
Une liste de position et un graphique montrant les positions trouvées par rapport au nuage de points.
"""
import matplotlib.pyplot as plt
import scipy.signal as signal
import pandas as pd
# ****************
# ****************
# ** Paramètres **
# ****************
# ****************
# chemin d'accès et nom du fichier à créer
chemin = "~/dummypath/"
nomFichier = "donnees.csv"
# *************************
# *************************
# ** Programme principal **
# *************************
# *************************
# ***********************
# * Lecture des données *
# ***********************
donnees = pd.read_csv(chemin+nomFichier).to_numpy()
x = donnees[:, 1]
y = donnees[:, 2]
# **********************
# * Détection des pics *
# **********************
pics2 = signal.find_peaks(y, prominence=0.03)
# ***************************
# * Affichage des résultats *
# ***************************
print(pics2)
fig = plt.figure(figsize = [10, 6])
for i in pics2[0]:
plt.plot(x[i]*np.ones(2), [0, 1], "g", linewidth="0.5")
for i in range(len(pics2[0])):
i1 = pics2[1]["left_bases"][i]
i2 = pics2[1]["right_bases"][i]
plt.plot([x[i1], x[i2]], [y[i1], y[i2]], "g", linewidth="0.5")
plt.plot(x, y,
color="blue", linewidth = "1", label = "données brutes")
plt.xlabel("x (u.a.)")
plt.ylabel("y (u.a.)")
plt.legend()
plt.savefig(chemin+"detection_pics_scipy_signal_find_peaks.svg", format="svg")
Licensing
I, the copyright holder of this work, hereby publish it under the following license:
This file is licensed under the Creative Commons Attribution-Share Alike 4.0 International license.
- You are free:
- to share – to copy, distribute and transmit the work
- to remix – to adapt the work
- Under the following conditions:
- attribution – You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- share alike – If you remix, transform, or build upon the material, you must distribute your contributions under the same or compatible license as the original.