001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.math.filter;
006
007import edu.wpi.first.math.MathSharedStore;
008import edu.wpi.first.math.MathUsageId;
009import edu.wpi.first.util.DoubleCircularBuffer;
010import java.util.Arrays;
011import org.ejml.simple.SimpleMatrix;
012
013/**
014 * This class implements a linear, digital filter. All types of FIR and IIR filters are supported.
015 * Static factory methods are provided to create commonly used types of filters.
016 *
017 * <p>Filters are of the form: y[n] = (b0 x[n] + b1 x[n-1] + ... + bP x[n-P]) - (a0 y[n-1] + a2
018 * y[n-2] + ... + aQ y[n-Q])
019 *
020 * <p>Where: y[n] is the output at time "n" x[n] is the input at time "n" y[n-1] is the output from
021 * the LAST time step ("n-1") x[n-1] is the input from the LAST time step ("n-1") b0...bP are the
022 * "feedforward" (FIR) gains a0...aQ are the "feedback" (IIR) gains IMPORTANT! Note the "-" sign in
023 * front of the feedback term! This is a common convention in signal processing.
024 *
025 * <p>What can linear filters do? Basically, they can filter, or diminish, the effects of
026 * undesirable input frequencies. High frequencies, or rapid changes, can be indicative of sensor
027 * noise or be otherwise undesirable. A "low pass" filter smooths out the signal, reducing the
028 * impact of these high frequency components. Likewise, a "high pass" filter gets rid of slow-moving
029 * signal components, letting you detect large changes more easily.
030 *
031 * <p>Example FRC applications of filters: - Getting rid of noise from an analog sensor input (note:
032 * the roboRIO's FPGA can do this faster in hardware) - Smoothing out joystick input to prevent the
033 * wheels from slipping or the robot from tipping - Smoothing motor commands so that unnecessary
034 * strain isn't put on electrical or mechanical components - If you use clever gains, you can make a
035 * PID controller out of this class!
036 *
037 * <p>For more on filters, we highly recommend the following articles:<br>
038 * <a
039 * href="https://en.wikipedia.org/wiki/Linear_filter">https://en.wikipedia.org/wiki/Linear_filter</a>
040 * <br>
041 * <a href="https://en.wikipedia.org/wiki/Iir_filter">https://en.wikipedia.org/wiki/Iir_filter</a>
042 * <br>
043 * <a href="https://en.wikipedia.org/wiki/Fir_filter">https://en.wikipedia.org/wiki/Fir_filter</a>
044 * <br>
045 *
046 * <p>Note 1: calculate() should be called by the user on a known, regular period. You can use a
047 * Notifier for this or do it "inline" with code in a periodic function.
048 *
049 * <p>Note 2: For ALL filters, gains are necessarily a function of frequency. If you make a filter
050 * that works well for you at, say, 100Hz, you will most definitely need to adjust the gains if you
051 * then want to run it at 200Hz! Combining this with Note 1 - the impetus is on YOU as a developer
052 * to make sure calculate() gets called at the desired, constant frequency!
053 */
054public class LinearFilter {
055  private final DoubleCircularBuffer m_inputs;
056  private final DoubleCircularBuffer m_outputs;
057  private final double[] m_inputGains;
058  private final double[] m_outputGains;
059
060  private static int instances;
061
062  /**
063   * Create a linear FIR or IIR filter.
064   *
065   * @param ffGains The "feedforward" or FIR gains.
066   * @param fbGains The "feedback" or IIR gains.
067   */
068  public LinearFilter(double[] ffGains, double[] fbGains) {
069    m_inputs = new DoubleCircularBuffer(ffGains.length);
070    m_outputs = new DoubleCircularBuffer(fbGains.length);
071    m_inputGains = Arrays.copyOf(ffGains, ffGains.length);
072    m_outputGains = Arrays.copyOf(fbGains, fbGains.length);
073
074    instances++;
075    MathSharedStore.reportUsage(MathUsageId.kFilter_Linear, instances);
076  }
077
078  /**
079   * Creates a one-pole IIR low-pass filter of the form: y[n] = (1-gain) x[n] + gain y[n-1] where
080   * gain = e<sup>-dt / T</sup>, T is the time constant in seconds.
081   *
082   * <p>Note: T = 1 / (2 pi f) where f is the cutoff frequency in Hz, the frequency above which the
083   * input starts to attenuate.
084   *
085   * <p>This filter is stable for time constants greater than zero.
086   *
087   * @param timeConstant The discrete-time time constant in seconds.
088   * @param period The period in seconds between samples taken by the user.
089   * @return Linear filter.
090   */
091  public static LinearFilter singlePoleIIR(double timeConstant, double period) {
092    double gain = Math.exp(-period / timeConstant);
093    double[] ffGains = {1.0 - gain};
094    double[] fbGains = {-gain};
095
096    return new LinearFilter(ffGains, fbGains);
097  }
098
099  /**
100   * Creates a first-order high-pass filter of the form: y[n] = gain x[n] + (-gain) x[n-1] + gain
101   * y[n-1] where gain = e<sup>-dt / T</sup>, T is the time constant in seconds.
102   *
103   * <p>Note: T = 1 / (2 pi f) where f is the cutoff frequency in Hz, the frequency below which the
104   * input starts to attenuate.
105   *
106   * <p>This filter is stable for time constants greater than zero.
107   *
108   * @param timeConstant The discrete-time time constant in seconds.
109   * @param period The period in seconds between samples taken by the user.
110   * @return Linear filter.
111   */
112  public static LinearFilter highPass(double timeConstant, double period) {
113    double gain = Math.exp(-period / timeConstant);
114    double[] ffGains = {gain, -gain};
115    double[] fbGains = {-gain};
116
117    return new LinearFilter(ffGains, fbGains);
118  }
119
120  /**
121   * Creates a K-tap FIR moving average filter of the form: y[n] = 1/k (x[k] + x[k-1] + ... + x[0]).
122   *
123   * <p>This filter is always stable.
124   *
125   * @param taps The number of samples to average over. Higher = smoother but slower.
126   * @return Linear filter.
127   * @throws IllegalArgumentException if number of taps is less than 1.
128   */
129  public static LinearFilter movingAverage(int taps) {
130    if (taps <= 0) {
131      throw new IllegalArgumentException("Number of taps was not at least 1");
132    }
133
134    double[] ffGains = new double[taps];
135    Arrays.fill(ffGains, 1.0 / taps);
136
137    double[] fbGains = new double[0];
138
139    return new LinearFilter(ffGains, fbGains);
140  }
141
142  /**
143   * Creates a finite difference filter that computes the nth derivative of the input given the
144   * specified stencil points.
145   *
146   * <p>Stencil points are the indices of the samples to use in the finite difference. 0 is the
147   * current sample, -1 is the previous sample, -2 is the sample before that, etc. Don't use
148   * positive stencil points (samples from the future) if the LinearFilter will be used for
149   * stream-based online filtering (e.g., taking derivative of encoder samples in real-time).
150   *
151   * @param derivative The order of the derivative to compute.
152   * @param stencil List of stencil points. Its length is the number of samples to use to compute
153   *     the given derivative. This must be one more than the order of the derivative or higher.
154   * @param period The period in seconds between samples taken by the user.
155   * @return Linear filter.
156   * @throws IllegalArgumentException if derivative &lt; 1, samples &lt;= 0, or derivative &gt;=
157   *     samples.
158   */
159  public static LinearFilter finiteDifference(int derivative, int[] stencil, double period) {
160    // See
161    // https://en.wikipedia.org/wiki/Finite_difference_coefficient#Arbitrary_stencil_points
162    //
163    // For a given list of stencil points s of length n and the order of
164    // derivative d < n, the finite difference coefficients can be obtained by
165    // solving the following linear system for the vector a.
166    //
167    // [s₁⁰   ⋯  sₙ⁰ ][a₁]      [ δ₀,d ]
168    // [ ⋮    ⋱  ⋮   ][⋮ ] = d! [  ⋮   ]
169    // [s₁ⁿ⁻¹ ⋯ sₙⁿ⁻¹][aₙ]      [δₙ₋₁,d]
170    //
171    // where δᵢ,ⱼ are the Kronecker delta. The FIR gains are the elements of the
172    // vector 'a' in reverse order divided by hᵈ.
173    //
174    // The order of accuracy of the approximation is of the form O(hⁿ⁻ᵈ).
175
176    if (derivative < 1) {
177      throw new IllegalArgumentException(
178          "Order of derivative must be greater than or equal to one.");
179    }
180
181    int samples = stencil.length;
182
183    if (samples <= 0) {
184      throw new IllegalArgumentException("Number of samples must be greater than zero.");
185    }
186
187    if (derivative >= samples) {
188      throw new IllegalArgumentException(
189          "Order of derivative must be less than number of samples.");
190    }
191
192    var S = new SimpleMatrix(samples, samples);
193    for (int row = 0; row < samples; ++row) {
194      for (int col = 0; col < samples; ++col) {
195        S.set(row, col, Math.pow(stencil[col], row));
196      }
197    }
198
199    // Fill in Kronecker deltas: https://en.wikipedia.org/wiki/Kronecker_delta
200    var d = new SimpleMatrix(samples, 1);
201    for (int i = 0; i < samples; ++i) {
202      d.set(i, 0, (i == derivative) ? factorial(derivative) : 0.0);
203    }
204
205    var a = S.solve(d).divide(Math.pow(period, derivative));
206
207    // Reverse gains list
208    double[] ffGains = new double[samples];
209    for (int i = 0; i < samples; ++i) {
210      ffGains[i] = a.get(samples - i - 1, 0);
211    }
212
213    return new LinearFilter(ffGains, new double[0]);
214  }
215
216  /**
217   * Creates a backward finite difference filter that computes the nth derivative of the input given
218   * the specified number of samples.
219   *
220   * <p>For example, a first derivative filter that uses two samples and a sample period of 20 ms
221   * would be
222   *
223   * <pre><code>
224   * LinearFilter.backwardFiniteDifference(1, 2, 0.02);
225   * </code></pre>
226   *
227   * @param derivative The order of the derivative to compute.
228   * @param samples The number of samples to use to compute the given derivative. This must be one
229   *     more than the order of derivative or higher.
230   * @param period The period in seconds between samples taken by the user.
231   * @return Linear filter.
232   */
233  public static LinearFilter backwardFiniteDifference(int derivative, int samples, double period) {
234    // Generate stencil points from -(samples - 1) to 0
235    int[] stencil = new int[samples];
236    for (int i = 0; i < samples; ++i) {
237      stencil[i] = -(samples - 1) + i;
238    }
239
240    return finiteDifference(derivative, stencil, period);
241  }
242
243  /** Reset the filter state. */
244  public void reset() {
245    m_inputs.clear();
246    m_outputs.clear();
247  }
248
249  /**
250   * Resets the filter state, initializing internal buffers to the provided values.
251   *
252   * <p>These are the expected lengths of the buffers, depending on what type of linear filter used:
253   *
254   * <table>
255   * <tr><th>Type</th><th>Input Buffer Length</th><th>Output Buffer Length</th></tr>
256   * <tr><td>Unspecified</td><td>length of {@code ffGains}</td><td>length of {@code fbGains}</td>
257   * </tr>
258   * <tr><td>Single Pole IIR</td><td>1</td><td>1</td></tr>
259   * <tr><td>High-Pass</td><td>2</td><td>1</td></tr>
260   * <tr><td>Moving Average</td><td>{@code taps}</td><td>0</td></tr>
261   * <tr><td>Finite Difference</td><td>length of {@code stencil}</td><td>0</td></tr>
262   * <tr><td>Backward Finite Difference</td><td>{@code samples}</td><td>0</td></tr>
263   * </table>
264   *
265   * @param inputBuffer Values to initialize input buffer.
266   * @param outputBuffer Values to initialize output buffer.
267   * @throws IllegalArgumentException if length of inputBuffer or outputBuffer does not match the
268   *     length of ffGains and fbGains provided in the constructor.
269   */
270  public void reset(double[] inputBuffer, double[] outputBuffer) {
271    // Clear buffers
272    reset();
273
274    if (inputBuffer.length != m_inputGains.length || outputBuffer.length != m_outputGains.length) {
275      throw new IllegalArgumentException("Incorrect length of inputBuffer or outputBuffer");
276    }
277
278    for (double input : inputBuffer) {
279      m_inputs.addFirst(input);
280    }
281    for (double output : outputBuffer) {
282      m_outputs.addFirst(output);
283    }
284  }
285
286  /**
287   * Calculates the next value of the filter.
288   *
289   * @param input Current input value.
290   * @return The filtered value at this step
291   */
292  public double calculate(double input) {
293    double retVal = 0.0;
294
295    // Rotate the inputs
296    if (m_inputGains.length > 0) {
297      m_inputs.addFirst(input);
298    }
299
300    // Calculate the new value
301    for (int i = 0; i < m_inputGains.length; i++) {
302      retVal += m_inputs.get(i) * m_inputGains[i];
303    }
304    for (int i = 0; i < m_outputGains.length; i++) {
305      retVal -= m_outputs.get(i) * m_outputGains[i];
306    }
307
308    // Rotate the outputs
309    if (m_outputGains.length > 0) {
310      m_outputs.addFirst(retVal);
311    }
312
313    return retVal;
314  }
315
316  /**
317   * Returns the last value calculated by the LinearFilter.
318   *
319   * @return The last value.
320   */
321  public double lastValue() {
322    return m_outputs.getFirst();
323  }
324
325  /**
326   * Factorial of n.
327   *
328   * @param n Argument of which to take factorial.
329   */
330  private static int factorial(int n) {
331    if (n < 2) {
332      return 1;
333    } else {
334      return n * factorial(n - 1);
335    }
336  }
337}