Debian Codegraph @

demo/dwt_signal_decomposition.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 import numpy as np
5 import matplotlib.pyplot as plt
6
7 import pywt
8 import pywt.data
9
10
11 ecg = pywt.data.ecg()
12
13 data1 = np.concatenate((np.arange(1, 400),
14 np.arange(398, 600),
15 np.arange(601, 1024)))
16 x = np.linspace(0.082, 2.128, num=1024)[::-1]
17 data2 = np.sin(40 * np.log(x)) * np.sign((np.log(x)))
18
19 mode = pywt.Modes.smooth
20
21
22 def plot_signal_decomp(data, w, title):
23 """Decompose and plot a signal S.
24
25 S = An + Dn + Dn-1 + ... + D1
26 """
27 w = pywt.Wavelet(w)
28 a = data
29 ca = []
30 cd = []
31 for i in range(5):
32 (a, d) = pywt.dwt(a, w, mode)
33 ca.append(a)
34 cd.append(d)
35
36 rec_a = []
37 rec_d = []
38
39 for i, coeff in enumerate(ca):
40 coeff_list = [coeff, None] + [None] * i
41 rec_a.append(pywt.waverec(coeff_list, w))
42
43 for i, coeff in enumerate(cd):
44 coeff_list = [None, coeff] + [None] * i
45 rec_d.append(pywt.waverec(coeff_list, w))
46
47 fig = plt.figure()
48 ax_main = fig.add_subplot(len(rec_a) + 1, 1, 1)
49 ax_main.set_title(title)
50 ax_main.plot(data)
51 ax_main.set_xlim(0, len(data) - 1)
52
53 for i, y in enumerate(rec_a):
54 ax = fig.add_subplot(len(rec_a) + 1, 2, 3 + i * 2)
55 ax.plot(y, 'r')
56 ax.set_xlim(0, len(y) - 1)
57 ax.set_ylabel("A%d" % (i + 1))
58
59 for i, y in enumerate(rec_d):
60 ax = fig.add_subplot(len(rec_d) + 1, 2, 4 + i * 2)
61 ax.plot(y, 'g')
62 ax.set_xlim(0, len(y) - 1)
63 ax.set_ylabel("D%d" % (i + 1))
64
65
66 plot_signal_decomp(data1, 'coif5', "DWT: Signal irregularity")
67 plot_signal_decomp(data2, 'sym5',
68 "DWT: Frequency and phase change - Symmlets5")
69 plot_signal_decomp(ecg, 'sym5', "DWT: Ecg sample - Symmlets5")
70
71
72 plt.show()