# FFT with Python¶

If you want to know how the FFT Algorithm works, Jake Vanderplas explained it extremely well in his blog: http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/

Here is, how it is applied and how the axis are scaled to real physical values.

In [80]:
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

In [81]:
%pylab inline --no-import-all

Populating the interactive namespace from numpy and matplotlib


## First: A synthetic Signal, a simple Sine Wave¶

In [82]:
t = np.linspace(0, 2*np.pi, 1000, endpoint=True)
f = 3.0 # Frequency in Hz
A = 100.0 # Amplitude in Unit
s = A * np.sin(2*np.pi*f*t) # Signal

In [83]:
plt.plot(t,s)
plt.xlabel('Time ($s$)')
plt.ylabel('Amplitude ($Unit$)')

Out[83]:
<matplotlib.text.Text at 0x10fd4dbd0>

## Do the Discrete Fourier Transform with the Blazing Fast FFT Algorithm¶

In [84]:
Y = np.fft.fft(s)


That's it.

### Let's take a look at the result¶

In [85]:
plt.plot(Y)

Out[85]:
[<matplotlib.lines.Line2D at 0x10ff3f7d0>]

Hm, looks strange. Something, which is mirrored at the half, right?!

In [86]:
N = len(Y)/2+1
Y[N-4:N+3]

Out[86]:
array([ 35.82784530 -3.47926591e-01j,  35.82789273 -2.31947205e-01j,
35.82792118 -1.15972446e-01j,  35.82793066 +2.45137244e-13j,
35.82792118 +1.15972446e-01j,  35.82789273 +2.31947205e-01j,
35.82784530 +3.47926591e-01j])

Can you see it?

And it is something with imaginary parts (the $j$) in it. So let's just take the real part of it with the abs command.

In [87]:
plt.plot(np.abs(Y))

Out[87]:
[<matplotlib.lines.Line2D at 0x10f78b210>]

Again, it is perfectly mirrored at the half. So let's just take the first half.

## Amplitude Spectrum¶

Remember: $N$ is half the length of the output of the FFT.

In [88]:
plt.plot(np.abs(Y[:N]))

Out[88]:
[<matplotlib.lines.Line2D at 0x110008690>]

That looks pretty good. It is called the amplitude spectrum of the time domain signal and was calculated with the Discrete Fourier Transform with the Chuck-Norris-Fast FFT algorithm. But how to get the x- and y-axis to real physical scaled values?!

## Real Physical Values for the Amplitude and Frequency Axes of the FFT¶

### x-Axis: The Frequency Axis of the FFT¶

First, let us determine the timestep, which is used to sample the signal. We made it synthetically, but a real signal has a period (measured every second or every day or something similar). If there is no constant frequency, the FFT can not be used! One can interpolate the signal to a new time base, but then the signal spectrum is not the original one. It depends on the case, if the quality is enough or if the information is getting lost with this shift keying. Enough.

We have a good signal:

In [89]:
dt = t[1] - t[0]
fa = 1.0/dt # scan frequency
print('dt=%.5fs (Sample Time)' % dt)
print('fa=%.2fHz (Frequency)' % fa)

dt=0.00629s (Sample Time)
fa=159.00Hz (Frequency)


Now we need to create a x-Axis vector, which starts from $0.0$ and is filled with $N$ (length of half of the FFT signal) values and going all the way to the maximum frequency, which can be reconstructed. This frequency is half of the maximum sampling frequency ($f_a$) and is called the Nyquist-Frequency (see Nyquist-Shannon Sampling Theorem).

In [90]:
X = np.linspace(0, fa/2, N, endpoint=True)
X[:4]

Out[90]:
array([ 0.        ,  0.15899579,  0.31799158,  0.47698736])

Now let's plot the amplitude spectrum over the newly created frequency vector $X$

In [91]:
plt.plot(X, np.abs(Y[:N]))
plt.xlabel('Frequency ($Hz$)')

