Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Least-Squares Natural Splines

I am trying to find a numerical package which will fit a natural spline which minimizes weighted least squares.

There is a package in scipy which does what I want for unnatural splines.

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate, randn

x = np.arange(0,5,1.0/6)
xs = np.arange(0,5,1.0/500)

y = np.sin(x+1) + .2*np.random.rand(len(x)) -.1

knots = np.array([1,2,3,4])
tck = interpolate.splrep(x,y,s=0,k=3,t=knots,task=-1)
ys = interpolate.splev(xs,tck,der=0)

plt.figure()
plt.plot(xs,ys,x,y,'x')
like image 780
Eldila Avatar asked Mar 14 '10 03:03

Eldila


1 Answers

The spline.py file inside of this tar file from this page does a natural spline fit by default. There is also some code on this page that claims to mostly what you want. The pyD3D package also has a natural spline function in its pyDataUtils module. This last one looks the most promising to me. However, it doesn't appear to have the option of setting your own knots. Maybe if you look at the source you can find a way to rectify that.

Also, I found this message on the Scipy mailing list which says that using s=0.0 (as in your given code) makes splines fitted using your above procedure natural according the writer of the message. I did find this splmake function that has an option to do a natural spline fit, but upon looking at the source I found that it isn't implemented yet.

like image 169
Justin Peel Avatar answered Sep 22 '22 08:09

Justin Peel