用numpy拟合的Fourier系列数据:fft与编码

时间:2019-02-11 15:52:42

标签: python numpy fft curve-fitting

假设我有一些数据y,我想对它们进行傅立叶级数拟合。在这个post上, Mermoz 发布了一个解决方案,其中使用了该级数的复数格式并“用黎曼和求系数”。在另外一个post上,通过FFT获得序列,并写下示例。

我尝试实现这两种方法(下面的图像和代码-注意每次运行代码时,由于使用 numpy.random.normal 而会生成不同的数据),但我想知道为什么获得不同的结果-黎曼方法似乎“被错误地移位”,而FFT方法似乎被“压缩”。我也不确定我对系列“ tau”期间的定义。感谢您的关注。

我正在Windows 7上将Spyder与Python 3.7.1结合使用

Example

import matplotlib.pyplot as plt
import numpy as np

# Assume x (independent variable) and y are the data.
# Arbitrary numerical values for question purposes:
start = 0
stop = 4
mean = 1
sigma = 2
N = 200
terms = 30 # number of terms for the Fourier series

x = np.linspace(start,stop,N,endpoint=True) 
y = np.random.normal(mean, sigma, len(x))

# Fourier series
tau = (max(x)-min(x)) # assume that signal length = 1 period (tau)

# From ref 1
def cn(n):
    c = y*np.exp(-1j*2*n*np.pi*x/tau)
    return c.sum()/c.size
def f(x, Nh):
    f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/tau) for i in range(1,Nh+1)])
    return f.sum()
y_Fourier_1 = np.array([f(t,terms).real for t in x])

# From ref 2
Y = np.fft.fft(y)
np.put(Y, range(terms+1, len(y)), 0.0) # zero-ing coefficients above "terms"
y_Fourier_2 = np.fft.ifft(Y)

# Visualization
f, ax = plt.subplots()
ax.plot(x,y, color='lightblue', label = 'artificial data')
ax.plot(x, y_Fourier_1, label = ("'Riemann' series fit (%d terms)" % terms))
ax.plot(x,y_Fourier_2, label = ("'FFT' series fit (%d terms)" % terms))
ax.grid(True, color='dimgray', linestyle='--', linewidth=0.5)
ax.set_axisbelow(True)
ax.set_ylabel('y')
ax.set_xlabel('x')
ax.legend()

1 个答案:

答案 0 :(得分:2)

执行两个小的修改就足以使总和几乎类似于np.fft的输出。 The FFTW library indeed computes these sums

1)要考虑信号c[0]的平均值:

f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/tau) for i in range(0,Nh+1)]) # here : 0, not 1

2)必须缩放输出。

y_Fourier_1=y_Fourier_1*0.5

enter image description here 输出似乎被“压缩”,因为高频分量已被滤波。实际上,输入的高频振荡已经清除,输出看起来像是移动平均线。

在这里,tau实际上定义为stop-start:它对应于帧的长度。这是信号的预期周期。

如果帧与信号周期不对应,则可以通过使信号与自身卷积并找到第一个最大值来猜测其周期。看到 Find period of a signal out of the FFT不过,不可能与numpy.random.normal生成的数据集一起正常工作:这是Additive White Gaussian Noise。由于它具有恒定的功率谱密度,因此很难将其描述为周期性的!