python - Numpy roll in several dimensions -
i need shift 3d array 3d vector of displacement algorithm. of i'm using (admitedly ugly) method :
shiftedarray = np.roll(np.roll(np.roll(arraytoshift, shift[0], axis=0) , shift[1], axis=1), shift[2], axis=2)
which works, means i'm calling 3 rolls ! (58% of algorithm time spent in these, according profiling)
from docs of numpy.roll:
parameters:
shift : intaxis : int, optional
no mention of array-like in parameter ... can't have multidimensional rolling ?
i thought call kind of function (sounds numpy thing do) :
np.roll(arraytoshift,3dshiftvector,axis=(0,1,2))
maybe flattened version of array reshaped ? how compute shift vector ? , shift same ?
i'm surprised find no easy solution this, thought pretty common thing (okay, not that common, ...)
so how --relatively-- efficiently shift ndarray n-dimensional vector ?
i think scipy.ndimage.interpolation.shift
want, docs
shift : float or sequence, optional
the shift along axes. if float, shift same each axis. if sequence, shift should contain 1 value each axis.
which means can following,
from scipy.ndimage.interpolation import shift import numpy np arraytoshift = np.reshape([i in range(27)],(3,3,3)) print('before shift') print(arraytoshift) shiftvector = (1,2,3) shiftedarray = shift(arraytoshift,shift=shiftvector,mode='wrap') print('after shift') print(shiftedarray)
which yields,
before shift [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]] [[18 19 20] [21 22 23] [24 25 26]]] after shift [[[16 17 16] [13 14 13] [10 11 10]] [[ 7 8 7] [ 4 5 4] [ 1 2 1]] [[16 17 16] [13 14 13] [10 11 10]]]
Comments
Post a Comment