Exercise: Fourier transform & basis functions
Goal
By the end of this exercise you should be able to:
- describe a sinusoid by its frequency, amplitude, and phase, and read those off a picture,
- explain in your own words why the Fourier transform is a change of basis, and why it is reversible,
- explain why sinusoids of different frequencies form an orthogonal basis, and how that lets each amplitude be read off as a projection,
- contrast the fixed Fourier basis with the data-driven PCA basis, and say when each is appropriate,
- reason about what a spectrum shows, and how low-pass / high-pass / notch filtering and compression act on it,
- read a small
fft()output in R and interpret the magnitude spectrum.
This is an appreciation exercise. It builds conceptual fluency and light intuition — there is no by-hand transform to grind through. Do the reasoning parts on paper first, then use the short R section to confirm the picture.
Background
A sinusoid is one pure wave, \(A\cos(2\pi f\,t + \varphi)\), set by three numbers: frequency \(f\) (cycles per unit), amplitude \(A\) (height), phase \(\varphi\) (starting point in the cycle).
The Fourier transform writes any signal as a sum of sinusoids and returns the amplitude and phase of every frequency — the recipe of waves. Equivalently, it re-expresses the signal from the standard basis (one coordinate per time point or pixel) into the Fourier basis (one coordinate per frequency). It is a change of basis: the same object in new coordinates, fully reversible via the inverse transform.
The Fourier basis works because sinusoids of different frequencies are orthogonal — treating whole signals as vectors, \(f \cdot g = \sum_t f(t)g(t) = 0\) for two different-frequency waves. So each frequency’s amplitude is a projection of the signal onto that wave, computed independently of the others — the same projection idea as reading off PCA scores.
Two families of use:
- Compression keeps the few large (usually low-frequency) coefficients and discards the rest — like truncating a PCA to its top components (JPEG uses the DCT, a Fourier relative).
- Filtering multiplies the spectrum by a mask and transforms back: low-pass smooths/denoises, high-pass sharpens, a notch removes one artefact frequency. This is fast because of the convolution theorem (convolution in space = multiplication in frequency).
Fixed vs learned basis: Fourier commits to sinusoids for every signal; PCA learns axes from the data’s covariance.
By hand (reasoning)
B1. Sketch (roughly) three sinusoids over one unit of time: (a) \(\cos(2\pi\cdot 1\cdot t)\), (b) \(\cos(2\pi\cdot 4\cdot t)\), (c) \(2\cos(2\pi\cdot 1\cdot t)\). How many cycles does each complete? Which pair differs only in amplitude, and which only in frequency?
B2. A signal is described as “mostly a slow smooth trend with a little fine texture on top.” Where does its energy sit in the spectrum — low frequencies, high frequencies, or both? Which part would a low-pass filter keep?
B3. Explain, in one or two sentences each, why the Fourier transform is (a) a change of basis and (b) reversible (no information lost).
B4. Two people record the same biological signal but one starts the recording a fraction of a second later. Which of the three sinusoid parameters — frequency, amplitude, phase — is most affected, and which are essentially unchanged? What does this tell you about why the magnitude spectrum (amplitudes only) is often more useful than the phase?
B5. For each task, say whether a fixed Fourier basis or a data-driven PCA basis is the more natural first choice, and why: (a) detecting a regular striation pattern in a muscle micrograph; (b) finding the main axes of variation in a gene-expression table (cells × genes); (c) removing a 50 Hz electrical hum from an electrophysiology trace; (d) summarising a large set of noisy spectra into a few components that capture most of the variance.
B6. A microscopy image has a faint, perfectly regular diagonal stripe artefact from the detector. In the 2D spectrum this appears as an isolated pair of bright dots. Describe how you would remove the artefact using the frequency domain, and name the filter type. What real structure might you accidentally damage, and how does that connect to the honesty caveat from the lecture?
B7. “Noise is high-frequency, so I’ll just delete all high frequencies and my image will be clean.” Give one reason this works reasonably well and one reason it can go wrong.
B8. (compression) An image’s Fourier coefficients are dominated by a handful of large low-frequency values; the rest are tiny. Explain the compression recipe in three steps, and state the analogy to truncating a PCA. Why is this lossy, and what artefact appears if you keep too few coefficients?
Explore: build a wave
The demo below adds up five waves, \(a_f \sin(2\pi f\,t)\) for \(f = 1, \dots, 5\) cycles per window, over one window \(0 \le t \le 1\). Each slider sets one amplitude \(a_f\) and has the same colour as its thin line in the plot; the bold black line is the sum. (A sine is a cosine with phase \(\varphi = -\pi/2\).) The bar chart shows the amplitude spectrum \(|a_f|\): the amount of each frequency, which is what the Fourier transform of the black curve gives back.
W1. Choose pure tone. How many cycles does the sum complete in the window, and what does the spectrum look like? Now set that slider to −1. What changes in the plot, and what changes in the spectrum? Which of the three sinusoid parameters (frequency, amplitude, phase) did the sign change?
W2. Start from all zero, set \(a_1 = 1\), then add \(a_3 \approx 0.33\) and finally \(a_5 = 0.2\) (or press square). Describe how the shape of the sum changes at each step. Roughly what height do the flat parts reach? Which frequencies would you have to add to make the edges steeper still?
W3. Press sawtooth and compare its spectrum with the one for square. Then change the signs of \(a_2\) and \(a_4\) to \(+1/2\) and \(+1/4\). What happens to the signal, and to the spectrum? (Compare with B4.) Finally, change only \(a_3\) to \(-1/3\). Does the signal still have the same shape? What information does the amplitude spectrum leave out?
W1. The pure tone is \(\sin(2\pi\cdot 2\cdot t)\): two cycles in the window, and a single bar at \(f = 2\) of height 1. With amplitude −1 the wave is flipped upside down, which is the same as sliding it half a cycle along: the phase changed by \(\pi\). Frequency and the height \(|a|\) are the same, so the amplitude spectrum does not change.
W2. \(a_1\) alone is one smooth swell. Adding the third harmonic flattens the tops and steepens the sides; adding the fifth flattens them further, with small ripples on the plateaus. The flat parts sit near \(\pm\pi/4 \approx \pm 0.79\) (that is the limit of \(\sin x + \tfrac13\sin 3x + \tfrac15\sin 5x + \dots\); with three terms the plateaus wiggle around this value). Steeper edges need higher odd harmonics: \(f = 7, 9, 11, \dots\) with amplitudes \(1/7, 1/9, \dots\). Sharp edges live at high frequencies.
W3. The square wave uses only the odd frequencies; the sawtooth uses all five, with heights \(1, 1/2, 1/3, 1/4, 1/5\). Flipping the signs of \(a_2\) and \(a_4\) gives the negative of the original sawtooth shifted by half a window: if the original is \(x(t)\), the new signal is \(-x(t + 1/2)\). A half-window shift alone multiplies each harmonic by \((-1)^f\), flipping the odd frequencies; the extra minus sign leaves the odd ones unchanged and flips the even ones. The amplitude spectrum is unchanged: both a time shift and an overall sign reversal change phases but preserve magnitudes. Flipping only \(a_3\) is not a shift: the signal gets a clearly different shape, yet the bars are still the same. The amplitude spectrum leaves out the phase of each wave (here only its sign), so different signals can share the same amplitude spectrum. The full Fourier transform keeps the phase too, which is why the signal can be rebuilt from it.
Explore: filter an image
The demo below is the lecture’s micrograph (a 256 × 256 crop). Left: the image; middle: its 2D spectrum, log of the magnitude, with frequency 0 in the centre; right: the image rebuilt from the coefficients you keep. Removed coefficients are shown dark red. The radial filters keep the coefficients whose distance \(r\) from the centre lies between a min radius and a max radius (the two blue circles; ∞ means no upper limit). The buttons are presets: low-pass sets min = 0, high-pass sets max = ∞, band-pass uses both. The box “keep average brightness (centre)” keeps the centre coefficient whatever the min radius is. The readout gives the share of coefficients kept, the share of the image’s variation they carry, and the RMS error of the rebuilt image (pixel values run from 0 to 1).
E1. Choose low-pass (min radius 0) and set the max radius to 5, 30 and 90. For each, note the percentage of coefficients kept and the percentage of the variation kept. What does that tell you about where the image’s content sits in the spectrum?
E2. Choose keep largest at 3%. Then go back to low-pass and find the max radius that also keeps about 3% of the coefficients. Which of the two has the smaller error? Look at where the kept coefficients lie in the spectrum in “keep largest” mode: why are the two results so similar?
E3. Choose high-pass (max radius ∞) with min radius 10. What is left of the cell? Why is the picture grey rather than black, although most of the low frequencies are gone? Untick keep average brightness (centre) to check your answer.
E4. Tick add stripe artefact and choose no filter: note the error. The stripe adds two bright coefficients to the spectrum, marked with yellow rings. Erase them by dragging over them. What happens to the error? Why are there two dots for one stripe? Then try removing the stripe with a low-pass filter instead, at max radius 15. Which approach is better here?
E5. Go back to low-pass with max radius 30, then raise the min radius from 0 to 5, so that only a ring between the two circles is kept. How many coefficients does that remove, and how much of the variation? What disappears from the image, and what is left? Compare with E1.
E1. Radius 5 keeps 0.12% of the coefficients but already 53% of the variation; radius 30 keeps 4.3% of the coefficients and 81% of the variation; radius 90 keeps 39% and 96%. A tiny disc of low frequencies carries most of the variation: the broad light and dark regions. The many high-frequency coefficients each carry little; together they make the fine detail (and the grain). This is why a frequency basis compresses natural images well.
E2. Keep largest 3%: 81% of the variation, RMS error 0.100. Low-pass with max radius 25 also keeps 3.0% of the coefficients: 78% of the variation, error 0.109. Keeping the largest coefficients is slightly better, because it picks the coefficients that matter for this image, while the disc is fixed in advance. They are similar because most of the largest coefficients are low frequencies anyway: in “keep largest” mode the kept coefficients crowd around the centre, with a scatter of single ones further out.
E3. Only edges and fine texture remain: the outline of the nucleus, the membranes, the grain inside the cell. Large uniform regions all become the same grey, because their brightness is low-frequency content. The picture stays grey because the centre coefficient (frequency 0, the average brightness of the whole image) is kept by the “keep average brightness” box, even though it lies inside the min radius. Untick the box and the average of the rebuilt image drops from 0.66 to 0: the values vary around 0, the negative half is shown as black (about half the pixels), and the RMS error jumps from 0.18 to 0.69.
E4. With the stripe and no filter the error is 0.106 (the stripe itself). The stripe is a single 2D wave, so it adds a single bright pair of coefficients, about 19 units from the centre (16 across, 10 down, and its mirror image). Erasing them brings the error down to about 0.02; zeroing exactly the two coefficients would give 0.002, the brush also removes a few of the cell’s own coefficients around them. There are two dots because a real-valued wave is the sum of a frequency and its mirror image (\(+k\) and \(-k\)), the same mirror symmetry as in the 1D spectrum in R (R2 below). A low-pass filter at max radius 15 also removes the stripe, but it removes the cell’s detail too: the error is 0.127, worse than leaving the stripe in. A notch removes exactly what you want to remove; a low-pass removes everything above a frequency.
E5. Raising the min radius from 0 to 5 removes very few coefficients: the kept share drops from 4.3% to 4.2% (only 68 of the 65 536 coefficients lie inside radius 5, not counting the centre, which is kept). But the variation kept drops from 81% to 29%, and the RMS error rises from 0.10 to 0.19. As in E1, the few lowest frequencies carry about half of the variation: they are the broad shading, such as the dark nucleus against the lighter cytoplasm. Without them the nucleus becomes the same mid grey as its surroundings, and what is left is structure of intermediate size: the outline of the nucleus, membranes and small organelles, but neither the overall shading (below the min radius) nor the fine grain (above the max radius). A band-pass picks out structures of one size range.
In R
Use R only to confirm the intuition above. This is illustrative static code — read it and predict the output before you would run it.
Build a signal and look at its spectrum
# a signal: a slow 3-cycle wave + a smaller fast 20-cycle wave + noise
set.seed(1)
n <- 256
t <- (0:(n - 1)) / n # n equally spaced samples; frequency k is FFT bin k
x <- sin(2*pi*3*t) + 0.5*sin(2*pi*20*t) + rnorm(n, sd = 0.2)
X <- fft(x) # discrete Fourier transform -> complex numbers
mag <- Mod(X) # magnitude = amount of each frequency
mag <- mag[1:(n/2 + 1)] # keep DC through Nyquist; negative frequencies mirror these
plot(mag, type = "h", xlab = "frequency index", ylab = "amplitude")
# expect two clear spikes: a tall one at R index 4 (frequency 3), another at index 21 (frequency 20)The transform is reversible
x_back <- Re(fft(X, inverse = TRUE) / length(X)) # inverse transform
max(abs(x - x_back)) # ~0 (tiny numerical error): the signal is recoveredA crude low-pass filter (denoising in the frequency domain)
X_lp <- X
keep <- 6 # keep only the lowest few frequencies
X_lp[(keep+1):(n-keep+1)] <- 0 # zero out the high-frequency middle band
x_lp <- Re(fft(X_lp, inverse = TRUE) / n)
# x_lp is a smoothed version of x: the fast 20-cycle wave and the noise are goneTasks
R1. In the first block, before looking: at which two frequency indices do you expect spikes, and which should be taller? (Match the amplitudes in the formula for x.)
R2. Why do we take Mod(X) rather than plotting X directly, and why do we keep mag[1:(n/2 + 1)] (DC through Nyquist)? (Two short reasons — one about complex numbers, one about symmetry.)
R3. In the low-pass block, predict what happens to x_lp if you increase keep from 6 to 30. Will it look more like the smooth trend or more like the original noisy signal? Explain in terms of which frequencies you are now keeping.
R4. Explain why the reconstruction block divides by length(X). (Base R’s fft() is unnormalised, so the round-trip picks up a factor of \(n\).)
Hints
The number in front of \(t\) inside \(\cos(2\pi f\,t)\) is the frequency \(f\) = cycles per unit time, so as \(t\) goes from 0 to 1 it completes exactly \(f\) cycles. The number multiplying the whole cosine is the amplitude (height). See the wave picture in the lecture, and R’s cos.
Low frequencies = slow, broad, smooth structure. High frequencies = fast, fine detail — sharp real edges and random noise both live here. That overlap is exactly why blunt high-frequency removal is imperfect.
A basis is a set of coordinate directions; changing basis re-expresses the same object in new coordinates. Standard basis: one coordinate per time point. Fourier basis: one coordinate per frequency. Reversible because the inverse transform exists — see fft with inverse = TRUE. Compare with the change-of-basis idea from Matrices as transformations and PCA.
Shifting when you start recording slides every wave along in its cycle — it changes the phase but leaves each wave’s frequency and amplitude intact. So the magnitude spectrum is invariant to a time shift, which is why amplitude-only summaries are often the robust choice.
Ask: do I expect structure at particular frequencies (rhythms, stripes, hums) → Fourier, a fixed basis. Or do I want axes that adapt to my dataset’s variation (expression tables, sets of spectra) → PCA, a learned basis. Both are orthogonal bases read off by projection.
A perfectly periodic artefact is localised in frequency (a few bright dots), so you can zero out just those frequencies — a notch (band-stop) filter — and transform back. The risk: any real structure at that same frequency is deleted too.
fft returns complex numbers; use Mod for amplitude and Arg for phase. For a real input the negative-frequency coefficients are the complex conjugates of the positive-frequency ones. For even n, keep indices 1:(n/2 + 1) to include both DC and Nyquist. The transform is unnormalised, so the inverse must be divided by the length. The spike height tracks the amplitude in the formula for x.
Solutions
B1. As \(t\) goes from 0 to 1: (a) \(\cos(2\pi\cdot1\cdot t)\) completes 1 cycle; (b) \(\cos(2\pi\cdot4\cdot t)\) completes 4 cycles; (c) \(2\cos(2\pi\cdot1\cdot t)\) completes 1 cycle but is twice as tall. So (a) and (c) differ only in amplitude (same frequency, different height); (a) and (b) differ only in frequency (same height, different number of cycles).
B2. A slow smooth trend is low-frequency; the fine texture on top is high-frequency. So the energy sits mostly at low frequencies with a small high-frequency contribution — both, but dominated by the low end. A low-pass filter keeps the low frequencies, i.e. it keeps the smooth trend and removes the fine texture.
B3. (a) Change of basis: the signal is one object; in the standard basis its coordinates are its values at each time point (one axis per time point), and the Fourier transform re-expresses the same object in the Fourier basis, where the coordinates are the amounts of each frequency (one axis per frequency). Nothing but the coordinate system changed. (b) Reversible: the Fourier basis is a complete orthogonal basis, so the transform is an invertible change of coordinates — the inverse Fourier transform reconstructs the original signal exactly, so no information is lost.
B4. Starting the recording later slides every constituent wave along in its cycle, which changes the phase of every frequency. The frequencies present and their amplitudes are unchanged (the same waves are there, equally strong). Therefore the magnitude spectrum (amplitudes only) is unaffected by when you started recording, while the phase spectrum is. That shift-invariance is a big reason amplitude-only summaries are often preferred for comparing signals.
B5. (a) Fourier — a regular striation is periodic, so it appears at a specific spatial frequency; a fixed sinusoid basis is the natural detector. (b) PCA — you want axes that adapt to the data’s own directions of variation; there is no reason expression variation should align with fixed sinusoids. (c) Fourier — a 50 Hz hum is a single frequency; a notch filter in the frequency domain removes it cleanly. (d) PCA — “capture most of the variance in a few components” is exactly what a learned, data-driven basis does.
B6. Transform the image to the 2D frequency domain, locate the isolated bright dots produced by the periodic stripe, set those coefficients (a small band around them) to zero — a notch / band-stop filter — then apply the inverse transform to get the cleaned image. Risk: if any genuine image structure happens to sit at that same spatial frequency, it is removed along with the artefact. This is the lecture’s honesty caveat — filtering in frequency space cannot distinguish “artefact at frequency \(f\)” from “real signal at frequency \(f\)”, so it is always a trade-off.
B7. Works reasonably well because random noise really is spread across high frequencies, so cutting them removes a lot of noise. Can go wrong because sharp real edges and fine true detail are also high-frequency, so a blunt cut blurs genuine structure along with the noise. A frequency mask cannot tell noise from real detail when both sit at the same frequencies, so filtering is always a trade-off between removing noise and keeping detail.
B8. Three-step compression recipe: (1) transform the image to the frequency domain; (2) keep only the largest / lowest-frequency coefficients and discard the many small ones; (3) transform back (or store the kept coefficients and reconstruct on demand). This is the same idea as truncating a PCA to its top components — represent the data in a smart basis, then keep only the coordinates that carry most of the signal. It is lossy because the discarded coefficients held some (small) real information; keep too few and you lose real high-frequency content, producing visible blocky / blurred artefacts (in JPEG, block boundaries become visible because the DCT is applied on small blocks).
R1. The spikes are at frequencies 3 and 20. In this one-based R vector they appear at indices 4 and 21, because index 1 is the zero-frequency (DC) term. The frequency-3 spike is taller, because that component has amplitude 1 versus 0.5 for the frequency-20 component. The noise contributes a low, roughly flat floor across all frequencies.
R2. We take Mod(X) because fft() returns complex numbers (real + imaginary parts encoding amplitude and phase); Mod() extracts the amplitude, which is what we want to see. For a real input with even length n, we keep mag[1:(n/2 + 1)]: this includes the zero-frequency (DC) and Nyquist bins as well as the positive frequencies. The remaining negative-frequency coefficients are complex conjugates of their positive-frequency partners, so their magnitudes are redundant. Magnitudes alone still omit phase; reconstruction needs the complex coefficients.
R3. Raising keep from 6 to 30 keeps more of the higher frequencies. At keep = 6 you keep only the slowest components, so x_lp is a very smooth curve close to the 3-cycle trend. At keep = 30 you now also retain the 20-cycle component (and more of the noise band), so x_lp looks more like the original noisy signal — less smoothing. More kept frequencies = less aggressive low-pass = closer to the original.
R4. Base R’s fft() is unnormalised: fft() followed by fft(..., inverse = TRUE) returns the original signal multiplied by n = length(X). Dividing by length(X) cancels that factor so the reconstruction matches the original signal, up to tiny floating-point error.
Where this leads
- PCA (earlier this week): the data-driven counterpart to Fourier — instead of fixing the basis to sinusoids, it learns the orthogonal axes from the data’s covariance. Both are “represent in an orthogonal basis, then keep the coordinates that matter.”
- Polar coordinates: measuring a ring (week 1):
Mod()andArg()are the distance \(r\) and angle \(\theta\) of each coefficient; that unit used the same polar coordinates on an image, as an example of a useful but nonlinear transformation. - Chemometrics: spectra (mass, IR, Raman) are signals in frequency/wavelength; Fourier methods, filtering, and PCA of spectra are everyday tools there.