Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of numpy.unwrap

Tags:

python

numpy

In Python numpy, there is an unwrap function that:

Unwrap radian phase p by changing absolute jumps greater than discont to their 2*pi complement along the given axis.

Now, I'd like to do the opposite function. How can I wrap an array of phases? E.g. how to convert all angles to constraint them between -π and π?

The obvious way would be to do something like:

for i, a in enumerate(phases):     while a < pi:         a += 2 * pi     while a > pi:         a -= 2 * pi     phases[i] = a 

but is there a simpler / faster way?

like image 312
Charles Brunet Avatar asked Apr 10 '13 13:04

Charles Brunet


People also ask

What does np Unwrap do?

unwrap() in Python. numpy. unwrap(p, discount=3.141592653589793, axis=-1) function helps user to unwrap a given array by changing deltas to values of 2*pi complement. It unwraps radian phase p by changing absolute jumps greater than discount to their 2*pi complement along the given axis.

How do you write pi in Numpy?

Numpy is a scientific computation library in python and has values for a number of numerical constants including pi. You can use numpy. pi or np. pi depending on how you import the library to get the value of pi.


2 Answers

phases = (phases + np.pi) % (2 * np.pi) - np.pi 
like image 121
sega_sai Avatar answered Sep 17 '22 18:09

sega_sai


import numpy as np phases = np.arctan2(np.sin(phases), np.cos(phases)) 

This works because sin(phases)/cos(phases) == tan(phases). We get back phases (modulo 2π) by using the inverse-tangent function. Mathematically, the inverse-tangent function is multivalued, so in programming languages it is usually defined to return the phase in a fixed interval.

The two-parameter arctangent function, i.e. np.arctan2(numerator, denominator), is the same as the regular arctangent function except that it keeps track of the signs of the numerator and denominator, and therefore is able to return the phase modulo 2π, instead of the regular np.arctan(numerator/denominator) function which is only able to return the phase modulo π. Numpy's implementation of the arctan2 function is defined to return the phase in the range [-π, +π], which is the range that the OP requested.

Additional explanation: This arctan2 method follows directly from the complex representation, and is entirely mathematically equivalent to:

phases = np.angle(np.exp(1j*phases)) 

which may be more intuitive. And in fact, numpy's angle function uses arctan2 behind the scenes to separate the imaginary and real components of the exponential, i.e. the sine and cosine.

like image 29
u55 Avatar answered Sep 20 '22 18:09

u55