0

I would like to get the frequency value of the second highest peak from the graph. I tried getting the frequencies which are nonzero, then sorting them in a descending order and getting the second value from that list. But it does not work that way. Below is the code for it. The file for replicating can be found here.

n = len(time)
fhat_A = np.fft.fft(channelA, n)
PSD_A = fhat_A * np.conj(fhat_A)/n
freq_A = (1/(0.0001*n)) * np.arange(n)
L_A = np.arange(1,np.floor(n/2),dtype='int')

plt.plot(freq_A[L_A], PSD_A[L_A], 'k', label='Noise_A')
plt.xlabel('Frequency [Hz]')
plt.ylabel('PSD [G^2/Hz]')
plt.title('Noise in Channel A Pipe03_2')
plt.legend(bbox_to_anchor=(0.6, -0.2), ncol=4)
plt.rcParams["figure.dpi"] = 300
plt.show()

The plot looks like below and I would like to know the PSD value of the red marked line. Is there a better way to do it? Only the real values are enough. The resultant plot

EDIT: Following is the code and result on using find_peaks. I do not understand why there are so many peaks shown on the x-axis.

from scipy.signal import find_peaks

peaks, _ = find_peaks(PSD_A[L_A], distance=30)
plt.plot(freq_A[L_A], PSD_A[L_A], 'k', label='Noise_A')
plt.plot(peaks, PSD_A[L_A][peaks], 'xr')

Peak_plot

lqope54
  • 113
  • 7
  • 3
    Does this answer your question? [Peak-finding algorithm for Python/SciPy](https://stackoverflow.com/questions/1713335/peak-finding-algorithm-for-python-scipy) – Ari Cooper-Davis Aug 31 '21 at 14:25
  • I did not think of treating it as peaks for some reason but yes this works partially. I don't understand why there are so many peaks shown in the x-axis as well. I have added the picture in the original post. – lqope54 Sep 01 '21 at 10:21
  • [This answer](https://stackoverflow.com/a/52612432/6144626) highlights the importance of the parameters `width`, `threshold`, `distance` and `prominence`. You're only using `distance` to identify peaks, but I'd suggest you explore these other parameters a little more - `prominence` is likely to be particularly relevant for weeding out unwanted peaks. – Ari Cooper-Davis Sep 01 '21 at 10:31
  • Yeah I tried all of them but I always get the peak on the x-axis too. I found width and distance to be the most useful for my application though. – lqope54 Sep 01 '21 at 10:49

1 Answers1

0

If many frequencies are not zero, and therefore your peaks are formed by many points, sorting will not be useful (e.g. you'll get just a point next to the max). Finding peaks in a signal can be complicated. I suggest to use peakutils. See the tutorial there: if your signal is x,y, it's as simple as

indexes = peakutils.indexes(y, thres=0.5, min_dist=30)
print(indexes)
print(x[indexes], y[indexes])
scrx2
  • 2,242
  • 1
  • 12
  • 17
  • Thanks, I could not install this package. I will try again later. But what is the difference between peakutils and find_peak ? – lqope54 Sep 01 '21 at 10:25