Exercise: the Haar transform

Goal

By the end of this exercise you should be able to:

  • explain why a spike or a step is spread over all Fourier coefficients, and what a window trades off,
  • compute a full Haar transform of 8 samples by hand, and invert it,
  • check that the normalised Haar matrix is orthogonal, and use it to compute the error of keeping only some coefficients,
  • predict which signals are sparse in the Haar basis.

Do the pen-and-paper part first, then the two demos. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Idea What it means
Haar step (by hand) pair (a, b) → average s = (a+b)/2 and half-difference d = (a-b)/2
Inverse step a = s + d, b = s - d
Full transform of N = 2^J samples repeat on the averages J times; result (s \mid d_J \mid \dots \mid d_1), coarse to fine
Orthonormal version s = (a+b)/\sqrt2, d = (a-b)/\sqrt2: energy \sum x^2 = \sum c^2 (Parseval)
Keeping K coefficients in an orthonormal basis: squared error = sum of the dropped squared coefficients
Sparse few large coefficients, the rest zero or nearly zero

By hand

B1. Compute the full Haar transform (averages and half-differences) of x = (6, 2, 5, 7, 9, 9, 4, 0), level by level. Write the result as (s \mid d_3 \mid d_2, d_2 \mid d_1, d_1, d_1, d_1). Then invert it and check that you get x back.

B2. The board example x = (4, 6, 10, 12, 8, 6, 5, 5) has the orthonormal Haar coefficients (19.80 \mid 2.83 \mid -6,\ 2 \mid -1.41,\ -1.41,\ 1.41,\ 0). (a) Check that \sum c^2 = \sum x^2. (b) Keep only the 3 largest coefficients (in magnitude) and set the rest to 0. What is the squared error \sum (x - \hat x)^2, without reconstructing anything? (c) Reconstruct \hat x and check (b). (d) In the by-hand version the coefficients are (7 \mid 1 \mid -3, 1 \mid -1, -1, 1, 0). Why is “keep the largest” not a good rule there?

B3. Write down the orthonormal Haar matrices for N = 2 and N = 4 (rows = basis vectors, coarse to fine). Check that every row has length 1 and that any two rows are perpendicular.

B4. A spike at position 5 of 8: x = (0, 0, 0, 0, 8, 0, 0, 0). Compute its Haar transform. How many coefficients are nonzero? How many would a spike have in a signal of 1024 samples? And in the Fourier basis?

B5. Two steps: x = (2, 2, 2, 10, 10, 10, 10, 10) and y = (2, 2, 2, 2, 10, 10, 10, 10). Compute both Haar transforms. Which has fewer nonzero coefficients, and why?

B6. The ramp x = (1, 2, 3, 4, 5, 6, 7, 8). Compute its Haar transform. Which details are zero? What does this tell you about the Haar basis?

B7. The 8-point DFT X_k = \sum_n x_n e^{-2\pi i k n/8} of a spike at position 0, x = (1, 0, 0, 0, 0, 0, 0, 0), and of a spike at position 3. What are |X_k| in both cases? Where is the position of the spike stored?

B8. A signal sampled at 1000 samples per second contains a slow wave of 4 Hz and, at one moment, a sharp step. You analyse it with a short-time Fourier transform. (a) With a window of 50 ms, how many cycles of the slow wave fit in one window? Can you tell its frequency? (b) With a window of 2 s, over how many samples is the step smeared? (c) What would a wavelet analysis do differently?

B1.

level averages differences
1 (6+2)/2 = 4, 6, 9, 2 (6-2)/2 = 2, -1, 0, 2
2 5, 5.5 -1, 3.5
3 5.25 -0.25

Result: (5.25 \mid -0.25 \mid -1,\ 3.5 \mid 2,\ -1,\ 0,\ 2). Inverse: 5.25 \pm (-0.25) = (5, 5.5); 5 \pm (-1) = (4, 6), 5.5 \pm 3.5 = (9, 2); 4 \pm 2 = (6, 2), 6 \pm (-1) = (5, 7), 9 \pm 0 = (9, 9), 2 \pm 2 = (4, 0). Back to x.

