Scipy Find Peaks – Useful Tutorial

In this Python tutorial, we will learn about the “Scipy Find Peaks” and also discuss its usability with the help of a variety of examples. Additionally, cover the following topics.

  • Scipy Find Peaks
  • Scipy Finds Peaks of Prominence
  • Scipy Find Peaks cwt
  • Scipy Find Peaks and Valleys
  • Scipy Find Peaks Minima
  • Scipy Finds Peak Width

Scipy Find Peaks

The Python Scipy has a method find_peaks() within a module scipy.signal that returns all the peaks based on given peak properties. Peaks are not merely the peaks of an electric signal, maxima and minima in a mathematical function are also considered peaks.

The syntax is given below.

scipy.signal.find_peaks(x, height=1, prominence=4,  distance=2, width=2, threshold=1, rel_height=0.5, wlen=1, )

Where parameters are:

  • x(sequence): It is used to accept the signal whose peaks need to be found.
  • height (sequence, ndarray, number): It might be an integer or an array, and it’s used to set the minimum height for a peak to be recognized.
  • threshold(sequence, ndarray, number): The required vertical distance between a peak and its neighbors is known as the threshold, and it’s highly beneficial in the situation of noisy functions when we don’t want to pick out peaks from the noise.
  • distance(number): It is the required minimum horizontal distance (number) between nearby peaks. It can be quite valuable in circumstances where the periodicity of the peaks is known.
  • prominence(sequence,ndarray, number): It is used to provide peak prominence.
  • width(sequence,ndarray, number): It is used to provide the width of the peak.
  • wlen(int): It is used to calculate the peak prominence.
  • rel_height(int): It is used to calculate the peak height.

Let’s take an example by following the below steps:

Import the required library using the below python code.

from scipy.signal import find_peaks
from scipy.misc import electrocardiogram
import matplotlib.pyplot as plt
%matplotlib inline

Generate an electrocardiogram using the below code.

value = electrocardiogram()[1000:5000]

Now the peaks using the below code.

peak, _ = find_peaks(value, height=0)
plt.plot(value)
plt.plot(peak, value[peak], "*")
plt.plot(np.zeros_like(value), "--", color="green")
plt.show()
Scipy Find Peaks
Scipy Find Peaks

This is how to find the peaks of the signal using the method find_peaks() of Python SciPy.

Read: Scipy Misc + Examples

Scipy Find Peaks Prominence

The Python SciPy has a method peak_prominence() that computes the vertical distance between the peak and its lowest contour line in comparison to the surrounding baseline of the signal.

The syntax is given below.

scipy.signal.peak_prominences(x, wlen=None, peaks)

Where the parameters are:

  • x(sequence): It is used to accept the signal whose peaks need to be found.
  • wlen(int): It is used to specify the sample window length.
  • peaks(sequence): Peak indices in x.

The method peak_prominence() return the prominences(each peak) and the left-right bases of type ndarray.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
%matplotlib inline

Generate a signal using the below code.

array_data = np.linspace(0, 5 * np.pi, 1100)
sig = np.sin(array_data) + 0.5 * np.sin(1.7 * array_data)

Determine the prominences of all peaks using the below code.

sig_peaks, _ = signal.find_peaks(sig)
promin = signal.peak_prominences(sig, sig_peaks)[0]
promin

Now compute and graph the height of each peak’s contour line using the below code.

contur_height = sig[sig_peaks] - promin
plt.plot(sig)
plt.plot(sig_peaks, sig[sig_peaks], "*")
plt.vlines(x=sig_peaks, ymin=contur_height, ymax=sig[sig_peaks])
plt.show()
Scipy Find Peaks Prominence
Scipy Find Peaks Prominence

This is how to find the prominences of peaks using the method peak_prominences() of Python SciPy.

Read: Scipy Sparse – Helpful Tutorial

Scipy Find Peaks cwt

The Python SciPy has a method find_peaks_cwt() that uses the Wavelet transformation to find peaks in a 1-D array. But “What is Wavelet transformation?” A signal of N samples is decomposed into low and high-frequency bands using a pair of filters. Each band is two-fold undersampled, with N/2 samples in each.

The syntax is given below.

scipy.signal.find_peaks_cwt(vector, wavelet=None, widths, max_distances=None, window_size=None, gap_thresh=None, min_snr=0, min_length=None, noise_perc=9)

Where the parameters are:

  • vector(ndarray): Find the peaks in a 1-D array.
  • wavelet(callable): It must return a 1-D array to convolve with the vector after taking two arguments. The first argument specifies the number of points in the output wavelet array, while the second specifies the wavelet’s scale.
  • widths(): To calculate the CWT matrix, utilize a single width or a one-dimensional array of widths.
  • max_distances(ndarray): A ridgeline is connected at each row only if the relative maximum at row[n] is within max distances[n] of the relative maximum at row[n+1].
  • window_size(int): To calculate the noise floor, specify the size of the window.
  • gap_thresh(float): There will be a gap if a relative maximum is not found inside max distances. If there’s more than the gap_thresh point without a new relative maximum, the ridgeline is terminated.
  • min_snr(float): Minimum signal-to-noise ratio.
  • min_length(int): A ridge line’s minimum length must be acceptable.
  • noise_perc(float): The noise floor is calculated using the percentile of data points below which noise is considered.

The method find_peaks_cwt() returns te peak_indices.

Let’s understand with an example by following the below steps:

Import the required libraries using the below python code.

