| 1 |
|
| 2 |
|
| 3 |
import numpy as np |
| 4 |
import matplotlib.pyplot as plt |
| 5 |
|
| 6 |
import pywt |
| 7 |
import pywt.data |
| 8 |
|
| 9 |
ecg = pywt.data.ecg() |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
coeffs = pywt.swt(ecg, wavelet='sym4', trim_approx=True, norm=True) |
| 17 |
ca = coeffs[0] |
| 18 |
details = coeffs[1:] |
| 19 |
|
| 20 |
print("Variance of the ecg signal = {}".format(np.var(ecg, ddof=1))) |
| 21 |
|
| 22 |
variances = [np.var(c, ddof=1) for c in coeffs] |
| 23 |
detail_variances = variances[1:] |
| 24 |
print("Sum of variance across all SWT coefficients = {}".format( |
| 25 |
np.sum(variances))) |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
ylim = [ecg.min(), ecg.max()] |
| 30 |
|
| 31 |
fig, axes = plt.subplots(len(coeffs) + 1) |
| 32 |
axes[0].set_title("normalized SWT decomposition") |
| 33 |
axes[0].plot(ecg) |
| 34 |
axes[0].set_ylabel('ECG Signal') |
| 35 |
axes[0].set_xlim(0, len(ecg) - 1) |
| 36 |
axes[0].set_ylim(ylim[0], ylim[1]) |
| 37 |
|
| 38 |
for i, x in enumerate(coeffs): |
| 39 |
ax = axes[-i - 1] |
| 40 |
ax.plot(coeffs[i], 'g') |
| 41 |
if i == 0: |
| 42 |
ax.set_ylabel("A%d" % (len(coeffs) - 1)) |
| 43 |
else: |
| 44 |
ax.set_ylabel("D%d" % (len(coeffs) - i)) |
| 45 |
|
| 46 |
ax.set_xlim(0, len(ecg) - 1) |
| 47 |
ax.set_ylim(ylim[0], ylim[1]) |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
level = np.arange(1, len(detail_variances) + 1) |
| 52 |
|
| 53 |
|
| 54 |
plt.figure(figsize=(8, 6)) |
| 55 |
fontdict = dict(fontsize=16, fontweight='bold') |
| 56 |
plt.plot(level, detail_variances[::-1], 'k.') |
| 57 |
plt.xlabel("Decomposition level", fontdict=fontdict) |
| 58 |
plt.ylabel("Variance", fontdict=fontdict) |
| 59 |
plt.title("Variances of detail coefficients", fontdict=fontdict) |
| 60 |
plt.show() |