Search code examples
pythonnumpynumericcalculus

Curve radius in Python


I have this curve and I would like to compute the radius and the center of the curve below: enter image description here

The data for this curve https://pastebin.com/FZTi3bAf

My code so far:

poly = np.polyfit(df['x'], df['y'],2)
p = np.poly1d(poly)

I need to have new point (x, y) as input in this problem.


Solution

  • You can plot the line from 2 edge points and calculate the distance from the middle of this line to curve (dh). Then if dl is the distance between edge points you can write (dl/2)^2 = (2R - dh) * dh and get R from this equation.

    a = df.to_numpy()
    x_middle = (a[0, 0] + a[-1, 0]) / 2
    y_middle = (a[0, 1] + a[-1, 1]) / 2
    dx = a[-1, 0] - a[0, 0]
    dy = a[0, 1] - a[-1, 1]
    dl = np.sqrt(dx ** 2 + dy ** 2)
    cos = dx / dl
    sin = dy / dl
    dh = cos * (np.interp(x_middle, a[:, 0], a[:, 1]) - y_middle)
    R = dl ** 2 / 8 / dh + dh / 2
    x0 = x_middle - (R - dh) * sin
    y0 = y_middle - (R - dh) * cos
    
    
    plt.scatter(a[:, 0], a[:, 1])
    circle = plt.Circle((x0, y0), R, fill=False)
    plt.gca().add_artist(circle)
    plt.show()
    

    plot