Find intersection between parametric spline curve and line

990 Views Asked by At

I am fitting a parametric spline curve(t) from a bunch of (x, y) sampling points. How do I compute the intersection point with a line given by slope and one point? In my special case the spline intersects with the line once or not at all but never multiple times.

Here's the code for spline & line...

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate


# Fit spline from points
x = np.array([152, 200, 255, 306, 356, 407, 457, 507, 561, 611, 661, 711, 761, 811, 861])
y = np.array([225, 227, 229, 229, 228, 226, 224, 222, 218, 215, 213, 212, 212, 215, 224])
tck, u = interpolate.splprep((x, y), k=3, s=1)

# Plot it...
u = np.linspace(0, 1, 100)
xy = np.asarray(interpolate.splev(u, tck, der=0))
plt.plot(*xy)


# Line defined by slope and (x, y) point
m = 3
(x, y) = (500, 100)

# Plot it...
x_vals = np.array([400, 700])
y_vals = m * (x_vals - x) + y
plt.plot(x_vals, y_vals)
plt.show()

... which looks like this: Plot

1

There are 1 best solutions below

0
On

Add the following lines

from scipy.interpolate import interp1d
spline = interp1d(xy[0], xy[1]) # define function based on spline data points
line = interp1d(x_vals, y_vals) # define function based on line data points

import scipy.optimize as spopt
f = lambda x: spline(x) - line(x) # difference function, its zero marks the intersection
r = spopt.bisect(f, a = max(xy[0][0], x_vals[0]), b = min(xy[0][-1], x_vals[-1])) # find root via bisection

plt.scatter(r, spline(r))
print(r, spline(r))
plt.show()

First define functions for your spline and line based on its data. The root of the difference function f marks your intersection. Since there is exactly one, bisection works nicely to find it.

It would probably be more accurate to somehow re-use splev to define the function for the spline, but I'll leave that one to you.