FFT Helper Routines

Discrete Fourier Transforms in standard computational packages like Mathematica, MATLAB, and python/numpy can be a little tricky to work with because the output of the functions like Fourier[data] in Mathematica 
The following set of FFT helper routines make Discrete Fourier Transforms more user friendly:

1. fft[list] function where the normalization agrees with MATLAB and Python.
2. fftfreq[n,d]  function which generates a frequency array for a length n Fourier Transform and the d is the sample rate of the data.
3. fftshift[list] function which reorders the array to go from negative frequencies to positive frequencies.
4. fftshift2D[list] function which reorder a 2D FFT array so that zero frequency is centered in the middle of the array, rather than a corner.

Defining a simple fft function that works like MATLAB and Python.

The default Mathematica Fast Fourier Transform is accomplished using the Fourier[] function.  However, in order to get Mathematica to agree with MATLAB and Python on the exact definition of the Discrete Fourier Transform you must set the Fourier Parameters option.


Quoted from the Mathematica Help document on “Fourier”:

With the setting FourierParameters->{a,b} the discrete Fourier transform computed by Fourier is

({{({{(1/(n^((1-a)/2)))(∑_(r=1)^n)(Subscript[u, r])(e^(2π i b(r-1)(s-1)/n)).}})}})

Some common choices for {a,b} are {0,1} (default), {-1,1} (data analysis), {1,-1} (signal processing).

As the help file indicates, {a,b}-> {1,-1}   is the choice which agrees with Python (and presumably MATLAB as well).

fft[list_] := Fourier[list, FourierParameters->{1,-1}];

Defining fftfreq (make a frequency array)

The following function is based upon the numpy python equivalent function.  Documentation can be found at http : // docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftfreq.html.

In the function, the two input parameters are
n = length of the fft.
d = sample rate of the time series.

fftfreq[n_,d_:1] := Which[
EvenQ[n],
Join[Range[0,n/2-1], Range[-n/2,-1]]/(d n),
OddQ[n],
Join[Range[0,(n-1)/2],Range[-(n-1)/2,-1]]/(d n)
]

Defining fftshift (centers the frequency array at zero)

The default is to position zero frequency at the start of the array, meaning the negative frequencies occur after the positive ones.  A simple function to shift the array so that zero frequency is in the middle of the array is a helpful utility.

fftshift[list_]:= Module[{n},
n = Length[list];
Which[
EvenQ[n],
RotateRight[list,n/2],
OddQ[n],
RotateRight[list,(n-1)/2]
]
]

Define fftshift2D (centers a 2D fft at (0,0))

This function shifts the zero frequency components to the middle of the FFT array.  It is the 2D version of fftshift.

fftshift2D[list_]:= Module[{m,n,temp},
{m,n}=Dimensions[list];
Which[
EvenQ[n],
temp = RotateRight[list,{0,n/2}],
OddQ[n],
temp = RotateRight[list,{0,(n-1)/2}]
];
Which[
EvenQ[m],
temp =RotateRight[temp,{m/2,0}],
OddQ[m],
temp =RotateRight[temp,{(m-1)/2,0}]
];
temp
]