Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions doc/analysis/FrequencyResponse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Frequency Response

## Overview & Motivation

The frequency response $H(e^{j\omega})$ characterizes how a discrete-time linear system (filter) modifies the amplitude and phase of each frequency component in a signal. Computing and plotting the frequency response (Bode plot) is essential for verifying filter designs, understanding system behavior, and tuning parameters. This implementation evaluates the transfer function at logarithmically spaced frequencies, producing magnitude (dB) and phase (degrees) curves.

## Mathematical Theory

### Transfer Function Evaluation

Given a filter with feedforward coefficients $\{b_i\}_{i=0}^{P-1}$ and feedback coefficients $\{a_i\}_{i=0}^{Q-1}$, the frequency response at angular frequency $\omega$ is:

$$H(e^{j\omega}) = \frac{\sum_{i=0}^{P-1} b_i \cdot e^{-j\omega i}}{\sum_{i=0}^{Q-1} a_i \cdot e^{-j\omega i}}$$

For FIR filters, the denominator reduces to $a_0 = 1$.

### Magnitude and Phase

From the complex-valued response:

$$|H(e^{j\omega})| = \sqrt{\text{Re}(H)^2 + \text{Im}(H)^2}$$

$$\text{Magnitude (dB)} = 20 \log_{10} |H(e^{j\omega})|$$

$$\text{Phase (degrees)} = \frac{180}{\pi} \cdot \arg(H(e^{j\omega}))$$

### Frequency Grid

Frequencies are evaluated on a logarithmic grid from $f_s / N$ to $f_s / 2$ (Nyquist), where $f_s$ is the sampling frequency and $N$ is the number of evaluation points. The angular frequency at each point is:

$$\omega_k = \frac{2\pi f_k}{f_s}$$

## Complexity Analysis

| Case | Time | Space | Notes |
|---------|--------------------|--------|------------------------------------------|
| Average | $O(N \cdot (P+Q))$ | $O(N)$ | $N$ frequency points, $P+Q$ coefficients |

## Step-by-Step Walkthrough

Given a simple first-order low-pass FIR filter with $b = [0.5, 0.5]$, $a = [1.0]$, and $f_s = 100$ Hz, evaluated at $f = 10$ Hz:

1. Compute $\omega = 2\pi \cdot 10 / 100 = 0.2\pi$
2. Numerator: $0.5 \cdot e^{0} + 0.5 \cdot e^{-j0.2\pi} = 0.5 + 0.5(\cos(0.2\pi) - j\sin(0.2\pi))$
- $= 0.5 + 0.5(0.809 - j0.588) = 0.905 - j0.294$
3. Denominator: $1.0$
4. $|H| = \sqrt{0.905^2 + 0.294^2} = 0.952$
5. Magnitude: $20\log_{10}(0.952) = -0.43$ dB
6. Phase: $\arctan(-0.294/0.905) = -18°$

## Pitfalls & Edge Cases

- **Zero denominator**: If the denominator evaluates to zero at a frequency, the implementation sets it to 1.0 to avoid division by zero. This produces a meaningful (if approximate) result near resonances.
- **QNumber conversion**: When coefficients are in Q15/Q31 format, they are converted to float via `math::ToFloat()` before evaluation. This ensures sufficient dynamic range for the complex arithmetic.
- **Logarithmic spacing**: Very low frequencies near DC may have sparse coverage. The lowest evaluated frequency is $f_s / N$.
- **Phase wrapping**: The `std::arg` function returns phase in $(-\pi, \pi]$. Phase unwrapping is not performed.

## Variants & Generalizations

- **Linear frequency spacing**: Alternative to logarithmic spacing for uniform frequency resolution.
- **Zero-pole form**: Evaluate directly from pole-zero locations rather than polynomial coefficients.
- **Chirp z-transform**: Generalization that evaluates the z-transform along arbitrary paths in the z-plane.

## Applications

- Verifying filter coefficient designs match the desired specification
- Bode plot generation for stability analysis
- Comparing filter topologies (FIR vs. IIR, different orders)
- System identification validation

## Connections to Other Algorithms

