Episode 6: Spectral Analysis via FFT
Turn the last second of a signal into a spectrum with an FFT, twice a second, and watch it in a SpectrumScope.
A spectrum answers which rhythms are in a signal, and how strong each one is. Build the smallest pipeline that shows one live.
A 10 Hz rectangular wave of amplitude 10, with a little noise. A square wave is a sum of sines at the odd multiples of its frequency, so there is more to see than one peak.
7 app = gp.MainApp()
8 p = gp.Pipeline()
9
10 # A rectangular wave carries odd harmonics: 10, 30, 50, 70 Hz ...
11 source = gp.Generator(sampling_rate=250, channel_count=2,
12 signal_frequency=10, signal_amplitude=10,
13 signal_shape="rect", noise_amplitude=1)
gp.FFT(window_size=250, overlap=0.5) looks at the last 250 samples, one second at 250 Hz, so the spectrum’s bins are 1 Hz apart; with an overlap of one half it produces a new spectrum every 125 samples. Before each transform the samples are weighted by a window function: "hamming" spreads each peak a little into its neighbours but keeps it from leaking into bins far away; the default, "boxcar", weighs every sample alike.
15 # One spectrum per 250 samples (bins 1 Hz apart), a new one every 125
16 fft = gp.FFT(window_size=250, overlap=0.5, window_function="hamming")
What comes out is a spectrum, not samples: one frame is one spectrum of 126 bins, 0 to 125 Hz, each value an amplitude in the channel’s own unit. A SpectrumScope draws each one as it arrives, one lane per channel.
17 scope = gp.SpectrumScope(amplitude_limit=20)
18
19 p.connect(source, fft)
20 p.connect(fft, scope)
21 app.add_widget(scope)
Run the script. The 10 Hz peak stands highest, its neighbours at 9 and 11 Hz next to it, then the harmonics at 30, 50 and 70 Hz, each lower than the last: a square wave’s harmonics fall off as 1, 1/3, 1/5, 1/7.
Figure 28: The spectrum of a 10 Hz square wave: the fundamental and its odd harmonics.
In this episode, you learned how to:
turn a signal into spectra with FFT
read
window_sizeas frequency resolution andoverlapas update rateshow spectra in a SpectrumScope
Proceed to Episode 7, where a Delay closes a feedback loop.
Nodes in this episode: Generator, FFT, SpectrumScope
File s2e6_fft.py – View file on GitHub
1"""Season 2, Episode 6: the live spectrum of a 10 Hz rectangular wave."""
2
3import gpype as gp
4
5if __name__ == "__main__":
6
7 app = gp.MainApp()
8 p = gp.Pipeline()
9
10 # A rectangular wave carries odd harmonics: 10, 30, 50, 70 Hz ...
11 source = gp.Generator(sampling_rate=250, channel_count=2,
12 signal_frequency=10, signal_amplitude=10,
13 signal_shape="rect", noise_amplitude=1)
14
15 # One spectrum per 250 samples (bins 1 Hz apart), a new one every 125
16 fft = gp.FFT(window_size=250, overlap=0.5, window_function="hamming")
17 scope = gp.SpectrumScope(amplitude_limit=20)
18
19 p.connect(source, fft)
20 p.connect(fft, scope)
21 app.add_widget(scope)
22
23 p.start()
24 app.run()
25 p.stop()
26 p.close()