B2. (a) \sum x^2 = 16 + 36 + 100 + 144 + 64 + 36 + 25 + 25 = 446; \sum c^2 = 392 + 8 + 36 + 4 + 2 + 2 + 2 + 0 = 446. (b) Keep 19.80, -6 and 2.83; drop 2, -1.41, -1.41, 1.41 and 0: error 4 + 2 + 2 + 2 + 0 = 10. (c) Inverting (7 \mid 1 \mid -3, 0 \mid 0, 0, 0, 0) (the same kept coefficients in the by-hand scaling): 7 \pm 1 = (8, 6); 8 \pm (-3) = (5, 11), 6 \pm 0 = (6, 6); level 1 has no details: \hat x = (5, 5, 11, 11, 6, 6, 6, 6). Error: 1 + 1 + 1 + 1 + 4 + 0 + 1 + 1 = 10. ✓ (d) With the 1/2 scaling, coefficients at different levels are not comparable: a level-3 coefficient changes all 8 samples, a level-1 coefficient only 2. The level-2 detail 1 and the level-1 details \pm 1 look equally large, but dropping the level-2 one costs 2^2 = 4 in squared error and a level-1 one only 2. In the orthonormal scaling the size of a coefficient is exactly its contribution to the energy.

B3. N = 2: \frac{1}{\sqrt2}\begin{pmatrix}1 & 1\\ 1 & -1\end{pmatrix}. N = 4: \begin{pmatrix} \tfrac12 & \tfrac12 & \tfrac12 & \tfrac12 \\ \tfrac12 & \tfrac12 & -\tfrac12 & -\tfrac12 \\ \tfrac1{\sqrt2} & -\tfrac1{\sqrt2} & 0 & 0 \\ 0 & 0 & \tfrac1{\sqrt2} & -\tfrac1{\sqrt2}\end{pmatrix}. Lengths: 4 \cdot \tfrac14 = 1 and 2 \cdot \tfrac12 = 1. Dot products: rows 1 and 2: \tfrac14 + \tfrac14 - \tfrac14 - \tfrac14 = 0; rows 1 and 3: \tfrac{1}{2\sqrt2} - \tfrac{1}{2\sqrt2} = 0; rows 3 and 4 do not overlap: 0; and so on.

B4. Level 1: averages (0, 0, 4, 0), differences (0, 0, 4, 0). Level 2: (0, 2), (0, 2). Level 3: 1, -1. Result (1 \mid -1 \mid 0, 2 \mid 0, 0, 4, 0): 4 nonzero coefficients, one per level plus the average, \log_2 8 + 1. For 1024 samples: \log_2 1024 + 1 = 11. In the Fourier basis all 1024 coefficients are nonzero (|X_k| = 8 for every k).

B5. x: level 1 (2, 6, 10, 10) / (0, -4, 0, 0); level 2 (4, 10) / (-2, 0); level 3 7 / -3: (7 \mid -3 \mid -2, 0 \mid 0, -4, 0, 0), 4 nonzero. y: level 1 (2, 2, 10, 10) / (0, 0, 0, 0); level 2 (2, 10) / (0, 0); level 3 6 / -4: (6 \mid -4 \mid 0, 0 \mid 0, 0, 0, 0), only 2 nonzero. In y the jump falls exactly on the border between the two halves, so every shorter pattern sees a flat piece; in x the jump falls inside a pair and inside a quarter, so one pattern per level sees it. (The Haar transform depends on where a jump sits relative to the grid: unit 3 comes back to this.)

B6. Level 1: averages (1.5, 3.5, 5.5, 7.5), differences (-0.5, -0.5, -0.5, -0.5); level 2: (2.5, 6.5) / (-1, -1); level 3: 4.5 / -2: (4.5 \mid -2 \mid -1, -1 \mid -0.5, -0.5, -0.5, -0.5). No detail is zero. A Haar pattern gives zero only on a constant; a ramp is nowhere constant, so every pattern sees the slope. Smooth but sloped signals are not sparse in the Haar basis.

B7. Spike at 0: X_k = 1 for all k. Spike at 3: X_k = e^{-2\pi i \cdot 3k/8}, again |X_k| = 1 for all k. The magnitudes are identical; the position is stored only in the phases -3\pi k/4, i.e. in all eight coefficients together.

B8. (a) 50 ms holds 0.05 \cdot 4 = 0.2 cycles: a fifth of a wave looks like a slope, and its frequency cannot be told (the window’s frequency resolution is about 1/0.05\,\text{s} = 20 Hz). (b) A 2 s window holds 2000 samples; the step affects every window that contains it, so its position is only known to within about 2000 samples (2 s). (c) A wavelet analysis uses long patterns (here: about a second) for the slow wave and short ones (a few ms) for the step, so both are described well.

