views:

95

answers:

2

I have the following numpy array:

#                      A    B    C         Y
my_arr = np.array([ [.20, .54, .26],     # <0
                    [.22, .54, .24],     # 1
                    [.19, .56, .25],     # 2
                    [.19, .58, .23],     # 3
                    [.17, .62, .21] ])   # 4+

if a user enters a y (example, 2.5) I should out put three values, one for A, B, and C:

in my example A: .19, B: .57, C: .24

More Examples:

Y     A      B      C
0.2   .20    .54    .26 
1.5   .215   .55    .245
4.0   .17    .62    .21
8.7   .17    .62    .21

The user will enter a multiple of y values as a numpy array. the result should be an array as well

I've done bits and pieces of the code for example

#boundaries:
y[y < 0] = 0
y[y > 4] = 4

I'm also assuming that scipy.ndimage / map_coordinates will best fit my requirements rather than scipy.interpolate but I could be wrong

+6  A: 
from scipy import array, ndimage

#              A    B    C         Y
m = array([ [.20, .54, .26],     # 0
            [.22, .54, .24],     # 1
            [.19, .56, .25],     # 2
            [.19, .58, .23],     # 3
            [.17, .62, .21] ])   # 4

inputs = array([-1, 0, 0.2, 1, 1.5, 2, 2.5, 3, 4, 8.7])
inputs[inputs < 0] = 0
inputs[inputs > 4] = 4

for y in inputs:
    x = ndimage.map_coordinates(m, [y * numpy.ones(3), numpy.arange(3)], order=1)
    print y, x

>>> 
0.0 [ 0.2   0.54  0.26]
0.0 [ 0.2   0.54  0.26]
0.2 [ 0.204  0.54   0.256]
1.0 [ 0.22  0.54  0.24]
1.5 [ 0.205  0.55   0.245]
2.0 [ 0.19  0.56  0.25]
2.5 [ 0.19  0.57  0.24]
3.0 [ 0.19  0.58  0.23]
4.0 [ 0.17  0.62  0.21]
4.0 [ 0.17  0.62  0.21]
Judge Maygarden
what if the y axis is different from 0 to 4
dassouki
+2  A: 

There might be a better way using scipy.ndimage, but here is how you could do it with scipy.interpolate.interp1d:

import numpy as np
import scipy.interpolate as spi

#                      A    B    C         Y
my_arr = np.array([ [.20, .54, .26],     # 0
                    [.22, .54, .24],     # 1
                    [.19, .56, .25],     # 2
                    [.19, .58, .23],     # 3
                    [.17, .62, .21] ])

print(my_arr)
Y=np.arange(len(my_arr))
interp_funcs=[spi.interp1d(Y,my_arr[:,col]) for col in range(3)]
y=np.array([2.5,0.2,1.5,4.0,8.7])
y[y < 0] = 0
y[y > 4] = 4
print(np.vstack(f(y) for f in interp_funcs))
# [[ 0.19   0.204  0.205  0.17   0.17 ]
#  [ 0.57   0.54   0.55   0.62   0.62 ]
#  [ 0.24   0.256  0.245  0.21   0.21 ]]
unutbu