Exercise: quadratic smoothing and total variation

Goal

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

  • set up and solve the linear system of quadratic (Gaussian MRF) smoothing for a few pixels,
  • explain with numbers why a quadratic prior blurs edges and total variation keeps them,
  • solve small TV problems by hand with the plateau rule, and predict staircasing and contrast loss,
  • read quadratic smoothing as a low-pass filter,
  • choose between quadratic, Huber and TV for a given kind of image.

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

Background

Word Meaning
Energy E(\mathbf x) = \tfrac12\sum_p(x_p - y_p)^2 + \lambda\sum_{(p,q)}\rho(x_p - x_q), neighbours on a line or grid
Quadratic \rho(d) = d^2/2; minimum solves (I + \lambda L)\mathbf x = \mathbf y
Path Laplacian L diagonal 1, 2, …, 2, 1; -1 for each neighbour pair
Gain quadratic smoothing multiplies frequency \omega by 1/(1 + \lambda(2 - 2\cos\omega))
Total variation (TV) \rho(d) = \lvert d\rvert
Plateau rule (TV, 1D) the solution is made of flat runs; each sits at the mean of its data, moved by \lambda/\text{width} towards each neighbouring run that is higher or lower
Huber \rho(d) = d^2/2 for \lvert d\rvert \le \delta, \delta(\lvert d\rvert - \delta/2) beyond

By hand

B1. Quadratic, three pixels. \mathbf y = (0, 3, 0). (a) Write I + \lambda L for \lambda = 1 and solve (I + L)\mathbf x = \mathbf y. (b) Repeat for \lambda = 2. What happens to the sum x_1 + x_2 + x_3? (c) Compute the energy of your solution for \lambda = 1, and of \mathbf y itself and of (1, 1, 1). Is the solution really the best of the three?

B2. Ramps and jumps. A signal must go from 0 to 3. Compute the prior cost \sum\rho(d) of doing it in one jump, in 3 equal steps, and in 30 equal steps, for the quadratic and the absolute penalty. Which shape does each prior prefer? What does this predict for an edge in a noisy image?

B3. TV, a step. \mathbf y = (0, 0, 3, 3). (a) Use the plateau rule to find the TV solution for \lambda = 1. Check that its energy is lower than that of \mathbf y. (b) For which \lambda does the step disappear completely? What is the solution then? (c) Compare with quadratic smoothing at \lambda = 1: \hat{\mathbf x} = (0.43, 0.86, 2.14, 2.57). Describe the difference in words.

B4. TV, a narrow peak. \mathbf y = (0, 3, 0). (a) Find the TV solution for \lambda = 0.5 and for \lambda = 1. (b) A peak of width w samples and height a on a flat background: about how much does TV lower it? For which \lambda does it vanish, roughly? Which features of an image does TV therefore remove first?

B5. Low-pass. For quadratic smoothing: (a) Compute the gain at \omega = \pi (the pattern +1, -1, +1, \dots) for \lambda = 1 and \lambda = 10. (b) For \lambda = 10, at which frequency (in cycles per sample, \omega/2\pi) is the gain \tfrac12? (c) Why does any low-pass filter blur a step edge?

B6. Which prior? Choose quadratic, Huber or TV, and explain: (a) a fluorescence image of cells with flat interiors and sharp boundaries; (b) an estimate of the slowly varying illumination of a microscope; (c) a gel image with smooth gradients and sharp bands.

B1. (a) I + L = \begin{bmatrix} 2 & -1 & 0 \\ -1 & 3 & -1 \\ 0 & -1 & 2\end{bmatrix}. By symmetry x_1 = x_3 = a, x_2 = b: 2a - b = 0, -2a + 3b = 3, so b = 1.5, a = 0.75. (b) I + 2L: 3a - 2b = 0, -4a + 5b = 3: \hat{\mathbf x} = (0.857, 1.286, 0.857). The sum stays 3: quadratic smoothing preserves the mean (the rows of L sum to 0). (c) E(\hat{\mathbf x}) = \tfrac12(0.75^2 + 1.5^2 + 0.75^2) + \tfrac12(0.75^2 + 0.75^2) = 1.6875 + 0.5625 = 2.25. E(\mathbf y) = 0 + \tfrac12(9 + 9) = 9. E(1, 1, 1) = \tfrac12(1 + 4 + 1) + 0 = 3. Yes, 2.25 is the lowest.