- **FIR / IIR Filters**: The frequency response evaluates the transfer functions implemented by `Fir` and `Iir` filters.
- **FFT**: The DFT of a zero-padded impulse response produces the frequency response at uniformly spaced frequencies. This class generalizes to arbitrary frequency points.
- **Root Locus**: Both frequency response and root locus analyze the same transfer function from complementary perspectives (frequency domain vs. pole-zero domain).
- **Power Density Spectrum**: PDS estimates the spectral content of a signal; frequency response characterizes the system that shapes it.

## References & Further Reading

- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapters 5–6.
- Proakis, J.G. and Manolakis, D.G., *Digital Signal Processing: Principles, Algorithms, and Applications*, 4th ed., Pearson, 2006 — Chapter 6.
- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapter 21.
94 changes: 94 additions & 0 deletions doc/estimators/RecursiveLeastSquares.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Recursive Least Squares (RLS)

## Overview & Motivation

Recursive Least Squares (RLS) is an online parameter estimation algorithm that incrementally updates a least-squares fit as new data arrives, without reprocessing past observations. It converges faster than gradient-descent methods (e.g., LMS) and is well-suited for real-time system identification and adaptive filtering on embedded systems.

## Mathematical Theory

### Problem Setting

Given a linear model $y = \mathbf{x}^T \boldsymbol{\theta} + \epsilon$, where $\mathbf{x} \in \mathbb{R}^p$ is the regressor, $\boldsymbol{\theta} \in \mathbb{R}^p$ are the unknown parameters, and $\epsilon$ is noise, RLS minimizes the exponentially weighted cost:

$$J(\boldsymbol{\theta}) = \sum_{k=1}^{n} \lambda^{n-k} (y_k - \mathbf{x}_k^T \boldsymbol{\theta})^2$$

where $\lambda \in (0, 1]$ is the forgetting factor.

### Update Equations

Given a new observation $(\mathbf{x}, y)$:

1. **Gain vector**: $\mathbf{g} = P \mathbf{x}$
2. **Denominator**: $d = \lambda + \mathbf{x}^T P \mathbf{x}$
3. **Innovation (pre-update error)**: $e = y - \mathbf{x}^T \hat{\boldsymbol{\theta}}$
4. **Parameter update**: $\hat{\boldsymbol{\theta}} \leftarrow \hat{\boldsymbol{\theta}} + \frac{\mathbf{g} \cdot e}{d}$
5. **Covariance update**: $P \leftarrow \frac{1}{\lambda}\left(P - \frac{\mathbf{g} \mathbf{g}^T}{d}\right)$

### Forgetting Factor

- $\lambda = 1$: Full memory — equivalent to batch least squares with all past data equally weighted.
- $\lambda < 1$: Exponential forgetting — recent data is weighted more heavily, enabling tracking of time-varying systems.
- Typical values: $0.95 \leq \lambda \leq 1.0$.

### Convergence Evaluation

The implementation provides convergence diagnostics via `EstimationMetrics`:
- **Innovation**: Pre-update prediction error magnitude
- **Residual**: Post-update prediction error magnitude
- **Uncertainty**: Trace of the covariance matrix $P$ (overall parameter uncertainty)

## Complexity Analysis

| Case | Time | Space | Notes |
|---------|----------|----------|----------------------------------------|
| Average | $O(p^2)$ | $O(p^2)$ | Matrix-vector products + outer product |

Per-update cost is $O(p^2)$ for $p$ parameters, dominated by the covariance update. This is significantly cheaper than the $O(p^3)$ batch solution via matrix inversion.

## Step-by-Step Walkthrough

Estimating the slope of $y = 2x$ with RLS ($p = 2$: bias + slope, $\lambda = 1$):

| Step | $\mathbf{x}$ | $y$ | $\hat{\theta}_0$ (bias) | $\hat{\theta}_1$ (slope) | Innovation |
|------|--------------|-----|-------------------------|--------------------------|------------|
| Init | — | — | 0.0 | 0.0 | — |
| 1 | [1, 1] | 2 | 1.0 | 1.0 | 2.0 |
| 2 | [1, 2] | 4 | 0.0 | 2.0 | 1.0 |
| 3 | [1, 3] | 6 | 0.0 | 2.0 | 0.0 |

