复杂的交叉谱密度

时间:2014-12-11 15:32:36

标签: python-2.7 matplotlib spectral-density

来自matplotlib的mlab.csd:http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.csd可用于获得实值交叉谱密度。如果我想从谱密度中获取相位信息,我需要一个csd计算,它返回复数值。有吗?

1 个答案:

答案 0 :(得分:0)

这是讨论的,例如在这个答案:https://stackoverflow.com/a/29306730/3920342

如果使用mlab库的csd,您将获得复杂的值,因此您可以计算相位角(以及实际值的相干性)。在下面的代码中,s1和s2包含要相关的两个信号(在时域中)。

from matplotlib import mlab

# First create power sectral densities for normalization
(ps1, f) = mlab.psd(s1, Fs=1./dt, scale_by_freq=False)
(ps2, f) = mlab.psd(s2, Fs=1./dt, scale_by_freq=False)
plt.plot(f, ps1)
plt.plot(f, ps2)

# Then calculate cross spectral density
(csd, f) = mlab.csd(s1, s2, NFFT=256, Fs=1./dt,sides='default', scale_by_freq=False)
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
# Normalize cross spectral absolute values by auto power spectral density
ax1.plot(f, np.absolute(csd)**2 / (ps1 * ps2))
ax2 = fig.add_subplot(1, 2, 2)
angle = np.angle(csd, deg=True)
angle[angle<-90] += 360
ax2.plot(f, angle)

# zoom in on frequency with maximum coherence
ax1.set_xlim(9, 11)
ax1.set_ylim(0, 1e-0)
ax1.set_title("Cross spectral density: Coherence")
ax2.set_xlim(9, 11)
ax2.set_ylim(0, 90)
ax2.set_title("Cross spectral density: Phase angle")

这里是交叉谱密度的实部和虚部(!)部分: real and imaginary part of the cross spectral density

此代码取自问题How to use the cross-spectral density to calculate the phase shift of two related signals以创建两个信号s1和s2:

"""
Compute the coherence of two signals
"""
import numpy as np
import matplotlib.pyplot as plt

# make a little extra space between the subplots
plt.subplots_adjust(wspace=0.5)

nfft = 256
dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2
r = np.exp(-t/0.05)

cnse1 = np.convolve(nse1, r, mode='same')*dt   # colored noise 1
cnse2 = np.convolve(nse2, r, mode='same')*dt   # colored noise 2

# two signals with a coherent part and a random part
s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1
s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2