Ziffusion
Ziffusion

Reputation: 8923

How do I compute phase and amplitude of a sinusoidal by correlating it with a sine and cosine?

I have an incoming sinusoidal with a known frequency. I understand that one can compute it's phase and amplitude by computing it's correlation with a sine and a cosine. How would I do this using numpy?

Or maybe there is a better way to do this? Looking at this here, but I don't know how to do the computation in numpy.

Upvotes: 1

Views: 1590

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

One convenient method would be to take advantage of Euler's formula e^(i phi) = cos phi + i sin phi:

def get_cos_params(samples):
    N = len(samples)
    x = np.linspace(-np.pi, np.pi, N, endpoint=False)
    template = np.exp(1j * x)
    corr = 2 / N * template@samples
    R = np.abs(corr)
    phi = np.log(corr).imag
    return R, phi

Example:

N = np.random.randint(10, 1000)
phi = np.random.uniform(-np.pi, np.pi)
R = np.random.uniform(0.1, 10)
x = np.linspace(-np.pi, np.pi, N, endpoint=False)
signal = R * np.cos(x-phi)
R_recon, phi_recon = get_cos_params(signal)
print(np.isclose(R, R_recon), np.isclose(phi, phi_recon))
# True True

Upvotes: 2

Related Questions