dubbbdan
dubbbdan

Reputation: 2740

Find Closest Minima to Peak

I am using scipy.singal.find_peaks to find peaks and minimas using:

import numpy as np
from scipy.signal import find_peaks

x=np.array([9.8,57.,53.,37.,24.,19.,16.,15.,13.,13.,12.,12.,11.,11.,11.,11.,11.,11.,10.,13.,13.,13.,15.,13.,12.,14.,15.,14.,51.,34.,24.,20.,24.,22.,18.,57.,63.,38.,27.,28.,31.,33.,94.,71.,48.,40.,43.,39.,31.,27.,22.,21.,20.,19.,18.,18.,19.,20.,20.,49.,62.,48.,43.,34.,33.,28.,26.,26.,24.,23.,23.,26.,27.,70.,97.,57.,46.,68.,82.,59.,49.,37.,40.,45.,36.,33.,28.,22.,23.,284.,524.,169.,111.,148.,98.,68.,50.,38.,30.,28.])
peaks, _ = find_peaks(x)
mins, _ =find_peaks(x*-1)

Which looks like:

enter image description here

Now I am interested to find the closest minima to each peak. So I can take the difference between them.

After looking through the find_peaks documentation, the argument peak_prominece seems like what I am looking for.

prominences = peak_prominences(x, peaks)[0]
contour_heights = x[peaks] - prominences

Which then looks like:

enter image description here

After inspection, peak_prominences has found the minimum preceding the peak. For my application, I want the closest peak, regardless if it was preceding or following.

How could I to use mins to define the parameter wlen for the peak_prominence calculation.?

Since mins consists of the indices of the minima, how can I use it to define wlen? I would basically have to find the indices in min that bound each peak (i.e. peaks[i]).

Is there a better way to achieve this just using mins and peaks?

Upvotes: 0

Views: 1204

Answers (1)

Stelios
Stelios

Reputation: 5521

Now I am interested to find the closest minima to each peak. So I can take the difference between them.

Is the following what you are looking for?

closest_mins = [mins[np.argmin(np.abs(x-mins))] for x in peaks]
difference = x[peaks]-x[closest_mins]
print(difference)
[ 47.   3.   1.  37.   4.  45.  54.   3.  44.  51.  36.   8. 413.  37.]

Below is a plot of peaks, mins, and peaks-closest mins pairs indicated by dashed lines. Note that there are mins which are closest to more than one peaks.

plt.plot(x)
plt.plot(peaks, x[peaks],'o', label = 'peaks')
plt.plot(mins, x[mins],'s', label = 'mins')
plt.plot(closest_mins, x[closest_mins],'*', label = 'closest mins')

for p, m in zip(peaks, closest_mins):
    plt.plot([p,m], [x[p], x[m]], 'k', dashes = (4,1))
plt.legend();

enter image description here

Upvotes: 1

Related Questions