Convergence is achieved in 2 steps for this noiseless system.

## Pitfalls & Edge Cases

- **Covariance blow-up**: With $\lambda < 1$ and insufficient excitation, the covariance matrix $P$ can grow unbounded. Monitor the uncertainty metric and consider covariance resetting.
- **Numerical conditioning**: The covariance update can lose symmetry and positive-definiteness due to floating-point errors. For long-running applications, consider using the Joseph form: $P \leftarrow (I - K\mathbf{x}^T)P(I - K\mathbf{x}^T)^T + K K^T / \lambda$.
- **Initial covariance**: A large initial $P$ (e.g., $\alpha I$ with $\alpha = 100$) gives fast initial convergence but higher initial sensitivity. A small $P$ gives conservative updates.
- **Regressor scaling**: Large differences in regressor magnitudes can cause numerical issues. Normalize inputs when possible.

## Variants & Generalizations

- **Weighted RLS**: Use a general weighting matrix instead of scalar forgetting.
- **QR-decomposition RLS**: Better numerical stability by avoiding explicit covariance updates.
- **Kalman filter**: RLS is equivalent to a steady-state Kalman filter for the linear regression problem.
- **Regularized RLS**: Add a regularization term $\mu \|\boldsymbol{\theta}\|^2$ to prevent overfitting.

## Applications

- Online system identification for adaptive control
- Adaptive noise cancellation
- Channel equalization in communications
- Real-time parameter tracking in engine/motor control
- Sensor calibration

## Connections to Other Algorithms

- **Linear Regression**: Batch (offline) version of the same problem. Linear regression solves via matrix inversion; RLS updates incrementally.
- **Yule-Walker**: Both estimate AR model parameters, but Yule-Walker uses autocorrelation statistics (offline) while RLS processes samples sequentially.
- **Kalman Filter**: RLS is a special case of the Kalman filter where the state transition is identity and the process noise is zero.
- **Gradient Descent**: LMS/gradient descent is a simpler adaptive algorithm with $O(p)$ cost but slower convergence compared to RLS's $O(p^2)$.

## References & Further Reading

- Haykin, S., *Adaptive Filter Theory*, 5th ed., Pearson, 2014 — Chapter 9.
- Ljung, L., *System Identification: Theory for the User*, 2nd ed., Prentice Hall, 1999 — Chapter 11.
- Åström, K.J. and Wittenmark, B., *Adaptive Control*, 2nd ed., Dover, 2008 — Chapter 2.
2 changes: 1 addition & 1 deletion doc/filters/active/KalmanFilter.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ $$y_k = z_k - H_k \hat{x}_k^- \qquad \text{(innovation)}$$
$$S_k = H_k P_k^- H_k^T + R_k \qquad \text{(innovation covariance)}$$
$$K_k = P_k^- H_k^T S_k^{-1} \qquad \text{(Kalman gain)}$$
$$\hat{x}_k = \hat{x}_k^- + K_k y_k \qquad \text{(state update)}$$
$$P_k = (I - K_k H_k) P_k^- \qquad \text{(covariance update)}$$
$$P_k = (I - K_k H_k) P_k^- (I - K_k H_k)^T + K_k R_k K_k^T \qquad \text{(Joseph form covariance update)}$$

### Optimality

Expand Down
85 changes: 85 additions & 0 deletions doc/filters/passive/Fir.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Finite Impulse Response (FIR) Filter

## Overview & Motivation

A Finite Impulse Response (FIR) filter is a discrete-time filter whose impulse response has a finite duration. FIR filters are inherently stable, have linear phase properties (when symmetric), and are straightforward to design and implement. They are the default choice for applications requiring guaranteed stability and predictable phase behavior.

## Mathematical Theory

### Core Definition

A causal FIR filter of order $N-1$ (with $N$ taps) computes the output as a weighted sum of the current and past inputs (discrete convolution):

$$y[n] = \sum_{i=0}^{N-1} b_i \cdot x[n-i]$$

where:
- $b_i$ are the filter coefficients (tap weights)
- $x[n-i]$ are the current and $N-1$ most recent input samples
- $N$ is the number of taps (filter length)

