a different ben
a different ben

Reputation: 4008

How do I use scipy.interpolate.splrep to interpolate a curve?

Using some experimental data, I cannot for the life of me work out how to use splrep to create a B-spline. The data are here: http://ubuntuone.com/4ZFyFCEgyGsAjWNkxMBKWD

Here is an excerpt:

#Depth  Temperature
1   14.7036
-0.02   14.6842
-1.01   14.7317
-2.01   14.3844
-3  14.847
-4.05   14.9585
-5.03   15.9707
-5.99   16.0166
-7.05   16.0147

and here's a plot of it with depth on y and temperature on x: enter image description here

Here is my code:

import numpy as np
from scipy.interpolate import splrep, splev

tdata = np.genfromtxt('t-data.txt', 
                      skip_header=1, delimiter='\t')
depth = tdata[:, 0]
temp = tdata[:, 1]

# Find the B-spline representation of 1-D curve:
tck = splrep(depth, temp)
### fails here with "Error on input data" returned. ###

I know I am doing something bleedingly stupid, but I just can't see it.

Upvotes: 3

Views: 3655

Answers (1)

Nolen Royalty
Nolen Royalty

Reputation: 18633

You just need to have your values from smallest to largest :). It shouldn't be a problem for you @a different ben, but beware readers from the future, depth[indices] will throw a TypeError if depth is a list instead of a numpy array!

>>> indices = np.argsort(depth)
>>> depth = depth[indices]
>>> temp = temp[indices]
>>> splrep(depth, temp)
(array([-7.05, -7.05, -7.05, -7.05, -5.03, -4.05, -3.  , -2.01, -1.01,
        1.  ,  1.  ,  1.  ,  1.  ]), array([ 16.0147    ,  15.54473241,  16.90606794,  14.55343229,
        15.12525673,  14.0717599 ,  15.19657895,  14.40437622,
        14.7036    ,   0.        ,   0.        ,   0.        ,   0.        ]), 3)

Hat tip to @FerdinandBeyer for the suggestion of argsort instead of my ugly "zip the values, sort the zip, re-assign the values" method.

Upvotes: 6

Related Questions