Spectral analysis with periodograms

We can think of periodic signals as being composed of multiple frequencies. For instance, sound is composed of multiple tones and light is composed of multiple colors. The range of frequencies is called the frequency spectrum. When we analyze the frequency spectrum of a signal, it's natural to take a look at the result of the Fourier Transform of the signal. The periodogram extends this and is equal to the squared magnitude of the Fourier Transform, as follows:

Spectral analysis with periodograms

We will look at the periodograms of the following variables:

  • Rain values from the KNMI De Bilt weather data
  • The second difference (comparable to second derivative in calculus) of the rain values
  • The rolling sum of the rain values using a window of 365 days
  • The rolling mean of the rain values using a window of 365 days

How to do it...

  1. The imports are as follows:
    from scipy import signal
    import matplotlib.pyplot as plt
    import dautil as dl
    import numpy as np
    import pandas as pd
    from IPython.display import HTML
  2. Load the data as follows:
    fs = 365
    rain = dl.data.Weather.load()['RAIN'].dropna()
  3. Define the following function to plot periodograms:
    def plot_periodogram(arr, ax):
        f, Pxx_den = signal.periodogram(arr, fs)
        ax.set_xlabel('Frequency (Hz)')
        ax.set_ylabel('PSD')
        ax.semilogy(f, Pxx_den)
  4. Plot the periodograms with the following code:
    sp = dl.plotting.Subplotter(2, 2, context)
    sp.label()
    plot_periodogram(rain, sp.ax)
    sp.label(advance=True)
    plot_periodogram(np.diff(rain, 2), sp.ax)
    sp.label(advance=True)
    plot_periodogram(pd.rolling_sum(rain, fs).dropna(), sp.ax)
    sp.label(advance=True)
    plot_periodogram(pd.rolling_mean(rain, fs).dropna(), sp.ax)
    HTML(sp.exit())

Refer to the following screenshot for the end result:

How to do it...

The code is from the periodograms.ipynb file in this book's code bundle demonstrates periodograms.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset