Peak finding algorithm using python and SciPy

85 views Asked by At

I have vehicle data of speed vs time where y axis is speed and x axis is the time. I need to count the number of accelerations of a vehicle. the peaks has to be detected where peak lower values is in between 0 to 13 and peak upper value is in between 20 to 25 how to detect this this is the code i used

import numpy as np
from scipy.signal import find_peaks, find_peaks_cwt
import matplotlib.pyplot as plt
x=np.array([ 0, 14,  9,  0,  0,  7,  0,  0, 12, 16, 15, 11,  7, 20, 24, 13, 13,
       14, 19, 13, 12, 10,  7,  3,  3,  3, 25, 14, 14, 14,  7, 24, 20, 20,
       21, 20, 20, 20, 20, 20, 21, 16, 11, 11, 18, 22, 22, 20, 19, 19, 18,
       15, 20, 23, 21, 23, 24, 15, 16, 19, 25, 24,  0, 20, 23, 24, 23, 22,
       21, 23, 25, 28, 24, 23, 23, 17,  7, 11, 21, 25, 25, 25, 25, 25, 25,
       15, 13,  9,  0, 21, 10, 18, 25, 25, 26, 23, 25, 23, 25, 27, 25, 12,
        0,  0,  0, 19, 22, 24, 25, 25, 24, 24, 23, 23, 16, 19, 23, 24, 24,
       17,  8,  0,  9,  7, 11, 18, 20, 23, 23, 24, 25, 25, 25, 17, 24, 24])

zero_locs = np.where(x<13 ) # find zeros in x
search_lims = np.append(zero_locs, len(x)) # limits for search area

diff_x = np.diff(x) # find the derivative of x
diff_x_mapped = diff_x >13   # find the max's of x (zero crossover 

peak_locs = []

for i in range(len(search_lims)-2):
    peak_loc = search_lims[i] + np.where(diff_x_mapped[search_lims[i]:search_lims[i+1]]==0)[0][0]
    if x[peak_loc] > 20 and x[peak_loc] <25:
        peak_locs.append(peak_loc)
fig= plt.figure(figsize=(19,5))
plt.plot(x)
plt.xlim(0,100)
plt.plot(np.array(peak_locs), x[np.array(peak_locs)], "x", color = 'r'

above code I used but not able to find the peaks properly. this is my out expected out put marked expected output 5 peaks I am new to the python I don't know where I am missing thanks in advance

1

There are 1 answers

2
J_H On

You found no peaks. That is, len(peak_locs) is zero.

So you wind up with this array, whose type defaulted to float:

>>> np.array(peak_locs)
array([], dtype=float64)

To fix it? Find more peaks!

An empty list will always produce that diagnostic error message. Focus on why the for loop never found anything in the range 20 .. 25.