### Transfer Function

In the z-domain, the FIR filter transfer function is a polynomial in $z^{-1}$:

$$H(z) = \sum_{i=0}^{N-1} b_i z^{-i}$$

Since the denominator is unity, FIR filters have all poles at the origin and are always stable.

### Frequency Response

Evaluating on the unit circle ($z = e^{j\omega}$):

$$H(e^{j\omega}) = \sum_{i=0}^{N-1} b_i e^{-j\omega i}$$

## Complexity Analysis

| Case | Time | Space | Notes |
|---------|--------|--------|------------------------------------|
| Best | $O(N)$ | $O(N)$ | Disabled (passthrough) |
| Average | $O(N)$ | $O(N)$ | Convolution sum |
| Worst | $O(N)$ | $O(N)$ | Same — no data-dependent branching |

Time is per sample. Space is for the coefficient and delay line buffers.

## Step-by-Step Walkthrough

Given a 3-tap FIR filter with coefficients $b = [0.25, 0.5, 0.25]$ and input sequence $x = [1.0, 2.0, 3.0, 4.0]$:

| $n$ | $x[n]$ | $x[n-1]$ | $x[n-2]$ | $y[n] = 0.25 x[n] + 0.5 x[n-1] + 0.25 x[n-2]$ |
|-----|--------|----------|----------|-----------------------------------------------|
| 0 | 1.0 | 0.0 | 0.0 | 0.25 |
| 1 | 2.0 | 1.0 | 0.0 | 1.0 |
| 2 | 3.0 | 2.0 | 1.0 | 2.0 |
| 3 | 4.0 | 3.0 | 2.0 | 3.0 |

## Pitfalls & Edge Cases

- **Group delay**: A linear-phase FIR filter introduces a delay of $(N-1)/2$ samples. This must be accounted for in real-time control loops.
- **Fixed-point overflow**: When using Q15 or Q31 arithmetic, ensure the sum of absolute coefficient values does not exceed 1.0 to prevent saturation.
- **Coefficient quantization**: Converting floating-point coefficients to fixed-point can distort the frequency response, especially for narrowband filters with large $N$.
- **Initial transient**: The first $N-1$ outputs are computed with zero-padded history; these may not be representative of steady-state behavior.

## Variants & Generalizations

- **Windowed design**: FIR coefficients are often designed by applying a window function (Hamming, Hann, Blackman) to the ideal impulse response.
- **Equiripple (Parks-McClellan)**: Minimax optimal design that minimizes the maximum deviation from the desired response.
- **Polyphase decomposition**: For efficient multirate (decimation/interpolation) implementations.

## Applications

- Low-pass, high-pass, band-pass, and band-stop filtering
- Anti-aliasing before downsampling
- Matched filtering in communications
- Moving average smoothing (special case with equal coefficients)

## Connections to Other Algorithms

- **IIR Filter**: IIR filters achieve sharper cutoffs with fewer coefficients but sacrifice guaranteed stability and linear phase.
- **FFT**: For large $N$, the convolution can be computed more efficiently via FFT-based overlap-add/save methods.
- **Window Functions**: Window functions from the `windowing` module are used in FIR coefficient design.

## References & Further Reading

- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapter 7.
- Parks, T.W. and Burrus, C.S., *Digital Filter Design*, Wiley, 1987.
- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapters 14–16.
85 changes: 85 additions & 0 deletions doc/filters/passive/Iir.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Infinite Impulse Response (IIR) Filter

## Overview & Motivation

An Infinite Impulse Response (IIR) filter uses feedback from its own past outputs to achieve a desired frequency response. IIR filters can match the selectivity of high-order FIR filters using far fewer coefficients, making them efficient for resource-constrained embedded systems. The trade-off is potential instability and nonlinear phase.

## Mathematical Theory

### Core Definition

A causal IIR filter with $P$ feedforward coefficients and $Q$ feedback coefficients computes:

$$y[n] = \sum_{i=0}^{P-1} b_i \cdot x[n-i] + \sum_{i=0}^{Q-1} a_i \cdot y[n-i]$$

