|
| 1 | +#!/usr/bin/env python |
| 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 | +# set trim_approx to avoid keeping approximation coefficients for all levels |
| 12 | + |
| 13 | +# set norm=True to rescale the wavelets so that the transform partitions the |
| 14 | +# variance of the input signal among the various coefficient arrays. |
| 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 | +# Create a plot using the same y axis limits for all coefficient arrays to |
| 28 | +# illustrate the preservation of amplitude scale across levels when norm=True. |
| 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 | + # Scale axes |
| 46 | + ax.set_xlim(0, len(ecg) - 1) |
| 47 | + ax.set_ylim(ylim[0], ylim[1]) |
| 48 | + |
| 49 | + |
| 50 | +# reorder from first to last level of coefficients |
| 51 | +level = np.arange(1, len(detail_variances) + 1) |
| 52 | + |
| 53 | +# create a plot of the variance as a function of level |
| 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() |
0 commit comments