Skip to content

Instantly share code, notes, and snippets.

@denis-bz
Created March 28, 2013 17:26
Show Gist options
  • Save denis-bz/5265158 to your computer and use it in GitHub Desktop.
Save denis-bz/5265158 to your computer and use it in GitHub Desktop.
a little testcase for scipy splines, random-uniform X -> linspace Y: see http://imgur.com/Z9ikNCk
# interp1d != splev random-uniform -> 0 1 2 ...
# big swings, different end conditions
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html
# http://stackoverflow.com/questions/6216881/python-interp1d-vs-univariatespline
# 28mar 2013
from __future__ import division
import sys
import numpy as np
import scipy
from scipy.interpolate import interp1d, splrep, splev, UnivariateSpline
# $scipy/interpolate/fitpack.py $scipy/interpolate/fitpack2.py
# 2012 dec 13 Stickel splev waaay faster ?
print "versions: numpy %s scipy %s python %s" % (
np.__version__, scipy.__version__, sys.version.split()[0] )
#...............................................................................
nx = 11
nfine = 101
k = 3
plot = 0
seed = 0
exec( "\n".join( sys.argv[1:] )) # run this.py n= ... from sh or ipython
np.set_printoptions( 1, threshold=100, edgeitems=10, suppress=True )
np.random.seed(seed)
#...............................................................................
# random-uniform X -> linspace --
X = np.r_[ 0, np.sort( np.random.uniform( size = nx - 2 )), 1 ]
Y = np.r_[ 0., np.arange(nx - 2), nx - 2 ]
xfine = np.linspace( 0, 1, nfine )
if plot:
import pylab as pl
pl.title( "scipy interpolation X: random uniform, Y: 0 1 2 ..." )
pl.ylim( -100, nx )
pl.plot( X, Y, "o", markersize=5, markerfacecolor="none" )
#...............................................................................
def spline( label, f ):
""" print / plot Y - f(X), yfine = f(xfine) """
print "\n%s --" % label
diff = Y - f(X)
print "Y - f(X): min max %.1g %.1g" % (diff.min(), diff.max())
yfine = f(xfine)
print "yfine: min %.2g %s" % (yfine.min(), yfine)
if plot:
pl.plot( xfine, yfine, label=label )
#...............................................................................
spline( "splev", lambda x: splev( x, splrep( X, Y, k=k )))
spline( "interp1d", interp1d( X, Y, kind=k ))
# spline( "UnivariateSpline", UnivariateSpline( X, Y, k=k, s=0 )) # == splev
if plot:
pl.legend( loc="upper left" )
pl.savefig( "tmp.png", dpi=80 )
pl.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment