使用numpy在重复信号的一部分内绘制抛物线

时间:2010-10-28 23:00:42

标签: python numpy scipy signal-processing scientific-computing

我有一个重复信号,每个周期重复大约每秒一次,但是每个周期的持续时间和内容在某些参数内略有不同。每秒信号数据都有一千个x,y坐标。每个周期内的一小部分但很重要的数据部分已损坏,我想用向上的抛物线替换每个损坏的部分。

对于需要用抛物线替换的每个数据段,我有三个点的x,y坐标。顶点/最小值是这些点之一。另外两个点是向上U形的左右顶部,即抛物线。换句话说,左上角是此函数域中最低x值的x,y坐标对,而右上角是此函数域中最高x值的x,y坐标对。左上顶和右上顶点的y坐标彼此相等,是数据段中两个最高的y值。

如何编写代码来绘制这个面向上的抛物线中的剩余数据点?请记住,对于每分钟数据,此函数需要调用60或70次,并且形状为/抛物线的公式在每次调用此函数时都需要更改,以便考虑每个结果抛物线中这三对x,y坐标之间的不同关系。

def ReplaceCorruptedDataWithParabola(Xarray, Yarray, LeftTopX, LeftTopY
                                     , LeftTopIndex, MinX, MinY, MinIndex
                                     , RightTopX, RightTopY, RightTopIndex):  

    # Step One: Derive the formula for the upward-facing parabola using 
    # the following data from the three points:
        LeftTopX,LeftTopY,LeftTopIndex  
        MinX,MinY,MinIndex  
        RightTopX,RightTopY,RightTopIndex 

    # Step Two: Use the formula derived in step one to plot the parabola in
    # the places where the corrupted data used to reside:
    for n in Xarray[LeftTopX:RightTopX]:
        Yarray[n]=[_**The formula goes here**_]

    return Yarray 

注意:Xarray和Yarray是每个单列向量,每个索引都有数据,将两个数组链接为x,y坐标集。它们都是numpy数组。 Xarray包含时间信息但不会改变,但是Yarray包含信号数据,包括将被需要由此函数计算的抛物线数据替换的损坏段。

1 个答案:

答案 0 :(得分:7)

所以,据我所知,你有3个点你想要抛物线。

通常情况下,使用numpy.polyfit最简单,但如果你真的担心速度,并且你恰好适合三个点,那么使用最小二乘拟合没有意义。

相反,我们有一个均匀确定的系统(将抛物线拟合到3 x,y点),我们可以得到一个简单线性代数的精确解。

所以,总而言之,你可能会做这样的事情(大部分是绘制数据):

import numpy as np                                                                              
import matplotlib.pyplot as plt                                                                 

def main():
    # Generate some random data
    x = np.linspace(0, 10, 100)
    y = np.cumsum(np.random.random(100) - 0.5)

    # Just selecting these arbitrarly 
    left_idx, right_idx = 20, 50      
    # Using the mininum y-value within the arbitrary range
    min_idx = np.argmin(y[left_idx:right_idx]) + left_idx 

    # Replace the data within the range with a fitted parabola
    new_y = replace_data(x, y, left_idx, right_idx, min_idx)  

    # Plot the data
    fig = plt.figure()
    indicies = [left_idx, min_idx, right_idx]

    ax1 = fig.add_subplot(2, 1, 1)
    ax1.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
    ax1.plot(x, y)                                                    
    ax1.plot(x[indicies], y[indicies], 'ro')                          

    ax2 = fig.add_subplot(2, 1, 2)
    ax2.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
    ax2.plot(x,new_y)                                                 
    ax2.plot(x[indicies], y[indicies], 'ro')

    plt.show()

def fit_parabola(x, y):
    """Fits the equation "y = ax^2 + bx + c" given exactly 3 points as two
    lists or arrays of x & y coordinates"""
    A = np.zeros((3,3), dtype=np.float)
    A[:,0] = x**2
    A[:,1] = x
    A[:,2] = 1
    a, b, c = np.linalg.solve(A, y)
    return a, b, c

def replace_data(x, y, left_idx, right_idx, min_idx):
    """Replace the section of "y" between the indicies "left_idx" and
    "right_idx" with a parabola fitted to the three x,y points represented
    by "left_idx", "min_idx", and "right_idx"."""
    x_fit = x[[left_idx, min_idx, right_idx]]
    y_fit = y[[left_idx, min_idx, right_idx]]
    a, b, c = fit_parabola(x_fit, y_fit)

    new_x = x[left_idx:right_idx]
    new_y = a * new_x**2 + b * new_x + c

    y = y.copy() # Remove this if you want to modify y in-place
    y[left_idx:right_idx] = new_y
    return y

if __name__ == '__main__':
    main()

Example plot

希望有所帮助...