where:
- $b_i$ are the feedforward (numerator) coefficients
- $a_i$ are the feedback (denominator) coefficients
- $x[n-i]$ are past input samples
- $y[n-i]$ are past output samples

**Sign convention**: The implementation uses addition for the feedback term. This means the feedback coefficients $a_i$ must be provided with the appropriate sign (negated relative to the standard form $y[n] = \sum b_i x[n-i] - \sum a_i y[n-i]$).

### Transfer Function

$$H(z) = \frac{\sum_{i=0}^{P-1} b_i z^{-i}}{1 - \sum_{i=0}^{Q-1} a_i z^{-i}}$$

### Stability Criterion

The filter is stable if and only if all poles of $H(z)$ lie strictly inside the unit circle ($|z| < 1$). This must be verified at design time.

## Complexity Analysis

| Case | Time | Space | Notes |
|---------|----------|----------|---------------------------------|
| Best | $O(P+Q)$ | $O(P+Q)$ | Disabled (passthrough) |
| Average | $O(P+Q)$ | $O(P+Q)$ | Feedforward + feedback sums |
| Worst | $O(P+Q)$ | $O(P+Q)$ | Same — sequential, no branching |

Time is per sample. Space stores coefficient and delay line buffers.

## Step-by-Step Walkthrough

Given a first-order IIR (1 feedforward, 1 feedback) with $b_0 = 0.5$, $a_0 = 0.3$ and input $x = [1.0, 0.0, 0.0]$:

| $n$ | $x[n]$ | $y[n-1]$ | $y[n] = 0.5 \cdot x[n] + 0.3 \cdot y[n-1]$ |
|-----|--------|----------|--------------------------------------------|
| 0 | 1.0 | 0.0 | 0.5 |
| 1 | 0.0 | 0.5 | 0.15 |
| 2 | 0.0 | 0.15 | 0.045 |

The output decays exponentially — characteristic of IIR filters with $|a_0| < 1$.

## Pitfalls & Edge Cases

- **Instability**: If any pole has magnitude $\geq 1$, the output grows without bound. Always verify pole locations before deployment.
- **Coefficient quantization**: Fixed-point representation of feedback coefficients can shift pole locations, potentially pushing them outside the unit circle.
- **Limit cycles**: In fixed-point implementations, small-signal oscillations can occur due to quantization of the feedback path.
- **Overflow in feedback**: The recursive nature means accumulated rounding errors compound over time. Consider using higher-precision accumulators (Q31 for Q15 data).
- **Initial conditions**: Nonzero initial conditions in the output buffer affect the transient response.

## Variants & Generalizations

- **Direct Form I**: Separate feedforward and feedback computation (as implemented).
- **Direct Form II**: Reduces memory by sharing a single delay line, but is more sensitive to quantization.
- **Cascade (Second-Order Sections)**: Factor the transfer function into biquad sections for improved numerical stability.
- **Lattice structure**: Alternative topology with better quantization properties.

## Applications

- Butterworth, Chebyshev, and elliptic filter implementations
- DC removal (high-pass with pole near $z = 1$)
- Resonant filtering and equalization
- Control loop compensation filters

## Connections to Other Algorithms

- **FIR Filter**: FIR is a special case of IIR with $Q = 0$ (no feedback). FIR is always stable but requires more coefficients for comparable selectivity.
- **Frequency Response**: The `FrequencyResponse` class evaluates $H(e^{j\omega})$ for both FIR and IIR filters by accepting both $b$ and $a$ coefficient arrays.
- **Kalman Filter**: Kalman filters can be viewed as optimal adaptive IIR filters with time-varying coefficients.

## References & Further Reading

- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapter 7.
- Mitra, S.K., *Digital Signal Processing: A Computer-Based Approach*, 4th ed., McGraw-Hill, 2010 — Chapters 6–8.
- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapter 19.
1 change: 1 addition & 0 deletions numerical/analysis/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ target_sources(numerical.analysis PRIVATE
numerical_add_coverage_sources(numerical.analysis
FastFourierTransformRadix2Impl.cpp
FrequencyResponse.cpp
PowerDensitySpectrum.cpp
RootLocus.cpp
)

Expand Down
Loading
Loading