Out[91]:
<matplotlib.text.Text at 0x10f02da90>

Yeah! The x-Axis is showing us, that we have a peak at exactly these frequencies, from which our synthetically created signal was build of. That was the job.

The sample frequency was $f_a=159Hz$, so the amplitude spectrum is from $0.0$ to $\frac{f_a}{2}=79.5Hz$.

### y-Axis: The Amplitude of the FFT Signal¶

This task is not this easy, because one have to understand, how the Fourier Transform or the Discrete Fourier Transform works in detail. We need to transform the y-axis value from something to a real physical value. Because the power of the signal in time and frequency domain have to be equal, and we just used the left half of the signal (look at $N$), now we need to multiply the amplitude with the factor of 2. If we inverse the FFT with IFFT, the power of the signal is the same.

But that was the easy part. The more complicated one is, if you look at the definition of the Discrete Fourier Transform:

$Y[k]=\frac{1}{N} \underbrace{\sum_{N} x(nT)\cdot e^{-i 2 \pi \frac{k}{N}n}}_{DFT}$

In most implementations, the output $Y$ of the FFT is normalized with the number of samples. We have to divide by $N$ to get the real physical value.

The magic factor is $\frac{2}{N}$.

In [92]:
plt.plot(X, 2.0*np.abs(Y[:N])/N)
plt.xlabel('Frequency ($Hz$)')
plt.ylabel('Amplitude ($Unit$)')

Out[92]:
<matplotlib.text.Text at 0x10f6dd890>

Yeah! Job accomplised. Congratulations. But wait...

If you look at the parameters for the original signal ($A$), our signal amplitude was not, what is calculated here. Why??

## The wrong Amplitude Spectrum because of Leakage Effect¶

Take a look at the original signal.

In [93]:
plt.plot(t,s)
plt.xlabel('Time ($s$)')
plt.ylabel('Amplitude ($Unit$)')

Out[93]:
<matplotlib.text.Text at 0x10f764650>

Do you see, that the signal do not end at amplitude zero, where it started? That means, if you add these signals up, it looks like this:

In [94]:
plt.plot(t, s, label='Signal 1')
plt.plot(t+t[-1], s, label='Signal 1 again')
plt.xlim(t[-1]-1, t[-1]+1)
plt.xlabel('Time ($s$)')
plt.ylabel('Amplitude ($Unit$)')
plt.legend()

Out[94]:
<matplotlib.legend.Legend at 0x1105ecf10>

And the Fourier Transform was originally invented by Mr Fourier for, and only for, periodic signals (see Fourier Transform). So the Discrete Fourier Transform does and the Fast Fourier Transform Algorithm does it, too.

The signal has to be strictly periodic, which introduces the so called windowing to eliminate the leakage effect.

## Window Functions to get periodic signals from real data¶

There are a lot of window functions, like the Hamming, Hanning, Blackman, ...

In [95]:
hann = np.hanning(len(s))
hamm = np.hamming(len(s))
black= np.blackman(len(s))

plt.figure(figsize=(8,3))
plt.subplot(131)
plt.plot(hann)
plt.title('Hanning')
plt.subplot(132)
plt.plot(hamm)
plt.title('Hamming')
plt.subplot(133)
plt.plot(black)
plt.title('Blackman')
plt.tight_layout()


All have different characteristics, which is an own engineering discipline. Let's take the Hanning window function to multiply our signal with.

In [96]:
plt.plot(t,hann*s)
plt.xlabel('Time ($s$)')
plt.ylabel('Amplitude ($Unit$)')
plt.title('Signal with Hanning Window function applied')

Out[96]:
<matplotlib.text.Text at 0x1107829d0>

## FFT with windowed signal¶

In [97]:
Yhann = np.fft.fft(hann*s)

