7

scipy.interpolate.UnivariateSpline用来平滑地插入大量数据。效果很好。我得到一个像函数一样的对象。

现在我想保存样条点供以后使用,并在 Matlab 中使用它们(还有 Python,但这不那么紧急),而不需要原始数据。我怎样才能做到这一点?

在 scipy 中我不知道;UnivariateSpline 似乎没有提供具有先前计算的结和系数的构造函数。

在 MATLAB 中,我尝试了 Matlab 函数spline()pchip(),虽然两者都很接近,但它们在看起来有点像Gibbs ear的端点附近有错误。

这是我拥有的一组样本数据,采用 Matlab 格式:

splinedata = struct('coeffs',[-0.0412739180955273 -0.0236463479425733 0.42393753107602 -1.27274336116436 0.255711720888164 1.93923263846732 -2.30438927604816 1.02078680231079 0.997156858475075 -2.35321792387215 0.667027554745454 0.777918416623834],...
 'knots',[0 0.125 0.1875 0.25 0.375 0.5 0.625 0.75 0.875 0.9999],...
 'y',[-0.0412739180955273 -0.191354308450615 -0.869601364377744 -0.141538578624065 0.895258135865578 -1.04292294390242 0.462652465278345 0.442550440125204 -1.03967756446455 0.777918416623834])

系数和结是调用get_coeffs()get_knots()在 scipy UnivariateSpline 上的结果。'y' 值是节点处的 UnivariateSpline 的值,或更准确地说:

 y = f(f.get_knots())

其中 f 是我的 UnivariateSpline。

如何使用这些数据制作与 UnivariateSpline 的行为相匹配的样条曲线,而无需使用曲线拟合工具箱?我不需要在 Matlab 中进行任何数据拟合,我只需要知道如何从节点/系数/样条值构造三次样条。

4

2 回答 2

7

You can do it by using the functions _eval_args() and _from_tck() from the class UnivariateSpline. The first one gives returns the spline parameters, which you can store and later create a similar spline object using the the second one.

Here is an example:

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

x = np.linspace(-3, 3, 50)
y = np.exp(-x**2) + 0.1 * np.random.randn(50)

spl1 = UnivariateSpline(x, y, s=.5)

xi = np.linspace(-3, 3, 1000)

tck = spl1._eval_args

spl2 = UnivariateSpline._from_tck(tck)

plt.plot(x, y, 'ro', ms=5, label='data')
plt.plot(xi, spl1(xi), 'b', label='original spline')
plt.plot(xi, spl2(xi), 'y:', lw=4, label='recovered spline')

plt.legend()
plt.show()

enter image description here

于 2017-10-02T18:28:53.977 回答
1

在 scipy 中,尝试scipy.interpolate.splev,它需要

tck:一个序列...包含样条的节点、系数和度数。

补充:以下python类创建样条函数:init with (knots, coefs, degree),然后像样条函数一样使用它UnivariateSpline( x, y, s )

from scipy.interpolate import splev
    # http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html

class Splinefunc:
    """ splinef = Splinefunc( knots, coefs, degree )
        ...
        y = splinef( x )  # __call__

        19june untested
    """

    def __init__( self, knots, coefs, degree ):
        self.knots = knots
        self.coefs = coefs
        self.degree = degree

    def __call__( self, x ):
        return splev( x, (self.knots, self.coefs, self.degree ))
于 2013-06-18T08:42:40.873 回答