Skip to main content

Savitzky-Golay Filter

Mediumdifficulty

Prerequisites and a starting path

Read Moving Average and Low-Pass Filtering first. The derivation uses a parabola, a line of best fit, and one derivative. You can use the five-point filter at the end without following every step.

Your robot is driving toward an AprilTag and the vision pose jitters by a few centimeters from frame to frame, so you smooth it. The jitter goes away, but so does part of the real signal.

The average of a curve is not a point on the curve​

Forget noise for a moment. Take a signal with no noise at all, sampled five times, that happens to follow y=10−x2y = 10 - x^2 around the sample you care about:

offset xx−2-2−1-1001122
reading yy691096

The middle reading is exactly 10, and it is exactly right, because there is no noise. Now average the five readings the way a moving average would:

6+9+10+9+65=405=8\frac{6 + 9 + 10 + 9 + 6}{5} = \frac{40}{5} = 8

The filter says 8 when the truth is 10. There's no noise here at all, so cleaner readings won't help. Averaging asks "what single flat value best fits these five readings?", and for data that curves, the best flat value sits below the peak.

Blurring a photo. Blur a photo to hide the grain and the edges go soft too. The blur can't tell noise from a real edge, because both are places where neighboring pixels disagree.

Fit the shape the signal actually has​

A moving average is a least-squares fit​

You already fit a line to data in System Identification: you logged voltage and velocity, then picked the kSk_S and kVk_V that made the total squared error as small as possible. Run that same machinery on the simplest model there is, a single constant aa, and ask for the aa that minimises

E(a)=∑i(yi−a)2E(a) = \sum_{i} \left(y_i - a\right)^2

Differentiate, set to zero: −2∑i(yi−a)=0-2\sum_i (y_i - a) = 0, so ∑iyi=na\sum_i y_i = na, so a=1n∑iyia = \frac{1}{n}\sum_i y_i.

That's the average. So the moving average is a least-squares fit: the best horizontal line through the window. The 8 from the opening is the right answer to the wrong question. To fix it, fit a shape that can bend.

Fit a parabola instead​

Keep the window, keep least squares, and let the fitted shape curve. Number the samples by their offset from the centre, x=−2,−1,0,1,2x = -2, -1, 0, 1, 2, and fit

y=a+bx+cx2y = a + bx + cx^2

The value we want is the fitted curve at the centre of the window, and at x=0x = 0 that is just aa. Minimising ∑i(yi−a−bxi−cxi2)2\sum_i (y_i - a - bx_i - cx_i^2)^2 means setting the derivative with respect to each of aa, bb and cc to zero, which gives three equations. Symmetric offsets make them collapse, because ∑xi=0\sum x_i = 0 and ∑xi3=0\sum x_i^3 = 0 kill every odd power:

5a+10c=S010b=S110a+34c=S2\begin{aligned} 5a + 10c &= S_0 \\ 10b &= S_1 \\ 10a + 34c &= S_2 \end{aligned}

The middle equation stands alone and hands you b=S1/10b = S_1/10. The first and third are two equations in aa and cc. Double the first and subtract the third to eliminate aa, then back-substitute:

a=17S0−5S235a = \frac{17S_0 - 5S_2}{35}

The fit collapses into five fixed numbers​

Now expand that. S0S_0 and S2S_2 are both just sums of the five readings with known multipliers, so group by reading:

a=−3y−2+12y−1+17y0+12y1−3y235a = \frac{-3y_{-2} + 12y_{-1} + 17y_{0} + 12y_{1} - 3y_{2}}{35}

The weights don't depend on the readings. They're always (−3,12,17,12,−3)(-3, 12, 17, 12, -3) divided by 35. You do the algebra once on paper, and on the robot a Savitzky-Golay filter is five multiplies and some adds, the same cost as a moving average.

Two checks you can do by eye. The coefficients sum to −3+12+17+12−3=35-3+12+17+12-3 = 35, so a constant signal comes through unchanged, exactly as it must. And on the five readings from the opening:

−3(6)+12(9)+17(10)+12(9)−3(6)35=−18+108+170+108−1835=35035=10\frac{-3(6) + 12(9) + 17(10) + 12(9) - 3(6)}{35} = \frac{-18 + 108 + 170 + 108 - 18}{35} = \frac{350}{35} = 10

Exactly 10. The five readings lie on y=10−x2y = 10 - x^2, and a fit that can represent that shape reproduces it exactly.

off by 2average = 8fit = 10-2-1012

Same five readings, two models. The flat line is the best horizontal explanation of the data and still misses the centre by 2. The parabola passes through every point.

Where the moving average went​

Set the degree to 0 and the derivation shrinks: with no bb or cc the only equation is 5a=S05a = S_0, the weights are (1,1,1,1,1)/5(1, 1, 1, 1, 1)/5, and you're back to the moving average. Degree 1 fits a tilted line and, for a symmetric window, gives the same equal weights. Degree 2 is the first one that can bend.

Drag the degree slider from 0 upward and watch the weight bars change shape. At degree 0 they are a flat block. At degree 2 the outer two go negative, and those negative weights are exactly what lets the output climb above every reading in the window when the signal is peaking.