Math questions

B9. (math) Show that the 2 \times 2 matrix Q = \frac1{\sqrt2}\begin{pmatrix}1 & 1\\ 1 & -1\end{pmatrix} satisfies QQ^\top = I. Use this to argue that one level of the normalised Haar transform on N samples, and then the whole transform, is an orthogonal matrix.

B10. (math) Let \{\mathbf u_i\} be an orthonormal basis of \mathbb R^N and c_i = \mathbf u_i^\top x. Show that the squared error of \hat x = \sum_{i \in S} c_i\mathbf u_i is \sum_{i \notin S} c_i^2, and that among all sets S of size K the smallest error is reached by the K largest |c_i|.

B11. (math) Show that the coefficients of the two normalisations are related by c^{\text{orth}} = 2^{j/2}\,c^{\text{hand}} for a detail at level j (and for the final average after J levels, 2^{J/2}). Check it on the board example.

B12. (math) Compute the DFT magnitudes of a box of m ones in N samples, |X_k| = |\sin(\pi k m/N)/\sin(\pi k/N)|, and show that for 1 \ll k \ll N it behaves like N/(\pi k) times a bounded factor.

B9. QQ^\top = \tfrac12\begin{pmatrix}1+1 & 1-1\\ 1-1 & 1+1\end{pmatrix} = I. One level maps each pair (x_{2k}, x_{2k+1}) by Q and then reorders the outputs (averages first, differences after). As a matrix this is P\,\mathrm{diag}(Q, \dots, Q) with a permutation P; both factors are orthogonal, so the product is. The full transform applies such a level to the first N/2^{j} entries and leaves the rest alone, \mathrm{diag}(L_j, I), again orthogonal; a product of orthogonal matrices is orthogonal.

B10. x - \hat x = \sum_{i \notin S} c_i\mathbf u_i, so \|x - \hat x\|^2 = \sum_{i,k \notin S} c_i c_k\,\mathbf u_i^\top\mathbf u_k = \sum_{i \notin S} c_i^2 by orthonormality. For a fixed K this is the total energy \sum_i c_i^2 minus \sum_{i \in S} c_i^2, which is largest when S holds the K largest c_i^2.

B11. Each orthonormal step multiplies by 1/\sqrt2 where the by-hand step multiplies by 1/2, a factor \sqrt2 more. A level-j detail is built from j steps (the j-1 averaging steps before it and its own difference step), so it carries (\sqrt2)^j = 2^{j/2}; the final average after J levels carries 2^{J/2}. Board example: 7 \cdot 2^{3/2} = 19.80, 1 \cdot 2^{3/2} = 2.83, -3 \cdot 2 = -6, 1 \cdot 2 = 2, -1 \cdot \sqrt2 = -1.41. ✓

B12. \sum_{n=0}^{m-1} e^{-i\theta n} = \frac{1 - e^{-i\theta m}}{1 - e^{-i\theta}} = e^{-i\theta(m-1)/2}\frac{\sin(\theta m/2)}{\sin(\theta/2)} with \theta = 2\pi k/N; a shift of the box only multiplies by a phase. So |X_k| = |\sin(\pi k m/N)|/|\sin(\pi k/N)|. For k \ll N, \sin(\pi k/N) \approx \pi k/N, giving |X_k| \approx \frac{N}{\pi k}|\sin(\pi k m/N)|, with |\sin| \le 1: a 1/k envelope.

Explore: the Haar transform step by step

The upper panel shows the signal as bars: drag a bar’s top to change it. step combines the bracketed pairs into averages (grey blocks over the signal) and differences; the lower panel shows the coefficient vector so far, coloured by level (s grey, then level 3, 2, 1). back undoes one level. Choose the normalisation s = (a+b)/2 (by hand) or s = (a+b)/\sqrt2 (orthonormal). Click a coefficient to drop it (dashed) or use keep K largest: the orange dashed line is the reconstruction from the kept coefficients. show basis draws the transform matrix instead of the coefficients.

E1. Preset board example, normalisation (a+b)/2. Press step three times and compare each stage with the table in the lecture. Read \Sigma c^2 after each step. Then switch to (a+b)/\sqrt2 and repeat. What do you notice?

