How can I put constraint of derivative zero at all data points for spline interpolation?

醉酒当歌 提交于 2020-02-24 16:50:02

问题


Is there any method in scipy for spline interpolation in which I can use constraint on derivative at each data points? I found one "scipy.interpolate.PiecewisePolynomial" but PiecewisePolynomial class has been deprecated.


回答1:


Yes.

The BPoly class in scipy.interpolate has a method that constructs

a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints.

as stated in the scipy reference, here.

Basic usage on Python3 can go as following:

from numpy import linspace, sin, pi
from scipy.interpolate import BPoly, CubicSpline

xi = linspace(0, pi, 5)
xnew = linspace(0, pi, 50)

yi = sin(xi)
ynew = sin(xnew)
yder = [[yi[i], 0] for i in range(len(yi))]

cubic = CubicSpline(xi, yi)
bpoly = BPoly.from_derivatives(xi, yder)

y_bpoly = bpoly(xnew)
y_cubic = cubic(xnew)

Explaining

This program creates two spline interpolations for the first semi-period of a senoid, one using the CubicSpline class, and one using the from_derivatives method of the BPoly class, setting the derivative as 0 at each point of the original curve.

The main issue regarding this method is that, unless you specify the derivatives at each point, the algorithm doesn't guarantee smooth transitions. The derivative is, however, guaranteed at the points it was specified. Still, this should not present a problem since what you're looking for is to set the derivative as 0 at each point.

Plot

Using the following you can properly see the different results, as in this image:

import matplotlib.pyplot as plt

plt.figure()
plt.plot(xnew, y_bpoly, '-g', xnew, ynew, '--c', xnew, y_cubic, '-.m', xi, yi, '*r')
plt.legend(['BPoly', 'True', 'Cubic', 'Points'])
plt.title('Spline interpolation')
plt.grid()
plt.show()


来源:https://stackoverflow.com/questions/51050622/how-can-i-put-constraint-of-derivative-zero-at-all-data-points-for-spline-interp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!