Hướng dẫn python find peaks and valleys - trăn tìm đỉnh và thung lũng

Chức năng của bạn sử dụng khá nhiều tham số. Bạn có thể phân tách vấn đề thành một vài bước:

  1. Đầu tiên phát hiện tất cả các điểm trên ngưỡng. Thêm các điểm đó vào danh sách maxthreshminthresh.
  2. Lặp lại thông qua danh sách maxthresh và nếu giá trị y trước điểm nhỏ hơn điểm và giá trị y sau điểm nhỏ hơn điểm, thì điểm là cực đại.
  3. Lặp lại thông qua danh sách minthresh và nếu giá trị y trước điểm lớn hơn điểm và giá trị y sau điểm có độ rộng hơn điểm, thì điểm là cực đại.

Thực hiện mã:

from math import sin
from matplotlib import pylab
from pylab import *

def peakdet[v, thresh]:
    maxthresh = []
    minthresh = []
    peaks = []
    valleys = []

    for x, y in v:
        if y > thresh:
            maxthresh.append[[x, y]]
        elif y < -thresh:
            minthresh.append[[x, y]]

    for x, y in maxthresh:
        try:
            if [v[x - 1][1] < y] & [v[x + 1][1] < y]:
                peaks.append[[x, y]]
        except Exception:
            pass

    for x, y in minthresh:
        try:
            if [v[x - 1][1] > y] & [v[x + 1][1] > y]:
                valleys.append[[x, y]]
        except Exception:
            pass

    return peaks, valleys

Kiểm tra mã:

# input signal
t = array[range[100]]
series = 0.3 * sin[t] + 0.7 * cos[2 * t] - 0.5 * sin[1.2 * t]

arr = [*zip[t, series]]  # create a list of tuples where the tuples represent the [x, y] values of the function
thresh = 0.95

peaks, valleys = peakdet[arr, thresh]

scatter[[x for x, y in peaks], [y for x, y in peaks], color = 'red']
scatter[[x for x, y in valleys], [y for x, y in valleys], color = 'blue']
plot[t, 100 * [thresh], color='green', linestyle='--', dashes=[5, 3]]
plot[t, 100 * [-thresh], color='green', linestyle='--', dashes=[5, 3]]
plot[t, series, 'k']
show[]

Kiểm tra bổ sung để đảm bảo phát hiện đỉnh cao khi nhiều điểm trên ngưỡng:

# input signal
t = array[range[100]]
series = 6.3 * sin[t] + 4.7 * cos[2 * t] - 3.5 * sin[1.2 * t]

arr = [*zip[t, series]]
thresh = 0.95

peaks, valleys = peakdet[arr, thresh]

scatter[[x for x, y in peaks], [y for x, y in peaks], color = 'red']
scatter[[x for x, y in valleys], [y for x, y in valleys], color = 'blue']
plot[t, 100 * [thresh], color='green', linestyle='--', dashes=[5, 3]]
plot[t, 100 * [-thresh], color='green', linestyle='--', dashes=[5, 3]]
plot[t, series, 'k']
show[]


Tổng quan

Tôi đã cố gắng tìm một hàm trả về các đỉnh và thung lũng của biểu đồ. Tôi đã thử nghiệm scipy.signal.find_peaks_cwt[] nhưng hóa ra nó không phù hợp với trường hợp sử dụng của tôi. Có vẻ như nó chỉ phù hợp để xử lý đồ thị tín hiệu. Rốt cuộc, chức năng thuộc gói signal. Xem phần đầu ra biểu đồ dưới đây để biết các trường hợp tốt và xấu.Chart output section below for good and bad cases.

Xem giải pháp tốt ở đây.

Mã để tìm các đỉnh và thung lũng - không thành công

#!/usr/bin/python3
import matplotlib
matplotlib.use['Agg'] # Bypass the need to install Tkinter GUI framework
 
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
 
# Generate random data.
data_x = np.arange[start = 0, stop = 25, step = 1, dtype='int']
data_y = np.random.normal[loc = 0, scale = 1, size = 25]*2
data_y = np.absolute[data_y] # Want positive numbers only.
 
# Find peaks[max]
widths=np.arange[1,4] # Widths range should cover the expected width of peaks of interest.
peak_indexes = signal.find_peaks_cwt[data_y, widths]
 
# Find valleys[min]
inv_data_y = data_y*[-1] # Tried 1/data_y but not better.
valley_indexes = signal.find_peaks_cwt[inv_data_y, widths]
 
# Plot main graph
[fig, ax] = plt.subplots[]
ax.plot[data_x, data_y]
 
# Plot peaks
peak_x = peak_indexes
peak_y = data_y[peak_indexes]
ax.plot[peak_x, peak_y, marker='o', linestyle='dashed', color='green', label="Peaks"]
 
# Plot valleys
valley_x = valley_indexes
valley_y = data_y[valley_indexes]
ax.plot[valley_x, valley_y, marker='o', linestyle='dashed', color='red', label="Valleys"]
 
 
# Save graph to file.
plt.title['Find peaks and valleys using find_peaks_cwt[]']
plt.legend[loc='best']
plt.savefig['scipypeak.png']

Biểu đồ OUPUT

Trường hợp tốt hơn hoặc ít

Trường hợp xấu

Thông tin về các Tác giả

Xuan NGO là người sáng lập OpenWritings.net. Ông hiện đang sống ở Montreal, Canada. Anh ấy thích viết về lập trình và các chủ đề nguồn mở.

Bài Viết Liên Quan

Chủ Đề