这个出色的示例提供了为非单调曲线创建样条线的选项:非单调数据的三次样条线(不是一维函数)
但是,我现在需要另一个步骤 - 获取给定
y
值的 x
值。我无法弄清楚如何在没有循环的情况下扩展样条线的使用。我想我可以寻找一些 r
的解决方案,从而提供一些 x_i
,但这将是一个非常漫长的过程。
假设我需要
y
处的 x = 4.5
的值。但最接近的是 'spline(0.1)' 给出 array([4.54115695, 0.40519822])
找到了这个解决方案,首先使用上采样,然后使用径向基函数进行插值(由于非单调,唯一有效的解决方案
x
)
import numpy
import scipy.interpolate
import matplotlib.pyplot as plt
# very sparse path, non-monotonic
path_x = numpy.asarray((4.0, 5.638304088577984, 6.785456961280076, 5.638304088577984, 4.0),dtype=float)
path_y = numpy.asarray((0.0, 1.147152872702092, 2.7854569612800755, 4.423761049858059, 3.2766081771559668),dtype=float)
# Upsample using spline interpolation
# then downsample using griddata nearest interpolation
# defining arbitrary parameter to parameterize the curve
path_t = numpy.linspace(0,1,path_x.size)
# this is the position vector with
# x coord (1st row) given by path_x, and
# y coord (2nd row) given by path_y
r = numpy.vstack((path_x.reshape((1,path_x.size)),path_y.reshape((1,path_y.size))))
# creating the spline object
spline = scipy.interpolate.interp1d(path_t,r,kind='cubic')
# defining values of the arbitrary parameter over which
# you want to interpolate x and y
# it MUST be within 0 and 1, since you defined
# the spline between path_t=0 and path_t=1
t = numpy.linspace(numpy.min(path_t),numpy.max(path_t),1000)
# interpolating along t
# r[0,:] -> interpolated x coordinates
# r[1,:] -> interpolated y coordinates
rr = spline(t)
xi = rr[0,:]
yi = rr[1,:]
plt.plot(path_x,path_y,'ro')
plt.plot(xi,yi,'-')
plt.xlabel('x')
plt.ylabel('y')
from scipy.interpolate import Rbf
# xii = resample(xi,20) # resample at 20 points along x
# yii = scipy.interpolate.griddata(xi,yi,path_x,method='nearest')
rbfi = Rbf(t, xi, yi, function='linear')
yii = rbfi(path_t, path_x)
# plt.plot(path_x,path_y,'or')
# plt.plot(xi,yi,'x-k')
plt.plot(path_x, yii, 'gs')
plt.show()