傅立叶将实验数据转换为频域

时间:2013-10-04 17:44:09

标签: python fft

我对python完全不熟悉。我进行了波浪数据测试实验。我有时间序列数据可供我使用。如何继续在频域中显示?有什么例子我可以参考吗?我提出了一个如下所示的程序,但它似乎不起作用。请帮忙。

#Program for Fourier Transformation
import numpy as np
import numpy.fft as fft
import matplotlib.pyplot as plt

def readdat( filename ):
    """
        Reads sectional area curve data from file filename
    """

    # read all lines of input files
    fp = open( filename, 'r')
    lines = fp.readlines() # to read the tabulated data
    fp.close()

    # interpret data
    time = []
    ampl = []
    for line in lines:
        if line[0:1] == '#':
            continue # ignore comments in the file
        try:
            time.append(float(line.split()[0])) #first column is time
            ampl.append(float(line.split()[1])) # second column is corresponding amplitude
        except:
            # if the data interpretation fails..
            continue
    return np.asarray(time), np.asarray(ampl)

if __name__ == '__main__':

    time, ampl = readdat( 'data.dat')
    print time
    print ampl

spectrum = fft.fft(ampl)
freq = fft.fftfreq(len(spectrum))
print freq

1 个答案:

答案 0 :(得分:0)

对程序进行最小修正以绘制一些结果就像这样

#Program for Fourier Transformation
import numpy as np
import numpy.fft as fft
import matplotlib.pyplot as plt

def readdat( filename ):
    """
        Reads sectional area curve data from file filename
    """

    # read all lines of input files
    fp = open( filename, 'r')
    lines = fp.readlines() # to read the tabulated data
    fp.close()

    # interpret data
    time = []
    ampl = []
    for line in lines:
        if line[0:1] == '#':
            continue # ignore comments in the file
        try:
            time.append(float(line.split()[0])) #first column is time
            ampl.append(float(line.split()[1])) # second column is corresponding amplitude
        except:
            # if the data interpretation fails..
            continue
    return np.asarray(time), np.asarray(ampl)

if __name__ == '__main__':

    time, ampl = readdat( 'data.dat')
    print time
    print ampl

spectrum = fft.fft(ampl)
timestep = time[1]-time[0] # assume samples at regular intervals
freq = fft.fftfreq(len(spectrum),d=timestep)
freq=fft.fftshift(freq)
spectrum = fft.fftshift(spectrum)
plt.figure(0,figsize=(5.0*1.21,5.0))
plt.plot(freq,spectrum)
print freq
plt.xlabel("frequencies")
plt.ylabel("spectrum")
plt.savefig("/tmp/figure.png")