2

Let's assume I have an array of phases (from complex numbers)

A = np.angle(np.random.uniform(-1,1,[10,10,10]) + 1j*np.random.uniform(-1,1,[10,10,10]))

I would now like to unwrap this array in ALL dimensions. In the above 3D case I would do

A_unwrapped = np.unwrap(np.unwrap(np.unwrap(A,axis=0), axis=1),axis=2)

While this is still feasible in the 3D case, in case of higher dimensionality, this approach seems a little cumbersome to me. Is there a more efficient way to do this with numpy?

Ethunxxx
  • 1,229
  • 4
  • 16
  • 34

2 Answers2

1

You could use np.apply_over_axes, which is supposed to apply a function over each dimension of an array in turn:

np.apply_over_axes(np.unwrap, A, np.arange(len(A.shape)))

I believe this should do it.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • I expect all these solutions will have same speed, since they all call `unwrap` `ndim` times. – hpaulj Jul 19 '17 at 15:00
  • @hpaulj Yep... at that point it's just a matter of how many lines of code you want your unwrapping code to take. – cs95 Jul 19 '17 at 15:02
0

I'm not sure if there is a way to bypass performing the unwrap operation along each axis. Obviously if it acted on individual elements you could use vectorization, but that doesn't seem to be an option here. What you can do that will at least make the code cleaner is create a loop over the dimensions:

for dim in range(len(A.shape)):
   A = np.unwrap(A, axis=dim)

You could also repeatedly apply a function that takes the dimension on which to operate as a parameter:

reduce(lambda A, axis: np.unwrap(A, axis=axis), range(len(A.shape)), A)

Remember that in Python 3 reduce needs to be imported from functools.

David Z
  • 128,184
  • 27
  • 255
  • 279