Savitzky-Golay Filter
Mediumdifficulty
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 around the sample you care about:
| offset | |||||
|---|---|---|---|---|---|
| reading | 6 | 9 | 10 | 9 | 6 |
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:
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 and that made the total squared error as small as possible. Run that same machinery on the simplest model there is, a single constant , and ask for the that minimises
Differentiate, set to zero: , so , so .
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, , and fit
The value we want is the fitted curve at the centre of the window, and at that is just . Minimising means setting the derivative with respect to each of , and to zero, which gives three equations. Symmetric offsets make them collapse, because and kill every odd power:
The middle equation stands alone and hands you . The first and third are two equations in and . Double the first and subtract the third to eliminate , then back-substitute:
The fit collapses into five fixed numbers
Now expand that. and are both just sums of the five readings with known multipliers, so group by reading:
The weights don't depend on the readings. They're always 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 , so a constant signal comes through unchanged, exactly as it must. And on the five readings from the opening:
Exactly 10. The five readings lie on , and a fit that can represent that shape reproduces
it exactly. 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 or the only equation is , the weights are , 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.
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 term is the slope of the fitted parabola at the middle of the window, and the same grouping turns into fixed weights:
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.
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.
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.
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
. 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? The average is . The fit is
. 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.Show solution
What do the two negative weights do? Think about what the filter should output when the outer readings
are far below the inner ones. 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.Show solution
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.
All of this assumes readings arrive evenly spaced in time, because the offsets 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.
- A. Savitzky and M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures, Analytical Chemistry 36(8), 1964 - the original paper, which is where the tabulated convolution coefficients come from.
- WPILib: Filters - robotics filtering reference, including the linear-filter machinery these weights plug into.
- System Identification - the Control Lab lesson where the same least-squares normal equations fit a motor model instead of a window.
- Moving Average - the degree-0 case, and the filter this lesson is a correction to.