Warrick
Warrick

Reputation: 727

Vector/array output from `scipy.ndimage.map_coordinates`

Basically, is it possible to get scipy.ndimage.map_coordinates to return a multi-valued structure, instead of just a scalar? I'd like to be able to interpolate once to retrieve 5 values at a point, rather than having to interpolate 5 times.

Here's my try at a MWE to demonstrate the problem. I'll start with a 3D interpolation of a scalar. I won't go between points for now because that's not the point.

import numpy as np
from scipy import ndimage
coords = np.array([[1.,1.,1.]])
a = np.arange(3*3*3).reshape(3,3,3)
ndimage.map_coordinates(a,coords.T) # array([13.])

Now, suppose I want a to have pairs of values, not just one. My instinct is

a = np.arange(3*3*3*2).reshape(3,3,3,2)
a[1,1,1] # array([26.,27.])
ndimage.map_coordinates(a[:,:,:],coords.T)  # I'd like array([26.,27.])

Instead of the desired output, I get the following:

RuntimeError                              Traceback (most recent call last)
(...)/<ipython-input-84-77334fb7469f> in <module>()
----> 1 ndimage.map_coordinates(a[:,:,:],np.array([[1.,1.,1.]]).T)

/usr/lib/python2.7/dist-packages/scipy/ndimage/interpolation.pyc in map_coordinates(input, coordinates, output, order, mode, cval, prefilter)
    287         raise RuntimeError('input and output rank must be > 0')
    288     if coordinates.shape[0] != input.ndim:
--> 289         raise RuntimeError('invalid shape for coordinate array')
    290     mode = _extend_mode_to_code(mode)
    291     if prefilter and order > 1:

RuntimeError: invalid shape for coordinate array

I can't find a permutation of the shapes of any of the structures (a, coords, etc.) that gives me the answer I'm looking for. Also, if there's a better way to do this than using map_coordinates, go ahead. I thought scipy.interpolate.interp1d might be the way to go but I can't find any documentation or an inkling of what it might do...

Upvotes: 3

Views: 5161

Answers (1)

pv.
pv.

Reputation: 35125

That's not possible, I think.

But tensor product interpolation is not difficult:

import numpy as np
from scipy.interpolate import interp1d

def interpn(*args, **kw):
    """Interpolation on N-D. 

    ai = interpn(x, y, z, ..., a, xi, yi, zi, ...)
    where the arrays x, y, z, ... define a rectangular grid
    and a.shape == (len(x), len(y), len(z), ...)
    """
    method = kw.pop('method', 'cubic')
    if kw:
        raise ValueError("Unknown arguments: " % kw.keys())
    nd = (len(args)-1)//2
    if len(args) != 2*nd+1:
        raise ValueError("Wrong number of arguments")
    q = args[:nd]
    qi = args[nd+1:]
    a = args[nd]
    for j in range(nd):
        a = interp1d(q[j], a, axis=j, kind=method)(qi[j])
    return a

import matplotlib.pyplot as plt

x = np.linspace(0, 1, 6)
y = np.linspace(0, 1, 7)
k = np.array([0, 1])
z = np.cos(2*x[:,None,None] + k[None,None,:]) * np.sin(3*y[None,:,None])

xi = np.linspace(0, 1, 60)
yi = np.linspace(0, 1, 70)
zi = interpn(x, y, z, xi, yi, method='linear')

plt.subplot(221)
plt.imshow(z[:,:,0].T, interpolation='nearest')

plt.subplot(222)
plt.imshow(zi[:,:,0].T, interpolation='nearest')

plt.subplot(223)
plt.imshow(z[:,:,1].T, interpolation='nearest')

plt.subplot(224)
plt.imshow(zi[:,:,1].T, interpolation='nearest')

plt.show()

Upvotes: 3

Related Questions