E2. Orthonormal normalisation, all three levels done. Move keep K largest from 8 down to 1. For each K, compare \Sigma dropped c^2 with \Sigma (x - \hat x)^2. Which coefficient goes first, and which is kept longest? What is \hat x for K = 1?

E3. Now switch to (a+b)/2 and keep K = 3. Are the same three coefficients kept? Compare \Sigma dropped c^2 with the actual error.

E4. Try the presets spike, step, ramp and constant (all levels done). Count the nonzero coefficients and compare with B4–B6.

E5. Tick show basis with all levels done, in both normalisations. Which rows have length 1? (Hint: for N = 8 the numbers are printed in the cells.)

E1. With (a+b)/2: \Sigma c^2 = 446, 223, 113, 63 after 0, 1, 2, 3 levels: every step loses energy. The stages are (5, 11, 7, 5 \mid -1, -1, 1, 0), (8, 6 \mid -3, 1 \mid \dots), (7 \mid 1 \mid \dots). With (a+b)/\sqrt2, \Sigma c^2 = 446 at every stage: the orthonormal transform keeps the energy.

E2. K = 8, 7: error 0 (the dropped coefficient is 0). K = 6: 2, K = 5: 4, K = 4: 6 (the three level-1 details \pm1.41 go, 2 each), K = 3: 10 (the level-2 detail 2 goes), K = 2: 18 (2.83^2 = 8), K = 1: 54 ((-6)^2 = 36). The dropped sum always equals the error. The zero goes first; the average 19.80 stays longest, and with it alone \hat x = (7, 7, 7, 7, 7, 7, 7, 7), the mean of x.

E3. With (a+b)/2 the demo keeps 7, -3 and 1, the first of the two coefficients of size 1 in the vector (the level-3 detail), which happens to be the same choice as before, so \hat x = (5, 5, 11, 11, 6, 6, 6, 6) and the error is 10. But \Sigma dropped c^2 is only 1 + 1 + 1 + 1 = 4: in this scaling the dropped coefficients do not add up to the error (B2d, B11).

E4. Spike (0, 0, 0, 0, 8, 0, 0, 0): 4 nonzero (B4). Step (2, 2, 2, 10, \dots): 4 nonzero (B5). Ramp (1, \dots, 8): all 8 nonzero (B6). Constant (5, \dots, 5): 1 (only the average).

E5. Orthonormal: all rows have length 1 (entries \pm0.35 in the first two rows, \pm0.5 in the next two, \pm0.71 in the last four). By hand: the rows have entries \pm\tfrac18, \pm\tfrac14, \pm\tfrac12, so lengths 0.35, 0.35, 0.5, 0.5, 0.71, 0.71, 0.71, 0.71: still perpendicular, but not of length 1.

Explore: sparsity in two bases

A signal of 256 samples (black). One slider keep K keeps the K largest coefficients in the real Fourier basis (cosines and sines; red) and in the Haar basis (5 levels; blue); both reconstructions are drawn over the signal. Lower left: the coefficient magnitudes of both bases sorted from large to small (log scales), or the Haar coefficients laid out by level and position (bright = large, faded = dropped). Lower right: the relative error \|x - \hat x\|/\|x\| against K for both bases. The readout gives the error at the current K and the K needed for 1 % error.

E6. Preset step. Read the relative errors at K = 8 and the K needed for 1 % error in both bases. Switch the lower-left panel to wavelet coefficients by level: where are the large coefficients?

E7. Preset spike. How many coefficients does each basis need for 1 % error? Explain the Haar number from what you found in B4 (here with 5 levels).

E8. Preset sine. Now which basis wins, and by how much? Why?

E9. Signal two steps and Blocks (a piecewise-constant test signal). Read the K for 1 % error in both bases.

E10. Preset Doppler: a wave whose frequency falls from left to right. Read the K for 1 % error in both bases and the errors at K = 32. Why is neither basis good here?

E6. At K = 8: Fourier 16.5 %, Haar 2.79 %. For 1 % error: Fourier 176 coefficients, Haar 11. In the by-level view the large details sit in one column, at the position of the step, one per level; the rest are the approximation coefficients (a_5).

E7. Fourier 247 of 256, Haar 6. With 5 levels the spike touches one detail per level (5) and one approximation coefficient: 6 nonzero coefficients, so 6 give it exactly.

