Signal processing, from first principles to working practice
Sixty-two modules covering the whole roadmap. Every figure on this page is computed live in your browser from the controls beneath it — nothing here is a picture of a result, it is the result. Move a slider and the mathematics runs again.
How the modules are built
Each module follows the same shape: a short explanation of what the idea is and why anyone bothered inventing it, one or more interactive panels where you can break it, the formulas with every symbol defined, and a few questions to check that the idea landed rather than just the words.
The bench at the top of the screen
Two parameters follow you everywhere: the sampling rate fs and the record length N. Nearly every quantity in digital signal processing is derived from those two numbers, and the strip at the top shows the derivations updating as you work: the Nyquist frequency fs/2, the bin spacing Δf = fs/N, and the record duration T = N/fs. Change the sampling rate in the sampling module and the FFT module inherits it.
One signal, threaded through the course
Rather than a new toy example every module, most panels analyse the same synthetic measurement: an accelerometer on a gearbox test rig. It is deliberately awkward. It contains a shaft rotation and its harmonics, a gear mesh tone with sidebands, a bearing fault that rings after each impact, mains pickup, a slow thermal drift, and broadband noise. It is the signal the roadmap's closing section asks you to be able to analyse, and by the end of these modules you will have taken it apart with every tool here.
Every number printed under a panel was computed by the code running in this page. Where a result should match a textbook value — window figures of merit against Harris (1978), quantisation noise against 6.02N + 1.76 dB, Savitzky–Golay coefficients against the published tables — it was checked against that value during the build. Where a method is an approximation, the panel says so.
Suggested order
The stages in the left rail run in dependency order, and the roadmap's own recommended progression is built into them. If you are short of time, the Core path button in the rail hides everything except the modules that later ones actually depend on. That leaves twenty-six modules which take you from "what is a signal" to a defensible spectral analysis with a designed filter.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010 — the standard graduate reference, and the source of most conventions used here
- Lyons, Understanding Digital Signal Processing, 3rd ed., Prentice-Hall, 2010 — the best practical companion, strong on the things that trip people up
- Smith, The Scientist and Engineer's Guide to Digital Signal Processing, 1997 — free online, and unmatched on intuition
- Harris, "On the use of windows for harmonic analysis with the discrete Fourier transform", Proc. IEEE 66(1), 1978 — every window figure in this trainer is checked against it
- Bendat & Piersol, Random Data: Analysis and Measurement Procedures, 4th ed., Wiley, 2010 — the authority on estimator uncertainty
- Every module carries its own Sources list; the numerical results in each panel are computed live and were verified against the published values in these works
What a signal is
A signal is a measurable quantity that carries information about how something is behaving. The mathematics does not care whether the quantity is a voltage, a pressure, a temperature or a share price.
Formally a signal is a function: it maps an independent variable onto a value. Almost everything else in this course follows from asking two questions about that function — is the independent variable continuous or discrete, and is the value continuous or discrete?
The independent variable need not be time
Time is the usual one, written x(t). But a signal can equally be a function of space (the intensity along a line of a photograph), of two spatial coordinates (an image, I(x,y)), of frequency (a spectrum), of angle, or of sample index. Every technique here transfers: a spatial low-pass filter blurs an image for exactly the reason a temporal low-pass filter smooths a noisy measurement, and spatial aliasing produces moiré patterns for exactly the reason temporal aliasing produces a wagon wheel that turns backwards.
The notation matters and is worth being pedantic about early: round brackets mean a continuous argument, square brackets mean an integer index. x(0.5) is a legitimate question; x[0.5] is not, because there is no sample at index one half. Interpolation is the process of inventing an answer to that illegitimate question, and module 45 is about how honest that invention is.
Discrete-time is not the same as digital
A discrete-time signal is sampled in time but its values may still be real numbers of unlimited precision. A digital signal is discrete in both axes: sampled in time and quantised in amplitude. The distinction is not pedantry — sampling and quantisation cause different problems, are analysed with different mathematics, and are fixed by different means. Sampling too slowly causes aliasing, which is irreversible and is treated in module 15. Quantising too coarsely adds noise, which is tolerable and is treated in module 16.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., Prentice Hall, 1997 — chapter 1 for the definitions and notation used here
- Lyons, Understanding Digital Signal Processing, 3rd ed., Prentice Hall, 2010 — the practical framing of discrete versus digital
Classifying signals
The classifications are not taxonomy for its own sake. Each one tells you which tools are legal to use, and several classic mistakes are simply the use of a tool on a signal of the wrong class.
| Class | Test | Why it matters |
|---|---|---|
| Deterministic | Future values are exactly predictable from a rule | Can be described by a formula; averaging repeated trials converges to the signal itself |
| Random | Described only by statistics | You must talk about power spectral density, not spectrum; module 21 |
| Periodic | x(t) = x(t + T) for some T > 0 | Has a Fourier series: a line spectrum at harmonics of 1/T |
| Aperiodic | No such T exists | Has a Fourier transform: a continuous spectrum |
| Even | x(−t) = x(t) | Purely real Fourier transform |
| Odd | x(−t) = −x(t) | Purely imaginary Fourier transform |
| Energy | 0 < E < ∞, so P = 0 | Transients, pulses. Talk about energy, and energy spectral density |
| Power | E = ∞ but 0 < P < ∞ | Sinusoids, noise, anything that runs forever. Talk about power, and PSD |
| Causal | x(t) = 0 for t < 0 | Physically realisable as a response starting at an event |
| Real / complex | Values real, or in ℂ | Real signals have conjugate-symmetric spectra, so half the spectrum is redundant; module 38 |
Every signal splits into an even and an odd part
This decomposition is not a curiosity — it is why the Fourier transform of a real signal has a real part that comes entirely from the even content and an imaginary part that comes entirely from the odd content.
"Periodic" is a much stronger claim than "repetitive". A sum of two sinusoids is periodic only if the ratio of their frequencies is rational. 27.5 Hz and 50 Hz give a period of 0.4 s because 11:20 is a ratio of integers. 27.5 Hz and 50√2 Hz never repeat at all, and the resulting signal has no Fourier series, only a transform. Real machinery running against mains-locked equipment is full of this.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §1.2 for signal classes and the even/odd decomposition
- Papoulis, Probability, Random Variables and Stochastic Processes, 4th ed., McGraw-Hill, 2002 — the deterministic/random boundary
Signal operations
Five operations account for most of what is ever done to a signal before it reaches a system: scale the amplitude, add signals, shift in time, scale time, and multiply signals together.
The order of operations is where mistakes happen. In x(a(t − t0)) the shift is applied to t before scaling, so the feature that was at t = 0 in the original appears at t = t0 in the result regardless of a. Written the other way, x(at − t0), the same feature appears at t0/a. The panel below applies them in the bracketed order and draws the reference feature so you can watch where it lands.
Why multiplication deserves its own module
Adding two signals puts both spectra side by side. Multiplying two signals does something far more interesting: it moves them. Multiplying by a sinusoid shifts a spectrum bodily up and down the frequency axis, which is what modulation, mixing and heterodyning all are (module 39). Multiplying by a finite-length window is what every practical FFT does whether you asked for it or not, and it convolves the true spectrum with the window's own spectrum — the origin of spectral leakage (module 18).
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §1.2.1 on transformations of the independent variable
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — the practical consequences of multiplication
Elementary signals
A dozen standard signals appear again and again, both as building blocks and as test inputs. Recognising them on sight, and knowing their transforms, removes a surprising amount of work later.
The impulse, and the property that makes it useful
The continuous-time impulse δ(t) is not a function in the ordinary sense. It is defined by what it does inside an integral: it has zero width, infinite height, unit area, and it picks out the value of whatever it multiplies. That is the sifting property, and it is the single most useful identity in the subject.
The discrete version is much better behaved: δ[n] is an ordinary sequence, equal to one at n = 0. The sum above says any sequence is a sum of shifted, scaled impulses — which is precisely the observation that leads to convolution in module 08.
The sinc function is the Fourier transform of a rectangular pulse, and rectangles are everywhere: a finite recording is a rectangular window on an infinite signal, a zero-order-hold DAC output is a train of rectangles, an ideal brick-wall filter is a rectangle in frequency. Every time you meet a rectangle in one domain, expect a sinc in the other — and expect its side lobes to cause trouble.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §1.4 on the unit impulse and step
- Bracewell, The Fourier Transform and Its Applications, 3rd ed., McGraw-Hill, 2000 — the definitive treatment of δ, sinc and rectangle functions
Energy, power and the numbers that describe amplitude
"How big is this signal" has at least five defensible answers, and choosing the wrong one is a common source of disagreement between two people looking at the same data.
An energy signal has finite energy and therefore zero average power — every transient, impact and pulse. A power signal has infinite energy but finite average power — every sinusoid, every noise process, every steady machine vibration. No signal is both, and the classification decides whether you should be plotting an energy spectral density or a power spectral density.
Crest factor: the number that catches clipping
The ratio of peak to RMS is the single most useful diagnostic in the list. A pure sine has a crest factor of exactly √2 (3.01 dB). Gaussian noise sits around 3 to 4 depending on record length. A bearing fault, which is a train of sharp impacts sitting on top of a smooth vibration, pushes it well above that — which is why crest factor is a standard condition-monitoring feature. And a signal that has been clipped by the ADC has its crest factor squashed towards 1, which is how you detect clipping without ever looking at the raw trace.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §1.1.2 energy and power definitions
- Randall, Vibration-based Condition Monitoring, Wiley, 2011 — crest factor and kurtosis as fault indicators
What a system does, and the six questions to ask about it
A system maps an input signal to an output signal. Six properties decide which analytical tools are available to you — and if two of them hold, an enormous amount follows for free.
The six properties
Linearity is two conditions at once. Additivity: the response to a sum is the sum of the responses. Homogeneity: scaling the input scales the output by the same factor. Together they give superposition, which is what lets you decompose an input into simple pieces, process them separately, and add the answers.
Time invariance means the system does not care when you apply the input: delay the input and the output is delayed by the same amount, otherwise unchanged. A filter with fixed coefficients is time invariant; an adaptive filter, by design, is not. Causality means the output at any instant depends only on present and past inputs — mandatory for anything running in real time, optional for offline processing (module 48). BIBO stability means every bounded input produces a bounded output. Memory: a memoryless system's output depends only on the input at the same instant; anything with memory holds state. Invertibility: distinct inputs give distinct outputs, so the input can in principle be recovered.
Trying one or two inputs proves nothing. y = x + 1 passes the additivity test for the specific input x = 0, and y = x² passes homogeneity for a = 1. A single counter-example disproves linearity; no finite number of successes proves it. The systematic route is to check the definition symbolically — or, in practice, to check whether the operation involves anything other than sums of scaled, delayed copies of the input and output.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §1.6 system properties with worked counter-examples
- Proakis & Manolakis, Digital Signal Processing, 4th ed., Pearson, 2006 — §2.2, the discrete-time treatment
Linear time-invariant systems
If a system is both linear and time invariant, one measurement characterises it completely and for ever: its response to a single impulse.
The argument is three lines long and is worth following, because everything else in the course rests on it. Any input can be written as a sum of shifted, scaled impulses (module 04). Time invariance says the response to a shifted impulse is a shifted impulse response. Linearity says the response to the sum is the sum of the responses. Therefore:
That is convolution, and module 08 is devoted to it. The point here is what it means: h completely determines the system. Measure it once and you can predict the response to any input whatsoever, without ever knowing what is inside the box.
Three faces of the same information
The impulse response, the step response and the frequency response are three views of one object. The step response is the running integral of the impulse response (because the step is the running integral of the impulse, and the system is linear). The frequency response is the Fourier transform of the impulse response. Measuring whichever is most convenient gives you the other two.
Why sinusoids, and not some other family
Feed a complex exponential into an LTI system and the output is the same complex exponential, scaled by a complex constant. The frequency is untouched. No other family of signals has this property for all LTI systems — sinusoids are the eigenfunctions of LTI systems, and the complex constant is the eigenvalue.
This is the entire justification for frequency-domain thinking. An LTI system cannot create a frequency that was not in its input — it can only change the amplitude and phase of what was already there. If you see a new frequency at the output of a supposedly linear system, the system is not linear, and that observation is a standard diagnostic (module 44 on harmonic distortion).
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — chapter 2, the derivation of convolution from LTI properties; §3.2 on eigenfunctions
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — impulse, step and frequency response as practical measurements
Convolution
Flip one signal, slide it across the other, and at every position multiply and add. That is the whole operation — and it is what every linear filter physically does.
Doing it graphically
The four steps never change: reflect h about the origin, shift it to position n, multiply point by point with x, and sum the products. The slider below moves n; the shaded area is the product being summed, and its total is the single output value plotted at that n. Work through it once by hand and you will never need to again.
The properties, and why they are useful
| Property | Statement | What it buys you |
|---|---|---|
| Commutative | x * h = h * x | Either signal may be the one you flip — flip the shorter one |
| Associative | (x * h₁) * h₂ = x * (h₁ * h₂) | A cascade of filters is one filter, whose impulse response is the convolution of the parts |
| Distributive | x * (h₁ + h₂) = x*h₁ + x*h₂ | Parallel paths add; a filter bank can be analysed branch by branch |
| Identity | x * δ = x | The impulse is the "do nothing" system |
| Shift | x * δ[n−d] = x[n−d] | A pure delay is convolution with a shifted impulse |
The result that changes how you work
Filtering is therefore a choice of viewpoint. In the time domain the filter slides a kernel along the data; in the frequency domain it multiplies the spectrum by a gain curve. They are the same operation. The practical consequence is computational: convolving two long signals directly costs order N·M operations, while transforming, multiplying and transforming back costs order N log N. Module 51 covers where the crossover sits and how overlap-add handles continuous streams.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — §2.1–2.3, graphical convolution and its properties
- Smith, The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing, 1997 — chapters 6–7, the clearest visual treatment available
Frequency-domain thinking
The same signal, described two ways. Neither description is more true than the other, but for any given question one of them is usually much easier.
The time domain answers questions about when: when did the impact occur, how long did the transient last, what is the peak value. The frequency domain answers questions about what: what is rotating, at what rate, and which resonance is being excited. A signal that looks like meaningless hash in time can be three clean lines in frequency, and a spectrum that looks featureless can hide an obvious event in time.
The vocabulary
| Term | Meaning |
|---|---|
| DC component | The zero-frequency term: the mean value of the signal |
| Fundamental | The lowest frequency of a periodic signal; its reciprocal is the period |
| Harmonics | Integer multiples of the fundamental. Produced by any periodic non-sinusoidal shape, and by non-linearity |
| Spectral magnitude | How much of each frequency is present |
| Spectral phase | The relative timing of each frequency. Discard it and you can no longer reconstruct the signal |
| Bandwidth | The width of the frequency range that carries the signal, by some stated definition (−3 dB, −20 dB, 99 % power) |
| Frequency resolution | The smallest separation of two tones you can still tell apart: Δf = 1/T, set by record duration |
It is tempting to look only at magnitude spectra, because that is what most instruments display. But magnitude alone does not determine a signal: two records with identical magnitude spectra and different phase can look completely different in time — one a clean impulse, the other a diffuse rumble of the same total energy. Phase carries the timing, and therefore the shape. Module 34 on group delay and module 60 on phase unwrapping treat it properly.
- Smith, The Scientist and Engineer's Guide to DSP, 1997 — chapters 8–10 on interpreting spectra
- Bracewell, The Fourier Transform and Its Applications, 3rd ed., 2000 — the duality of the two descriptions
Fourier series
Any reasonable periodic signal is a sum of sinusoids at integer multiples of its fundamental frequency. The coefficients tell you how much of each.
The complex form is not a different theory, it is the same theory written more compactly — one complex coefficient per harmonic instead of two real ones, and negative frequencies carrying the conjugate half. Every result later in the course is stated in the complex form, so it is worth becoming comfortable with it now.
Building waveforms from harmonics
The classic three shapes each have a characteristic harmonic signature, and recognising them in a real spectrum is a genuinely useful skill: odd harmonics only with 1/n amplitudes means a square wave somewhere in the chain; odd harmonics with 1/n² means a triangle; all harmonics with 1/n means a sawtooth.
Gibbs phenomenon
Add more harmonics to a square wave and the approximation improves everywhere except at the discontinuity, where an overshoot of about 9 % of the step height stubbornly refuses to shrink. It gets narrower as harmonics are added but never shorter. This is not a numerical artefact — it is what a truncated series does at a jump, and it is the same effect that produces ringing at the edges of a sharply filtered signal, and overshoot around impulsive events in filtered data.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — chapter 3, including the convergence conditions and Gibbs
- Bracewell, The Fourier Transform and Its Applications, 3rd ed., 2000 — series as a special case of the transform
The continuous Fourier transform
Let the period of a Fourier series go to infinity and the discrete harmonics merge into a continuum. The result applies to any signal, periodic or not.
The pairs worth memorising
Six transform pairs cover most of what you will meet. The panel lets you vary the width of each and watch the other side respond — always in the opposite direction, which is the reciprocal spreading principle: narrow in time is wide in frequency.
The properties, and what each one is used for
| Property | Statement | Used for |
|---|---|---|
| Linearity | ax₁+bx₂ ⟷ aX₁+bX₂ | Decomposing complicated signals |
| Time shift | x(t−t₀) ⟷ X(f)e−j2πft₀ | A delay is a linear phase ramp — the basis of time-delay estimation, module 60 |
| Frequency shift | x(t)ej2πfct ⟷ X(f−fc) | Modulation and mixing, module 39 |
| Time scaling | x(at) ⟷ (1/|a|)X(f/a) | Speeding a signal up spreads its spectrum; Doppler, module 57 |
| Differentiation | dx/dt ⟷ j2πf·X(f) | Explains why differentiating amplifies high-frequency noise, module 34 |
| Integration | ∫x dt ⟷ X(f)/(j2πf) + ½X(0)δ(f) | Converting acceleration to velocity — and why DC offset ruins it |
| Duality | If x(t) ⟷ X(f), then X(t) ⟷ x(−f) | Every pair gives you a second pair free |
| Convolution | x*h ⟷ X·H | Filtering, module 08 |
| Parseval | ∫|x(t)|²dt = ∫|X(f)|²df | Energy is conserved between domains — the check that your FFT scaling is right |
- Bracewell, The Fourier Transform and Its Applications, 3rd ed., 2000 — the standard reference for pairs and properties
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — chapter 4
The Laplace transform
Generalise the Fourier transform by letting frequency become complex. You gain the ability to describe growth and decay, and with it a clean account of stability.
That last proviso is the whole reason the Laplace transform exists. A growing exponential has no Fourier transform — the integral does not converge. It does have a Laplace transform, valid in the region of the s-plane where e−σt decays fast enough to win. The region of convergence is part of the answer, not a footnote: the same algebraic expression can describe a stable causal system or an unstable anticausal one, and only the ROC distinguishes them.
Transfer functions, poles and zeros
The geometry is the intuition. To find the frequency response at some frequency ω, stand at the point s = jω on the imaginary axis and measure the distances to every pole and every zero. The gain is the product of the zero distances divided by the product of the pole distances. Move close to a pole and the gain rises — that is a resonance. Move close to a zero and it falls — that is a notch. The panel below draws those distances as you drag the poles.
Laplace is the natural language of analog filters and of control systems, and it is how analog prototypes are specified before being converted to digital by the bilinear transform (module 31). It also gives the cleanest account of what a resonance is: a lightly damped pole pair, whose distance from the imaginary axis sets the sharpness and whose height sets the resonant frequency. The digital counterpart, the z-transform in module 29, is the same picture on a different map.
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — chapter 9, including the role of the region of convergence
- Franklin, Powell & Emami-Naeini, Feedback Control of Dynamic Systems, 7th ed., Pearson, 2015 — pole locations and transient behaviour
Sampling theory
Sampling replaces a continuous signal with a list of numbers. The remarkable result is that under one condition, nothing is lost — the continuous signal can be reconstructed exactly.
The Nyquist frequency is a property of your sampling: half the sample rate. The Nyquist rate is a property of your signal: twice its highest frequency. You sample above the Nyquist rate, and the result is a Nyquist frequency above your signal's content. Note also that the theorem's inequality is strict — sampling a 100 Hz sine at exactly 200 Hz can land every sample on a zero crossing and recover nothing.
What sampling does in the frequency domain
Sampling multiplies the signal by an impulse train. Multiplication in time is convolution in frequency, and the transform of an impulse train is another impulse train — so the spectrum is replicated at every multiple of fs. If the replicas do not overlap, a low-pass filter can isolate the original and the signal is recovered exactly. If they do overlap, the overlapping parts add together and are permanently indistinguishable. That overlap is aliasing.
The theorem as usually stated assumes the signal occupies 0 to fmax. What actually matters is that the replicas do not overlap, and a signal occupying 90–100 MHz has a bandwidth of only 10 MHz. Such a signal can be sampled at rates far below 2×100 MHz provided the replicas land cleanly — deliberate, controlled aliasing. That is bandpass sampling, module 53.
- Shannon, "Communication in the presence of noise", Proc. IRE 37(1), 1949 — the original statement
- Oppenheim & Willsky, Signals and Systems, 2nd ed., 1997 — chapter 7, the impulse-train derivation used here
Aliasing
A frequency above the Nyquist limit does not disappear. It reappears somewhere else, indistinguishable from a genuine signal, and no amount of later processing can remove it.
Two sinusoids whose frequencies differ by a multiple of fs produce identical samples. Not similar — identical. The information needed to tell them apart was never recorded. This is why an anti-aliasing filter must be analog and must sit before the ADC: once the samples exist, it is too late.
The roadmap's sampling experiment
Roadmap project 2 asks you to sample a 100 Hz sinusoid at 1000, 300, 210, 150 and 90 Hz and observe what happens. The table below runs it. Note 210 Hz: comfortably above the Nyquist rate of 200 Hz, and the result is correct but visually unconvincing — only 2.1 samples per cycle. Correct sampling and useful-looking sampling are different standards.
Aliasing in other independent variables
Sample space too coarsely and you get spatial aliasing: moiré patterns in a photograph of a striped shirt, jagged edges in an undersampled render, and — in sensor arrays — an ambiguity about which direction a wave arrived from, because the array elements sample the wavefront in space. Sample time too coarsely with a camera and a rotating propeller appears stationary or turns backwards. It is one phenomenon.
1. Analog low-pass filter before the ADC, with its stopband starting below fs/2. This is the only real defence. 2. Sample considerably faster than you need, which relaxes the filter's transition band (module 52). 3. Know your sensor's bandwidth — a sensor that physically cannot respond above 500 Hz provides some anti-aliasing for free, but check the specification rather than assuming it.
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — §2.4, the folding diagram
- Smith, The Scientist and Engineer's Guide to DSP, 1997 — chapter 3
Analog-to-digital conversion
Four stages, each with its own failure mode: filter, sample, hold, quantise.
Quantisation
An N-bit converter has 2N levels spread across its input range. The step size and the resulting noise follow immediately:
The 6.02 dB per bit is worth internalising: each extra bit halves the step and buys 6 dB. But the 1.76 dB assumes a sine filling the whole range. A signal using only a tenth of the range loses 20 dB of that, which is why input gain staging matters as much as converter resolution. A 16-bit converter used across 5 % of its range delivers roughly the performance of a 12-bit one.
Saturation and clipping
Exceed the input range and the converter simply stops following. The flat tops that result are not a gentle distortion — they are a discontinuity in the slope, and they generate harmonics across the entire spectrum. Clipped data cannot be repaired, and analysis of it produces confident, wrong answers. Detect it by checking for repeated extreme values, or by watching the crest factor collapse (module 05).
Two habits catch most converter problems before they reach the analysis. First, record and check the fraction of samples at the extreme codes — anything above a handful in a long record means clipping. Second, plot a histogram of the raw integer codes: a healthy record fills the range smoothly, while a stuck bit, a missing code or an over-ranged input all show up immediately as structure that should not be there.
- Kester (ed.), The Data Conversion Handbook, Analog Devices / Newnes, 2005 — the standard practical reference
- Widrow & Kollár, Quantization Noise, Cambridge, 2008 — when the uniform-noise model holds and when it does not
Digital-to-analog conversion and reconstruction
Getting back out is not simply the reverse of getting in. The staircase a DAC produces is not the original signal, and two corrections are needed.
A practical DAC holds each sample value until the next one arrives — a zero-order hold. That staircase contains the wanted signal plus images: copies of the spectrum centred on every multiple of fs, which were always there in the sampled representation and are now radiated into the analog world unless removed. It also imposes a gentle low-pass tilt, because holding a value for Ts is convolution with a rectangle of width Ts, and that is a sinc in frequency.
So a complete reconstruction path needs a reconstruction filter to suppress the images, and often a sinc-compensation stage — a mild high-frequency boost — to undo the droop. Oversampling makes both jobs much easier by pushing the first image far away from the wanted band, which is why audio converters run at many times the nominal rate internally.
- Kester (ed.), The Data Conversion Handbook, 2005 — reconstruction, images and sinc compensation
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — §10 on sample-rate conversion and imaging
The discrete Fourier transform
N samples in, N complex numbers out. Each output is the correlation of your data with one complex exponential.
Negative frequencies and the two-sided spectrum
The second half of the output, bins N/2+1 to N−1, represents negative frequencies. For real input these are the complex conjugates of the first half and carry no new information, which is why instruments show a one-sided spectrum with the amplitudes doubled. For complex input — IQ data from a radio or radar receiver — the two halves are genuinely different, and discarding one destroys the ability to tell an upward Doppler shift from a downward one (module 38).
DFT and FFT are not the same kind of thing
The DFT is a mathematical transform: a definition. The FFT is an algorithm for computing it quickly, by exploiting the symmetry of the exponentials to reduce the cost from N² to N log₂N operations. The answers are identical. For N = 4096 the saving is a factor of about 340; for N = 1048576 it is nearly 90 000, which is the difference between practical and impossible.
Getting amplitudes right
Raw FFT output is not in engineering units. To read a sinusoid's amplitude off the plot you must divide by N, double for the one-sided spectrum, and divide by the window's coherent gain. Miss any of those and you will be out by a factor of two, N, or 2.3 — module 19 covers the window correction and module 61 the full estimation procedure.
- Cooley & Tukey, "An algorithm for the machine calculation of complex Fourier series", Math. Comp. 19, 1965
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — chapters 3–4, the clearest account of DFT scaling conventions
Spectral leakage
The DFT assumes your record repeats for ever. When the ends do not match, it sees a discontinuity that was never in the signal — and reports the frequencies needed to make one.
The transform of an N-sample record is exactly the transform of an infinite signal formed by joining copies of that record end to end. If the record happens to contain a whole number of cycles, the joins are seamless and the tone lands exactly in one bin. If it does not, each join is a step change, and the spectrum acquires the broadband content of a step: energy smeared across every bin.
Integer-cycle recording works only when you know the frequency in advance and control the sample clock — order tracking on a machine with a tachometer can do it, and it is genuinely the best answer where it is available. But a real record contains many frequencies at once and cannot be integer for all of them, so leakage is the normal case and windowing is the standard mitigation. Module 20.
What leakage costs you
Two things. First, amplitude error: a tone falling between bins is split between neighbours and its peak reads low — up to 3.92 dB low with no window, which is the worst-case scalloping loss. Second, masking: the skirts of a strong component bury weak ones nearby. A −13 dB first side lobe means a component 20 dB down and a few bins away is simply invisible. Window functions trade the first problem against the second.
- Harris, "On the use of windows for harmonic analysis with the discrete Fourier transform", Proc. IEEE 66(1), 1978 — the definitive treatment; all figures of merit in the next module follow its definitions
Window functions
Taper the ends of the record to zero and the periodic extension becomes continuous. The discontinuity goes away, and with it most of the leakage — at a price.
The price is resolution. Every window widens the main lobe in exchange for lowering the side lobes, and there is no window that does both. The choice is therefore a question about your measurement: are you trying to separate two close components of similar size, or find a small one next to a large one, or measure an amplitude accurately?
The three figures of merit
All three are computed live in the panel above from the actual window samples, not quoted from a table. They match the published values in Harris (1978), which is the paper every window table in every textbook derives from.
Choosing one
| Situation | Window | Reasoning |
|---|---|---|
| General purpose, don't know yet | Hann | Good compromise: −31 dB side lobes, 1.5 bin ENBW. The sensible default |
| Accurate amplitude of a tone | Flat-top | Scalloping loss under 0.01 dB, so the peak reads true wherever it falls. Very poor resolution — 3.8 bin ENBW |
| Small signal near a large one | Blackman–Harris | −92 dB side lobes stop the strong component masking the weak one |
| Two close tones of similar size | Rectangular or Hamming | Narrowest main lobe wins when resolution is the binding constraint and there is nothing weak to mask |
| Transient shorter than the record | Rectangular | The signal already tapers to zero on its own; a window would just attenuate it and distort the shape |
| Adjustable trade-off | Kaiser | One parameter β sweeps continuously from rectangular to very low side lobes |
- Harris, "On the use of windows for harmonic analysis with the DFT", Proc. IEEE 66(1), 1978
- Nuttall, "Some windows with very good sidelobe behavior", IEEE Trans. ASSP 29(1), 1981 — corrections and additions to Harris
Zero padding, and what resolution actually means
Appending zeros to a record gives a smoother-looking spectrum with more points. It does not let you see anything that was not already resolvable.
Zero padding interpolates. The underlying spectrum — the transform of the windowed record — is a continuous function, and the DFT samples it at N points. Padding to 4N samples it at 4N points, revealing the shape between the original bins. That is genuinely useful: it makes peak interpolation easier, improves the readability of a plot, and reduces apparent scalloping. What it cannot do is separate two components that the record duration was too short to distinguish, because the width of the main lobe is set by the duration of the actual data and padding does not change it.
Resolution versus sampling rate
These are independent and constantly conflated. The sampling rate sets the highest frequency you can see: fs/2. The record duration sets the finest frequency difference you can resolve: roughly 1/T. Sampling ten times faster for the same number of samples gives you a wider frequency axis and worse resolution, because T has fallen by ten.
- Lyons, Understanding Digital Signal Processing, 3rd ed., 2010 — §3.11 on zero padding, with the same warning
- Harris, Proc. IEEE 66(1), 1978 — resolution defined via equivalent noise bandwidth
Power spectral density
For random signals the spectrum of a single record is a poor estimate — as noisy as the data itself, and it does not improve with more data. The PSD is the estimate that does.
A single periodogram has a standard deviation roughly equal to its own mean, whatever N you use. Doubling the record length gives you twice as many bins, each just as noisy. The fix is to average: split the record into segments, transform each, and average the resulting power spectra. That is Welch's method, and the variance falls in proportion to the number of segments.
The defining property is that a PSD does not depend on how long you recorded or which window you used. A raw spectrum's noise floor drops as you lengthen the record, which is confusing; a PSD's noise floor stays put, and its level is a genuine property of the process. That is what makes PSDs the right currency for noise specifications, vibration standards and sensor datasheets.
For a fixed record, more segments means less variance but shorter segments, and therefore coarser frequency resolution. Averaging 64 segments gives a smooth curve you can quote a number from; averaging 4 gives a ragged one that still resolves fine detail. Choose by asking what the estimate is for — a resonance search wants resolution, a broadband noise level wants stability. Overlapping segments by 50 % recovers some of the lost statistical efficiency for free, because the tapered ends of a windowed segment would otherwise waste that data.
- Welch, "The use of FFT for the estimation of power spectra", IEEE Trans. Audio Electroacoust. 15(2), 1967
- Bendat & Piersol, Random Data: Analysis and Measurement Procedures, 4th ed., Wiley, 2010 — chapter 11 on estimator variance and degrees of freedom
Decibels
A logarithmic ratio. The only two things to get right are whether you are dealing with power or amplitude, and what the reference is.
The consequence is that a factor of two in power is +3.01 dB but a factor of two in amplitude is +6.02 dB. Mixing them up produces errors of exactly a factor of two in the answer, which is common enough to be worth a deliberate check whenever a result seems out by 3 or 6 dB.
Suffixes mean references
| Unit | Reference | Where used |
|---|---|---|
| dB | none — a pure ratio | Gains, attenuations, differences between two measurements |
| dBm | 1 milliwatt | RF and communications power levels |
| dBW | 1 watt | Transmitter power; dBW = dBm − 30 |
| dBV | 1 volt RMS | Audio and instrumentation voltage levels |
| dBu | 0.775 V RMS | Professional audio (historically 1 mW into 600 Ω) |
| dBFS | converter full scale | Digital audio and ADC levels; always ≤ 0 |
| dB re 1 µPa | 1 micropascal | Underwater acoustics — a different reference from airborne sound, hence the 26 dB offset that catches people out |
"The noise floor is −90 dB" means nothing on its own. −90 dBFS, −90 dBV and −90 dB relative to the signal are three different claims. Where a plot's y-axis says only "dB", find out what the reference is before drawing conclusions from it.
- IEC 60027-3, Letter symbols to be used in electrical technology — Part 3: Logarithmic and related quantities
- Horowitz & Hill, The Art of Electronics, 3rd ed., Cambridge, 2015 — §1.3.2 for practical use of the suffixed units
Noise
Noise is not one thing. Its colour, its distribution and its origin each tell you something different about where it came from and what will remove it.
Two independent descriptions are needed. Colour is how power is distributed across frequency. Distribution is how the amplitude values are spread. They are unrelated: white Gaussian and white uniform noise have the same spectrum and different histograms, and a signal can be Gaussian at every instant while being strongly coloured.
Colours
| Type | Spectrum | Typical physical source |
|---|---|---|
| White / thermal (Johnson) | flat | Resistor thermal agitation, amplifier input noise. Sets the floor of almost every electronic measurement |
| Pink (1/f), flicker | −3 dB/octave | Semiconductor surface effects, drift in almost every physical process. Dominates at low frequencies |
| Brown (1/f²) | −6 dB/octave | Random walk — integrated white noise. Gyroscope bias drift, temperature wander |
| Shot | flat, Poisson counts | Discrete carrier arrivals: photon detection, junction current. Variance proportional to the mean |
| Quantisation | approximately flat | The ADC. Deterministic in principle but usefully modelled as noise (module 15) |
| Interference | discrete lines | Mains hum and its harmonics, switching supplies, clock feedthrough. Not random — and therefore removable |
Random noise is reduced by averaging, by narrowing bandwidth, or by longer integration — √N improvements. Mains hum at 50 Hz averages perfectly coherently and never goes away; it needs a notch filter, better grounding, or removal at source. If your "noise" sits at a specific frequency and stays there, stop averaging and start looking for the cable.
- Johnson, "Thermal agitation of electricity in conductors", Phys. Rev. 32, 1928; Nyquist's theoretical companion paper, same volume
- Vasilescu, Electronic Noise and Interfering Signals, Springer, 2005 — the colour taxonomy and physical origins used here
Signal-to-noise ratio
A single number that decides whether a measurement is possible at all. Almost every processing technique in this trainer is, at bottom, a way of improving it.
Three ways to buy SNR
All three work the same way: the signal adds coherently while the noise adds in power. Averaging 100 triggered repetitions gives 20 dB. Narrowing a 10 kHz measurement to the 100 Hz band the signal actually occupies gives 20 dB. Both require knowing something about the signal — when it occurs, or where it lives in frequency. SNR improvement is always paid for with prior knowledge.
Coherent averaging needs the signal to be identical and identically aligned in every repetition. A timing jitter of a fraction of a period causes the signal to partly cancel too, and the gain flattens out well short of 10log₁₀N. If averaging stops improving your result, suspect trigger jitter or drift before suspecting the noise.
- Bendat & Piersol, Random Data, 4th ed., 2010 — chapter 8 on averaging and estimator variance
- Van Trees, Detection, Estimation and Modulation Theory, Part I, Wiley, 2001 — processing gain from the estimation-theory side
Random signals and stationarity
A random signal has no formula. What it has is statistics — and those only mean something if they hold still.
A stationary process has statistics that do not change with time. Weak (wide-sense) stationarity, which is what practical work relies on, requires only that the mean is constant and the autocorrelation depends on the lag rather than on absolute time. An ergodic process is one where averaging over time gives the same answer as averaging over many realisations — which matters enormously, because you almost always have one long record rather than a thousand short ones.
The distributions worth recognising
Gaussian arises whenever many small independent contributions add — the central limit theorem — which covers thermal noise and most measurement error. Uniform describes quantisation error. Rayleigh describes the magnitude of a complex Gaussian, so it is the distribution of an FFT bin's magnitude in noise, and of fading in radio. Poisson counts rare independent events. Knowing which one applies determines the correct detection threshold (module 41) and whether a large excursion is remarkable or routine.
A PSD of a non-stationary signal is an average over states that never coexisted, and can describe a condition the machine was never in. The cheap test is to split the record into blocks and compare their means, variances and spectra. If they drift, either analyse the segments separately or move to a time–frequency method (module 36).
- Papoulis & Pillai, Probability, Random Variables and Stochastic Processes, 4th ed., McGraw-Hill, 2002
- Bendat & Piersol, Random Data, 4th ed., 2010 — chapter 4, stationarity tests for real records
Correlation and autocorrelation
Slide two signals past each other and measure the overlap at every shift. It finds hidden periodicities, measures delays, and connects directly to the spectrum.
The autocorrelation of white noise is a single spike at zero lag: no sample tells you anything about any other. The autocorrelation of a periodic signal keeps returning to a peak at every period, even when the signal is invisible in the raw time record. That property makes it the classic tool for pulling periodicity out of noise, and it is the basis of pitch detection in speech.
Wiener–Khinchin
This is why a PSD can be computed either by averaging periodograms or by transforming the autocorrelation, and why a narrow spectral peak corresponds to a slowly decaying autocorrelation. It also explains the shape of coloured noise: filtering shapes the spectrum, which necessarily shapes the correlation between neighbouring samples.
Cross-correlation for time delay
If y is a delayed, scaled, noisy copy of x, the peak of Rxy sits at the delay. This is how sonar ranges, how a two-microphone array finds a direction, and how ultrasonic flow meters work. Normalising gives a coefficient between −1 and +1 that also reports how confident the match is, which matters when several peaks compete (module 60).
- Wiener, "Generalized harmonic analysis", Acta Math. 55, 1930; Khinchin, Math. Ann. 109, 1934
- Knapp & Carter, "The generalized correlation method for estimation of time delay", IEEE Trans. ASSP 24(4), 1976
Filter fundamentals
A filter is an LTI system chosen for the shape of its frequency response. Everything else — the design method, the implementation — follows from a specification written in five numbers.
These five numbers determine the required order. A narrow transition band is expensive: halving it roughly doubles the order of an IIR filter and doubles the length of an FIR one. Before designing anything, ask whether the transition band can be widened — often the signal and the interference are further apart than the first specification assumed.
The four responses
Low-pass keeps frequencies below a cutoff: anti-aliasing, smoothing, envelope extraction. High-pass removes drift and DC offsets. Band-pass isolates a band of interest, such as a single gear-mesh order or a radio channel. Band-stop or notch removes a narrow interferer, typically mains hum. A notch is a band-stop with a very high Q and requires care: too narrow and it drifts off the interference, too wide and it removes signal.
The "cutoff frequency" of a filter is usually where the response has fallen by 3 dB — 70.7 % of amplitude, half the power. Content is not removed there; it is barely touched. If you need something genuinely gone, specify the frequency at which you need 40 or 60 dB of attenuation and design to that. Chebyshev and elliptic designs use the ripple edge rather than −3 dB as their reference, so the same nominal cutoff means different things across families.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010 — chapter 7
- Zumbahlen (ed.), Linear Circuit Design Handbook, Analog Devices, 2008 — practical specification of analog anti-alias filters
The classical filter families
Four approximations to the impossible ideal, each sacrificing something different. Choosing between them is choosing which imperfection you can live with.
The ideal brick wall is unrealisable — it is non-causal and its impulse response extends infinitely in both directions. Every real filter approximates it, and the classical families differ in where they put the approximation error.
| Family | Passband | Stopband | Roll-off | Phase | Use when |
|---|---|---|---|---|---|
| Butterworth | maximally flat | monotonic | slowest | moderate | Amplitude accuracy in the passband matters and you can afford the order. The safe default |
| Chebyshev I | equal ripple | monotonic | fast | worse | You need steep roll-off and can tolerate a stated passband ripple |
| Chebyshev II | flat | equal ripple | fast | worse | Passband must stay flat but the stopband only needs to reach a level, not keep falling |
| Elliptic (Cauer) | equal ripple | equal ripple | steepest | worst | Lowest possible order for a given specification. Standard for anti-aliasing where phase does not matter |
| Bessel | flat | monotonic | slowest | maximally linear | Pulse shapes and timing must survive. The only family that preserves waveform shape |
For a fixed order, steeper amplitude roll-off is bought with more nonlinear phase and more ringing on transients. Elliptic gives the sharpest cut and the worst overshoot; Bessel gives the cleanest step response and the laziest roll-off. If your measurement is about frequency content, favour steepness; if it is about waveform shape or arrival time, favour phase linearity — or use a zero-phase FIR approach instead (module 33).
- Parks & Burrus, Digital Filter Design, Wiley, 1987 — the approximation theory behind all five families
- Thomson, "Delay networks having maximally flat frequency characteristics", Proc. IEE 96, 1949 — the Bessel filter
The z-transform, poles and zeros
The discrete-time counterpart of Laplace. It turns difference equations into algebra, and it turns a filter's behaviour into a picture you can read at a glance.
Evaluating H(z) on the unit circle, z = ejω, gives the frequency response — the unit circle is the frequency axis, running from DC at z = 1 round to the Nyquist frequency at z = −1. A zero near the circle pulls the response down at that angle; a pole near it pushes the response up. The whole frequency response can be read off the pole–zero diagram as a ratio of distances.
Stability
This is a hard rule with practical consequences. A high-order IIR filter implemented as a single long difference equation can have poles that are stable in exact arithmetic but drift outside the circle when the coefficients are rounded to finite precision. Factoring into second-order sections avoids it, which is why every serious implementation uses them (module 32).
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — chapter 3
- Proakis & Manolakis, Digital Signal Processing, 4th ed., Pearson, 2006 — §3, region of convergence and stability
FIR filters
A finite impulse response: the output is a weighted sum of the last N inputs and nothing else. Always stable, and capable of exactly linear phase.
Linear phase
If the coefficients are symmetric, bk = bN−1−k, every frequency is delayed by exactly the same amount: (N−1)/2 samples. No frequency-dependent distortion of the waveform, and the delay is a known constant you can simply subtract. This is the reason FIR filters dominate anywhere waveform shape or relative timing matters — audio crossovers, radar pulse processing, biomedical signals, anything where a peak's arrival time is the measurement.
Design methods
| Method | Idea | Character |
|---|---|---|
| Window method | Take the ideal (infinite, sinc) impulse response and truncate it with a window | Simple and predictable. Ripple is set by the window's side lobes; passband and stopband ripple are always equal |
| Frequency sampling | Specify the response at N equally spaced frequencies and inverse-transform | Direct control at the sample points, uncontrolled between them. Useful for arbitrary shapes |
| Parks–McClellan (Remez) | Minimise the maximum error by equiripple approximation | Optimal: shortest filter for a given specification. Lets passband and stopband ripple be weighted differently |
| Least squares | Minimise total squared error | Smaller average error but larger peaks near the band edges. Good when overall energy matters more than worst case |
FIR filters need far more coefficients than an IIR of equivalent sharpness — often by a factor of ten or more. A 60 dB stopband with a 1 % transition band might need 500 taps as an FIR and an eighth-order IIR. That is 500 multiplies per sample and a delay of 250 samples. Kaiser's estimate N ≈ (Astop − 8)/(2.285·Δω) gives the length before you commit.
- Parks & McClellan, "Chebyshev approximation for nonrecursive digital filters with linear phase", IEEE Trans. Circuit Theory 19(2), 1972
- Kaiser, "Nonrecursive digital filter design using the I₀-sinh window function", Proc. IEEE ISCAS, 1974 — the length estimate quoted above
IIR filters
Feedback makes them enormously more efficient than FIR filters, and introduces every problem that FIR filters do not have.
Designing by transformation
The standard route borrows a century of analog filter theory: design an analog prototype with the classical families, then map it to discrete time. The bilinear transform is the usual mapping. It substitutes s = (2/T)(z−1)/(z+1), which maps the entire left half plane inside the unit circle — so a stable analog filter always becomes a stable digital one.
Instability — poles can leave the unit circle, particularly with rounded coefficients at high order. Nonlinear phase — different frequencies are delayed differently, so waveform shape is not preserved and peaks move. Transients — the filter has internal state, so the first samples of the output are contaminated until the state settles, roughly 5 time constants (module 55). None of these applies to FIR.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — §7.1, the bilinear transform and pre-warping
- Rabiner & Gold, Theory and Application of Digital Signal Processing, Prentice-Hall, 1975
Implementation structures and finite precision
The same transfer function can be computed in several arrangements. They are equivalent in exact arithmetic and very different in practice.
Direct form I keeps separate delay lines for input and output — more memory, but the intermediate sum has full precision. Direct form II shares one delay line and uses half the storage, at the cost of an internal node whose range can be much larger than either input or output, which is a real overflow risk. The transposed direct form II is usually the best choice in floating point: same low storage, better numerical behaviour.
Second-order sections
Any high-order filter should be factored into cascaded biquads. The reason is coefficient sensitivity: the roots of a high-degree polynomial move violently when its coefficients are perturbed slightly. A tenth-order filter written as a single difference equation can lose stability from rounding alone, while the same filter as five biquads is entirely robust, because each section's two poles depend on only two coefficients.
Fixed point
Fixed-point implementation adds three distinct effects. Coefficient quantisation moves the poles and zeros, changing the response from the one you designed. Round-off noise is injected at every multiply and shaped by the remaining filter stages. Limit cycles are small self-sustaining oscillations that persist with zero input, caused by rounding in the feedback path. Scaling — deliberately attenuating at each stage to prevent overflow — trades headroom against SNR, and getting that balance right is most of the work in a fixed-point design.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — chapter 6, structures and finite-precision effects
- Jackson, "On the interaction of roundoff noise and dynamic range in digital filters", Bell Syst. Tech. J. 49, 1970
Phase, group delay and zero-phase filtering
A filter's magnitude response tells you what survives. Its phase response tells you where it ends up in time — and that is often the measurement.
If group delay is constant, every frequency is held up by the same amount and the waveform emerges intact, merely late. If it varies, different components arrive at different times and the shape is destroyed — a sharp pulse smears out, a step acquires overshoot and ringing, and the apparent arrival time of an event becomes a function of its frequency content.
Zero-phase filtering
Offline, you can escape the problem entirely. Filter the record forwards, reverse it, filter again, and reverse back. The two passes apply the same phase distortion in opposite senses, so it cancels exactly. The magnitude response is squared, so the effective attenuation doubles in dB and the effective cutoff moves.
It still smears energy in time, and now symmetrically — a sharp transient acquires a precursor before it happens, which can be badly misleading when you are looking for onset times. And the record's ends are contaminated from both directions, so discard a settling length from each end rather than just the start.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — §5.1, phase and group delay
- Gustafsson, "Determining the initial states in forward–backward filtering", IEEE Trans. Sig. Proc. 44(4), 1996 — the edge-transient correction used by filtfilt
Smoothing, and differentiating without disaster
The moving average is the most-used and least-understood filter in engineering. And differentiation, done naively, will amplify your noise by a factor of a thousand.
The moving average is a bad low-pass filter
It is optimal for one specific job — minimising white noise while preserving a step edge in the time domain — and it is genuinely the right choice for that. As a frequency-selective filter it is poor: the response is a sinc, with side lobes that leak badly, and a passband that already droops well before the nominal cutoff. If you want a low-pass filter, design one.
When the noise is spikes, not hiss
A single large outlier drags a moving average by (spike ÷ M) across the whole window. A median filter ignores it completely, because a median is insensitive to values that are merely extreme. Medians preserve step edges perfectly too, where a linear filter must always round them off. The cost is nonlinearity: no transfer function, no superposition, and the behaviour on real signals must be checked empirically. The Hampel filter refines this by replacing only points that lie more than a few robust standard deviations from the local median, leaving everything else untouched.
Savitzky–Golay
Fit a low-order polynomial to a sliding window by least squares and take the value of the fit at the centre. Because the fit is linear in the data, the whole operation collapses to a fixed FIR kernel — the famous [−3, 12, 17, 12, −3]/35 for a quadratic over five points. It preserves peak heights and widths far better than a moving average, which is why it dominates in spectroscopy and chromatography, and the same fit gives you smoothed derivatives for free.
The gain of a differentiator rises linearly with frequency, so noise at 1 kHz is amplified a thousand times more than a 1 Hz signal. A simple difference y[n] = x[n] − x[n−1] on a noisy record produces something dominated entirely by the noise. Always band-limit first, or use a Savitzky–Golay derivative kernel, which combines the smoothing and the differentiation into one operation with a bounded gain. Integration has the opposite hazard: it has infinite gain at DC, so any offset — however small — grows without bound as a ramp.
- Savitzky & Golay, "Smoothing and differentiation of data by simplified least squares procedures", Anal. Chem. 36(8), 1964
- Schafer, "What is a Savitzky–Golay filter?", IEEE Sig. Proc. Mag. 28(4), 2011 — the modern DSP reading of it
Decimation, interpolation and resampling
Changing the sample rate is easy to do and easy to do wrong. Both directions need a filter, and each needs it on a different side of the operation.
Decimation. Keeping every M-th sample is sampling all over again, at fs/M, so everything above the new Nyquist frequency aliases. The anti-alias filter must come first, cut off below fs/(2M), and then the discarding is safe. Skipping it is one of the most common bugs in signal-processing code, and it produces plausible-looking spectra with entirely fictitious peaks.
Interpolation. Inserting L−1 zeros between samples leaves the spectrum unchanged but now, at the higher rate, the old replicas sit inside the new band as images. A low-pass filter at the old Nyquist removes them, and its gain must be L to restore the amplitude lost by the zeros.
Filtering at the full rate and then discarding M−1 of every M outputs wastes almost all the work. Polyphase decomposition computes only the outputs that survive, cutting the cost by exactly M. For interpolation it skips the multiplications by the inserted zeros, saving L. This is why a well-written resampler is far faster than the obvious implementation, and why large rate changes are done in several small stages rather than one big one.
- Crochiere & Rabiner, Multirate Digital Signal Processing, Prentice-Hall, 1983
- Vaidyanathan, Multirate Systems and Filter Banks, Prentice-Hall, 1993 — polyphase structures
The short-time Fourier transform
Real signals change. Chop the record into overlapping windows, transform each, and you can watch the spectrum evolve — subject to one unavoidable trade-off.
The trade-off is not a limitation of the method
So the window length is a statement about what you are looking for. Distinguishing two close tones needs a long window. Locating a click needs a short one. If you need both at once, you need more than one spectrogram — or a method that varies its resolution with frequency, which is what wavelets do.
Overlap of 50 % with a Hann window, or 75 % for smoother displays, gives good reconstruction and even weighting of every sample. Below 50 % overlap the tapered window edges under-weight parts of the record and events can fall between frames. Hop size sets the time axis resolution of the display; window length sets the actual resolution — as with zero padding, do not confuse the two.
- Allen & Rabiner, "A unified approach to short-time Fourier analysis and synthesis", Proc. IEEE 65(11), 1977
- Gabor, "Theory of communication", J. IEE 93(26), 1946 — the time–frequency uncertainty relation
Wavelets
The STFT uses one window length for every frequency. A wavelet transform scales the window with the frequency — short windows for high frequencies, long ones for low.
This matches how signals usually behave. A transient click is brief and broadband; a slow oscillation is long and narrowband. Analysing both with the same window means compromising on both. The wavelet's constant-Q tiling gives fine time resolution where events are fast and fine frequency resolution where they are slow.
Where it earns its place
Transient detection in vibration monitoring — a bearing fault is a train of short impacts that a spectrogram either locates badly or resolves badly. Denoising, by thresholding small wavelet coefficients and reconstructing, which removes noise while keeping edges sharp in a way linear filtering cannot. Compression, where JPEG 2000 uses a wavelet transform. And multi-resolution analysis generally, whenever a signal has structure at several scales at once.
Wavelets have no single frequency axis you can quote a number from, the choice of mother wavelet materially changes the result, and coefficients are harder to interpret physically than a spectrum in engineering units. For stationary signals a PSD is better in every way. Reach for wavelets when the signal is genuinely multi-scale or transient — not as a default upgrade.
- Mallat, A Wavelet Tour of Signal Processing, 3rd ed., Academic Press, 2008
- Daubechies, Ten Lectures on Wavelets, SIAM, 1992
The Hilbert transform, envelopes and IQ
Discard the negative frequencies and the signal becomes complex. Its magnitude is the envelope, its phase derivative is the instantaneous frequency, and it is the foundation of every modern receiver.
Envelope detection
The magnitude of the analytic signal is the envelope, computed without rectifying and low-pass filtering and without the distortion that introduces. This is the standard first step in bearing fault diagnosis: a fault produces impacts that ring the structure at a high resonant frequency, and the useful information is the rate of the impacts, not the resonance. Band-pass around the resonance, take the envelope, then take the spectrum of the envelope — and the fault frequency appears clearly where the raw spectrum showed nothing (module 54).
IQ representation
Splitting the analytic signal into real and imaginary parts gives in-phase and quadrature components. Radio, radar and sonar receivers work in IQ because it halves the required sample rate for a given bandwidth, and because it preserves the sign of a frequency offset — with a real signal you cannot tell an upward Doppler shift from a downward one, and with IQ you can.
- Randall & Antoni, "Rolling element bearing diagnostics — a tutorial", Mech. Syst. Signal Process. 25(2), 2011 — envelope analysis in practice
- Boashash, "Estimating and interpreting the instantaneous frequency of a signal", Proc. IEEE 80(4), 1992
Modulation, mixing and heterodyning
Multiplying by a sinusoid shifts a spectrum. That single fact underlies radio, every superheterodyne receiver, and the sidebands that appear around a gear mesh frequency.
Amplitude modulation, and why it matters mechanically
AM produces a carrier plus sidebands at fc ± fm. In communications that is a design choice. In machinery it is a diagnosis: if a load varies once per shaft revolution, it amplitude-modulates the gear mesh tone, and the spectrum shows the mesh frequency flanked by sidebands spaced at the shaft rate. The spacing identifies which shaft, and the sideband amplitude tracks the severity. The rig example threaded through this trainer has exactly this structure — 632.5 Hz mesh with ±27.5 Hz sidebands.
Frequency modulation
FM encodes information in the instantaneous frequency instead. Its spectrum is much less obvious — Bessel functions of the modulation index — and its bandwidth is approximated by Carson's rule, B ≈ 2(Δf + fm). Mechanically, FM sidebands appear when shaft speed fluctuates within a revolution, so an AM/FM mixture in gear sidebands distinguishes a load problem from a torsional one.
- Proakis & Salehi, Communication Systems Engineering, 2nd ed., Prentice-Hall, 2002 — chapters 3–4
- Randall, Vibration-based Condition Monitoring, 2nd ed., Wiley, 2021 — modulation sidebands as a diagnostic
Chirps and instantaneous frequency
When frequency changes during the record, a single spectrum describes a state the signal never occupied. You need to follow it instead.
A chirp sweeps frequency with time. Linear chirps are the workhorse of radar and sonar because they can be compressed to a sharp peak after transmission (module 41), and they appear naturally whenever a machine runs up or coasts down. Their whole-record spectrum is a broad, flat plateau spanning the swept range — technically correct and diagnostically useless.
It is only meaningful for a signal with a single dominant component. Compute it for a sum of two tones and you get a quantity that oscillates wildly, sometimes going negative, describing neither. Band-pass to isolate one component first, and treat any instantaneous-frequency estimate where the envelope is near zero as undefined — the phase is unconstrained there and its derivative explodes.
- Boashash, Time–Frequency Signal Analysis and Processing, 2nd ed., Academic Press, 2016
- Cohen, Time–Frequency Analysis, Prentice-Hall, 1995
Detection and the matched filter
If you know the shape of what you are looking for, correlating with that shape is provably the best thing you can do in white noise. There is no cleverer filter.
The output SNR depends only on the signal's energy, not on its shape or duration. A long quiet pulse and a short loud one with the same energy detect equally well — which is exactly why radar transmits long coded pulses and compresses them on receive, getting the range resolution of a short pulse with the energy of a long one.
Thresholds and the two ways to be wrong
The ROC curve plots PD against PFA as the threshold sweeps. Its shape is fixed by the SNR; the threshold only chooses your position along it. Improving detection therefore means improving SNR, not tuning the threshold — a distinction worth being firm about when someone asks you to "just make it more sensitive".
- Van Trees, Detection, Estimation and Modulation Theory, Part I, 2nd ed., Wiley, 2001
- Kay, Fundamentals of Statistical Signal Processing, Vol. II: Detection Theory, Prentice-Hall, 1998
Preprocessing: the steps before the analysis
Most bad results come from skipping these, not from choosing the wrong transform.
Remove the mean and the trend
A DC offset puts all its energy in bin 0, and leakage from that huge bin swamps the low-frequency region you probably care about. A linear trend is worse: it is a ramp, its spectrum falls as 1/f², and it contaminates a wide band. Subtracting the mean is one line; subtracting a least-squares straight line is barely more, and both should be reflexive before any spectral estimate.
Detrend before windowing — windowing a record with an offset creates a bump at the window's own shape. But if the trend is the measurement — a drift study, a settling test, a temperature ramp — removing it destroys the signal. Ask what the low-frequency content means before deleting it.
Normalisation
| Method | Formula | Use when |
|---|---|---|
| Mean removal | x − μ | Always, before spectral analysis |
| Z-score | (x − μ)/σ | Comparing channels with different units or gains; feeding machine learning |
| Peak | x / max|x| | Display, audio levels. Sensitive to a single outlier |
| RMS | x / rms(x) | Equalising energy rather than peaks; more robust than peak normalisation |
| Calibration | x · ksens | Converting counts to engineering units. Do this first, and keep the units with the data |
The checklist
- Bendat & Piersol, Random Data, 4th ed., 2010 — chapter 10, data qualification and preparation
- Wickham, "Tidy data", J. Stat. Software 59(10), 2014 — on keeping units and provenance with the data
What real data actually looks like
Textbook signals are clean, complete and correctly scaled. Real records have dropouts, spikes, saturation, and a sample clock that is not quite what the datasheet says.
| Defect | How to spot it | What to do |
|---|---|---|
| Clipping / saturation | Flat tops at a constant value; a histogram with spikes at the extremes; new harmonics appearing as level rises | Cannot be repaired — the information is gone. Reduce gain and re-record. Flag and exclude the affected spans |
| Dropouts / gaps | Runs of exact zeros or repeated identical values; timestamps that jump | Never interpolate silently. Mark them, and exclude affected windows from spectra |
| Spikes | Isolated points many standard deviations out, often single-sample | Hampel or median replacement if they are genuinely artefacts — but check they are not the signal (impacts look like spikes) |
| Stuck / dead channel | Variance near zero, or a constant value | Detect automatically before analysis; a flat channel produces a beautiful, meaningless spectrum |
| Clock error | Known tone appears at the wrong frequency; two devices drift apart over a long record | Calibrate against a reference tone; resample to a common time base |
| Quantisation floor | Signal occupies only a few LSBs; the histogram is comb-like | Increase gain. No amount of processing recovers resolution that was never digitised |
Filling a gap with a straight line, or with zeros, creates a signal that was never measured, and the spectrum will faithfully report its content. Zeros are especially bad: a sudden step to zero and back is a broadband transient. If you must fill, fill with something spectrally neutral and — more importantly — keep a mask of which samples are real and carry it through the analysis.
- Bendat & Piersol, Random Data, 4th ed., 2010 — chapter 10 on data qualification
- Hampel, "The influence curve and its role in robust estimation", J. Amer. Stat. Assoc. 69, 1974
Features, harmonics and distortion
Reducing a record to a handful of numbers that mean something — and knowing which of those numbers are actually sensitive to the thing you care about.
Time-domain features
Kurtosis illustrates the general point about features nicely. It is highly sensitive to early impulsive faults, and then it falls back towards 3 as the fault worsens and the impacts become continuous — so a single reading is ambiguous and the trend is what matters. No feature is meaningful without a baseline.
Harmonics and THD
Harmonics mean nonlinearity. A perfectly linear system fed a sine returns a sine; anything else — clipping, backlash, a loose joint, an amplifier at its limit — folds energy into integer multiples. The pattern is diagnostic: symmetric distortion such as clipping produces odd harmonics, while asymmetric distortion produces even ones too.
- Randall, Vibration-based Condition Monitoring, 2nd ed., Wiley, 2021 — feature selection and trending
- IEEE Std 1241-2010, Terminology and Test Methods for Analog-to-Digital Converters — THD and SINAD definitions
Interpolation, in time and in frequency
Estimating values between the samples you have. The right method depends entirely on whether you are reconstructing a band-limited signal or just drawing a smooth line.
| Method | Character | Use for |
|---|---|---|
| Zero-order hold | Staircase; sinc-shaped spectral droop and strong images | Nothing analytical. It is what a DAC does before reconstruction |
| Linear | Continuous but kinked; attenuates high frequencies noticeably | Display, and rough resampling where accuracy is not critical |
| Cubic spline | Smooth first and second derivatives; can overshoot near sharp features | Smooth physical quantities; plotting; non-uniform data |
| Sinc / band-limited | Exact for a properly sampled band-limited signal | Correct resampling of sampled signals. This is what the sampling theorem prescribes |
Interpolating a spectral peak
A different problem with a neat solution. A peak in a magnitude spectrum rarely falls exactly on a bin, so the bin index underestimates the true frequency by up to half a bin. Fitting a parabola through the peak bin and its two neighbours recovers the fractional offset and typically improves the estimate by an order of magnitude — for essentially no cost.
- Smith, Spectral Audio Signal Processing, W3K, 2011 — quadratic peak interpolation
- Unser, "Splines: a perfect fit for signal and image processing", IEEE Sig. Proc. Mag. 16(6), 1999
Cross-spectra, coherence and frequency response
With two channels you can measure a system rather than a signal — and coherence tells you, frequency by frequency, whether to believe the measurement.
Coherence answers the question "how much of the output at this frequency is linearly caused by the input?" A value near 1 means the FRF estimate there is trustworthy. A value near 0 means it is not, and the reasons are worth distinguishing: noise on either channel, a nonlinearity, an additional unmeasured input, or a leakage or resolution problem in the estimate itself.
With one average, |Sxy|² = SxxSyy identically, regardless of the data — the formula is a normalised inner product of one vector with itself. Coherence is only meaningful after averaging several blocks, and its variance falls roughly as 1/√nd. If your coherence plot is a flat line at 1.0, you have not averaged.
H₁ and H₂
H₁ = Sxy/Sxx is biased low when the input measurement is noisy; H₂ = Syy/Syx is biased high in the same situation but is unbiased when only the input is noisy. In practice, H₁ near resonances and H₂ near anti-resonances are the more accurate choices, and the ratio H₁/H₂ equals the coherence — which gives you a quick check that the two estimators agree.
- Bendat & Piersol, Engineering Applications of Correlation and Spectral Analysis, 2nd ed., Wiley, 1993
- Ewins, Modal Testing: Theory, Practice and Application, 2nd ed., Research Studies Press, 2000
Parametric spectral estimation
Instead of transforming the data, fit a model to it and derive the spectrum from the model. Much better resolution on short records — and much easier to fool yourself.
Because the model is all-pole, it represents peaks very efficiently and needs no window, so there is no leakage and no 1/T resolution limit. On a 64-sample record containing two tones 3 bins apart, an AR model will separate them cleanly where a periodogram shows one lump. This is why it dominates in speech coding, where the vocal tract genuinely is an all-pole resonant system.
Too low and peaks merge or vanish. Too high and the model invents sharp peaks that fit noise — and they look entirely convincing, because a parametric spectrum is smooth and confident by construction. Use an information criterion (AIC, MDL) rather than eye, cross-check against a periodogram, and be suspicious of any peak that appears only above a certain order. Burg's method is generally preferred over Yule–Walker on short records, being less biased and always stable.
- Burg, Maximum Entropy Spectral Analysis, PhD thesis, Stanford, 1975
- Kay & Marple, "Spectrum analysis — a modern perspective", Proc. IEEE 69(11), 1981
Adaptive filters
A filter that tunes its own coefficients from the data, continuously, without being told what the interference looks like.
Choosing μ
Convergence requires 0 < μ < 2/(L·Px), where L is the filter length and Px the input power. Too small and it never catches up with a changing environment; too large and it becomes unstable, often after working fine for hours. Normalised LMS divides by the running input power, which makes the effective step independent of signal level and is almost always the better choice in practice. RLS converges far faster — in about 2L samples rather than 20L — at roughly L× the computation, and with a genuine risk of numerical divergence in finite precision.
Where they are used
Noise cancellation needs a reference sensor measuring the interference alone: the classic case is a microphone near the engine in an active-noise-control system, or a second electrode measuring mains pickup. Echo cancellation in telephony identifies the echo path and subtracts its prediction. Channel equalisation inverts a distorting medium. All share one requirement: something must define what "desired" means.
- Widrow & Stearns, Adaptive Signal Processing, Prentice-Hall, 1985
- Haykin, Adaptive Filter Theory, 5th ed., Pearson, 2013
Multichannel data, PCA and beamforming
Several sensors give you something one sensor cannot: the ability to separate sources by where they are, or by how they co-vary.
Principal component analysis
Take the covariance matrix across channels, find its eigenvectors, and you have a new set of axes ordered by how much variance each explains. In practice the first few components usually capture nearly everything, so PCA is a compression and a denoiser at once — and the components often correspond to physically meaningful modes, though nothing guarantees that.
Beamforming
An array of sensors can be steered without moving. Delaying each channel by the propagation time from a chosen direction and summing makes signals from that direction add coherently while everything else partly cancels. The array's resolution is set by its aperture in wavelengths, and its ability to reject other directions by the number and spacing of elements — with element spacing above half a wavelength producing grating lobes, which is spatial aliasing and behaves exactly like the temporal kind.
- Jolliffe, Principal Component Analysis, 2nd ed., Springer, 2002
- Van Trees, Optimum Array Processing, Wiley, 2002
State estimation and sensor fusion
When you have a model of how something moves and noisy measurements of where it is, the Kalman filter combines them optimally — and tells you how much to trust the result.
The gain is the whole idea. When measurements are noisy relative to the model, K is small and the filter coasts on prediction; when the model is uncertain, K is large and it follows the data. It does this optimally and automatically, and it is recursive — it needs only the previous state, not the history, which is why it fits real-time systems and why it flew on Apollo.
R can often be measured — record a stationary sensor and take the variance. Q rarely can: it encodes how wrong your motion model is. Too small a Q makes the filter overconfident and it will ignore genuine manoeuvres; too large and it becomes an expensive low-pass filter. Check the innovation z − Hx̂⁻: it should be white with the covariance the filter predicts. If it is correlated, the model is wrong and no amount of tuning will fix that.
- Kalman, "A new approach to linear filtering and prediction problems", J. Basic Eng. 82(1), 1960
- Bar-Shalom, Li & Kirubarajan, Estimation with Applications to Tracking and Navigation, Wiley, 2001
Real-time processing
Offline you have the whole record and all the time you want. In real time you have a fragment, a deadline, and no ability to look ahead.
Block processing and the overlap methods
Fast convolution via the FFT is far cheaper than direct convolution for long filters, but the FFT assumes circular convolution, which wraps the end of each block onto its start. Overlap-add and overlap-save are the two standard ways to stitch blocks together so the result matches true linear convolution exactly.
Latency
Total latency is the sum of the acquisition block, the algorithmic delay, and the output buffer — and it is usually dominated by the block size rather than the arithmetic. A 1024-sample block at 48 kHz costs 21 ms of buffering before a single instruction executes, plus the same again on output. Halving the block halves the latency and roughly doubles the per-sample overhead. Linear-phase FIR filters add (N−1)/2 samples on top; minimum-phase or IIR designs give less delay for the same magnitude response, which is exactly why control loops use them despite the phase distortion.
A system that processes a block in 40 % of the available time on average but occasionally takes 130 % will glitch, and the glitch will be audible or destabilising. Budget for worst-case execution time, avoid dynamic memory allocation in the processing path, and treat garbage collection or page faults as design faults rather than surprises.
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — §8.7, overlap-add and overlap-save
- Lyons, Understanding Digital Signal Processing, 3rd ed., Prentice-Hall, 2010 — chapter 13 on implementation
Getting the data in correctly
Everything in this trainer assumes the numbers in your array faithfully represent the physical quantity. That assumption is where most real errors live.
The signal chain
Calibration
Things that quietly corrupt a measurement
Ground loops — two earth connections at different potentials drive current through the signal return, appearing as mains hum. AC coupling — a high-pass corner you forgot about, which removes real low-frequency content. Aperture jitter — uncertainty in when the sample was taken, which limits SNR at high frequencies to roughly −20log₁₀(2πf·tjitter) regardless of how many bits the ADC has. Channel skew — a multiplexed ADC does not sample its channels simultaneously, so phase and correlation between channels are wrong unless corrected.
Sampling at 4× the rate you need and averaging groups of four gains 6 dB — one extra bit — because quantisation noise is spread over four times the bandwidth while the signal is not. Each factor of four buys another bit. It also relaxes the analog anti-alias filter enormously: at 4× the transition band is four times wider, so a gentle second-order analog filter plus a sharp digital one beats an expensive eighth-order analog design. This is why nearly every modern converter oversamples.
- Kester (ed.), Data Conversion Handbook, Analog Devices / Newnes, 2005
- Ott, Electromagnetic Compatibility Engineering, Wiley, 2009 — grounding and ground loops
Bandpass sampling
The Nyquist rule you learned is a special case. What actually matters is the signal's bandwidth, not its highest frequency — and exploiting that lets you sample a 100 MHz signal at 25 MHz on purpose.
Aliasing folds the band down to baseband, and provided the folded copies do not overlap each other, no information is lost — the process is reversible. This is undersampling or direct IF sampling, and it is how software-defined radios digitise high-frequency signals without impossibly fast converters.
The anti-alias filter is now a band-pass, and it must be genuinely selective — anything outside the intended band folds in on top of your signal with no way to separate it. The track-and-hold bandwidth of the converter must reach fH, not merely fs/2, which many datasheets bury. And aperture jitter is now judged against the carrier frequency rather than the sample rate, so a clock that is fine at baseband may be hopeless here.
- Vaughan, Scott & White, "The theory of bandpass sampling", IEEE Trans. Sig. Proc. 39(9), 1991
- Kester (ed.), Data Conversion Handbook, Analog Devices, 2005 — undersampling in practice
Rotating machinery: order analysis and envelopes
The rig used throughout this trainer, treated properly. Two techniques carry most of the diagnostic weight, and both exist because machines do not run at a constant speed.
Order analysis
When shaft speed varies, every speed-related component smears across the spectrum while fixed-frequency components such as mains hum stay sharp. Order tracking resamples the signal at equal increments of shaft angle rather than of time, using a tachometer or an estimated speed. In the resampled domain every rotational component is at a fixed order — a multiple of shaft rotation — and becomes sharp again, while fixed-frequency components smear instead. That inversion is itself diagnostic.
Envelope analysis for bearings
Bearing defect frequencies are low — the rig's is 118.4 Hz — but a defect excites brief impacts that ring the structure at a high resonance, typically several kilohertz. The energy is at the resonance; the information is in the repetition rate. Band-pass around the resonance, take the analytic envelope, then take the spectrum of that envelope: the defect frequency appears clearly where the raw spectrum showed only a broad hump.
BPFO, BPFI, BSF and FTF depend on the bearing's geometry and involve the contact angle, so they are non-integer orders and they drift slightly as the rolling elements slip. That is why they cannot be removed by synchronous averaging — which is exactly how synchronous averaging is used to separate gear faults from bearing faults, since gear signals are locked to the shaft and bearing signals are not.
- Randall & Antoni, "Rolling element bearing diagnostics — a tutorial", Mech. Syst. Signal Process. 25(2), 2011
- Fyfe & Munck, "Analysis of computed order tracking", Mech. Syst. Signal Process. 11(2), 1997
Transients, edge effects and causality
Every filter has a startup transient, every window has ends, and the first and last portions of any processed record are wrong. How wrong, and what to do about it.
How much to discard
An FIR filter's transient is finite and exactly known: until N samples have entered, the output is a partial sum. An IIR filter's decays asymptotically, so "settled" is a tolerance you choose. Either way, the fix is the same — record more than you need, and trim.
Reducing rather than discarding
| Approach | Idea | Caution |
|---|---|---|
| Trim | Discard the settling length from each end | Always correct. Costs data, which is why you record extra |
| Warm-up state | Initialise filter state to the steady-state response of the first sample | Standard in good filtfilt implementations; removes most of the step at the start |
| Reflect / mirror | Extend the record with a mirrored copy before filtering | Smooth at the join but introduces a false symmetry; it can create or hide features at the ends |
| Taper | Window the ends to zero | Fine for spectra, destructive if you need the actual values near the edges |
Offline you may use future samples: zero-phase filtering, non-causal smoothers, and iterating over the whole record. In real time you may not, and every one of those techniques is unavailable. Deciding which regime you are in — before choosing an algorithm — avoids the common and expensive discovery that a prototype validated offline cannot be deployed.
- Gustafsson, "Determining the initial states in forward–backward filtering", IEEE Trans. Sig. Proc. 44(4), 1996
- Oppenheim & Schafer, Discrete-Time Signal Processing, 3rd ed., 2010 — §2.4 on causality
Audio and speech
The domain where perceptual limits matter as much as mathematical ones — and where the ear's own properties decide what processing is worth doing.
What the ear imposes
Hearing spans roughly 20 Hz to 20 kHz, so 44.1 kHz sampling is a modest margin above Nyquist. Loudness perception is approximately logarithmic, which is why audio works in decibels throughout. Frequency perception is also approximately logarithmic — an octave sounds like a constant interval whether it spans 100–200 Hz or 4–8 kHz — which is why audio analysis uses constant-Q, mel or third-octave scales rather than the FFT's linear bins.
Speech
Because the vocal tract is genuinely an all-pole resonant cavity, linear prediction (module 47) models it almost exactly — which is why LPC underpins nearly all speech codecs. Pitch is estimated from the autocorrelation or cepstrum of a 20–40 ms frame, short enough that the signal is quasi-stationary and long enough to contain several pitch periods.
Take the log of the magnitude spectrum and transform again. Multiplication becomes addition under the log, so the slowly varying spectral envelope (the vocal tract) and the rapidly varying harmonic comb (the pitch) separate into different quefrency regions and can be windowed apart. The same trick works on gearboxes, where the "source" is the mesh harmonics and the "filter" is the transmission path.
- Rabiner & Schafer, Theory and Applications of Digital Speech Processing, Pearson, 2010
- Bogert, Healy & Tukey, "The quefrency alanysis of time series for echoes", 1963 — the original cepstrum paper
Radar, sonar and communications
Where detection theory, matched filtering and modulation come together — and where range and velocity resolution turn out to be two faces of one trade-off.
Those last two are the key insight. A short pulse has wide bandwidth and gives fine range resolution but little energy and poor velocity discrimination. A long tone has fine velocity resolution and hopeless range resolution. A chirp has both a long duration and a wide bandwidth, so after pulse compression it delivers both — which is why coded waveforms replaced simple pulses everywhere.
Doppler
A moving target returns a frequency-shifted echo. The sign of the shift gives the direction of motion, which is why receivers work in IQ (module 38) — a real-valued sampler cannot distinguish approach from recession. In sonar the shift is proportionally much larger because the propagation speed is so much lower, which means a chirp's compression can be significantly degraded by target motion: the Doppler tolerance of the waveform becomes a design parameter in its own right.
- Richards, Fundamentals of Radar Signal Processing, 2nd ed., McGraw-Hill, 2014
- Woodward, Probability and Information Theory with Applications to Radar, Pergamon, 1953 — the ambiguity function
Two-dimensional signal processing
An image is a signal sampled on a grid. Nearly every concept so far carries over unchanged — convolution, filtering, the Fourier transform, aliasing — with one extra dimension and one extra idea.
What changes in two dimensions
Frequency becomes a vector: spatial frequency has a direction as well as a magnitude, so an image of vertical stripes has energy along the horizontal frequency axis. Aliasing becomes visible as moiré patterns — the same folding, now spatial, which is why cameras have optical low-pass filters over the sensor and why resizing an image without filtering first produces shimmering artefacts.
Edge detection is differentiation, with all the noise amplification that implies (module 34), which is why Sobel and Canny smooth before differentiating. Compression exploits the fact that natural images have most of their energy at low spatial frequencies — JPEG transforms 8×8 blocks with a DCT and quantises the high-frequency coefficients heavily, since the eye barely notices.
- Gonzalez & Woods, Digital Image Processing, 4th ed., Pearson, 2018
- Wallace, "The JPEG still picture compression standard", Commun. ACM 34(4), 1991
Feeding signals to machine learning
Most of the value is in the signal processing, not the model. Good features from a modest classifier beat raw samples into a large one, almost every time, on the data volumes engineering problems actually have.
The pipeline
Leakage through overlapping windows. If windows overlap and you split randomly, nearly identical windows land in both training and test sets, and your reported accuracy is close to meaningless. Split by recording, by machine, or by day — never by window.
Normalising before splitting. Computing a mean and standard deviation over the whole dataset and then splitting leaks test statistics into training. Fit the scaler on the training set alone and apply it to the test set.
Metrics
Accuracy is misleading whenever classes are imbalanced, which in condition monitoring they always are — a detector that never predicts a fault scores 99 % on a machine that fails 1 % of the time. Precision, recall and the confusion matrix say what actually happened, and the ROC and precision–recall curves show the whole threshold trade-off rather than one point on it. The choice between them is an engineering judgement about the relative cost of a missed fault and a false alarm — exactly the question module 41 posed for detection.
- Kaufman et al., "Leakage in data mining", ACM TKDD 6(4), 2012
- Saito & Rehmsmeier, "The precision–recall plot is more informative than the ROC plot on imbalanced datasets", PLoS ONE 10(3), 2015
Estimating frequency, amplitude and delay well
Three measurements you will make constantly, each with a naive method that is needlessly poor and a better one that costs almost nothing.
Frequency
Taking the peak bin quantises the estimate to fs/N. Parabolic interpolation over three bins (module 45) improves it by an order of magnitude. Better still, when the tone is stable across the record, is to unwrap the phase at the peak bin across successive frames — phase advances linearly at a rate set by the frequency offset, so the slope gives a very precise correction.
Phase unwrapping
Computed phase is confined to (−π, π] and jumps by 2π whenever it crosses. Unwrapping adds the multiples of 2π back, and works reliably only when the true phase changes by less than π between samples. Noise near a zero of the envelope, or genuine steps larger than π, produce errors that propagate forwards through the entire remainder of the record — a single bad sample can corrupt everything after it.
Time delay
Cross-correlation with parabolic interpolation is the baseline. Generalised cross-correlation with phase transform weighting (GCC-PHAT) whitens both spectra before correlating, which sharpens the peak dramatically in reverberant or coloured-noise conditions — at the cost of poor behaviour at low SNR, since whitening amplifies the bands where there is no signal.
- Rife & Boorstyn, "Single-tone parameter estimation from discrete-time observations", IEEE Trans. Inf. Theory 20(5), 1974
- Knapp & Carter, "The generalized correlation method for estimation of time delay", IEEE Trans. ASSP 24(4), 1976
Knowing whether your answer is right
The single most valuable habit in this field: test every processing chain on a signal whose answer you already know, before you point it at data you do not understand.
Synthetic signals are the test harness
If your pipeline cannot recover a 100 Hz sine of amplitude 2.0 to within a fraction of a percent, it will not tell you anything true about a gearbox. Build a synthetic signal with known amplitudes, frequencies, phases and noise level; run it through the exact chain you intend to use; and check the numbers that come out against the ones you put in. Nearly every scaling error, windowing error, and off-by-one is caught this way in minutes.
The errors that recur
| Symptom | Usual cause |
|---|---|
| Amplitudes wrong by a factor of about 2 | One-sided versus two-sided spectrum, or a missing factor of 2 on the positive-frequency bins |
| Amplitudes low by 30–60% | No window amplitude correction — divide by the window's coherent gain |
| Amplitudes wrong by exactly N or 1/N | FFT normalisation convention; check where your library puts the 1/N |
| Peak at the wrong frequency by 2× | Confusing f and ω, or Hz and rad/s, somewhere in the chain |
| Spectrum mirrored or duplicated | Plotting the full two-sided spectrum where you meant one-sided |
| Everything smeared | Non-stationary record, or an unremoved trend |
| Peaks at unexpected frequencies | Aliasing from a missing anti-alias filter, or from decimation without filtering |
| Result changes with record length | Leakage; or the estimate is not converged and needs more averages |
Uncertainty
- Bendat & Piersol, Random Data, 4th ed., 2010 — chapter 8, statistical errors in estimates
- JCGM 100:2008, Guide to the Expression of Uncertainty in Measurement (the GUM)
Projects, and what mid-level competence looks like
Reading about signal processing produces recognition. Building something produces the judgement that this trainer has been aiming at throughout.
The capstone: analyse the rig properly
Everything needed is in the modules above. Take the accelerometer record — 2 kHz sampling, a 27.5 Hz shaft, a 23-tooth pinion, a bearing defect at 118.4 Hz, mains at 50 Hz, thermal drift and broadband noise — and produce a defensible condition assessment.
Other projects, roughly in order of difficulty
| Project | Exercises |
|---|---|
| Guitar tuner | Windowing, peak interpolation, pitch detection, real-time constraints |
| Mains hum remover | Notch design, Q trade-offs, harmonic combs, before/after verification |
| Heart-rate from a pulse sensor | Band-pass design, detrending, peak detection, artefact rejection |
| Room impulse response | Chirp excitation, deconvolution, matched filtering, SNR budgeting |
| Speech pitch and formant tracker | STFT, LPC, cepstrum, voiced/unvoiced decisions |
| Two-microphone direction finder | Cross-correlation, GCC-PHAT, sub-sample delay, geometry |
| Order-tracking analyser | Resampling, tacho processing, spectrograms, synchronous averaging |
What mid-level actually means
Not knowing more transforms. It means: choosing the window and record length from the measurement requirement rather than from habit; knowing what your filter does to phase and to the first samples of the record; recognising leakage, aliasing and non-stationarity from the shape of a plot; quantifying the uncertainty on the number you report; and testing every chain on a synthetic signal before trusting it. Those habits are worth more than any individual technique in this trainer.
Every technique here trades something for something else. Resolution against variance, sharpness against ringing, speed against accuracy, sensitivity against false alarms. There is no setting that wins on every axis, and the mark of competence is being able to say which axis your application cares about — and defend it.
- Smith, The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing, 1997 — free online, and excellent on intuition
- Lyons, Understanding Digital Signal Processing, 3rd ed., Prentice-Hall, 2010
- Harris, "On the use of windows for harmonic analysis with the DFT", Proc. IEEE 66(1), 1978 — still the definitive window reference
Formula reference
Every equation used in this trainer, with every symbol defined. Type to filter across titles, equations and descriptions.
Glossary
The vocabulary of signal processing, defined in the sense used here. Filtering searches the definitions as well as the terms, so you can look up a concept you cannot yet name.