Hilbert Transform and Envelope Detection
What is the Hilbert transform?
The Hilbert transform is an operation that shifts every frequency component of a signal by a quarter of a cycle (−90°) while leaving its amplitude unchanged, so a cosine becomes a sine. Combined with the original signal, it forms the analytic signal, whose length is the signal's envelope and whose angle gives its instantaneous phase and frequency. Envelope detection means recovering that outline, for example to demodulate AM radio or to time an ultrasound echo.

An AM tone (blue) with its true envelope (dashed), the rectify-and-low-pass envelope (orange) and the Hilbert envelope ±|z| (yellow); below, each method's error (sample data). Try the interactive version, with an echo train, a chirp, noise and a cutoff slider.
- The Hilbert transform delays every frequency by a quarter cycle (−90° for positive frequencies, +90° for negative ones), so . Its frequency response is .
- The analytic signal has no negative frequencies. Its magnitude is the envelope, and its angle is the instantaneous phase.
- Instantaneous frequency is how fast that phase turns: .
- Digitally, compute it with an FFT (zero the negative bins, double the positive ones) or an FIR Hilbert transformer for real-time streams.
- In hardware, a diode envelope detector rectifies and low-pass filters; the envelope detector circuit guide covers choosing its R and C.
What the Hilbert transform does: a quarter-cycle phase shift
Picture a signal as a sum of sine waves. The Hilbert transform takes each one and delays it by a quarter of its own cycle: a 10 Hz wave by 25 ms, a 1 kHz wave by 0.25 ms. Every wave keeps its frequency and its size; only its timing moves.
| Input | Hilbert transform | What happened |
|---|---|---|
| A quarter cycle later | ||
| A quarter cycle later | ||
| , with slower than | The carrier shifts and the slow amplitude passes through unchanged (Bedrosian's theorem, which holds when has no frequencies as high as ) | |
| A constant (DC) | 0 | Zero frequency has no phase to shift |
| Two quarter-cycle shifts make a half cycle: an inversion |
Because the amplitude never changes, the transformed signal has exactly the same spectrum magnitude and the same energy as the original (apart from any DC, which is lost). It is an all-pass filter, which shifts phase and leaves amplitude alone.
The definition
Mathematically, the Hilbert transform is the convolution of the signal with :
The "p.v." (Cauchy principal value) means the integral is taken symmetrically around , where blows up. In the frequency domain, convolution becomes multiplication (see convolution), and the Fourier transform of is
Multiplying by is a rotation by −90°, and by a rotation by +90°. So the transform turns each frequency by a quarter-turn, in opposite directions for positive and negative frequencies. It's named after David Hilbert, whose 1905 work on analytic functions introduced it; its use in signal processing began with Dennis Gabor's analytic signal in 1946.
The analytic signal: no negative frequencies
A real signal's spectrum is symmetric: every positive frequency has a mirror image at the matching negative frequency (the reason an FFT shows a mirrored second half). The analytic signal removes that redundancy:
Its spectrum is : doubled for positive frequencies, kept as is at 0 Hz, and zero for negative frequencies. The two mirror-image halves cancel on the negative side and add on the positive side.
A signal with only positive frequencies can be drawn as a single arrow spinning one way around the complex plane. For a tone, gives : an arrow of fixed length turning times a second. The real signal is that arrow's shadow on the real axis. For a modulated signal, the arrow's length and speed change slowly, and they are exactly the envelope and the instantaneous frequency.
Instantaneous amplitude, phase and frequency
Write the analytic signal in polar form, . Then:
| Quantity | Formula | What it means |
|---|---|---|
| Instantaneous amplitude (the envelope) | The size of the oscillation at each moment | |
| Instantaneous phase | Where in its cycle the signal is | |
| Instantaneous frequency | How fast it is cycling right now, in Hz |
Instantaneous frequency only means something for a narrowband signal, one with a single dominant oscillation at a time, such as a tone, a chirp or a modulated carrier. Add two tones of similar size and the arrow traces loops; its speed then wobbles and can even go negative, which no one would call "the frequency". For multi-component signals, split them first, for example with a band-pass filter or a spectrogram.
Why does the Hilbert envelope have no ripple?
For a steady tone, and , so at every instant. Squaring and adding a signal and its quarter-cycle-shifted copy cancels the carrier completely. A rectifier, by contrast, gives , which still bounces twice per cycle and has to be smoothed.
Worked examples: an AM tone and an 8-point FFT
For an AM tone, take a 200 Hz carrier whose amplitude follows a 3 Hz message at 80% depth: . The message is far slower than the carrier, so Bedrosian's theorem applies and . Then exactly: the envelope peaks at 1.8 at and falls to 0.2 at s. The phase is , so the instantaneous frequency is a constant 200 Hz.
For an 8-point FFT, sample one cycle of a cosine 8 times, . Its FFT has and (the mirror image), and zeros elsewhere. Double bin 1 and zero bin 7: , everything else 0. The inverse FFT gives : the real part is the cosine, the imaginary part is the sine (), and at every sample.
How to compute the Hilbert transform digitally
There are two standard ways: one for a recorded block of samples, and one for a live stream.
The FFT method (for a block of samples)
This is what scipy.signal.hilbert and MATLAB's hilbert do (Marple, 1999):
- Remove the mean (the DC offset). A constant offset adds to but not to , so it makes the envelope wobble at the carrier frequency.
- Zero pad to a power of 2, at least twice the length, if you use a radix-2 FFT. The FFT treats the block as repeating; padding stops the end of the block wrapping onto its start.
- FFT the samples to get bins .
- Build the analytic spectrum. Keep (DC) and (Nyquist) once, double bins to (the positive frequencies), and set to zero bins to (the negative frequencies).
- Inverse FFT. The result is the analytic signal : its real part is your signal again, its imaginary part is the Hilbert transform, and is the envelope.
While you are in the frequency domain, you can also zero the bins outside the band you care about, which band-pass filters the signal at no extra cost and keeps broadband noise out of the envelope.
The FIR Hilbert transformer (for a stream)
For real-time processing, a finite impulse response (FIR) filter approximates the transform sample by sample (see FIR vs IIR filters). The ideal discrete Hilbert transformer's impulse response is
so , , and so on. It goes on forever, so practical filters keep taps either side of the centre and taper them with a window such as Hamming. A practical FIR Hilbert transformer:
- Has odd length and is antisymmetric, , which is what makes the phase shift exactly 90° at every frequency.
- Has every other tap zero. A 31-tap filter has only 16 non-zero taps, in ± pairs, so it needs just 8 multiplications per output sample.
- Can't work near 0 Hz or the Nyquist frequency. An odd-length antisymmetric filter always has zero gain at both. We measured a 31-tap Hamming-windowed design: its gain is within 0.1 dB of 1 from to and within 1 dB from . Longer filters widen the band: 63 taps hold 0.1 dB from .
- Delays the output by samples (15 for 31 taps), so delay the original signal by the same amount before pairing it with the Hilbert output, or the envelope ripples.
| FFT method | FIR Hilbert transformer | |
|---|---|---|
| Works on | A whole block, after it's recorded | A stream, one sample at a time |
| Accuracy | Exact inside the block, with errors near its ends | A small ripple across the band; useless near 0 Hz and |
| Delay | None (it sees the whole block) | samples, constant |
| Cost | About per block | A few multiplications per sample |
| Typical use | Offline analysis, Python and MATLAB | Radios, single-sideband and I/Q processing, real-time audio |
Edge effects: why you window or pad
The FFT method assumes the block repeats forever, and the convolution kernel dies away only slowly. So samples near the start and end of the block are computed from a signal that suddenly stops. We measured the AM tone from the worked example above, with no band-pass: the envelope is more than 10% wrong for the first 3 ms and more than 1% wrong for about the first 50 ms (ten carrier cycles), while the middle is accurate to about 0.1%.
- Zero pad to at least twice the length, so the end doesn't wrap around onto the start.
- Taper the ends with a short window, or record a little extra either side and throw it away.
- Ignore the edges when you measure, for example the first and last 10% of the block.
- An FIR transformer has the same problem for its first samples, while its delay line fills.
Envelope detection methods compared
An envelope detector, in hardware or software, recovers the slowly varying outline of a fast oscillation. All four common methods agree on a clean, steady tone; they differ in ripple, delay and cost.
Adapted from Burnett-Thompson (2007).
| Method | How it works | Carrier ripple | Delay | Best for |
|---|---|---|---|---|
| Rectify + low-pass | Take , then a low-pass filter; scale by to read the peak (the average of is ) | At twice the carrier, reduced by the filter | The filter's delay: about 11 ms for a 2nd-order 20 Hz Butterworth | Diode envelope detectors in AM radios, EMG "linear envelope", simple embedded code |
| Square-law + low-pass + square root | Square , low-pass, then the result | At twice the carrier, reduced by the filter | The filter's delay | RF power detectors (a diode at low level is square-law), RMS meters |
| Hilbert magnitude | None for a narrowband signal | None offline; samples with an FIR | Vibration envelope spectra, ultrasound, instantaneous frequency, accurate timing | |
| Peak-hold (attack and release) | Jump up to each new peak quickly, decay slowly between them | A sawtooth set by the release time | Set by the attack time | Audio compressors, gates and level meters |
Why does the Hilbert method need less filtering?
A full-wave rectifier gives two bumps per carrier cycle, so the filter after it must remove a strong ripple at twice the carrier frequency. Adding the rectified signal to its rectified quarter-cycle-shifted copy (quadrature rectification) already gives four smaller bumps per cycle that fill in each other's gaps. Squaring and adding instead, , leaves no bumps at all for a steady tone. Any filter afterwards only has to deal with noise, so it can be much gentler, and gentler means less delay.
In the live example, with the AM tone at a 20 Hz cutoff, the readout shows the rectify-and-low-pass envelope about 11 ms late; slide the cutoff down to 5 Hz and the delay grows to about 49 ms while the envelope's dips get shallower. The Hilbert envelope stays on time. Then pick the echo train and see how a low cutoff smears and delays each echo, which in a ranging system is a distance error.
The diode envelope detector circuit
The simplest hardware envelope detector, used in most AM radios, is a diode followed by a capacitor and a resistor in parallel. The diode charges the capacitor to each carrier peak, and the resistor lets it discharge slowly between peaks, so the capacitor voltage follows the envelope. Its time constant must be long compared with a carrier cycle, or the output ripples, and short compared with the message, or the output cuts across the troughs (diagonal clipping). The envelope detector circuit guide covers choosing R and C, the diode drop and precision detectors, with a circuit simulator. In software, the same circuit is a rectifier followed by a single-pole low-pass filter, or a peak-hold with exponential release.
Hilbert transform vs Fourier transform, quadrature demodulation and other tools
| If you need… | Use | Why |
|---|---|---|
| Which frequencies a signal contains | Fourier transform or FFT | It moves to the frequency domain; the Hilbert transform stays in time |
| The envelope or instantaneous phase of a recorded narrowband signal | Hilbert transform (FFT method) | No ripple, no delay, and it gives the phase as well |
| The envelope of a live signal in hardware | Diode envelope detector, or rectify + low-pass in code | Cheap and simple, if some delay and ripple are acceptable |
| The amplitude and phase at one known frequency, buried in noise | Quadrature (I/Q) demodulation, as in a lock-in amplifier | Multiplies by a reference sine and cosine, then low-pass filters both; very narrow bandwidth rejects noise |
| How several frequencies change over time | Spectrogram | Instantaneous frequency only works for one component at a time |
| How similar a signal is to a delayed copy of itself | Autocorrelation | Correlating envelopes, rather than raw signals, gives a cleaner time-delay peak for echoes |
What the Hilbert transform and envelope detection are used for
- AM demodulation: the envelope of an AM broadcast is the audio. A diode envelope detector does it in hardware; a software radio takes .
- Single-sideband (SSB) modulation: mixing a signal and its Hilbert transform with a cosine and a sine carrier cancels one sideband, halving the bandwidth used.
- Vibration and bearing fault analysis: a cracked bearing race produces a burst of high-frequency ringing every time a ball passes the crack. Band-pass around the ringing, take the envelope, then an FFT of the envelope: the envelope spectrum shows peaks at the ball-pass rate, which identifies the faulty part (Randall and Antoni, 2011).
- Ultrasound imaging and echo ranging: each ultrasound echo is a short burst of a few megahertz. B-mode scanners take its envelope, then compress it to a log scale, to make the grey-level image; sonar and radar time echoes from their envelopes.
- EMG and EEG amplitude: muscle activity is read from the rectified, smoothed EMG (its "linear envelope"); the amplitude of a brain rhythm, such as the alpha band, from the Hilbert envelope of the band-passed EEG.
- Audio: compressors, limiters, noise gates and level meters all follow the envelope, usually with separate attack and release times.
- Instantaneous frequency of chirps: radar, sonar and bat calls sweep their frequency; the derivative of the analytic signal's phase shows the sweep sample by sample, with no FFT block to blur it.
Common Hilbert transform and envelope detection mistakes
- Applying it to a broadband signal and expecting a meaningful envelope. The envelope and instantaneous frequency only make sense for a narrowband signal. Band-pass filter around the component you want first.
- Forgetting that the analytic signal is complex.
scipy.signal.hilbertand MATLABhilbertreturn , not . Take the imaginary part for the transform and the magnitude for the envelope. - A low-pass cutoff that's too low after rectifying. It removes ripple, but also delays and flattens the envelope; in a ranging system that delay is a distance error.
- Differentiating a noisy phase. Instantaneous frequency amplifies noise, especially where the envelope is small. Band-pass first, and smooth the frequency, not the phase.
How to compute the Hilbert transform and envelope in JavaScript, React or Angular
SciChart.js draws signals with WebGL and WebGPU, so you can recompute a Hilbert transform and redraw thousands of samples every time a control moves. In the example below, the top chart shows a signal (blue), its true envelope (dashed white), the rectify-and-low-pass envelope (orange) and the Hilbert envelope (yellow). The bottom chart shows each envelope's error against the truth, or, for the chirp, the instantaneous frequency from the analytic signal's phase.
Choose the signal (an AM tone, an echo train like ultrasound or sonar, or a linear chirp), the modulation depth of the AM tone and the noise level. Method shows either envelope or both, Low-pass cutoff sets the filter after the rectifier, and Band-pass before Hilbert removes noise outside the carrier band, using the same cutoff. The readout gives each method's delay and its remaining ripple and noise. Scroll to zoom, drag to pan, double-click to reset, and hover for values.
Here is the code for this example. The FFT, the analytic signal and both envelope methods are plain JavaScript; the charts are ordinary SciChart.js line series.
- JavaScript
- React
- Angular
// Envelope detection two ways (rectify + low-pass, and the Hilbert transform), charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// --- DSP helpers (plain JavaScript, no library needed) ---
// In-place radix-2 FFT (re and im have a power-of-two length)
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) {
[re[i], re[j]] = [re[j], re[i]];
[im[i], im[j]] = [im[j], im[i]];
}
}
for (let size = 2; size <= n; size *= 2) {
const half = size / 2;
const step = (-2 * Math.PI) / size;
for (let start = 0; start < n; start += size) {
for (let k = 0; k < half; k++) {
const wr = Math.cos(step * k);
const wi = Math.sin(step * k);
const a = start + k;
const b = a + half;
const tr = re[b] * wr - im[b] * wi;
const ti = re[b] * wi + im[b] * wr;
re[b] = re[a] - tr;
im[b] = im[a] - ti;
re[a] += tr;
im[a] += ti;
}
}
}
}
// The analytic signal z = x + i H{x}, by the FFT method:
// 1. remove the mean (DC) and zero pad to at least twice the length, so the end doesn't wrap onto the start;
// 2. FFT; 3. double the positive-frequency bins, keep bin 0 (DC) and bin size/2 (Nyquist) once,
// and zero the negative-frequency bins; 4. inverse FFT.
// The real part of z is the signal; the imaginary part is its Hilbert transform.
// Optional band = { low, high, taper } in Hz: while in the frequency domain, also remove the bins outside
// the band, a free band-pass filter that keeps broadband noise out of the envelope.
function analyticSignal(values, sampleRate, band) {
const n = values.length;
let size = 1;
while (size < 2 * n) size *= 2;
const re = new Float64Array(size);
const im = new Float64Array(size);
const mean = values.reduce((sum, v) => sum + v, 0) / n;
for (let i = 0; i < n; i++) re[i] = values[i] - mean;
fft(re, im);
for (let k = 1; k < size / 2; k++) {
re[k] *= 2;
im[k] *= 2;
}
for (let k = size / 2 + 1; k < size; k++) {
re[k] = 0;
im[k] = 0;
}
if (band) {
for (let k = 0; k <= size / 2; k++) {
const f = (k * sampleRate) / size;
// Full gain inside the band, then a smooth (raised-cosine) roll-off to zero over band.taper Hz,
// which rings far less than cutting the bins off sharply
const outside = Math.max(band.low - f, f - band.high, 0) / band.taper;
const gain = outside >= 1 ? 0 : 0.5 + 0.5 * Math.cos(Math.PI * outside);
re[k] *= gain;
im[k] *= gain;
}
}
// Inverse FFT with the forward one: conjugate, FFT, conjugate again and divide by size
for (let k = 0; k < size; k++) im[k] = -im[k];
fft(re, im);
const zRe = new Float64Array(n);
const zIm = new Float64Array(n);
for (let i = 0; i < n; i++) {
zRe[i] = re[i] / size;
zIm[i] = -im[i] / size;
}
return { re: zRe, im: zIm };
}
// Instantaneous frequency: how fast the analytic signal's phase turns, divided by 2 pi.
// The angle of z[i+1] times the conjugate of z[i-1] is the phase step over two samples, with no unwrapping.
function instantaneousFrequency(z, sampleRate) {
const n = z.re.length;
const f = new Float64Array(n);
for (let i = 1; i < n - 1; i++) {
const re = z.re[i + 1] * z.re[i - 1] + z.im[i + 1] * z.im[i - 1];
const im = z.im[i + 1] * z.re[i - 1] - z.re[i + 1] * z.im[i - 1];
f[i] = (Math.atan2(im, re) * sampleRate) / (4 * Math.PI);
}
f[0] = f[1];
f[n - 1] = f[n - 2];
return f;
}
// Second-order Butterworth low-pass filter (a biquad), run forwards in time like an analogue circuit,
// so its delay shows. Its delay at low frequencies is about sqrt(2) / (2 pi cutoff) seconds.
function lowPass(values, cutoffHz, sampleRate) {
const w0 = (2 * Math.PI * cutoffHz) / sampleRate;
const alpha = Math.sin(w0) / (2 * Math.SQRT1_2); // Q = 1 / sqrt(2): Butterworth
const cos = Math.cos(w0);
const a0 = 1 + alpha;
const b0 = (1 - cos) / 2 / a0;
const b1 = (1 - cos) / a0;
const a1 = (-2 * cos) / a0;
const a2 = (1 - alpha) / a0;
const out = new Float64Array(values.length);
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
for (let i = 0; i < values.length; i++) {
const y = b0 * values[i] + b1 * x1 + b0 * x2 - a1 * y1 - a2 * y2;
x2 = x1;
x1 = values[i];
y2 = y1;
y1 = y;
out[i] = y;
}
return out;
}
// Method 1, the classic: full-wave rectify, then low-pass filter away the carrier ripple.
// The average of |sin| is 2/pi of its peak, so scale by pi/2 to read the envelope's height.
function rectifyEnvelope(values, cutoffHz, sampleRate) {
const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
return lowPass(values.map((v) => (Math.abs(v - mean) * Math.PI) / 2), cutoffHz, sampleRate);
}
// Method 2: the magnitude of the analytic signal, |z| = sqrt(x^2 + H{x}^2)
function hilbertEnvelope(z) {
return z.re.map((re, i) => Math.hypot(re, z.im[i]));
}
// How far an envelope estimate is behind the true envelope (the shift, up to maxLagSeconds, that
// lines them up best), and the RMS error left once that delay is removed (carrier ripple plus noise).
// Ignores the first and last 10%, where the edge effects are.
function compareWithTruth(estimate, truth, sampleRate, maxLagSeconds) {
const n = truth.length;
const from = Math.floor(n * 0.1);
const to = Math.floor(n * 0.9);
const maxLag = Math.floor(maxLagSeconds * sampleRate);
const mean = truth.reduce((sum, v) => sum + v, 0) / n;
let bestLag = 0;
let best = -Infinity;
for (let lag = -maxLag; lag <= maxLag; lag++) {
let sum = 0;
for (let i = from; i < to; i++) sum += (estimate[i + lag] - mean) * (truth[i] - mean);
if (sum > best) {
best = sum;
bestLag = lag;
}
}
let squares = 0;
for (let i = from; i < to; i++) squares += (estimate[i + bestLag] - truth[i]) ** 2;
return { lagMs: (1000 * bestLag) / sampleRate, rmsError: Math.sqrt(squares / (to - from)) };
}
// --- Chart 1: the signal and its envelopes ---
const top = await SciChartSurface.create(ui.signalDiv, { theme: new SciChartJsNavyTheme() });
top.sciChartSurface.xAxes.add(new NumericAxis(top.wasmContext, { axisTitle: "Time (s)" }));
top.sciChartSurface.yAxes.add(
new NumericAxis(top.wasmContext, {
axisTitle: "Signal",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.05, 0.05)
})
);
const signalSeries = new XyDataSeries(top.wasmContext, { dataSeriesName: "Signal", dataIsSortedInX: true });
const trueSeries = new XyDataSeries(top.wasmContext, { dataSeriesName: "True envelope", dataIsSortedInX: true });
const rectifySeries = new XyDataSeries(top.wasmContext, {
dataSeriesName: "Rectify + low-pass",
dataIsSortedInX: true
});
const hilbertSeries = new XyDataSeries(top.wasmContext, {
dataSeriesName: "Hilbert envelope ±|z|",
dataIsSortedInX: true
});
const hilbertLowerSeries = new XyDataSeries(top.wasmContext, {
dataSeriesName: "Hilbert envelope −|z|",
dataIsSortedInX: true
});
const signalLine = new FastLineRenderableSeries(top.wasmContext, {
dataSeries: signalSeries,
stroke: "#3E8FC0",
strokeThickness: 1
});
const trueLine = new FastLineRenderableSeries(top.wasmContext, {
dataSeries: trueSeries,
stroke: "#FFFFFF",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
});
const rectifyLine = new FastLineRenderableSeries(top.wasmContext, {
dataSeries: rectifySeries,
stroke: "#F48420",
strokeThickness: 3
});
const hilbertLine = new FastLineRenderableSeries(top.wasmContext, {
dataSeries: hilbertSeries,
stroke: "#F5E663",
strokeThickness: 2.5
});
const hilbertLowerLine = new FastLineRenderableSeries(top.wasmContext, {
dataSeries: hilbertLowerSeries,
stroke: "#F5E663",
strokeThickness: 2.5
});
top.sciChartSurface.renderableSeries.add(signalLine, trueLine, rectifyLine, hilbertLine, hilbertLowerLine);
const topLegend = new LegendModifier({ showCheckboxes: true });
top.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
topLegend,
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// --- Chart 2: each method's error against the true envelope, or (for the chirp) instantaneous frequency ---
const lower = await SciChartSurface.create(ui.lowerDiv, { theme: new SciChartJsNavyTheme() });
lower.sciChartSurface.xAxes.add(new NumericAxis(lower.wasmContext, { axisTitle: "Time (s)" }));
const lowerYAxis = new NumericAxis(lower.wasmContext, {
axisTitle: "Envelope error",
autoRange: EAutoRange.Never // set in update()
});
lower.sciChartSurface.yAxes.add(lowerYAxis);
const rectifyErrorSeries = new XyDataSeries(lower.wasmContext, {
dataSeriesName: "Rectify + low-pass error",
dataIsSortedInX: true
});
const hilbertErrorSeries = new XyDataSeries(lower.wasmContext, {
dataSeriesName: "Hilbert error",
dataIsSortedInX: true
});
const trueFrequencySeries = new XyDataSeries(lower.wasmContext, {
dataSeriesName: "True frequency",
dataIsSortedInX: true
});
const hilbertFrequencySeries = new XyDataSeries(lower.wasmContext, {
dataSeriesName: "Instantaneous frequency (Hilbert)",
dataIsSortedInX: true
});
const rectifyErrorLine = new FastLineRenderableSeries(lower.wasmContext, {
dataSeries: rectifyErrorSeries,
stroke: "#F48420",
strokeThickness: 2
});
const hilbertErrorLine = new FastLineRenderableSeries(lower.wasmContext, {
dataSeries: hilbertErrorSeries,
stroke: "#F5E663",
strokeThickness: 1.5
});
const trueFrequencyLine = new FastLineRenderableSeries(lower.wasmContext, {
dataSeries: trueFrequencySeries,
stroke: "#FFFFFF",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
});
const hilbertFrequencyLine = new FastLineRenderableSeries(lower.wasmContext, {
dataSeries: hilbertFrequencySeries,
stroke: "#F5E663",
strokeThickness: 1.5
});
lower.sciChartSurface.renderableSeries.add(
rectifyErrorLine,
hilbertErrorLine,
hilbertFrequencyLine,
trueFrequencyLine
);
const lowerLegend = new LegendModifier({ showCheckboxes: true });
lower.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
lowerLegend,
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// Replace a data series' values
function setData(dataSeries, x, y) {
dataSeries.clear();
dataSeries.appendRange(x, Array.from(y));
}
// --- The controls: every change reruns the DSP and redraws ---
function update() {
const kind = ui.signalSelect.value;
const depth = Number(ui.depthInput.value) / 100;
const noiseLevel = Number(ui.noiseInput.value) / 100;
const cutoffHz = 2 * Math.pow(100, Number(ui.cutoffInput.value) / 100); // log scale, 2 to 200 Hz
const method = ui.methodSelect.value;
ui.depthInput.disabled = kind !== "am";
const useBand = ui.bandCheckbox.checked;
ui.cutoffInput.disabled = method === "hilbert" && !useBand;
ui.bandCheckbox.disabled = method === "rectify";
ui.depthOutput.textContent = `${Math.round(depth * 100)}%`;
ui.noiseOutput.textContent = noiseLevel.toFixed(2);
ui.cutoffOutput.textContent = `${cutoffHz < 10 ? cutoffHz.toFixed(1) : cutoffHz.toFixed(0)} Hz`;
const { x, y, envelope, frequency, carrierRange } = makeSignal(kind, depth, noiseLevel);
const rectified = rectifyEnvelope(y, cutoffHz, SAMPLE_RATE);
// The band-pass keeps the carrier range and rolls off to half gain at the cutoff on either side,
// so both methods pass about the same envelope bandwidth
const band = useBand
? { low: carrierRange[0] - cutoffHz / 2, high: carrierRange[1] + cutoffHz / 2, taper: cutoffHz }
: null;
const z = analyticSignal(y, SAMPLE_RATE, band);
const hilbert = hilbertEnvelope(z);
setData(signalSeries, x, y);
setData(trueSeries, x, envelope);
setData(rectifySeries, x, rectified);
setData(hilbertSeries, x, hilbert);
setData(hilbertLowerSeries, x, hilbert.map((v) => -v));
setData(rectifyErrorSeries, x, rectified.map((v, i) => v - envelope[i]));
setData(hilbertErrorSeries, x, hilbert.map((v, i) => v - envelope[i]));
setData(trueFrequencySeries, x, frequency);
const frequencies = instantaneousFrequency(z, SAMPLE_RATE);
setData(hilbertFrequencySeries, x, frequencies);
// Show only the series that apply to this signal and method, in the charts and in their legends
// (once includeSeries has been called, a legend lists only the series included)
topLegend.includeSeries(signalLine, true);
topLegend.includeSeries(trueLine, true);
const showRectify = method !== "hilbert";
const showHilbert = method !== "rectify";
const chirp = kind === "chirp";
const show = (series, legend, visible) => {
series.isVisible = visible;
legend.includeSeries(series, visible);
};
show(rectifyLine, topLegend, showRectify);
show(hilbertLine, topLegend, showHilbert);
hilbertLowerLine.isVisible = showHilbert;
topLegend.includeSeries(hilbertLowerLine, false); // one legend entry is enough for +|z| and -|z|
show(rectifyErrorLine, lowerLegend, showRectify && !chirp);
show(hilbertErrorLine, lowerLegend, showHilbert && !chirp);
show(trueFrequencyLine, lowerLegend, chirp);
show(hilbertFrequencyLine, lowerLegend, chirp);
// The lower chart's y-axis: the frequency range for the chirp; otherwise scaled to the errors away from
// the ends of the block, so the start-up and edge errors don't squash the rest
lowerYAxis.axisTitle = chirp ? "Frequency (Hz)" : "Envelope error";
lowerYAxis.labelProvider.precision = chirp ? 0 : 2;
if (chirp) {
lowerYAxis.visibleRange = new NumberRange(0, 1000);
} else {
let largest = 0.05;
for (let i = Math.floor(SAMPLE_COUNT / 10); i < Math.floor((SAMPLE_COUNT * 9) / 10); i++) {
if (showRectify) largest = Math.max(largest, Math.abs(rectified[i] - envelope[i]));
if (showHilbert) largest = Math.max(largest, Math.abs(hilbert[i] - envelope[i]));
}
lowerYAxis.visibleRange = new NumberRange(-1.2 * largest, 1.2 * largest);
}
// The readout. The chirp's envelope changes too slowly to measure a lag, so it reports the
// instantaneous frequency error instead.
const parts = [];
const maxLagSeconds = chirp ? 0 : 0.1;
const describe = (name, estimate) => {
const { lagMs, rmsError } = compareWithTruth(estimate, envelope, SAMPLE_RATE, maxLagSeconds);
const lag = chirp ? "" : `lag ${Math.round(lagMs) || 0} ms, `; // || 0 turns -0 into 0
parts.push(`${name}: ${lag}ripple and noise ${rmsError.toFixed(3)} RMS`);
};
if (showRectify) describe("Rectify + low-pass", rectified);
if (showHilbert) describe("Hilbert", hilbert);
if (chirp) {
const error = frequencies
.map((f, i) => f - frequency[i])
.slice(Math.floor(SAMPLE_COUNT / 10), Math.floor((SAMPLE_COUNT * 9) / 10));
const rms = Math.sqrt(error.reduce((sum, e) => sum + e * e, 0) / error.length);
parts.push(`instantaneous frequency error ${rms.toFixed(1)} Hz RMS`);
}
ui.summary.textContent = parts.join(" · ");
}
for (const input of [ui.depthInput, ui.noiseInput, ui.cutoffInput]) input.addEventListener("input", update);
for (const select of [ui.signalSelect, ui.methodSelect, ui.bandCheckbox]) select.addEventListener("change", update);
update();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// fft and analyticSignal: copy them from the JavaScript tab
import { analyticSignal } from "./hilbert";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Signal" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const z = analyticSignal(yValues, sampleRate, null); // z.re = signal, z.im = Hilbert transform
const envelope = Array.from(z.re, (re, i) => Math.hypot(re, z.im[i]));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Signal" }),
stroke: "#50C7E0",
strokeThickness: 1
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: envelope, dataSeriesName: "Envelope" }),
stroke: "#F5E663",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new LegendModifier(),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const EnvelopeChart = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// fft and analyticSignal: copy them from the JavaScript tab
import { analyticSignal } from "./hilbert";
@Component({
selector: "app-envelope-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class EnvelopeChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Signal" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const z = analyticSignal(yValues, sampleRate, null); // z.re = signal, z.im = Hilbert transform
const envelope = Array.from(z.re, (re, i) => Math.hypot(re, z.im[i]));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Signal" }),
stroke: "#50C7E0",
strokeThickness: 1
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: envelope, dataSeriesName: "Envelope" }),
stroke: "#F5E663",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new LegendModifier(),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- Each envelope is an ordinary line chart: an
XyDataSeriesof times and values, drawn by aFastLineRenderableSeries. The lower envelope is a second series with the values negated. - To update the charts when a control moves, the example keeps every data series and calls
clear()thenappendRange()with the new values; SciChart.js redraws on the next frame. SettingisVisibleon a series hides it without removing its data. - The Hilbert transform is the
analyticSignal()function: an FFT, a change to the bins and an inverse FFT, about 40 lines of plain JavaScript. Swap in any FFT library; the chart code stays the same. - The rectify-and-low-pass envelope runs its filter forwards in time, like a circuit, so its delay is real. Offline, you could run the filter forwards and then backwards to cancel the delay, but not the ripple-versus-bandwidth trade-off.
See it in the demo app: JavaScript audio waveform chart · React audio waveform chart · Angular audio waveform chart. It shows live audio from your microphone as a waveform, an FFT spectrum and a spectrogram.
Go deeper: SciChart.js line chart documentation, and the FFT guide for the FFT behind the Hilbert transform.
Frequently asked questions
What does the Hilbert transform do?
The Hilbert transform delays every frequency in a signal by a quarter of a cycle: positive frequencies are shifted by -90 degrees and negative frequencies by +90 degrees, and no amplitude changes. A cosine becomes a sine of the same frequency. Its main use is to build the analytic signal, from which you read a signal's envelope, instantaneous phase and instantaneous frequency.
What is the Hilbert transform of sin and cos?
The Hilbert transform of cos(2 pi f t) is sin(2 pi f t), and the Hilbert transform of sin(2 pi f t) is -cos(2 pi f t), for any frequency f above zero. Applying the transform twice gives the negative of the original signal, so the inverse Hilbert transform is the transform with a minus sign.
What is the difference between the Hilbert transform and the Fourier transform?
The Fourier transform changes a signal from time to frequency: it tells you which frequencies the signal contains. The Hilbert transform keeps the signal in time and only shifts the phase of each frequency by a quarter cycle. The two work together: the usual way to compute a Hilbert transform is to take an FFT, change the bins and take an inverse FFT.
How do you find the envelope of a signal?
The envelope is the slowly changing outline of a fast oscillation. In software, the most accurate way to find it is the magnitude of the analytic signal, the square root of x squared plus H(x) squared, computed with the Hilbert transform. A simpler way is to rectify the signal and low-pass filter it, which leaves some ripple and adds delay. In hardware, a diode envelope detector does the same with a diode, a capacitor and a resistor.
Does scipy.signal.hilbert or MATLAB hilbert return the Hilbert transform?
No. Both scipy.signal.hilbert(x) and MATLAB hilbert(x) return the analytic signal, x + iH(x), computed with the FFT method. The Hilbert transform itself is the imaginary part (numpy.imag or MATLAB imag), and the envelope is the absolute value (numpy.abs or MATLAB abs).
How do I compute the Hilbert transform in JavaScript?
Remove the mean, zero pad the samples to a power of 2 at least twice their length, and run an FFT. Double bins 1 to N/2 - 1, keep bin 0 and bin N/2 as they are, set the rest to zero, and run an inverse FFT. The result is the analytic signal: its imaginary part is the Hilbert transform and its magnitude is the envelope. With SciChart.js, draw the signal and its envelope as FastLineRenderableSeries.
Sources
- Gabor, D. (1946), Theory of communication. Part 1: The analysis of information. Journal of the Institution of Electrical Engineers, Part III, 93(26), 429–441. The analytic signal.
- Bedrosian, E. (1963), A product theorem for Hilbert transforms. Proceedings of the IEEE, 51(5), 868–869. When the Hilbert transform of is .
- Marple, S. L. (1999), Computing the discrete-time "analytic" signal via FFT. IEEE Transactions on Signal Processing, 47(9), 2600–2603. The FFT method, including the DC and Nyquist bins.
- Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson, chapter 12, Discrete Hilbert Transforms. The ideal discrete Hilbert transformer and FIR approximations.
- Lyons, R. G. (2010), Understanding Digital Signal Processing, 3rd edition, Prentice Hall, chapter 9, The Discrete Hilbert Transform. FIR Hilbert transformers and their delay.
- Smith, J. O., Spectral Audio Signal Processing, Center for Computer Research in Music and Acoustics (CCRMA), Stanford University. Analytic signals and Hilbert transform filters.
- Haykin, S. and Moher, M. (2009), Communication Systems, 5th edition, Wiley. Amplitude modulation and the envelope detector, including the diagonal-clipping limit.
- Randall, R. B. and Antoni, J. (2011), Rolling element bearing diagnostics: a tutorial. Mechanical Systems and Signal Processing, 25(2), 485–520. Envelope analysis of bearing faults.
- SciPy developers, scipy.signal.hilbert, SciPy documentation. Returns the analytic signal.
- Burnett-Thompson, A. (2007), A 3D Local Positioning System to track A Neutrally Buoyant Flow Follower, PhD thesis, chapter 3 (associated published paper). The envelope detection diagram (rectify and low-pass, and the Hilbert method that needs a gentler filter) is adapted from it.