Live demoPolynomial fit versus flat average
True rangeNoisy vision readingMoving averageSavitzky-Golay
Both filters see the same window.
Fitting a degree-2 curve to each window.
Window: 13 samples (0.33 s)Output delay: 0.150 sLargest weight: 0.175
The weight applied to each sample in the window, oldest on the left. Bars below the line are negative, which is how the fit is able to lift a peak instead of flattening it.
Warn
Negative weights cut both ways.

A moving average always stays between the smallest and largest reading in its window. A Savitzky-Golay filter can go beyond them, because two of its weights are negative. On a real peak that's what you want. On a single wild reading it's a problem: the filter treats the spike as a curve and leans into it harder than an average would. Reject readings that jump further than the mechanism could physically move in one loop before they reach this filter.

Velocity from the same fit​

The bb term is the slope of the fitted parabola at the middle of the window, and the same grouping turns b=S1/10b = S_1/10 into fixed weights:

b=−2y−2−y−1+0y0+y1+2y210b = \frac{-2y_{-2} - y_{-1} + 0y_{0} + y_{1} + 2y_{2}}{10}

That's a velocity in units per sample; divide by the loop period to get units per second. The usual way to get velocity from a noisy position, subtracting two consecutive readings, is about the noisiest option there is. It doubles the noise variance while the real change between two samples is tiny. This estimate uses all five samples and costs one more multiply-and-add pass.

Precompute the weights, then it is a dot product​

None of the derivation runs on the robot. The weights are constants, so the Control Hub only does the multiplying and adding.

FTCFive-point quadratic smoothing
private static final double[] SG_SMOOTH = {-3.0 / 35, 12.0 / 35, 17.0 / 35, 12.0 / 35, -3.0 / 35};

private final double[] window = new double[SG_SMOOTH.length];
private int filled;

double smooth(double reading) {
System.arraycopy(window, 1, window, 0, window.length - 1);
window[window.length - 1] = reading;
if (filled < window.length) {
filled++;
return reading; // no full window yet, so pass the raw value through
}

double total = 0;
for (int i = 0; i < window.length; i++) {
total += window[i] * SG_SMOOTH[i];
}
return total;
}

The result describes the middle of the window, two samples behind the newest reading. A symmetric moving average has the same two-loop delay. If that's too much, evaluate the fitted parabola at the newest sample instead of the middle. The demo's second button does this, and you can see the weights change. It responds faster, but it's noticeably noisier, because it's predicting the edge of the window instead of the middle.

FTCCentre velocity from the same window
private static final double[] SG_SLOPE = {-0.2, -0.1, 0.0, 0.1, 0.2};

double centreVelocity(double loopSeconds) {
double perSample = 0;
for (int i = 0; i < window.length; i++) {
perSample += window[i] * SG_SLOPE[i];
}
return perSample / loopSeconds;
}

When you tune this, log the raw readings next to both outputs. If the smoothed line cuts off the tops of real peaks, the degree is too low for the shape or the window is too long for how fast the signal changes.

ExerciseCompute both filters by hand

Take the readings 4, 10, 12, 10, 5, which are noise-free samples of a signal peaking at the centre. Compute the five-point moving average, then the five-point quadratic Savitzky-Golay value using (−3,12,17,12,−3)/35(-3, 12, 17, 12, -3)/35. Which one recovers the peak, and by how much does the other miss?

Then answer the part that matters: if you doubled the window to nine samples, would the moving average's error get better or worse, and why?

Show solution

The average is (4+10+12+10+5)/5=41/5=8.2(4+10+12+10+5)/5 = 41/5 = 8.2. The fit is (−3(4)+12(10)+17(12)+12(10)−3(5))/35=(−12+120+204+120−15)/35=417/35=11.91(-3(4) + 12(10) + 17(12) + 12(10) - 3(5))/35 = (-12 + 120 + 204 + 120 - 15)/35 = 417/35 = 11.91.

The true peak is 12. The average misses by 3.8 and the fit by 0.09. The fit isn't exact because these readings aren't exactly a parabola, which is what real data looks like.

A wider window makes the average worse. It reaches further down both sides of the peak, so it averages in lower values and the result sinks. On a curved signal, the moving average's error grows with the window size, which is why "just average more samples" stops helping at some point.

ExerciseWhy the outer weights are negative

What do the two negative weights do? Think about what the filter should output when the outer readings are far below the inner ones.

Show solution

When the outer readings are well below the inner ones, the data is curving downward, and a parabola through them peaks above the middle reading. To report that, the filter has to push its output up, and subtracting the outer readings does exactly that. The further the edges drop, the more it lifts the answer. On a straight line the effect cancels out, so lines and constants pass through unchanged.

ExercisePick the setting for a real signal

You're filtering AprilTag range at 40 Hz while driving at about 1 m/s, and the vision noise is about 2 cm (one standard deviation). How would you choose between a 5-sample and a 21-sample quadratic fit? Think about how far the robot moves during one window and how much smoothing you need.

Dropped frames

All of this assumes readings arrive evenly spaced in time, because the offsets −2,−1,0,1,2-2, -1, 0, 1, 2 count samples, not seconds. When the vision pipeline drops frames, the filter keeps producing numbers, but the window covers more time than you think and the velocity comes out wrong. Timestamp your frames, and either throw out windows with gaps or fit against the real timestamps.

This filter and the moving average both work on a single sensor, and both only fight jitter. Neither can tell that your vision pose is off by a steady 10 cm, because a smooth wrong answer is still wrong. The rest of the module brings in a second sensor, starting with the complementary filter.

Sources & references