E8. Fourier needs 1 coefficient (the sine is one of its basis vectors); Haar needs 218. A wave extends over the whole signal, exactly what the Fourier basis is made of, while every Haar pattern sees a piece of a slope.

E9. Two steps: Fourier 207, Haar 16. Blocks: Fourier 224, Haar 39. Piecewise-constant signals are sparse in the Haar basis: a few details per jump.

E10. Fourier 231, Haar 196; at K = 32, 29.9 % (Fourier) and 27.1 % (Haar). The Doppler signal changes frequency along the way: Fourier needs many waves to describe one whose frequency drifts, and Haar’s square patterns fit oscillations poorly. Smoother wavelets do much better (next unit: db4 needs 75).

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in wavelets/src/haar/exercise.rs.

C1. haar_step(x, orthonormal): every pair becomes an average and a difference, with f = \tfrac12 (by hand) or f = \tfrac1{\sqrt2} (orthonormal). Then haar_forward(x, orthonormal), the full transform:

c = x;  len = N
while len > 1:
    for k = 0 … len/2 − 1:
        s[k] = (c[2k] + c[2k+1]) · f
        d[k] = (c[2k] − c[2k+1]) · f
    c[0 … len/2 − 1] = s;   c[len/2 … len − 1] = d     # the details stay where they are
    len = len / 2

The result is (s \mid d_3 \mid d_2, d_2 \mid d_1, \dots), coarse to fine. The checks are the board example, B1, B2 (orthonormal) and B4–B6 (spike, steps, ramp).

C2. haar_inverse(c, orthonormal): the same levels backwards, from the coarsest up: each (s, d) becomes a = s + d, b = s - d (by hand) or a = (s + d)/\sqrt2, b = (s - d)/\sqrt2 (orthonormal). The checks: B1 backwards, forward then inverse gives x back, and the energies of B2(a): 446 for x and for the orthonormal coefficients, but 63 by hand.

C3. keep_largest(c, k): keep the k coefficients of largest magnitude, set the rest to 0, and return the sum of the dropped squares as well. The check is B2(b, c): keeping 3 drops 10, and the reconstruction is (5, 5, 11, 11, 6, 6, 6, 6).

C4. haar_basis(n): the orthonormal basis vectors as rows: row i is haar_inverse of the coefficient vector with a single 1 at position i. The check is the 4 \times 4 matrix of B3, and that the 16 rows for n = 16 have length 1 and are perpendicular.

Then cargo run -p wavelets -- haar and open the pictures in out/haar/.

C5. The program counts the nonzero Haar coefficients of a spike and a step at position 23 of 64 samples, and the relative error when keeping the 6 largest coefficients in the Fourier and in the Haar basis. Before you run it: how many nonzero Haar coefficients do you expect for each? Then compare the errors with the lecture slide “A spike and a step in the Fourier basis”.

C6. For row 160 of the micrograph, how many coefficients does each basis need for 1 % error? Look at row-keep16.png (grey: the row, red: 16 Fourier coefficients, blue: 16 Haar coefficients). What kind of error does each basis make?

The model solution is wavelets/src/haar/solution.rs in the download.

C5. 7 each: one per level (\log_2 64 = 6) plus the average, because only one pattern per level contains the spike or the jump (B4, B5). Keeping 6: Fourier 90.3 % (spike) and 19.2 % (step), Haar 12.5 % and 5.5 %, as on the slide. With 7 coefficients Haar is exact, while Fourier needs 63 (spike) and 52 (step) coefficients for 1 %.

C6. Fourier 200 and Haar 170 of 256: the row is full of fine texture, and neither basis is sparse for it; with 16 coefficients both have about 13 % error. The kinds of error differ: the Fourier curve is smooth and wavy, with ripples where the row is flat and rounded jumps; the Haar curve is a staircase of flat pieces with sharp jumps that sit on the dyadic grid. The large dark and bright plateaus are followed well by both.

Where this leads

The Haar basis only sees constants as “nothing to report”, so ramps and smooth curves leave details everywhere. The next unit, filter banks, builds wavelets with more vanishing moments (Daubechies), computes every wavelet transform with the same two filters and a downsampling step (a filter bank), and explains why that costs only \mathcal O(N) operations.

Further on, the Haar patterns come back as Haar-like features for fast object detection: sums over neighbouring rectangles, computed with integral images (rectangle features).