# Wavelet transform of a sequence

```import matplotlib.pyplot as plt def mean(x): return sum(x) / len(x) seq = [17, 9, 32, 18, 10, 27, 29, 12, 17, 31, 16, 8, 24, 28, 31, 19] seq_copy = seq[:] detail_coeffs = [] steps = int(len(seq)**0.5) for i in range(steps): averages, detail_coeffs_level = [], [] for i in range(0, len(seq_copy), 2): two_slice = seq_copy[i : i+2] avg = mean(two_slice) averages.append(avg) detail_coeffs_level.append(seq_copy[i] - avg) seq_copy = averages detail_coeffs.append(detail_coeffs_level) transformed = [averages[0]] for el in reversed(detail_coeffs): transformed.extend(el) print(transformed) # [20.5, -1.25, -0.25, -3.75, -6.0, -1.0, 6.0, 0.5, 4.0, 7.0, -8.5, 8.5, -7.0, 4.0, -2.0, 6.0] plt.title('Wavelet transform of a sequence') plt.axhline(0, lw=0.5, ls='--', color='#AAAAAA') plt.plot(range(len(seq)), seq, '-', color='#5EB200', label='original sequence') plt.plot(range(len(transformed)), transformed, '-', color='#DC00FF', label='transformed sequence') plt.xlabel('index') plt.ylabel('coefficient') plt.legend(loc='best', frameon=False) plt.tight_layout() plt.show()```

The wavelet transform managed to decrease the coefficients of the initial sequence, potentially improving compression. By using the means and the detail coefficients at each level, we can go back in reverse and reconstruct the original sequence.

Here is a detailed view how the detail coefficients are determined at each level.

Now we see that the final, transformed sequence is the concatenation of the result at the bottom of the left column (20.5) and the detail coefficients on the right, starting from the bottom-most level (-1.25), moving up through intermediary levels (-0.25, -3.75 and -6, -1, 6, 0.5) and reaching the top one (4, 7, -8.5, 8.5, -7, 4, -2, 6).