I have a cube of shape (x,y,t). I need to shift each (x,y) indices of a varying number of position along the t axis. Basically I have something like:
roll_matrix = [[0,5,9,0], [3,2,0,0]]
The roll_matrix specifies, for each (x,y) position how much to shift along the remaining axis (axis=2). I never need to roll along other axis.
For example, cube[1,0] must shift 3 position, cube [0,0] must stay as-is, etc. I don't care too much what happens with the rolled values - ideally just move them form the front to the end of the array along the time axis. But I could pad with neutral values, in case some slicing notation would do the trick.
I care more about speed than what happens with rolled over values, in other words.
I currently have a for-loop that takes forever. I need an optimized notation to accomplish this instead. I looked up numpy.roll(), however it only allows you to roll along more than one axis, not to perform different roll values along the same one....
Any ideas?
EDIT:
The current for loop:
import numpy as np
cube = np.linspace(0,39,40)
cube = cube.reshape((2,2,10))
roll_matrix = np.array([[4,0],[3,2]])
print(cube)
print("")
def roll(cube, roll_matrix):
cp_cube = np.copy(cube)
Rawf = cube.reshape(cube.shape[0] * cube.shape[1], cube.shape[2])
ThPosf = roll_matrix.reshape(roll_matrix.shape[0] * roll_matrix.shape[1])
RawThf = Rawf
for i, trigger_value in enumerate(ThPosf):
RawThf[i, :] = np.roll(Rawf[i, :], -trigger_value)
RawTh = RawThf.reshape(cube.shape[0], cube.shape[1], cube.shape[2])
return RawTh
ans = roll(cube, roll_matrix)
print(ans)
While yields:
Initial data:
[[[ 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. 27. 28. 29.]
[30. 31. 32. 33. 34. 35. 36. 37. 38. 39.]]]
Rolled data:
[[[ 4. 5. 6. 7. 8. 9. 0. 1. 2. 3.] #shifted 4
[10. 11. 12. 13. 14. 15. 16. 17. 18. 19.]] # no shift, 0
[[23. 24. 25. 26. 27. 28. 29. 20. 21. 22.] #shifted 3
[32. 33. 34. 35. 36. 37. 38. 39. 30. 31.]]] # 2
roll_matrix
isn't being used other than here - it's the output from a calculation that tells me how much each to move to be aligned along the time axis. Basically the data obtained is misaligned and I need to align them properly along the time axis.