[SciPy-user] using UnivariateSpline

josef.pktd at gmail.com josef.pktd at gmail.com
Fri May 22 16:12:10 EDT 2009


On Fri, May 22, 2009 at 3:57 PM, David Warde-Farley <dwf at cs.toronto.edu> wrote:
> I must be crazy, but how does one actually USE UnivariateSpline, etc.
> to do interpolation?

read the source, look at the tests,
scipy\interpolate\tests\test_fitpack.py, search the mailing lists and
hope for the best (and file a bug report)

below are some of my attempt of understanding what's going on with the
spline classes

> How do I evaluate the spline at other data after
> it's fit?
>
> There seems to be no "evaluate" method or equivalent to splev.


-------------------


"""
try_spline.py
"""

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

npoints = 51
x = np.linspace(0, 20, npoints)
y = np.sqrt(x) + np.sin(x) + 0.2* np.random.randn(npoints)
tck = interpolate.splrep(x, y)
x2 = np.linspace(0, 20, 200)
y2 = interpolate.splev(x2, tck)
plt.plot(x, y, 'o', x2, y2, '-.')
#plt.show()

#tck2 = interpolate.splrep(x, y, t=tck[1])
#x3 = np.linspace(0, 20, 300)
#y3 = interpolate.splev(x3, tck2)
#plt.plot(x, y, 'o', x3, y3, '-.')
#

us = interpolate.UnivariateSpline(x,y)
t = us.get_knots()
print t
#tck2 = interpolate.splrep(x2, y2, t=t, full_output=True)

tck2 = interpolate.splrep(x, y, s=1, full_output=True)
y2 = interpolate.splev(x2, tck2[0])
plt.plot(x, y, 'o', x2, y2, '-.')

tt=x[1:-1:2]
lsus=interpolate.LSQUnivariateSpline(x,y,tt)
yh = lsus(x2)
plt.figure()
plt.plot(x, y, 'o', x2, yh, '-.')

lsus=interpolate.UnivariateSpline(x,y,s=2)
yh = lsus(x2)
plt.figure()
plt.plot(x, y, 'o', x2, yh, '-.')

#derivatives doesn't take array arguments correctly
print lsus.derivatives(x)
#using fitpacks spalde directly works
deri = np.array(interpolate.spalde(x, lsus._eval_args))
print deri[:10,:]
print np.all(lsus(x) == deri[:,0])
print np.max(np.abs(lsus(x) - deri[:,0]))
deri2 = np.array(map(lsus.derivatives,x))
print np.all(deri2 == deri)
print np.max(np.abs(deri2 - deri))


print lsus.integral(x[0],x[-1])

#plt.show()


example = 0
if example == 3:
    #copied from
    #http://groups.google.ca/group/scipy-user/browse_thread/thread/ded43ebce135c520/eccf1dd343456137?hl=en&lnk=gst&q=splrep#eccf1dd343456137
    import scipy as sp
    x=sp.linspace(0,10,11)
    y=sp.sin(x)
    x2=sp.linspace(0,10,201)
    tck=sp.interpolate.splrep(x,y,k=3)
    y2=sp.interpolate.splev(x2,tck)
    f=sp.interpolate.interp1d(x,y,kind=3)
    y3=f(x2)

    '''
   :members:  __call__, derivatives, get_coeffs, get_knots, get_residual,
              integral, roots, set_smoothing_factor'
    '''



More information about the SciPy-User mailing list