Debian Codegraph @

demo/dwt_swt_show_coeffs.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.sp1DWT = 1
20
21
22 def plot_coeffs(data, w, title, use_dwt=True):
23 """Show dwt or swt coefficients for given data and wavelet."""
24 w = pywt.Wavelet(w)
25 a = data
26 ca = []
27 cd = []
28
29 if use_dwt:
30 for i in range(5):
31 (a, d) = pywt.dwt(a, w, mode)
32 ca.append(a)
33 cd.append(d)
34 else:
35 coeffs = pywt.swt(data, w, 5) # [(cA5, cD5), ..., (cA1, cD1)]
36 for a, d in reversed(coeffs):
37 ca.append(a)
38 cd.append(d)
39
40 fig = plt.figure()
41 ax_main = fig.add_subplot(len(ca) + 1, 1, 1)
42 ax_main.set_title(title)
43 ax_main.plot(data)
44 ax_main.set_xlim(0, len(data) - 1)
45
46 for i, x in enumerate(ca):
47 ax = fig.add_subplot(len(ca) + 1, 2, 3 + i * 2)
48 ax.plot(x, 'r')
49 ax.set_ylabel("A%d" % (i + 1))
50 if use_dwt:
51 ax.set_xlim(0, len(x) - 1)
52 else:
53 ax.set_xlim(w.dec_len * i, len(x) - 1 - w.dec_len * i)
54
55 for i, x in enumerate(cd):
56 ax = fig.add_subplot(len(cd) + 1, 2, 4 + i * 2)
57 ax.plot(x, 'g')
58 ax.set_ylabel("D%d" % (i + 1))
59 # Scale axes
60 ax.set_xlim(0, len(x) - 1)
61 if use_dwt:
62 ax.set_ylim(min(0, 1.4 * min(x)), max(0, 1.4 * max(x)))
63 else:
64 vals = x[w.dec_len * (1 + i):len(x) - w.dec_len * (1 + i)]
65 ax.set_ylim(min(0, 2 * min(vals)), max(0, 2 * max(vals)))
66
67
68 # Show DWT coefficients
69 use_dwt = True
70 plot_coeffs(data1, 'db1',
71 "DWT: Signal irregularity shown in D1 - Haar wavelet",
72 use_dwt)
73 plot_coeffs(data2, 'sym5', "DWT: Frequency and phase change - Symmlets5",
74 use_dwt)
75 plot_coeffs(ecg, 'sym5', "DWT: Ecg sample - Symmlets5", use_dwt)
76
77 # Show DWT coefficients
78 use_dwt = False
79 plot_coeffs(data1, 'db1', "SWT: Signal irregularity detection - Haar wavelet",
80 use_dwt)
81 plot_coeffs(data2, 'sym5', "SWT: Frequency and phase change - Symmlets5",
82 use_dwt)
83 plot_coeffs(ecg, 'sym5', "SWT: Ecg sample - simple QRS detection - Symmlets5",
84 use_dwt)
85
86
87 plt.show()