【问题标题】:Find two points/derivatives on curves between which the line is straight/constant在直线/常数之间的曲线上找到两个点/导数
【发布时间】:2020-05-02 11:18:19
【问题描述】:
我正在绘制 x 和 y 点。这导致了一条曲线,这条线首先弯曲,然后在一个点之后变成直线,一段时间后它再次弯曲。我想找回这两点。虽然 x 是线性的,并且 y 是针对 x 绘制的,但 y 不是线性依赖于 x。
我尝试使用 matplotlib 绘制和 numpy 多项式函数,目前正在研究样条曲线,但似乎对于这些 y 需要直接依赖于 x。
【问题讨论】:
标签:
python
matplotlib
spline
【解决方案1】:
您的数据嘈杂,因此您不能使用简单的数值导数。相反,正如您可能已经发现的那样,您应该使用样条曲线拟合它,然后检查样条曲线的曲率。
关闭this answer,您可以像这样拟合样条曲线并计算二阶导数(曲率):
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
x = file['n']
y = file['Ds/2']
y_spline = UnivariateSpline(x, y)
x_range = np.linspace(x[0], x[-1], 1000) # or could use x_range = x
y_spline_deriv = y_spl.derivative(n=2)
curvature = y_spline_deriv(x_range)
然后你可以像这样找到直线区域的开始和结束:
straight_points = np.where(curvature.abs() <= 0.1)[0] # pick your threshold
start_idx = straight_points[0]
end_idx = straight_points[-1]
start_x = x_range[start_idx]
end_x = x_range[end_idx]
或者,如果您主要对找到曲线的 最平坦 部分感兴趣(如图所示),您可以尝试计算一阶导数,然后找到斜率所在的区域数据中任何地方的少量最小斜率。在这种情况下,只需在上面的代码中替换 y_spline_deriv = y_spl.derivative(n=1)。