Take a signal apart, and put it back.

The last chapter ended on a question. When you look for detail in a signal, which size of detail should you look for? A wavelet transform answers "every size," and it keeps the answers in separate layers. This chapter does that to a single line, where every move can be followed.

Averages and differences

A portrait painter starts with the big shapes, such as the oval of the face and the mass of the hair. Smaller strokes come next, and the eyelashes come last. A wavelet transform describes a signal in that same order, broad shapes first and fine detail last, and it builds the whole description from two plain operations, which are averaging and taking differences.

The whole method grows out of one small move, and the move is easiest to follow with a few plain numbers. Take these eight: 8, 6, 3, 5, 4, 4, 9, 1. Group them into neighboring pairs, and for each pair write down two things. The first is the average of the pair, which is the number halfway between the two. The second is how far each member of the pair sits from that average.

The first pair is 8 and 6. Their average is 7, and each of them is 1 away from it, with the 8 sitting 1 above and the 6 sitting 1 below. So the pair 8, 6 can be written as "7, give or take 1." Everything is still there, because given the 7 and the 1, you can get the 8 and the 6 back by adding and subtracting.

Here are the eight numbers, taken apart. Each amber number is the average of the two numbers above it. Each cyan number is the difference that was set aside: add it to the average to get the left number of the pair, subtract it to get the right one.

Do this for all four pairs and the eight numbers become four averages and four differences. The four averages, 7, 4, 4 and 5, are a shorter and smoother version of the original list. They are its outline. The four differences are the fine detail that the outline leaves out.

Now make the same move on the four averages alone. They become two averages and two differences, and the two averages become one average and one difference. At the end there is a single number, 5, which is the average of all eight, plus seven differences sorted by size: one that describes the broadest change across the whole list, two for the changes half that broad, and four for the changes between next-door neighbors. Eight numbers went in and eight came out, and the original eight can be rebuilt exactly by running the moves backward.

Look at what the differences say. The third pair was 4 and 4, and its difference is 0. Wherever a signal is flat, its differences vanish. The last pair was 9 and 1, and its difference is 4, the largest on the board. Wherever a signal jumps, a large difference marks the spot. That behavior is what the rest of this chapter, and the next one, depend on.

This is a complete wavelet transform. It is the simplest one there is, and it was published in 1910 by the Hungarian mathematician Alfred Haar, long before anyone used the word wavelet.

From Haar to the symlet

Haar's method compares each number with a single neighbor, and that makes it blunt. Describe a gentle slope with it and the outline comes out as a staircase, with a small leftover difference at every stair.

In 1988 the mathematician Ingrid Daubechies found a way to do better. In place of a plain average of two neighbors, her method takes a weighted average, in which some neighbors count for more than others, across four neighbors, or six, or eight. It takes a weighted difference across the same stretch. The weights are chosen with great care, so that two things remain true. The first is that the signal can still be rebuilt exactly from the averages and differences. The second is that a smooth stretch of signal, even a sloping or curving one, now gives differences that are almost exactly zero.

There is another way to see the same thing. When the signal is rebuilt, each difference puts back one small wave-shaped bump at one place, and that bump is the wavelet. Haar's wavelet has square corners, like a single stair. Daubechies' wavelets are smooth, but they lean to one side, and for work on pictures a lopsided shape is a nuisance because it nudges edges sideways. So she worked out the least lopsided shapes that her rules allow. Those are the symlets, short for symmetrical wavelets, and they gave this site its name. Choose different wavelets in the menu below and the small chart beside it shows the shape of each.

Try it on a line of your own

The top chart below holds a line of 512 points. Draw on it, or start from one of the ready-made shapes. Underneath are its numbers after the transform: first the outline, then each layer of differences, from the broadest detail down to the finest. Each bar is one number.

the linedraw here. gray is your drawing, amber is the rebuilt line

Four things are worth doing here, in this order.

First, point at any single bar, or touch it. A cyan line appears on the top chart showing exactly what that one number contributes, which is one small wave, at one place, of one width. Bars in the lower rows make narrow waves and bars in the upper rows make wide ones. The whole line is simply all of these waves added together.

Second, press "build it up, layer by layer." The page rebuilds the line from the outline alone and then adds one layer of detail at a time. You can watch the rough shape arrive first and the sharp corners arrive last.

Third, choose "a raised block" and look at where the bars are. Almost every one is zero, and the only bars standing are the ones that sit over the two jumps at the sides of the block. A sudden change in a signal leaves a mark in every layer, at the same position, and that is how wavelets are used to find sudden changes, such as a crack starting in a machine bearing, a skipped heartbeat in a hospital recording, or an edge in a photograph.

