forked from AllenDowney/ThinkDSP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvolution.py
More file actions
273 lines (211 loc) · 7.87 KB
/
Copy pathconvolution.py
File metadata and controls
273 lines (211 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""This file contains code used in "Think DSP",
by Allen B. Downey, available from greenteapress.com
Copyright 2014 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import thinkdsp
import thinkplot
import numpy as np
import pandas as pd
import scipy.signal
PI2 = np.pi * 2
def plot_bitcoin():
"""Plot BitCoin prices and a smoothed time series.
"""
nrows = 1625
df = pandas.read_csv('coindesk-bpi-USD-close.csv',
nrows=nrows, parse_dates=[0])
ys = df.Close.values
window = np.ones(30)
window /= sum(window)
smoothed = np.convolve(ys, window, mode='valid')
N = len(window)
smoothed = thinkdsp.shift_right(smoothed, N//2)
thinkplot.plot(ys, color='0.7', label='daily')
thinkplot.plot(smoothed, label='30 day average')
thinkplot.config(xlabel='time (days)',
ylabel='price',
xlim=[0, nrows],
loc='lower right')
thinkplot.save(root='convolution1')
GRAY = "0.7"
def plot_facebook():
"""Plot Facebook prices and a smoothed time series.
"""
names = ['date', 'open', 'high', 'low', 'close', 'volume']
df = pd.read_csv('fb.csv', header=0, names=names, parse_dates=[0])
close = df.close.values[::-1]
dates = df.date.values[::-1]
days = (dates - dates[0]) / np.timedelta64(1,'D')
M = 30
window = np.ones(M)
window /= sum(window)
smoothed = np.convolve(close, window, mode='valid')
smoothed_days = days[M//2: len(smoothed) + M//2]
thinkplot.plot(days, close, color=GRAY, label='daily close')
thinkplot.plot(smoothed_days, smoothed, label='30 day average')
last = days[-1]
thinkplot.config(xlabel='Time (days)',
ylabel='Price ($)',
xlim=[-7, last+7],
legend=True,
loc='lower right')
thinkplot.save(root='convolution1')
def plot_boxcar():
"""Makes a plot showing the effect of convolution with a boxcar window.
"""
# start with a square signal
signal = thinkdsp.SquareSignal(freq=440)
wave = signal.make_wave(duration=1, framerate=44100)
# and a boxcar window
window = np.ones(11)
window /= sum(window)
# select a short segment of the wave
segment = wave.segment(duration=0.01)
# and pad with window out to the length of the array
N = len(segment)
padded = thinkdsp.zero_pad(window, N)
# compute the first element of the smoothed signal
prod = padded * segment.ys
print(sum(prod))
# compute the rest of the smoothed signal
smoothed = np.zeros(N)
rolled = padded
for i in range(N):
smoothed[i] = sum(rolled * segment.ys)
rolled = np.roll(rolled, 1)
# plot the results
segment.plot(color=GRAY)
smooth = thinkdsp.Wave(smoothed, framerate=wave.framerate)
smooth.plot()
thinkplot.config(xlabel='Time(s)', ylim=[-1.05, 1.05])
thinkplot.save(root='convolution2')
# compute the same thing using np.convolve
segment.plot(color=GRAY)
ys = np.convolve(segment.ys, window, mode='valid')
smooth2 = thinkdsp.Wave(ys, framerate=wave.framerate)
smooth2.plot()
thinkplot.config(xlabel='Time(s)', ylim=[-1.05, 1.05])
thinkplot.save(root='convolution3')
# plot the spectrum before and after smoothing
spectrum = wave.make_spectrum()
spectrum.plot(color=GRAY)
ys = np.convolve(wave.ys, window, mode='same')
smooth = thinkdsp.Wave(ys, framerate=wave.framerate)
spectrum2 = smooth.make_spectrum()
spectrum2.plot()
thinkplot.config(xlabel='Frequency (Hz)',
ylabel='Amplitude',
xlim=[0, 22050])
thinkplot.save(root='convolution4')
# plot the ratio of the original and smoothed spectrum
amps = spectrum.amps
amps2 = spectrum2.amps
ratio = amps2 / amps
ratio[amps<560] = 0
thinkplot.plot(ratio)
thinkplot.config(xlabel='Frequency (Hz)',
ylabel='Amplitude ratio',
xlim=[0, 22050])
thinkplot.save(root='convolution5')
# plot the same ratio along with the FFT of the window
padded = thinkdsp.zero_pad(window, len(wave))
dft_window = np.fft.rfft(padded)
thinkplot.plot(abs(dft_window), color=GRAY, label='DFT(window)')
thinkplot.plot(ratio, label='amplitude ratio')
thinkplot.config(xlabel='Frequency (Hz)',
ylabel='Amplitude ratio',
xlim=[0, 22050])
thinkplot.save(root='convolution6')
def plot_gaussian():
"""Makes a plot showing the effect of convolution with a boxcar window.
"""
# start with a square signal
signal = thinkdsp.SquareSignal(freq=440)
wave = signal.make_wave(duration=1, framerate=44100)
spectrum = wave.make_spectrum()
# and a boxcar window
boxcar = np.ones(11)
boxcar /= sum(boxcar)
# and a gaussian window
gaussian = scipy.signal.gaussian(M=11, std=2)
gaussian /= sum(gaussian)
thinkplot.preplot(2)
thinkplot.plot(boxcar, label='boxcar')
thinkplot.plot(gaussian, label='Gaussian')
thinkplot.config(xlabel='Index', legend=True)
thinkplot.save(root='convolution7')
ys = np.convolve(wave.ys, gaussian, mode='same')
smooth = thinkdsp.Wave(ys, framerate=wave.framerate)
spectrum2 = smooth.make_spectrum()
# plot the ratio of the original and smoothed spectrum
amps = spectrum.amps
amps2 = spectrum2.amps
ratio = amps2 / amps
ratio[amps<560] = 0
# plot the same ratio along with the FFT of the window
padded = thinkdsp.zero_pad(gaussian, len(wave))
dft_gaussian = np.fft.rfft(padded)
thinkplot.plot(abs(dft_gaussian), color=GRAY, label='Gaussian filter')
thinkplot.plot(ratio, label='amplitude ratio')
thinkplot.config(xlabel='Frequency (Hz)',
ylabel='Amplitude ratio',
xlim=[0, 22050])
thinkplot.save(root='convolution8')
def fft_convolve(signal, window):
"""Computes convolution using FFT.
"""
fft_signal = np.fft.fft(signal)
fft_window = np.fft.fft(window)
return np.fft.ifft(fft_signal * fft_window)
def fft_autocorr(signal):
"""Computes the autocorrelation function using FFT.
"""
N = len(signal)
signal = thinkdsp.zero_pad(signal, 2*N)
window = np.flipud(signal)
corrs = fft_convolve(signal, window)
corrs = np.roll(corrs, N//2+1)[:N]
return corrs
def plot_fft_convolve():
"""Makes a plot showing that FFT-based convolution works.
"""
names = ['date', 'open', 'high', 'low', 'close', 'volume']
df = pd.read_csv('fb.csv',
header=0, names=names, parse_dates=[0])
close = df.close.values[::-1]
# compute a 30-day average using np.convolve
window = scipy.signal.gaussian(M=30, std=6)
window /= window.sum()
smoothed = np.convolve(close, window, mode='valid')
# compute the same thing using fft_convolve
N = len(close)
padded = thinkdsp.zero_pad(window, N)
M = len(window)
smoothed4 = fft_convolve(close, padded)[M-1:]
# check for the biggest difference
diff = smoothed - smoothed4
print(max(abs(diff)))
# compute autocorrelation using np.correlate
corrs = np.correlate(close, close, mode='same')
corrs2 = fft_autocorr(close)
# check for the biggest difference
diff = corrs - corrs2
print(max(abs(diff)))
# plot the results
lags = np.arange(N) - N//2
thinkplot.plot(lags, corrs, color=GRAY, linewidth=7, label='np.convolve')
thinkplot.plot(lags, corrs2.real, linewidth=2, label='fft_convolve')
thinkplot.config(xlabel='Lag',
ylabel='Correlation',
xlim=[-N//2, N//2])
thinkplot.save(root='convolution9')
def main():
plot_facebook()
plot_boxcar()
plot_gaussian()
plot_fft_convolve()
#plot_bitcoin()
if __name__ == '__main__':
main()