【问题标题】:How to find the closest value on the left如何在左侧找到最接近的值
【发布时间】:2021-04-24 03:09:50
【问题描述】:

我有一个函数,我检测到了这个函数的峰值。我取了每个峰高的一半,现在我想找到交点,只在左边,函数和经过峰高一半的线之间。

请注意,在下图中,该线并未完全通过山峰的一半。实际上,每个峰都有一个特定的中间高度值,我需要找到左侧与该值的交点。

我的函数值是:

data= [2.50075550e+01  2.68589513e+01  2.88928569e+01  3.05468408e+01
 3.17558878e+01  3.28585597e+01  3.41860820e+01  3.56781188e+01
 3.68868815e+01  3.72671655e+01  3.65050587e+01  3.47342596e+01
 3.24647483e+01  3.02772213e+01  2.84592589e+01  2.68653782e+01
 2.51627240e+01  2.33132310e+01  2.18235229e+01 ...]

我正在使用来自 SciPy 的 find_peaks 获得一半的高度

heights.append(signal.find_peaks(data, height=height)[1]['peak_heights'])

#Then calculating the half of each peak
          

【问题讨论】:

    标签: python python-3.x numpy matplotlib numpy-ndarray


    【解决方案1】:

    我将简单地尝试解释一般算法。基本逻辑就是,简单的遍历一遍time[s]的值,根据迭代的time[s]的值找到高度值。您需要的唯一数据是该值,您将在其中使用该值是否等于或大于您想要的相交线值。如果信号的高度等于或大于给定的height 值,则表示存在交叉点,如果没有,则信号高度肯定小于您想要与信号相交的线值。

    【讨论】:

      【解决方案2】:

      以下代码使用来自How to find the exact intersection of a curve with y==0? 的函数find_roots。此函数搜索与给定半值对应的精确插值 x 值。该段被限制在前一个峰值和当前峰值之间的间隔内,并从结果列表中获取最后一个根(如果有的话)。

      import numpy as np
      import matplotlib.pyplot as plt
      from scipy import signal
      
      def find_roots(x, y):
          s = np.abs(np.diff(np.sign(y))).astype(bool)
          return x[:-1][s] + np.diff(x)[s] / (np.abs(y[1:][s] / y[:-1][s]) + 1)
      
      np.random.seed(11235)
      x = np.linspace(0, 20, 500)
      data = np.convolve(1.1 ** np.random.randn(x.size).cumsum(), np.ones(40), 'same')
      data -= data.min()
      plt.plot(x, data, c='dodgerblue')
      peaks, _ = signal.find_peaks(data, height=40, distance=50)
      
      plt.scatter(x[peaks], data[peaks], color='turquoise')
      for p, prev in zip(peaks, np.append(0, peaks)):
          half = data[p] / 2
          roots = find_roots(x[prev:p], data[prev:p] - half)
          if len(roots) > 0:
              plt.scatter(roots[-1], half, color='crimson')
      plt.ylim(ymin=0)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 2015-03-01
        • 2012-05-15
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 2018-01-07
        相关资源
        最近更新 更多