Fourth, choose "a wave with noise" and move the slider that drops the small numbers. The noise is spread thinly across hundreds of small bars, and the wave itself is held in a few large ones. Drop the small bars and the rebuilt line comes out clean. The same trick, on photographs, is the subject of the next chapter.

You can also drag any bar up or down to change its number, and the amber line will follow. It is a strange way to draw, and a good way to get a feel for what each layer holds.

About the two ends. The page treats the line as a loop, with its right end joined to its left. If the two ends sit at different heights, the join is a jump like any other, and bars will stand up at both ends of every row. Those bars come from the join, and the rest of your drawing is read just as you drew it.

The loop

Here is Haar's move as a program, along with the move that undoes it. One detail differs from the worked example above. Programs divide by the square root of two, about 1.414, where the example divided by two. This keeps the overall size of the numbers the same before and after, which makes it fair to compare numbers from different layers. Everything else is the same. The last lines of the Python version show how the whole transform, with any wavelet and any number of layers, is done with a library, which is a collection of programs that someone else has already written and tested.

/* One step of the simplest wavelet transform (Haar).
   x holds n numbers, n even. Each pair becomes one average and one difference. */
void haar_step(const float *x, int n, float *avg, float *diff)
{
    const float s = 0.70710678f;                 /* 1 / sqrt(2) */
    for (int k = 0; k < n / 2; k++) {
        avg[k]  = (x[2 * k] + x[2 * k + 1]) * s;
        diff[k] = (x[2 * k] - x[2 * k + 1]) * s;
    }
}

/* The way back. Every pair is recovered exactly. */
void haar_unstep(const float *avg, const float *diff, int half, float *x)
{
    const float s = 0.70710678f;
    for (int k = 0; k < half; k++) {
        x[2 * k]     = (avg[k] + diff[k]) * s;
        x[2 * k + 1] = (avg[k] - diff[k]) * s;
    }
}
#include <cmath>
#include <utility>
#include <vector>

// One step of the simplest wavelet transform (Haar):
// each pair of neighbors becomes one average and one difference.
std::pair<std::vector<float>, std::vector<float>> haar_step(const std::vector<float>& x)
{
    const float s = 1.0f / std::sqrt(2.0f);
    std::vector<float> avg(x.size() / 2), diff(x.size() / 2);
    for (std::size_t k = 0; k < avg.size(); k++) {
        avg[k]  = (x[2 * k] + x[2 * k + 1]) * s;
        diff[k] = (x[2 * k] - x[2 * k + 1]) * s;
    }
    return {avg, diff};
}

// The way back. Every pair is recovered exactly.
std::vector<float> haar_unstep(const std::vector<float>& avg, const std::vector<float>& diff)
{
    const float s = 1.0f / std::sqrt(2.0f);
    std::vector<float> x(avg.size() * 2);
    for (std::size_t k = 0; k < avg.size(); k++) {
        x[2 * k]     = (avg[k] + diff[k]) * s;
        x[2 * k + 1] = (avg[k] - diff[k]) * s;
    }
    return x;
}
/// One step of the simplest wavelet transform (Haar):
/// each pair of neighbors becomes one average and one difference.
pub fn haar_step(x: &[f32]) -> (Vec<f32>, Vec<f32>) {
    let s = 1.0 / 2.0_f32.sqrt();
    let avg = x.chunks_exact(2).map(|p| (p[0] + p[1]) * s).collect();
    let diff = x.chunks_exact(2).map(|p| (p[0] - p[1]) * s).collect();
    (avg, diff)
}

/// The way back. Every pair is recovered exactly.
pub fn haar_unstep(avg: &[f32], diff: &[f32]) -> Vec<f32> {
    let s = 1.0 / 2.0_f32.sqrt();
    let mut x = Vec::with_capacity(avg.len() * 2);
    for (a, d) in avg.iter().zip(diff) {
        x.push((a + d) * s);
        x.push((a - d) * s);
    }
    x
}
import numpy as np
import pywt

def haar_step(x):
    """Each pair of neighbors becomes one average and one difference."""
    x = np.asarray(x, dtype=float)
    avg = (x[0::2] + x[1::2]) / np.sqrt(2)
    diff = (x[0::2] - x[1::2]) / np.sqrt(2)
    return avg, diff

def haar_unstep(avg, diff):
    """The way back. Every pair is recovered exactly."""
    x = np.empty(2 * len(avg))
    x[0::2] = (avg + diff) / np.sqrt(2)
    x[1::2] = (avg - diff) / np.sqrt(2)
    return x

# any wavelet and any number of layers, with a library:
outline, *details = pywt.wavedec(x, "sym4", mode="periodization", level=5)
rebuilt = pywt.waverec([outline, *details], "sym4", mode="periodization")