Fourier analysis is a method for expressing a function as a sum of periodic
components, and for recovering the signal from those components. When both
the function and its Fourier transform are replaced with discretized
counterparts, it is called the discrete Fourier transform (DFT). The DFT has
become a mainstay of numerical computing in part because of a very fast
algorithm for computing it, called the Fast Fourier Transform (FFT), which was
known to Gauss (1805) and was brought to light in its current form by Cooley
and Tukey 1. Press et al. provide an accessible introduction to
Fourier analysis and its applications.
This chapter is structured as follows: The first section defines the discrete Fourier
transform and presents its key properties. The second section discusses the
relationship to continuous Fourier series and introduces various forms of its Fourier
transform. Then practical implications, which mainly results from the DFT’s periodicity
properties, are discussed in the Caveats section. The remaining
sections give definitions of higher-dimensional DFTs, discrete sine and cosine
transforms as well as the Hankel transform.
The Discrete Fourier Transform
The discrete Fourier Transform [3] is a one-to-one mapping between two
complex-valued sequences of length N. The mappings between x[k],X[l]∈\IC, with k,l∈{0,…,N−1}, are defined by
which are implemented by the fft / ifft
functions. γ is a normalization constant, which is set by the norm
parameter. It may have the values 1 (norm='backward', default),
N (norm='forward'), or ().
Note that X[l] can be continued periodically outside its domain {0,…,N−1}. I.e., X[l+pN]=X[l] for when is
calculated with Eq. . This allows to define the DFT over
shifted coefficients, e.g., using . The same
holds for : When determined with Eq. , , is true.
This DFT can be rewritten in vector-matrix form as
with \conjT\mF being the conjugate transpose of \mF. It can be shown
that \conjT\mF\mF=N\mI holds and thus \mF−1=\conjT\mF/N,
which makes it straightforward to verify that the two relations of Eq.
are inverses of each other. The module
provides the function to calculate the matrix :
>>> importnumpyasnp>>> fromscipy.linalgimportdft>>> fromscipy.fftimportfft>>> np.set_printoptions(precision=2,suppress=True)# for compact output...>>> dft
This notation makes it also easy to show that the DFT changes the inner product (or
scalar product) only by the scaling factor N/γ2. I.e., expressing the
inner product of \vbX and \vbY in terms of \vbx and
gives
Here, the circular convolution is defined over finite length sequences, whereas in
literature it is often defined over infinite length sequences. For sufficiently large
N (roughly: N>500), it is typically computationally more efficient to
use this multiplication together with the fft /
ifft functions than to calculate the convolution directly. Note that
convolve, and
implement the non-circular convolution by using appropriate
zero-padding before applying the FFT.
Fourier Series and the DFT
A Fourier series
(3)\[z(t)=Nγl=−N2∑N2cl\e\jj2πlt/τ,t∈[0,τ],
with N=2N2+1 complex-valued Fourier coefficients cl represents a
closed curve z:[0,τ]↦\IC. Determining the values of
equidistant samples with sampling interval , i.e.,
may be interpreted as a shifted version the inverse DFT of Eq.
(1). Since the (inverse) DFT is a one-to-one mapping, the
N samples are an alternative representation of the N Fourier
coefficients. Here, the scaling factor γ/N exists only to ensure
notational consistency with Eq. (1).
The following example produces a closed curve z(t) resembling the letter ω by
utilizing a Fourier series: The Fourier coefficients are calculated by the
fft function from 31 provided samples. In the plot, the dots
represent the samples z[k] and the coloration of the line the value of the
parameter t∈[0,1]. Since the function expects indexes
but is defined on the indexes
, the function is utilized.
That the plot is a closed curve is due to the periodic nature of Fourier series,
i.e., z(t+pτ)=z(t),p∈\IZ. As a consequence, a given closed curve
can be represented by various Fourier series and with that by various sets of
samples. E.g., increasing the number of samples can be achieved by adding zero-valued
Fourier coefficients to their DFT and then calculating the corresponding inverse DFT.
This technique is used in the function.
Besides the DFT, other variations for calculating a Fourier transform of a Fourier
series exist. The important case of extending the domain from the fixed interval
[0,τ] to the real axis \IR is discussed in the following: When
assuming z(t)≡0 holds for t∈[0,τ], it is
straightforward to apply the continuous Fourier transform to the Fourier Series of Eq.
:
with \sinc(f):=sin(πf)/(πf). Note that Z(f) is continuous
and its support extends over the complete real axis. The DFT may be interpreted as
sampling the continuous Fourier transform due to
Z(lΔf)=τNγcl=Tγcl for l∈\IZ
being true. When continuing z(t) periodically outside the interval [0,τ], i.e.,
zp(t)=p∈\IZ∑z(t+pτ),
then the continuous Fourier transform can be expressed as
Zp(f)=Nγl=−N2∑N2clδ(f−lΔf),Δf=1/τ=1/(NT),
where δ(.) denotes the Dirac delta function. Note that Zp(f) is
only non-zero at multiples of Δf. Furthermore, Zp(f) is
bandlimited, i.e., for .
In signal processing, is usually referred to as sampling frequency
and is called the Nyquist frequency.
The so-called “discrete-time Fourier transform” (DTFT) [4] of the sampled
signal zp[k]:=zp(kT) is defined as
ZpDTFT(f):=k∈\IZ∑zp[k]\e−2\jjπfkT or ZpDTFT(\jjΩ):=k∈\IZ∑zp[k]\e−\jjkΩ,
with Ω:=2πf/fS=2πfT. The convention of using the normalized
frequency Ω instead of f is common in signal processing.
is a continuous function in with a periodicity of
. Due to being periodic in , it can be expressed in
terms of the Fourier coefficients as
Hence, the DTFT may be interpreted as a periodic continuation of Zp(f), i.e.,
as the periodic continuation in f of the Fourier transform of the
continuous-time periodic signal.
A brief introduction about analyzing the spectral properties of sampled signals can be
found in the Spectral Analysis section.
Caveats
This subsection briefly discusses practical implications of the periodicity properties
of Fourier transforms and provides recommendations for improving computational
efficiency.
Periodicity in the Time Domain
When working with sampled signals, it is typically assumed that the underlying
continuous signals are represented by Fourier series. The circumstance that to
accurately model signals with discontinuities requires many Fourier coefficients is
known as Gibbs phenomenon. Since Fourier series are inherently periodic, representing
non-periodic signals introduces artificial discontinuities. A common technique to make
non-periodic signals “more” periodic is subtracting a best-fit polynomial.
detrend can be used to subtract a signal’s mean (0th
order polynomial) or linear trend (1st order polynomial). NumPy’s
Polynomial class provides means to
fit higher order polynomials.
The following example illustrates the effect of removing the linear trend from a noisy
signal on its spectrum: The signal x(t) is represented by N=1000
samples with a sampling interval of T=0.1ms. The first row depicts
x(t) (with linear trend) and (with removed linear trend). To
determine the periodic components, a magnitude spectrum of and of
is calculated and drawn is second and third row.
importmatplotlib.pyplotaspltimportnumpyasnpfromscipy.fftimportrfft,rfftfreqfromscipy.signalimportdetrendrng=np.random.default_rng()# seeding with default seed for reproducibilityN,tau
The signal’s trend manifests as a decreasing slope in the spectrum’s low-frequency part.
Removing the linear trend steepens this slope significantly, making the peaks at
100, 200, and 300Hz much better distinguishable. These peaks, which
correspond to the sinusoidal components of x(t), would have a magnitude of
0.5 in a noise- and trend-free signal.
Note that detrending a signal does not necessarily improve its spectrum. I.e., periodic
components whose frequencies are not integer multiples of the frequency resolution
Δf produce a trend that should not be removed. More information on
calculating and interpreting spectra can be found in the
Spectral Analysis section.
Periodicity in the Frequency Domain
The following plot compares fft and rfft
representations of two signals made up of an odd number (N=5, left column) and
an even number of samples (N=4, right column). The real-valued input signals
were chosen in such a way so that their Fourier transforms are real-valued, i.e.,
. The first row shows the DFTs of Eq. with
its non-negative frequencies. The gray stems represent the periodic continuation to the
left and to the right. The center row shows the with the shifted
frequencies produced by , where the two highest frequencies
are shifted to the negative side. The last row depicts the one-sided
, which only produces only the non-negative frequencies of the
(two-sided) .
Speed Considerations
The efficiency of the FFT algorithm depends on how well the number of input samples
N can be factored into small prime factors. I.e., it is slowest if N is
prime and fastest if N is a power of 2. The fft module provides
the functions prev_fast_len and next_fast_len for
determining adequate input lengths for fast execution.
Furthermore, the fft module provides also the context manager
to set the maximum number of allowed threads when
calculating the FFT. Note that some third-party FFT libraries provide SciPy backends,
which can be activated by utilizing .
2- and N-D discrete Fourier transforms
The functions fft2 and ifft2 provide 2-D FFT and
IFFT, respectively. Similarly, fftn and ifftn provide
N-D FFT, and IFFT, respectively.
For real-input signals, similarly to rfft, we have the functions
rfft2 and irfft2 for 2-D real transforms;
rfftn and irfftn for N-D real transforms.
The example below demonstrates a 2-D IFFT and plots the resulting
(2-D) time-domain signals.
SciPy provides a DCT with the function dct and a corresponding IDCT
with the function idct. There are 8 types of the DCT [5][6];
however, only the first 4 types are implemented in SciPy. “The” DCT generally
refers to DCT type 2, and “the” Inverse DCT generally refers to DCT type 3. In
addition, the DCT coefficients can be normalized differently (for most types,
scipy provides None and ortho). Two parameters of the dct/idct
function calls allow setting the DCT type and coefficient normalization.
For a single dimension array x, dct(x,norm='ortho') is equal to
MATLAB’s “dct(x)”.
Type I DCT
SciPy uses the following definition of the unnormalized DCT-I
(norm=None):
y[k] = x_0 + (-1)^k x_{N-1} + 2\sum_{n=1}^{N-2} x[n]
\cos\left(\frac{\pi nk}{N-1}\right),
\qquad 0 \le k < N.
Note that the DCT-I is only supported for input size > 1.
Type II DCT
SciPy uses the following definition of the unnormalized DCT-II
(norm=None):
y[k] = 2 \sum_{n=0}^{N-1} x[n] \cos \left({\pi(2n+1)k \over 2N} \right)
\qquad 0 \le k < N.
In case of the normalized DCT (norm='ortho'), the DCT coefficients
y[k] are multiplied by a scaling factor f:
SciPy uses the following definition of the unnormalized DCT-III
(norm=None):
y[k] = x_0 + 2 \sum_{n=1}^{N-1} x[n] \cos\left({\pi n(2k+1) \over 2N}\right)
\qquad 0 \le k < N,
or, for norm='ortho':
y[k] = {x_0\over\sqrt{N}} + {2\over\sqrt{N}} \sum_{n=1}^{N-1} x[n]
\cos\left({\pi n(2k+1) \over 2N}\right) \qquad 0 \le k < N.
Type IV DCT
SciPy uses the following definition of the unnormalized DCT-IV
(norm=None):
y[k] = 2 \sum_{n=0}^{N-1} x[n] \cos\left({\pi (2n+1)(2k+1) \over 4N}\right)
\qquad 0 \le k < N,
or, for norm='ortho':
y[k] = \sqrt{2\over N}\sum_{n=0}^{N-1} x[n] \cos\left({\pi (2n+1)(2k+1) \over 4N}\right)
\qquad 0 \le k < N
DCT and IDCT
The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up to a
factor of 2N. The orthonormalized DCT-III is exactly the inverse of the
orthonormalized DCT- II. The function idct performs the mappings between
the DCT and IDCT types, as well as the correct normalization.
The following example shows the relation between DCT and IDCT for different
types and normalizations.
The DCT exhibits the “energy compaction property”, meaning that for many
signals only the first few DCT coefficients have significant magnitude.
Zeroing out the other coefficients leads to a small reconstruction error, a
fact which is exploited in lossy signal compression (e.g. JPEG compression).
The example below shows a signal x and two reconstructions (x_{20} and
x_{15}) from the signal’s DCT coefficients. The signal x_{20}
is reconstructed from the first 20 DCT coefficients, x_{15} is
reconstructed from the first 15 DCT coefficients. It can be seen that the
relative error of using 20 coefficients is still very small (~0.1%), but
provides a five-fold compression rate.
SciPy provides a DST [6] with the function dst and a corresponding IDST
with the function idst.
There are, theoretically, 8 types of the DST for different combinations of
even/odd boundary conditions and boundary offsets [7], only the first 4
types are implemented in SciPy.
Type I DST
DST-I assumes the input is odd around n=-1 and n=N. SciPy uses the following
definition of the unnormalized DST-I (norm=None):
y[k] = 2\sum_{n=0}^{N-1} x[n] \sin\left( \pi {(n+1) (k+1)}\over{N+1}
\right), \qquad 0 \le k < N.
Note also that the DST-I is only supported for input size > 1. The
(unnormalized) DST-I is its own inverse, up to a factor of 2(N+1).
Type II DST
DST-II assumes the input is odd around n=-1/2 and even around n=N. SciPy uses
the following definition of the unnormalized DST-II (norm=None):
y[k] = 2 \sum_{n=0}^{N-1} x[n] \sin\left( {\pi (n+1/2)(k+1)} \over N
\right), \qquad 0 \le k < N.
Type III DST
DST-III assumes the input is odd around n=-1 and even around n=N-1. SciPy uses
the following definition of the unnormalized DST-III (norm=None):
y[k] = (-1)^k x[N-1] + 2 \sum_{n=0}^{N-2} x[n] \sin \left( {\pi
(n+1)(k+1/2)} \over N \right), \qquad 0 \le k < N.
Type IV DST
SciPy uses the following definition of the unnormalized DST-IV
(norm=None):
y[k] = 2 \sum_{n=0}^{N-1} x[n] \sin\left({\pi (2n+1)(2k+1) \over 4N}\right)
\qquad 0 \le k < N,
or, for norm='ortho':
y[k] = \sqrt{2\over N}\sum_{n=0}^{N-1} x[n] \sin\left({\pi (2n+1)(2k+1) \over 4N}\right)
\qquad 0 \le k < N,
DST and IDST
The following example shows the relation between DST and IDST for
different types and normalizations.
which is a convolution in logarithmic space. The FHT algorithm uses the FFT
to perform this convolution on discrete input data.
Care must be taken to minimise numerical ringing due to the circular nature
of FFT convolution. To ensure that the low-ringing condition [8] holds,
the output array can be slightly shifted by an offset computed using the
fhtoffset function.
A Fourier series is a decomposition of a complex-valued closed curve into circular
closed curves with various frequencies: The l-th term zl(t):=Nγclexp(\jj2πlt/τ) may be interpreted as a circular
curve centered at the origin with radius ∣γcl/N∣ and starting point
zl(0)=γcl/N. For t∈[0,τ], it cycles the circle
l times in counterclockwise direction if l>0 or clockwise direction
if l<0. The number of cycles per unit interval, i.e, fl:=l/τ, is usually called the frequency of zl(t) (having the same sign as
l). The fftfreq function determines those corresponding
frequencies for the Fourier coefficients.
Especially in signal processing, t frequently represents time. Hence, the
sample values z[k] with their associated sample times t[k]=kT are
commonly referred to as being in the so-called “time-domain”, whereas coefficients
cl with their associated frequency values fl=lΔf with
Δf:=1/τ=1/(NT), are referred as to being in the so-called
“frequency domain” or “Fourier domain”.
If only real-valued curves are of interest, then
ℑ{z(t)}=(z(t)−\conjz(t))/2\jj≡0 holds. This is
equivalent to z(t)=\conjz(t) as well as to cl=\conjc−l.
As a consequence, for DFTs with real-valued inputs only the non-negative DFT
coefficients need to be calculated. This is implemented by the
rfft / irfft / rfftfreq
functions.
importmatplotlib.pyplotaspltimportnumpyasnpfromscipy.fftimportfft,fftfreq,irfft,rfft,rfftfreq# Create signals:x0=np.array([4,1,0,1])x1=irfft(rfft(x0),n=5)# Here: rfft(x1) == rfft(x0)tau=1# signal duration in secondsll=np.arange(-3,6)# indices of DFT coefficients_,ax01=plt.subplots(3,2,sharex='col',tight_layout=True,figsize=(6.,4.))forx,axxinzip((x1,x0),ax01.T):N=len(x)# number of samplesT,delta_f=tau/N,1/tau# sampling interval and frequency resolutionkk=np.arange(0,N)# sample indices of DFTX_DFT=np.array([sum(x*np.exp(-2j*np.pi*l_*kk/N))forl_inll])f_DFT=ll*delta_f# frequencies of DFTXX=fft(x),fft(x),rfft(x)# DFT values and FFT values coincideff=np.arange(N)*delta_f,fftfreq(N,T),rfftfreq(N,T)t_strs=["DFT","fft / fftfreq","rfft / rfftfreq"]# do the plotting:forp,(ax,f,X,ts)inenumerate(zip(axx,ff,XX,t_strs)):lns=axx[p].stem(f_DFT,abs(X_DFT),linefmt='k-',markerfmt="k.",basefmt=' ')[ln_.set_alpha(0.1)forln_inlns]# set transparencyaxx[p].stem(f,abs(X),linefmt=f'C{p}-',markerfmt=f'C{p}.',basefmt=' ')ax.set(title=f"{ts} for len(x) = {N}",yticks=[],ylim=(0,6.5))axx[-1].set(xticks=f_DFT,xlim=(f_DFT[0]-0.5,f_DFT[-1]+0.5))axx[-1].set_xlabel(rf"Frequency $f$ in hertz ($\Delta f ={delta_f:g}\,$Hz)")plt.show()
This plot illustrates the following two aspects:
For an odd number of samples (here: N=5), fftfreq produces
an equal number of positive and negative frequencies, i.e. [-2,-1,0,1,2]. For
an even number of samples (here: N=4), it would be valid to have either the
frequencies, [-2,-1,0,1] or the frequencies [-1,0,1,2] due to the FFT
values at f = \pm2\,Hz being identical. By convention,
fftfreq places the Nyquist frequency
f_\text{Ny} = \Delta f\, N/2 = 2\,Hz on the negative side.
Here, the rfft values for input lengths of N=4,5 are equal
in spite of the input signals being different. This illustrates that the number
of signal samples N need to be passed to irfft to be able
reconstruct the original signal, e.g.: