Recreating time series data using FFT results without using ifft

2024/10/5 19:20:58

I analyzed the sunspots.dat data (below) using fft which is a classic example in this area. I obtained results from fft in real and imaginery parts. Then I tried to use these coefficients (first 20) to recreate the data following the formula for Fourier transform. Thinking real parts correspond to a_n and imaginery to b_n, I have

import numpy as np
from scipy import *
from matplotlib import pyplot as gplt
from scipy import fftpackdef f(Y,x):total = 0for i in range(20):total += Y.real[i]*np.cos(i*x) + Y.imag[i]*np.sin(i*x)return totaltempdata = np.loadtxt("sunspots.dat")year=tempdata[:,0]
wolfer=tempdata[:,1]Y=fft(wolfer)
n=len(Y)
print nxs = linspace(0, 2*pi,1000)
gplt.plot(xs, [f(Y, x) for x in xs], '.')
gplt.show()       

For some reason however, my plot does not mirror the one generated by ifft (I use the same number of coefficients on both sides). What could be wrong ?

Data:

http://linuxgazette.net/115/misc/andreasen/sunspots.dat

Answer

When you called fft(wolfer), you told the transform to assume a fundamental period equal to the length of the data. To reconstruct the data, you have to use basis functions of the same fundamental period = 2*pi/N. By the same token, your time index xs has to range over the time samples of the original signal.

Another mistake was in forgetting to do to the full complex multiplication. It's easier to think of this as Y[omega]*exp(1j*n*omega/N).

Here's the fixed code. Note I renamed i to ctr to avoid confusion with sqrt(-1), and n to N to follow the usual signal processing convention of using the lower case for a sample, and the upper case for total sample length. I also imported __future__ division to avoid confusion about integer division.

forgot to add earlier: Note that SciPy's fft doesn't divide by N after accumulating. I didn't divide this out before using Y[n]; you should if you want to get back the same numbers, rather than just seeing the same shape.

And finally, note that I am summing over the full range of frequency coefficients. When I plotted np.abs(Y), it looked like there were significant values in the upper frequencies, at least until sample 70 or so. I figured it would be easier to understand the result by summing over the full range, seeing the correct result, then paring back coefficients and seeing what happens.

from __future__ import division
import numpy as np
from scipy import *
from matplotlib import pyplot as gplt
from scipy import fftpackdef f(Y,x, N):total = 0for ctr in range(len(Y)):total += Y[ctr] * (np.cos(x*ctr*2*np.pi/N) + 1j*np.sin(x*ctr*2*np.pi/N))return real(total)tempdata = np.loadtxt("sunspots.dat")year=tempdata[:,0]
wolfer=tempdata[:,1]Y=fft(wolfer)
N=len(Y)
print(N)xs = range(N)
gplt.plot(xs, [f(Y, x, N) for x in xs])
gplt.show()
https://en.xdnf.cn/q/70454.html

Related Q&A

python BeautifulSoup get all href in Children of div

I am new to python and Ive been trying to get links and inner text from this html code : <div class="someclass"><ul class="listing"><li><a href="http://lin…

Python TypeError: sort() takes no positional arguments

I try to write a small class and want to sort the items based on the weight. The code is provided, class Bird:def __init__(self, weight):# __weight for the private variableself.__weight = weightdef wei…

Trouble with basemap subplots

I need to make a plot with n number of basemap subplots. But when I am doing this the all the values are plotted on the first subplot.My data is a set of n matrixes, stored in data_all.f, map = plt.sub…

Remove circular references in dicts, lists, tuples

I have this following really hack code which removes circular references from any kind of data structure built out of dict, tuple and list objects.import astdef remove_circular_refs(o):return ast.liter…

how to change image format when uploading image in django?

When a user uploads an image from the Django admin panel, I want to change the image format to .webp. I have overridden the save method of the model. Webp file is generated in the media/banner folder b…

Write info about nodes to a CSV file on the controller (the local)

I have written an Ansible playbook that returns some information from various sources. One of the variables I am saving during a task is the number of records in a certain MySQL database table. I can p…

Python minimize function: passing additional arguments to constraint dictionary

I dont know how to pass additional arguments through the minimize function to the constraint dictionary. I can successfully pass additional arguments to the objective function.Documentation on minimiz…

PyQt5 triggering a paintEvent() with keyPressEvent()

I am trying to learn PyQt vector painting. Currently I am stuck in trying to pass information to paintEvent() method which I guess, should call other methods:I am trying to paint different numbers to a…

A python regex that matches the regional indicator character class

I am using python 2.7.10 on a Mac. Flags in emoji are indicated by a pair of Regional Indicator Symbols. I would like to write a python regex to insert spaces between a string of emoji flags.For exampl…

Importing modules from a sibling directory for use with py.test

I am having problems importing anything into my testing files that I intend to run with py.test.I have a project structure as follows:/ProjectName | |-- /Title | |-- file1.py | |-- file2.py | …