[SciPy-User] help interpreting univariate spline
Mon Apr 26 14:26:31 CDT 2010
On Fri, Apr 23, 2010 at 6:53 PM, Elliot Hallmark <email@example.com> wrote:
> I am wanting to use a scipy interpolation routine to generate
> polynomials approximating function I have sampled.
> import numpy as np
>from scipy.interpolate import splrep, UnivariateSpline
>x = np.linspace(1, 10, 100)
>y = 1/x #approximate a hyperbola
>g = UnivariateSpline(x, y, w=None, k=3, s=.0005)
>and the output was:
>[ 1. 2.18181818 3.27272727 5.54545455 10. ]
>[ 0.98462432 0.66575572 0.423 0.25461626 0.13929847 0.11763985
>That is 5 knots and 7 coefficients for a degree=3 spline. naively, I
>was expecting 4 coefficents for each interval between knots.
I found this post:
This seems very round-a-bout and ignores the piecewise nature of the
spline. I mean, really? is there no direct or documented way to get
the polynomial coefficents from a spline in python? If not, then this
code is the best I have found. For my purposes I have modified it
explorations into getting polynomial coefficents from a spline.
Modified from http://mail.scipy.org/pipermail/scipy-user/2009-June/021572.html
please email offonoffoffonoff@gmail with improvements to this technique.
import numpy as np
import scipy as sp
from scipy import interpolate
"evaluate a cubic"
def deriv2coeff(x2, tck):
'''construct a piecewise cubic polynomial from derivatives of
spline at given knots (x2)
output is an array of knot abscissa and coefficent of poly for that section.
out = (x_knot,a,b,c,d)'''
if tck != 3:
print "interpolation must be cubic!"
coeffr = np.vstack(interpolate.spalde(x2,tck))
coeffr[:,3] /= 6.
coeffr[:,2] = (coeffr[:,2] - 6*coeffr[:,3]*x2)/2.
coeffr[:,1] = coeffr[:,1] - 2*coeffr[:,2]*x2 - 3*coeffr[:,3]*x2**2
coeffr[:,0] = coeffr[:,0] - coeffr[:,1]*x2 - coeffr[:,2]*x2**2 -
return np.concatenate((np.resize(x2,(x2.size,1)),coeffr), axis=1)
def calc_poly(xs, coeff):
'''determine which piece of the piecewise polynomial the given x
value corisponds to
and return the value of the approximation based on evaluating the
result = np.zeros((xs.size,4))
for i,x in enumerate(xs):
a = b = c = d = 0
for x_knot,a1,b1,c1,d1 in coeff:
if x>x_knot: #x_knot is in ascending order (required by splrep also)
result[i] = a,b,c,d
#print "single: ",x, result[i]
npoints = 51
x = np.linspace(1, 20, 2*npoints)
y = 1/x
tck = interpolate.splrep(x, y, k=3)
#calculate coefficents at original x points,
# would using tck knot values be more faithful to original spline?
coeffr = deriv2coeff(x, tck)
#now, compare the polynomial and original spline over a different dataset
x2 = np.linspace(3, 18, 40)
y_spline = interpolate.splev(x2, tck)
y_polynomial = calc_poly(x2,coeffr)
print "max error: ", np.max(np.abs(y_spline-y_polynomial))
#using the actual knots of the spline
coeffk = deriv2coeff(tck[3:-3], tck)
y_polynomial = calc_poly(x2,coeffk)
print "max error using spline's knots: ", np.max(np.abs(y_spline-y_polynomial))
More information about the SciPy-User