1

I am trying to find the peaks of a function using scipy, however I want it to detect the peaks at the boundary as well. Here is the snapshot of one such case. As we see that the method has detected 10 peaks but I want the total peaks to be 12 including the peaks at boundaries as well. Is there any way to do it? Also I don't want to include the start and the ending indices just like that. I will be running this method on a large dataset so looking for a generic solution.

coordinates = df.loc[:, columns].sum(axis=1)
peaks_max_y = argrelextrema(coordinates.to_numpy(), np.greater)[0]

index = np.arange(df.shape[0])
_ = plt.plot(index, coordinates, 'b-', linewidth = 2)
_ = plt.plot(index[peaks_max_y], coordinates[peaks_max_y], 'ro', label = 'minima peaks')
plt.title(pid)

enter image description here

ashish14
  • 650
  • 1
  • 8
  • 20
  • If the peaks are always on the boundaries, you could just take the first and the last element of the array – user8408080 Feb 26 '20 at 15:09
  • It seems to me that SciPy correctly found *all* 10 peaks (local maxima). If you additionally want the end points, just add `data[0]` and `data[-1]` to your list of peaks. – jmd_dk Feb 26 '20 at 15:10
  • 1
    You should at least add the code that generated this. – jlanik Feb 26 '20 at 15:14
  • Does this answer your question? [Peak-finding algorithm for Python/SciPy](https://stackoverflow.com/questions/1713335/peak-finding-algorithm-for-python-scipy) – Basj Feb 26 '20 at 16:31
  • 1
    Look at my answer https://stackoverflow.com/questions/1713335/peak-finding-algorithm-for-python-scipy/52612432#52612432 @ashish14. – Basj Feb 26 '20 at 16:31

1 Answers1

0

Since find_peaks will take care of the rest of the points, how about checking the slope just at the endpoints? If the slope is negative on the left side, you have a peak at the start. Similarly if it's positive at the end, you have a peak.

Something like this:

if np.sign(np.diff(y))[0] < 0:
    # accept y[0] as peak
if np.sign(np.diff(y))[-1] > 0:
    # accept y[-1] as peak
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23