【问题标题】:How to determine when the distance between two lines gets within a certain threshold?如何确定两条线之间的距离何时达到某个阈值?
【发布时间】:2019-10-16 05:38:05
【问题描述】:

我有一个包含主要数据点(蓝线)和最大值(绿色)和最小值(红色)的图表。

请注意,最小值和最大值的 x 值不相同,也不保证它们具有相同的值计数。

现在我的目标是确定最大值线和最小值线之间沿 y 轴的距离(积分?抱歉,自从 uni 中的微积分以来已经有一段时间了)从沿 y 轴的平均距离。

这里是用来生成的代码:

# Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Plotting the values for the graph above
plt.plot(df.flow.values)
upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')

如果有什么不同,我使用的是 Pandas Dataframe、scipy 和 matplotlib。

【问题讨论】:

  • 你能补充一些数据吗?
  • 你能定义“沿y轴的平均距离”吗? min_extreme (max_extreme) 的最左边(最右边)部分在 max_extreme (min_extreme) 上没有交易对手呢?你只是想忽略吗?
  • @YiBao 是的,这些可以忽略,因为数据集实际上要大得多,并且会被均匀修剪。平均距离可以定义为:(到绿线-红线的距离)对于蓝线上的每个x值/蓝线上的总点数

标签: python pandas numpy matplotlib


【解决方案1】:

如果我理解你的问题是正确的,你基本上想插入由极值定义的线。从Interpolate NaN values in a numpy array这个帖子里偷答案,你可以这样做

# Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Interpolate so you get no 'nan' values
df['min_extreme'] = df['min_extreme'].interpolate()
df['max_extreme'] = df['max_extreme'].interpolate() 

从这里应该很容易处理两条线之间的距离的各种东西。比如

# Get the average distance between the upper and lower extrema-lines
df['distance'] = df['max_extreme'] - df['min_extreme']
avg_dist = np.mean(df['distance'])

# Find indexes where distance is within some tolerance
df.index[df['distance']< avg_dist * .95]

【讨论】:

  • 太棒了!我发现这是最简单、最直接的解决方案。
【解决方案2】:

这绝不是一个完美的解决方案。由于没有更多数据,它旨在为您提供一些关于如何完成它的想法。

您要解决的主要问题是处理两条分段直线。并且碎片不对齐。一个明显的解决方案是对两者进行插值并获得 x 的并集。那么距离的计算就比较容易了。

import numpy as np
import matplotlib.pyplot as plt

# Toy data
x1 = [0, 1, 2, 3, 4, 5, 6]
y1 = [9, 8, 9, 10, 7, 6, 9]
x2 = [0.5, 3, 5, 6, 9]
y2 = [0, 1, 3, 2, 1]

# Interpolation for both lines
points1 = list(zip(x1, y1))
y1_interp = np.interp(x2, x1, y1)
interp_points1 = list(zip(x2, y1_interp))
l1 = list(set(points1 + interp_points1))
all_points1 = sorted(l1, key = lambda x: x[0])

points2 = list(zip(x2, y2))
y2_interp = np.interp(x1, x2, y2)
interp_points2 = list(zip(x1, y2_interp))
l2 = list(set(points2 + interp_points2))
all_points2 = sorted(l2, key = lambda x: x[0])

assert(len(all_points1) == len(all_points2))

# Since I do not have data points on the blue line, 
# I will calculate the average distance based on x's of all interpolated points
sum_d = 0
for i in range(len(all_points1)):
    sum_d += all_points1[i][1] - all_points2[i][1]
avg_d = sum_d / len(all_points1)
threshold = 0.5
d_threshold = avg_d * threshold

for i in range(len(all_points1)):
    d = all_points1[i][1] - all_points2[i][1]
    if d / avg_d < threshold:
        print("Distance below threshold between", all_points1[i], "and", all_points2[i])

请注意,np.interp 也会外推值,但它们不参与计算。

现在还有一个问题:如果您真的需要知道何时距离低于阈值而不仅仅是插值点,则需要分析搜索每个片段中的第一个和最后一个点的行。这是一个示例:

for i in range(len(all_points1) - 1):
    (pre_x1, pre_y1) = all_points1[i]
    (post_x1, post_y1) = all_points1[i + 1]
    (pre_x2, pre_y2) = all_points2[i]
    (post_x2, post_y2) = all_points2[i + 1]
    # Skip the pieces that will never have qualified points
    if (pre_y1 - pre_y2) / avg_d >= threshold and (post_y1 - post_y2) / avg_d >= threshold:
        continue
    k1 = (post_y1 - pre_y1) / (post_x1 - pre_x1)
    b1 = (post_x1 * pre_y1 - pre_x1 * post_y1) / (post_x1 - pre_x1)
    k2 = (post_y2 - pre_y2) / (post_x2 - pre_x2)
    b2 = (post_x2 * pre_y2 - pre_x2 * post_y2) / (post_x2 - pre_x2)
    x_start = (d_threshold - b1 + b2) / (k1 - k2)
    print("The first point where the distance falls below threshold is at x=", x_start)
    break

【讨论】:

    【解决方案3】:

    您的问题是 min_extrememax_extreme 没有一直对齐/定义。我们可以通过interpolate解决:

    # this will interpolate values linearly, i.e data on the upper and lower lines
    df = df.interpolate()
    
    # vertical distance between upper and lower lines:
    df['dist'] = df.max_extreme - df.min_extreme
    
    # thresholding, thresh can be scalar or series
    # thresh = 0.5 -- absolute value
    # thresh = df.max_extreme / 2 -- relative to the current max_extreme
    
    thresh = df.dist.quantile(0.5) # larger than 50% of the distances
    
    df['too_far'] = df.dist.gt(thresh)
    
    # visualize:
    tmp_df = df[df.too_far]
    
    upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
    lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')
    
    df.flow.plot()
    
    plt.scatter(tmp_df.index, tmp_df.min_extreme, s=10)
    plt.scatter(tmp_df.index, tmp_df.max_extreme, s=10)
    plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2013-05-23
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多