Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 7344
1
"""This file contains code used in "Think DSP",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2013 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
import thinkdsp
11
import thinkplot
12
13
FORMATS = ['pdf', 'png']
14
15
def triangle_example(freq):
16
"""Makes a figure showing a triangle wave.
17
18
freq: frequency in Hz
19
"""
20
framerate = 10000
21
signal = thinkdsp.TriangleSignal(freq)
22
23
duration = signal.period*3
24
segment = signal.make_wave(duration, framerate=framerate)
25
segment.plot()
26
thinkplot.save(root='triangle-%d-1' % freq,
27
xlabel='Time (s)',
28
axis=[0, duration, -1.05, 1.05])
29
30
wave = signal.make_wave(duration=0.5, framerate=framerate)
31
spectrum = wave.make_spectrum()
32
33
thinkplot.preplot(cols=2)
34
spectrum.plot()
35
thinkplot.config(xlabel='Frequency (Hz)',
36
ylabel='Amplitude')
37
38
thinkplot.subplot(2)
39
spectrum.plot()
40
thinkplot.config(ylim=[0, 500],
41
xlabel='Frequency (Hz)')
42
43
thinkplot.save(root='triangle-%d-2' % freq)
44
45
46
def square_example(freq):
47
"""Makes a figure showing a square wave.
48
49
freq: frequency in Hz
50
"""
51
framerate = 10000
52
signal = thinkdsp.SquareSignal(freq)
53
54
duration = signal.period*3
55
segment = signal.make_wave(duration, framerate=framerate)
56
segment.plot()
57
thinkplot.save(root='square-%d-1' % freq,
58
xlabel='Time (s)',
59
axis=[0, duration, -1.05, 1.05])
60
61
wave = signal.make_wave(duration=0.5, framerate=framerate)
62
spectrum = wave.make_spectrum()
63
spectrum.plot()
64
thinkplot.save(root='square-%d-2' % freq,
65
xlabel='Frequency (Hz)',
66
ylabel='Amplitude')
67
68
69
def aliasing_example(offset=0.000003):
70
"""Makes a figure showing the effect of aliasing.
71
"""
72
framerate = 10000
73
74
def plot_segment(freq):
75
signal = thinkdsp.CosSignal(freq)
76
duration = signal.period*4
77
thinkplot.Hlines(0, 0, duration, color='gray')
78
segment = signal.make_wave(duration, framerate=framerate*10)
79
segment.plot(linewidth=0.5, color='gray')
80
segment = signal.make_wave(duration, framerate=framerate)
81
segment.plot_vlines(label=freq, linewidth=4)
82
83
thinkplot.preplot(rows=2)
84
plot_segment(4500)
85
thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])
86
87
thinkplot.subplot(2)
88
plot_segment(5500)
89
thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])
90
91
thinkplot.save(root='aliasing1',
92
xlabel='Time (s)',
93
formats=FORMATS)
94
95
96
def main():
97
triangle_example(freq=200)
98
triangle_example(freq=1100)
99
square_example(freq=100)
100
aliasing_example()
101
102
103
if __name__ == '__main__':
104
main()
105
106