views:

576

answers:

1

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')
+3  A: 

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.

Justin Peel
Thanks for the response. The file that you pointed to will interpolate any data with a natural spline. This means that the curve will go through every point in the data. If the data is noisy (in my case it is), this is a bad thing to do. If you separate your data into bins and do a least square approximation, we can get a smooth curve that doesn't interpolate the data exactly (which is better with noisy data). I think I am going to have to write the class myself, but it just seems to be one more thing that can go wrong. Thanks again.
Eldila
I got my own code working. Also, I looked at the 2nd option using the pyD3D package again. At first I thought it just did interpolation, but I'm unsure of that now. Either way, I will mark your answer as the accepted answer.
Eldila