简体   繁体   中英

Calculating a Power Spectrum in Python via Autocorrelation

I want to calculate the Power Spectrum of a 8192 data vector through the usage of cumulants. I calculated autocorrrelation with 128 max shiftings, reduced it by the signal's mean and performed an fft. The result was complex instead of real and positive. Where did I go wrong?

This is my code.

import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import acf
import pandas as pd

#Creating the random variables
φ=[]
for i in range(0,6):
    if(i==2):
        φ.append((φ[0]+φ[1]))
    elif(i==5):
        φ.append((φ[3]+φ[4]))
    else:
        φ.append(np.random.uniform(0,2*np.pi))
        
#Creating the λ variables
λ=[0.12,0.3,0.42,0.19,0.17,0.36]

#Building the x process
x=[]
samples=8192
for k in range(0,samples):
    x.append(0)
    for i in range(0,6):
        x[k]+=np.cos(k*2*λ[i]*np.pi+φ[i])

#Preparing The Plot and adding x to it
fig, [ax1,ax2,ax3,ax4]=plt.subplots(nrows=4,ncols=1)
ax1.plot(x)
ax1.set_title("Time Signal")

#Building The Autocorellation function
lags=128
corr=[]
temp=[]
for i in range(0,lags):
    for k in range(0,samples):
        if(i+k>=samples):
            temp.append(0)
        else:
            temp.append(x[k+i]*x[k])
    corr.append(np.mean(temp))
    corr[i]-=(np.mean(x))**2
    temp.clear()
  
#Calculating The Power Spectrum
C2=np.fft.fft(corr)
print(C2)


When performing the Fourier transform with np.fft.fft , the result is always a complex signal which contains the amplitude and phase of each frequency.

What you want is the power spectrum, which can be found by squaring the Fourier transformed signal:

C2= np.abs(np.fft.fft(corr))**2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM