假设我在python中有两个数组,我希望得到(并实际使用)这些点之间的三次样条插值。 (IE:我希望整合这个功能)。我非常喜欢使用numpy scipy的方式。
我知道scipy.interpolate.interp1d。然而,这只允许我评估点数,例如:非常简单的函数:
现在我可以做一些简单的事情:
import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt
y = np.array([0,2,3,4,8,10,12,12,12,10,9,8,7,1,0,0,1,2])
x = np.array(range(len(y)))
xvals = np.linspace(0, len(y)-1, len(y)*100, endpoint = False)
func = scipy.interpolate.interp1d(x, y, kind = "cubic")
yvals = func(xvals)
plt.plot(xvals,yvals)
plt.plot(x,y, "o")
但是我希望进一步处理这个三次样条(即我需要进行积分)。对于手动操作,我需要得到因子,所以:
a_i * x^3 + b_i * x^2 + c_i * x + d_i where i goes from 0 to n/3
(n = elemet的数量 - 这只是第i个立方体的定义)
因此我期望一个描述所有样条的元组(或2d数组)列表。 - 或者一种获得第i个立方体的方法,而且真的,真的很想得到一个方便的" x-to-i"找到我目前的样条曲线。
(当然,后一个问题是在排序列表中简单搜索大于引用的第一个值 - 如果需要,我可以轻松地手动完成)。
答案 0 :(得分:1)
对于插值,您可以使用scipy.interpolate.UnivariateSpline(..., s=0)
。
除其他外,它还有integrate方法。
编辑:UnivariateSpline构造函数的s=0
参数强制样条线通过所有数据点。结果是在B样条基础上,您可以使用get_coefs()
和get_knots()
方法获得结和系数。格式与netlib上的FITPACK,dierckx中使用的格式相同。请注意,interp1d
(依赖于splmake
ATM)和UnivariateSpline
(或splrep
/ splev
)内部使用的tck格式不一致。< / p>
EDIT2:您可以使用PPoly.from_spline得到样条曲线的分段多项式表示形式---但 与iterp1d一致。使用splrep(...,s = 0)获取插值样条曲线,然后转换结果。
答案 1 :(得分:1)
只是一个可能有帮助的想法。 From the docs,您可以通过不同的方式获得三次样条插值,这可能对您有所帮助:
import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt
y = np.array([0,2,3,4,8,10,12,12,12,10,9,8,7,1,0,0,1,2])
x = np.array(range(len(y)))
xvals = np.linspace(0, len(y)-1, len(y)*100, endpoint = False)
func = scipy.interpolate.splrep(x, y, s=0)
yvals = scipy.interpolate.splev(xvals, func, der=0)
# display original vs cubic spline representation for security...
plt.figure()
plt.plot(x, y, 'x', xvals, yvals, x, y, 'b')
plt.legend(['Linear', 'Cubic Spline'])
plt.axis([-0.05, 20, -2, 20])
plt.title('Cubic-spline interpolation')
plt.show()
这使您可以通过
访问系数pp = scipy.interpolate.spltopp(func[0][1:-1],func[1],func[2])
#Print the coefficient arrays, one for cubed terms, one for squared etc
print(pp.coeffs)
它还在页面上给出了如何使用此三次样条表示进行整合的示例(根据您的情况更改常量,我希望 - 您的里程可能会有所不同):
def integ(x, tck, constant=0):
x = np.atleast_1d(x)
out = np.zeros(x.shape, dtype=x.dtype)
for n in xrange(len(out)):
out[n] = scipy.interpolate.splint(0, x[n], tck)
out += constant
return out
const_of_integration = 0
yint = integ(xvals, func, const_of_integration)
答案 2 :(得分:0)
函数scipy.signal.cspline1d
返回具有镜像对称边界条件的b样条项的系数。如果您需要对系数进行其他滤波,这将非常有用