Rishi Jaiswal
Rishi Jaiswal

Reputation: 41

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

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.

Upvotes: 3

Views: 1710

Answers (1)

MatBBastos
MatBBastos

Reputation: 401

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 the image at the end:

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()

Plot using pyplot

Upvotes: 4

Related Questions