B2. Quadratic: \tfrac12 \cdot 9 = 4.5; 3 \cdot \tfrac12 = 1.5; 30 \cdot \tfrac12 \cdot 0.01 = 0.15. Absolute: 3 in all three cases. The quadratic prior strongly prefers spreading the change over many small steps (a ramp); TV is indifferent to how a monotone change is spread. Prediction: under a quadratic prior an edge is smeared out; under TV the data decide, and they say the edge is sharp.

B3. (a) Two plateaus of width 2, data means 0 and 3. The left one has a higher neighbour: up by \lambda/2 = 0.5; the right one down by 0.5: \hat{\mathbf x} = (0.5, 0.5, 2.5, 2.5). Energy: data 4 \cdot \tfrac12 \cdot 0.25 = 0.5, TV \lambda \cdot 2 = 2: total 2.5, against 0 + 3 = 3 for \mathbf y. (b) The plateaus meet at the mean 1.5 when \lambda/2 = 1.5: \lambda = 3. For \lambda \ge 3 the solution is (1.5, 1.5, 1.5, 1.5). (c) TV keeps one sharp jump, just smaller (2 instead of 3): contrast is lost but the edge stays where it is and stays sharp. Quadratic smoothing replaces the jump by a ramp over all four samples.

B4. (a) The peak (width 1, two lower neighbours) drops by 2\lambda, each side (width 1, one higher neighbour) rises by \lambda: \lambda = 0.5: (0.5, 2, 0.5). At \lambda = 1 they would meet at 1: (1, 1, 1), the mean. (b) It is lowered by about 2\lambda/w (a little less in practice, because the background rises too). It disappears for \lambda around aw/2. Small and narrow features lose contrast first and then vanish, even if they are bright: TV shrinks small structures.

B5. (a) \omega = \pi: 2 - 2\cos\pi = 4; gain 1/5 = 0.2 (\lambda = 1) and 1/41 = 0.024 (\lambda = 10). (b) 1 + 10(2 - 2\cos\omega) = 2: \cos\omega = 0.95, \omega = 0.318, i.e. 0.051 cycles per sample (a period of about 20 samples). (c) A step is a sum of waves of all frequencies (its Fourier transform falls off only like 1/\omega); damping the high frequencies removes the parts that make it sharp. A linear filter cannot distinguish a high frequency belonging to an edge from one belonging to noise.

B6. (a) TV: flat regions with sharp boundaries are exactly what its solutions look like (some contrast loss at small cells). (b) Quadratic (and a large \lambda): illumination has no edges, and the linear system is fast. (c) Huber: quadratic for the small differences of smooth gradients (no staircases), linear for the large jumps at bands (no blurring).

Math questions

B7. (math) Show that \sum_{(p,q)}(x_p - x_q)^2 = \mathbf x^\top L\mathbf x, that the gradient of E for the quadratic prior is (\mathbf x - \mathbf y) + \lambda L\mathbf x, and that I + \lambda L is positive definite, so the minimum is unique.

B8. (math) On a ring of n samples, show that \mathbf f with f_p = e^{i\omega p}, \omega = 2\pi k/n, is an eigenvector of L with eigenvalue 2 - 2\cos\omega, and derive the gain of B5.

B9. (math) Derive the plateau rule for 1D TV from the optimality condition x_p - y_p + \lambda(g_{p-1} - g_p) = 0, g_p \in \operatorname{sign}(x_{p+1} - x_p) (with g_p \in [-1, 1] where x_{p+1} = x_p, and g = 0 beyond the ends).