from scipy.signal import find_peaks_cwt
import numpy as np

Generate the array elements and apply the function sin on that array using the method np.sin() using the below code.

x_data = np.arange(0, np.pi, 0.06)
sin_data = np.sin(x_data)

Calculate the peak indices or peaks using the below code.

peak_indices = signal.find_peaks_cwt(sin_data, np.arange(2,11))
peak_indices, x_data[peak_indices], sin_data[peak_indices]
Scipy Find Peaks cwt
Scipy Find Peaks cwt

This is how to find the peaks using the method find_peaks_cwt of Python SciPy.

Read: Scipy Optimize – Helpful Guide

Scipy Finds Peak Width

The Python SciPy has a method peak_widths() that determines the width of each signal’s peak.

The syntax is given below.

scipy.signal.peak_widths(x, rel_height=0.3, peaks, wlen=None, prominence_data=None)

Where the parameters are:

  • x(sequence): It is used to accept the signal.
  • wlen(int): It is used to specify the sample window length.
  • peaks(sequence): Peak indices in x.
  • rel_height(float): Selects the relative height at which the peak breadth is expressed as a percentage of its prominence. The breadth of the peak is calculated at its lowest contour line at 1.0, and half the prominence height is calculated at 0.5.
  • prominence_data(tuple): When invoked with the same parameters x and peaks, a tuple of 3 arrays matches the result of peak prominences.

The method peak_widths() returns widths(sample peak widths), widths_height(the height of the contour lines used to calculate the widths.) and right_ips, left_ips(Interpolated positions of a horizontal line’s left and right junction points at each evaluation height).

Let’s see with an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
%matplotlib inline

Generate a signal using the below code.

array_data = np.linspace(0, 5 * np.pi, 1100)
sig = np.sin(array_data) + 0.5 * np.sin(1.7 * array_data)

Determine the width of all peaks using the below code.

sig_peaks, _ = signal.find_peaks(sig)
promin = signal.peak_prominences(sig, sig_peaks)[0]
promin

Plot the widths of the signal, peaks, and contour lines using the below code.

plt.plot(sig)
plt.plot(sig_peaks, sig[sig_peaks], "*")
plt.hlines(*half_peak_res[1:], color="C4")
plt.hlines(*full_peak_res[1:], color="C5")
plt.show()
Scipy Finds Peak Width
Scipy Finds Peak Width

This is how to compute the width of the peak using the method peak_widths() of Python SciPy.

Read: Python Scipy FFT [11 Helpful Examples]

Scipy Find Peaks and Valleys

In the Python SciPy, there is no inbuilt method to find peaks and valleys of signal, here we will perform this task manually by using the method argrelextrema() that exists within the module scipy.signal.

To find the peaks and valleys of the signal flow the below steps:

Import the required libraries using the below python code.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from scipy.signal import argrelextrema
%matplotlib inline

Generate the data using the below code.

x_data = np.arange(start = 0, stop = 30, step = 1, dtype='int')
y_data = np.random.random(30)*5

Compute the peaks using the below code.

peaks_ind = argrelextrema(y_data, np.greater)
peaks_ind = peaks_ind[0]

Compute the valleys using the below code.

valleys_ind = argrelextrema(y_data, np.less)
valleys_ind = valleys_ind[0]

Plot the graph with peak and valleys data that we have generated using the below code.

(fig, ax) = plt.subplots()
ax.plot(x_data, y_data)

x_peak = peaks_ind
y_peak = y_data[peaks_ind]
ax.plot(x_peak, y_peak, marker='*', linestyle='dashed', color='orange', label="peaks")

x_valley = valleys_ind
y_valley = y_data[valleys_ind]
ax.plot(x_valley, y_valley, marker='*', linestyle='dashed', color='blue', label="Valleys")
Scipy Find Peaks and Valleys
Scipy Find Peaks and Valleys

This is how to find the peak and valleys of the signal in Python SciPy.

Read: Scipy Linalg – Helpful Guide

Scipy Find Peaks Minima

We have learned how to find the peaks or the maximum value of the signal using the method find_peaks() of the Python Scipy library. But here in this section, we are going to find the Minima or the valleys of a given signal.

To find the minima of the signal or the given data follow the below steps:

Import the required libraries using the below python code.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from scipy.signal import argrelextrema

Create a signal using the random data by following the below code.

array_data = np.arange(start = 0, stop = 40, step = 1, dtype='int')
y_array_data = np.random.random(40)*5

Calculate the minima of the signal using the below code.

minima_ind = argrelextrema(y_array_data, np.less)
minima_ind = minima_ind[0]
minima_ind

Plat the calculated minima on the graph using the below code.

(fig, ax) = plt.subplots()
ax.plot(array_data, y_array_data)

x_minima = minima_ind
y_minima = y_array_data[minima_ind]
ax.plot(x_minima, y_minima, marker='*', linestyle='dashed', color='green', label="Minima")
Scipy Find Peaks Minima
Scipy Find Peaks Minima

This is how to find the minima of the signal or data using the method argrelextrema() of Python SciPy.

Also, take a look at some more Python Scipy tutorials.

So, in this tutorial, we have learned about the “Scipy Find Peaks” and covered the following topics.

  • Scipy Find Peaks
  • Scipy Finds Peaks of Prominence
  • Scipy Find Peaks cwt
  • Scipy Find Peaks and Valleys
  • Scipy Find Peaks Minima
  • Scipy Finds Peak Width