📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This file contains code used in "Think DSP",1by Allen B. Downey, available from greenteapress.com23Copyright 2013 Allen B. Downey4License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html5"""67from __future__ import print_function, division89import thinkdsp10import thinkplot1112FORMATS = ['pdf', 'png']1314def triangle_example(freq):15"""Makes a figure showing a triangle wave.1617freq: frequency in Hz18"""19framerate = 1000020signal = thinkdsp.TriangleSignal(freq)2122duration = signal.period*323segment = signal.make_wave(duration, framerate=framerate)24segment.plot()25thinkplot.save(root='triangle-%d-1' % freq,26xlabel='Time (s)',27axis=[0, duration, -1.05, 1.05])2829wave = signal.make_wave(duration=0.5, framerate=framerate)30spectrum = wave.make_spectrum()3132thinkplot.preplot(cols=2)33spectrum.plot()34thinkplot.config(xlabel='Frequency (Hz)',35ylabel='Amplitude')3637thinkplot.subplot(2)38spectrum.plot()39thinkplot.config(ylim=[0, 500],40xlabel='Frequency (Hz)')4142thinkplot.save(root='triangle-%d-2' % freq)434445def square_example(freq):46"""Makes a figure showing a square wave.4748freq: frequency in Hz49"""50framerate = 1000051signal = thinkdsp.SquareSignal(freq)5253duration = signal.period*354segment = signal.make_wave(duration, framerate=framerate)55segment.plot()56thinkplot.save(root='square-%d-1' % freq,57xlabel='Time (s)',58axis=[0, duration, -1.05, 1.05])5960wave = signal.make_wave(duration=0.5, framerate=framerate)61spectrum = wave.make_spectrum()62spectrum.plot()63thinkplot.save(root='square-%d-2' % freq,64xlabel='Frequency (Hz)',65ylabel='Amplitude')666768def aliasing_example(offset=0.000003):69"""Makes a figure showing the effect of aliasing.70"""71framerate = 100007273def plot_segment(freq):74signal = thinkdsp.CosSignal(freq)75duration = signal.period*476thinkplot.Hlines(0, 0, duration, color='gray')77segment = signal.make_wave(duration, framerate=framerate*10)78segment.plot(linewidth=0.5, color='gray')79segment = signal.make_wave(duration, framerate=framerate)80segment.plot_vlines(label=freq, linewidth=4)8182thinkplot.preplot(rows=2)83plot_segment(4500)84thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])8586thinkplot.subplot(2)87plot_segment(5500)88thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])8990thinkplot.save(root='aliasing1',91xlabel='Time (s)',92formats=FORMATS)939495def main():96triangle_example(freq=200)97triangle_example(freq=1100)98square_example(freq=100)99aliasing_example()100101102if __name__ == '__main__':103main()104105106