B10. (math) With Gaussian noise of standard deviation \sigma_n and the prior p(\mathbf x) \propto \exp(-\frac{\lambda'}2\mathbf x^\top L\mathbf x), show that the posterior is Gaussian, that its MAP solves (I + \lambda'\sigma_n^2L)\mathbf x = \mathbf y, and that MAP and posterior mean coincide.

B7. \mathbf x^\top L\mathbf x = \sum_pd_px_p^2 - \sum_{p,q}W_{pq}x_px_q = \sum_{(p,q)}(x_p^2 + x_q^2 - 2x_px_q) = \sum_{(p,q)}(x_p - x_q)^2 (each edge once). \nabla\tfrac12\|\mathbf x - \mathbf y\|^2 = \mathbf x - \mathbf y and \nabla\frac\lambda2\mathbf x^\top L\mathbf x = \lambda L\mathbf x (L symmetric). \mathbf x^\top(I + \lambda L)\mathbf x = \|\mathbf x\|^2 + \lambda\sum(x_p - x_q)^2 > 0 for \mathbf x \ne \mathbf 0: positive definite, so E is strictly convex with one minimum.

B8. (L\mathbf f)_p = 2e^{i\omega p} - e^{i\omega(p-1)} - e^{i\omega(p+1)} = (2 - e^{-i\omega} - e^{i\omega})e^{i\omega p} = (2 - 2\cos\omega)f_p; on the ring p \pm 1 wraps around, which works because e^{i\omega n} = 1. Then (I + \lambda L)\mathbf f = (1 + \lambda(2 - 2\cos\omega))\mathbf f, and solving the system divides the \mathbf f-component of \mathbf y by this number: the gain.

B9. On a plateau x_a = \dots = x_b = c with different values outside, add the conditions for p = a, \dots, b: the terms \lambda(g_{p-1} - g_p) telescope to \lambda(g_{a-1} - g_b), so \sum_{p=a}^b(c - y_p) = -\lambda(g_{a-1} - g_b) and c = \bar y_{[a,b]} - \lambda(g_{a-1} - g_b)/(b - a + 1). g_{a-1} = +1 if the left neighbour is lower (-1 if higher), g_b = +1 if the right neighbour is higher (-1 if lower). A higher neighbour on one side and a lower one on the other: g_{a-1} = g_b, no shift. A local maximum: g_{a-1} = 1, g_b = -1, shift -2\lambda/w. A plateau at the end of the signal with one higher neighbour: +\lambda/w.

B10. -\log p(\mathbf x \mid \mathbf y) = \frac1{2\sigma_n^2}\|\mathbf x - \mathbf y\|^2 + \frac{\lambda'}2\mathbf x^\top L\mathbf x + \text{const}, a quadratic form in \mathbf x with Hessian A = I/\sigma_n^2 + \lambda'L (positive definite): the posterior is Gaussian with covariance A^{-1}. Gradient zero: (\mathbf x - \mathbf y)/\sigma_n^2 + \lambda'L\mathbf x = 0, i.e. (I + \lambda'\sigma_n^2L)\mathbf x = \mathbf y. A Gaussian has its maximum at its mean, and each marginal is a Gaussian centred at the same point: MAP = mean = MPM.

Explore

A profile of 200 samples with Gaussian noise (fixed seed): step · ramp · peak (a step at 40, a ramp from 2 down to 0 over 80–140, a 4-sample peak of height 2 at 166–169), plateaus, or a line across the micrograph. Choose the prior and \lambda (and \delta for Huber). The plot shows the noisy data (grey dots), the truth (dashed) and the estimate; the readout splits the energy into data and prior terms and gives the error (RMSE) against the truth. Tabs: prior samples (five random walks from the quadratic and from the TV prior, with the same step variance, and the two step distributions), and the matrix (I + \lambda L for 10 samples, and the gain of quadratic smoothing against frequency).

E1. Preset quadratic blurs the step (\lambda = 10). Read the RMSE of the estimate and of the noisy data. Over how many samples is the step spread? How high is the peak? Now find the \lambda with the smallest RMSE for the quadratic prior. What do you see at that \lambda?

E2. Preset TV keeps the step (\lambda = 1). Compare the step, the RMSE and the energy split with E1. What happened to the ramp and to the peak?

E3. Preset TV staircases the ramp (\lambda = 3, zoomed on the ramp). Describe the estimate on the ramp. Is the RMSE better or worse than at \lambda = 1?

E4. Preset TV shrinks the narrow peak (\lambda = 2, zoomed on the peak). Read the peak height of the estimate at \lambda = 1, 2 and 3 and compare with B4(b) (w = 4, a = 2).

E5. Preset Huber in between (\lambda = 5, \delta = 0.1). Compare step, ramp, peak and RMSE with the best quadratic and the best TV result (find the best \lambda for TV).

E6. Choose the plateaus profile. Compare quadratic (\lambda = 10) and TV (\lambda = 1). Why does TV do especially well here?

E7. Tab prior samples. Which draws look more like the profiles we denoise: the quadratic or the TV ones? Do the TV draws have flat plateaus? Compare the two step distributions in the lower plot.

E8. Tab the matrix. For \lambda = 10, read the entries of I + \lambda L and compare with the Background table. Read the gain at 0.05 and at 0.5 cycles per sample, and check with B5.

E1. RMSE 0.240 against 0.291 for the noisy data. The step rises from 10 % to 90 % over about 15 samples, and the peak reaches only 0.90 (true height 2). The best quadratic \lambda is about 1.2 (RMSE 0.190): the step is a little sharper (about 13 samples) and the peak higher (1.53), but much of the noise is back. Quadratic smoothing trades noise against blur and cannot win both.

E2. The step stays sharp (from 0.25 to 2.04 within two samples), RMSE 0.137, energy 7.30 (data) + 6.81 (prior). The ramp is cut into flat steps (staircasing), and the peak is lowered to 1.36.

E3. The ramp becomes a staircase of about a dozen flat steps. RMSE 0.268, worse than at \lambda = 1 (0.137): the plateaus also lose more contrast (the peak is down to 0.36).

E4. Peak 1.36 (\lambda = 1), 0.86 (\lambda = 2), 0.36 (\lambda = 3). The rule 2\lambda/w = \lambda/2 predicts 1.5, 1.0, 0.5: the same trend, each a bit lower because the noise and the rising background also count. It vanishes around \lambda = aw/2 = 4.

E5. Huber (\lambda = 5, \delta = 0.1): sharp step, smooth ramp without stairs, peak 1.72, RMSE 0.128. The best quadratic gets 0.190 (\lambda \approx 1.2), the best TV 0.125 (\lambda \approx 0.55; small noise plateaus remain in the flat parts, and the ramp is still a staircase). Huber and TV are about equally good by RMSE; Huber looks better on the ramp.

E6. Plateaus: quadratic RMSE 0.227, TV 0.104. The profile is piecewise constant, which is exactly the shape of a TV solution: TV’s prior assumption is right here, so it removes noise without blurring the jumps.

E7. Neither looks like a profile with steps: both are rough random walks drifting up and down. The TV draws have no flat plateaus. Their step distribution (Laplace) has a sharper peak at 0 and heavier tails than the normal one: more tiny steps and more big ones. The flat plateaus of TV estimates come from minimising the energy, not from the prior’s typical samples.

E8. Diagonal 1 + 10 = 11 at the two ends and 1 + 20 = 21 inside, -10 next to the diagonal, zeros elsewhere: tridiagonal. Gain 0.505 at 0.05 cycles per sample and 1/41 = 0.024 at 0.5: as in B5.

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 ising/src/gmrf/exercise.rs.

C1. penalty(d, ρ) for the three penalties (quadratic, TV, Huber with its \delta), and energy_1d(x, y, λ, ρ): E = \tfrac12\sum_p (x_p - y_p)^2 + \lambda\sum_p \rho(x_{p+1} - x_p). The checks are B2 (4.5, 1.5, 0.15 against 3, 3, 3), B1(c) and B3(a).

C2. quadratic_1d(y, λ): solve (I + \lambda L)\mathbf x = \mathbf y on a path. The matrix is tridiagonal, so elimination needs one pass down and one pass up:

row p:  −λ x[p−1] + a[p] x[p] − λ x[p+1] = y[p]       a = 1+λ at the two ends, 1+2λ inside
down:   c[0] = −λ / a[0],  d[0] = y[0] / a[0]
        for p = 1 .. n−1:
            m = a[p] + λ c[p−1]
            c[p] = −λ / m,  d[p] = (y[p] + λ d[p−1]) / m
up:     x[n−1] = d[n−1]
        for p = n−2 down to 0:  x[p] = d[p] − c[p] x[p+1]

The checks are B1(a, b), B3(c), and that the sum of the values is kept.

C3. tv_1d(y, λ, iterations): total variation in 1D. Each pair of neighbours gets a number z_p between -\lambda and \lambda: the \lambda g_p of the math slide, the force that holds the two samples together. Given the z’s, the samples are x_p = y_p - (z_{p-1} - z_p):

z = 0 for every pair
repeat iterations times:
    x[p] = y[p] − (z[p−1] − z[p])          for every p (z = 0 beyond the ends)
    z[p] = z[p] + ¼ · (x[p+1] − x[p])       for every pair, then clip to [−λ, λ]
x[p] = y[p] − (z[p−1] − z[p])

Where a pair’s z stays strictly inside (-\lambda, \lambda), the two samples end up equal (a plateau); where it sticks at \pm\lambda, there is a jump. The checks are B3 and B4.

C4. quadratic_2d(y, λ, sweeps): quadratic smoothing of an image with 4-neighbours, by Gauss–Seidel sweeps (each equation of the system, solved for its own pixel):

x = y
repeat sweeps times:
    for every pixel p, row by row:
        x[p] = (y[p] + λ · Σ over neighbours q of x[q]) / (1 + λ · number of neighbours)

The checks: a one-row image gives the result of C2, and the mean stays the same.

C5. tv_2d(y, λ, iterations): C3 for an image, with one z for every horizontal pair and one for every vertical pair, and the step \tfrac18 instead of \tfrac14. The checks: B3(a) as a one-row image, and a bright 4 \times 4 square that stays flat and sharp but is lowered by \lambda \cdot (\text{perimeter}/\text{area}) = \lambda.

Then cargo run -p ising -- gmrf and open the pictures in out/gmrf/. The program smooths a noisy profile like the one of the demo (step, ramp, narrow peak, noise \sigma_n = 0.3) and plots data (grey), truth (green) and estimate (orange); then it smooths the micrograph with noise.

C6. Read the table for the quadratic prior: which \lambda has the smallest error, and what happens to the peak as \lambda grows? Compare with TV at \lambda = 1. Then compare the peak heights of TV at \lambda = 1, 2, 3 with the rule 2\lambda/w of B4(b).

C7. Look at quadratic-10.png, tv-1.png and tv-3.png. Describe the step, the ramp and the plateaus in each.

C8. Compare quadratic-2d.png and tv-2d.png with noisy.png, and the printed errors. What does each do to the nuclear envelope, and to the flat parts of the cell?

The model solution is ising/src/gmrf/solution.rs in the download.

C6. The noisy data have an RMSE of 0.298. For the quadratic prior the error is smallest near \lambda = 1.5 (0.194); at \lambda = 10 it is 0.242 and the peak (height 2) is only 0.92 high. Raising \lambda removes more noise but blurs more, and no \lambda wins both. TV at \lambda = 1: 0.129, with the peak at 1.40. TV peak heights 1.40, 0.90, 0.40 for \lambda = 1, 2, 3; the rule 2 - 2\lambda/4 predicts 1.5, 1.0, 0.5: the same steps of 0.5, each a little lower (noise, and the background next to the peak rises too).

C7. Quadratic (\lambda = 10): smooth everywhere; the step is a ramp several samples wide, and the peak a low bump. TV (\lambda = 1): the step is one sharp jump, the flat parts are flat, and the ramp is a staircase. TV (\lambda = 3): fewer, larger stairs; the plateau after the step and the peak lose contrast, and the error grows to 0.263.

C8. RMSE 0.100 (noisy), 0.085 (quadratic, \lambda = 2), 0.076 (TV, \lambda = 0.08). Quadratic smoothing removes the grain but blurs the thin dark nuclear envelope and all fine detail. TV keeps the envelope and the edges sharp, but turns flat parts into patches of constant grey (a cartoon look, the 2D version of the staircase).

Where this leads

The same two priors return when the image is also blurred: the deconvolution day adds a point-spread function to the data term (Tikhonov = quadratic, and TV). In 2D, TV denoising keeps object boundaries in microscopy images (TV flow runs it as a smoothing flow), and its binary cousin, the boundary length, is the smoothness term of graph cuts, of the Ising model and of the Chan–Vese level-set model. The quadratic system (I + \lambda L)\mathbf x = \mathbf y returns with seeds as the random walker (day 29).