plt.figure(figsize=(7,3))
plt.subplot(121)
plt.plot(t,s)
plt.title('Time Domain Signal')
plt.ylim(np.min(s)*3, np.max(s)*3)
plt.xlabel('Time ($s$)')
plt.ylabel('Amplitude ($Unit$)')

plt.subplot(122)
plt.plot(X, 2.0*np.abs(Yhann[:N])/N)
plt.title('Frequency Domain Signal')
plt.xlabel('Frequency ($Hz$)')
plt.ylabel('Amplitude ($Unit$)')

plt.annotate("FFT",
xy=(0.0, 0.1), xycoords='axes fraction',
xytext=(-0.8, 0.2), textcoords='axes fraction',
size=30, va="center", ha="center",
arrowprops=dict(arrowstyle="simple",
plt.tight_layout()

plt.savefig('FFT.png',bbox_inches='tight', dpi=150, transparent=True)


This is exactly, what we wanted to see: A beautiful amplitude spectrum of our signal, which was calcualted with the FFT algorithm.

Now let's take a look at some real data!

# Vertical Grid Load of Germany 2013¶

"The vertical grid load is the sum, positive or negative, of all power transferred from the transmission grid through directly connected transformers and power lines to distribution grids and final consumers."

In [98]:
!wget -O 'Vertikale_Netzlast_2013.csv' 'http://www.50hertz.com/transmission/files/sync/Netzkennzahlen/Netzlast/ArchivCSV/Vertikale_Netzlast_2013.csv'

--2014-04-29 14:21:02--  http://www.50hertz.com/transmission/files/sync/Netzkennzahlen/Netzlast/ArchivCSV/Vertikale_Netzlast_2013.csv
Resolving www.50hertz.com... 95.100.62.102
Connecting to www.50hertz.com|95.100.62.102|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/comma-seperated-values]
Saving to: ‘Vertikale_Netzlast_2013.csv’

[  <=>                                  ] 980,895     3.24MB/s   in 0.3s

2014-04-29 14:21:03 (3.24 MB/s) - ‘Vertikale_Netzlast_2013.csv’ saved [980895]


In [99]:
df = pd.read_csv('Vertikale_Netzlast_2013.csv', header=6, sep=';', parse_dates=[[0, 1]], index_col=0, na_values=['n.v.'])


Interpolate the missing data

In [100]:
df.Load = df.Load.interpolate()

In [101]:
plt.figure(figsize=(14,5))
plt.ylabel('Power [$MW$]')


### Do the FFT¶

In [102]:
hann = np.hanning(len(df.Load.values))

In [103]:
Y = np.fft.fft(hann*df.Load.values)

In [104]:
N = len(Y)/2+1
fa = 1.0/(15.0*60.0) # every 15 minutes
print('fa=%.4fHz (Frequency)' % fa)

fa=0.0011Hz (Frequency)

In [105]:
X = np.linspace(0, fa/2, N, endpoint=True)

In [106]:
plt.plot(X, 2.0*np.abs(Y[:N])/N)
plt.xlabel('Frequency ($Hz$)')
plt.ylabel('vertical powergrid load ($MW$)')

Out[106]:
<matplotlib.text.Text at 0x110734bd0>

Hm. This is not what we expected. For humans, the x-axis is not understandable. What is $0.0002Hz$? Let's convert it to period, which is the reciprocal of the sampling rate.

## The Rythm of modern Life, seen in the Power Grid¶

In [107]:
Xp = 1.0/X # in seconds
Xph= Xp/(60.0*60.0) # in hours

In [108]:
plt.figure(figsize=(15,6))
plt.plot(Xph, 2.0*np.abs(Y[:N])/N)
plt.xticks([12, 24, 33, 84, 168])
plt.xlim(0, 180)
plt.ylim(0, 1500)
plt.xlabel('Period ($h$)')

• 12h day/night rythm
• 24h daily rythm
• 33.6h something? Any suggestions?
• 84.2h something? Any suggestions?
• 168h week rythm