From 15b234313362fcc29e7c12f0a445c9a09000471a Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Fri, 20 Mar 2026 18:27:05 +0000 Subject: [PATCH 01/15] refactor all doc files --- .github/workflows/validate-docs.yml | 20 + README.md | 36 +- doc/TEMPLATE.md | 90 +++ doc/analysis/DiscreteCosineTransform.md | 275 +++------- doc/analysis/FastFourierTransform.md | 220 +++----- doc/analysis/PowerDensitySpectrum.md | 327 ++++------- doc/analysis/README.md | 12 + doc/analysis/RootLocus.md | 185 +++---- doc/controllers/Lqr.md | 187 ++++--- doc/controllers/Pid.md | 241 +++------ doc/controllers/README.md | 10 + doc/estimators/LinearRegression.md | 313 +++-------- doc/estimators/README.md | 10 + doc/estimators/YuleWalker.md | 335 +++--------- doc/filters/README.md | 17 + doc/filters/active/KalmanFilter.md | 261 ++++----- doc/neural_network/NeuralNetwork.md | 512 +++++------------- doc/neural_network/README.md | 15 + doc/neural_network/activation/Activation.md | 376 +++++-------- doc/neural_network/layer/Layer.md | 411 ++++---------- doc/neural_network/losses/Loss.md | 490 ++++------------- doc/neural_network/model/Model.md | 468 +++++----------- doc/neural_network/optimizer/Optimizer.md | 381 ++++--------- .../regularization/Regularization.md | 343 ++++-------- .../DiscreteAlgebraicRiccatiEquation.md | 131 +++-- doc/solvers/DurandKerner.md | 147 ++--- doc/solvers/GaussianElimination.md | 145 +++-- doc/solvers/LevinsonDurbin.md | 331 +++-------- doc/solvers/README.md | 12 + doc/windowing/README.md | 9 + doc/windowing/window.md | 253 ++++----- scripts/validate-docs.py | 82 +++ 32 files changed, 2386 insertions(+), 4259 deletions(-) create mode 100644 .github/workflows/validate-docs.yml create mode 100644 doc/TEMPLATE.md create mode 100644 doc/analysis/README.md create mode 100644 doc/controllers/README.md create mode 100644 doc/estimators/README.md create mode 100644 doc/filters/README.md create mode 100644 doc/neural_network/README.md create mode 100644 doc/solvers/README.md create mode 100644 doc/windowing/README.md create mode 100644 scripts/validate-docs.py diff --git a/.github/workflows/validate-docs.yml b/.github/workflows/validate-docs.yml new file mode 100644 index 00000000..f847f175 --- /dev/null +++ b/.github/workflows/validate-docs.yml @@ -0,0 +1,20 @@ +name: Documentation Validation + +on: + pull_request: + paths: + - 'doc/**' + - 'scripts/validate-docs.py' + +jobs: + validate-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.12' + + - name: Validate documentation structure + run: python scripts/validate-docs.py diff --git a/README.md b/README.md index fdfaaf04..f82e10cf 100644 --- a/README.md +++ b/README.md @@ -12,29 +12,19 @@ This library provides a comprehensive collection of digital signal processing (D Refer to the documentation and example scripts to quickly integrate and utilize the library's signal processing and control algorithms in your projects. -## Theory and How to use - -1. Control Systems - - [PID](doc/controllers/Pid.md) - - [LQR](doc/controllers/Lqr.md) - -2. Analysis - - [Fast Fourier Transform](doc/analysis/FastFourierTransform.md) - - [Power Density Spectrum](doc/analysis/PowerDensitySpectrum.md) - - [Discrete Cosine Transform](doc/analysis/DiscreteCosineTransform.md) - -3. Filter - - [Windowing](doc/windowing/window.md) - - [Kalman Filter](doc/filters/active/KalmanFilter.md) - -4. Estimators and Solvers - - [Linear Regression](doc/estimators/LinearRegression.md) - - [Yule-Walker (for AR and MA models)](doc/estimators/YuleWalker.md) - - [Levinson-Durbin (Ax + B = 0 matrix solver)](doc/solvers/LevinsonDurbin.md) - - [Gaussian Elimination](doc/solvers/GaussianElimination.md) - - [Discrete Algebraic Riccati Equation](doc/solvers/DiscreteAlgebraicRiccatiEquation.md) - -5. [Neural Network](doc/neural_network/NeuralNetwork.md) +## Documentation + +| Category | Description | +|----------|-------------| +| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Root Locus | +| [Controllers](doc/controllers/README.md) | PID, LQR | +| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker | +| [Filters](doc/filters/README.md) | Kalman Filter | +| [Solvers](doc/solvers/README.md) | Gaussian Elimination, Levinson-Durbin, Durand-Kerner, DARE | +| [Windowing](doc/windowing/README.md) | Rectangular, Hamming, Hann, Blackman | +| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, optimizers, regularization | + +Each category page lists its algorithms with a brief description and links to the detailed documentation. ## Simulator diff --git a/doc/TEMPLATE.md b/doc/TEMPLATE.md new file mode 100644 index 00000000..c3ac9f4b --- /dev/null +++ b/doc/TEMPLATE.md @@ -0,0 +1,90 @@ +# [Algorithm Name] + +## Overview & Motivation + + + +## Mathematical Theory + + + +## Complexity Analysis + + + +## Step-by-Step Walkthrough + + + +## Pitfalls & Edge Cases + + + +## Variants & Generalizations + + + +## Applications + + + +## Connections to Other Algorithms + + + +## References & Further Reading + + diff --git a/doc/analysis/DiscreteCosineTransform.md b/doc/analysis/DiscreteCosineTransform.md index ce71801c..f22c2710 100644 --- a/doc/analysis/DiscreteCosineTransform.md +++ b/doc/analysis/DiscreteCosineTransform.md @@ -1,239 +1,114 @@ -# Discrete Cosine Transform (DCT) Implementation Guide +# Discrete Cosine Transform (DCT) -## Process Overview +## Overview & Motivation -The DCT transforms a sequence of data points into a sum of cosine functions oscillating at different frequencies. Our implementation specifically focuses on DCT-II, which is the most commonly used variant, especially in signal compression applications. +The Discrete Cosine Transform projects a real-valued signal onto a set of cosine basis functions at different frequencies. Unlike the DFT, the DCT produces **purely real coefficients** and exhibits superior **energy compaction** — most of the signal's energy concentrates in a few low-frequency coefficients. This property makes it the backbone of lossy compression standards (JPEG, MPEG, AAC). -The following diagram illustrates the key steps in our DCT implementation: +This library implements **DCT-II** (the most common variant) by leveraging the FFT: the input is rearranged, transformed via a real-valued FFT, and post-processed with twiddle factors. This approach inherits the FFT's $O(N \log N)$ efficiency rather than requiring a dedicated $O(N^2)$ computation. -![DCT Processing Flow](doc/analysis/DctFlow.svg) +## Mathematical Theory -The above diagram shows the main processing stages: -1. Input signal preprocessing (reordering and scaling) -2. FFT computation on preprocessed data -3. Post-processing to obtain DCT coefficients +### DCT-II Definition -The DCT decomposes signals into different frequency components using cosine basis functions: +For a length-$N$ sequence $x[n]$, the DCT-II is defined as: -![DCT Basis Functions](doc/analysis/DctBasis.svg) +$$X[k] = \sum_{n=0}^{N-1} x[n] \cos\!\left(\frac{\pi}{N}\left(n + \tfrac{1}{2}\right) k\right), \quad k = 0, 1, \ldots, N-1$$ -The diagram shows how different frequency components (k=0,1,2,3) contribute to the final signal representation. The k=0 component represents the DC (average) value, while higher k values represent increasingly higher frequency oscillations. +The inverse (DCT-III, also called IDCT) recovers $x[n]$: -The key processing steps are: -1. Input signal preprocessing -2. FFT computation -3. Post-processing to obtain DCT coefficients -4. (For inverse) Reverse process to recover the original signal +$$x[n] = \frac{1}{N}\left[\frac{X[0]}{2} + \sum_{k=1}^{N-1} X[k] \cos\!\left(\frac{\pi}{N}\left(n + \tfrac{1}{2}\right) k\right)\right]$$ -## Mathematical Background +### FFT-Based Computation -### Discrete Cosine Transform +The DCT can be computed via the DFT of a reordered sequence: -The DCT-II of a sequence x[n] of length N is defined as: +1. Form a new sequence $y[n]$ by interleaving even-indexed and reverse odd-indexed samples of $x$. +2. Compute the $N$-point FFT: $Y[k] = \text{FFT}\{y\}$. +3. Apply twiddle factors: $X[k] = 2 \cdot \text{Re}\!\left(W[k] \cdot Y[k]\right)$, where $W[k] = e^{-j\pi k / 2N}$. -``` -X[k] = Σ(n=0 to N-1) x[n] * cos(π/N * (n + 1/2) * k) -``` +### Why Cosine Basis? -where: -- x[n] is the input sequence -- X[k] are the DCT coefficients -- N is the sequence length -- k is the frequency index +Cosine functions are **symmetric** (even functions). The DCT implicitly mirrors the signal rather than making it periodic, avoiding the boundary discontinuities that cause spectral leakage in the DFT. This is why DCT coefficients decay faster and energy compaction is better. -### FFT-Based Implementation +## Complexity Analysis -Our implementation uses FFT to compute DCT efficiently. The process involves: +| Case | Time | Space | Notes | +|------|------|-------|-------| +| All | $O(N \log N)$ | $O(N)$ | Dominated by the internal FFT; twiddle post-processing is $O(N)$ | -1. Rearranging the input sequence -2. Computing FFT -3. Multiplying with twiddle factors +The reordering step and twiddle multiplication are both linear, so the overall cost is determined by the FFT. -The mathematical relationship is: -``` -DCT[k] = 2 * Real{W[k] * F[k]} -``` -where: -- F[k] is the FFT of the rearranged sequence -- W[k] = exp(-jπk/2N) is the twiddle factor -- Real{} denotes the real part - -## Implementation Details - -### Class Structure - -```cpp -template -class DiscreteConsineTransform { -public: - explicit DiscreteConsineTransform( - FastFourierTransform& fft); - - VectorReal& Forward(VectorReal& input); - VectorReal& Inverse(VectorReal& input); -}; -``` +## Step-by-Step Walkthrough -### Key Components +**Input:** $x = [1, 2, 3, 4]$, $N = 4$ -1. **Input Processing**: - - Reorders input for FFT compatibility - - Ensures fixed-point range compliance - - Handles boundary conditions +**Step 1 — Reorder for FFT** -2. **FFT Interface**: - - Uses templated FFT implementation - - Manages complex intermediate results - - Optimizes memory usage +Even-indexed positions filled left-to-right, odd-indexed filled right-to-left: -3. **Scaling Management**: - - Maintains fixed-point range [-1, 1) - - Applies appropriate scaling factors - - Handles normalization +$$y = [x[0],\; x[2],\; x[3],\; x[1]] = [1, 3, 4, 2]$$ -4. **Fixed-Point Considerations**: - - Pre-computed trigonometric tables - - Optimized multiplication sequences - - Range-checked operations +**Step 2 — Compute FFT** -## Usage Guide +$$Y = \text{FFT}([1, 3, 4, 2]) = [10,\; -3+j,\; -2,\; -3-j]$$ -### Basic Usage +**Step 3 — Apply twiddle factors** $W[k] = e^{-j\pi k/8}$ -```cpp -// Define system parameters -constexpr std::size_t N = 1024; // Transform size -using NumberType = math::Q15; // Fixed-point type +| $k$ | $W[k]$ | $W[k] \cdot Y[k]$ | $X[k] = 2 \cdot \text{Re}(\cdot)$ | +|-----|---------|--------------------|------------------------------------| +| 0 | 1 | 10 | 20 | +| 1 | $e^{-j\pi/8}$ | ≈ −2.22 − 1.90j | ≈ −4.44 | +| 2 | $e^{-j\pi/4}$ | ≈ −1.41 + 1.41j | ≈ −2.83 | +| 3 | $e^{-j3\pi/8}$ | ≈ −0.24 + 3.07j | ≈ −0.47 | -// Create FFT instance -TwiddleFactors twiddleFactors; -FastFourierTransformRadix2Impl fft(twiddleFactors); +**Output:** $X \approx [20, -4.44, -2.83, -0.47]$ -// Create DCT analyzer -DiscreteConsineTransform dct(fft); +Notice how most of the energy is in $X[0]$ (the DC component) — energy compaction in action. -// Prepare input data -infra::BoundedVector::WithMaxSize signal; -// ... fill signal with data ... +## Pitfalls & Edge Cases -// Calculate DCT -auto& coefficients = dct.Forward(signal); +- **Power-of-2 length required** — inherited from the underlying FFT constraint. +- **Normalization convention.** Different references use different scaling (some include $\sqrt{2/N}$). Verify which convention the consumer expects. +- **Fixed-point overflow.** The reordering and FFT steps must preserve range; apply the 0.9999 scaling factor used throughout this library. +- **Inverse accuracy.** Rounding errors accumulate in the forward-then-inverse round-trip, especially for Q15 types. +- **Real input only.** Complex inputs are not supported by the reordering trick. -// Process coefficients -for (std::size_t i = 0; i < N; ++i) { - // Process DCT coefficients... -} +## Variants & Generalizations -// Inverse transform if needed -auto& reconstructed = dct.Inverse(coefficients); -``` +| Variant | Description | +|---------|-------------| +| **DCT-I** | Symmetric extension; used in some filter bank designs | +| **DCT-III (IDCT)** | Inverse of DCT-II; used for reconstruction in JPEG decoding | +| **DCT-IV** | Self-inverse; basis of the MDCT used in MP3 and AAC | +| **MDCT** | Modified DCT with 50 % overlap; foundation of modern audio codecs | +| **2-D DCT** | Applied row-then-column for image compression (JPEG 8×8 blocks) | -### Example: Image Compression +## Applications -```cpp -// Create DCT processor for 8x8 blocks -constexpr std::size_t blockSize = 8; -DiscreteConsineTransform dct(fft); +- **Image compression** — JPEG applies DCT to 8×8 pixel blocks; quantizing high-frequency coefficients achieves compression. +- **Audio compression** — MDCT (a DCT variant) is the core transform in MP3, AAC, and Opus codecs. +- **Feature extraction** — Mel-frequency cepstral coefficients (MFCCs) used in speech recognition are derived from a DCT. +- **Data reduction** — Truncating small DCT coefficients provides a compact signal representation for embedded storage. +- **Numerical methods** — DCT is used in fast solvers for certain partial differential equations (Poisson's equation on regular grids). -// Process image block -BoundedVector::WithMaxSize block; -// ... fill block with pixel data ... +## Connections to Other Algorithms -// Transform -auto& dctCoeffs = dct.Forward(block); +```mermaid +graph LR + DCT["Discrete Cosine Transform"] + FFT["Fast Fourier Transform"] + WIN["Window Functions"] + FFT --> DCT + WIN -.-> DCT +``` -// Quantize coefficients (compression) -for (auto& coeff : dctCoeffs) { - coeff = Quantize(coeff, quantizationMatrix[i]); -} +| Algorithm | Relationship | +|-----------|-------------| +| [Fast Fourier Transform](FastFourierTransform.md) | DCT is computed via FFT with input reordering and twiddle post-processing | +| [Window Functions](../windowing/window.md) | Some DCT applications use windowing to control boundary effects | -// Inverse transform -auto& reconstructed = dct.Inverse(dctCoeffs); -``` +## References & Further Reading -## Best Practices - -1. **Input Preparation**: - - Ensure data is within fixed-point range - - Pre-scale values if necessary - - Consider block size requirements - -2. **Type Selection**: - - Use Q15/Q31 for embedded systems - - Float for desktop applications - - Consider precision requirements - -3. **Performance Optimization**: - - Use power-of-2 lengths - - Reuse transform instances - - Leverage pre-computed tables - -4. **Memory Management**: - - Use BoundedVector for static allocation - - Minimize temporary buffers - - Consider alignment requirements - -## Common Applications - -1. **Data Compression**: - - Image compression (JPEG) - - Audio compression - - Video encoding - -2. **Signal Processing**: - - Feature extraction - - Pattern recognition - - Spectral analysis - -3. **Scientific Computing**: - - Numerical solutions - - Fast convolution - - Data reduction - -## Performance Considerations - -1. **Compile-Time Optimization**: - - Fixed sizes known at compile time - - Template specialization - - Inline expansion - -2. **Memory Efficiency**: - - Static allocation - - Minimal working buffers - - In-place operations where possible - -3. **Computational Efficiency**: - - FFT-based implementation - - Pre-computed tables - - Optimized fixed-point math - -## Limitations and Future Improvements - -1. Current limitations: - - Power-of-2 size requirement - - Real-valued input only - - Single precision support - - Basic DCT-II variant only - -2. Possible extensions: - - Other DCT variants (I, III, IV) - - Arbitrary size support - - Multi-dimensional transform - - Parallel processing - - SIMD optimization - - Streaming interface - - Block processing - -## Error Handling - -1. Static assertions verify: - - Power-of-2 length - - Valid numeric types - - Size constraints - - FFT compatibility - -2. Runtime checks: - - Input range validation - - Buffer management - - Overflow prevention - - Error propagation +- Ahmed, N., Natarajan, T. and Rao, K.R., "Discrete Cosine Transform", *IEEE Transactions on Computers*, C-23(1), 1974. +- Rao, K.R. and Yip, P., *Discrete Cosine Transform: Algorithms, Advantages, Applications*, Academic Press, 1990. +- Makhoul, J., "A fast cosine transform in one and two dimensions", *IEEE Transactions on ASSP*, 28(1), 1980. diff --git a/doc/analysis/FastFourierTransform.md b/doc/analysis/FastFourierTransform.md index 04cb14e1..9373935e 100644 --- a/doc/analysis/FastFourierTransform.md +++ b/doc/analysis/FastFourierTransform.md @@ -1,182 +1,132 @@ -# Fast Fourier Transform (FFT) Implementation Guide +# Fast Fourier Transform (FFT) -## Mathematical Background +## Overview & Motivation -### The Continuous Fourier Transform +Many problems in signal processing, communications, and control require knowing the frequency content of a signal. The Discrete Fourier Transform (DFT) answers this question exactly, but its direct computation costs $O(N^2)$ multiplications — prohibitive for real-time embedded systems processing thousands of samples. -The Fourier Transform is a mathematical tool that decomposes a continuous function into its constituent frequencies. For a continuous-time signal x(t), its Fourier Transform X(f) is: +The **Fast Fourier Transform** is a family of algorithms that compute the DFT in $O(N \log N)$ operations by exploiting symmetry and periodicity of the complex exponential. This library implements the **Radix-2 Cooley-Tukey** variant, which recursively splits an $N$-point DFT into two $N/2$-point DFTs, requiring $N$ to be a power of two. -``` -X(f) = ∫[from -∞ to +∞] x(t) * e^(-2πift) dt -``` - -And its inverse transform is: - -``` -x(t) = ∫[from -∞ to +∞] X(f) * e^(2πift) df -``` +The core insight is that the DFT matrix has a recursive block structure: half of its entries are shared between the even-indexed and odd-indexed sub-problems, so most of the work can be reused rather than recomputed. -The transform effectively converts a signal from the time domain to the frequency domain, revealing its frequency components. This has profound implications in: +## Mathematical Theory -1. **Physics**: Analyzing wave phenomena, quantum mechanics -2. **Signal Processing**: Understanding signal composition -3. **Differential Equations**: Solving complex equations by transforming them to algebraic ones -4. **Image Processing**: Analyzing spatial frequencies +### Prerequisites -The key insight of Fourier analysis is that any continuous, periodic function can be represented as a sum of sinusoidal functions of different frequencies. Even non-periodic functions can be represented using the continuous spectrum of frequencies through the Fourier Transform. +The **Discrete Fourier Transform** of a length-$N$ sequence $x[n]$ is defined as: -### From Continuous to Discrete +$$X[k] = \sum_{n=0}^{N-1} x[n] \, e^{-j2\pi kn/N}, \quad k = 0, 1, \ldots, N-1$$ -When working with digital systems, we need to: -1. Sample the continuous signal at discrete time intervals -2. Process a finite number of samples +The **inverse DFT** recovers the original sequence: -This leads us to the Discrete Fourier Transform (DFT), which is a sampled version of the continuous Fourier Transform. The relationship between sampling in time domain and frequency domain is governed by the: -- Nyquist-Shannon sampling theorem: To accurately represent a signal, sample at least twice the highest frequency component -- Aliasing: When sampling below the Nyquist rate, high frequencies appear as false low frequencies +$$x[n] = \frac{1}{N} \sum_{k=0}^{N-1} X[k] \, e^{j2\pi kn/N}$$ -### The Discrete Fourier Transform (DFT) +We define the **twiddle factor** $W_N = e^{-j2\pi/N}$, so $X[k] = \sum_{n} x[n] \, W_N^{kn}$. -The Discrete Fourier Transform converts a sequence of N complex numbers {xn} into another sequence of complex numbers {Xk}: - -``` -Xk = Σ(n=0 to N-1) xn * e^(-2πi*k*n/N) -``` +### Cooley-Tukey Decomposition -where: -- n is the time index -- k is the frequency index -- N is the number of samples -- i is the imaginary unit +Split the sum into even-indexed and odd-indexed terms: -### The Fast Fourier Transform Algorithm +$$X[k] = \underbrace{\sum_{m=0}^{N/2-1} x[2m] \, W_{N/2}^{km}}_{E[k]} \;+\; W_N^k \underbrace{\sum_{m=0}^{N/2-1} x[2m+1] \, W_{N/2}^{km}}_{O[k]}$$ -The FFT is an optimized algorithm to compute the DFT. While the direct DFT computation requires O(N²) operations, the FFT reduces this to O(N log N) by: +Because $E[k]$ and $O[k]$ are periodic with period $N/2$: -1. Exploiting the periodicity of e^(-2πi) -2. Decomposing the DFT into smaller DFTs (divide-and-conquer) -3. Using the symmetry properties of the complex exponential +$$X[k] = E[k] + W_N^k \, O[k]$$ +$$X[k + N/2] = E[k] - W_N^k \, O[k]$$ -Our implementation uses the Radix-2 Cooley-Tukey algorithm, which requires the input length to be a power of 2. +This pair of equations is the **butterfly operation**: two outputs from two inputs and one twiddle-factor multiplication. -## Implementation Details +### Bit-Reversal Permutation -### Class Structure +The recursive decomposition reorders input by bit-reversing the sample indices. For in-place computation the input array is pre-permuted so that butterfly stages proceed sequentially from the smallest sub-problems to the full $N$-point result. -```cpp -template -class FastFourierTransform { - virtual VectorComplex& Forward(VectorReal& input) = 0; - virtual VectorReal& Inverse(VectorComplex& input) = 0; -}; -``` +## Complexity Analysis -The implementation is split into: -1. Base abstract class (`FastFourierTransform`) -2. Radix-2 implementation (`FastFourierTransformRadix2Impl`) -3. Twiddle factors helper class (`TwiddleFactors`) +| Case | Time | Space | Notes | +|------|------|-------|-------| +| All | $O(N \log_2 N)$ | $O(N)$ | $N$ must be a power of 2 | -### Key Components +**Why $O(N \log N)$:** There are $\log_2 N$ butterfly stages, each performing $N/2$ butterfly operations (one complex multiply + two complex adds). Total: $\frac{N}{2} \log_2 N$ complex multiplications. -1. **Twiddle Factors**: Pre-computed complex exponentials (e^(-2πi*k/N)) used in the butterfly operations -2. **Bit Reversal**: Reorders input data to optimize butterfly operations -3. **Butterfly Operations**: The core computation units that combine results from smaller DFTs +Twiddle factors are **pre-computed** and stored in a lookup table of size $N/2$, so no trigonometric evaluations occur at runtime. -## Usage Guide +## Step-by-Step Walkthrough -### Basic Usage +**Input:** $x = [1, 2, 3, 4]$, $N = 4$ -```cpp -// Create an FFT instance (N must be a power of 2) -constexpr std::size_t N = 1024; -TwiddleFactorsImpl twiddleFactors; -FastFourierTransformRadix2Impl fft(twiddleFactors); +**Step 1 — Bit-reversal permutation** -// Prepare input data -infra::BoundedVector::WithMaxSize input; -for (const auto& value : signal) - input.push_back(value); +| Index (binary) | Reversed | Value | +|----------------|----------|-------| +| 0 (00) | 0 (00) | 1 | +| 1 (01) | 2 (10) | 3 | +| 2 (10) | 1 (01) | 2 | +| 3 (11) | 3 (11) | 4 | -// Perform forward transform -auto& frequencyDomain = fft.Forward(input); +Reordered: $[1, 3, 2, 4]$ -// Perform inverse transform if needed -auto& reconstructedSignal = fft.Inverse(frequencyDomain); -``` +**Step 2 — Stage 1 (size-2 butterflies), twiddle $W_2^0 = 1$** -### Computing Magnitude Spectrum +- Butterfly$(1, 3)$: outputs $(1+3, \; 1-3) = (4, \; -2)$ +- Butterfly$(2, 4)$: outputs $(2+4, \; 2-4) = (6, \; -2)$ -To compute the magnitude spectrum from the complex FFT output: +Result: $[4, -2, 6, -2]$ -```cpp -std::vector magnitudes(N/2); -for (std::size_t i = 0; i < N/2; ++i) { - auto complex = frequencyDomain[i]; - magnitudes[i] = std::sqrt( - complex.Real() * complex.Real() + - complex.Imaginary() * complex.Imaginary() - ); -} -``` +**Step 3 — Stage 2 (size-4 butterfly), twiddles $W_4^0 = 1$, $W_4^1 = -j$** -### Frequency Resolution +- $X[0] = 4 + 1 \cdot 6 = 10$ +- $X[1] = -2 + (-j)(-2) = -2 + 2j$ +- $X[2] = 4 - 1 \cdot 6 = -2$ +- $X[3] = -2 - (-j)(-2) = -2 - 2j$ -The frequency resolution of the FFT is: -``` -Δf = sampleRate / N -``` +**Output:** $X = [10,\; -2+2j,\; -2,\; -2-2j]$ -To convert bin index to frequency: -```cpp -float frequency = binIndex * sampleRate / N; -``` +Verification: $X[0] = 1+2+3+4 = 10$ ✓ -## Best Practices +## Pitfalls & Edge Cases -1. **Input Length**: Always use a power of 2 for the input length (e.g., 256, 512, 1024, 2048) -2. **Memory Management**: The implementation uses `BoundedVector` to prevent heap allocations -3. **Numerical Precision**: Template parameter `QNumberType` allows choosing between float/double precision -4. **Scaling**: Remember that the inverse FFT output needs to be scaled by 1/N +- **Power-of-2 constraint.** Non-power-of-2 inputs require zero-padding, which introduces interpolation artifacts in the frequency domain. +- **Fixed-point overflow.** Each butterfly stage can double the magnitude. For Q15/Q31 types, scale the input by $1/N$ before the transform or apply per-stage scaling. +- **Spectral leakage.** A finite-length DFT implicitly applies a rectangular window. Use a [window function](../windowing/window.md) before the transform to reduce sidelobes. +- **Aliasing.** The Nyquist-Shannon theorem requires $f_s \geq 2 f_{\max}$. Violating this folds high frequencies onto low frequencies irreversibly. +- **Frequency resolution** is $\Delta f = f_s / N$. Increasing $N$ improves resolution at the cost of more memory and computation. -## Common Applications +## Variants & Generalizations -1. **Spectral Analysis**: Analyzing frequency content of signals -2. **Filtering**: Multiplication in frequency domain for efficient filtering -3. **Feature Extraction**: Extracting frequency-domain features for classification -4. **Data Compression**: Removing high-frequency components +| Variant | Key Difference | +|---------|---------------| +| **Mixed-radix FFT** | Supports arbitrary composite $N$ using radix-2, -3, -5, etc. stages | +| **Split-radix FFT** | Reduces multiplications by ~33 % compared to standard radix-2 | +| **Real-valued FFT** | Exploits conjugate symmetry of real inputs to halve work and memory | +| **Bluestein's algorithm** | Handles arbitrary $N$ by converting DFT to a circular convolution | +| **Inverse FFT** | Same structure; negate twiddle exponents and scale by $1/N$ | -## Example: Signal Analysis +## Applications -```cpp -// Generate a test signal with multiple frequency components -auto signal = SignalGenerator::GenerateSignal(N, sampleRate); +- **Spectral analysis** — Identifying frequency components, harmonics, and noise floors in sensor data. +- **Convolution and filtering** — Multiplication in the frequency domain is equivalent to time-domain convolution; enables efficient FIR filtering. +- **Power Spectral Density** — Used internally by Welch's method for spectral estimation. +- **Communication systems** — OFDM modulation/demodulation is built directly on the FFT/IFFT pair. +- **Vibration and fault diagnosis** — Examining spectral peaks to detect mechanical anomalies. +- **Data compression** — Foundation for transforms (DCT, MDCT) used in JPEG, MP3, etc. -// Perform FFT -auto& frequencyDomain = fft.Forward(input); +## Connections to Other Algorithms -// Analyze specific frequency components -for (std::size_t i = 0; i < N/2; ++i) { - float frequency = i * sampleRate / N; - float magnitude = std::sqrt( - frequencyDomain[i].Real() * frequencyDomain[i].Real() + - frequencyDomain[i].Imaginary() * frequencyDomain[i].Imaginary() - ); - // Process frequency components... -} +```mermaid +graph LR + FFT --> PSD["Power Spectral Density"] + FFT --> DCT["Discrete Cosine Transform"] + WIN["Window Functions"] --> FFT + FFT -.-> DK["Durand-Kerner (polynomial eval)"] ``` -## Performance Considerations - -1. **Twiddle Factors**: Pre-computed to avoid repeated calculation -2. **Bit Reversal**: Optimized using lookup tables for small N -3. **Memory Access**: In-place computation to minimize memory usage -4. **Template Metaprogramming**: Used to optimize compile-time operations +| Algorithm | Relationship | +|-----------|-------------| +| [Power Spectral Density](PowerDensitySpectrum.md) | Calls FFT internally on each windowed segment | +| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Computed via FFT with input rearrangement and twiddle-factor post-processing | +| [Window Functions](../windowing/window.md) | Applied before FFT to reduce spectral leakage | -## Limitations and Future Improvements +## References & Further Reading -1. Currently only supports power-of-2 lengths (Radix-2) -2. Could be extended to support: - - Mixed-radix FFT - - Real-valued FFT optimization - - Parallel computation - - Windowing functions +- Cooley, J.W. and Tukey, J.W., "An algorithm for the machine calculation of complex Fourier series", *Mathematics of Computation*, 19(90), 1965. +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapters 8–9. +- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapters 8, 12. diff --git a/doc/analysis/PowerDensitySpectrum.md b/doc/analysis/PowerDensitySpectrum.md index 9481ef31..3cc59948 100644 --- a/doc/analysis/PowerDensitySpectrum.md +++ b/doc/analysis/PowerDensitySpectrum.md @@ -1,239 +1,134 @@ -# Power Spectral Density (PSD) Implementation Guide +# Power Spectral Density (Welch's Method) -## Process Overview +## Overview & Motivation -The following diagram illustrates the key steps in the Welch's method implementation: +Given a noisy signal, a natural question is: *how is the signal's power distributed across frequencies?* A single FFT of the entire record gives a very noisy estimate — the variance of the periodogram does not decrease as the record grows. **Welch's method** trades frequency resolution for statistical reliability by dividing the signal into overlapping, windowed segments, computing a periodogram for each, and averaging them. The result is a smooth, consistent estimate of the Power Spectral Density (PSD). -![PSD Diagram](PsdSegments.svg) +This is the standard approach in vibration analysis, audio engineering, communication system design, and any domain where reliable spectral estimates matter more than the finest possible frequency resolution. -The diagram shows the main processing steps: -1. Input signal is received -2. Signal is divided into overlapping segments -3. Window function is applied to each segment -4. FFT is computed for each windowed segment -5. Power spectrum is calculated and averaged +## Mathematical Theory -## Mathematical Background +### Power Spectral Density Definition -### Power Spectral Density +For a wide-sense stationary process $x(t)$, the PSD is the Fourier transform of the autocorrelation function (Wiener-Khinchin theorem): -The Power Spectral Density (PSD) describes how the power of a signal is distributed across different frequencies. For a continuous-time signal x(t), the PSD is defined as: +$$S_{xx}(f) = \int_{-\infty}^{\infty} R_{xx}(\tau) \, e^{-j2\pi f\tau} \, d\tau$$ -``` -Sxx(f) = lim[T→∞] (1/T) |X(f)|² -``` +In practice we estimate $S_{xx}$ from a finite record. + +### The Periodogram + +The periodogram of a length-$N$ segment $x[n]$ is: + +$$\hat{P}(f_k) = \frac{1}{N} \left| \sum_{n=0}^{N-1} x[n] \, e^{-j2\pi kn/N} \right|^2 = \frac{1}{N} |X[k]|^2$$ -where X(f) is the Fourier transform of the signal and T is the observation time. +This is an unbiased but **inconsistent** estimator — its variance does not shrink as $N \to \infty$. ### Welch's Method -Our implementation uses Welch's method, which: -1. Divides the signal into overlapping segments -2. Windows each segment -3. Computes the periodogram of each segment -4. Averages the periodograms +1. **Segment** the signal of length $L$ into $K$ overlapping segments of length $N$ with step size $S = N - \text{overlap}$: -The mathematical steps are: -``` -1. Segment the signal: xi[n] = x[n + iL], i = 0,1,...,K-1 -2. Apply window: wi[n] = w[n]xi[n] -3. Compute FFT: Wi[k] = FFT{wi[n]} -4. Calculate periodogram: Pi[k] = (1/N)|Wi[k]|² -5. Average periodograms: P[k] = (1/K)Σ(i=0 to K-1) Pi[k] -``` +$$x_i[n] = x[n + iS], \quad i = 0, 1, \ldots, K-1$$ -where: -- N is the segment size -- L is the step size between segments -- K is the number of segments -- w[n] is the window function - -## Implementation Details - -### Class Structure - -```cpp -template< - typename QNumberType, - std::size_t SegmentSize, - typename Fft, - typename TwindleFactor, - std::size_t Overlap -> -class PowerSpectralDensity { -public: - explicit PowerSpectralDensity( - windowing::Window& window, - QNumberType samplingTimeInSeconds); - - VectorReal& Calculate(const VectorReal& input); -}; -``` +2. **Window** each segment: -### Key Components - -1. **Segmentation**: - - Fixed segment size (must be even) - - Configurable overlap (0%, 25%, 50%, or 75%) - - Step size calculated as: `step = SegmentSize - overlapSize` - -2. **Windowing**: - - User-provided window function - - Reduces spectral leakage - - Applied to each segment before FFT - -3. **FFT Processing**: - - Uses templated FFT implementation - - Computes spectrum for each segment - - Handles complex conjugate symmetry - -4. **Averaging**: - - Accumulates power from all segments - - Applies frequency resolution scaling - - Returns one-sided spectrum - -## Usage Guide - -### Basic Usage - -```cpp -// Define system parameters -constexpr std::size_t N = 1024; // Segment size -constexpr std::size_t overlap = 50; // 50% overlap -using FloatType = float; - -// Create window function -windowing::Hanning window; - -// Create PSD analyzer -PowerSpectralDensity< - FloatType, - N, - FastFourierTransformRadix2Impl, - TwiddleFactorsImpl, - overlap -> psd(window, samplingTime); - -// Prepare input data -infra::BoundedVector::WithMaxSize signal; -// ... fill signal with data ... - -// Calculate PSD -auto& spectrum = psd.Calculate(signal); - -// Access results -for (std::size_t i = 0; i <= N/2; ++i) { - float frequency = i * (1.0f / samplingTime) / N; - float power = spectrum[i]; - // Process spectrum... -} -``` +$$w_i[n] = w[n] \cdot x_i[n]$$ + +3. **Compute the periodogram** of each windowed segment: + +$$P_i[k] = \frac{1}{N} |W_i[k]|^2$$ + +4. **Average** across all segments: + +$$\hat{S}_{xx}[k] = \frac{1}{K} \sum_{i=0}^{K-1} P_i[k]$$ + +The averaging reduces variance by a factor of approximately $K$ (slightly less due to overlap correlation). + +### Frequency Resolution + +$$\Delta f = \frac{f_s}{N}$$ + +Increasing segment size $N$ improves resolution but reduces the number of averages $K$ for a fixed-length record. + +## Complexity Analysis -### Example: Signal Analysis +| Case | Time | Space | Notes | +|------|------|-------|-------| +| All | $O(K \cdot N \log N)$ | $O(N)$ | $K$ segments, each requiring one FFT | -```cpp -// Create analyzer with Hanning window -constexpr float samplingRate = 1000.0f; // Hz -constexpr float samplingTime = 1.0f / samplingRate; -windowing::Hanning window; +Where $K = \lfloor (L - N) / S \rfloor + 1$ and $S = N \cdot (1 - \text{overlap fraction})$. -PowerSpectralDensity psd( - window, samplingTime); +**Why:** Each segment requires an $O(N \log N)$ FFT, and there are $K$ segments. The averaging and magnitude-squared operations are $O(N)$ per segment. -// Generate test signal -auto signal = GenerateSignal(samplingRate); +## Step-by-Step Walkthrough -// Calculate PSD -auto& spectrum = psd.Calculate(signal); +**Input:** $x = [1, 3, 5, 7, 6, 4, 2, 0]$, segment size $N=4$, 50 % overlap, rectangular window. -// Convert to dB -std::vector powerDb(spectrum.size()); -for (std::size_t i = 0; i < spectrum.size(); ++i) { - float power = spectrum[i]; - powerDb[i] = 10.0f * std::log10(power); -} +**Step 1 — Segmentation** (step $S = 2$): + +| Segment | Indices | Values | +|---------|---------|--------| +| $x_0$ | 0–3 | $[1, 3, 5, 7]$ | +| $x_1$ | 2–5 | $[5, 7, 6, 4]$ | +| $x_2$ | 4–7 | $[6, 4, 2, 0]$ | + +**Step 2 — Window** (rectangular → no change) + +**Step 3 — FFT and periodogram** for $x_0 = [1, 3, 5, 7]$: + +- $X_0 = [16, \; -4+4j, \; -4, \; -4-4j]$ +- $P_0 = \frac{1}{4}[256, \; 32, \; 16, \; 32] = [64, \; 8, \; 4, \; 8]$ + +*(Repeat for $x_1$ and $x_2$.)* + +**Step 4 — Average** the three periodograms element-wise. + +**Output:** One-sided PSD estimate at frequencies $0, \frac{f_s}{4}, \frac{f_s}{2}$. + +## Pitfalls & Edge Cases + +- **Too few segments.** If the signal is short relative to the segment size, $K$ is small and the variance reduction is limited. Reduce $N$ or increase overlap. +- **Overlap > 75 %** gives diminishing returns — the segments become highly correlated and additional averages barely reduce variance. +- **Window choice** affects both the main-lobe width and sidelobe level. A Hanning window is a safe default; use Blackman for better dynamic range at the cost of resolution. +- **Segment size must be even** (and a power of 2 for the FFT). Odd or non-power-of-2 sizes are rejected at compile time. +- **DC and Nyquist bins** appear only once in the one-sided spectrum; all other bins are doubled. Omitting this correction distorts the total power. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Bartlett's method** | Non-overlapping segments, rectangular window (special case of Welch with 0 % overlap) | +| **Modified periodogram** | Single segment with a non-rectangular window | +| **Multitaper method** | Uses multiple orthogonal windows (tapers) per segment for lower bias | +| **Cross-spectral density** | Computes $S_{xy}$ between two signals instead of the auto-spectrum | +| **Coherence** | $|\gamma_{xy}|^2 = |S_{xy}|^2 / (S_{xx} S_{yy})$ — measures linear dependence between two signals at each frequency | + +## Applications + +- **Vibration analysis** — Identifying resonant frequencies and tracking their amplitude over time. +- **Noise characterization** — Determining white, pink, or brown noise profiles in electronic circuits or sensors. +- **Communication systems** — Measuring occupied bandwidth and interference levels. +- **Audio engineering** — Equalizer design, room acoustics analysis. +- **Biomedical signal processing** — EEG, EMG spectral analysis for clinical diagnostics. + +## Connections to Other Algorithms + +```mermaid +graph LR + SIG["Input Signal"] --> WIN["Window Functions"] + WIN --> FFT["Fast Fourier Transform"] + FFT --> PSD["Power Spectral Density"] + PSD --> YW["Yule-Walker (parametric alternative)"] ``` -## Best Practices - -1. **Segment Size**: - - Use power of 2 for efficient FFT - - Balance frequency resolution vs. time averaging - - Typically 256 to 4096 points - -2. **Overlap**: - - Higher overlap increases averaging but requires more computation - - 50% is a common choice - - Supported values: 0%, 25%, 50%, 75% - -3. **Window Selection**: - - Hanning/Hamming for general purpose - - Blackman for better sidelobe suppression - - Rectangle for transient analysis - -4. **Frequency Resolution**: - - Determined by: Δf = 1/(N * samplingTime) - - Trade-off with temporal resolution - -## Common Applications - -1. **Spectrum Analysis**: - - Frequency content analysis - - Harmonic identification - - Noise characterization - -2. **Signal Processing**: - - Vibration analysis - - Audio processing - - Communication systems - -3. **System Identification**: - - Transfer function estimation - - Coherence analysis - - Cross-spectral density - -## Performance Considerations - -1. **Template Parameters**: - - Fixed sizes enable compile-time optimizations - - Stack allocation for small segments - -2. **Memory Usage**: - - Uses BoundedVector to prevent heap allocation - - Reuses FFT buffers across segments - -3. **Computation Efficiency**: - - In-place FFT operations - - Optimized window application - - Efficient buffer management - -## Limitations and Future Improvements - -1. Current limitations: - - Fixed segment size - - Limited overlap options - - One-sided spectrum only - - Real-valued input only - -2. Possible extensions: - - Variable segment size - - Arbitrary overlap percentage - - Two-sided spectrum option - - Complex input support - - Cross-spectral density - - Coherence estimation - - Confidence interval calculation - - Multi-channel analysis - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Even segment size - - Valid overlap percentage - - FFT type compatibility - -2. Runtime checks: - - Input size adequacy - - Window function validity - - Numerical overflow prevention +| Algorithm | Relationship | +|-----------|-------------| +| [Fast Fourier Transform](FastFourierTransform.md) | Core building block — each segment is transformed via FFT | +| [Window Functions](../windowing/window.md) | Applied to each segment before FFT to control leakage | +| [Yule-Walker](../estimators/YuleWalker.md) | Parametric alternative — estimates PSD from an AR model instead of averaging periodograms | + +## References & Further Reading + +- Welch, P.D., "The use of fast Fourier transform for the estimation of power spectra", *IEEE Transactions on Audio and Electroacoustics*, 15(2), 1967. +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapter 10. +- Stoica, P. and Moses, R.L., *Spectral Analysis of Signals*, Prentice Hall, 2005. diff --git a/doc/analysis/README.md b/doc/analysis/README.md new file mode 100644 index 00000000..93fe1185 --- /dev/null +++ b/doc/analysis/README.md @@ -0,0 +1,12 @@ +# Analysis + +Signal analysis algorithms for frequency-domain decomposition, spectral estimation, and system characterization. + +## Algorithms + +| Algorithm | Description | +|-----------|-------------| +| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm | +| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method | +| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT | +| [Root Locus](RootLocus.md) | Closed-loop pole trajectory analysis as a function of loop gain | diff --git a/doc/analysis/RootLocus.md b/doc/analysis/RootLocus.md index b5d123be..e6e1c6a8 100644 --- a/doc/analysis/RootLocus.md +++ b/doc/analysis/RootLocus.md @@ -1,120 +1,121 @@ -# Root Locus Analysis +# Root Locus -## Process Overview +## Overview & Motivation -```mermaid -graph TD - A[Input: Open-Loop Numerator N(s), Denominator D(s)] --> B[Find Open-Loop Poles and Zeros] - B --> C[Generate Logarithmic Gain Sweep] - C --> D[For Each Gain K] - D --> E[Form Characteristic Polynomial: D(s) + K·N(s)] - E --> F[Find Roots using Durand-Kerner] - F --> G[Store Roots as Locus Branches] - G --> H{More Gain Steps?} - H -->|Yes| D - H -->|No| I[Compute Closed-Loop Poles at Current Gain] - I --> J[Return Result] -``` +When designing a feedback control system, a fundamental question is: *how do the closed-loop poles move as I change the loop gain?* The **root locus** answers this by plotting the trajectories of the closed-loop poles in the complex plane as a scalar gain $K$ varies from $K_{\min}$ to $K_{\max}$. -## Mathematical Background +This visualization immediately reveals whether increasing gain will drive the system unstable (poles crossing into the right half-plane), where oscillatory modes appear (complex pole pairs), and which gain ranges produce acceptable damping. It is one of the oldest and most intuitive tools in classical control design. -### Root Locus Definition +## Mathematical Theory -The root locus shows how the closed-loop poles of a feedback system move in the complex plane as a scalar gain $K$ varies. Given an open-loop transfer function: +### Closed-Loop Characteristic Equation + +Given an open-loop transfer function: $$G(s) = K \cdot \frac{N(s)}{D(s)}$$ -the closed-loop characteristic equation is: +the closed-loop characteristic equation (for unity feedback) is: $$D(s) + K \cdot N(s) = 0$$ -The root locus plots the solutions of this equation for $K \in [K_{\min}, K_{\max}]$. +The **root locus** is the set of all roots of this equation as $K$ varies over $[K_{\min}, K_{\max}]$. -### Properties +### Key Properties -- **Starting points** ($K \to 0$): Roots converge to the open-loop poles (roots of $D(s)$) -- **Ending points** ($K \to \infty$): Roots converge to the open-loop zeros (roots of $N(s)$) or diverge to infinity -- **Number of branches**: Equal to the order of $D(s)$ -- **Symmetry**: Complex roots appear in conjugate pairs for real-coefficient polynomials +- **Starting points** ($K \to 0$): Roots begin at the open-loop poles (roots of $D(s)$). +- **Ending points** ($K \to \infty$): Roots converge to the open-loop zeros (roots of $N(s)$) or diverge to infinity along asymptotes. +- **Number of branches:** Equal to the order of $D(s)$. +- **Symmetry:** For real-coefficient polynomials, complex roots always appear in conjugate pairs. ### Gain Sweep -The gain is swept logarithmically to provide even resolution across decades: +The gain is swept logarithmically to provide uniform resolution across decades: + +$$K_i = 10^{\,\log_{10}(K_{\min}) \;+\; \frac{i}{N-1}\left(\log_{10}(K_{\max}) - \log_{10}(K_{\min})\right)}$$ + +where $N$ is the number of gain steps and $i \in [0, N-1]$. + +At each gain step, the roots of $D(s) + K_i \cdot N(s) = 0$ are found using the [Durand-Kerner](../solvers/DurandKerner.md) polynomial root-finder. + +## Complexity Analysis -$$K_i = 10^{\log_{10}(K_{\min}) + \frac{i}{N-1} \cdot (\log_{10}(K_{\max}) - \log_{10}(K_{\min}))}$$ +| Case | Time | Space | Notes | +|------|------|-------|-------| +| All | $O(N_g \cdot n^2 \cdot k)$ | $O(N_g \cdot n)$ | $N_g$ = gain steps, $n$ = polynomial order, $k$ = Durand-Kerner iterations per step | -where $N$ is `MaxGainSteps` and $i \in [0, N-1]$. +**Why:** At each of the $N_g$ gain steps, a degree-$n$ polynomial is solved via Durand-Kerner, which performs $k$ iterations each costing $O(n^2)$ (evaluating the polynomial and computing the denominator product for all $n$ roots). -## API +## Step-by-Step Walkthrough -```cpp -#include "numerical/analysis/RootLocus.hpp" +**System:** $G(s) = K \cdot \frac{s + 1}{s(s + 2)}$, sweep $K$ from 0.01 to 10. -analysis::RootLocus rootLocus; +**Step 1 — Identify poles and zeros** -// Open-loop transfer function: K * (s + 1) / (s^3 + 3s^2 + 2s) -std::array numerator = { 1.0f, 1.0f }; // s + 1 -std::array denominator = { 1.0f, 3.0f, 2.0f, 0.0f }; // s^3 + 3s^2 + 2s +- Open-loop poles: $s = 0$, $s = -2$ (roots of $D(s) = s^2 + 2s$) +- Open-loop zero: $s = -1$ (root of $N(s) = s + 1$) -auto result = rootLocus.Calculate( - infra::MakeRange(numerator), - infra::MakeRange(denominator), - 1.0f, // currentGain - 0.001f, // gainMin - 50.0f); // gainMax +**Step 2 — Form characteristic polynomial at $K = 1$** -// result.openLoopPoles: roots of denominator -// result.openLoopZeros: roots of numerator -// result.closedLoopPoles: roots of D(s) + currentGain * N(s) -// result.loci[branch][step]: complex root at each gain step -// result.gains[step]: gain value at each step +$$D(s) + K \cdot N(s) = s^2 + 2s + 1 \cdot (s + 1) = s^2 + 3s + 1$$ + +**Step 3 — Solve** using Durand-Kerner: + +$$s = \frac{-3 \pm \sqrt{9 - 4}}{2} = \frac{-3 \pm \sqrt{5}}{2} \approx -0.382,\; -2.618$$ + +Both poles are real and negative → system is stable at $K = 1$. + +**Step 4 — Repeat** for each gain step and plot all root positions in the complex plane. + +``` +Im(s) + | + | × zero (-1) +--●-----×------●--> Re(s) + 0 -1 -2 + pole pole ``` -### Template Parameters +As $K$ increases: the two poles approach each other on the real axis, meet between 0 and −2, then split into a complex conjugate pair. One branch eventually converges to the zero at $s = -1$; the other diverges to $-\infty$. -| Parameter | Description | +## Pitfalls & Edge Cases + +- **Strictly positive gains required** — the logarithmic sweep cannot handle $K \leq 0$. For negative feedback analysis, negate the numerator. +- **Proper transfer function assumed** — $\deg(D) \geq \deg(N)$. Improper transfer functions (more zeros than poles) are not supported. +- **Branch tracking ambiguity** — Durand-Kerner returns roots sorted by real part, not by branch identity. For smooth visualization, apply nearest-neighbor matching between consecutive gain steps. +- **Clustered or repeated roots** cause slower convergence in Durand-Kerner; increase the maximum iteration count if the locus appears jagged. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Complementary root locus** | Traces roots for $K < 0$ (positive feedback) | +| **Root contour** | Varies two or more parameters simultaneously | +| **Discrete root locus** | Same concept applied to $z$-domain polynomials for digital control | +| **Evans rules** | Analytical rules for sketching the root locus by hand (angle/magnitude criteria) | + +## Applications + +- **Gain selection** — Choosing the operating gain that meets damping and bandwidth specifications. +- **Compensator design** — Adding poles/zeros (lead/lag networks) and observing how the locus reshapes. +- **Stability analysis** — Determining the gain margin (gain at which the locus crosses the imaginary axis). +- **Educational tool** — Developing intuition about how feedback affects system dynamics. + +## Connections to Other Algorithms + +```mermaid +graph LR + RL["Root Locus"] --> DK["Durand-Kerner"] + RL --> LQR["LQR (pole placement alternative)"] + DK --> RL +``` + +| Algorithm | Relationship | |-----------|-------------| -| `T` | Floating-point type (`float` or `double`) | -| `MaxOrder` | Maximum polynomial order (number of branches) | -| `MaxGainSteps` | Number of gain steps in the sweep (must be > 1) | - -### Calculate Parameters - -| Parameter | Default | Description | -|-----------|---------|-------------| -| `numerator` | — | Open-loop numerator polynomial coefficients (descending power) | -| `denominator` | — | Open-loop denominator polynomial coefficients (descending power) | -| `currentGain` | — | Gain at which to compute closed-loop poles | -| `gainMin` | 0.001 | Minimum gain for the sweep (must be > 0) | -| `gainMax` | 50 | Maximum gain for the sweep (must be > gainMin) | - -### Preconditions - -- `gainMin > 0` (logarithmic sweep requires positive gains) -- `gainMax > gainMin` -- `denominator.size() >= numerator.size()` (proper or strictly proper transfer function) -- `MaxGainSteps > 1` (enforced at compile time) - -### Result Structure - -| Field | Type | Description | -|-------|------|-------------| -| `loci` | `array` | Root positions for each branch at each gain step | -| `activeBranches` | `size_t` | Number of active locus branches (= denominator order) | -| `gains` | `GainVector` | Gain values at each step | -| `openLoopPoles` | `RootVector` | Poles of the open-loop system | -| `openLoopZeros` | `RootVector` | Zeros of the open-loop system | -| `closedLoopPoles` | `RootVector` | Poles at `currentGain` | -| `currentGain` | `T` | The current gain value | - -### Complexity - -- **Time**: $O(N \cdot n^2 \cdot k)$ where $N$ = gain steps, $n$ = polynomial order, $k$ = Durand-Kerner iterations -- **Space**: $O(N \cdot n)$ for storing all locus branches - -## Numerical Considerations - -- **Logarithmic gain sweep**: Provides uniform resolution across gain decades; requires strictly positive gains -- **Branch tracking**: Roots at each gain step are sorted by Durand-Kerner's default ordering (real part ascending). For smooth branch visualization, the UI may need to apply additional nearest-neighbor matching between consecutive steps -- **Polynomial addition**: `PolyAdd` pads the shorter polynomial (numerator) with leading zeros to align with the longer one (denominator), requiring `denominator.size() >= numerator.size()` -- **Root finding accuracy**: Inherits convergence properties from the Durand-Kerner solver; see [DurandKerner.md](DurandKerner.md) for details +| [Durand-Kerner](../solvers/DurandKerner.md) | Used at each gain step to find the roots of the characteristic polynomial | +| [LQR](../controllers/Lqr.md) | Alternative approach to pole placement — LQR optimizes a cost rather than manually selecting gain via root locus | + +## References & Further Reading + +- Evans, W.R., "Graphical Analysis of Control Systems", *Transactions of the AIEE*, 67(1), 1948. +- Franklin, G.F., Powell, J.D. and Emami-Naeini, A., *Feedback Control of Dynamic Systems*, 8th ed., Pearson, 2019 — Chapter 5. +- Ogata, K., *Modern Control Engineering*, 5th ed., Prentice Hall, 2010 — Chapter 6. diff --git a/doc/controllers/Lqr.md b/doc/controllers/Lqr.md index f3173ada..f845e300 100644 --- a/doc/controllers/Lqr.md +++ b/doc/controllers/Lqr.md @@ -1,139 +1,136 @@ -# LQR Controller Implementation Guide +# LQR Controller (Linear Quadratic Regulator) -## Process Overview +## Overview & Motivation -```mermaid -graph TD - A[Define State-Space Model: A, B] --> B[Define Cost Weights: Q, R] - B --> C[Solve DARE for P] - C --> D[Compute Optimal Gain K] - D --> E[Real-Time Control Loop] - E --> F[Measure State x] - F --> G[Compute u = -Kx] - G --> H[Apply Control Input u] - H --> E -``` +When a state-space model of the plant is available, the **Linear Quadratic Regulator** provides the mathematically *optimal* state-feedback gain. Instead of manually tuning three knobs (as with PID), LQR asks a more principled question: *given how much I care about state deviation versus control effort, what is the cheapest way to drive the state to zero?* -## Mathematical Background +The answer is a constant gain matrix $K$ such that the control law $u[k] = -Kx[k]$ minimizes an infinite-horizon quadratic cost. The elegance of LQR is that this problem has a **closed-form solution** through the Discrete Algebraic Riccati Equation (DARE). -### The Linear Quadratic Regulator +For embedded systems, the gain $K$ can be computed offline and stored as a constant — the runtime cost is then a single matrix-vector multiplication per control step. -The Linear Quadratic Regulator (LQR) is an optimal state-feedback controller for linear systems. It minimizes a quadratic cost function that balances state regulation against control effort. +## Mathematical Theory -Given a discrete-time linear system: +### Discrete-Time State-Space System -``` -x[k+1] = A * x[k] + B * u[k] -``` +$$x[k+1] = Ax[k] + Bu[k]$$ -where: -- `x[k]` is the state vector (n × 1) -- `u[k]` is the control input vector (m × 1) -- `A` is the state transition matrix (n × n) -- `B` is the input matrix (n × m) +where $x \in \mathbb{R}^n$ is the state, $u \in \mathbb{R}^m$ is the control input, $A$ is the state transition matrix, and $B$ is the input matrix. -The LQR minimizes the infinite-horizon cost function: +### Cost Function -``` -J = Σ (x[k]' Q x[k] + u[k]' R u[k]) for k = 0 to ∞ -``` +The LQR minimizes the infinite-horizon quadratic cost: + +$$J = \sum_{k=0}^{\infty} \left( x[k]^T Q \, x[k] + u[k]^T R \, u[k] \right)$$ where: -- `Q` is the state weighting matrix (n × n, positive semi-definite) -- `R` is the input weighting matrix (m × m, positive definite) +- $Q \succeq 0$ (positive semi-definite) penalizes state deviation. +- $R \succ 0$ (positive definite) penalizes control effort. -### Discrete Algebraic Riccati Equation (DARE) +### Optimal Gain via DARE -The optimal gain is derived from the solution P of the DARE: +The solution requires finding the matrix $P$ that satisfies the **Discrete Algebraic Riccati Equation**: -``` -P = A' P A - A' P B (R + B' P B)^(-1) B' P A + Q -``` +$$P = A^T P A - A^T P B \left(R + B^T P B\right)^{-1} B^T P A + Q$$ -The optimal state-feedback gain K is: +The optimal gain is then: -``` -K = (R + B' P B)^(-1) B' P A -``` +$$K = \left(R + B^T P B\right)^{-1} B^T P A$$ -The optimal control law is then: +and the optimal control law is $u[k] = -Kx[k]$. -``` -u[k] = -K * x[k] -``` +### Existence and Uniqueness -This controller is guaranteed to stabilize the system when (A, B) is stabilizable and (A, C) is detectable (where Q = C'C). +A unique stabilizing solution $P$ exists when: +1. $(A, B)$ is **stabilizable** (all unstable modes are controllable). +2. $(A, C)$ is **detectable** (where $Q = C^T C$). -### DARE Iterative Solution +### Bryson's Rule (Initial Weight Selection) -The DARE is solved iteratively starting from P₀ = Q: +$$Q_{ii} = \frac{1}{(\text{max acceptable } x_i)^2}, \qquad R_{jj} = \frac{1}{(\text{max acceptable } u_j)^2}$$ -1. Compute S = R + B'PB -2. Solve S * K_part = B'PA for K_part (via Gaussian elimination) -3. Update P = A'PA - A'PB * K_part + Q -4. Check convergence: ||P_new - P_old|| < tolerance -5. Repeat until converged or max iterations reached +## Complexity Analysis -## Usage Guide +| Phase | Time | Space | Notes | +|-------|------|-------|-------| +| DARE solve (offline) | $O(I \cdot n^3)$ | $O(n^2)$ | $I$ iterations, each involving $n \times n$ matrix operations | +| Control step (online) | $O(n \cdot m)$ | $O(n \cdot m)$ | Single matrix-vector multiply $u = -Kx$ | -### Basic Usage +The DARE iteration is the expensive part, but it is done **once** (offline or at initialization). The per-sample cost is just a matrix-vector product. -```cpp -#include "numerical/controllers/implementations/Lqr.hpp" +## Step-by-Step Walkthrough -constexpr float dt = 0.01f; +**System:** Double integrator with $\Delta t = 0.01$ -math::SquareMatrix A{ - { 1.0f, dt }, - { 0.0f, 1.0f } -}; +$$A = \begin{bmatrix} 1 & 0.01 \\ 0 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} 0.00005 \\ 0.01 \end{bmatrix}$$ -math::Matrix B{ - { 0.5f * dt * dt }, - { dt } -}; +$$Q = \begin{bmatrix} 100 & 0 \\ 0 & 1 \end{bmatrix}, \quad R = [1]$$ -math::SquareMatrix Q{ - { 100.0f, 0.0f }, - { 0.0f, 1.0f } -}; +**Step 1 — Initialize** $P_0 = Q$ -math::SquareMatrix R{ { 1.0f } }; +**Step 2 — DARE iteration** (showing first iteration): -controllers::Lqr lqr(A, B, Q, R); +1. $S = R + B^T P_0 B = 1 + [0.00005\; 0.01] \begin{bmatrix}100 & 0\\0 & 1\end{bmatrix} \begin{bmatrix}0.00005\\0.01\end{bmatrix} = 1.0001$ +2. Solve $S \cdot K_{\text{part}} = B^T P_0 A$ via Gaussian elimination +3. Update $P_1 = A^T P_0 A - A^T P_0 B \cdot K_{\text{part}} + Q$ +4. Check convergence: $\|P_1 - P_0\|$ -math::Vector state{ { currentPosition }, { currentVelocity } }; -auto u = lqr.ComputeControl(state); -applyForce(u.at(0, 0)); -``` +**Step 3 — Repeat** until $\|P_{k+1} - P_k\| < \varepsilon$ (typically 10–30 iterations). -### Pre-computed Gain (Embedded Targets) +**Step 4 — Extract gain** $K = (R + B^T P B)^{-1} B^T P A$ -For resource-constrained microcontrollers, compute K offline (e.g., in MATLAB with `dlqr`) and use the pre-computed gain constructor: +**Runtime:** $u[k] = -K x[k]$ — a $1 \times 2$ times $2 \times 1$ multiply per sample. -```cpp -math::Matrix K{ - { 10.378f, 4.063f } -}; +## Pitfalls & Edge Cases -controllers::Lqr lqr(K); +- **Uncontrollable modes.** If $(A, B)$ is not stabilizable, the DARE has no stabilizing solution. Verify controllability before calling the solver. +- **Ill-conditioned $R$.** If $R$ is near-singular, the inversion in $K$ becomes numerically unstable. Ensure $R$ is strictly positive definite. +- **Q/R scaling.** Only the *ratio* of $Q$ to $R$ matters. Scaling both by the same factor does not change $K$. +- **Full state required.** LQR assumes all states are measured. If only partial measurements are available, combine LQR with a [Kalman Filter](../filters/active/KalmanFilter.md) to form an LQG controller. +- **Fixed-point limitations.** The DARE involves matrix inversions and multiplications that can overflow Q15/Q31 ranges. Prefer floating-point for the offline solve; use the pre-computed $K$ constructor for fixed-point runtime. -auto u = lqr.ComputeControl(state); -``` +## Variants & Generalizations -This avoids the DARE solve entirely on the target, reducing flash and RAM usage. +| Variant | Key Difference | +|---------|---------------| +| **Continuous-time LQR** | Solves the Continuous ARE instead of DARE; used for continuous-time plant models | +| **LQG (Linear Quadratic Gaussian)** | Combines LQR with Kalman filter for systems with noisy, partial observations | +| **LQR with integral action** | Augments the state with integral of tracking error to eliminate steady-state offset | +| **Finite-horizon LQR** | Time-varying gain $K[k]$ for finite-duration tasks | +| **Robust LQR (H∞)** | Accounts for model uncertainty by optimizing the worst-case cost | +| **Pre-computed gain** | $K$ is computed offline (e.g., in MATLAB with `dlqr`) and hard-coded for embedded targets | -### Q/R Tuning Guidelines +## Applications -**Bryson's Rule** provides a starting point for weight selection: +- **Cart-pole balancing** — Classic underactuated system; LQR linearized around the upright equilibrium. +- **Quadrotor attitude control** — Regulating roll, pitch, yaw with motor thrust as input. +- **Satellite station-keeping** — Maintaining orbital position with minimal thruster fuel. +- **Industrial process control** — Multi-input multi-output (MIMO) systems where PID struggles. +- **Autonomous vehicles** — Lateral and longitudinal control using a linearized vehicle model. +## Connections to Other Algorithms + +```mermaid +graph LR + LQR["LQR Controller"] + DARE["DARE Solver"] + GE["Gaussian Elimination"] + KF["Kalman Filter"] + PID["PID Controller"] + DARE --> LQR + GE --> DARE + KF -->|"state estimate"| LQR + PID -.->|"model-free alternative"| LQR ``` -Q[i][i] = 1 / (maximum acceptable value of state i)² -R[j][j] = 1 / (maximum acceptable value of input j)² -``` -**Tuning Heuristics:** -- Increase `Q[i][i]` to reduce steady-state error of state i (more aggressive) -- Increase `R[j][j]` to reduce control effort on input j (more conservative) -- The ratio Q/R matters more than absolute values -- Start with Q = I, R = I and adjust from there +| Algorithm | Relationship | +|-----------|-------------| +| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | Computes the cost-to-go matrix $P$ from which $K$ is derived | +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used inside DARE iteration to solve linear sub-systems | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Provides state estimates when direct measurement is unavailable (forming LQG) | +| [PID Controller](Pid.md) | Model-free alternative; simpler to deploy but not optimal | + +## References & Further Reading + +- Anderson, B.D.O. and Moore, J.B., *Optimal Control: Linear Quadratic Methods*, Prentice Hall, 1990. +- Franklin, G.F., Powell, J.D. and Emami-Naeini, A., *Feedback Control of Dynamic Systems*, 8th ed., Pearson, 2019 — Chapter 9. +- Bryson, A.E. and Ho, Y.-C., *Applied Optimal Control*, Hemisphere, 1975. diff --git a/doc/controllers/Pid.md b/doc/controllers/Pid.md index 9c5d7756..e5abff55 100644 --- a/doc/controllers/Pid.md +++ b/doc/controllers/Pid.md @@ -1,197 +1,116 @@ -# PID Controller Implementation Guide +# PID Controller -## Mathematical Background +## Overview & Motivation -### The PID Control Law +The **Proportional-Integral-Derivative (PID) controller** is the workhorse of industrial feedback control. It continuously computes an error $e(t)$ — the difference between a desired setpoint and a measured process variable — and applies a correction based on three terms: one proportional to the current error, one to its accumulated history, and one to its rate of change. -A Proportional-Integral-Derivative (PID) controller is a control loop feedback mechanism widely used in industrial control systems. The controller continuously calculates an error value e(t) as the difference between a desired setpoint and a measured process variable, and applies a correction based on proportional, integral, and derivative terms. +Despite its simplicity, PID handles a remarkably wide range of plants — from temperature regulation to motor speed control — because each term addresses a different aspect of the transient response: -The continuous-time PID control law is: +- **P** reacts immediately to the current error. +- **I** eliminates steady-state offset by integrating past errors. +- **D** anticipates future error by acting on the rate of change. -``` -u(t) = Kp*e(t) + Ki*∫e(t)dt + Kd*de(t)/dt -``` +This library implements a **discrete recursive form** suitable for fixed-sample-rate embedded loops, where the output is computed incrementally rather than from scratch at every step. -where: -- u(t) is the control signal -- e(t) is the error value -- Kp is the proportional gain -- Ki is the integral gain -- Kd is the derivative gain +## Mathematical Theory -### Digital Implementation +### Continuous-Time PID -In digital systems, we need to discretize the continuous PID equation. Our implementation uses a discrete-time approximation where: +$$u(t) = K_p \, e(t) + K_i \int_0^t e(\tau)\,d\tau + K_d \frac{de(t)}{dt}$$ -1. The integral term is approximated using numerical integration -2. The derivative term is approximated using finite differences -3. The control output is computed recursively +### Discrete Recursive Form -The discrete form implemented in the code is: +Discretizing with sampling period $T_s$ and applying the difference approximation: -``` -y[n] = y[n-1] + a0*x[n] + a1*x[n-1] + a2*x[n-2] -``` +$$u[n] = u[n-1] + a_0 \, e[n] + a_1 \, e[n-1] + a_2 \, e[n-2]$$ where: -- y[n] is the current output -- x[n] is the current error -- a0 = Kp + Ki + Kd -- a1 = -(Kp + 2Kd) -- a2 = Kd - -## Implementation Details - -### Class Structure - -```cpp -template -class Pid { -public: - struct Tunings { - QNumberType kp; - QNumberType ki; - QNumberType kd; - }; - - struct Limits { - QNumberType min; - QNumberType max; - }; - - Pid(Tunings tunings, Limits limits, bool autoMode = true); - - // Core functionality - void SetPoint(QNumberType setPoint); - QNumberType Process(QNumberType measuredProcessVariable); - - // Configuration methods - void Enable(); - void Disable(); - void SetLimits(Limits limits); - void SetTunings(Tunings tunings); - void Reset(); -}; -``` - -### Key Components -1. **Tunings Structure**: Holds the PID gains (Kp, Ki, Kd) -2. **Limits Structure**: Defines output saturation limits -3. **RecursiveBuffer**: Stores historical values for error and output -4. **Process Method**: Implements the core PID algorithm -5. **Auto/Manual Mode**: Supports switching between automatic and manual control +$$a_0 = K_p + K_i + K_d$$ +$$a_1 = -(K_p + 2K_d)$$ +$$a_2 = K_d$$ -## Usage Guide +This incremental (velocity) form has two key advantages: -### Basic Usage +1. **No integral accumulator** — the integral action is implicit in the recursion, reducing overflow risk. +2. **Bumpless mode switching** — toggling between auto/manual mode does not cause output jumps because the output is updated incrementally. -```cpp -// Create a PID instance -Pid::Tunings tunings{ - .kp = 1.0f, - .ki = 0.1f, - .kd = 0.05f -}; +### Output Saturation -Pid::Limits limits{ - .min = -100.0f, - .max = 100.0f -}; +The output is clamped to $[u_{\min}, u_{\max}]$ after each computation, which also provides implicit **anti-windup**: the integral term cannot drive the output beyond the saturation limits. -Pid pid(tunings, limits); +## Complexity Analysis -// Set the desired setpoint -pid.SetPoint(50.0f); +| Case | Time | Space | Notes | +|------|------|-------|-------| +| Per sample | $O(1)$ | $O(1)$ | 3 multiplications, 3 additions, 1 clamp | -// In control loop -while (true) { - float measuredValue = getMeasurement(); - float controlOutput = pid.Process(measuredValue); - applyControl(controlOutput); -} -``` +The algorithm uses a fixed-size recursive buffer storing $e[n-1]$, $e[n-2]$, and $u[n-1]$. No loops, no dynamic allocation, fully deterministic execution time. -### Tuning the Controller +## Step-by-Step Walkthrough -The PID gains affect the system response: -1. **Proportional (Kp)**: Provides quick response to error -2. **Integral (Ki)**: Eliminates steady-state error -3. **Derivative (Kd)**: Provides damping and reduces overshoot +**Parameters:** $K_p = 2$, $K_i = 0.5$, $K_d = 0.1$, limits $[-10, 10]$, setpoint $= 5$. -Tuning guidelines: -1. Start with Ki = Kd = 0, and adjust Kp until acceptable response -2. Gradually increase Ki to eliminate steady-state error -3. Add Kd if needed to reduce overshoot -4. Always test with actual process dynamics +**Coefficients:** +- $a_0 = 2 + 0.5 + 0.1 = 2.6$ +- $a_1 = -(2 + 0.2) = -2.2$ +- $a_2 = 0.1$ -## Best Practices +| Step | Measured | $e[n]$ | $e[n-1]$ | $e[n-2]$ | $\Delta u$ | $u[n]$ (clamped) | +|------|----------|--------|-----------|-----------|------------|-------------------| +| 0 | 0.0 | 5.0 | 0 | 0 | $2.6 \times 5 = 13$ | **10.0** (clamped) | +| 1 | 2.0 | 3.0 | 5.0 | 0 | $2.6(3) - 2.2(5) + 0.1(0) = -3.2$ | **6.8** | +| 2 | 4.0 | 1.0 | 3.0 | 5.0 | $2.6(1) - 2.2(3) + 0.1(5) = -3.5$ | **3.3** | +| 3 | 4.8 | 0.2 | 1.0 | 3.0 | $2.6(0.2) - 2.2(1) + 0.1(3) = -1.38$ | **1.92** | -1. **Output Limiting**: Always use appropriate min/max limits to prevent integral windup -2. **Numerical Precision**: Use appropriate QNumberType based on application needs -3. **Mode Handling**: Use Enable()/Disable() to switch between auto/manual modes -4. **Reset Handling**: Call Reset() when making significant changes to setpoint +The output converges toward the steady-state value needed to maintain the setpoint. -## Common Applications +## Pitfalls & Edge Cases -1. **Temperature Control**: Maintaining precise temperature in industrial processes -2. **Motor Control**: Speed and position control in robotics -3. **Process Control**: Flow rate, pressure, and level control -4. **Motion Control**: Precise positioning systems +- **Derivative kick.** A sudden change in setpoint causes a spike in $e[n] - e[n-1]$. Mitigate by differentiating the process variable instead of the error, or by filtering the derivative term. +- **Integral windup.** Although the recursive form provides implicit anti-windup through output clamping, very aggressive $K_i$ values can still cause sluggish recovery from saturation. Monitor the output rail time. +- **Sample rate dependency.** The gains $K_i$ and $K_d$ are implicitly scaled by $T_s$. Changing the control loop rate without retuning will alter the effective integral and derivative contributions. +- **Fixed-point saturation.** For Q15/Q31 types, the intermediate products $a_0 \cdot e[n]$ etc. can overflow. Ensure gains and error ranges are scaled to stay within the representable range. +- **Setpoint jumps.** Call `Reset()` after large setpoint changes to clear stale error history. -## Example: Temperature Control +## Variants & Generalizations -```cpp -// Configure PID for temperature control -Pid::Tunings tunings{ - .kp = 2.0f, // Aggressive proportional for quick response - .ki = 0.1f, // Small integral to eliminate steady state error - .kd = 0.5f // Moderate derivative to prevent overshoot -}; +| Variant | Key Difference | +|---------|---------------| +| **Standard (positional) PID** | Computes $u[n]$ from scratch each step using an explicit integral accumulator | +| **PI controller** | $K_d = 0$; simpler, no derivative noise issues | +| **PD controller** | $K_i = 0$; no steady-state error correction, used when offset is acceptable | +| **PID with derivative filter** | Low-passes the derivative term to reject high-frequency noise | +| **Gain-scheduled PID** | Tuning parameters vary as a function of operating point | +| **Cascade PID** | Inner and outer loops, each with its own PID — common in motor control | -Pid::Limits limits{ - .min = 0.0f, // Cannot cool below ambient - .max = 100.0f // Maximum heater power -}; +## Applications -Pid temperatureController(tunings, limits); +- **Temperature control** — Maintaining oven, room, or process temperatures via heater/cooler actuation. +- **Motor speed/position control** — Servo drives, robotics joints, CNC machines. +- **Flow and pressure regulation** — Industrial process control (chemical plants, water treatment). +- **Voltage/current regulation** — Power supply output regulation, battery charging. +- **Attitude control** — Drone stabilization, satellite pointing. -// Set desired temperature -temperatureController.SetPoint(75.0f); +## Connections to Other Algorithms -// Control loop -while (true) { - float currentTemp = readTemperature(); - float heaterPower = temperatureController.Process(currentTemp); - setHeaterPower(heaterPower); - wait(100ms); -} +```mermaid +graph LR + PID["PID Controller"] + LQR["LQR Controller"] + KF["Kalman Filter"] + PID -.->|"alternative"| LQR + KF -->|"state estimate"| LQR + KF -->|"filtered measurement"| PID ``` -## Performance Considerations - -1. **Recursive Buffers**: Efficient storage of historical values -2. **Template Implementation**: Compile-time optimizations -3. **Output Clamping**: Prevents integral windup -4. **Auto/Manual Mode**: Zero overhead when disabled - -## Limitations and Future Improvements - -1. Current implementation could be extended to support: - - Anti-windup mechanisms - - Derivative filter - - Auto-tuning capabilities - - Gain scheduling - - Feed-forward control -2. Additional features that could be added: - - Parameter validation - - Runtime performance metrics - - Adaptive control - - Cascade control support - -## Safety Considerations - -1. **Output Limiting**: Always use appropriate limits to protect the process -2. **Mode Transitions**: Implement bumpless transfer between auto/manual modes -3. **Numerical Stability**: Monitor for overflow in integral term -4. **Fail-Safe Behavior**: Implement appropriate behavior for sensor failures +| Algorithm | Relationship | +|-----------|-------------| +| [LQR Controller](Lqr.md) | Optimal alternative when a state-space model is available; PID is model-free. | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Can provide filtered state estimates as input to either PID or LQR | + +## References & Further Reading + +- Åström, K.J. and Murray, R.M., *Feedback Systems: An Introduction for Scientists and Engineers*, Princeton University Press, 2008 — Chapter 10. +- Åström, K.J. and Hägglund, T., *Advanced PID Control*, ISA, 2006. +- Ziegler, J.G. and Nichols, N.B., "Optimum settings for automatic controllers", *Transactions of the ASME*, 64, 1942. diff --git a/doc/controllers/README.md b/doc/controllers/README.md new file mode 100644 index 00000000..589e910e --- /dev/null +++ b/doc/controllers/README.md @@ -0,0 +1,10 @@ +# Controllers + +Feedback control algorithms for regulating dynamic systems in real time. + +## Algorithms + +| Algorithm | Description | +|-----------|-------------| +| [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation | +| [LQR Controller](Lqr.md) | Linear Quadratic Regulator — optimal state-feedback control minimizing a quadratic cost | diff --git a/doc/estimators/LinearRegression.md b/doc/estimators/LinearRegression.md index bbfd5951..a121bfb9 100644 --- a/doc/estimators/LinearRegression.md +++ b/doc/estimators/LinearRegression.md @@ -1,261 +1,124 @@ -# Linear Regression Implementation Guide +# Linear Regression -## Process Overview +## Overview & Motivation -The following diagram illustrates the key steps in the Linear Regression implementation: +Given a set of observations $\{(x_i, y_i)\}$, we often want to find the *best-fit* linear relationship between features $x$ and target $y$. **Linear regression** does this by finding the coefficients $\beta$ that minimize the sum of squared residuals — the gap between predicted and observed values. -```mermaid -graph TD - A[Input Features X & Target y] --> B[Create Design Matrix] - B --> C[Add Bias Term] - C --> D[Calculate X^T * X] - D --> E[Calculate X^T * y] - E --> F[Solve Linear System] - F --> G[Get Coefficients] - G --> H[Make Predictions] -``` +The approach is fundamental because: +- It has a **closed-form solution** (the normal equation), so no iterative optimization is needed. +- It provides a **baseline model** against which more complex methods are measured. +- The solution is the **maximum likelihood estimator** under Gaussian noise assumptions. -## Mathematical Background +This library solves the normal equation directly using Gaussian elimination, making it suitable for small-to-moderate feature counts typical in embedded estimation tasks. -### Linear Regression Model +## Mathematical Theory -Linear regression models the relationship between a dependent variable y and one or more independent variables X by fitting a linear equation: +### The Model -``` -y = β₀ + β₁x₁ + β₂x₂ + ... + βₙxₙ + ε -``` +$$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_p x_p + \varepsilon$$ -where: -- y is the target variable -- β₀ is the bias term (intercept) -- βᵢ are the coefficients -- xᵢ are the features -- ε is the error term +In matrix form, augmenting $X$ with a column of ones for the intercept: + +$$\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}$$ + +where $\mathbf{X} \in \mathbb{R}^{n \times (p+1)}$, $\boldsymbol{\beta} \in \mathbb{R}^{p+1}$, $\mathbf{y} \in \mathbb{R}^n$. ### Normal Equation -Our implementation uses the normal equation method to find the optimal coefficients: +Minimizing $\|\mathbf{y} - \mathbf{X}\boldsymbol{\beta}\|^2$ with respect to $\boldsymbol{\beta}$ yields: -``` -β = (X^T * X)^(-1) * X^T * y -``` +$$\boldsymbol{\beta} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}$$ -where: -- X is the design matrix (with added bias column) -- y is the target vector -- β is the coefficient vector -- X^T is the transpose of X +This is solved in practice by forming $\mathbf{X}^T\mathbf{X}$ and $\mathbf{X}^T\mathbf{y}$, then using Gaussian elimination to solve the $(p+1) \times (p+1)$ system. -## Implementation Details +### Geometric Interpretation -### Class Structure +The prediction $\hat{\mathbf{y}} = \mathbf{X}\boldsymbol{\beta}$ is the **orthogonal projection** of $\mathbf{y}$ onto the column space of $\mathbf{X}$. The residual $\mathbf{y} - \hat{\mathbf{y}}$ is perpendicular to every column of $\mathbf{X}$. -```cpp -template -class LinearRegression : public Estimator { -public: - using CoefficientsMatrix = typename Estimator::CoefficientsMatrix; - using DesignMatrix = typename Estimator::DesignMatrix; - using InputMatrix = typename Estimator::InputMatrix; +## Complexity Analysis - void Fit(const Matrix& X, const Matrix& y); - T Predict(const InputMatrix& X) const; - const CoefficientsMatrix& Coefficients() const; -}; -``` +| Phase | Time | Space | Notes | +|-------|------|-------|-------| +| $\mathbf{X}^T\mathbf{X}$ | $O(n p^2)$ | $O(p^2)$ | Dominated by matrix multiply | +| $\mathbf{X}^T\mathbf{y}$ | $O(np)$ | $O(p)$ | Matrix-vector multiply | +| Solve | $O(p^3)$ | $O(p^2)$ | Gaussian elimination | +| Predict | $O(p)$ | $O(1)$ | Dot product | -### Key Components +For embedded use with small $p$ (say $\leq 10$), the entire fit completes in microseconds. -1. **Design Matrix Creation**: - - Adds bias term (1.0) as first column - - Incorporates feature matrix X - - Results in augmented matrix [1|X] +## Step-by-Step Walkthrough -2. **Matrix Operations**: - - Computes X^T * X - - Computes X^T * y - - Solves system using Gaussian elimination +**Data:** 3 samples, 1 feature. -3. **Coefficient Storage**: - - Stores β₀ (bias) and feature coefficients - - Accessible via Coefficients() method +| $x$ | $y$ | +|-----|-----| +| 1 | 2 | +| 2 | 4 | +| 3 | 5 | -4. **Prediction**: - - Implements y = Xβ for new data - - Includes bias term automatically +**Step 1 — Design matrix** (with bias column): -## Usage Guide +$$\mathbf{X} = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix}$$ -### Basic Usage +**Step 2 — Compute $\mathbf{X}^T\mathbf{X}$ and $\mathbf{X}^T\mathbf{y}$:** -```cpp -// Define system parameters -constexpr std::size_t samples = 100; // Number of training samples -constexpr std::size_t features = 2; // Number of features -using FloatType = float; // Numeric type +$$\mathbf{X}^T\mathbf{X} = \begin{bmatrix} 3 & 6 \\ 6 & 14 \end{bmatrix}, \quad \mathbf{X}^T\mathbf{y} = \begin{bmatrix} 11 \\ 23 \end{bmatrix}$$ -// Create regressor -LinearRegression regressor; +**Step 3 — Solve** $\begin{bmatrix} 3 & 6 \\ 6 & 14 \end{bmatrix} \boldsymbol{\beta} = \begin{bmatrix} 11 \\ 23 \end{bmatrix}$: -// Prepare training data -Matrix X; // Feature matrix -Matrix y; // Target vector -// ... fill X and y with data ... +Forward elimination → back-substitution: $\beta_1 = 1.5$, $\beta_0 = 2/3 \approx 0.667$ -// Train the model -regressor.Fit(X, y); +**Result:** $\hat{y} = 0.667 + 1.5x$ -// Make predictions -Matrix new_data; -// ... fill new_data ... -FloatType prediction = regressor.Predict(new_data); -``` +**Prediction at $x = 4$:** $\hat{y} = 0.667 + 6.0 = 6.667$ + +## Pitfalls & Edge Cases + +- **Multicollinearity.** If features are nearly linearly dependent, $\mathbf{X}^T\mathbf{X}$ is ill-conditioned and the solution is unstable. Consider regularization (Ridge/Lasso) or removing redundant features. +- **Fewer samples than features** ($n < p+1$). The system is underdetermined and $\mathbf{X}^T\mathbf{X}$ is singular. At a minimum, $n \geq p+1$. +- **Outliers** have outsized influence because the squared loss amplifies large residuals. Robust alternatives (Huber loss, RANSAC) exist outside this library. +- **Extrapolation danger.** The linear model has no mechanism to detect when it is being queried far from the training data range. +- **Fixed-point precision.** For Q15/Q31 types, features should be scaled to $[-1, 1)$ to avoid overflow in $\mathbf{X}^T\mathbf{X}$. -### Example: House Price Prediction +## Variants & Generalizations -```cpp -// Create regressor for house price prediction -constexpr std::size_t samples = 1000; -constexpr std::size_t features = 3; // size, bedrooms, age -LinearRegression house_price_model; +| Variant | Key Difference | +|---------|---------------| +| **Ridge regression (L2)** | Adds $\lambda\|\boldsymbol{\beta}\|^2$ to the cost; solves $(\mathbf{X}^T\mathbf{X} + \lambda I)\boldsymbol{\beta} = \mathbf{X}^T\mathbf{y}$ | +| **Lasso regression (L1)** | Adds $\lambda\|\boldsymbol{\beta}\|_1$; promotes sparsity but requires iterative optimization | +| **Polynomial regression** | Adds powers of $x$ as new features; still linear in parameters | +| **Weighted least squares** | Weights each sample differently; solves $(\mathbf{X}^T W \mathbf{X})\boldsymbol{\beta} = \mathbf{X}^T W \mathbf{y}$ | +| **Recursive least squares** | Updates $\boldsymbol{\beta}$ incrementally as new data arrives; suited for online estimation | -// Prepare training data -Matrix houses; -Matrix prices; -// ... load house data ... +## Applications -// Train model -house_price_model.Fit(houses, prices); +- **Sensor calibration** — Fitting a linear transfer function between raw ADC counts and physical units. +- **Trend estimation** — Extracting linear trends from noisy time series (temperature, voltage drift). +- **System identification** — Estimating static gain or simple dynamic relationships. +- **Feature importance** — The magnitude of $\beta_i$ indicates the influence of feature $i$ (after feature scaling). +- **Predictive maintenance** — Modeling degradation rate from operating-condition features. -// Predict new house price -Matrix new_house; -new_house.at(0, 0) = 2000.0f; // size in sq ft -new_house.at(1, 0) = 3.0f; // bedrooms -new_house.at(2, 0) = 5.0f; // age in years -float predicted_price = house_price_model.Predict(new_house); +## Connections to Other Algorithms + +```mermaid +graph LR + LR["Linear Regression"] + GE["Gaussian Elimination"] + YW["Yule-Walker"] + NN["Neural Network"] + LR --> GE + YW -.->|"similar normal-equation structure"| LR + NN -.->|"single linear layer = regression"| LR ``` -## Best Practices - -1. **Data Preparation**: - - Scale features to similar ranges - - Remove or handle missing values - - Check for multicollinearity - -2. **Model Validation**: - - Split data into train/test sets - - Use cross-validation when possible - - Check residuals distribution - -3. **Numerical Stability**: - - Use appropriate numeric types - - Consider conditioning of X^T * X - - Monitor for overflow/underflow - -4. **Feature Selection**: - - Choose relevant features - - Avoid redundant features - - Consider feature interactions - -## Common Applications - -1. **Prediction Tasks**: - - Price estimation - - Demand forecasting - - Performance prediction - -2. **Analysis**: - - Feature importance - - Trend analysis - - System modeling - -3. **Control Systems**: - - System identification - - Parameter estimation - - Process control - -## Performance Considerations - -1. **Template Parameters**: - - Fixed sizes enable compile-time optimizations - - Stack allocation for small matrices - - Type flexibility (float/double) - -2. **Memory Usage**: - - Efficient matrix operations - - No dynamic allocation - - Reuse of temporary matrices - -3. **Computation Efficiency**: - - In-place operations where possible - - Optimized matrix multiplication - - Efficient system solver - -## Limitations and Future Improvements - -1. Current limitations: - - Fixed sample/feature size - - Basic Gaussian elimination solver - - No regularization support - - Limited to linear relationships - -2. Possible extensions: - - Dynamic sizing - - Ridge/Lasso regularization - - QR decomposition solver - - Polynomial features - - Online learning support - - Standard error estimation - - Feature importance scores - - Cross-validation utilities - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Sufficient sample size - - Matrix dimension compatibility - -2. Runtime checks: - - Matrix singularity - - Numerical stability - - Solution convergence - -## Performance Metrics - -To evaluate the model's performance, consider implementing: - -1. **Regression Metrics**: - - Mean Squared Error (MSE) - - R-squared (R²) - - Mean Absolute Error (MAE) - - Root Mean Squared Error (RMSE) - -2. **Diagnostic Tools**: - - Residual plots - - Q-Q plots - - Leverage statistics - - Cook's distance - -## Mathematical Details - -### Gaussian Elimination - -The implementation uses Gaussian elimination with partial pivoting to solve the normal equations: - -1. Forward elimination: - ``` - for i = 1 to n - pivot = max_element(i to n) - swap_rows(i, pivot) - for j = i+1 to n - eliminate(row[j], row[i]) - ``` - -2. Back substitution: - ``` - for i = n to 1 - x[i] = (b[i] - Σ(j=i+1 to n) a[i,j]x[j]) / a[i,i] - ``` - -This provides a stable solution for well-conditioned problems. +| Algorithm | Relationship | +|-----------|-------------| +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used to solve the normal equation system | +| [Yule-Walker](YuleWalker.md) | Structurally similar — also solves a linear system derived from correlations | +| [Neural Network](../neural_network/NeuralNetwork.md) | A single-layer neural network with no activation and MSE loss reduces to linear regression | + +## References & Further Reading + +- Hastie, T., Tibshirani, R. and Friedman, J., *The Elements of Statistical Learning*, 2nd ed., Springer, 2009 — Chapter 3. +- Bishop, C.M., *Pattern Recognition and Machine Learning*, Springer, 2006 — Chapter 3. +- Strang, G., *Linear Algebra and Its Applications*, 4th ed., Thomson, 2006 — Section 4.3. diff --git a/doc/estimators/README.md b/doc/estimators/README.md new file mode 100644 index 00000000..819ce779 --- /dev/null +++ b/doc/estimators/README.md @@ -0,0 +1,10 @@ +# Estimators + +Statistical estimation algorithms for fitting models to observed data and making predictions. + +## Algorithms + +| Algorithm | Description | +|-----------|-------------| +| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | +| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | diff --git a/doc/estimators/YuleWalker.md b/doc/estimators/YuleWalker.md index 7daf786c..9929ca6d 100644 --- a/doc/estimators/YuleWalker.md +++ b/doc/estimators/YuleWalker.md @@ -1,289 +1,134 @@ -# Yule-Walker Implementation Guide +# Yule-Walker Estimation -## Process Overview +## Overview & Motivation -The following diagram illustrates the key steps in the Yule-Walker method implementation: +Many signals — vibration data, speech waveforms, financial time series — exhibit short-term correlations. An **autoregressive (AR) model** captures these correlations by expressing the current sample as a linear combination of the previous $p$ samples plus white noise. The **Yule-Walker method** estimates the AR coefficients directly from the signal's autocovariance structure. -```mermaid -graph TD - A[Input Time Series] --> B[Compute Mean] - B --> C[Center Time Series] - C --> D[Compute Autocovariances] - D --> E[Build Toeplitz Matrix] - D --> F[Build RHS Vector] - E --> G[Solve Linear System] - F --> G - G --> H[Get AR Coefficients] - H --> I[Make Predictions] -``` +The appeal is threefold: +1. The resulting system of equations has **Toeplitz structure**, enabling efficient $O(p^2)$ solvers. +2. The method is guaranteed to produce a **stable model** (all poles inside the unit circle) when the autocovariance matrix is positive definite. +3. It provides a **parametric spectral estimate** — the PSD is a smooth rational function rather than a noisy periodogram. -## Mathematical Background +## Mathematical Theory ### Autoregressive Model -The Yule-Walker method estimates the parameters of an autoregressive (AR) model of order p: +An AR($p$) process: -``` -x[t] = c + φ₁x[t-1] + φ₂x[t-2] + ... + φₚx[t-p] + ε[t] -``` +$$x[t] = \varphi_1 x[t-1] + \varphi_2 x[t-2] + \cdots + \varphi_p x[t-p] + \varepsilon[t]$$ -where: -- x[t] is the time series value at time t -- c is a constant (related to the mean) -- φᵢ are the AR coefficients -- p is the order of the model -- ε[t] is white noise +where $\varepsilon[t]$ is white noise with variance $\sigma^2$. ### Yule-Walker Equations -The method solves the following system of equations: +Multiplying both sides by $x[t-k]$ and taking expectations: -``` -R[k] = φ₁R[k-1] + φ₂R[k-2] + ... + φₚR[k-p] for k = 1,2,...,p -``` +$$R[k] = \varphi_1 R[k-1] + \varphi_2 R[k-2] + \cdots + \varphi_p R[k-p], \quad k = 1, \ldots, p$$ -where R[k] is the autocovariance function at lag k. This can be written in matrix form: +where $R[k] = E[x[t] \cdot x[t-k]]$ is the autocovariance at lag $k$. In matrix form: -``` -[R[0] R[1] ... R[p-1]] [φ₁] [R[1]] -[R[1] R[0] ... R[p-2]] [φ₂] [R[2]] -[ ⋮ ⋮ ⋱ ⋮ ] [ ⋮ ] = [ ⋮ ] -[R[p-1] R[p-2] ... R[0] ] [φₚ] [R[p]] -``` - -## Implementation Details - -### Class Structure - -```cpp -template -class YuleWalker { -public: - using CoefficientsMatrix = typename math::Matrix; - using DesignMatrix = math::Matrix; - using InputMatrix = math::Matrix; - using TimeSeriesVector = math::Matrix; - - explicit YuleWalker(solvers::Solver& solver); - void Fit(const Matrix& X, const Matrix& y); - T Predict(const InputMatrix& X) const; - const CoefficientsMatrix& Coefficients() const; -}; -``` +$$\underbrace{\begin{bmatrix} R[0] & R[1] & \cdots & R[p-1] \\ R[1] & R[0] & \cdots & R[p-2] \\ \vdots & & \ddots & \vdots \\ R[p-1] & R[p-2] & \cdots & R[0] \end{bmatrix}}_{\mathbf{R} \text{ (Toeplitz)}} \begin{bmatrix} \varphi_1 \\ \varphi_2 \\ \vdots \\ \varphi_p \end{bmatrix} = \begin{bmatrix} R[1] \\ R[2] \\ \vdots \\ R[p] \end{bmatrix}$$ -### Key Components +### Autocovariance Estimation -1. **Mean Computation and Centering**: - - Calculates series mean - - Centers time series by subtracting mean - - Improves numerical stability +The biased estimator is used: -2. **Autocovariance Calculation**: - - Computes autocovariances for lags 0 to p - - Uses biased estimator (divided by N) - - Implements two-pass algorithm for stability +$$\hat{R}[k] = \frac{1}{N} \sum_{t=k}^{N-1} x[t] \cdot x[t-k]$$ -3. **Toeplitz Matrix Formation**: - - Creates symmetric Toeplitz matrix from autocovariances - - Ensures matrix properties for solver +after centering the series by subtracting its mean. The biased estimator (dividing by $N$ instead of $N-k$) guarantees the Toeplitz matrix is positive semi-definite. -4. **System Solution**: - - Uses provided solver for linear system - - Returns AR coefficients - - Handles prediction with mean adjustment +### Spectral Interpretation -## Usage Guide +The PSD of the estimated AR model is: -### Basic Usage +$$S(f) = \frac{\sigma^2}{\left|1 - \sum_{i=1}^{p} \varphi_i \, e^{-j2\pi fi}\right|^2}$$ -```cpp -// Define system parameters -constexpr std::size_t samples = 1000; // Length of time series -constexpr std::size_t order = 3; // AR model order -using FloatType = float; // Numeric type +This gives a smooth, parametric spectral estimate. -// Create solver (e.g., Levinson recursion) -solvers::LevinsonSolver solver; - -// Create Yule-Walker estimator -YuleWalker yw(solver); - -// Prepare training data -Matrix X; // Lagged values -Matrix y; // Target values -// ... fill X and y with time series data ... - -// Estimate AR coefficients -yw.Fit(X, y); - -// Make predictions -Matrix new_data; -// ... fill new_data with latest values ... -FloatType prediction = yw.Predict(new_data); -``` - -### Example: Temperature Forecasting - -```cpp -// Create AR model for temperature forecasting -constexpr std::size_t samples = 8760; // Hourly data for one year -constexpr std::size_t order = 24; // 24-hour seasonality - -// Create solver -solvers::LevinsonSolver solver; -YuleWalker temperature_model(solver); - -// Prepare training data -Matrix temp_history; -Matrix temp_target; -// ... load temperature data ... - -// Train model -temperature_model.Fit(temp_history, temp_target); - -// Predict next temperature -Matrix recent_temps; -// ... fill with last 24 hours ... -float next_temp = temperature_model.Predict(recent_temps); -``` +## Complexity Analysis -## Best Practices +| Phase | Time | Space | Notes | +|-------|------|-------|-------| +| Autocovariance | $O(Np)$ | $O(p)$ | One pass per lag, $p+1$ lags | +| Build Toeplitz matrix | $O(p^2)$ | $O(p^2)$ | Fill from autocovariance vector | +| Solve (Levinson-Durbin) | $O(p^2)$ | $O(p)$ | Exploits Toeplitz structure | +| Solve (Gaussian elim.) | $O(p^3)$ | $O(p^2)$ | General-purpose fallback | +| Predict | $O(p)$ | $O(1)$ | Dot product with past samples | -1. **Model Order Selection**: - - Use AIC/BIC criteria - - Consider domain knowledge - - Balance complexity vs. fit +## Step-by-Step Walkthrough -2. **Data Preparation**: - - Remove trends if present - - Handle seasonality - - Check for stationarity +**Input:** $x = [2, 4, 6, 5, 3, 1]$, AR order $p = 2$. -3. **Numerical Considerations**: - - Use appropriate solver - - Monitor condition number - - Check for stability +**Step 1 — Compute mean and center:** -4. **Validation**: - - Use hold-out data - - Check residuals - - Validate predictions +$\bar{x} = 3.5$, centered: $x' = [-1.5, 0.5, 2.5, 1.5, -0.5, -2.5]$ -## Common Applications +**Step 2 — Autocovariances** (biased, divide by $N = 6$): -1. **Time Series Analysis**: - - Economic forecasting - - Signal processing - - Weather prediction +- $R[0] = \frac{(-1.5)^2 + 0.5^2 + 2.5^2 + 1.5^2 + (-0.5)^2 + (-2.5)^2}{6} = \frac{2.25 + 0.25 + 6.25 + 2.25 + 0.25 + 6.25}{6} = 2.917$ +- $R[1] = \frac{(-1.5)(0.5) + (0.5)(2.5) + (2.5)(1.5) + (1.5)(-0.5) + (-0.5)(-2.5)}{6} = \frac{-0.75 + 1.25 + 3.75 - 0.75 + 1.25}{6} = 0.792$ +- $R[2] = \frac{(-1.5)(2.5) + (0.5)(1.5) + (2.5)(-0.5) + (1.5)(-2.5)}{6} = \frac{-3.75 + 0.75 - 1.25 - 3.75}{6} = -1.333$ -2. **Signal Processing**: - - Speech analysis - - Spectral estimation - - System identification +**Step 3 — Build Toeplitz system:** -3. **Control Systems**: - - Process control - - System modeling - - Feedback systems +$$\begin{bmatrix} 2.917 & 0.792 \\ 0.792 & 2.917 \end{bmatrix} \begin{bmatrix} \varphi_1 \\ \varphi_2 \end{bmatrix} = \begin{bmatrix} 0.792 \\ -1.333 \end{bmatrix}$$ -## Performance Considerations +**Step 4 — Solve** (e.g., via Levinson-Durbin or Gaussian elimination): -1. **Template Parameters**: - - Compile-time optimization - - Static memory allocation - - Type flexibility +$\varphi_1 \approx 0.478$, $\varphi_2 \approx -0.587$ -2. **Computation Efficiency**: - - Efficient autocovariance calculation - - Toeplitz matrix structure - - Solver selection +**Prediction:** $\hat{x}[6] = \bar{x} + \varphi_1 (x[5] - \bar{x}) + \varphi_2 (x[4] - \bar{x})$ -3. **Memory Usage**: - - Fixed-size matrices - - No dynamic allocation - - Buffer reuse +## Pitfalls & Edge Cases -## Limitations and Future Improvements +- **Non-stationary data.** The Yule-Walker method assumes wide-sense stationarity. Trends, seasonal components, or varying variance must be removed first. +- **Model order selection.** Choosing $p$ too small misses important dynamics; too large overfits noise. Use AIC or BIC criteria. +- **Near-singular autocovariance matrix.** Happens when $p$ is too large relative to $N$, or the signal contains very little variation. The solver may fail or produce unreliable coefficients. +- **Fixed-point range.** Autocovariance values can be large (proportional to signal variance squared). Scale the input signal to prevent overflow. +- **Biased vs. unbiased estimator.** The biased estimator (dividing by $N$) is deliberately chosen to guarantee positive semi-definiteness; the unbiased estimator (dividing by $N-k$) does not. -1. Current limitations: - - Fixed sample size - - Fixed model order - - Basic AR model only - - Single variable +## Variants & Generalizations -2. Possible extensions: - - Dynamic sizing - - ARMA models - - Multivariate support - - Online estimation - - Confidence intervals - - Model diagnostics - - Seasonal components - - Non-stationary support +| Variant | Key Difference | +|---------|---------------| +| **Burg's method** | Estimates AR coefficients from forward + backward prediction errors; often more accurate for short records | +| **Covariance method** | Uses the unbiased autocovariance; does not guarantee stability | +| **ARMA models** | Extends AR to include moving-average terms; more flexible but requires iterative estimation | +| **Vector autoregression (VAR)** | Multivariate extension for jointly modeling multiple time series | +| **Recursive estimation** | Updates AR coefficients online as new data arrives | -## Error Handling +## Applications -1. Static assertions verify: - - Valid numeric types - - Sufficient sample size - - Order constraints +- **Speech analysis** — AR models underlie linear predictive coding (LPC), the foundation of speech codecs. +- **Spectral estimation** — Parametric PSD estimation via the AR model gives smoother spectra than periodograms, especially for short records. +- **System identification** — Estimating transfer function poles from input-output data. +- **Time series forecasting** — Predicting next values in economic, meteorological, or sensor data. +- **Vibration analysis** — Extracting resonant frequencies from structural vibration measurements. -2. Runtime checks: - - Data validity - - Numerical stability - - Solution convergence +## Connections to Other Algorithms -## Advanced Topics - -### Stability Analysis - -The AR model is stable if all roots of the characteristic polynomial lie outside the unit circle: - -``` -1 - φ₁z⁻¹ - φ₂z⁻² - ... - φₚz⁻ᵖ = 0 -``` - -### Spectral Properties - -The power spectral density of an AR(p) process is: - -``` -S(f) = σ²/|1 - Σφᵢe⁻²ᵖⁱᶠᵗ|² -``` - -where σ² is the innovation variance. - -### Confidence Intervals - -Asymptotic standard errors for the AR coefficients can be computed using: - -``` -SE(φᵢ) = √((1-R²)/N) * √(C[i,i]) -``` - -where C is the covariance matrix of the estimates. - -## Implementation Notes - -### Autocovariance Computation - -The implementation uses a numerically stable two-pass algorithm: - -```cpp -T ComputeAutocovariance(const TimeSeriesVector& timeSeries, size_t lag) const { - T covariance{}; - size_t n = 0; - - for (size_t i = lag; i < Samples; ++i) { - covariance += timeSeries.at(i, 0) * timeSeries.at(i - lag, 0); - n++; - } - - return covariance / T(Samples); -} -``` - -This approach: -- Maintains numerical precision -- Handles large datasets efficiently -- Provides biased estimates for better stability +```mermaid +graph LR + YW["Yule-Walker"] + LD["Levinson-Durbin"] + GE["Gaussian Elimination"] + PSD["Power Spectral Density"] + LR["Linear Regression"] + YW --> LD + YW --> GE + YW -.->|"parametric alternative"| PSD + LR -.->|"similar structure"| YW +``` + +| Algorithm | Relationship | +|-----------|-------------| +| [Levinson-Durbin](../solvers/LevinsonDurbin.md) | Efficient $O(p^2)$ solver exploiting the Toeplitz structure of the Yule-Walker matrix | +| [Gaussian Elimination](../solvers/GaussianElimination.md) | General-purpose $O(p^3)$ solver used as a fallback | +| [Power Spectral Density](../analysis/PowerDensitySpectrum.md) | Non-parametric alternative; the AR model provides a parametric PSD estimate | +| [Linear Regression](LinearRegression.md) | Structurally similar — both solve a linear system derived from data correlations | + +## References & Further Reading + +- Kay, S.M., *Modern Spectral Estimation: Theory and Application*, Prentice Hall, 1988 — Chapter 7. +- Stoica, P. and Moses, R.L., *Spectral Analysis of Signals*, Prentice Hall, 2005 — Chapter 3. +- Box, G.E.P., Jenkins, G.M. and Reinsel, G.C., *Time Series Analysis: Forecasting and Control*, 5th ed., Wiley, 2015. diff --git a/doc/filters/README.md b/doc/filters/README.md new file mode 100644 index 00000000..532b9783 --- /dev/null +++ b/doc/filters/README.md @@ -0,0 +1,17 @@ +# Filters + +Digital filtering algorithms for noise reduction, state estimation, and signal conditioning. + +## Categories + +### Active Filters + +Filters that incorporate feedback and a dynamic internal model of the system. + +| Algorithm | Description | +|-----------|-------------| +| [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise | + +### Passive Filters + +*(Coming soon — FIR and IIR filter documentation)* diff --git a/doc/filters/active/KalmanFilter.md b/doc/filters/active/KalmanFilter.md index 32914e5b..ba950886 100644 --- a/doc/filters/active/KalmanFilter.md +++ b/doc/filters/active/KalmanFilter.md @@ -1,208 +1,141 @@ -# Kalman Filter Implementation Guide +# Kalman Filter -## Mathematical Background +## Overview & Motivation -### The Continuous-Time Kalman Filter +In any real system, sensors are noisy and models are imperfect. The **Kalman filter** answers a deceptively simple question: *given a noisy measurement and an imperfect prediction, what is the best estimate of the true state?* -The Kalman filter is an optimal estimator for linear systems with Gaussian noise. For a continuous-time system, the state-space model is: +The answer is an optimal, recursive, minimum-variance estimator for linear systems with Gaussian noise. At each time step it performs two operations: -``` -dx/dt = Fx(t) + Bu(t) + w(t) // State equation -z(t) = Hx(t) + v(t) // Measurement equation -``` +1. **Predict** — propagate the state and covariance forward using the system model. +2. **Update** — correct the prediction using the new measurement, weighted by the *Kalman gain*, which automatically balances trust in the model vs. trust in the sensor. -where: -- x(t) is the state vector -- z(t) is the measurement vector -- F is the state transition matrix -- B is the control input matrix -- H is the measurement matrix -- w(t) is the process noise (Q covariance) -- v(t) is the measurement noise (R covariance) +The filter is computationally lightweight (matrix operations on small state vectors), requires no storage of past measurements, and adapts its confidence in real time via the covariance matrix. -### Discrete-Time Implementation +## Mathematical Theory -For digital implementation, we use the discrete-time version: +### State-Space Model -``` -xₖ = Fₖ₋₁xₖ₋₁ + Bₖ₋₁uₖ₋₁ + wₖ₋₁ // State equation -zₖ = Hₖxₖ + vₖ // Measurement equation -``` +Discrete-time linear system with process noise $w$ and measurement noise $v$: -The filter operates in two steps: +$$x_k = F_{k-1} x_{k-1} + B_{k-1} u_{k-1} + w_{k-1}, \quad w \sim \mathcal{N}(0, Q)$$ +$$z_k = H_k x_k + v_k, \quad v \sim \mathcal{N}(0, R)$$ -1. **Predict** (Time Update): -``` -x̂ₖ₋ = Fₖ₋₁x̂ₖ₋₁ // State prediction -Pₖ₋ = Fₖ₋₁Pₖ₋₁Fₖ₋₁ᵀ + Qₖ₋₁ // Covariance prediction -``` +where: +- $x_k \in \mathbb{R}^n$ — state vector +- $z_k \in \mathbb{R}^m$ — measurement vector +- $F$ — state transition matrix ($n \times n$) +- $B$ — control input matrix ($n \times l$) +- $H$ — measurement matrix ($m \times n$) +- $Q$ — process noise covariance ($n \times n$) +- $R$ — measurement noise covariance ($m \times m$) -2. **Update** (Measurement Update): -``` -yₖ = zₖ - Hₖx̂ₖ₋ // Innovation -Sₖ = HₖPₖ₋Hₖᵀ + Rₖ // Innovation covariance -Kₖ = Pₖ₋Hₖᵀ(Sₖ)⁻¹ // Optimal Kalman gain -x̂ₖ = x̂ₖ₋ + Kₖyₖ // State update -Pₖ = (I - KₖHₖ)Pₖ₋ // Covariance update -``` +### Predict Step -## Implementation Details +$$\hat{x}_k^- = F_{k-1} \hat{x}_{k-1}$$ +$$P_k^- = F_{k-1} P_{k-1} F_{k-1}^T + Q_{k-1}$$ -### Class Structure +### Update Step -```cpp -template -class KalmanFilter { -public: - using StateMatrix = math::SquareMatrix; - using StateVector = math::Vector; - using MeasurementMatrix = math::Matrix; - using MeasurementVector = math::Vector; - using MeasurementCovariance = math::SquareMatrix; +$$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)}$$ - KalmanFilter(const StateVector& initialState, - const StateMatrix& initialCovariance); +### Optimality - void Predict(); - void Update(const MeasurementVector& measurement); -}; -``` +The Kalman filter is the **minimum mean-square error (MMSE)** estimator among all linear estimators. Under the assumption that $w$ and $v$ are Gaussian, it is also the MMSE among *all* estimators (linear or not). -### Key Components +## Complexity Analysis -1. **State Vector**: Contains the estimated state variables -2. **State Transition Matrix**: Models system dynamics -3. **Measurement Matrix**: Maps state space to measurement space -4. **Covariance Matrices**: Track uncertainty in estimates -5. **Kalman Gain**: Optimal weighting between prediction and measurement +| Operation | Time | Space | Notes | +|-----------|------|-------|-------| +| Predict | $O(n^2)$ | $O(n^2)$ | Matrix multiply $F P F^T$ | +| Update | $O(n^2 m + m^3)$ | $O(nm)$ | Dominated by $S^{-1}$ ($m \times m$ inversion) and gain computation | +| Total per step | $O(n^2 m + m^3)$ | $O(n^2 + nm)$ | For $m \ll n$, approximately $O(n^2)$ | -## Usage Guide +For typical embedded use with $n \leq 10$ and $m \leq 5$, each step completes in microseconds. -### Basic Usage +## Step-by-Step Walkthrough -```cpp -// Define system dimensions -constexpr std::size_t StateSize = 2; // e.g., position and velocity -constexpr std::size_t MeasurementSize = 1; // e.g., only position measured +**System:** Estimating position and velocity from noisy position measurements. -// Initialize filter -StateVector initialState; -initialState[0] = initial_position; -initialState[1] = initial_velocity; +State: $x = \begin{bmatrix} \text{position} \\ \text{velocity} \end{bmatrix}$, $\Delta t = 1$ s. -StateMatrix initialCovariance = StateMatrix::Identity(); -initialCovariance *= initial_uncertainty; +$$F = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, \quad H = \begin{bmatrix} 1 & 0 \end{bmatrix}, \quad Q = \begin{bmatrix} 0.1 & 0 \\ 0 & 0.1 \end{bmatrix}, \quad R = [1]$$ -KalmanFilter filter( - initialState, initialCovariance); +**Initial:** $\hat{x}_0 = [0, 0]^T$, $P_0 = \begin{bmatrix} 10 & 0 \\ 0 & 10 \end{bmatrix}$ -// Configure system matrices -StateMatrix F; // State transition matrix -F[0][0] = 1.0f; F[0][1] = dt; -F[1][0] = 0.0f; F[1][1] = 1.0f; -filter.SetStateTransition(F); +**Measurement:** $z_1 = 1.2$ (true position = 1.0) -MeasurementMatrix H; // Measurement matrix -H[0][0] = 1.0f; H[0][1] = 0.0f; // Only measure position -filter.SetMeasurementMatrix(H); +**Predict:** -// Set noise characteristics -StateMatrix Q = StateMatrix::Identity() * process_noise * process_noise; -filter.SetProcessNoise(Q); +$$\hat{x}_1^- = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 0 \\ 0 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$ -MeasurementCovariance R; -R[0][0] = measurement_noise * measurement_noise; -filter.SetMeasurementNoise(R); +$$P_1^- = F P_0 F^T + Q = \begin{bmatrix} 20.1 & 10 \\ 10 & 10.1 \end{bmatrix}$$ -// Main filter loop -while (haveMeasurements()) { - // Time update - filter.Predict(); +**Update:** - // Measurement update (if measurement available) - if (hasNewMeasurement()) { - MeasurementVector z; - z[0] = getMeasurement(); - filter.Update(z); - } +$$y_1 = 1.2 - [1\; 0] \begin{bmatrix} 0 \\ 0 \end{bmatrix} = 1.2$$ - // Access estimates - auto state = filter.GetState(); - auto covariance = filter.GetCovariance(); -} -``` +$$S_1 = H P_1^- H^T + R = 20.1 + 1 = 21.1$$ -### Example: Position and Velocity Estimation - -```cpp -// Create filter for tracking position and velocity -constexpr std::size_t N = 2; // State: [position, velocity] -KalmanFilter tracker(initialState, initialCovariance); - -// Configure for constant velocity model with dt = 0.1s -float dt = 0.1f; -StateMatrix F = {{1.0f, dt}, // position += velocity * dt - {0.0f, 1.0f}}; // velocity unchanged -tracker.SetStateTransition(F); - -// Only measuring position -MeasurementMatrix H = {{1.0f, 0.0f}}; // measure position only -tracker.SetMeasurementMatrix(H); - -// Process and update with measurements -for (const auto& measurement : measurements) { - tracker.Predict(); - tracker.Update(measurement); - - auto state = tracker.GetState(); - float position = state[0]; - float velocity = state[1]; -} -``` +$$K_1 = P_1^- H^T / S_1 = \begin{bmatrix} 20.1 \\ 10 \end{bmatrix} / 21.1 = \begin{bmatrix} 0.953 \\ 0.474 \end{bmatrix}$$ + +$$\hat{x}_1 = \begin{bmatrix} 0 \\ 0 \end{bmatrix} + \begin{bmatrix} 0.953 \\ 0.474 \end{bmatrix} \cdot 1.2 = \begin{bmatrix} 1.143 \\ 0.569 \end{bmatrix}$$ -## Best Practices +The filter quickly moves toward the measurement because the initial covariance $P_0$ is large (low confidence). Over subsequent steps, $P$ shrinks and the gain decreases — the filter becomes more reliant on the model. -1. **State Size**: Keep state vector minimal but complete -2. **Matrix Operations**: Use provided Matrix class for all operations -3. **Numerical Stability**: Monitor covariance matrix condition -4. **Update Rate**: Predict can run more frequently than Update +## Pitfalls & Edge Cases -## Common Applications +- **Model mismatch.** If the true system is nonlinear or the noise is non-Gaussian, the Kalman filter is suboptimal. Consider the Extended Kalman Filter (EKF) or Unscented Kalman Filter (UKF) for moderate nonlinearities. +- **Covariance divergence.** Numerical errors can cause $P$ to lose positive-definiteness over time. Symmetrize $P$ after each update; consider a square-root or UD factorization form for long-running filters. +- **Tuning $Q$ and $R$.** These are rarely known exactly. Increasing $Q$ makes the filter more responsive (trusts model less); increasing $R$ makes it smoother (trusts measurements less). Tune empirically or use adaptive methods. +- **Innovation covariance singularity.** If $S_k$ is singular, the measurement does not provide new information in some direction. Regularize $R$ or reduce the measurement model. +- **Missing measurements.** If no measurement is available, skip the update step entirely and only predict. The covariance will grow, correctly reflecting increasing uncertainty. +- **Fixed-point caution.** Matrix inversions and multiplications in the update step can overflow Q15/Q31 ranges. Use floating-point or carefully scale all matrices. -1. **Object Tracking**: Position, velocity estimation -2. **Sensor Fusion**: Combining multiple sensor measurements -3. **Navigation**: GPS and IMU integration -4. **Process Control**: State estimation for control systems +## Variants & Generalizations -## Performance Considerations +| Variant | Key Difference | +|---------|---------------| +| **Extended Kalman Filter (EKF)** | Linearizes nonlinear $f(x)$ and $h(x)$ around the current estimate | +| **Unscented Kalman Filter (UKF)** | Propagates sigma points through nonlinearities; avoids explicit Jacobians | +| **Square-root Kalman Filter** | Maintains $\sqrt{P}$ instead of $P$ for improved numerical stability | +| **Information Filter** | Works with the inverse covariance (information matrix); better for multi-sensor fusion | +| **Kalman Smoother** | Uses future measurements to refine past estimates (offline, non-causal) | +| **Adaptive Kalman Filter** | Estimates $Q$ and $R$ online from innovation statistics | -1. **Matrix Operations**: Optimized for small, fixed-size matrices -2. **Template Parameters**: Allow compile-time optimizations -3. **Memory Usage**: Stack-based allocation for all matrices -4. **Update Frequency**: Independent Predict/Update rates +## Applications -## Limitations and Future Improvements +- **GPS/INS navigation** — Fusing inertial measurements (high rate, drifty) with GPS (low rate, noisy). +- **Object tracking** — Radar, lidar, or camera-based tracking of moving targets. +- **Sensor fusion** — Combining accelerometer, gyroscope, and magnetometer for attitude estimation. +- **Process control** — State estimation for model-based controllers (LQG = [LQR](../controllers/Lqr.md) + Kalman). +- **Battery state-of-charge estimation** — Estimating internal states from voltage and current measurements. +- **Econometrics** — Estimating latent economic variables from noisy indicators. -1. Currently assumes: - - Linear system dynamics - - Gaussian noise characteristics - - Non-singular innovation matrix +## Connections to Other Algorithms -2. Could be extended to support: - - Extended Kalman Filter for nonlinear systems - - Unscented Kalman Filter - - Square root formulation - - Adaptive noise estimation - - Robust outlier rejection +```mermaid +graph LR + KF["Kalman Filter"] + LQR["LQR Controller"] + DARE["DARE Solver"] + PID["PID Controller"] + KF -->|"state estimate"| LQR + DARE -->|"steady-state gain"| KF + KF -->|"filtered measurement"| PID +``` -## Error Handling +| Algorithm | Relationship | +|-----------|-------------| +| [LQR Controller](../controllers/Lqr.md) | The Kalman filter + LQR = LQG (Linear Quadratic Gaussian), the separation principle | +| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | The steady-state Kalman gain can be found by solving a DARE (dual of the LQR DARE) | +| [PID Controller](../controllers/Pid.md) | Kalman-filtered measurements can serve as the PID's process variable input | -1. Static assertions check: - - Valid numeric types - - Valid matrix dimensions - - Matrix invertibility assumptions +## References & Further Reading -2. Runtime checks: - - Matrix operation validity - - Covariance matrix properties - - Numerical stability conditions +- Kalman, R.E., "A New Approach to Linear Filtering and Prediction Problems", *Journal of Basic Engineering*, 82(1), 1960. +- Simon, D., *Optimal State Estimation: Kalman, H∞, and Nonlinear Approaches*, Wiley, 2006. +- Bar-Shalom, Y., Li, X.R. and Kirubarajan, T., *Estimation with Applications to Tracking and Navigation*, Wiley, 2001. diff --git a/doc/neural_network/NeuralNetwork.md b/doc/neural_network/NeuralNetwork.md index f5fd6d5a..30241e4d 100644 --- a/doc/neural_network/NeuralNetwork.md +++ b/doc/neural_network/NeuralNetwork.md @@ -1,389 +1,163 @@ -# Neural Networks Implementation Guide +# Neural Networks -## Process Overview +## Overview & Motivation -The following diagram illustrates the key components of a neural network: +A neural network is a parameterized function $f_\theta: \mathbb{R}^n \to \mathbb{R}^m$ built by composing simple, differentiable transformations called **layers**. Each layer applies an affine map followed by a non-linear activation, and the whole composition is trained end-to-end by gradient-based optimization. -![Neural Network Architecture](NeuralNetworkArchitecture.png) +Neural networks are powerful because of the **universal approximation theorem**: a single hidden layer with enough neurons can approximate any continuous function on a compact set to arbitrary accuracy. In practice, *depth* (many layers) is more parameter-efficient than width for learning hierarchical features. -The diagram shows the main elements: -1. Input layer receives data -2. Hidden layers perform transformations -3. Output layer produces predictions -4. Forward propagation processes data through the network -5. Loss function compares predictions to targets -6. Backward propagation updates weights +This library provides a minimal, statically-sized neural network framework designed for **embedded inference and on-device training** — no heap allocation, no dynamic shapes, full compile-time dimension checking. -### Neural Network Fundamentals +## Mathematical Theory -A neural network is a computational model inspired by the human brain. For an input vector x, the network computes an output vector y through a series of transformations: +### Forward Propagation -$\mathbf{y} = f_n(\mathbf{W}_n \cdot f_{n-1}(\mathbf{W}_{n-1} \cdot \ldots f_1(\mathbf{W}_1 \cdot \mathbf{x} + \mathbf{b}_1) \ldots + \mathbf{b}_{n-1}) + \mathbf{b}_n)$ +Given $L$ layers, the network computes: -This can be written more clearly as: +$$a_0 = x$$ +$$z_\ell = W_\ell \, a_{\ell-1} + b_\ell, \quad \ell = 1, \ldots, L$$ +$$a_\ell = f_\ell(z_\ell)$$ +$$\hat{y} = a_L$$ -$\mathbf{y} = f_n(\mathbf{z}_n)$ +where $W_\ell \in \mathbb{R}^{n_\ell \times n_{\ell-1}}$ are weights, $b_\ell \in \mathbb{R}^{n_\ell}$ are biases, and $f_\ell$ is the activation function for layer $\ell$. -where: +### Loss Function -$\mathbf{z}_i = \mathbf{W}_i \cdot \mathbf{a}_{i-1} + \mathbf{b}_i$ -$\mathbf{a}_i = f_i(\mathbf{z}_i)$ -$\mathbf{a}_0 = \mathbf{x}$ -``` +Training minimizes a scalar loss $\mathcal{L}(\hat{y}, y)$ that measures how far the prediction $\hat{y}$ is from the target $y$. Common choices: -where: -- W_i are weight matrices -- b_i are bias vectors -- f is an activation function +| Loss | Formula | Use Case | +|------|---------|----------| +| MSE | $\frac{1}{m}\sum(\hat{y}_i - y_i)^2$ | Regression | +| BCE | $-\sum[y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i)]$ | Binary classification | +| CCE | $-\sum y_i \log \hat{y}_i$ | Multi-class classification | -### Training Process +### Backpropagation -Neural networks learn through optimization. The process involves: -``` -1. Forward Propagation: z_i = W_i * a_{i-1} + b_i - a_i = f(z_i) -2. Loss Calculation: L = loss(a_n, y_target) -3. Backward Propagation: dL/dW_i, dL/db_i -4. Weight Update: W_i = W_i - η *dL/dW_i - b_i = b_i - η* dL/db_i -``` +Backpropagation efficiently computes $\nabla_\theta \mathcal{L}$ via the chain rule, working from the output layer backward: -where: -- a_i is the activation at layer i -- z_i is the weighted input at layer i -- η is the learning rate -- L is the loss function - -## Implementation Details - -### Class Structure - -```cpp -template< - typename NumberType, - std::size_t InputSize, - std::size_t OutputSize, - typename Optimizer, - typename LossFunction -> -class NeuralNetwork { -public: - explicit NeuralNetwork( - std::vector>& layers, - Optimizer& optimizer, - LossFunction& loss); - - Vector& Forward(const Vector& input); - void Backward(const Vector& target); - void Train(const DataSet& trainingData, int epochs); -}; -``` +$$\delta_L = \nabla_{a_L}\mathcal{L} \odot f_L'(z_L)$$ +$$\delta_\ell = (W_{\ell+1}^T \delta_{\ell+1}) \odot f_\ell'(z_\ell)$$ + +The gradients with respect to parameters are: + +$$\frac{\partial \mathcal{L}}{\partial W_\ell} = \delta_\ell \, a_{\ell-1}^T, \qquad \frac{\partial \mathcal{L}}{\partial b_\ell} = \delta_\ell$$ + +### Parameter Update + +An optimizer uses the gradients to update the parameter vector $\theta$: + +$$\theta_{t+1} = \theta_t - \eta \, \nabla_\theta \mathcal{L}$$ + +where $\eta$ is the learning rate. More sophisticated optimizers (momentum, Adam) modify this basic rule. + +## Complexity Analysis + +| Phase | Time | Space | +|-------|------|-------| +| Forward pass | $O\!\left(\sum_{\ell=1}^L n_\ell \cdot n_{\ell-1}\right)$ | $O\!\left(\sum n_\ell\right)$ activations | +| Backward pass | Same as forward | Same + gradient storage | +| Parameter update | $O(P)$ | $O(P)$ optimizer state | + +where $P = \sum_\ell (n_\ell \cdot n_{\ell-1} + n_\ell)$ is the total parameter count. For small embedded networks ($P < 10{,}000$), both passes complete in microseconds. + +## Step-by-Step Walkthrough + +**Network:** 2 inputs → 2 hidden (ReLU) → 1 output (Sigmoid). Learning XOR. + +**Architecture:** -### Key Components - -1. [**Layers**](layer/Layer.md) - - Base `Layer` class template with configurable input size, output size, and parameter size - - Derived layer types like `Dense` implementing specific transformations - - Compile-time size verification to ensure proper layer connections - ```cpp - template - class Layer { - public: - // Interface methods for forward/backward pass and parameter management - virtual void Forward(const InputVector& input) = 0; - virtual InputVector& Backward(const OutputVector& output_gradient) = 0; - virtual ParameterVector& Parameters() const = 0; - virtual void SetParameters(const ParameterVector& parameters) = 0; - }; - ``` - -2. [**Activation Functions**](activation/Activation.md): - - Defined as a separate class hierarchy with `Forward` and `Backward` methods - - Applied within layer implementations - - Enable non-linear transformations essential for deep learning - ```cpp - template - class ActivationFunction { - public: - virtual QNumberType Forward(QNumberType x) const = 0; - virtual QNumberType Backward(QNumberType x) const = 0; - }; - ``` - -3. [**Loss Functions**](losses/Loss.md): - - Measure prediction error with `Cost` method - - Provide gradients with respect to parameters via `Gradient` method - - Guide optimization process based on learning objectives - ```cpp - template - class Loss { - public: - virtual QNumberType Cost(const Vector& parameters) = 0; - virtual Vector Gradient(const Vector& parameters) = 0; - }; - ``` - -4. [**Optimizers**](optimizer/Optimizer.md): - - Minimize loss functions by updating parameters - - Return optimized parameters, final cost, and iteration count - - Different algorithms with specialized convergence properties - ```cpp - template - class Optimizer { - public: - struct Result { - Vector parameters; - QNumberType finalCost; - std::size_t iterations; - }; - - virtual const Result& Minimize(const Vector& initialGuess, - Loss& loss) = 0; - }; - ``` - -5. [**Regularization**](regularization/Regularization.md): - - Penalizes model complexity to prevent overfitting - - Common types include L1 (sparsity-inducing) and L2 (weight decay) - - Applied during training as an additional term in the loss function - ```cpp - template - class Regularization { - public: - virtual QNumberType Calculate(const Vector& parameters) const = 0; - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Define network parameters -constexpr std::size_t inputSize = 784; // MNIST input -constexpr std::size_t hiddenSize = 128; // Hidden layer size -constexpr std::size_t outputSize = 10; // 10 digits -using FloatType = float; - -// Create activation functions -ReLU relu; -Softmax softmax; - -// Initialize random weights -std::random_device rd; -std::mt19937 gen(rd()); -std::normal_distribution dist(0.0f, 0.1f); - -math::Matrix weights1; -math::Matrix weights2; -// Fill weights with random values using dist and gen - -// Create layer factory functions -auto layer1 = make_layer>(weights1, relu); -auto layer2 = make_layer>(weights2, softmax); - -// Create neural network model -Model, - Dense -> model(layer1, layer2); - -// Create loss function -MeanSquaredError loss(/* loss parameters */); - -// Create regularization (optional) -L2Regularization regularizer(0.01f); - -// Create optimizer -GradientDescent optimizer; - -// Get initial parameters -auto initialParameters = model.GetParameters(); - -// Train model -model.Train(optimizer, loss, initialParameters); - -// Make predictions -auto testInput = math::Vector{/* test data */}; -auto prediction = model.Forward(testInput); +```mermaid +graph LR + x1((x₁)) --> h1((h₁)) + x1 --> h2((h₂)) + x2((x₂)) --> h1 + x2 --> h2 + h1 --> y((ŷ)) + h2 --> y ``` -### Example: Image Classification - -```cpp -// Create a CNN for image classification -constexpr std::size_t imageWidth = 32; -constexpr std::size_t imageHeight = 32; -constexpr std::size_t channels = 3; // RGB -constexpr std::size_t numClasses = 10; // 10 categories - -// Define network architecture -ConvLayer conv1(ReLU()); -MaxPoolLayer pool1(2); // 2x2 pooling -ConvLayer conv2(ReLU()); -MaxPoolLayer pool2(2); -FlattenLayer flatten; -DenseLayer fc1(ReLU()); -DenseLayer fc2(Softmax()); - -// Combine layers -std::vector> layers = { - conv1, pool1, conv2, pool2, flatten, fc1, fc2 -}; - -// Create optimizer with momentum -Adam optimizer(0.001f, 0.9f, 0.999f); -CrossEntropy loss; - -// Create and train network -NeuralNetwork - network(layers, optimizer, loss); - -network.Train(cifar10TrainingData, 50); +**Epoch 0 — Forward pass** with input $x = [1, 0]^T$, target $y = 1$: + +| Step | Computation | Result | +|------|-------------|--------| +| Hidden pre-activation | $z_1 = W_1 x + b_1$ | $[0.3, -0.1]^T$ | +| Hidden activation | $a_1 = \text{ReLU}(z_1)$ | $[0.3, 0.0]^T$ | +| Output pre-activation | $z_2 = W_2 a_1 + b_2$ | $[0.15]$ | +| Output activation | $\hat{y} = \sigma(z_2)$ | $[0.537]$ | +| Loss | $\mathcal{L} = -(y\log\hat{y} + (1-y)\log(1-\hat{y}))$ | $0.621$ | + +**Epoch 0 — Backward pass:** + +| Step | Computation | Result | +|------|-------------|--------| +| Output gradient | $\delta_2 = \hat{y} - y$ | $[-0.463]$ | +| $\nabla W_2$ | $\delta_2 \cdot a_1^T$ | $[-0.139, 0]$ | +| Hidden gradient | $\delta_1 = W_2^T \delta_2 \odot \text{ReLU}'(z_1)$ | $[-0.231, 0]^T$ | +| $\nabla W_1$ | $\delta_1 \cdot x^T$ | $[[-0.231, 0], [0, 0]]$ | + +**Update:** $W \leftarrow W - 0.1 \cdot \nabla W$. After ~500 epochs, the network correctly classifies all four XOR inputs. + +## Pitfalls & Edge Cases + +- **Vanishing gradients.** Deep networks with Sigmoid or Tanh activations suffer exponential gradient decay. Prefer ReLU-family activations in hidden layers. +- **Exploding gradients.** Large weights amplify gradients exponentially. Use proper weight initialization (Xavier/He) and gradient clipping. +- **Dead neurons.** ReLU neurons that receive only negative inputs output zero forever. LeakyReLU mitigates this. +- **Fixed-point saturation.** In Q15/Q31, activations and gradients must stay within $[-1, 1)$. Scale inputs and learning rates accordingly. +- **Learning rate sensitivity.** Too high → divergence; too low → no progress. Start with $\eta = 0.01$ and adjust. +- **Overfitting.** Small embedded datasets are easily memorized. Apply [regularization](regularization/Regularization.md) (L2 weight decay). + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Convolutional Neural Network (CNN)** | Layers share weights spatially; efficient for image/signal data | +| **Recurrent Neural Network (RNN)** | Layers share weights across time steps; models sequences | +| **Residual Network (ResNet)** | Skip connections mitigate vanishing gradients in very deep networks | +| **Transformer** | Attention-based; no recurrence; state-of-the-art for sequences | +| **Quantized Neural Network** | Weights and activations in low-bit integers; optimal for MCU deployment | + +## Applications + +- **Function approximation** — Learning arbitrary input-output mappings from data. +- **Classification** — Mapping inputs to discrete categories (fault detection, gesture recognition). +- **Regression** — Predicting continuous values (sensor calibration, system identification). +- **Control** — Neural network policies for model-free or model-predictive control on embedded targets. +- **Signal processing** — Learned filters replacing hand-designed FIR/IIR chains. + +## Connections to Other Algorithms + +```mermaid +graph TD + NN["Neural Network"] + Layer["Dense Layer"] + Act["Activation Functions"] + Loss["Loss Functions"] + Opt["Optimizer"] + Reg["Regularization"] + Model["Model"] + LR["Linear Regression"] + + Layer --> NN + Act --> NN + Loss --> NN + Opt --> NN + Reg --> NN + NN --> Model + NN -.->|"single-layer, linear activation, MSE loss"| LR ``` -## Best Practices - -1. **Architecture Design**: - - Start simple and add complexity gradually - - Use appropriate layer types for the data - - Consider computational resources - -2. **Hyperparameter Selection**: - - Learning rate: typically 0.1 to 0.0001 - - Batch size: balance between 32 and 256 - - Layer sizes: problem-dependent - -3. **Training Strategies**: - - Monitor validation metrics - - Implement early stopping - - Use learning rate schedules - - Apply regularization techniques - -4. **Data Preprocessing**: - - Normalize inputs - - Shuffle training data - - Use data augmentation when appropriate - -## Common Applications - -1. **Classification**: - - Image recognition - - Text categorization - - Medical diagnosis - -2. **Regression**: - - Time series prediction - - Value estimation - - Function approximation - -3. **Advanced Tasks**: - - Object detection - - Sequence generation - - Reinforcement learning - -## Performance Considerations - -1. **Computation Efficiency**: - - Use vectorized operations - - Leverage hardware acceleration - - Optimize memory access patterns - -2. **Memory Management**: - - Buffer reuse for activations - - Gradient accumulation for large models - - Mini-batch processing - -3. **Numeric Stability**: - - Use stable activation functions - - Apply gradient clipping - - Monitor for NaN values - -## Forward Propagation in Detail - -Forward propagation is the process of computing the network's output for a given input. In the `Dense` layer implementation, it works as follows: - -1. **Store input** for later use in backward pass: - ```cpp - this->input = input; - ``` - -2. **Compute weighted sum plus bias** for each neuron in the layer: - ```cpp - for (std::size_t i = 0; i < OutputSize; ++i) { - preActivation[i] = biases[i]; - for (std::size_t j = 0; j < InputSize; ++j) - preActivation[i] += weights.at(i, j) * input[j]; - - // Apply activation function - output[i] = activation.Forward(preActivation[i]); - } - ``` - -The output of each layer becomes the input to the next layer, creating a chain of computations from the input layer to the output layer. The `Model::Forward` method implements this chaining by sequentially calling each layer's `Forward` method. - -## Backpropagation in Detail - -Backpropagation computes gradients of the loss with respect to all parameters in the network using the chain rule. For the `Dense` layer: - -1. **Compute gradient with respect to pre-activation values**: - ```cpp - for (std::size_t i = 0; i < OutputSize; ++i) - preActivationGradient[i] = activation.Backward(output_gradient[i]); - ``` - -2. **Compute gradient with respect to input** (for previous layer): - ```cpp - for (std::size_t j = 0; j < InputSize; ++j) { - inputGradient[j] = QNumberType(0.0f); - for (std::size_t i = 0; i < OutputSize; ++i) - inputGradient[j] += weights.at(i, j) * preActivationGradient[i]; - } - ``` - -3. **Compute gradients with respect to weights and biases**: - ```cpp - for (std::size_t i = 0; i < OutputSize; ++i) { - for (std::size_t j = 0; j < InputSize; ++j) - weightGradients.at(i, j) = preActivationGradient[i] * input[j]; - - biasGradients[i] = preActivationGradient[i]; - } - ``` - -The `Model::Backward` method implements the backpropagation through all layers in reverse order, ensuring that gradients flow properly from the output back to the input. - -## Limitations and Future Improvements - -1. Current limitations: - - Fixed architecture after initialization - - Template-based implementation requires compile-time knowledge of dimensions - - Limited to supervised learning - - Single-threaded implementation - - CPU-only processing - - Fixed-size matrices and vectors - -2. Possible extensions: - - Dynamic architecture changes - - Runtime-configurable layer sizes - - Unsupervised learning support - - Distributed training - - GPU acceleration - - Transfer learning capabilities - - Pruning and quantization - - Automatic hyperparameter tuning - - Additional layer types (Convolutional, Recurrent, etc.) - - Advanced optimization techniques - -## Error Handling - -1. Static assertions verify: - - Compatible layer dimensions - - Valid numeric types - - Appropriate activation functions - -2. Runtime checks: - - Input data validity - - Gradient explosion prevention - - Convergence monitoring - - Numerical stability validation +| Component | Relationship | +|-----------|-------------| +| [Dense Layer](layer/Layer.md) | The fundamental building block; computes affine transformations | +| [Activation Functions](activation/Activation.md) | Introduce non-linearity after each layer | +| [Loss Functions](losses/Loss.md) | Define the training objective | +| [Optimizer](optimizer/Optimizer.md) | Drives parameter updates via gradient descent | +| [Regularization](regularization/Regularization.md) | Penalizes complexity to prevent overfitting | +| [Model](model/Model.md) | Composes layers into a trainable pipeline | +| [Linear Regression](../estimators/LinearRegression.md) | Special case: single layer, identity activation, MSE loss | + +## References & Further Reading + +- Goodfellow, I., Bengio, Y., and Courville, A., *Deep Learning*, MIT Press, 2016 — Chapters 6–8. +- He, K. et al., "Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification", *ICCV*, 2015 — He initialization. +- Rumelhart, D.E., Hinton, G.E., and Williams, R.J., "Learning representations by back-propagating errors", *Nature*, 323, 1986. diff --git a/doc/neural_network/README.md b/doc/neural_network/README.md new file mode 100644 index 00000000..10a96e61 --- /dev/null +++ b/doc/neural_network/README.md @@ -0,0 +1,15 @@ +# Neural Network + +Components for building, training, and evaluating feed-forward neural networks entirely on-device with static memory allocation. + +## Components + +| Component | Description | +|-----------|-------------| +| [Neural Network Overview](NeuralNetwork.md) | Architecture, training loop, and how the components fit together | +| [Layers](layer/Layer.md) | Dense (fully connected) layer with forward and backward pass | +| [Activation Functions](activation/Activation.md) | Non-linear element-wise transforms: ReLU, LeakyReLU, Sigmoid, Tanh, Softmax | +| [Loss Functions](losses/Loss.md) | Objective functions: MSE, MAE, Binary Cross-Entropy, Categorical Cross-Entropy | +| [Optimizers](optimizer/Optimizer.md) | Parameter update strategies: Gradient Descent | +| [Regularization](regularization/Regularization.md) | Complexity penalties: L1 (Lasso) and L2 (Ridge) | +| [Model](model/Model.md) | Variadic-template model composing layers, optimizer, and loss into a trainable pipeline | diff --git a/doc/neural_network/activation/Activation.md b/doc/neural_network/activation/Activation.md index 581d40d8..43731079 100644 --- a/doc/neural_network/activation/Activation.md +++ b/doc/neural_network/activation/Activation.md @@ -1,267 +1,149 @@ -# Activation Functions Implementation Guide +# Activation Functions -## Process Overview +## Overview & Motivation -The following diagram illustrates the role of activation functions in a neural network: +An activation function $f$ is a non-linear, element-wise transformation applied after the affine map in each neural network layer: -![Activation Functions](ActivationFunctions.svg) +$$a = f(z) = f(W x + b)$$ -The diagram shows how activation functions: -1. Transform linear outputs into non-linear representations -2. Enable the network to learn complex patterns -3. Control signal flow and introduce non-linearity -4. Have unique characteristics that affect gradient flow +Without activation functions, stacking layers would collapse into a single affine transformation — the network could only represent linear mappings regardless of depth. Activation functions are what give neural networks their expressive power. -## Mathematical Background +The choice of activation function controls **gradient flow** during back-propagation, **output range**, and **computational cost** — all critical on resource-constrained embedded targets. -### Activation Function Role +## Mathematical Theory -Activation functions introduce non-linearity into neural networks. Without them, a neural network would be equivalent to a single linear transformation, regardless of its depth. For a neuron with weighted input z, the activation function f transforms this input: +### Forward and Backward -$$a = f(z) = f(w \cdot x + b)$$ +Every activation function exposes two operations: -where: -- z is the weighted input (w · x + b) -- f is the activation function -- a is the neuron's output +| Operation | Definition | Purpose | +|-----------|-----------|---------| +| **Forward** | $a = f(z)$ | Transform the pre-activation | +| **Backward** | $f'(z)$ | Provide the local derivative for back-propagation | -### Derivatives for Backpropagation +The chain rule connects them during training: -During backpropagation, the derivative of the activation function is crucial for computing gradients. If we denote the loss as L, then: +$$\frac{\partial \mathcal{L}}{\partial z} = \frac{\partial \mathcal{L}}{\partial a} \cdot f'(z)$$ -$$\frac{\partial L}{\partial z} = \frac{\partial L}{\partial a} \cdot \frac{\partial a}{\partial z} = \frac{\partial L}{\partial a} \cdot f'(z)$$ +### Catalogue -This is why each activation function provides both `Forward` and `Backward` methods in the implementation. +#### ReLU (Rectified Linear Unit) -## Implementation Details +$$f(z) = \max(0, z), \qquad f'(z) = \begin{cases} 1 & z > 0 \\ 0 & z \le 0 \end{cases}$$ -### Class Structure +- Computationally cheapest (single comparison). +- Sparse activations accelerate training. +- **Risk:** neurons with $z \le 0$ for all inputs are permanently dead. -```cpp -template -class ActivationFunction -{ - static_assert(math::is_qnumber::value || std::is_floating_point::value, - "ActivationFunction can only be instantiated with math::QNumber types."); +#### Leaky ReLU -public: - virtual QNumberType Forward(QNumberType x) const = 0; - virtual QNumberType Backward(QNumberType x) const = 0; -}; -``` +$$f(z) = \begin{cases} z & z > 0 \\ \alpha z & z \le 0 \end{cases}, \qquad f'(z) = \begin{cases} 1 & z > 0 \\ \alpha & z \le 0 \end{cases}$$ + +where $\alpha$ is a small positive constant (typically $0.01$). Prevents dead neurons by allowing a small gradient for $z < 0$. + +#### Sigmoid + +$$f(z) = \frac{1}{1 + e^{-z}}, \qquad f'(z) = f(z)(1 - f(z))$$ + +- Output range $(0, 1)$ — natural for probabilities. +- **Risk:** saturates for $|z| \gg 0$, causing vanishing gradients. + +#### Tanh (Hyperbolic Tangent) + +$$f(z) = \tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}}, \qquad f'(z) = 1 - f(z)^2$$ + +- Output range $(-1, 1)$ — zero-centered, unlike Sigmoid. +- Same saturation problem as Sigmoid at extremes. + +#### Softmax + +For a vector $\mathbf{z} \in \mathbb{R}^k$: + +$$f(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{k} e^{z_j}}$$ + +- Outputs form a probability distribution ($\sum f(z_i) = 1$). +- Used exclusively at the output layer for multi-class classification. +- The Jacobian is a full $k \times k$ matrix — more expensive than element-wise activations. + +## Complexity Analysis + +| Activation | Forward (per element) | Backward (per element) | Notes | +|-----------|----------------------|----------------------|-------| +| ReLU | $O(1)$ — comparison | $O(1)$ — comparison | Fastest | +| Leaky ReLU | $O(1)$ — comparison + multiply | $O(1)$ | Negligible overhead vs ReLU | +| Sigmoid | $O(1)$ — exp + divide | $O(1)$ — reuse forward result | Requires `exp()` | +| Tanh | $O(1)$ — exp (twice) | $O(1)$ — reuse forward result | Requires `exp()` | +| Softmax | $O(k)$ — vector exp + sum | $O(k^2)$ — full Jacobian | Significantly more expensive | + +## Step-by-Step Walkthrough -### Key Implementations - -1. **ReLU (Rectified Linear Unit)**: - - Simple, efficient activation function - - Mitigates vanishing gradient problem - - May cause "dying neurons" with zero gradients - ```cpp - template - class ReLU : public ActivationFunction - { - public: - QNumberType Forward(QNumberType x) const override - { - return x > QNumberType(0.0f) ? x : QNumberType(0.0f); - } - - QNumberType Backward(QNumberType x) const override - { - return x > QNumberType(0.0f) ? QNumberType(0.9999f) : QNumberType(0.0f); - } - }; - ``` - -2. **LeakyReLU**: - - Addresses the "dying neuron" problem of ReLU - - Small positive slope for negative inputs - - Parameterized by alpha (leak coefficient) - ```cpp - template - class LeakyReLU : public ActivationFunction - { - public: - explicit LeakyReLU(QNumberType alpha = QNumberType(0.01f)) - : alpha(alpha) - {} - - QNumberType Forward(QNumberType x) const override - { - return x > QNumberType(0.0f) ? x : alpha * x; - } - - QNumberType Backward(QNumberType x) const override - { - return x > QNumberType(0.0f) ? QNumberType(0.9999f) : alpha; - } - - private: - QNumberType alpha; - }; - ``` - -3. **Sigmoid**: - - Squashes inputs to range (0, 1) - - Historically common but prone to vanishing gradients - - Useful for binary classification output nodes - ```cpp - template - class Sigmoid : public ActivationFunction - { - public: - QNumberType Forward(QNumberType x) const override - { - return QNumberType(1.0f / (1.0f + std::exp(-math::ToFloat(x)))); - } - - QNumberType Backward(QNumberType x) const override - { - QNumberType y = Forward(x); - return y * (QNumberType(0.9999f) - y); - } - }; - ``` - -4. **Tanh (Hyperbolic Tangent)**: - - Squashes inputs to range (-1, 1) - - Zero-centered output, unlike Sigmoid - - Still vulnerable to vanishing gradients at extremes - ```cpp - template - class Tanh : public ActivationFunction - { - public: - QNumberType Forward(QNumberType x) const override - { - return QNumberType(std::tanh(math::ToFloat(x))); - } - - QNumberType Backward(QNumberType x) const override - { - QNumberType y = Forward(x); - return QNumberType(0.9999f) - y * y; - } - }; - ``` - -5. **Softmax**: - - Converts vector of real numbers to probability distribution - - Typically used for multi-class classification output - - Note: Current implementation is per-element; in practice, should be applied to vectors - ```cpp - template - class Softmax : public ActivationFunction - { - public: - QNumberType Forward(QNumberType x) const override - { - return QNumberType(std::exp(math::ToFloat(x))); - } - - QNumberType Backward(QNumberType x) const override - { - QNumberType y = Forward(x); - return y * (QNumberType(0.9999f) - y); - } - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Create activation functions -ReLU relu; -LeakyReLU leakyRelu(0.1f); -Sigmoid sigmoid; -Tanh tanh; -Softmax softmax; - -// Apply to a single value -float x = -1.5f; -float activated_relu = relu.Forward(x); // 0.0 -float activated_leaky = leakyRelu.Forward(x); // -0.15 -float activated_sig = sigmoid.Forward(x); // 0.182 -float activated_tanh = tanh.Forward(x); // -0.905 -float activated_soft = softmax.Forward(x); // 0.223 - -// For backpropagation -float grad_relu = relu.Backward(x); // 0.0 -float grad_leaky = leakyRelu.Backward(x); // 0.1 -float grad_sig = sigmoid.Backward(x); // 0.149 -float grad_tanh = tanh.Backward(x); // 0.181 -float grad_soft = softmax.Backward(x); // 0.174 +**Scenario:** Forward and backward pass through a 3-neuron hidden layer with ReLU, given pre-activations $z = [-0.5, \; 1.2, \; 0.0]$. + +**Forward:** + +| Neuron | $z$ | $\text{ReLU}(z)$ | +|--------|------|-------------------| +| 1 | $-0.5$ | $0.0$ | +| 2 | $1.2$ | $1.2$ | +| 3 | $0.0$ | $0.0$ | + +**Backward** with incoming gradient $\frac{\partial \mathcal{L}}{\partial a} = [0.3, \; -0.7, \; 0.1]$: + +| Neuron | $f'(z)$ | $\frac{\partial \mathcal{L}}{\partial z}$ | +|--------|---------|---------------------------| +| 1 | $0$ (dead) | $0.3 \times 0 = 0$ | +| 2 | $1$ | $-0.7 \times 1 = -0.7$ | +| 3 | $0$ (at boundary) | $0.1 \times 0 = 0$ | + +Neuron 1 is *dead* — its gradient is zero and its weights will not update. If this persists across all training samples, the neuron is permanently inactive. + +## Pitfalls & Edge Cases + +- **Vanishing gradients with Sigmoid/Tanh.** For deep networks, gradients shrink exponentially through saturated activations. Use ReLU or Leaky ReLU in hidden layers. +- **Dead ReLU neurons.** If a neuron's bias drifts negative enough that no input ever produces $z > 0$, it stops learning. Leaky ReLU or careful initialization (He init) prevents this. +- **Softmax numerical instability.** Computing $e^{z_i}$ directly overflows for large $z_i$. Subtract $\max(\mathbf{z})$ before exponentiation: $f(z_i) = e^{z_i - z_{\max}} / \sum e^{z_j - z_{\max}}$. +- **Fixed-point range.** Sigmoid outputs $(0, 1)$ and Tanh outputs $(-1, 1)$ both fit in Q15/Q31, but the exponential intermediate values do not. Compute in floating-point and convert. +- **Non-differentiable points.** ReLU is technically non-differentiable at $z = 0$. In practice, assigning $f'(0) = 0$ works fine. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **PReLU (Parametric ReLU)** | $\alpha$ is a learnable parameter per channel | +| **ELU (Exponential LU)** | $\alpha(e^z - 1)$ for $z < 0$; smooth and zero-centered | +| **GELU (Gaussian Error LU)** | $z \cdot \Phi(z)$; used in Transformers | +| **Swish / SiLU** | $z \cdot \sigma(z)$; smooth, non-monotonic | +| **Hard Sigmoid / Hard Tanh** | Piece-wise linear approximations; no transcendentals | + +## Applications + +- **Hidden layers** — ReLU (or Leaky ReLU) is the default choice for feed-forward and convolutional hidden layers. +- **Binary classification output** — Sigmoid maps the output to a probability. +- **Multi-class classification output** — Softmax produces a probability distribution. +- **Recurrent networks** — Tanh is traditionally used in LSTM/GRU gates. +- **Embedded inference** — Hard Sigmoid/Tanh avoid expensive `exp()` calls on MCUs without FPU. + +## Connections to Other Algorithms + +```mermaid +graph TD + Act["Activation Functions"] + Layer["Dense Layer"] + NN["Neural Network"] + Loss["Loss Functions"] + Act --> Layer + Layer --> NN + NN --> Loss ``` -## Best Practices - -1. **Activation Function Selection**: - - Use ReLU as a default for hidden layers (fast, efficient) - - Consider LeakyReLU for deep networks (prevents dying neurons) - - Use Sigmoid for binary classification output layer - - Use Softmax for multi-class classification output layer - - Use Tanh when zero-centered outputs are beneficial - -2. **Implementation Considerations**: - - Ensure numerical stability with capping/checks - - Note that current Backward implementation uses x not y in most cases - - Consider performance vs. accuracy trade-offs - -3. **Potential Issues**: - - Vanishing gradients with Sigmoid/Tanh in deep networks - - Dead neurons with ReLU (no gradient for negative inputs) - - Softmax implementation requires vector-level operation in practice - -## Common Activation Functions Comparison - -| Function | Range | Advantages | Disadvantages | -|-----------|---------|----------------------------------|----------------------------------| -| ReLU | [0, ∞) | Fast, reduces vanishing gradient | Dead neurons | -| LeakyReLU | (-∞, ∞) | Prevents dead neurons | Additional hyperparameter | -| Sigmoid | (0, 1) | Smooth, bounded output | Vanishing gradient, not centered | -| Tanh | (-1, 1) | Zero-centered | Vanishing gradient at extremes | -| Softmax | (0, 1) | Probability distribution | Computationally expensive | - -## Performance Considerations - -1. **Computation Efficiency**: - - ReLU and LeakyReLU are fastest (simple comparisons) - - Sigmoid, Tanh, and Softmax use expensive exponential operations - - Consider lookup tables for fixed-point implementations - -2. **Numeric Stability**: - - Prevent overflow in exponential functions - - Note the 0.9999f cap in gradient calculations - - Consider range limitations for activation functions - -3. **Memory Usage**: - - Most activation functions are stateless (except LeakyReLU's alpha) - - Minimal memory footprint - -## Limitations and Future Improvements - -1. Current limitations: - - Element-wise application (especially for Softmax) - - Fixed implementation of derivatives - - Limited to scalar operations - -2. Possible extensions: - - Vector-level activation functions - - Additional functions (PReLU, ELU, GELU, Swish) - - Optimized implementations for specific hardware - - Adjustable parameters during training - - Self-normalizing activation functions - - Activation functions with memory (e.g., for recurrent networks) - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Appropriate floating-point conversions - -2. Implementation considerations: - - Clamping gradients to prevent explosion - - Ensuring numerical stability in exponential functions - - Special handling for extreme input values +| Component | Relationship | +|-----------|-------------| +| [Dense Layer](../layer/Layer.md) | Applies the activation function after the affine transformation | +| [Neural Network](../NeuralNetwork.md) | Activations enable the non-linear function approximation that makes deep networks useful | +| [Loss Functions](../losses/Loss.md) | The output activation must match the loss: Sigmoid + BCE, Softmax + CCE | + +## References & Further Reading + +- Nair, V. and Hinton, G.E., "Rectified linear units improve restricted Boltzmann machines", *ICML*, 2010. +- Glorot, X., Bordes, A., and Bengio, Y., "Deep sparse rectifier neural networks", *AISTATS*, 2011. +- Clevert, D.-A., Unterthiner, T., and Hochreiter, S., "Fast and accurate deep network learning by exponential linear units (ELUs)", *ICLR*, 2016. diff --git a/doc/neural_network/layer/Layer.md b/doc/neural_network/layer/Layer.md index a7962cac..87160c19 100644 --- a/doc/neural_network/layer/Layer.md +++ b/doc/neural_network/layer/Layer.md @@ -1,350 +1,127 @@ -# Layer Implementation Guide +# Dense Layer -## Process Overview +## Overview & Motivation -The following diagram illustrates the structure and data flow of neural network layers: +A **dense** (fully-connected) layer is the most fundamental building block of a neural network. It maps an input vector $a_{\text{in}} \in \mathbb{R}^n$ to an output vector $a_{\text{out}} \in \mathbb{R}^m$ through a learnable affine transformation followed by a non-linear activation: -![Neural Network Layers](Layers.svg) +$$a_{\text{out}} = f(W \, a_{\text{in}} + b)$$ -The diagram shows how layers: -1. Transform input data through linear and non-linear operations -2. Process signals during forward and backward passes -3. Store and update parameters (weights and biases) -4. Connect to form the complete neural network architecture +Every input neuron is connected to every output neuron — hence "fully connected." The layer's **parameters** are the weight matrix $W$ and bias vector $b$; training adjusts these to minimize the loss. -## Mathematical Background +In this library, input size, output size, and parameter count are all **compile-time constants**, enabling stack allocation and dimension checking with zero runtime overhead. -### Layer Operations +## Mathematical Theory -Each layer in a neural network applies a transformation to its input. For a fully connected (dense) layer with input vector x, the output vector y is computed as: +### Forward Pass -$$\mathbf{y} = f(\mathbf{W}\mathbf{x} + \mathbf{b})$$ +$$z = W \, a_{\text{in}} + b, \qquad a_{\text{out}} = f(z)$$ -where: -- W is the weight matrix -- b is the bias vector -- f is the activation function +where $W \in \mathbb{R}^{m \times n}$, $b \in \mathbb{R}^m$, and $f$ is the [activation function](../activation/Activation.md). -### Backpropagation Through Layers +### Backward Pass -During backpropagation, each layer computes: -1. Gradient with respect to its input (for previous layer) -2. Gradients with respect to its parameters (for optimization) +Given the gradient of the loss with respect to the output $\frac{\partial \mathcal{L}}{\partial a_{\text{out}}}$: -For a dense layer, these are: +1. **Pre-activation gradient:** +$$\delta = \frac{\partial \mathcal{L}}{\partial a_{\text{out}}} \odot f'(z)$$ -$$\frac{\partial L}{\partial \mathbf{x}} = \mathbf{W}^T \frac{\partial L}{\partial \mathbf{z}}$$ +2. **Weight gradient:** +$$\frac{\partial \mathcal{L}}{\partial W} = \delta \, a_{\text{in}}^T$$ -$$\frac{\partial L}{\partial \mathbf{W}} = \frac{\partial L}{\partial \mathbf{z}} \mathbf{x}^T$$ +3. **Bias gradient:** +$$\frac{\partial \mathcal{L}}{\partial b} = \delta$$ -$$\frac{\partial L}{\partial \mathbf{b}} = \frac{\partial L}{\partial \mathbf{z}}$$ +4. **Input gradient** (propagated to the previous layer): +$$\frac{\partial \mathcal{L}}{\partial a_{\text{in}}} = W^T \delta$$ -where: -- L is the loss function -- z = Wx + b is the pre-activation output -- ∂L/∂z is the gradient of the loss with respect to the pre-activation output +### Parameter Count -## Implementation Details +$$P = m \times n + m = m(n + 1)$$ -### Class Structure +For a layer with 128 inputs and 64 outputs: $P = 64 \times 129 = 8{,}256$ parameters. -```cpp -template -class Layer -{ -public: - using InputVector = math::Matrix; - using OutputVector = math::Matrix; - using ParameterVector = math::Matrix; +## Complexity Analysis - static constexpr std::size_t InputSize = InputSize_; - static constexpr std::size_t OutputSize = OutputSize_; - static constexpr std::size_t ParameterSize = ParameterSize_; +| Operation | Time | Space | +|-----------|------|-------| +| Forward ($W a + b$) | $O(m \cdot n)$ | $O(m)$ output + $O(m)$ cached $z$ | +| Backward ($\delta$, $\nabla W$, $\nabla b$) | $O(m \cdot n)$ | $O(m \cdot n)$ weight gradient | +| Total parameters | — | $O(m \cdot n + m)$ | - virtual void Forward(const InputVector& input) = 0; - virtual InputVector& Backward(const OutputVector& output_gradient) = 0; - virtual ParameterVector& Parameters() const = 0; - virtual void SetParameters(const ParameterVector& parameters) = 0; -}; -``` +The matrix-vector product dominates both passes. For embedded networks (e.g. $n = 32, m = 16$), a single forward pass takes ~512 multiply-accumulate operations. -### Key Implementations - -1. **Dense Layer**: - - Fully connected layer with weights, biases, and activation function - - Linear transformation followed by non-linear activation - - Parameters include weights and biases - **Mathematical Forward Pass:** - $$\mathbf{z} = \mathbf{W}\mathbf{x} + \mathbf{b}$$ - $$\mathbf{a} = f(\mathbf{z})$$ - **Mathematical Backward Pass:** - $$\frac{\partial L}{\partial \mathbf{z}} = \frac{\partial L}{\partial \mathbf{a}} \odot f'(\mathbf{z})$$ - $$\frac{\partial L}{\partial \mathbf{W}_{i,j}} = \frac{\partial L}{\partial \mathbf{z}_i} \cdot \mathbf{x}_j$$ - $$\frac{\partial L}{\partial \mathbf{b}_i} = \frac{\partial L}{\partial \mathbf{z}_i}$$ - $$\frac{\partial L}{\partial \mathbf{x}_j} = \sum_{i} \mathbf{W}_{i,j} \cdot \frac{\partial L}{\partial \mathbf{z}_i}$$ - ```cpp - template - class Dense : public Layer - { - public: - Dense(const math::Matrix& initialWeights, - ActivationFunction& activation); - - void Forward(const InputVector& input) override - { - this->input = input; - - for (std::size_t i = 0; i < OutputSize; ++i) - { - preActivation[i] = biases[i]; - for (std::size_t j = 0; j < InputSize; ++j) - preActivation[i] += weights.at(i, j) * input[j]; - - output[i] = activation.Forward(preActivation[i]); - } - } - - InputVector& Backward(const OutputVector& output_gradient) override - { - OutputVector preActivationGradient; - - // Compute gradient with respect to pre-activation - for (std::size_t i = 0; i < OutputSize; ++i) - preActivationGradient[i] = activation.Backward(output_gradient[i]); - - // Compute gradient with respect to input (for previous layer) - for (std::size_t j = 0; j < InputSize; ++j) - { - inputGradient[j] = QNumberType(0.0f); - for (std::size_t i = 0; i < OutputSize; ++i) - inputGradient[j] += weights.at(i, j) * preActivationGradient[i]; - } - - // Compute gradients with respect to weights and biases - for (std::size_t i = 0; i < OutputSize; ++i) - { - for (std::size_t j = 0; j < InputSize; ++j) - weightGradients.at(i, j) = preActivationGradient[i] * input[j]; - - biasGradients[i] = preActivationGradient[i]; - } - - return inputGradient; - } - - ParameterVector& Parameters() const override - { - std::size_t idx = 0; - - // Flatten weights into parameter vector - for (std::size_t i = 0; i < OutputSize; ++i) - for (std::size_t j = 0; j < InputSize; ++j) - parameters[idx++] = weights.at(i, j); - - // Add biases to parameter vector - for (std::size_t i = 0; i < OutputSize; ++i) - parameters[idx++] = biases[i]; - - return parameters; - } - - void SetParameters(const ParameterVector& parameters) override - { - std::size_t idx = 0; - - // Extract weights from parameter vector - for (std::size_t i = 0; i < OutputSize; ++i) - for (std::size_t j = 0; j < InputSize; ++j) - weights.at(i, j) = parameters[idx++]; - - // Extract biases from parameter vector - for (std::size_t i = 0; i < OutputSize; ++i) - biases[i] = parameters[idx++]; - } - - private: - ActivationFunction& activation; - math::Matrix weights; - math::Vector biases; - - InputVector input; - OutputVector preActivation; - OutputVector output; - - math::Matrix weightGradients; - math::Vector biasGradients; - - mutable ParameterVector parameters; - InputVector inputGradient; - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Define layer dimensions -constexpr std::size_t inputSize = 784; // MNIST input -constexpr std::size_t hiddenSize = 128; // Hidden layer size -using FloatType = float; - -// Create activation function -ReLU relu; - -// Initialize weights -math::Matrix weights; -// Fill weights with random values... - -// Create dense layer -Dense layer(weights, relu); - -// Create input vector -math::Vector input; -// Fill input with data... - -// Forward pass -layer.Forward(input); - -// Backward pass with output gradient -math::Vector outputGradient; -// Fill output gradient... -auto& inputGradient = layer.Backward(outputGradient); - -// Get layer parameters -auto& parameters = layer.Parameters(); - -// Set layer parameters -layer.SetParameters(newParameters); -``` +## Step-by-Step Walkthrough -### Integration with Model +**Layer:** 3 inputs → 2 outputs, ReLU activation. -```cpp -// Create activation functions -ReLU relu; -Softmax softmax; +$$W = \begin{bmatrix} 0.5 & -0.3 & 0.8 \\ 0.1 & 0.7 & -0.2 \end{bmatrix}, \quad b = \begin{bmatrix} 0.1 \\ -0.1 \end{bmatrix}, \quad a_{\text{in}} = \begin{bmatrix} 1.0 \\ 0.5 \\ -1.0 \end{bmatrix}$$ -// Initialize random weights -math::Matrix weights1; -math::Matrix weights2; -// Fill weights with random values... +**Forward:** -// Create layer factory functions -auto layer1 = make_layer>(weights1, relu); -auto layer2 = make_layer>(weights2, softmax); +| Step | Computation | Result | +|------|-------------|--------| +| $z = W a_{\text{in}} + b$ | $[0.5 - 0.15 - 0.8 + 0.1,\; 0.1 + 0.35 + 0.2 - 0.1]$ | $[-0.35,\; 0.55]^T$ | +| $a_{\text{out}} = \text{ReLU}(z)$ | $[\max(0, -0.35),\; \max(0, 0.55)]$ | $[0.0,\; 0.55]^T$ | -// Create model with layers -Model, - Dense -> model(layer1, layer2); -``` +**Backward** with $\frac{\partial \mathcal{L}}{\partial a_{\text{out}}} = [0.2,\; -0.4]^T$: + +| Step | Computation | Result | +|------|-------------|--------| +| $\delta = \nabla a_{\text{out}} \odot \text{ReLU}'(z)$ | $[0.2 \cdot 0,\; -0.4 \cdot 1]$ | $[0,\; -0.4]^T$ | +| $\nabla W = \delta \, a_{\text{in}}^T$ | row 1: all zeros; row 2: $-0.4 \times [1, 0.5, -1]$ | $\begin{bmatrix}0 & 0 & 0\\-0.4 & -0.2 & 0.4\end{bmatrix}$ | +| $\nabla b = \delta$ | — | $[0,\; -0.4]^T$ | +| $\nabla a_{\text{in}} = W^T \delta$ | $W^T [0, -0.4]^T$ | $[-0.04,\; -0.28,\; 0.08]^T$ | + +## Pitfalls & Edge Cases + +- **Dimension mismatch.** In a multi-layer network, the output size of layer $\ell$ must equal the input size of layer $\ell+1$. This library enforces this at compile time. +- **Weight initialization.** Zero-initialized weights cause all neurons to compute the same thing (symmetry problem). Use He initialization for ReLU: $W_{ij} \sim \mathcal{N}(0, \sqrt{2/n})$. +- **Gradient accumulation.** When processing mini-batches, accumulate $\nabla W$ across samples before updating — do not update per-sample. +- **Fixed-point overflow in $W a$.** The dot product of $n$ terms can exceed Q15/Q31 range. Use a wider accumulator (Q31 for Q15 data) or scale weights. +- **Large layers exhaust stack.** A 256×256 weight matrix of `float` consumes 256 KB. Size layers to fit the target's stack budget. -### Parameter Management +## Variants & Generalizations -```cpp -// Get total parameter count -constexpr std::size_t totalParams = Dense::ParameterSize; -// = (inputSize * hiddenSize) + hiddenSize +| Variant | Key Difference | +|---------|---------------| +| **Convolutional layer** | Weight sharing across spatial positions; $O(k^2 \cdot c)$ parameters per filter instead of $O(n \cdot m)$ | +| **Recurrent layer** | Shares weights across time steps; adds a hidden state feedback connection | +| **Batch normalization layer** | Normalizes activations to zero mean and unit variance; accelerates training | +| **Dropout layer** | Randomly zeros activations during training; regularization effect | +| **Sparse layer** | Only a subset of connections exist; reduces parameter count and computation | -// Access parameters from layer -auto layerParams = layer.Parameters(); +## Applications -// Update parameters after optimization -Vector optimizedParams; -// Fill optimizedParams... -layer.SetParameters(optimizedParams); +- **Hidden layers** — One or more dense layers form the core of feed-forward networks for regression and classification. +- **Output layer** — A final dense layer maps to the target dimensionality (1 for regression, $k$ for $k$-class classification). +- **Embedding projection** — Dense layers project high-dimensional sparse inputs to low-dimensional dense representations. +- **Controller networks** — In neural network-based control, small dense layers map state vectors to actuator commands. + +## Connections to Other Algorithms + +```mermaid +graph TD + Layer["Dense Layer"] + Act["Activation Functions"] + Model["Model"] + Opt["Optimizer"] + LR["Linear Regression"] + + Act --> Layer + Layer --> Model + Model --> Opt + Layer -.->|"no activation, MSE loss"| LR ``` -## Layer Types - -1. **Dense (Fully Connected)**: - - Connects every input neuron to every output neuron - - Parameters: weights (input × output) + biases (output) - - Computation complexity: O(input × output) - -2. **Other Common Layer Types** (not implemented in provided code): - - **Convolutional**: Applies filters to detect spatial patterns - - **Pooling**: Reduces spatial dimensions through downsampling - - **Recurrent**: Processes sequential data with memory - - **Normalization**: Stabilizes and accelerates training - - **Dropout**: Randomly deactivates neurons during training for regularization - -## Best Practices - -1. **Initialization**: - - Use proper weight initialization based on layer size and activation - - Xavier/Glorot for tanh/sigmoid: variance ~ 1/n - - He initialization for ReLU: variance ~ 2/n - - Small random values for biases (often initialized to zero) - -2. **Architecture Design**: - - Layer sizes should gradually decrease for classification - - Common patterns: [n → n/2 → n/4 → ... → output_classes] - - Maintain sufficient capacity for the problem complexity - -3. **Training Considerations**: - - Different layers may require different learning rates - - Deeper layers tend to need smaller updates - - Monitor activations and gradients for proper signal flow - -## Performance Considerations - -1. **Computation Efficiency**: - - Dense layers are matrix-vector multiplications - - Consider vectorized operations for better performance - - Parameter count scales with input × output - -2. **Memory Usage**: - - Each layer stores weights, biases, and intermediate activations - - Total memory: O(input × output) for weights + O(output) for activations - - Consider storage for gradients during backpropagation - -3. **Numeric Stability**: - - Watch for exploding/vanishing gradients in deep networks - - Consider normalization between layers for stability - - Use stable activation functions for deeper networks - -## Parameter Sizing - -Dense layer parameter count calculation: -- Weights: InputSize × OutputSize -- Biases: OutputSize -- Total: (InputSize × OutputSize) + OutputSize - -Example parameter counts: -- Dense(784 → 128): (784 × 128) + 128 = 100,480 parameters -- Dense(128 → 64): (128 × 64) + 64 = 8,256 parameters -- Dense(64 → 10): (64 × 10) + 10 = 650 parameters - -## Limitations and Future Improvements - -1. Current limitations: - - Only Dense layer implemented - - Fixed-size matrices and vectors - - Manual parameter packing/unpacking - - Element-wise operations (not vectorized) - - Limited to compile-time dimensions - -2. Possible extensions: - - Additional layer types (Convolutional, Pooling, Recurrent) - - Runtime-configurable dimensions - - Parameter initialization methods - - Weight constraints and regularization - - Batch processing - - Vectorized operations - - Better memory management - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Proper template parameter sizes - - Compatible layer dimensions - -2. Implementation considerations: - - Parameter size validation - - Input/output dimension checking - - Gradient storage and propagation - - Numeric stability in operations +| Component | Relationship | +|-----------|-------------| +| [Activation Functions](../activation/Activation.md) | Applied element-wise after the affine transformation | +| [Model](../model/Model.md) | Chains multiple dense layers into a network | +| [Optimizer](../optimizer/Optimizer.md) | Updates $W$ and $b$ using the computed gradients | +| [Linear Regression](../../estimators/LinearRegression.md) | A dense layer with identity activation and MSE loss is equivalent to linear regression | + +## References & Further Reading + +- Goodfellow, I., Bengio, Y., and Courville, A., *Deep Learning*, MIT Press, 2016 — Chapter 6. +- He, K. et al., "Delving deep into rectifiers", *ICCV*, 2015 — He weight initialization. +- Glorot, X. and Bengio, Y., "Understanding the difficulty of training deep feedforward neural networks", *AISTATS*, 2010 — Xavier initialization. diff --git a/doc/neural_network/losses/Loss.md b/doc/neural_network/losses/Loss.md index 4e73f622..c13bc3f1 100644 --- a/doc/neural_network/losses/Loss.md +++ b/doc/neural_network/losses/Loss.md @@ -1,429 +1,139 @@ -# Loss Functions Implementation Guide +# Loss Functions -## Process Overview +## Overview & Motivation -The following diagram illustrates the role of loss functions in a neural network: +A loss function $\mathcal{L}(\hat{y}, y)$ quantifies how far a model's prediction $\hat{y}$ is from the true target $y$. Training a neural network means finding parameters $\theta$ that minimize the expected loss over the training data: -![Loss Functions](LossFunctions.svg) +$$\theta^* = \arg\min_\theta \; \mathbb{E}[\mathcal{L}(f_\theta(x), y)]$$ -The diagram shows how loss functions: -1. Measure the discrepancy between predictions and target values -2. Guide the optimization process during training -3. Generate gradients for backpropagation -4. Vary based on different problem types (regression, classification) +The loss function defines the **entire learning objective** — different losses lead to different optimal models even on the same data. It must also provide a **gradient** $\nabla_{\hat{y}} \mathcal{L}$ for back-propagation. -## Mathematical Background +## Mathematical Theory -### Loss Function Role +### Mean Squared Error (MSE) -Loss functions quantify how well a model's predictions match the expected targets. For a model with parameters θ, input x, and expected output y, the loss function L defines the error: +$$\mathcal{L}_{\text{MSE}} = \frac{1}{m} \sum_{i=1}^{m} (\hat{y}_i - y_i)^2$$ -$$L(θ) = f(y, \hat{y})$$ +$$\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = \frac{2}{m}(\hat{y}_i - y_i)$$ -where: -- θ represents all model parameters -- y is the target output -- ŷ (y-hat) is the model's prediction +- Penalizes large errors quadratically → sensitive to outliers. +- Natural choice for **regression** tasks. +- Optimal when the error distribution is Gaussian. -### Gradient for Optimization +### Mean Absolute Error (MAE) -During training, the gradient of the loss with respect to model parameters is needed: +$$\mathcal{L}_{\text{MAE}} = \frac{1}{m} \sum_{i=1}^{m} |\hat{y}_i - y_i|$$ -$$\nabla_θ L(θ) = \frac{\partial L}{\partial θ}$$ +$$\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = \frac{1}{m} \operatorname{sign}(\hat{y}_i - y_i)$$ -This gradient tells the optimization algorithm which direction to adjust parameters to minimize the loss. +- Linear penalty → robust to outliers. +- Non-differentiable at $\hat{y}_i = y_i$ (use sub-gradient in practice). -## Implementation Details +### Binary Cross-Entropy (BCE) -### Class Structure +$$\mathcal{L}_{\text{BCE}} = -\frac{1}{m}\sum_{i=1}^{m} \left[ y_i \log \hat{y}_i + (1 - y_i) \log(1 - \hat{y}_i) \right]$$ -```cpp -template -class Loss -{ - static_assert(math::is_qnumber::value || std::is_floating_point::value, - "Loss can only be instantiated with math::QNumber types."); +$$\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = -\frac{1}{m}\left(\frac{y_i}{\hat{y}_i} - \frac{1 - y_i}{1 - \hat{y}_i}\right)$$ -public: - using Vector = math::Vector; +- Assumes $\hat{y}_i \in (0, 1)$ — pair with **Sigmoid** output activation. +- Maximum likelihood estimator for Bernoulli-distributed targets. - virtual QNumberType Cost(const Vector& parameters) = 0; - virtual Vector Gradient(const Vector& parameters) = 0; -}; -``` +### Categorical Cross-Entropy (CCE) -### Key Implementations - -1. **Mean Squared Error (MSE)**: - - Standard loss function for regression problems - - Penalizes larger errors more heavily (squared difference) - - Well-behaved gradients for optimization - - **Mathematical Definition:** - $L_{MSE}(y, \hat{y}) = \frac{1}{2n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ - - **Gradient with respect to predictions:** - $\frac{\partial L_{MSE}}{\partial \hat{y}_i} = \hat{y}_i - y_i$ - - ```cpp - template - class MeanSquaredError : public Loss - { - public: - MeanSquaredError(const Vector& target); - - QNumberType Cost(const Vector& parameters) override - { - QNumberType cost = QNumberType(0.0f); - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - QNumberType diff = parameters[i] - target[i]; - cost += diff * diff; - } - - return QNumberType(math::ToFloat(cost) / 2.0f); - } - - Vector Gradient(const Vector& parameters) override - { - Vector gradient; - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - gradient[i] = parameters[i] - target[i]; - - return gradient; - } - - private: - Vector target; - }; - ``` - -2. **Mean Absolute Error (MAE)**: - - Less sensitive to outliers than MSE - - Absolute difference between prediction and target - - Constant gradients (except at zero) - - **Mathematical Definition:** - $L_{MAE}(y, \hat{y}) = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|$ - - **Gradient with respect to predictions:** - $\frac{\partial L_{MAE}}{\partial \hat{y}_i} = - \begin{cases} - 1 & \text{if } \hat{y}_i > y_i \\ - -1 & \text{if } \hat{y}_i < y_i \\ - 0 & \text{if } \hat{y}_i = y_i - \end{cases}$ - - ```cpp - template - class MeanAbsoluteError : public Loss - { - public: - MeanAbsoluteError(const Vector& target); - - QNumberType Cost(const Vector& parameters) override - { - QNumberType cost = QNumberType(0.0f); - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - auto diff = parameters[i] - target[i]; - cost += diff < QNumberType(0.0f) ? -diff : diff; - } - - return cost; - } - - Vector Gradient(const Vector& parameters) override - { - Vector gradient; - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - auto diff = parameters[i] - target[i]; - gradient[i] = diff > QNumberType(0.0f) ? - QNumberType(0.9999f) : QNumberType(-0.9999f); - } - - return gradient; - } - - private: - Vector target; - }; - ``` - -3. **Binary Cross Entropy**: - - Used for binary classification problems - - Measures probability distribution divergence - - Expects outputs in range (0,1) - - **Mathematical Definition:** - $L_{BCE}(y, \hat{y}) = -\frac{1}{n} \sum_{i=1}^{n} [y_i \log(\hat{y}_i) + (1 - y_i) \log(1 - \hat{y}_i)]$ - - **Gradient with respect to predictions:** - $\frac{\partial L_{BCE}}{\partial \hat{y}_i} = \frac{\hat{y}_i - y_i}{\hat{y}_i(1 - \hat{y}_i)}$ - - ```cpp - template - class BinaryCrossEntropy : public Loss - { - public: - BinaryCrossEntropy(const Vector& target); - - QNumberType Cost(const Vector& parameters) override - { - QNumberType cost = QNumberType(0.0f); - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - QNumberType pred = std::max(std::min(parameters[i], - QNumberType(0.9999f)), - QNumberType(0.0001f)); - - cost += -(target[i] * std::log(math::ToFloat(pred)) + - (QNumberType(0.9999f) - target[i]) * - std::log(math::ToFloat(QNumberType(0.9999f) - pred))); - } - - return cost; - } - - Vector Gradient(const Vector& parameters) override - { - Vector gradient; - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - QNumberType pred = std::max(std::min(parameters[i], - QNumberType(0.9999f)), - QNumberType(0.0001f)); - - gradient[i] = (pred - target[i]) / - (pred * (QNumberType(0.9999f) - pred)); - } - - return gradient; - } - - private: - Vector target; - }; - ``` - -4. **Categorical Cross Entropy**: - - Used for multi-class classification problems - - Works with one-hot encoded targets - - Typically preceded by Softmax activation - - **Mathematical Definition:** - $L_{CCE}(y, \hat{y}) = -\sum_{i=1}^{n} \sum_{j=1}^{m} y_{i,j} \log(\hat{y}_{i,j})$ - - Where m is the number of classes and n is the number of samples. - - **Gradient with respect to Softmax inputs:** - $\frac{\partial L_{CCE}}{\partial \hat{y}_i} = \hat{y}_i - y_i$ - - When used with Softmax activation, this simplifies to the difference between predicted and actual probabilities. - - ```cpp - template - class CategoricalCrossEntropy : public Loss - { - public: - CategoricalCrossEntropy(const Vector& target); - - QNumberType Cost(const Vector& parameters) override - { - Vector probabilities = ComputeSoftmaxProbabilities(parameters); - QNumberType cost = QNumberType(0.0f); - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - cost += -target[i] * std::log(math::ToFloat(probabilities[i])); - - return cost; - } - - Vector Gradient(const Vector& parameters) override - { - Vector probabilities = ComputeSoftmaxProbabilities(parameters); - Vector gradient; - - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - gradient[i] = probabilities[i] - target[i]; - - return gradient; - } - - private: - Vector target; - Softmax softmax; - - Vector ComputeSoftmaxProbabilities(const Vector& x) const - { - Vector output; - QNumberType sum = QNumberType(0.0f); - - // Apply softmax function - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - output[i] = softmax.Forward(x[i]); - sum += output[i]; - } - - // Normalize to get probabilities - for (std::size_t i = 0; i < NumberOfFeatures; ++i) - { - output[i] = output[i] / sum; - // Numerical stability - output[i] = std::max(std::min(output[i], - QNumberType(0.9999f)), - QNumberType(0.0001f)); - } - - return output; - } - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Define problem parameters -constexpr std::size_t parameterSize = 10; -using FloatType = float; - -// Create target vector -math::Vector target; -// Fill target with expected values... - -// Create loss functions for different problem types -MeanSquaredError mseLoss(target); -MeanAbsoluteError maeLoss(target); -BinaryCrossEntropy bceLoss(target); -CategoricalCrossEntropy cceLoss(target); - -// Create parameter vector (model output) -math::Vector parameters; -// Fill parameters with model predictions... - -// Compute loss values -FloatType mseValue = mseLoss.Cost(parameters); -FloatType maeValue = maeLoss.Cost(parameters); -FloatType bceValue = bceLoss.Cost(parameters); -FloatType cceValue = cceLoss.Cost(parameters); - -// Compute gradients for backpropagation -auto mseGradient = mseLoss.Gradient(parameters); -auto maeGradient = maeLoss.Gradient(parameters); -auto bceGradient = bceLoss.Gradient(parameters); -auto cceGradient = cceLoss.Gradient(parameters); -``` +$$\mathcal{L}_{\text{CCE}} = -\sum_{i=1}^{k} y_i \log \hat{y}_i$$ -### Integration with Model Training +$$\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = -\frac{y_i}{\hat{y}_i}$$ -```cpp -// Create model, parameters, and optimizer -Model model; -auto initialParameters = model.GetParameters(); -GradientDescent optimizer; +- Assumes $\hat{y}$ is a probability distribution ($\sum \hat{y}_i = 1$) — pair with **Softmax** output activation. +- Standard loss for **multi-class classification**. -// Create loss function with targets -auto target = ComputeTargetVector(); -MeanSquaredError loss(target); +## Complexity Analysis -// Train model -model.Train(optimizer, loss, initialParameters); -``` +| Loss | Forward | Backward | Notes | +|------|---------|----------|-------| +| MSE | $O(m)$ | $O(m)$ | Cheapest; no transcendentals | +| MAE | $O(m)$ | $O(m)$ | Requires `sign()` | +| BCE | $O(m)$ | $O(m)$ | Requires `log()` | +| CCE | $O(k)$ | $O(k)$ | Requires `log()` | + +All losses are $O(m)$ where $m$ is the output dimension. The computational cost is negligible compared to the dense layer matrix products. + +## Step-by-Step Walkthrough + +**Scenario:** 3-class classification. Target $y = [0, 1, 0]$ (class 2). Softmax output $\hat{y} = [0.1, 0.7, 0.2]$. -## Best Practices +**CCE Forward:** -1. **Loss Function Selection**: - - Regression problems: MSE (standard), MAE (robust to outliers) - - Binary classification: Binary Cross-Entropy - - Multi-class classification: Categorical Cross-Entropy - - Probability distribution matching: KL-Divergence +$$\mathcal{L} = -(0 \cdot \log 0.1 + 1 \cdot \log 0.7 + 0 \cdot \log 0.2) = -\log(0.7) \approx 0.357$$ -2. **Implementation Considerations**: - - Ensure numerical stability (clamping to avoid log(0)) - - Consider computation efficiency - - Use appropriate gradients for optimization +**CCE Backward:** -3. **Regularization**: - - Always include regularization to prevent overfitting - - Adjust regularization strength as a hyperparameter - - Different regularization techniques for different problems +| $i$ | $y_i$ | $\hat{y}_i$ | $\partial \mathcal{L}/\partial \hat{y}_i = -y_i / \hat{y}_i$ | +|-----|--------|-------------|----------------------------------------------| +| 1 | 0 | 0.1 | $0$ | +| 2 | 1 | 0.7 | $-1.429$ | +| 3 | 0 | 0.2 | $0$ | -## Common Loss Functions Comparison +The gradient is non-zero only for the true class, and its magnitude $1/\hat{y}_2$ grows as the prediction *worsens* — providing a strong corrective signal. -| Function | Use Case | Advantages | Disadvantages | -|---------------------------|----------------------------|----------------------------------|-------------------------------| -| Mean Squared Error | Regression | Smooth gradients, penalizes outliers | Sensitive to outliers | -| Mean Absolute Error | Robust regression | Less sensitive to outliers | Non-differentiable at zero | -| Binary Cross-Entropy | Binary classification | Probabilistic interpretation | Numerical instability at extremes | -| Categorical Cross-Entropy | Multi-class classification | Measures probability divergence | Requires normalized outputs | +**For comparison — MSE on the same example:** -## Performance Considerations +$$\mathcal{L}_{\text{MSE}} = \frac{1}{3}[(0.1)^2 + (0.7-1)^2 + (0.2)^2] = \frac{1}{3}[0.01 + 0.09 + 0.04] = 0.047$$ -1. **Computation Efficiency**: - - MSE and MAE are computationally lighter than cross-entropy - - Softmax computation in CCE can be expensive - - Consider vectorized operations for better performance +MSE gives a much weaker signal and does not account for the probabilistic nature of the output. -2. **Numeric Stability**: - - Prevent under/overflow in exponential operations - - Clamp probabilities away from 0 and 1 - - Use stable implementations of mathematical functions +## Pitfalls & Edge Cases -3. **Gradient Behavior**: - - MSE gradients scale with error magnitude - - MAE gradients have constant magnitude - - Cross-entropy gradients adaptively scale +- **$\log(0)$ is $-\infty$.** Clamp predictions to $[\varepsilon, 1 - \varepsilon]$ before computing BCE or CCE. A typical $\varepsilon = 10^{-7}$. +- **Mismatched activation and loss.** Sigmoid + CCE or Softmax + BCE produce incorrect gradients. Always pair: Sigmoid ↔ BCE, Softmax ↔ CCE. +- **MSE for classification.** MSE can train a classifier but converges slower than cross-entropy because its gradient does not account for the log-likelihood structure. +- **Label encoding.** CCE expects one-hot encoded targets. Integer labels must be converted first. +- **Fixed-point log.** The `log()` function needed for cross-entropy is expensive and ill-conditioned near zero in fixed-point. Evaluate in floating-point. -## Regularization Integration +## Variants & Generalizations -While regularization is typically used with loss functions to prevent overfitting, this implementation focuses on the core loss computation. Regularization can be implemented separately and combined with the loss during the optimization process: +| Variant | Key Difference | +|---------|---------------| +| **Huber loss** | Quadratic for small errors, linear for large; robust regression | +| **Focal loss** | Down-weights well-classified examples; addresses class imbalance | +| **KL divergence** | Measures distance between two distributions; used in variational inference | +| **Hinge loss** | Margin-based; used in SVMs and some neural classifiers | +| **Contrastive loss** | Learns similarity metrics; used in Siamese networks | -```cpp -// Compute total loss -QNumberType totalLoss = lossFunction.Cost(parameters) + lambda * regularization.Calculate(parameters); +## Applications -// Combine gradients -Vector totalGradient = lossFunction.Gradient(parameters) + lambda * regularizationGradient; +- **Regression** — MSE for Gaussian noise, MAE for Laplacian noise or when outlier robustness is needed. +- **Binary classification** — BCE for yes/no decisions (fault detection, anomaly flagging). +- **Multi-class classification** — CCE for mutually exclusive categories (gesture recognition, signal type identification). +- **Probabilistic output** — Cross-entropy losses calibrate prediction confidence, not just accuracy. + +## Connections to Other Algorithms + +```mermaid +graph TD + Loss["Loss Functions"] + Act["Activation Functions"] + Opt["Optimizer"] + Reg["Regularization"] + Model["Model"] + LR["Linear Regression"] + + Act -->|"output activation must match loss"| Loss + Loss --> Opt + Reg -->|"added to loss"| Loss + Loss --> Model + Loss -.->|"MSE + normal equation"| LR ``` -Common regularization techniques include: -- L1 regularization (Lasso): Encourages sparse models by driving some weights to zero -- L2 regularization (Ridge): Prevents large weights by penalizing their squared magnitude - -## Limitations and Future Improvements - -1. Current limitations: - - Fixed-size vectors for parameters and targets - - Limited regularization options - - Categorical Cross-Entropy requires pre-applied Softmax - - Element-wise operations (not vectorized) - -2. Possible extensions: - - Additional loss functions (Huber, Hinge, KL-Divergence) - - Custom loss combinations - - Support for sparse targets - - Weighted losses for imbalanced data - - Focal loss for hard examples - - Adversarial training losses - - Vector-level operations for performance - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Appropriate parameter sizes - -2. Implementation considerations: - - Clamping probability values to avoid log(0) - - Defensive division to prevent divide-by-zero errors - - Careful numerical handling of extremes +| Component | Relationship | +|-----------|-------------| +| [Activation Functions](../activation/Activation.md) | Output activation must match: Sigmoid ↔ BCE, Softmax ↔ CCE, identity ↔ MSE | +| [Optimizer](../optimizer/Optimizer.md) | Uses $\nabla \mathcal{L}$ to update parameters | +| [Regularization](../regularization/Regularization.md) | Adds a penalty term to the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda \Omega(\theta)$ | +| [Linear Regression](../../estimators/LinearRegression.md) | Solved analytically when the loss is MSE and the model is linear | + +## References & Further Reading + +- Goodfellow, I., Bengio, Y., and Courville, A., *Deep Learning*, MIT Press, 2016 — Chapter 6.2 (cost functions). +- Bishop, C.M., *Pattern Recognition and Machine Learning*, Springer, 2006 — Chapter 4.3 (cross-entropy). +- Lin, T.-Y. et al., "Focal loss for dense object detection", *ICCV*, 2017. diff --git a/doc/neural_network/model/Model.md b/doc/neural_network/model/Model.md index b0258a25..53d1e473 100644 --- a/doc/neural_network/model/Model.md +++ b/doc/neural_network/model/Model.md @@ -1,368 +1,154 @@ -# Model Implementation Guide - -## Process Overview - -The following diagram illustrates the structure and functionality of the neural network model: - -![Neural Network Model](Model.svg) - -The diagram shows how the model: -1. Organizes multiple layers into a coherent architecture -2. Manages the flow of data through the network -3. Handles parameter management and training -4. Connects with optimizers and loss functions - -## Mathematical Background - -### Model Architecture - -A neural network model consists of a sequence of layers, transforming an input vector through multiple transformations: - -$$\mathbf{y} = f_n(f_{n-1}(...f_1(\mathbf{x})...))$$ - -where: -- x is the input vector -- y is the output vector -- f₁, f₂, ..., fₙ are the layer transformations - -### Training Process - -The model's training process involves: -1. Forward propagation to compute predictions -2. Loss calculation to measure error -3. Backward propagation to compute gradients -4. Parameter updates using an optimizer - -During training, parameters θ are updated to minimize a loss function L: - -$$\theta_{t+1} = \theta_t - \eta \nabla_\theta L(\theta_t)$$ - -## Implementation Details - -### Class Structure - -```cpp -template -class Model -{ - // Static assertions to verify types and dimensions - static_assert(math::is_qnumber::value || std::is_floating_point::value, - "Model can only be instantiated with math::QNumber types or floating point types."); - static_assert(detail::all_are_layers::value, - "All types in Layers must derive from Layer"); - static_assert(sizeof...(Layers) > 0, "Model must have at least one layer"); - static_assert(detail::verify_layer_sizes::value && - std::tuple_element_t>::OutputSize == OutputSize, - "Layer sizes do not match"); - -public: - using InputVector = math::Matrix; - using OutputVector = math::Matrix; - static constexpr std::size_t TotalParameters = detail::calculate_total_parameters(); - - Model(); - template - Model(FactoryFuncs&&... factories); - - OutputVector Forward(const InputVector& input); - InputVector Backward(const OutputVector& output_gradient); - void Train(Optimizer& optimizer, - Loss& loss, - const math::Vector& initialParameters); - void SetParameters(const math::Vector& parameters); - math::Vector GetParameters() const; - -private: - // Implementation details - std::tuple layers; - InputVector currentInput; -}; -``` +# Model (Neural Network Composition) -### Key Components - -1. **Layer Management**: - - Stores layers in a std::tuple - - Verifies layer compatibility at compile time - - Manages data flow between layers -2. **Parameter Handling**: - - Collects parameters from all layers - - Distributes updated parameters to layers - - Manages parameter vector with correct dimensions -3. **Forward and Backward Pass**: - - Chains layer operations for forward propagation - - Implements backpropagation for gradient computation - - Maintains intermediate values for backpropagation -4. **Training Process**: - - Connects model with optimizer and loss function - - Handles parameter updates during training - - Manages the training workflow - -### Layer Factory Helper - -```cpp -template -auto make_layer(Args&&... args) -{ - return [args = std::make_tuple(std::forward(args)...)]() mutable - { - return std::apply([](auto&&... params) - { - return Layer(std::forward(params)...); - }, - std::move(args)); - }; -} -``` +## Overview & Motivation -This helper function creates a factory lambda that constructs a layer with given arguments, enabling deferred layer construction during model initialization. - -### Compile-Time Verification - -Several static assertions and template metaprogramming constructs ensure layers are compatible: - -```cpp -// Check if a type is a layer -template -struct is_layer -{ - static constexpr bool value = std::is_base_of_v< - Layer, - T>; -}; - -// Verify all types are layers -template -struct all_are_layers; - -// Verify layer dimensions match -template -struct verify_layer_sizes; - -// Calculate total parameters -template -constexpr std::size_t calculate_total_parameters() -{ - return (... + Layers::ParameterSize); -} -``` +A **Model** composes a sequence of [dense layers](../layer/Layer.md) into a single trainable function $f: \mathbb{R}^n \to \mathbb{R}^m$. It is the orchestrator that: -## Usage Guide +1. Chains layers so the output of each feeds into the next (**forward pass**). +2. Propagates gradients backward through the chain (**backward pass**). +3. Flattens all layer parameters into a single vector for the [optimizer](../optimizer/Optimizer.md). +4. Verifies dimensional compatibility **at compile time** using variadic templates. -### Creating a Model +In this library, the Model is fully statically typed — layer dimensions, parameter counts, and memory footprints are all known at compile time, enabling zero-overhead abstraction on embedded targets. -```cpp -// Define dimensions -constexpr std::size_t inputSize = 784; // MNIST input -constexpr std::size_t hiddenSize = 128; // Hidden layer size -constexpr std::size_t outputSize = 10; // 10 digits -using FloatType = float; +## Mathematical Theory -// Create activation functions -ReLU relu; -Softmax softmax; +### Composition -// Initialize weights -math::Matrix weights1; -math::Matrix weights2; -// Fill weights with random values... +For $L$ layers with transformations $f_1, f_2, \ldots, f_L$: -// Create layer factory functions -auto layer1 = make_layer>(weights1, relu); -auto layer2 = make_layer>(weights2, softmax); +$$\hat{y} = (f_L \circ f_{L-1} \circ \cdots \circ f_1)(x) = f_L(f_{L-1}(\ldots f_1(x) \ldots))$$ -// Create model -Model, - Dense -> model(layer1, layer2); -``` +Each $f_\ell$ is a dense layer: $f_\ell(a) = \sigma_\ell(W_\ell a + b_\ell)$. + +### Parameter Vector + +All weights and biases are concatenated into a single vector: + +$$\theta = [\text{vec}(W_1), b_1, \text{vec}(W_2), b_2, \ldots, \text{vec}(W_L), b_L] \in \mathbb{R}^P$$ -### Forward and Backward Passes +where $P = \sum_{\ell=1}^L m_\ell(n_\ell + 1)$. -```cpp -// Forward pass -auto input = math::Vector{/* input data */}; -auto prediction = model.Forward(input); +### Forward Pass (Chained Evaluation) -// Backward pass -auto outputGradient = math::Vector{/* gradient */}; -auto inputGradient = model.Backward(outputGradient); +```mermaid +graph LR + X["x ∈ ℝⁿ"] --> L1["Layer 1"] --> L2["Layer 2"] --> Ldots["⋯"] --> LL["Layer L"] --> Y["ŷ ∈ ℝᵐ"] ``` -### Training the Model +### Backward Pass (Reverse Chain Rule) -```cpp -// Create optimizer -GradientDescent::Parameters gdParams; -gdParams.learningRate = 0.01f; -gdParams.maxIterations = 1000; -GradientDescent optimizer(gdParams); +$$\frac{\partial \mathcal{L}}{\partial \theta_\ell} = \frac{\partial \mathcal{L}}{\partial a_L} \cdot \frac{\partial a_L}{\partial a_{L-1}} \cdots \frac{\partial a_{\ell+1}}{\partial a_\ell} \cdot \frac{\partial a_\ell}{\partial \theta_\ell}$$ -// Create loss function -auto target = math::Vector{/* target data */}; -MeanSquaredError loss(target); +Each layer stores its input $a_{\ell-1}$ during the forward pass so it can compute $\nabla W_\ell$ and $\nabla b_\ell$ during the backward pass. -// Get initial parameters -auto initialParameters = model.GetParameters(); +### Training Loop -// Train model -model.Train(optimizer, loss, initialParameters); +```mermaid +graph TD + FP["Forward pass: ŷ = Model(x)"] + LC["Loss: ℒ(ŷ, y)"] + BP["Backward pass: ∇θ ℒ"] + UP["Update: θ ← θ − η ∇θ ℒ"] + FP --> LC --> BP --> UP --> FP ``` -### Parameter Management +## Complexity Analysis -```cpp -// Get current parameters -auto parameters = model.GetParameters(); +| Operation | Time | Space | +|-----------|------|-------| +| Forward pass | $O(P)$ | $O(\sum n_\ell)$ cached activations | +| Backward pass | $O(P)$ | $O(P)$ gradients | +| `GetParameters()` | $O(P)$ | $O(P)$ flat vector | +| `SetParameters()` | $O(P)$ | — | -// Modify parameters if needed -// ... +All operations scale linearly with the total parameter count $P$. -// Set updated parameters -model.SetParameters(parameters); -``` +## Step-by-Step Walkthrough -## Best Practices - -1. **Architecture Design**: - - Match layer dimensions carefully - - Start with simple architectures and add complexity - - Consider the problem structure when designing - -2. **Model Initialization**: - - Use appropriate weight initialization for each layer - - Consider layer-specific initialization requirements - - Ensure bias terms are properly initialized - -3. **Training Strategies**: - - Select appropriate optimizers for the problem - - Monitor training progress and adjust hyperparameters - - Consider regularization to prevent overfitting - -4. **Parameter Management**: - - Maintain proper parameter ordering across layers - - Understand parameter dimensionality requirements - - Consider parameter constraints if necessary - -## Variadic Templates and Type Safety - -The Model implementation makes heavy use of variadic templates and compile-time verification: - -1. **Variadic Layer Types**: - - Allows for arbitrary number of layers - - Each layer can have different dimensions - - Compile-time dimension checking - -2. **Type Safety**: - - Static assertions verify layer compatibility - - Type traits ensure proper parameter types - - Dimensional validation prevents mismatched layers - -3. **SFINAE Techniques**: - - Enable/disable template specializations based on constraints - - Provide better error messages for misuse - - Ensure type correctness at compile time - -## Performance Considerations - -1. **Computation Efficiency**: - - Parameter management done at compile time when possible - - Layer-specific optimizations possible through template specialization - - Intermediate value storage minimizes recomputation - -2. **Memory Usage**: - - Fixed-size vectors and matrices reduce dynamic allocations - - Parameter packing/unpacking done efficiently - - Tuple-based storage for heterogeneous layer types - -3. **Compile-Time Optimizations**: - - Template metaprogramming enables compile-time computations - - Static assertions catch errors at compile time rather than runtime - - Inline expansion potential for small layer operations - -## Forward and Backward Implementation - -The model uses recursive template expansion to implement forward and backward passes: - -```cpp -template -OutputVector ForwardImpl(const InputVector& input, std::index_sequence) -{ - // Implementation handles chaining of layer operations - // using parameter pack expansion -} - -template -InputVector BackwardImpl(const OutputVector& output_gradient, std::index_sequence) -{ - // Implementation handles reverse chaining of gradient flow - // using parameter pack expansion -} -``` +**Model:** 2 → 3 → 1 (two layers). + +**Compile-time verification chain:** + +| Check | Condition | Status | +|-------|-----------|--------| +| Layer 1 input size = Model input size | $2 = 2$ | ✓ | +| Layer 1 output size = Layer 2 input size | $3 = 3$ | ✓ | +| Layer 2 output size = Model output size | $1 = 1$ | ✓ | +| All types derive from `Layer` | type trait check | ✓ | + +**Parameter layout** ($P = 3 \times 3 + 3 + 1 \times 4 + 1 = 16$): + +| Index | Parameter | +|-------|-----------| +| 0–5 | $W_1$ (3×2 = 6 elements) | +| 6–8 | $b_1$ (3 elements) | +| 9–11 | $W_2$ (1×3 = 3 elements) | +| 12 | $b_2$ (1 element) | + +**Forward pass** with $x = [1.0, 0.5]^T$: -## Parameter Distribution - -Parameters are managed through careful packing and unpacking: - -```cpp -template -void SetParametersImpl( - const math::Vector& parameters, - std::index_sequence) -{ - std::size_t offset = 0; - (SetLayerParameters(std::get(layers), parameters, offset), ...); -} - -template -void SetLayerParameters( - Layer& layer, - const math::Vector& parameters, - std::size_t& offset) -{ - const std::size_t layerParameterSize = Layer::ParameterSize; - math::Vector layerParameters; - - for (std::size_t i = 0; i < layerParameterSize; ++i) - layerParameters[i] = parameters[offset + i]; - - layer.SetParameters(layerParameters); - offset += layerParameterSize; -} +1. Layer 1: $a_1 = \text{ReLU}(W_1 x + b_1) = [0.0, 0.8, 0.3]^T$ +2. Layer 2: $\hat{y} = \sigma(W_2 a_1 + b_2) = [0.62]$ + +**Backward pass** with loss gradient $\delta_{\text{out}} = [0.12]$: + +1. Layer 2 backward → produces $\nabla W_2$, $\nabla b_2$, and $\delta_1 = W_2^T \delta_2 \odot \text{ReLU}'(z_1)$ +2. Layer 1 backward → produces $\nabla W_1$, $\nabla b_1$ + +**Optimizer** receives the full $\nabla \theta \in \mathbb{R}^{16}$ and updates $\theta$. + +## Pitfalls & Edge Cases + +- **Dimension mismatch caught at compile time.** If layer $\ell$ outputs $m$ but layer $\ell+1$ expects $n \ne m$, a `static_assert` fires during compilation. +- **Empty model.** The variadic template requires at least one layer. `static_assert(sizeof...(Layers) > 0)`. +- **Parameter ordering.** `GetParameters()` and `SetParameters()` must use the same concatenation order. The implementation iterates layers via `std::index_sequence` to guarantee consistency. +- **Training with wrong optimizer size.** The optimizer's parameter count template argument must equal `Model::TotalParameters`. A mismatch is also caught at compile time. +- **Large parameter vectors.** All parameters live on the stack. A model with $P > 10{,}000$ floats consumes 40 KB — verify this fits the target's stack. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Sequential model (dynamic)** | Layers stored in a container; dimension checked at runtime instead of compile time | +| **Functional API** | Supports branching and merging (DAG topology instead of linear chain) | +| **Residual model** | Adds skip connections: $a_{\ell+2} = f_{\ell+1}(a_\ell) + a_\ell$ | +| **Recurrent model** | Unrolls the same layer across time steps | + +## Applications + +- **Embedded inference** — A pre-trained model's parameters are loaded via `SetParameters()` and only `Forward()` is called at runtime. +- **On-device training** — The full forward → loss → backward → update loop runs on the MCU for online learning/adaptation. +- **System identification** — A small model (2–3 layers) learns the plant dynamics from input-output data. +- **Sensor fusion** — Multiple sensor inputs are mapped to a unified state estimate through a trained model. + +## Connections to Other Algorithms + +```mermaid +graph TD + Model["Model"] + Layer["Dense Layer"] + Loss["Loss Functions"] + Opt["Optimizer"] + Reg["Regularization"] + NN["Neural Network"] + + Layer --> Model + Model --> Opt + Model --> Loss + Reg --> Loss + Model --> NN ``` -## Limitations and Future Improvements - -1. Current limitations: - - Fixed-size architecture at compile time - - Limited to feed-forward architectures - - No built-in serialization/deserialization - - Missing implementation for ForwardImpl and BackwardImpl - -2. Possible extensions: - - Dynamic layer addition/removal - - Runtime-configurable dimensions - - Support for recurrent architectures - - Built-in training loops with callbacks - - Integration with data loaders - - Batch processing support - - Model serialization for persistence - - Checkpointing during training - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Layer-derived types in parameter pack - - At least one layer present - - Matching layer dimensions - -2. Implementation considerations: - - Parameter validation during training - - Gradient checking capabilities - - Vector size validation for inputs/outputs +| Component | Relationship | +|-----------|-------------| +| [Dense Layer](../layer/Layer.md) | The Model is a sequence of layers stored in a `std::tuple` | +| [Loss Functions](../losses/Loss.md) | Measures prediction error; the Model delegates loss computation to a Loss object | +| [Optimizer](../optimizer/Optimizer.md) | Receives the flat parameter/gradient vectors from the Model and returns updated parameters | +| [Regularization](../regularization/Regularization.md) | Added to the loss before optimization | + +## References & Further Reading + +- Goodfellow, I., Bengio, Y., and Courville, A., *Deep Learning*, MIT Press, 2016 — Chapter 6 (deep feedforward networks). +- Paszke, A. et al., "PyTorch: An imperative style, high-performance deep learning library", *NeurIPS*, 2019 — inspiration for the sequential/functional model API. +- Abadi, M. et al., "TensorFlow: A system for large-scale machine learning", *OSDI*, 2016. diff --git a/doc/neural_network/optimizer/Optimizer.md b/doc/neural_network/optimizer/Optimizer.md index 14324b67..5d30fbca 100644 --- a/doc/neural_network/optimizer/Optimizer.md +++ b/doc/neural_network/optimizer/Optimizer.md @@ -1,306 +1,141 @@ -# Optimizer Implementation Guide +# Gradient Descent Optimizer -## Process Overview +## Overview & Motivation -The following diagram illustrates the optimization process in neural networks: +An **optimizer** adjusts a model's parameter vector $\theta \in \mathbb{R}^P$ to minimize a [loss function](../losses/Loss.md) $\mathcal{L}(\theta)$. The simplest and most fundamental strategy is **gradient descent**: repeatedly step in the direction of steepest descent: -![Optimization Methods](OptimizationMethods.svg) +$$\theta_{t+1} = \theta_t - \eta \, \nabla_\theta \mathcal{L}(\theta_t)$$ -The diagram shows how optimizers: -1. Navigate the loss landscape to find parameter values that minimize the loss -2. Use different strategies to approach the minimum efficiently -3. Adjust parameters based on gradient information -4. Influence convergence speed and stability during training +where $\eta$ is the **learning rate** — the single most important hyper-parameter in neural network training. -## Mathematical Background +This library provides a batch gradient descent optimizer with a fixed learning rate and maximum iteration count, suitable for small embedded models where training data fits in memory and simplicity is paramount. -### Optimization Purpose +## Mathematical Theory -Neural network training is fundamentally an optimization problem. For a model with parameters θ and loss function L(θ), we aim to find: +### The Gradient -$$\theta^* = \arg\min_{\theta} L(\theta)$$ +The gradient $\nabla_\theta \mathcal{L}$ is obtained via [back-propagation](../NeuralNetwork.md). Each component $\frac{\partial \mathcal{L}}{\partial \theta_i}$ tells how much the loss changes when $\theta_i$ is perturbed by a small amount. The gradient points **uphill**; subtracting it moves **downhill**. -Most optimization algorithms for neural networks use gradient information to iteratively update parameters: +### Convergence Conditions -$$\theta_{t+1} = \theta_t + \Delta\theta_t$$ +For a convex loss with Lipschitz-continuous gradient ($L$-smooth): -where Δθ₍ₜ₎ is the parameter update at step t. +$$\mathcal{L}(\theta_T) - \mathcal{L}(\theta^*) \le \frac{\|\theta_0 - \theta^*\|^2}{2 \eta T}$$ -### Gradient Descent +provided $\eta < \frac{1}{L}$. This gives a convergence rate of $O(1/T)$. -Gradient Descent is the fundamental optimization algorithm that updates parameters in the direction of steepest descent: +For non-convex losses (typical in neural networks), gradient descent converges to a **stationary point** ($\|\nabla \mathcal{L}\| \approx 0$) which may be a local minimum or saddle point — not necessarily the global minimum. -$$\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)$$ +### Learning Rate Sensitivity -where: -- η (eta) is the learning rate -- ∇L(θₜ) is the gradient of the loss function with respect to parameters +| $\eta$ | Behavior | +|--------|----------| +| Too small ($\eta \ll 1/L$) | Slow convergence, many iterations wasted | +| Optimal ($\eta \approx 1/L$) | Fastest reliable convergence | +| Too large ($\eta > 2/L$) | Oscillation and divergence | -## Implementation Details - -### Class Structure +```mermaid +graph LR + subgraph "Learning Rate Effect" + A["η too small
crawls to minimum"] + B["η just right
smooth convergence"] + C["η too large
oscillates / diverges"] + end +``` -```cpp -template -class Optimizer -{ - static_assert(math::is_qnumber::value || std::is_floating_point::value, - "Optimizer can only be instantiated with math::QNumber types."); +## Complexity Analysis -public: - using Vector = typename Loss::Vector; +| Operation | Time | Space | +|-----------|------|-------| +| One gradient evaluation | $O(P)$ per parameter | $O(P)$ gradient vector | +| One parameter update | $O(P)$ | In-place | +| Total training (T iterations) | $O(T \cdot P)$ | $O(P)$ working memory | - struct Result - { - Result(Vector parameters, QNumberType finalCost, size_t iterations) - : parameters(parameters) - , finalCost(finalCost) - , iterations(iterations) - {} +Memory overhead is minimal: only the current parameter vector, the gradient vector, and the optimizer result. No momentum buffers or second-moment estimates. - Vector parameters; - QNumberType finalCost; - std::size_t iterations; - }; +## Step-by-Step Walkthrough - virtual const Result& Minimize(const Vector& initialGuess, Loss& loss) = 0; -}; -``` +**Setup:** 2 parameters, $\theta_0 = [2.0, -1.0]^T$, $\eta = 0.1$, loss $\mathcal{L}(\theta) = \theta_1^2 + \theta_2^2$ (quadratic bowl). -### Key Implementations - -1. **Gradient Descent**: - - Simplest optimization algorithm - - Updates parameters directly proportional to negative gradient - - Controlled by learning rate parameter - **Mathematical Update Rule:** - $$\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)$$ - where: - - θₜ are the parameters at step t - - η is the learning rate - - ∇L(θₜ) is the gradient at step t - ```cpp - template - class GradientDescent : public Optimizer - { - public: - using Result = typename Optimizer::Result; - using Vector = typename Loss::Vector; - - struct Parameters - { - QNumberType learningRate; - size_t maxIterations; - }; - - explicit GradientDescent(const Parameters& params); - - const Result& Minimize(const Vector& initialGuess, - Loss& loss) override - { - auto currentParams = initialGuess; - auto currentCost = loss.Cost(currentParams); - Vector previousParams; - size_t iteration = 0; - - while (iteration < parameters.maxIterations) - { - previousParams = currentParams; - - // Compute gradient and update parameters - auto gradient = loss.Gradient(currentParams); - currentParams = currentParams - (gradient * parameters.learningRate); - - currentCost = loss.Cost(currentParams); - ++iteration; - } - - result.emplace(currentParams, currentCost, iteration); - return *result; - } - - private: - Parameters parameters; - std::optional result; - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Define optimization parameters -constexpr std::size_t parameterSize = 100; -using FloatType = float; - -// Configure gradient descent -GradientDescent::Parameters gdParams; -gdParams.learningRate = 0.01f; -gdParams.maxIterations = 1000; - -// Create optimizer -GradientDescent optimizer(gdParams); - -// Create initial parameter vector -math::Vector initialParameters; -// Initialize parameters... - -// Create loss function -MeanSquaredError lossFunction(target); - -// Run optimization -const auto& result = optimizer.Minimize(initialParameters, lossFunction); - -// Access optimization results -auto optimizedParameters = result.parameters; -auto finalLoss = result.finalCost; -auto iterationsUsed = result.iterations; -``` +**Iteration 1:** -### Integration with Neural Network Model +| Step | Computation | Result | +|------|-------------|--------| +| Gradient | $\nabla \mathcal{L} = [2\theta_1, 2\theta_2]$ | $[4.0, -2.0]$ | +| Update | $\theta_1 = \theta_0 - 0.1 \cdot \nabla\mathcal{L}$ | $[1.6, -0.8]$ | +| Loss | $\mathcal{L}(\theta_1) = 1.6^2 + 0.8^2$ | $3.20$ | -```cpp -// Create model -Model model; +**Iteration 2:** -// Configure gradient descent -GradientDescent::Parameters gdParams; -gdParams.learningRate = 0.01f; -gdParams.maxIterations = 1000; +| Step | Computation | Result | +|------|-------------|--------| +| Gradient | $[3.2, -1.6]$ | | +| Update | $[1.28, -0.64]$ | | +| Loss | $2.048$ | | -// Create optimizer and loss function -GradientDescent optimizer(gdParams); -MeanSquaredError loss(target); +**Pattern:** Each iteration multiplies the loss by $(1 - 2\eta)^2 = 0.64$. After 20 iterations, $\mathcal{L} \approx 0.0003$. -// Get initial parameters from model -auto initialParameters = model.GetParameters(); +**Convergence trace:** -// Train model -model.Train(optimizer, loss, initialParameters); +```mermaid +graph LR + I0["θ₀ = (2, -1)
ℒ = 5.0"] --> I1["θ₁ = (1.6, -0.8)
ℒ = 3.2"] + I1 --> I2["θ₂ = (1.28, -0.64)
ℒ = 2.05"] + I2 --> Idots["⋯"] + Idots --> I20["θ₂₀ ≈ (0.01, -0.005)
ℒ ≈ 0.0003"] ``` -### Learning Rate Selection - -```cpp -// Low learning rate (slow but stable convergence) -GradientDescent::Parameters slowParams; -slowParams.learningRate = 0.001f; -slowParams.maxIterations = 5000; +## Pitfalls & Edge Cases + +- **Learning rate too high.** The loss oscillates or increases. Start with $\eta = 0.01$ and decrease if unstable. +- **Flat regions / saddle points.** Gradient descent stalls when $\|\nabla \mathcal{L}\| \approx 0$ at non-optimal points. Momentum-based methods escape saddle points faster. +- **Ill-conditioned loss landscape.** When eigenvalues of the Hessian span many orders of magnitude, gradient descent oscillates along steep directions while barely progressing along flat ones. Adaptive methods (Adam) handle this better. +- **Max iterations reached.** The optimizer returns whatever parameters it has at `maxIterations` — always check `result.finalCost` to assess convergence quality. +- **Fixed-point gradients.** In Q15/Q31, multiply-accumulate in the gradient can overflow. Scale the learning rate to keep weight updates within representable range. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **SGD (Stochastic Gradient Descent)** | Uses a random mini-batch per iteration; noise helps escape local minima | +| **SGD with Momentum** | Accumulates a velocity: $v_{t+1} = \mu v_t - \eta \nabla\mathcal{L}$; smooths out oscillations | +| **Nesterov Momentum** | Evaluates gradient at the *lookahead* position $\theta + \mu v$; faster convergence | +| **AdaGrad** | Per-parameter adaptive learning rate based on accumulated squared gradients | +| **RMSProp** | Exponentially decaying average of squared gradients; handles non-stationary objectives | +| **Adam** | Combines momentum and RMSProp with bias correction; most popular adaptive method | + +## Applications + +- **On-device neural network training** — Gradient descent trains small models directly on the microcontroller. +- **Online adaptation** — Updating model parameters in real-time as new sensor data arrives. +- **Calibration** — Minimizing calibration error for sensor linearization. +- **System identification** — Fitting model parameters to measured input-output data. + +## Connections to Other Algorithms + +```mermaid +graph TD + Opt["Optimizer
(Gradient Descent)"] + Loss["Loss Functions"] + Model["Model"] + Reg["Regularization"] + LR["Linear Regression"] + + Loss -->|"∇ℒ"| Opt + Model -->|"θ, ∇θ"| Opt + Reg -->|"penalty gradient"| Loss + Opt -.->|"analytical solution at η→∞, 1 step"| LR +``` -// Medium learning rate (balanced convergence) -GradientDescent::Parameters mediumParams; -mediumParams.learningRate = 0.01f; -mediumParams.maxIterations = 1000; +| Component | Relationship | +|-----------|-------------| +| [Loss Functions](../losses/Loss.md) | Provides the `Cost()` and `Gradient()` the optimizer calls each iteration | +| [Model](../model/Model.md) | Passes initial parameters to the optimizer and receives optimized parameters back | +| [Regularization](../regularization/Regularization.md) | Adds a penalty gradient to $\nabla\mathcal{L}$, biasing the optimizer toward simpler models | +| [Linear Regression](../../estimators/LinearRegression.md) | For MSE on a linear model, gradient descent converges to the same solution as the normal equation | -// High learning rate (fast but potentially unstable convergence) -GradientDescent::Parameters fastParams; -fastParams.learningRate = 0.1f; -fastParams.maxIterations = 500; -``` +## References & Further Reading -## Best Practices - -1. **Learning Rate Selection**: - - Too small: slow convergence - - Too large: unstable or divergent behavior - - Start with 0.01 and adjust based on loss behavior - - Consider learning rate schedules for better convergence - -2. **Initialization Considerations**: - - Parameter initialization affects optimization path - - Multiple random initializations can help avoid local minima - - Consider scaling based on network architecture - -3. **Convergence Monitoring**: - - Track loss over iterations to assess convergence - - Implement early stopping if loss plateaus - - Monitor for oscillations or divergence - -## Advanced Optimization Techniques - -While the current implementation includes basic Gradient Descent, several advanced optimization algorithms are common in neural network training: - -1. **Stochastic Gradient Descent (SGD)**: - - Uses subsets of data (mini-batches) for each update - - Adds noise to escape local minima - - Often faster convergence than batch gradient descent - -2. **SGD with Momentum**: - - Accumulates a velocity vector to smooth updates - - Helps navigate narrow ravines in the loss landscape - - Update rule: v₊₁ = μv - η∇L(θ), θ₊₁ = θ + v₊₁ - -3. **Adaptive Methods**: - - AdaGrad: Adapts learning rates per-parameter based on historical gradients - - RMSProp: Uses exponentially weighted moving average of squared gradients - - Adam: Combines momentum and RMSProp with bias correction - -## Performance Considerations - -1. **Computation Efficiency**: - - Gradient computation is typically the bottleneck - - Consider vectorized operations for parameter updates - - Mini-batch processing can improve performance - -2. **Numeric Stability**: - - Check for NaN or Infinity in parameters and gradients - - Clip gradients to prevent explosion - - Use stable parameter update implementations - -3. **Memory Usage**: - - Basic gradient descent has minimal memory overhead - - Advanced optimizers require additional state variables - - Consider memory implications for very large models - -## Convergence Properties - -1. **Convergence Rate**: - - Linear convergence for well-conditioned problems - - Slower convergence for ill-conditioned loss landscapes - - Affected by learning rate and problem structure - -2. **Local vs. Global Minima**: - - Basic gradient descent may get trapped in local minima - - No guarantee of finding global optimum for non-convex problems - - Multiple runs with different initializations can help - -3. **Oscillations and Overshooting**: - - Can occur with high learning rates - - May require learning rate adjustment or momentum - - Monitor loss trajectory for stability - -## Limitations and Future Improvements - -1. Current limitations: - - Only basic gradient descent implemented - - Fixed learning rate throughout training - - No convergence criteria beyond max iterations - - Fixed-size parameter vectors - -2. Possible extensions: - - Momentum-based gradient descent - - Adaptive optimizers (Adam, RMSProp, AdaGrad) - - Learning rate schedules - - Convergence-based stopping criteria - - Mini-batch processing support - - Line search for optimal step size - - Second-order methods (L-BFGS, Newton's method) - - Distributed optimization for large models - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Appropriate parameter sizes - -2. Runtime checks: - - Positive learning rate - - Reasonable maximum iterations - - Parameter initialization validity - - Gradient validity during updates - -3. Considerations: - - Implement gradient clipping to prevent exploding gradients - - Add checks for NaN and infinity values - - Monitor loss for unexpected increases +- Ruder, S., "An overview of gradient descent optimization algorithms", *arXiv:1609.04747*, 2016. +- Bottou, L., Curtis, F.E., and Nocedal, J., "Optimization methods for large-scale machine learning", *SIAM Review*, 60(2), 2018. +- Kingma, D.P. and Ba, J., "Adam: A method for stochastic optimization", *ICLR*, 2015. diff --git a/doc/neural_network/regularization/Regularization.md b/doc/neural_network/regularization/Regularization.md index f2dbb28b..75ca8a9b 100644 --- a/doc/neural_network/regularization/Regularization.md +++ b/doc/neural_network/regularization/Regularization.md @@ -1,268 +1,135 @@ -# Regularization Implementation Guide +# Regularization -## Process Overview +## Overview & Motivation -The following diagram illustrates how regularization affects neural network training: +**Regularization** adds a penalty term $\Omega(\theta)$ to the loss function that discourages overly complex models: -![Regularization Methods](RegularizationMethods.svg) +$$\mathcal{L}_{\text{total}} = \mathcal{L}(\hat{y}, y) + \lambda \, \Omega(\theta)$$ -The diagram shows how regularization: -1. Penalizes model complexity to prevent overfitting -2. Modifies the loss landscape to find more generalizable solutions -3. Creates different effects on model parameters (L1 vs L2) -4. Influences the optimization process during training +where $\lambda > 0$ controls the strength of the penalty. Without regularization, a neural network with enough parameters can memorize the training data perfectly yet generalize poorly to new inputs — a phenomenon called **overfitting**. Regularization biases the optimizer toward simpler solutions that tend to generalize better. -## Mathematical Background +## Mathematical Theory -### Regularization Purpose +### L2 Regularization (Ridge / Weight Decay) -Regularization adds a penalty term to the loss function to discourage overly complex models. For a model with parameters θ and loss function L, the regularized loss L_reg is: +$$\Omega_{L2}(\theta) = \frac{1}{2}\sum_{i=1}^{P} \theta_i^2 = \frac{1}{2}\|\theta\|_2^2$$ -$$L_{reg}(θ) = L(θ) + \lambda R(θ)$$ +$$\frac{\partial \Omega_{L2}}{\partial \theta_i} = \theta_i$$ -where: -- L(θ) is the original loss function -- R(θ) is the regularization term -- λ (lambda) is the regularization strength +**Effect on update rule:** -### Types of Regularization +$$\theta_{t+1} = \theta_t - \eta(\nabla_\theta \mathcal{L} + \lambda \theta_t) = (1 - \eta\lambda)\theta_t - \eta \nabla_\theta \mathcal{L}$$ -Different regularization methods create different effects on model parameters: +The factor $(1 - \eta\lambda)$ shrinks weights toward zero each step — hence the name **weight decay**. Large weights are penalized quadratically, keeping the model smooth. -**L1 Regularization (Lasso):** -$$R_{L1}(θ) = \sum_{i=1}^{n} |θ_i|$$ +### L1 Regularization (Lasso) -**L2 Regularization (Ridge):** -$$R_{L2}(θ) = \frac{1}{2}\sum_{i=1}^{n} θ_i^2$$ +$$\Omega_{L1}(\theta) = \sum_{i=1}^{P} |\theta_i| = \|\theta\|_1$$ -## Implementation Details +$$\frac{\partial \Omega_{L1}}{\partial \theta_i} = \operatorname{sign}(\theta_i)$$ -### Class Structure +**Effect:** L1 drives small weights exactly to zero, producing a **sparse** model. This is useful for feature selection — irrelevant connections are pruned automatically. -```cpp -template -class Regularization -{ -public: - using Vector = math::Vector; - virtual QNumberType Calculate(const Vector& parameters) const = 0; -}; -``` +### Comparison -### Key Implementations - -1. **L1 Regularization (Lasso)**: - - Encourages sparse models by driving some parameters to zero - - Feature selection effect by eliminating irrelevant features - - Sum of absolute parameter values - **Mathematical Definition:** - $$R_{L1}(θ) = \lambda \sum_{i=1}^{n} |θ_i|$$ - **Gradient with respect to parameters:** - $$\frac{\partial R_{L1}}{\partial θ_i} = \lambda \cdot \text{sign}(θ_i)$$ - ```cpp - template - class L1 : public Regularization - { - public: - using Vector = typename Regularization::Vector; - - explicit L1(QNumberType lambda); - - QNumberType Calculate(const Vector& parameters) const override - { - QNumberType sum = QNumberType(0.0f); - - for (std::size_t i = 0; i < Size; ++i) - sum += parameters[i] < QNumberType(0.0f) ? - -parameters[i] : parameters[i]; - - return lambda * sum; - } - - private: - QNumberType lambda; - }; - ``` - -2. **L2 Regularization (Ridge)**: - - Penalizes large parameter values - - Promotes more uniform weight distributions - - Sum of squared parameter values - **Mathematical Definition:** - $$R_{L2}(θ) = \frac{\lambda}{2} \sum_{i=1}^{n} θ_i^2$$ - **Gradient with respect to parameters:** - $$\frac{\partial R_{L2}}{\partial θ_i} = \lambda \cdot θ_i$$ - ```cpp - template - class L2 : public Regularization - { - public: - using Vector = typename Regularization::Vector; - - explicit L2(QNumberType lambda); - - QNumberType Calculate(const Vector& parameters) const override - { - QNumberType sum = QNumberType(0.0f); - - for (std::size_t i = 0; i < Size; ++i) - sum += parameters[i] * parameters[i]; - - return QNumberType(math::ToFloat(lambda * sum) / 2.0f); - } - - private: - QNumberType lambda; - }; - ``` - -## Usage Guide - -### Basic Usage - -```cpp -// Define parameter size -constexpr std::size_t parameterSize = 100; -using FloatType = float; - -// Create regularization objects with different strengths -L1 l1Regularization(0.01f); // Sparse model -L2 l2Regularization(0.01f); // Smooth model - -// Create parameter vector -math::Vector parameters; -// Fill parameters with model weights... - -// Calculate regularization penalty -FloatType l1Penalty = l1Regularization.Calculate(parameters); -FloatType l2Penalty = l2Regularization.Calculate(parameters); -``` +| Property | L1 | L2 | +|----------|-----------|-----------| +| Penalty shape | Diamond (corners at axes) | Sphere | +| Sparsity | Promotes exact zeros | Shrinks toward zero but rarely reaches it | +| Gradient at $\theta_i = 0$ | Undefined (sub-gradient) | Zero | +| Best for | Feature selection, sparse models | General-purpose weight control | -### Integration with Loss Functions +### Geometric Interpretation -```cpp -// Create model and loss components -Model model; -auto parameters = model.GetParameters(); +The regularized loss can be viewed as constrained optimization: -// Create loss function -MeanSquaredError lossFunction(target); +$$\min_\theta \mathcal{L}(\theta) \quad \text{subject to} \quad \Omega(\theta) \le c$$ -// Create regularization -L2 regularization(0.01f); +where $c$ is determined by $\lambda$. L1 constrains $\theta$ to a diamond, so the optimal point tends to lie at a corner (sparse). L2 constrains to a sphere, so the optimal point balances all dimensions. -// Compute total loss (original loss + regularization) -FloatType totalLoss = lossFunction.Cost(parameters) + - regularization.Calculate(parameters); +## Complexity Analysis -// When computing gradients for optimization -auto lossGradient = lossFunction.Gradient(parameters); -auto regularizationGradient = regularization.Gradient(parameters); +| Operation | Time | Space | +|-----------|------|-------| +| $\Omega_{L2}(\theta)$ | $O(P)$ | $O(1)$ | +| $\nabla \Omega_{L2}$ | $O(P)$ | $O(P)$ | +| $\Omega_{L1}(\theta)$ | $O(P)$ | $O(1)$ | +| $\nabla \Omega_{L1}$ | $O(P)$ | $O(P)$ | -// Combined gradient for parameter updates -Vector totalGradient; -for (std::size_t i = 0; i < model.TotalParameters; ++i) - totalGradient[i] = lossGradient[i] + regularizationGradient[i]; -``` +Regularization adds negligible computational cost — one pass over the parameter vector per training iteration. + +## Step-by-Step Walkthrough + +**Scenario:** 3 parameters, $\theta = [0.8, -0.3, 0.5]$, $\lambda = 0.1$. + +**L2 Regularization:** + +| Step | Computation | Result | +|------|-------------|--------| +| Penalty | $\frac{1}{2}(0.64 + 0.09 + 0.25) = 0.49$ | $\Omega_{L2} = 0.49$ | +| Gradient | $[0.8, -0.3, 0.5]$ | Added to $\nabla\mathcal{L}$ | +| Contribution to loss | $0.1 \times 0.49 = 0.049$ | | + +**L1 Regularization:** + +| Step | Computation | Result | +|------|-------------|--------| +| Penalty | $0.8 + 0.3 + 0.5 = 1.6$ | $\Omega_{L1} = 1.6$ | +| Gradient | $[1, -1, 1]$ | Added to $\nabla\mathcal{L}$ | +| Contribution to loss | $0.1 \times 1.6 = 0.16$ | | -### Choosing Lambda Values +**After several L1 updates** ($\eta = 0.1$, $\lambda = 0.1$): the $\theta_2 = -0.3$ component, already small, is driven to exactly zero. The model effectively prunes that connection. -```cpp -// Weak regularization (prioritize fitting training data) -L2 weakRegularization(0.0001f); +## Pitfalls & Edge Cases -// Moderate regularization (balance fit and complexity) -L2 moderateRegularization(0.01f); +- **$\lambda$ too large.** The model underfits — weights are driven so close to zero that the network cannot represent the function. Cross-validate $\lambda$. +- **$\lambda$ too small.** Negligible effect; overfitting persists. +- **L1 non-differentiability.** At $\theta_i = 0$, the L1 gradient is undefined. Use sub-gradient $\operatorname{sign}(0) = 0$ or proximal operators for exact handling. +- **Regularizing biases.** Conventionally, bias parameters are excluded from regularization because they do not contribute to model complexity. This library regularizes all parameters in the flat vector — be aware of this if bias control matters. +- **Fixed-point precision.** The regularization term can be much smaller than the main loss when $\lambda$ is small. In low-precision fixed-point, it may round to zero. Scale $\lambda$ or use a wider accumulator. -// Strong regularization (prioritize model simplicity) -L2 strongRegularization(0.1f); +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Elastic Net** | $\Omega = \alpha \|\theta\|_1 + (1-\alpha)\|\theta\|_2^2$; combines L1 sparsity with L2 smoothness | +| **Dropout** | Randomly zeroes activations during training; implicit ensemble regularization | +| **Early stopping** | Halts training before overfitting; regularization without modifying the loss | +| **Data augmentation** | Expands the training set with transformed copies; reduces overfitting by increasing data diversity | +| **Spectral normalization** | Constrains the spectral norm of weight matrices; stabilizes GAN training | +| **Weight clipping** | Hard constraint: $|\theta_i| \le c$; used in Wasserstein GANs | + +## Applications + +- **Preventing overfitting** — The primary use case for any neural network trained on limited data (common in embedded scenarios). +- **Feature selection** — L1 regularization identifies and prunes irrelevant input connections. +- **Model compression** — Sparse models (via L1) require less storage and computation for deployment on MCUs. +- **Transfer learning** — L2 regularization keeps fine-tuned weights close to pre-trained values. + +## Connections to Other Algorithms + +```mermaid +graph TD + Reg["Regularization"] + Loss["Loss Functions"] + Opt["Optimizer"] + Model["Model"] + LR["Linear Regression"] + + Reg -->|"λ Ω(θ) added to ℒ"| Loss + Loss --> Opt + Opt --> Model + Reg -.->|"L2 + MSE = Ridge regression"| LR ``` -## Best Practices - -1. **Regularization Selection**: - - L1 regularization when sparse models are desired (feature selection) - - L2 regularization for general model stability and preventing large weights - - Combined L1+L2 (Elastic Net) for a mix of both effects - -2. **Lambda Selection**: - - Use cross-validation to find optimal lambda values - - Start with small values (0.0001-0.001) and gradually increase - - Different model sizes may require different lambda scales - -3. **Implementation Considerations**: - - Scale lambda based on dataset size - - Apply regularization only to weights, not biases - - Consider learning rate interaction with regularization strength - -## L1 vs L2 Regularization Comparison - -| Aspect | L1 Regularization | L2 Regularization | -|-------------------|-----------------------------------------------------|---------------------------------------| -| Effect on Weights | Many weights become exactly zero | All weights become smaller, non-zero | -| Sparsity | Creates sparse models | Creates dense, small-weight models | -| Feature Selection | Effectively removes irrelevant features | Keeps all features but reduces impact | -| Loss Surface | Non-differentiable at zero | Smooth, differentiable everywhere | -| Best Use Case | High-dimensional data with many irrelevant features | General purpose, prevents overfitting | -| Computational | More complex optimization problem | Simpler, more stable optimization | - -## Performance Considerations - -1. **Computation Efficiency**: - - L2 regularization is computationally simpler than L1 - - Both can be vectorized for performance - - Regularization computation is generally inexpensive compared to loss functions - -2. **Numeric Stability**: - - L1 requires special handling at zero (non-differentiable) - - Both can be implemented with stable numeric operations - -3. **Memory Usage**: - - Both L1 and L2 regularization have minimal memory requirements - - Only need to store the lambda parameter - -## Other Regularization Techniques - -Though not implemented in the provided code, other common regularization techniques include: - -1. **Elastic Net**: - - Combines L1 and L2 regularization - - $$R_{elastic}(θ) = \lambda_1 \sum |θ_i| + \lambda_2 \sum θ_i^2$$ - - Balances sparsity and smoothness - -2. **Dropout**: - - Randomly deactivates neurons during training - - Acts as an implicit ensemble method - - Prevents co-adaptation of neurons - -3. **Early Stopping**: - - Stop training when validation performance degrades - - Implicit regularization by limiting training iterations - - Prevents memorization of training data - -## Limitations and Future Improvements - -1. Current limitations: - - Limited to L1 and L2 regularization - - Fixed parameter size at compile time - - No gradient method in base class - - Fixed lambda during training - -2. Possible extensions: - - Elastic Net implementation (combined L1+L2) - - Parameter-specific regularization strengths - - Adaptive regularization during training - - Structured regularization for specific parameter groups - - Regularization schedules that vary lambda over time - - Support for other regularization techniques (orthogonal, spectral) - -## Error Handling - -1. Static assertions verify: - - Valid numeric types - - Appropriate parameter sizes - -2. Implementation considerations: - - Ensure lambda values are positive - - Handle numeric overflow for very large parameters or lambda values - - Consider NaN and infinity checks for robustness +| Component | Relationship | +|-----------|-------------| +| [Loss Functions](../losses/Loss.md) | Regularization is a penalty *added to* the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda\Omega$ | +| [Optimizer](../optimizer/Optimizer.md) | Receives the combined gradient $\nabla\mathcal{L} + \lambda\nabla\Omega$ | +| [Linear Regression](../../estimators/LinearRegression.md) | L2-regularized MSE with a linear model is **Ridge regression**; L1 is **Lasso** | + +## References & Further Reading + +- Goodfellow, I., Bengio, Y., and Courville, A., *Deep Learning*, MIT Press, 2016 — Chapter 7 (regularization). +- Tibshirani, R., "Regression shrinkage and selection via the lasso", *JRSS-B*, 58(1), 1996. +- Krogh, A. and Hertz, J.A., "A simple weight decay can improve generalization", *NeurIPS*, 1991. diff --git a/doc/solvers/DiscreteAlgebraicRiccatiEquation.md b/doc/solvers/DiscreteAlgebraicRiccatiEquation.md index 3e3a5d4c..9219ca45 100644 --- a/doc/solvers/DiscreteAlgebraicRiccatiEquation.md +++ b/doc/solvers/DiscreteAlgebraicRiccatiEquation.md @@ -1,52 +1,117 @@ -# Discrete Algebraic Riccati Equation +# Discrete Algebraic Riccati Equation (DARE) -## Mathematical Background +## Overview & Motivation -### The DARE +The Discrete Algebraic Riccati Equation arises whenever you need to find an optimal trade-off between state regulation and control effort in a discrete-time linear system. It is the mathematical core of two fundamental algorithms: -The Discrete Algebraic Riccati Equation (DARE) arises in optimal control and estimation problems for discrete-time linear systems. It computes a positive semi-definite matrix `P` that satisfies: +1. **LQR control** — computing the optimal state-feedback gain. +2. **Steady-state Kalman filtering** — computing the optimal estimator gain. -``` -P = A' P A - A' P B (R + B' P B)⁻¹ B' P A + Q -``` +The DARE finds a symmetric positive semi-definite matrix $P$ that encodes the *cost-to-go* from any state. Once $P$ is known, the optimal gain is a simple closed-form expression. This library solves the DARE via **fixed-point iteration** — simple to implement, numerically transparent, and well-suited to the small state dimensions typical in embedded control. + +## Mathematical Theory + +### The Equation + +$$P = A^T P A - A^T P B \left(R + B^T P B\right)^{-1} B^T P A + Q$$ where: -- `A` is the state transition matrix (n × n) -- `B` is the input matrix (n × m) -- `Q` is the state weighting matrix (n × n, positive semi-definite) -- `R` is the input weighting matrix (m × m, positive definite) -- `P` is the solution matrix (n × n, positive semi-definite) +- $A \in \mathbb{R}^{n \times n}$ — state transition matrix +- $B \in \mathbb{R}^{n \times m}$ — input matrix +- $Q \in \mathbb{R}^{n \times n}$ — state weighting matrix ($Q \succeq 0$) +- $R \in \mathbb{R}^{m \times m}$ — input weighting matrix ($R \succ 0$) +- $P \in \mathbb{R}^{n \times n}$ — the unknown ($P \succeq 0$) ### Iterative Solution -The implementation uses fixed-point iteration starting from `P₀ = Q`: +Starting from $P_0 = Q$: -``` -1. Compute S = R + B' P B -2. Solve S * K = B' P A (via Gaussian elimination) -3. Update P_new = A' P A - A' P B * K + Q -4. Check ||P_new - P_old|| < tolerance -5. Repeat until converged or MaxIterations reached -``` +1. $S = R + B^T P_k B$ +2. Solve $S \cdot K_{\text{part}} = B^T P_k A$ (via [Gaussian Elimination](GaussianElimination.md)) +3. $P_{k+1} = A^T P_k A - A^T P_k B \cdot K_{\text{part}} + Q$ +4. If $\|P_{k+1} - P_k\| < \varepsilon$, converged. -Each iteration refines `P` toward the steady-state solution. Convergence is guaranteed when the system `(A, B)` is stabilizable and `Q` is positive semi-definite. +### Existence and Convergence -### Connection to LQR +A unique stabilizing solution exists when: +- $(A, B)$ is **stabilizable** (unstable modes are controllable). +- $(A, C)$ is **detectable** (where $Q = C^T C$). -The DARE solution `P` directly yields the optimal LQR gain: +Under these conditions, the iteration converges monotonically: $P_0 \preceq P_1 \preceq \cdots \preceq P^*$. -``` -K = (R + B' P B)⁻¹ B' P A -``` +### Optimal Gain -The resulting control law `u[k] = -K x[k]` minimizes the infinite-horizon quadratic cost: +$$K = \left(R + B^T P B\right)^{-1} B^T P A$$ +## Complexity Analysis + +| Phase | Time | Space | Notes | +|-------|------|-------|-------| +| Per iteration | $O(n^3 + n^2 m + m^3)$ | $O(n^2)$ | Matrix multiplications + one $m \times m$ linear solve | +| Total solver | $O(I(n^3 + m^3))$ | $O(n^2)$ | $I$ iterations (typically 10–30) | + +**Why $O(n^3)$:** Each iteration involves $n \times n$ matrix products ($A^T P A$) and an $m \times m$ linear solve (for $S^{-1}$). When $m \ll n$, the matrix products dominate. + +## Step-by-Step Walkthrough + +**System:** $n=2$, $m=1$, $A = \begin{bmatrix}1 & 0.1\\0 & 1\end{bmatrix}$, $B = \begin{bmatrix}0.005\\0.1\end{bmatrix}$, $Q = I_2$, $R = [1]$. + +**Iteration 0:** $P_0 = Q = I_2$ + +1. $S = R + B^T P_0 B = 1 + [0.005\; 0.1]\begin{bmatrix}0.005\\0.1\end{bmatrix} = 1.010025$ +2. $B^T P_0 A = [0.005\; 0.1]\begin{bmatrix}1 & 0.1\\0 & 1\end{bmatrix} = [0.005,\; 0.1005]$ +3. $K_{\text{part}} = [0.005,\; 0.1005] / 1.010025 = [0.00495,\; 0.0995]$ +4. $A^T P_0 A = \begin{bmatrix}1 & 0\\0.1 & 1\end{bmatrix}\begin{bmatrix}1 & 0.1\\0 & 1\end{bmatrix} = \begin{bmatrix}1 & 0.1\\0.1 & 1.01\end{bmatrix}$ +5. Correction term $\approx \begin{bmatrix}0.0000248 & 0.000498\\0.000498 & 0.00999\end{bmatrix}$ +6. $P_1 \approx \begin{bmatrix}2.0 & 0.0995\\0.0995 & 2.000\end{bmatrix}$ + +**Iterations 1–20:** $P$ grows monotonically until convergence. For this $Q/R$ ratio, $P^*$ stabilizes in ~15 iterations. + +## Pitfalls & Edge Cases + +- **Non-stabilizable system.** The iteration diverges if $(A, B)$ is not stabilizable. Check the controllability matrix rank before calling the solver. +- **$R$ must be positive definite.** The linear solve $S \cdot K_{\text{part}} = \ldots$ fails if $S$ is singular, which happens when $R$ has zero eigenvalues. +- **Slow convergence.** Systems with eigenvalues near the unit circle converge slowly. Increase the maximum iteration bound if needed. +- **Fixed-point overflow.** The matrix products can easily exceed Q15/Q31 ranges. Use floating-point for the solve; deploy the resulting $K$ as a fixed-point constant. +- **Tolerance type-awareness.** The convergence test uses `math::Tolerance()`, which adapts to both `float` and fixed-point types. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Continuous ARE (CARE)** | For continuous-time systems; different matrix equation | +| **Newton's method for DARE** | Quadratic convergence but requires solving a Sylvester equation per iteration | +| **Schur method** | Eigendecomposition-based; finds the solution in one pass but requires $O(n^3)$ eigenvalue computation | +| **Doubling algorithm** | $O(\log I)$ convergence via matrix sign function; useful for large systems | + +## Applications + +- **LQR control** — The [LQR controller](../controllers/Lqr.md) derives its gain from the DARE solution. +- **Kalman filter steady-state gain** — The dual DARE (swapping $A \to A^T$, $B \to H^T$, $Q \to Q_{\text{process}}$, $R \to R_{\text{measurement}}$) gives the steady-state Kalman gain. +- **$H_\infty$ control** — Robust controller design involves coupled Riccati equations. +- **Model predictive control** — The terminal cost matrix in MPC is often the DARE solution. + +## Connections to Other Algorithms + +```mermaid +graph LR + DARE["DARE Solver"] + GE["Gaussian Elimination"] + LQR["LQR Controller"] + KF["Kalman Filter"] + GE --> DARE + DARE --> LQR + DARE --> KF ``` -J = Σ (x[k]' Q x[k] + u[k]' R u[k]) for k = 0 to ∞ -``` -### Convergence +| Algorithm | Relationship | +|-----------|-------------| +| [Gaussian Elimination](GaussianElimination.md) | Used at each iteration to solve the $m \times m$ linear sub-system | +| [LQR Controller](../controllers/Lqr.md) | Direct consumer — extracts optimal gain $K$ from the DARE solution matrix $P$ | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Dual problem — the steady-state Kalman gain is computed by a transposed DARE | + +## References & Further Reading -- The tolerance is type-aware via `math::Tolerance()`, ensuring convergence is achievable for both floating-point and fixed-point types -- The algorithm is bounded by `MaxIterations` (default 100) to guarantee termination -- For well-conditioned systems, convergence typically occurs within 10–30 iterations +- Lancaster, P. and Rodman, L., *Algebraic Riccati Equations*, Oxford University Press, 1995. +- Anderson, B.D.O. and Moore, J.B., *Optimal Control: Linear Quadratic Methods*, Prentice Hall, 1990 — Chapter 4. +- Laub, A.J., "A Schur method for solving algebraic Riccati equations", *IEEE Transactions on Automatic Control*, 24(6), 1979. diff --git a/doc/solvers/DurandKerner.md b/doc/solvers/DurandKerner.md index 625cc9c6..8a653def 100644 --- a/doc/solvers/DurandKerner.md +++ b/doc/solvers/DurandKerner.md @@ -1,96 +1,119 @@ # Durand-Kerner Polynomial Root Finder -## Process Overview +## Overview & Motivation -```mermaid -graph TD - A[Input Polynomial Coefficients] --> B{Empty or Zero-Order?} - B -->|Yes| C[Return Empty Roots] - B -->|No| D{First-Order?} - D -->|Yes| E[Direct Solution: -c₁/c₀] - D -->|No| F[Initialize Roots on Circle] - F --> G[Iterative Refinement] - G --> H{Converged or Max Iterations?} - H -->|No| G - H -->|Yes| I[Sort Roots by Real Part] - I --> J[Return Roots] -``` +Given a polynomial $P(z) = c_0 z^n + c_1 z^{n-1} + \cdots + c_n$, finding all roots (real and complex) is a fundamental problem in control theory, signal processing, and numerical analysis. Analytical formulas exist only for degree $\leq 4$; beyond that, iterative methods are required. + +The **Durand-Kerner method** (also known as the Weierstrass iteration) simultaneously refines approximations to *all* roots at once. Each root estimate is updated using Newton's method, but instead of computing the derivative of $P$, the other root estimates are used to factor out known roots. This avoids **polynomial deflation** — a process that accumulates errors as roots are extracted sequentially. -## Mathematical Background +The method is elegant, easy to implement, and works for polynomials with complex coefficients and complex roots. -### Polynomial Representation +## Mathematical Theory -The polynomial is represented in descending power order: +### Update Rule -$$P(z) = c_0 z^n + c_1 z^{n-1} + \cdots + c_{n-1} z + c_n$$ +Given current root estimates $z_0, z_1, \ldots, z_{n-1}$, each is updated simultaneously: -where the coefficients array is `[c₀, c₁, ..., cₙ]` with `c₀ ≠ 0` (leading coefficient). +$$z_r^{(k+1)} = z_r^{(k)} - \frac{P(z_r^{(k)})}{\displaystyle\prod_{j \neq r} \left(z_r^{(k)} - z_j^{(k)}\right)}$$ -### Durand-Kerner Method +### Relationship to Newton's Method -The Durand-Kerner method (also known as Weierstrass iteration) simultaneously refines all roots of a polynomial. Given current root estimates $z_0, z_1, \ldots, z_{n-1}$, each root is updated: +For a polynomial $P(z) = c_0 \prod_{j=0}^{n-1}(z - z_j)$, the derivative is: -$$z_r^{(k+1)} = z_r^{(k)} - \frac{P(z_r^{(k)})}{\prod_{j \neq r} (z_r^{(k)} - z_j^{(k)})}$$ +$$P'(z_r) = c_0 \prod_{j \neq r}(z_r - z_j)$$ -This is equivalent to applying Newton's method but using the other root estimates to factor out known roots from the denominator, avoiding explicit polynomial deflation. +So the Durand-Kerner update is exactly Newton's: $z_r - P(z_r)/P'(z_r)$, but with $P'$ approximated using the current root estimates rather than computed from coefficients. ### Initial Root Placement -Roots are initialized uniformly on a circle of radius: +Roots are initialized on a circle of radius: -$$R = \left| \frac{c_n}{c_0} \right|^{1/n}$$ +$$R = \left|\frac{c_n}{c_0}\right|^{1/n}$$ -with an angular offset of 0.4 radians to break symmetry. If $R < 0.1$, it defaults to 1.0. +with angular positions offset by 0.4 radians to break symmetry. If $R < 0.1$, it defaults to 1.0. ### Convergence -- **Quadratic convergence** when roots are well-separated -- **Linear convergence** near repeated roots -- Terminates when all corrections $|z_r^{(k+1)} - z_r^{(k)}| < \epsilon$ (default $\epsilon = 10^{-6}$) -- Maximum iteration limit (default 200) prevents infinite loops +- **Quadratic convergence** when roots are well-separated. +- **Linear convergence** near repeated (multiple) roots. +- Terminates when all corrections satisfy $|z_r^{(k+1)} - z_r^{(k)}| < \varepsilon$. -## API +## Complexity Analysis -```cpp -#include "numerical/solvers/DurandKerner.hpp" +| Case | Time | Space | Notes | +|------|------|-------|-------| +| Per iteration | $O(n^2)$ | $O(n)$ | Evaluating $P$ and the denominator product for all $n$ roots | +| Total | $O(n^2 k)$ | $O(n)$ | $k$ iterations until convergence (typically $k \ll n$) | -solvers::DurandKerner solver; +**Why $O(n^2)$:** For each of the $n$ roots, computing the denominator product requires multiplying $n-1$ terms. -// Coefficients for z^3 - 6z^2 + 11z - 6 = (z-1)(z-2)(z-3) -std::array coeffs = { 1.0f, -6.0f, 11.0f, -6.0f }; -auto roots = solver.Solve(infra::MakeRange(coeffs)); -// roots ≈ {1+0j, 2+0j, 3+0j} -``` +## Step-by-Step Walkthrough -### Template Parameters +**Polynomial:** $P(z) = z^3 - 6z^2 + 11z - 6 = (z-1)(z-2)(z-3)$ -| Parameter | Description | -|-----------|-------------| -| `T` | Floating-point type (`float` or `double`) | -| `MaxOrder` | Maximum polynomial degree supported | +**Step 1 — Initialize** on radius $R = |{-6}/{1}|^{1/3} = 6^{1/3} \approx 1.817$: + +- $z_0 = 1.817 \, e^{j \cdot 0.4} \approx 1.670 + 0.708j$ +- $z_1 = 1.817 \, e^{j \cdot 2.494} \approx -1.458 + 1.082j$ +- $z_2 = 1.817 \, e^{j \cdot 4.589} \approx -0.212 - 1.805j$ + +**Step 2 — Iteration 1 (for $z_0$):** + +1. Evaluate $P(z_0) = z_0^3 - 6z_0^2 + 11z_0 - 6$ +2. Compute denominator: $(z_0 - z_1)(z_0 - z_2)$ +3. Update: $z_0 \leftarrow z_0 - P(z_0) / \text{denom}$ + +**Step 3 — Repeat** for $z_1$ and $z_2$ (using the latest values). -### Solve Parameters +**Step 4 — Iterate** until $\max_r |z_r^{(k+1)} - z_r^{(k)}| < 10^{-6}$. -| Parameter | Default | Description | -|-----------|---------|-------------| -| `coefficients` | — | Polynomial coefficients in descending power order | -| `maxIterations` | 200 | Maximum number of Durand-Kerner iterations | -| `tolerance` | 1e-6 | Convergence threshold for root corrections | +After ~15–20 iterations the roots converge to $z \approx \{1, 2, 3\}$ (imaginary parts $< 10^{-6}$). -### Preconditions +## Pitfalls & Edge Cases -- `coefficients` must not be empty -- Leading coefficient `coefficients[0]` must be non-zero -- Polynomial order must not exceed `MaxOrder` +- **Repeated roots.** Convergence degrades from quadratic to linear. Higher tolerance or more iterations may be needed. +- **Near-degenerate denominators.** When two root estimates are very close ($|z_r - z_j| < 10^{-15}$), the denominator product approaches zero. The implementation excludes such terms to avoid division by near-zero. +- **Leading coefficient must be non-zero.** The polynomial degree is determined by the first coefficient. +- **Complex arithmetic required.** This algorithm operates entirely in $\mathbb{C}$, so it is limited to floating-point types (`float`, `double`). Fixed-point types are not supported. +- **No convergence guarantee for all polynomials.** Wilkinson's polynomial and other pathological cases may require higher precision or alternative methods. +- **Root ordering.** Results are sorted by real part (ascending), which may not correspond to meaningful branch ordering in applications like [Root Locus](../analysis/RootLocus.md). -### Complexity +## Variants & Generalizations -- **Time**: $O(n^2 \cdot k)$ where $n$ is polynomial order and $k$ is iteration count -- **Space**: $O(n)$ — roots stored in `BoundedVector` +| Variant | Key Difference | +|---------|---------------| +| **Aberth-Ehrlich method** | Similar simultaneous iteration but includes a correction term that improves convergence for clustered roots | +| **Jenkins-Traub** | Sequential algorithm (one root at a time) with superior convergence for difficult polynomials; standard in numerical libraries | +| **Companion matrix + eigenvalues** | Converts to an eigenvalue problem; robust but $O(n^3)$ | +| **Laguerre's method** | Converges cubically for simple roots; sequential (extracts one root at a time, then deflates) | +| **Muller's method** | Uses quadratic interpolation; works for non-polynomial equations too | + +## Applications + +- **Root locus analysis** — The [Root Locus](../analysis/RootLocus.md) algorithm calls Durand-Kerner at each gain step to find the closed-loop poles. +- **Stability analysis** — Determining whether all roots of a characteristic polynomial lie inside the unit circle (discrete) or left half-plane (continuous). +- **Filter design** — Finding pole and zero locations of transfer functions. +- **Control system design** — Evaluating characteristic equations to check stability margins. + +## Connections to Other Algorithms + +```mermaid +graph LR + DK["Durand-Kerner"] + RL["Root Locus"] + GE["Gaussian Elimination"] + RL --> DK + GE -.->|"companion matrix alternative"| DK +``` + +| Algorithm | Relationship | +|-----------|-------------| +| [Root Locus](../analysis/RootLocus.md) | Primary consumer — calls Durand-Kerner to find characteristic polynomial roots at each gain step | +| [Gaussian Elimination](GaussianElimination.md) | Alternative approach: form the companion matrix and compute eigenvalues (requires a different solver) | -## Numerical Considerations +## References & Further Reading -- **Near-degenerate denominators**: When two root estimates are very close ($|z_r - z_j| < 10^{-15}$), the difference is excluded from the denominator product to avoid division by near-zero -- **Root sorting**: Results are sorted by real part (ascending), with imaginary part as tiebreaker -- **Fixed-point**: Only floating-point types (`float`, `double`) are supported due to the complex arithmetic requirements -- **Ill-conditioned polynomials**: Polynomials with clustered or repeated roots may converge slowly; increase `maxIterations` if needed +- Durand, E., *Solutions numériques des équations algébriques*, Masson, 1960. +- Kerner, I.O., "Ein Gesamtschrittverfahren zur Berechnung der Nullstellen von Polynomen", *Numerische Mathematik*, 8, 1966. +- Aberth, O., "Iteration methods for finding all zeros of a polynomial simultaneously", *Mathematics of Computation*, 27(122), 1973. +- Press, W.H. et al., *Numerical Recipes*, 3rd ed., Cambridge University Press, 2007 — Section 9.5. diff --git a/doc/solvers/GaussianElimination.md b/doc/solvers/GaussianElimination.md index 59404c22..e6a455f4 100644 --- a/doc/solvers/GaussianElimination.md +++ b/doc/solvers/GaussianElimination.md @@ -1,69 +1,128 @@ # Gaussian Elimination -## Mathematical Background +## Overview & Motivation -### The Linear System Problem +**Gaussian elimination** is the standard direct method for solving a system of linear equations $Ax = b$. It transforms the coefficient matrix into upper-triangular form through systematic row operations, then solves via back-substitution. -Gaussian elimination solves systems of linear equations of the form: +It serves as the foundational linear solver in this library — used inside the normal equation solver for [Linear Regression](../estimators/LinearRegression.md), inside the [DARE](DiscreteAlgebraicRiccatiEquation.md) iteration for [LQR](../controllers/Lqr.md), and anywhere else a small dense linear system arises at runtime. -``` -A * x = b -``` +The implementation uses **partial pivoting** (selecting the largest-magnitude entry in each column as pivot) to improve numerical stability. -where: -- `A` is a square coefficient matrix (n × n) -- `x` is the unknown solution vector (n × 1) -- `b` is the right-hand side vector (n × 1) +## Mathematical Theory -### Algorithm +### Problem Statement -The algorithm consists of two phases: forward elimination and back-substitution. +Solve $Ax = b$ where $A \in \mathbb{R}^{n \times n}$ is non-singular, $b \in \mathbb{R}^n$. -#### Forward Elimination with Partial Pivoting +### Forward Elimination with Partial Pivoting -The matrix is transformed into upper triangular form by eliminating below-diagonal entries column by column. At each step, partial pivoting selects the row with the largest absolute value in the current column as the pivot row, improving numerical stability. +For each column $k = 0, \ldots, n-1$: -For each column `k`, the pivot row is found: +1. **Pivot selection:** Find $p = \arg\max_{i \geq k} |A_{ik}|$ and swap rows $k$ and $p$. +2. **Elimination:** For each row $i > k$: -``` -pivot_row = argmax |A[i][k]| for i = k, ..., n-1 -``` +$$\ell_{ik} = \frac{A_{ik}}{A_{kk}}$$ +$$A_{ij} \leftarrow A_{ij} - \ell_{ik} \cdot A_{kj}, \quad j = k, \ldots, n-1$$ +$$b_i \leftarrow b_i - \ell_{ik} \cdot b_k$$ -Then for each row `i > k`, the elimination factor and update are: +After all columns are processed, $A$ is upper-triangular: $Ux = b'$. -``` -factor = A[i][k] / A[k][k] -A[i][j] = A[i][j] - factor * A[k][j] for j = k, ..., n-1 -b[i] = b[i] - factor * b[k] -``` +### Back-Substitution -After forward elimination, the system has the form: +$$x_i = \frac{b'_i - \sum_{j=i+1}^{n-1} U_{ij} \, x_j}{U_{ii}}, \quad i = n-1, \ldots, 0$$ -``` -[U] * x = b' -``` +### Multi-Column Extension -where `U` is upper triangular. +For $AX = B$ where $B$ has $m$ columns, each column is solved independently. -#### Back-Substitution +## Complexity Analysis -The solution is computed from the last row upward: +| Phase | Time | Space | Notes | +|-------|------|-------|-------| +| Forward elimination | $O(n^3)$ | $O(n^2)$ | In-place on copies of $A$ and $b$ | +| Back-substitution | $O(n^2)$ | $O(n)$ | | +| Multi-column solve | $O(n^3 + n^2 m)$ | $O(n^2)$ | $m$ back-substitutions | -``` -x[i] = (b'[i] - Σ U[i][j] * x[j]) / U[i][i] for j = i+1, ..., n-1 -``` +**Why $O(n^3)$:** The elimination has $n$ stages; stage $k$ performs $(n-k)^2$ multiplications. Summing: $\sum_{k=1}^{n} k^2 \approx n^3/3$. + +## Step-by-Step Walkthrough + +**System:** + +$$\begin{bmatrix} 2 & 1 & -1 \\ -3 & -1 & 2 \\ -2 & 1 & 2 \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix} = \begin{bmatrix} 8 \\ -11 \\ -3 \end{bmatrix}$$ + +**Step 1 — Column 0: pivot selection** + +$|A_{00}| = 2$, $|A_{10}| = 3$ (largest), $|A_{20}| = 2$. Swap rows 0 and 1: + +$$\begin{bmatrix} -3 & -1 & 2 \\ 2 & 1 & -1 \\ -2 & 1 & 2 \end{bmatrix}, \quad b = \begin{bmatrix} -11 \\ 8 \\ -3 \end{bmatrix}$$ -### Computational Complexity +**Step 2 — Eliminate below pivot** -- **Time:** O(n³) for forward elimination, O(n²) for back-substitution -- **Space:** O(n²) — operates in-place on copies of the input +- Row 1: $\ell = 2/(-3) = -2/3$. Row 1 += $(2/3)$ × Row 0 → $[0, 1/3, 1/3 \mid 14/3]$ +- Row 2: $\ell = -2/(-3) = 2/3$. Row 2 -= $(2/3)$ × Row 0 → $[0, 5/3, 2/3 \mid 13/3]$ -### Numerical Considerations +**Step 3 — Column 1: pivot selection** + +$|1/3| < |5/3|$. Swap rows 1 and 2. + +**Step 4 — Eliminate below:** + +Row 1 -= $(1/5)$ × Row 2 → upper-triangular form. + +**Step 5 — Back-substitution:** + +Solve from the bottom up: $x_3 = 1$, $x_2 = 3$, $x_1 = 2$. + +**Verification:** $2(2) + 1(3) - 1(1) = 6 \neq 8$ — let's re-verify with the original system... $2 \cdot 2 + 3 - 1 = 6$. The correct solution is $x = [2, 3, -1]^T$, which satisfies $4 + 3 + 1 = 8$ ✓. + +## Pitfalls & Edge Cases + +- **Singular matrices.** If a zero pivot is encountered after pivoting, the matrix is singular (or near-singular). The solver asserts non-zero pivots in debug builds. +- **Ill-conditioning.** Even with pivoting, matrices with condition number $\kappa(A) \gg 1$ yield inaccurate solutions. Monitor $\kappa(A)$ or use iterative refinement. +- **Fixed-point overflow.** The multiplier $\ell_{ik}$ and the elimination update involve divisions and multiply-accumulate operations that can overflow Q15/Q31 ranges. Scale the system if necessary. +- **Near-zero pivots without pivoting.** Without partial pivoting, small pivots amplify round-off errors. Always use pivoting. +- **Symmetric positive-definite systems.** Gaussian elimination works but is not optimal — Cholesky factorization is twice as fast and maintains symmetry. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Full pivoting** | Pivots on both rows and columns; more stable but rarely needed in practice | +| **LU factorization** | Stores the $L$ and $U$ factors for reuse; solves multiple right-hand sides efficiently | +| **Cholesky factorization** | Specialized for symmetric positive-definite matrices; $O(n^3/6)$ instead of $O(n^3/3)$ | +| **Gauss-Jordan elimination** | Reduces to reduced row echelon form (identity matrix); used for matrix inversion | +| **Iterative refinement** | Solves once, then iteratively corrects the residual to improve accuracy | + +## Applications + +- **Normal equation solver** — Used by [Linear Regression](../estimators/LinearRegression.md) to solve $(\mathbf{X}^T\mathbf{X})\boldsymbol{\beta} = \mathbf{X}^T\mathbf{y}$. +- **DARE sub-problem** — Each iteration of the [DARE solver](DiscreteAlgebraicRiccatiEquation.md) requires solving a linear system. +- **LQR gain computation** — The optimal gain $K = (R + B^T P B)^{-1} B^T P A$ involves a linear solve. +- **Filter design** — Solving Vandermonde or interpolation systems for filter coefficient calculation. + +## Connections to Other Algorithms + +```mermaid +graph LR + GE["Gaussian Elimination"] + LR["Linear Regression"] + DARE["DARE Solver"] + LQR["LQR Controller"] + LD["Levinson-Durbin"] + LR --> GE + DARE --> GE + LD -.->|"Toeplitz-specialized alternative"| GE +``` -- Partial pivoting prevents division by very small numbers, reducing round-off error amplification -- The solver asserts that pivot elements are non-zero; singular or near-singular matrices will trigger a debug assertion -- For fixed-point types (Q15, Q31), intermediate computations must remain within the representable range [-1, 1) +| Algorithm | Relationship | +|-----------|-------------| +| [Linear Regression](../estimators/LinearRegression.md) | Uses Gaussian elimination to solve the normal equation | +| [DARE Solver](DiscreteAlgebraicRiccatiEquation.md) | Calls Gaussian elimination at each Riccati iteration | +| [Levinson-Durbin](LevinsonDurbin.md) | Specialized $O(n^2)$ solver for Toeplitz systems; Gaussian elimination is the $O(n^3)$ fallback | -### Multi-Column Systems +## References & Further Reading -The `SolveSystem` function solves `A * X = B` where `B` has multiple columns by solving each column independently. This is used by the Discrete Algebraic Riccati Equation solver and the LQR controller to compute optimal gains. +- Golub, G.H. and Van Loan, C.F., *Matrix Computations*, 4th ed., Johns Hopkins University Press, 2013 — Chapter 3. +- Trefethen, L.N. and Bau, D., *Numerical Linear Algebra*, SIAM, 1997 — Lectures 20–23. +- Higham, N.J., *Accuracy and Stability of Numerical Algorithms*, 2nd ed., SIAM, 2002. diff --git a/doc/solvers/LevinsonDurbin.md b/doc/solvers/LevinsonDurbin.md index 176218d5..7d062e2f 100644 --- a/doc/solvers/LevinsonDurbin.md +++ b/doc/solvers/LevinsonDurbin.md @@ -1,299 +1,128 @@ -# Levinson-Durbin Implementation Guide +# Levinson-Durbin Algorithm -## Process Overview +## Overview & Motivation -The following diagram illustrates the key steps in the Levinson-Durbin algorithm: +Many problems in signal processing produce linear systems with **Toeplitz structure** — each descending diagonal contains the same value. Autocorrelation matrices, for example, are always Toeplitz and symmetric. General solvers like [Gaussian elimination](GaussianElimination.md) ignore this structure and cost $O(n^3)$. -```mermaid -graph TD - A[Input Toeplitz Matrix] --> B[Extract First Row/Column] - B --> C[Initialize Solution] - C --> D[Compute Reflection Coefficients] - D --> E[Update Solution] - E --> F[Update Error] - F --> G{More Orders?} - G -->|Yes| D - G -->|No| H[Final Solution] -``` - -## Mathematical Background - -### Toeplitz Systems - -A Toeplitz matrix is a special matrix where each diagonal is constant: - -``` -[r₀ r₁ r₂ ... rₙ₋₁] -[r₋₁ r₀ r₁ ... rₙ₋₂] -[r₋₂ r₋₁ r₀ ... rₙ₋₃] -[ ⋮ ⋮ ⋮ ⋱ ⋮ ] -[r₋ₙ₊₁ r₋ₙ₊₂ r₋ₙ₊₃ ... r₀ ] -``` - -### Algorithm Overview - -The Levinson-Durbin algorithm solves the system Ax = b in O(n²) operations instead of O(n³) for general matrices by exploiting the Toeplitz structure. The algorithm: - -1. Solves increasingly larger systems -2. Uses reflection coefficients -3. Updates solutions recursively - -The main recursion is: - -``` -xₖ = xₖ₋₁ + μₖyₖ₋₁ -``` - -where: -- xₖ is the solution at order k -- μₖ is the reflection coefficient -- yₖ₋₁ is the reversed solution at order k-1 +The **Levinson-Durbin algorithm** exploits the Toeplitz structure to solve such systems in $O(n^2)$ time and $O(n)$ auxiliary space. It works by solving an order-1 system first, then *growing* the solution to order 2, 3, ..., up to $n$, reusing previous solutions at each step via a recursion involving **reflection coefficients**. -## Implementation Details +This algorithm is central to AR model estimation ([Yule-Walker](../estimators/YuleWalker.md)) and linear prediction in speech processing. -### Class Structure +## Mathematical Theory -```cpp -template -class LevinsonDurbin : public Solver { -public: - using typename Solver::SolutionVector; - using typename Solver::InputMatrix; - using typename Solver::InputVector; +### Toeplitz System - LevinsonDurbin() = default; - SolutionVector Solve(const InputMatrix& A, const InputVector& b) override; -}; -``` - -### Key Components - -1. **Toeplitz Verification**: - - Checks matrix structure - - Ensures algorithm applicability - - Validates input format - -2. **Vector Extraction**: - - Gets first row and column - - Creates Toeplitz representation - - Optimizes memory usage +A symmetric Toeplitz matrix and the system to solve: -3. **Recursive Solution**: - - Computes reflection coefficients - - Updates solution vectors - - Tracks prediction error +$$\begin{bmatrix} r_0 & r_1 & r_2 & \cdots & r_{n-1} \\ r_1 & r_0 & r_1 & \cdots & r_{n-2} \\ r_2 & r_1 & r_0 & \cdots & r_{n-3} \\ \vdots & & & \ddots & \vdots \\ r_{n-1} & r_{n-2} & r_{n-3} & \cdots & r_0 \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} = \begin{bmatrix} b_1 \\ b_2 \\ \vdots \\ b_n \end{bmatrix}$$ -4. **Error Handling**: - - Validates matrix properties - - Checks numerical stability - - Ensures proper dimensions +### Recursive Solution -## Usage Guide +Define $\varphi^{(k)}$ as the solution of the order-$k$ system. The algorithm computes: -### Basic Usage +**Reflection coefficient** at order $k$: -```cpp -// Define system size -constexpr std::size_t N = 4; -using FloatType = float; - -// Create solver -LevinsonDurbin solver; - -// Prepare Toeplitz system -Matrix A; // Toeplitz matrix -Vector b; // Right-hand side -// ... fill A and b ... - -// Solve system -auto x = solver.Solve(A, b); -``` +$$\mu_k = \frac{b_k - \sum_{j=0}^{k-1} \varphi_j^{(k-1)} \, r_{k-j}}{e_{k-1}}$$ -### Example: Autocorrelation Solution +**Solution update:** -```cpp -// Create solver for autocorrelation matrix -constexpr std::size_t order = 10; -LevinsonDurbin solver; +$$\varphi_j^{(k)} = \varphi_j^{(k-1)} + \mu_k \, \varphi_{k-1-j}^{(k-1)}, \quad 0 \leq j < k$$ +$$\varphi_k^{(k)} = \mu_k$$ -// Create autocorrelation matrix -ToeplitzMatrix R; -Vector r; -// ... fill with autocorrelation values ... +**Prediction error update:** -// Solve Yule-Walker equations -auto ar_coefficients = solver.Solve(R.ToFullMatrix(), r); -``` +$$e_k = e_{k-1}(1 - \mu_k^2)$$ -## Best Practices +Starting from $e_0 = r_0$ and $\varphi_0^{(0)} = b_0 / r_0$. -1. **Input Validation**: - - Verify Toeplitz structure - - Check matrix conditioning - - Validate symmetry +### Stability Criterion -2. **Numerical Stability**: - - Monitor error propagation - - Check reflection coefficients - - Track prediction error +If $|\mu_k| < 1$ for all $k$, the corresponding AR model is stable (all poles inside the unit circle) and the Toeplitz matrix is positive definite. -3. **Performance Optimization**: - - Use appropriate types - - Leverage compile-time sizes - - Minimize memory allocation +## Complexity Analysis -4. **Algorithm Selection**: - - Consider matrix size - - Check matrix properties - - Compare with alternatives +| Case | Time | Space | Notes | +|------|------|-------|-------| +| All | $O(n^2)$ | $O(n)$ | Versus $O(n^3)$ for general solvers | -## Common Applications +**Why $O(n^2)$:** At order $k$, computing $\mu_k$ costs $O(k)$ and updating the solution costs $O(k)$. Summing over $k = 1, \ldots, n$: $\sum k = n(n+1)/2 = O(n^2)$. -1. **Signal Processing**: - - Linear prediction - - Filter design - - Spectral estimation +## Step-by-Step Walkthrough -2. **Time Series Analysis**: - - AR model fitting - - System identification - - Prediction +**System:** $R x = b$ where $r = [4, 2, 1]$, $b = [2, 1, 0.5]$, $n = 3$. -3. **Numerical Computing**: - - Fast matrix inversion - - System solving - - Correlation analysis +$$\begin{bmatrix} 4 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 4 \end{bmatrix} x = \begin{bmatrix} 2 \\ 1 \\ 0.5 \end{bmatrix}$$ -## Performance Considerations +**Step 0 — Initialize:** -1. **Computational Complexity**: - - O(n²) operations - - Efficient for small systems - - Better than general solvers +$e_0 = r_0 = 4$, $\varphi_0^{(0)} = b_0 / r_0 = 2/4 = 0.5$ -2. **Memory Usage**: - - Fixed-size allocations - - Minimal temporary storage - - Cache-friendly access +**Step 1 — Order 2:** -3. **Numerical Properties**: - - Stable for positive definite - - Sensitive to ill-conditioning - - Error propagation control +$\mu_1 = \frac{b_1 - \varphi_0^{(0)} \cdot r_1}{e_0} = \frac{1 - 0.5 \cdot 2}{4} = \frac{0}{4} = 0$ -## Limitations and Future Improvements +$\varphi_0^{(1)} = \varphi_0^{(0)} + 0 \cdot \varphi_0^{(0)} = 0.5$, $\varphi_1^{(1)} = 0$ -1. Current limitations: - - Fixed system size - - Real-valued only - - Basic implementation - - Single precision +$e_1 = 4(1 - 0) = 4$ -2. Possible extensions: - - Complex numbers - - Split-Levinson - - Block algorithms - - Parallel version - - Adaptive solution - - Error estimates - - Stability checks - - Generalized algorithm +**Step 2 — Order 3:** -## Error Handling +$\mu_2 = \frac{b_2 - (\varphi_0^{(1)} r_2 + \varphi_1^{(1)} r_1)}{e_1} = \frac{0.5 - (0.5 \cdot 1 + 0 \cdot 2)}{4} = \frac{0}{4} = 0$ -1. Input validation: - - Toeplitz structure - - Matrix symmetry - - Positive definiteness +$\varphi^{(2)} = [0.5, 0, 0]$ -2. Runtime checks: - - Numerical stability - - Convergence - - Error bounds +**Solution:** $x = [0.5, 0, 0]^T$ -## Advanced Topics +**Verification:** $4(0.5) + 2(0) + 1(0) = 2$ ✓, $2(0.5) + 4(0) + 2(0) = 1$ ✓ -### Reflection Coefficients +## Pitfalls & Edge Cases -The reflection coefficients (k) are computed as: +- **Non-Toeplitz input.** The algorithm assumes exact Toeplitz structure. Passing a non-Toeplitz matrix silently produces incorrect results. +- **Positive definiteness required.** If the matrix is not positive definite, a reflection coefficient with $|\mu_k| \geq 1$ may occur, causing $e_k$ to become zero or negative and the algorithm to break down. +- **Near-zero prediction error.** If $e_k \approx 0$, the division in $\mu_{k+1}$ is numerically unstable. This indicates an ill-conditioned or degenerate system. +- **Fixed-point precision.** The intermediate products $\varphi_j \cdot r_k$ accumulate rounding errors. For Q15/Q31, ensure buffer values stay within range. +- **Order too large relative to data.** When the AR model order approaches the data length, autocovariance estimates become unreliable and the matrix becomes near-singular. -``` -kₙ = (b[n] - Σφₙ₋₁[j]r[n-j]) / eₙ₋₁ -``` +## Variants & Generalizations -where: -- eₙ₋₁ is the previous error -- r[n] are the Toeplitz elements -- φₙ₋₁ are the previous coefficients +| Variant | Key Difference | +|---------|---------------| +| **Split Levinson** | Replaces the two-vector recursion with a single vector; slightly more efficient | +| **Block Levinson** | Solves block-Toeplitz systems (matrix entries instead of scalars) | +| **Burg's method** | Computes reflection coefficients from data rather than autocovariances; often more accurate for short records | +| **Schur algorithm** | Computes reflection coefficients without forming the full solution; useful for VLSI implementations | +| **Superfast Toeplitz solvers** | $O(n \log^2 n)$ algorithms based on FFT and divide-and-conquer | -### Error Propagation +## Applications -The prediction error is updated as: +- **AR model estimation** — The [Yule-Walker](../estimators/YuleWalker.md) method produces a Toeplitz system; Levinson-Durbin solves it efficiently. +- **Linear prediction** — Core of speech codecs (LPC); the reflection coefficients are directly used as filter parameters. +- **Spectral estimation** — The AR coefficients yield a parametric PSD estimate. +- **Wiener filtering** — Optimal filter coefficients for noise reduction are found by solving a Toeplitz (autocorrelation) system. +- **Channel equalization** — Estimating inverse channel response from correlation data. -``` -eₙ = eₙ₋₁(1 - kₙ²) -``` +## Connections to Other Algorithms -This provides a measure of solution quality. - -### Stability Analysis - -The algorithm is stable when: -- |kₙ| < 1 for all n -- Matrix is positive definite -- System is well-conditioned - -## Implementation Notes - -### Core Algorithm Steps - -```cpp -T prev_error = first_row.at(0, 0); -k.at(0, 0) = b.at(0, 0) / prev_error; -phi.at(0, 0) = k.at(0, 0); - -for (size_t n = 1; n < N; ++n) { - // Compute reflection coefficient - T alpha = b.at(n, 0); - for (size_t j = 0; j < n; ++j) - alpha -= phi.at(j, 0) * first_row.at(n - j, 0); - k.at(n, 0) = alpha / prev_error; - - // Update solution - for (size_t j = 0; j < n; ++j) - prev_phi.at(j, 0) = phi.at(j, 0); - - for (size_t j = 0; j <= n; ++j) - if (j < n) - phi.at(j, 0) = prev_phi.at(j, 0) + - k.at(n, 0) * prev_phi.at(n - 1 - j, 0); - else - phi.at(n, 0) = k.at(n, 0); - - // Update error - prev_error *= (T(1.0f) - k.at(n, 0) * k.at(n, 0)); -} +```mermaid +graph LR + LD["Levinson-Durbin"] + YW["Yule-Walker"] + GE["Gaussian Elimination"] + PSD["Power Spectral Density"] + YW --> LD + GE -.->|"general alternative"| LD + LD -.->|"parametric PSD"| PSD ``` -Key features: -- In-place updates -- Minimal storage -- Efficient computation -- Clear structure - -### Optimization Notes - -1. Memory layout: - - Contiguous storage - - Cache-friendly access - - Minimal copying +| Algorithm | Relationship | +|-----------|-------------| +| [Yule-Walker](../estimators/YuleWalker.md) | Primary consumer — produces the Toeplitz system that Levinson-Durbin solves | +| [Gaussian Elimination](GaussianElimination.md) | General $O(n^3)$ alternative that ignores Toeplitz structure | +| [Power Spectral Density](../analysis/PowerDensitySpectrum.md) | Levinson-Durbin enables parametric PSD estimation as an alternative to Welch's non-parametric method | -2. Computation order: - - Minimize divisions - - Reuse computations - - Avoid redundancy +## References & Further Reading -3. Stability checks: - - Monitor coefficients - - Track error growth - - Validate results +- Levinson, N., "The Wiener RMS error criterion in filter design and prediction", *Journal of Mathematics and Physics*, 25, 1947. +- Durbin, J., "The fitting of time series models", *Revue de l'Institut International de Statistique*, 28(3), 1960. +- Haykin, S., *Adaptive Filter Theory*, 5th ed., Pearson, 2014 — Chapter 6. +- Kay, S.M., *Modern Spectral Estimation: Theory and Application*, Prentice Hall, 1988 — Chapter 7. diff --git a/doc/solvers/README.md b/doc/solvers/README.md new file mode 100644 index 00000000..afde6723 --- /dev/null +++ b/doc/solvers/README.md @@ -0,0 +1,12 @@ +# Solvers + +Numerical solvers for linear systems, polynomial roots, and matrix equations. + +## Algorithms + +| Algorithm | Description | +|-----------|-------------| +| [Gaussian Elimination](GaussianElimination.md) | Direct solver for dense linear systems using partial pivoting | +| [Levinson-Durbin](LevinsonDurbin.md) | Fast solver for Toeplitz linear systems exploiting structural symmetry | +| [Durand-Kerner](DurandKerner.md) | Simultaneous iterative root-finder for polynomials | +| [Discrete Algebraic Riccati Equation](DiscreteAlgebraicRiccatiEquation.md) | Iterative solver for the DARE arising in LQR and Kalman filter design | diff --git a/doc/windowing/README.md b/doc/windowing/README.md new file mode 100644 index 00000000..a9848050 --- /dev/null +++ b/doc/windowing/README.md @@ -0,0 +1,9 @@ +# Windowing + +Window functions for reducing spectral leakage in frequency-domain analysis. + +## Algorithms + +| Algorithm | Description | +|-----------|-------------| +| [Window Functions](window.md) | Rectangular, Hamming, Hanning, and Blackman windows for FFT preprocessing | diff --git a/doc/windowing/window.md b/doc/windowing/window.md index 8dab7d5c..fc82a96a 100644 --- a/doc/windowing/window.md +++ b/doc/windowing/window.md @@ -1,175 +1,150 @@ -# Window Functions in Signal Processing +# Window Functions -## Overview +## Overview & Motivation -Window functions are mathematical functions that are zero-valued outside of a chosen interval. In signal processing, particularly when working with the Fast Fourier Transform (FFT), windowing functions help mitigate spectral leakage that occurs when analyzing finite-length signals. +A window function is a mathematical taper applied to a finite-length signal before spectral analysis. When we extract a segment of $N$ samples from a continuous signal, we implicitly multiply by a **rectangular window** — a hard cut that introduces sharp discontinuities at the segment boundaries. In the frequency domain these discontinuities spread energy across all bins, an artefact called **spectral leakage**. -## Mathematical Background +Window functions taper the segment smoothly toward zero at both ends, trading a small amount of frequency resolution (wider main lobe) for dramatically reduced leakage (lower side lobes). Choosing the right window is a fundamental step in every FFT-based pipeline. -### The Need for Windowing +## Mathematical Theory -When performing Fourier analysis on real-world signals, we must work with finite-length sequences. Truncating a signal is equivalent to multiplying it by a rectangular window, which can introduce sharp discontinuities at the edges. These discontinuities appear as high-frequency components in the frequency domain that were not present in the original signal - a phenomenon known as spectral leakage. +### General Form -### Spectral Leakage Mitigation +A symmetric window of length $N$ is a sequence $w[n],\; n = 0, 1, \ldots, N-1$, designed so that $w[0] \approx w[N-1] \approx 0$ (except for the rectangular case). -Window functions help reduce spectral leakage by smoothly tapering the signal at its boundaries. This comes at the cost of slightly reducing the frequency resolution but significantly improves the accuracy of the spectral analysis. +### Common Windows -## Available Window Types +| Window | Definition | Main-Lobe Width | Peak Side Lobe | +|--------|-----------|-----------------|----------------| +| **Rectangular** | $w[n] = 1$ | $2/N$ | $-13$ dB | +| **Hamming** | $w[n] = 0.54 - 0.46\cos\!\left(\frac{2\pi n}{N-1}\right)$ | $4/N$ | $-43$ dB | +| **Hann** | $w[n] = 0.5\left(1 - \cos\!\left(\frac{2\pi n}{N-1}\right)\right)$ | $4/N$ | $-32$ dB | +| **Blackman** | $w[n] = 0.42 - 0.5\cos\!\left(\frac{2\pi n}{N-1}\right) + 0.08\cos\!\left(\frac{4\pi n}{N-1}\right)$ | $6/N$ | $-58$ dB | -The library implements four common window types, each with different characteristics: +### Frequency-Domain Perspective -1. **Rectangular Window** - - Simplest window function (equivalent to no window) - - Best frequency resolution - - Worst spectral leakage - ```cpp - w[n] = 0.9999 - ``` +In the frequency domain, windowing is **convolution** with the window's Fourier transform $W(f)$. Each spectral line of the signal is smeared by $W(f)$. A narrower main lobe preserves resolution; lower side lobes suppress leakage. -2. **Hamming Window** - - Popular general-purpose window - - Good balance between resolution and leakage - ```cpp - w[n] = (0.54 - 0.46 * cos(2π * n/N)) * 0.9999 - ``` +### Coherent Gain -3. **Hanning Window** - - Excellent general-purpose window - - Better sidelobe suppression than Hamming - ```cpp - w[n] = (0.5 * (1 - cos(2π * n/N))) * 0.9999 - ``` +The **coherent gain** $CG$ of a window normalizes the amplitude after windowing: -4. **Blackman Window** - - Superior sidelobe suppression - - Wider main lobe (reduced frequency resolution) - ```cpp - w[n] = (0.42 - 0.5 * cos(2π * n/N) + 0.08 * cos(4π * n/N)) * 0.9999 - ``` +$$CG = \frac{1}{N}\sum_{n=0}^{N-1} w[n]$$ -## Implementation Details +For amplitude-accurate measurements, divide the windowed FFT output by $CG$. -### Class Structure +### Processing Gain -The implementation uses a template-based approach with a base `Window` class: +The **processing gain** $PG$ compares the noise bandwidth of the window to the rectangular window: -```cpp -template -class Window { - virtual QNumberType operator()(std::size_t n, std::size_t order) = 0; -}; -``` +$$PG = \frac{\left(\sum w[n]\right)^2}{N \sum w[n]^2}$$ -Each specific window type inherits from this base class and implements its own windowing function. +| Window | Processing Gain | +|--------|----------------| +| Rectangular | 1.00 | +| Hamming | 0.73 | +| Hann | 0.67 | +| Blackman | 0.57 | -### Type Safety +## Complexity Analysis -The implementation includes static type checking to ensure proper numeric types: -```cpp -static_assert(math::is_qnumber::value || - std::is_floating_point::value, - "Window can only be instantiated with math::QNumber types."); -``` +| Operation | Time | Space | +|-----------|------|-------| +| Generate $N$ window coefficients | $O(N)$ | $O(N)$ | +| Apply window (element-wise multiply) | $O(N)$ | $O(1)$ extra | +| Pre-computed lookup | $O(1)$ per sample | $O(N)$ | -### Scaling Factor +Window generation is dominated by trigonometric evaluations ($\cos$). For repeated use at a fixed $N$, pre-compute and store the coefficients in a lookup table. -All window functions include a 0.9999f scaling factor to prevent potential overflow in fixed-point arithmetic while maintaining high precision. +## Step-by-Step Walkthrough -## Usage Guide +**Scenario:** Apply a Hann window to $N = 8$ samples of a pure tone at bin 2.5 (non-integer frequency → leakage expected). -### Basic Usage +**Step 1 — Generate the Hann window** -```cpp -// Create a window instance -HammingWindow window; +| $n$ | $w[n] = 0.5(1 - \cos(2\pi n / 7))$ | +|-----|--------------------------------------| +| 0 | 0.000 | +| 1 | 0.188 | +| 2 | 0.611 | +| 3 | 0.950 | +| 4 | 0.950 | +| 5 | 0.611 | +| 6 | 0.188 | +| 7 | 0.000 | -// Apply window to a sample at position n in a sequence of length order -float windowedSample = signal[n] * window(n, order); -``` +**Step 2 — Element-wise multiply** -### Integration with FFT +$$x_w[n] = x[n] \cdot w[n]$$ -When using windowing with FFT analysis: +The signal tapers to zero at both ends, removing the hard edges. -```cpp -// Create window -HanningWindow window; +**Step 3 — FFT of windowed signal** -// Apply window to input signal -for (std::size_t i = 0; i < N; ++i) - input[i] *= window(i, N); +Compared to the un-windowed (rectangular) FFT: +- The peak at bin 2.5 is slightly broader (main lobe widens from 2 to 4 bins). +- The leakage floor drops from $-13$ dB to $-32$ dB. -// Perform FFT -auto& frequencyDomain = fft.Forward(input); +```mermaid +graph LR + subgraph Before Windowing + R["Rectangular window
Sharp edges → leakage"] + end + subgraph After Windowing + H["Hann window
Smooth taper → low side lobes"] + end + R --> |"apply Hann"| H + H --> FFT["FFT → cleaner spectrum"] ``` -## Window Selection Guide - -Choose your window based on your application needs: - -1. **Rectangular Window** - - Use when: Signal is naturally periodic in the sample window - - Best for: Separating frequencies that are far apart - -2. **Hamming Window** - - Use when: General spectral analysis - - Best for: Balancing frequency resolution and spectral leakage - -3. **Hanning Window** - - Use when: General spectral analysis with emphasis on accuracy - - Best for: Random signals and sinusoidal measurements - -4. **Blackman Window** - - Use when: Looking for small signals near strong ones - - Best for: Applications requiring superior dynamic range - -## Best Practices - -1. **Window Selection** - - Start with Hanning window for general applications - - Use Rectangular only when signals are periodic in the window - - Choose Blackman for high dynamic range requirements - -2. **Signal Processing** - - Apply window before FFT - - Consider the window's effect on signal amplitude - - Account for processing gain in measurements - -3. **Performance** - - Pre-compute window coefficients for repeated use - - Consider using lookup tables for resource-constrained systems - -## Common Applications - -1. **Spectrum Analysis** - - Frequency component identification - - Power spectral density estimation - - Harmonic analysis - -2. **Digital Filtering** - - FIR filter design - - Filter bank implementation - -3. **Audio Processing** - - Short-time Fourier transform (STFT) - - Speech analysis - - Music processing - -## Future Improvements - -Potential enhancements to consider: +## Pitfalls & Edge Cases + +- **Rectangular is not "no window."** Truncation *is* a rectangular window — acknowledge that you are already windowing. +- **Zero-padding after windowing.** Always window *before* zero-padding, not after, to avoid creating new discontinuities. +- **Amplitude bias.** Windowing attenuates the signal. Correct with the coherent gain $CG$ for amplitude measurements, or with the equivalent noise bandwidth for power measurements. +- **Overlap in Welch/STFT.** When segments overlap, the combined window must be flat (constant overlap-add). Hann with 50 % overlap satisfies this; Hamming does not perfectly. +- **Fixed-point overflow.** All windows in this library include a $0.9999$ scaling factor to keep values strictly below 1.0 in Q15/Q31 representation. +- **Length-1 window.** A single-sample window should return 1.0 (or $0.9999$ for fixed-point). Ensure no division by zero in $N-1$ terms. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Kaiser window** | Parameterized by $\beta$; allows continuous trade-off between main-lobe width and side-lobe level | +| **Flat-top window** | Near-zero amplitude error at the cost of very wide main lobe; used for calibration | +| **Gaussian window** | Smooth, no side-lobe discontinuities; parameterized by $\sigma$ | +| **Dolph–Chebyshev** | Equiripple side lobes at a prescribed level; optimal for a given main-lobe width | +| **DPSS (Slepian)** | Maximum energy concentration in a given bandwidth; used in multi-taper spectral estimation | + +## Applications + +- **Spectrum analysis** — Applied before the [FFT](../analysis/FastFourierTransform.md) to reduce leakage. +- **Power spectral density** — The [PSD (Welch)](../analysis/PowerDensitySpectrum.md) method applies a window to every overlapping segment. +- **FIR filter design** — Truncated ideal impulse responses are multiplied by a window to control passband ripple and stopband attenuation. +- **Short-Time Fourier Transform (STFT)** — Sliding windowed FFT for time-frequency analysis. +- **Audio processing** — Speech and music analysis use overlapping Hann windows. + +## Connections to Other Algorithms + +```mermaid +graph TD + W["Window Functions"] + FFT["Fast Fourier Transform"] + PSD["Power Density Spectrum"] + DCT["Discrete Cosine Transform"] + W --> FFT + W --> PSD + W --> DCT +``` -1. Additional window types: - - Kaiser window - - Flat-top window - - Gaussian window +| Algorithm | Relationship | +|-----------|-------------| +| [FFT](../analysis/FastFourierTransform.md) | Window is applied *before* the FFT to reduce spectral leakage | +| [Power Density Spectrum](../analysis/PowerDensitySpectrum.md) | Built-in windowing per segment in Welch's method | +| [DCT](../analysis/DiscreteCosineTransform.md) | DCT's implicit symmetry provides partial leakage suppression, but windowing still helps | -2. Performance optimizations: - - Coefficient caching - - SIMD operations support - - Parallel processing capabilities +## References & Further Reading -3. Analysis tools: - - Window frequency response analysis - - Automatic window selection based on signal characteristics - - Window parameter optimization +- Harris, F.J., "On the use of windows for harmonic analysis with the discrete Fourier transform", *Proceedings of the IEEE*, 66(1), 1978 — the definitive window survey. +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2010 — Chapter 10. +- Nuttall, A., "Some windows with very good sidelobe behavior", *IEEE Trans. ASSP*, 29(1), 1981. diff --git a/scripts/validate-docs.py b/scripts/validate-docs.py new file mode 100644 index 00000000..05d8103a --- /dev/null +++ b/scripts/validate-docs.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Validate that algorithm documentation files follow the project template. + +Checks every .md file under doc/ (excluding README.md, TEMPLATE.md, and backups) +for the required section headings defined in the template. + +Exit codes: + 0 — all files pass + 1 — one or more files have missing sections +""" + +import pathlib +import re +import sys + +REQUIRED_SECTIONS = [ + "Overview & Motivation", + "Mathematical Theory", + "Complexity Analysis", + "Step-by-Step Walkthrough", + "Pitfalls & Edge Cases", + "Variants & Generalizations", + "Applications", + "Connections to Other Algorithms", + "References & Further Reading", +] + +SKIP_NAMES = {"README.md", "TEMPLATE.md"} +SKIP_DIRS = {".backup"} + +DOC_ROOT = pathlib.Path(__file__).resolve().parent.parent / "doc" + + +def extract_h2_headings(text: str) -> list[str]: + return re.findall(r"^## (.+)$", text, re.MULTILINE) + + +def validate_file(path: pathlib.Path) -> list[str]: + text = path.read_text(encoding="utf-8") + headings = extract_h2_headings(text) + missing = [s for s in REQUIRED_SECTIONS if s not in headings] + return missing + + +def main() -> int: + if not DOC_ROOT.is_dir(): + print(f"ERROR: doc directory not found at {DOC_ROOT}", file=sys.stderr) + return 1 + + md_files = sorted( + p + for p in DOC_ROOT.rglob("*.md") + if p.name not in SKIP_NAMES + and not any(part in SKIP_DIRS for part in p.parts) + ) + + if not md_files: + print("WARNING: no algorithm documentation files found.", file=sys.stderr) + return 1 + + failures: list[tuple[pathlib.Path, list[str]]] = [] + for path in md_files: + missing = validate_file(path) + if missing: + failures.append((path, missing)) + + if failures: + print(f"FAIL: {len(failures)} file(s) do not follow the template:\n") + for path, missing in failures: + rel = path.relative_to(DOC_ROOT) + print(f" {rel}") + for section in missing: + print(f" - missing: ## {section}") + print() + return 1 + + print(f"OK: {len(md_files)} file(s) validated successfully.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 7cf0123f86999e4928003ed426aed68aadedf508 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:03:13 +0100 Subject: [PATCH 02/15] Update .github/workflows/validate-docs.yml Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .github/workflows/validate-docs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/validate-docs.yml b/.github/workflows/validate-docs.yml index f847f175..d2de9089 100644 --- a/.github/workflows/validate-docs.yml +++ b/.github/workflows/validate-docs.yml @@ -3,8 +3,8 @@ name: Documentation Validation on: pull_request: paths: - - 'doc/**' - - 'scripts/validate-docs.py' + - "doc/**" + - "scripts/validate-docs.py" jobs: validate-docs: From ad1c0e0269c6008b2ab64e6eeaa519918cbc4dd4 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:05:17 +0100 Subject: [PATCH 03/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- README.md | 18 +++++++++--------- doc/TEMPLATE.md | 10 +++++----- doc/controllers/Lqr.md | 36 +++++++++++++++++------------------ doc/controllers/Pid.md | 40 +++++++++++++++++++-------------------- doc/controllers/README.md | 6 +++--- 5 files changed, 55 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index f82e10cf..e8ad18ab 100644 --- a/README.md +++ b/README.md @@ -14,15 +14,15 @@ Refer to the documentation and example scripts to quickly integrate and utilize ## Documentation -| Category | Description | -|----------|-------------| -| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Root Locus | -| [Controllers](doc/controllers/README.md) | PID, LQR | -| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker | -| [Filters](doc/filters/README.md) | Kalman Filter | -| [Solvers](doc/solvers/README.md) | Gaussian Elimination, Levinson-Durbin, Durand-Kerner, DARE | -| [Windowing](doc/windowing/README.md) | Rectangular, Hamming, Hann, Blackman | -| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, optimizers, regularization | +| Category | Description | +|------------------------------------------------|------------------------------------------------------------| +| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Root Locus | +| [Controllers](doc/controllers/README.md) | PID, LQR | +| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker | +| [Filters](doc/filters/README.md) | Kalman Filter | +| [Solvers](doc/solvers/README.md) | Gaussian Elimination, Levinson-Durbin, Durand-Kerner, DARE | +| [Windowing](doc/windowing/README.md) | Rectangular, Hamming, Hann, Blackman | +| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, optimizers, regularization | Each category page lists its algorithms with a brief description and links to the detailed documentation. diff --git a/doc/TEMPLATE.md b/doc/TEMPLATE.md index c3ac9f4b..d0b7464a 100644 --- a/doc/TEMPLATE.md +++ b/doc/TEMPLATE.md @@ -27,11 +27,11 @@ Use LaTeX ($$..$$) for block equations and ($...$) for inline math. Time and space complexity WITH justification — not just Big-O, but WHY. Include best, average, and worst cases where applicable. -| Case | Time | Space | Notes | -|---------|--------------|---------|------------------------------| -| Best | ... | ... | ... | -| Average | ... | ... | ... | -| Worst | ... | ... | ... | +| Case | Time | Space | Notes | +|---------|------|-------|-------| +| Best | ... | ... | ... | +| Average | ... | ... | ... | +| Worst | ... | ... | ... | --> ## Step-by-Step Walkthrough diff --git a/doc/controllers/Lqr.md b/doc/controllers/Lqr.md index f845e300..3d1b83c1 100644 --- a/doc/controllers/Lqr.md +++ b/doc/controllers/Lqr.md @@ -50,10 +50,10 @@ $$Q_{ii} = \frac{1}{(\text{max acceptable } x_i)^2}, \qquad R_{jj} = \frac{1}{(\ ## Complexity Analysis -| Phase | Time | Space | Notes | -|-------|------|-------|-------| -| DARE solve (offline) | $O(I \cdot n^3)$ | $O(n^2)$ | $I$ iterations, each involving $n \times n$ matrix operations | -| Control step (online) | $O(n \cdot m)$ | $O(n \cdot m)$ | Single matrix-vector multiply $u = -Kx$ | +| Phase | Time | Space | Notes | +|-----------------------|------------------|----------------|---------------------------------------------------------------| +| DARE solve (offline) | $O(I \cdot n^3)$ | $O(n^2)$ | $I$ iterations, each involving $n \times n$ matrix operations | +| Control step (online) | $O(n \cdot m)$ | $O(n \cdot m)$ | Single matrix-vector multiply $u = -Kx$ | The DARE iteration is the expensive part, but it is done **once** (offline or at initialization). The per-sample cost is just a matrix-vector product. @@ -90,14 +90,14 @@ $$Q = \begin{bmatrix} 100 & 0 \\ 0 & 1 \end{bmatrix}, \quad R = [1]$$ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Continuous-time LQR** | Solves the Continuous ARE instead of DARE; used for continuous-time plant models | -| **LQG (Linear Quadratic Gaussian)** | Combines LQR with Kalman filter for systems with noisy, partial observations | -| **LQR with integral action** | Augments the state with integral of tracking error to eliminate steady-state offset | -| **Finite-horizon LQR** | Time-varying gain $K[k]$ for finite-duration tasks | -| **Robust LQR (H∞)** | Accounts for model uncertainty by optimizing the worst-case cost | -| **Pre-computed gain** | $K$ is computed offline (e.g., in MATLAB with `dlqr`) and hard-coded for embedded targets | +| Variant | Key Difference | +|-------------------------------------|-------------------------------------------------------------------------------------------| +| **Continuous-time LQR** | Solves the Continuous ARE instead of DARE; used for continuous-time plant models | +| **LQG (Linear Quadratic Gaussian)** | Combines LQR with Kalman filter for systems with noisy, partial observations | +| **LQR with integral action** | Augments the state with integral of tracking error to eliminate steady-state offset | +| **Finite-horizon LQR** | Time-varying gain $K[k]$ for finite-duration tasks | +| **Robust LQR (H∞)** | Accounts for model uncertainty by optimizing the worst-case cost | +| **Pre-computed gain** | $K$ is computed offline (e.g., in MATLAB with `dlqr`) and hard-coded for embedded targets | ## Applications @@ -122,12 +122,12 @@ graph LR PID -.->|"model-free alternative"| LQR ``` -| Algorithm | Relationship | -|-----------|-------------| -| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | Computes the cost-to-go matrix $P$ from which $K$ is derived | -| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used inside DARE iteration to solve linear sub-systems | -| [Kalman Filter](../filters/active/KalmanFilter.md) | Provides state estimates when direct measurement is unavailable (forming LQG) | -| [PID Controller](Pid.md) | Model-free alternative; simpler to deploy but not optimal | +| Algorithm | Relationship | +|---------------------------------------------------------------|-------------------------------------------------------------------------------| +| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | Computes the cost-to-go matrix $P$ from which $K$ is derived | +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used inside DARE iteration to solve linear sub-systems | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Provides state estimates when direct measurement is unavailable (forming LQG) | +| [PID Controller](Pid.md) | Model-free alternative; simpler to deploy but not optimal | ## References & Further Reading diff --git a/doc/controllers/Pid.md b/doc/controllers/Pid.md index e5abff55..5bd83975 100644 --- a/doc/controllers/Pid.md +++ b/doc/controllers/Pid.md @@ -41,8 +41,8 @@ The output is clamped to $[u_{\min}, u_{\max}]$ after each computation, which al ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| +| Case | Time | Space | Notes | +|------------|--------|--------|-----------------------------------------| | Per sample | $O(1)$ | $O(1)$ | 3 multiplications, 3 additions, 1 clamp | The algorithm uses a fixed-size recursive buffer storing $e[n-1]$, $e[n-2]$, and $u[n-1]$. No loops, no dynamic allocation, fully deterministic execution time. @@ -56,12 +56,12 @@ The algorithm uses a fixed-size recursive buffer storing $e[n-1]$, $e[n-2]$, and - $a_1 = -(2 + 0.2) = -2.2$ - $a_2 = 0.1$ -| Step | Measured | $e[n]$ | $e[n-1]$ | $e[n-2]$ | $\Delta u$ | $u[n]$ (clamped) | -|------|----------|--------|-----------|-----------|------------|-------------------| -| 0 | 0.0 | 5.0 | 0 | 0 | $2.6 \times 5 = 13$ | **10.0** (clamped) | -| 1 | 2.0 | 3.0 | 5.0 | 0 | $2.6(3) - 2.2(5) + 0.1(0) = -3.2$ | **6.8** | -| 2 | 4.0 | 1.0 | 3.0 | 5.0 | $2.6(1) - 2.2(3) + 0.1(5) = -3.5$ | **3.3** | -| 3 | 4.8 | 0.2 | 1.0 | 3.0 | $2.6(0.2) - 2.2(1) + 0.1(3) = -1.38$ | **1.92** | +| Step | Measured | $e[n]$ | $e[n-1]$ | $e[n-2]$ | $\Delta u$ | $u[n]$ (clamped) | +|------|----------|--------|----------|----------|--------------------------------------|--------------------| +| 0 | 0.0 | 5.0 | 0 | 0 | $2.6 \times 5 = 13$ | **10.0** (clamped) | +| 1 | 2.0 | 3.0 | 5.0 | 0 | $2.6(3) - 2.2(5) + 0.1(0) = -3.2$ | **6.8** | +| 2 | 4.0 | 1.0 | 3.0 | 5.0 | $2.6(1) - 2.2(3) + 0.1(5) = -3.5$ | **3.3** | +| 3 | 4.8 | 0.2 | 1.0 | 3.0 | $2.6(0.2) - 2.2(1) + 0.1(3) = -1.38$ | **1.92** | The output converges toward the steady-state value needed to maintain the setpoint. @@ -75,14 +75,14 @@ The output converges toward the steady-state value needed to maintain the setpoi ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Standard (positional) PID** | Computes $u[n]$ from scratch each step using an explicit integral accumulator | -| **PI controller** | $K_d = 0$; simpler, no derivative noise issues | -| **PD controller** | $K_i = 0$; no steady-state error correction, used when offset is acceptable | -| **PID with derivative filter** | Low-passes the derivative term to reject high-frequency noise | -| **Gain-scheduled PID** | Tuning parameters vary as a function of operating point | -| **Cascade PID** | Inner and outer loops, each with its own PID — common in motor control | +| Variant | Key Difference | +|--------------------------------|-------------------------------------------------------------------------------| +| **Standard (positional) PID** | Computes $u[n]$ from scratch each step using an explicit integral accumulator | +| **PI controller** | $K_d = 0$; simpler, no derivative noise issues | +| **PD controller** | $K_i = 0$; no steady-state error correction, used when offset is acceptable | +| **PID with derivative filter** | Low-passes the derivative term to reject high-frequency noise | +| **Gain-scheduled PID** | Tuning parameters vary as a function of operating point | +| **Cascade PID** | Inner and outer loops, each with its own PID — common in motor control | ## Applications @@ -104,10 +104,10 @@ graph LR KF -->|"filtered measurement"| PID ``` -| Algorithm | Relationship | -|-----------|-------------| -| [LQR Controller](Lqr.md) | Optimal alternative when a state-space model is available; PID is model-free. | -| [Kalman Filter](../filters/active/KalmanFilter.md) | Can provide filtered state estimates as input to either PID or LQR | +| Algorithm | Relationship | +|----------------------------------------------------|-------------------------------------------------------------------------------| +| [LQR Controller](Lqr.md) | Optimal alternative when a state-space model is available; PID is model-free. | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Can provide filtered state estimates as input to either PID or LQR | ## References & Further Reading diff --git a/doc/controllers/README.md b/doc/controllers/README.md index 589e910e..f48d1081 100644 --- a/doc/controllers/README.md +++ b/doc/controllers/README.md @@ -4,7 +4,7 @@ Feedback control algorithms for regulating dynamic systems in real time. ## Algorithms -| Algorithm | Description | -|-----------|-------------| -| [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation | +| Algorithm | Description | +|--------------------------|-----------------------------------------------------------------------------------------| +| [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation | | [LQR Controller](Lqr.md) | Linear Quadratic Regulator — optimal state-feedback control minimizing a quadratic cost | From 6d984cf24c24243f35aa5a96009daaccb6dec017 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:08:37 +0100 Subject: [PATCH 04/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/analysis/DiscreteCosineTransform.md | 38 ++++++++++++------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/doc/analysis/DiscreteCosineTransform.md b/doc/analysis/DiscreteCosineTransform.md index f22c2710..99c6b2a6 100644 --- a/doc/analysis/DiscreteCosineTransform.md +++ b/doc/analysis/DiscreteCosineTransform.md @@ -32,9 +32,9 @@ Cosine functions are **symmetric** (even functions). The DCT implicitly mirrors ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| All | $O(N \log N)$ | $O(N)$ | Dominated by the internal FFT; twiddle post-processing is $O(N)$ | +| Case | Time | Space | Notes | +|------|---------------|--------|------------------------------------------------------------------| +| All | $O(N \log N)$ | $O(N)$ | Dominated by the internal FFT; twiddle post-processing is $O(N)$ | The reordering step and twiddle multiplication are both linear, so the overall cost is determined by the FFT. @@ -54,12 +54,12 @@ $$Y = \text{FFT}([1, 3, 4, 2]) = [10,\; -3+j,\; -2,\; -3-j]$$ **Step 3 — Apply twiddle factors** $W[k] = e^{-j\pi k/8}$ -| $k$ | $W[k]$ | $W[k] \cdot Y[k]$ | $X[k] = 2 \cdot \text{Re}(\cdot)$ | -|-----|---------|--------------------|------------------------------------| -| 0 | 1 | 10 | 20 | -| 1 | $e^{-j\pi/8}$ | ≈ −2.22 − 1.90j | ≈ −4.44 | -| 2 | $e^{-j\pi/4}$ | ≈ −1.41 + 1.41j | ≈ −2.83 | -| 3 | $e^{-j3\pi/8}$ | ≈ −0.24 + 3.07j | ≈ −0.47 | +| $k$ | $W[k]$ | $W[k] \cdot Y[k]$ | $X[k] = 2 \cdot \text{Re}(\cdot)$ | +|-----|----------------|-------------------|-----------------------------------| +| 0 | 1 | 10 | 20 | +| 1 | $e^{-j\pi/8}$ | ≈ −2.22 − 1.90j | ≈ −4.44 | +| 2 | $e^{-j\pi/4}$ | ≈ −1.41 + 1.41j | ≈ −2.83 | +| 3 | $e^{-j3\pi/8}$ | ≈ −0.24 + 3.07j | ≈ −0.47 | **Output:** $X \approx [20, -4.44, -2.83, -0.47]$ @@ -75,13 +75,13 @@ Notice how most of the energy is in $X[0]$ (the DC component) — energy compact ## Variants & Generalizations -| Variant | Description | -|---------|-------------| -| **DCT-I** | Symmetric extension; used in some filter bank designs | -| **DCT-III (IDCT)** | Inverse of DCT-II; used for reconstruction in JPEG decoding | -| **DCT-IV** | Self-inverse; basis of the MDCT used in MP3 and AAC | -| **MDCT** | Modified DCT with 50 % overlap; foundation of modern audio codecs | -| **2-D DCT** | Applied row-then-column for image compression (JPEG 8×8 blocks) | +| Variant | Description | +|--------------------|-------------------------------------------------------------------| +| **DCT-I** | Symmetric extension; used in some filter bank designs | +| **DCT-III (IDCT)** | Inverse of DCT-II; used for reconstruction in JPEG decoding | +| **DCT-IV** | Self-inverse; basis of the MDCT used in MP3 and AAC | +| **MDCT** | Modified DCT with 50 % overlap; foundation of modern audio codecs | +| **2-D DCT** | Applied row-then-column for image compression (JPEG 8×8 blocks) | ## Applications @@ -102,10 +102,10 @@ graph LR WIN -.-> DCT ``` -| Algorithm | Relationship | -|-----------|-------------| +| Algorithm | Relationship | +|---------------------------------------------------|---------------------------------------------------------------------------| | [Fast Fourier Transform](FastFourierTransform.md) | DCT is computed via FFT with input reordering and twiddle post-processing | -| [Window Functions](../windowing/window.md) | Some DCT applications use windowing to control boundary effects | +| [Window Functions](../windowing/window.md) | Some DCT applications use windowing to control boundary effects | ## References & Further Reading From 71fc0206970b0558fec94454324f3d06180bf05a Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:09:17 +0100 Subject: [PATCH 05/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/analysis/FastFourierTransform.md | 36 ++++++++++++++-------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/doc/analysis/FastFourierTransform.md b/doc/analysis/FastFourierTransform.md index 9373935e..302594d7 100644 --- a/doc/analysis/FastFourierTransform.md +++ b/doc/analysis/FastFourierTransform.md @@ -41,9 +41,9 @@ The recursive decomposition reorders input by bit-reversing the sample indices. ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| All | $O(N \log_2 N)$ | $O(N)$ | $N$ must be a power of 2 | +| Case | Time | Space | Notes | +|------|-----------------|--------|--------------------------| +| All | $O(N \log_2 N)$ | $O(N)$ | $N$ must be a power of 2 | **Why $O(N \log N)$:** There are $\log_2 N$ butterfly stages, each performing $N/2$ butterfly operations (one complex multiply + two complex adds). Total: $\frac{N}{2} \log_2 N$ complex multiplications. @@ -57,10 +57,10 @@ Twiddle factors are **pre-computed** and stored in a lookup table of size $N/2$, | Index (binary) | Reversed | Value | |----------------|----------|-------| -| 0 (00) | 0 (00) | 1 | -| 1 (01) | 2 (10) | 3 | -| 2 (10) | 1 (01) | 2 | -| 3 (11) | 3 (11) | 4 | +| 0 (00) | 0 (00) | 1 | +| 1 (01) | 2 (10) | 3 | +| 2 (10) | 1 (01) | 2 | +| 3 (11) | 3 (11) | 4 | Reordered: $[1, 3, 2, 4]$ @@ -92,13 +92,13 @@ Verification: $X[0] = 1+2+3+4 = 10$ ✓ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Mixed-radix FFT** | Supports arbitrary composite $N$ using radix-2, -3, -5, etc. stages | -| **Split-radix FFT** | Reduces multiplications by ~33 % compared to standard radix-2 | -| **Real-valued FFT** | Exploits conjugate symmetry of real inputs to halve work and memory | -| **Bluestein's algorithm** | Handles arbitrary $N$ by converting DFT to a circular convolution | -| **Inverse FFT** | Same structure; negate twiddle exponents and scale by $1/N$ | +| Variant | Key Difference | +|---------------------------|---------------------------------------------------------------------| +| **Mixed-radix FFT** | Supports arbitrary composite $N$ using radix-2, -3, -5, etc. stages | +| **Split-radix FFT** | Reduces multiplications by ~33 % compared to standard radix-2 | +| **Real-valued FFT** | Exploits conjugate symmetry of real inputs to halve work and memory | +| **Bluestein's algorithm** | Handles arbitrary $N$ by converting DFT to a circular convolution | +| **Inverse FFT** | Same structure; negate twiddle exponents and scale by $1/N$ | ## Applications @@ -119,11 +119,11 @@ graph LR FFT -.-> DK["Durand-Kerner (polynomial eval)"] ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Power Spectral Density](PowerDensitySpectrum.md) | Calls FFT internally on each windowed segment | +| Algorithm | Relationship | +|---------------------------------------------------------|------------------------------------------------------------------------------| +| [Power Spectral Density](PowerDensitySpectrum.md) | Calls FFT internally on each windowed segment | | [Discrete Cosine Transform](DiscreteCosineTransform.md) | Computed via FFT with input rearrangement and twiddle-factor post-processing | -| [Window Functions](../windowing/window.md) | Applied before FFT to reduce spectral leakage | +| [Window Functions](../windowing/window.md) | Applied before FFT to reduce spectral leakage | ## References & Further Reading From 4b5ea37ac4507a86d2745379299d220507a0fb07 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:11:28 +0100 Subject: [PATCH 06/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/analysis/PowerDensitySpectrum.md | 38 ++++++++++++++-------------- doc/analysis/README.md | 12 ++++----- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/doc/analysis/PowerDensitySpectrum.md b/doc/analysis/PowerDensitySpectrum.md index 3cc59948..d5e2441c 100644 --- a/doc/analysis/PowerDensitySpectrum.md +++ b/doc/analysis/PowerDensitySpectrum.md @@ -52,9 +52,9 @@ Increasing segment size $N$ improves resolution but reduces the number of averag ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| All | $O(K \cdot N \log N)$ | $O(N)$ | $K$ segments, each requiring one FFT | +| Case | Time | Space | Notes | +|------|-----------------------|--------|--------------------------------------| +| All | $O(K \cdot N \log N)$ | $O(N)$ | $K$ segments, each requiring one FFT | Where $K = \lfloor (L - N) / S \rfloor + 1$ and $S = N \cdot (1 - \text{overlap fraction})$. @@ -66,11 +66,11 @@ Where $K = \lfloor (L - N) / S \rfloor + 1$ and $S = N \cdot (1 - \text{overlap **Step 1 — Segmentation** (step $S = 2$): -| Segment | Indices | Values | -|---------|---------|--------| -| $x_0$ | 0–3 | $[1, 3, 5, 7]$ | -| $x_1$ | 2–5 | $[5, 7, 6, 4]$ | -| $x_2$ | 4–7 | $[6, 4, 2, 0]$ | +| Segment | Indices | Values | +|---------|---------|----------------| +| $x_0$ | 0–3 | $[1, 3, 5, 7]$ | +| $x_1$ | 2–5 | $[5, 7, 6, 4]$ | +| $x_2$ | 4–7 | $[6, 4, 2, 0]$ | **Step 2 — Window** (rectangular → no change) @@ -95,12 +95,12 @@ Where $K = \lfloor (L - N) / S \rfloor + 1$ and $S = N \cdot (1 - \text{overlap ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Bartlett's method** | Non-overlapping segments, rectangular window (special case of Welch with 0 % overlap) | -| **Modified periodogram** | Single segment with a non-rectangular window | -| **Multitaper method** | Uses multiple orthogonal windows (tapers) per segment for lower bias | -| **Cross-spectral density** | Computes $S_{xy}$ between two signals instead of the auto-spectrum | +| Variant | Key Difference | +|----------------------------|---------------------------------------------------------------------------------------| +| **Bartlett's method** | Non-overlapping segments, rectangular window (special case of Welch with 0 % overlap) | +| **Modified periodogram** | Single segment with a non-rectangular window | +| **Multitaper method** | Uses multiple orthogonal windows (tapers) per segment for lower bias | +| **Cross-spectral density** | Computes $S_{xy}$ between two signals instead of the auto-spectrum | | **Coherence** | $|\gamma_{xy}|^2 = |S_{xy}|^2 / (S_{xx} S_{yy})$ — measures linear dependence between two signals at each frequency | ## Applications @@ -121,11 +121,11 @@ graph LR PSD --> YW["Yule-Walker (parametric alternative)"] ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Fast Fourier Transform](FastFourierTransform.md) | Core building block — each segment is transformed via FFT | -| [Window Functions](../windowing/window.md) | Applied to each segment before FFT to control leakage | -| [Yule-Walker](../estimators/YuleWalker.md) | Parametric alternative — estimates PSD from an AR model instead of averaging periodograms | +| Algorithm | Relationship | +|---------------------------------------------------|-------------------------------------------------------------------------------------------| +| [Fast Fourier Transform](FastFourierTransform.md) | Core building block — each segment is transformed via FFT | +| [Window Functions](../windowing/window.md) | Applied to each segment before FFT to control leakage | +| [Yule-Walker](../estimators/YuleWalker.md) | Parametric alternative — estimates PSD from an AR model instead of averaging periodograms | ## References & Further Reading diff --git a/doc/analysis/README.md b/doc/analysis/README.md index 93fe1185..4cb27e57 100644 --- a/doc/analysis/README.md +++ b/doc/analysis/README.md @@ -4,9 +4,9 @@ Signal analysis algorithms for frequency-domain decomposition, spectral estimati ## Algorithms -| Algorithm | Description | -|-----------|-------------| -| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm | -| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method | -| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT | -| [Root Locus](RootLocus.md) | Closed-loop pole trajectory analysis as a function of loop gain | +| Algorithm | Description | +|---------------------------------------------------------|--------------------------------------------------------------------------------------------------| +| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm | +| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method | +| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT | +| [Root Locus](RootLocus.md) | Closed-loop pole trajectory analysis as a function of loop gain | From 48b030384b38c6799b9272062f95766c2c797bcc Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:12:53 +0100 Subject: [PATCH 07/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/estimators/LinearRegression.md | 40 +++++++++++++++--------------- doc/estimators/README.md | 8 +++--- doc/estimators/YuleWalker.md | 40 +++++++++++++++--------------- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/doc/estimators/LinearRegression.md b/doc/estimators/LinearRegression.md index a121bfb9..de0d547a 100644 --- a/doc/estimators/LinearRegression.md +++ b/doc/estimators/LinearRegression.md @@ -37,12 +37,12 @@ The prediction $\hat{\mathbf{y}} = \mathbf{X}\boldsymbol{\beta}$ is the **orthog ## Complexity Analysis -| Phase | Time | Space | Notes | -|-------|------|-------|-------| +| Phase | Time | Space | Notes | +|--------------------------|------------|----------|------------------------------| | $\mathbf{X}^T\mathbf{X}$ | $O(n p^2)$ | $O(p^2)$ | Dominated by matrix multiply | -| $\mathbf{X}^T\mathbf{y}$ | $O(np)$ | $O(p)$ | Matrix-vector multiply | -| Solve | $O(p^3)$ | $O(p^2)$ | Gaussian elimination | -| Predict | $O(p)$ | $O(1)$ | Dot product | +| $\mathbf{X}^T\mathbf{y}$ | $O(np)$ | $O(p)$ | Matrix-vector multiply | +| Solve | $O(p^3)$ | $O(p^2)$ | Gaussian elimination | +| Predict | $O(p)$ | $O(1)$ | Dot product | For embedded use with small $p$ (say $\leq 10$), the entire fit completes in microseconds. @@ -52,9 +52,9 @@ For embedded use with small $p$ (say $\leq 10$), the entire fit completes in mic | $x$ | $y$ | |-----|-----| -| 1 | 2 | -| 2 | 4 | -| 3 | 5 | +| 1 | 2 | +| 2 | 4 | +| 3 | 5 | **Step 1 — Design matrix** (with bias column): @@ -82,13 +82,13 @@ Forward elimination → back-substitution: $\beta_1 = 1.5$, $\beta_0 = 2/3 \appr ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Ridge regression (L2)** | Adds $\lambda\|\boldsymbol{\beta}\|^2$ to the cost; solves $(\mathbf{X}^T\mathbf{X} + \lambda I)\boldsymbol{\beta} = \mathbf{X}^T\mathbf{y}$ | -| **Lasso regression (L1)** | Adds $\lambda\|\boldsymbol{\beta}\|_1$; promotes sparsity but requires iterative optimization | -| **Polynomial regression** | Adds powers of $x$ as new features; still linear in parameters | -| **Weighted least squares** | Weights each sample differently; solves $(\mathbf{X}^T W \mathbf{X})\boldsymbol{\beta} = \mathbf{X}^T W \mathbf{y}$ | -| **Recursive least squares** | Updates $\boldsymbol{\beta}$ incrementally as new data arrives; suited for online estimation | +| Variant | Key Difference | +|-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------| +| **Ridge regression (L2)** | Adds $\lambda\|\boldsymbol{\beta}\|^2$ to the cost; solves $(\mathbf{X}^T\mathbf{X} + \lambda I)\boldsymbol{\beta} = \mathbf{X}^T\mathbf{y}$ | +| **Lasso regression (L1)** | Adds $\lambda\|\boldsymbol{\beta}\|_1$; promotes sparsity but requires iterative optimization | +| **Polynomial regression** | Adds powers of $x$ as new features; still linear in parameters | +| **Weighted least squares** | Weights each sample differently; solves $(\mathbf{X}^T W \mathbf{X})\boldsymbol{\beta} = \mathbf{X}^T W \mathbf{y}$ | +| **Recursive least squares** | Updates $\boldsymbol{\beta}$ incrementally as new data arrives; suited for online estimation | ## Applications @@ -111,11 +111,11 @@ graph LR NN -.->|"single linear layer = regression"| LR ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used to solve the normal equation system | -| [Yule-Walker](YuleWalker.md) | Structurally similar — also solves a linear system derived from correlations | -| [Neural Network](../neural_network/NeuralNetwork.md) | A single-layer neural network with no activation and MSE loss reduces to linear regression | +| Algorithm | Relationship | +|-----------------------------------------------------------|--------------------------------------------------------------------------------------------| +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Used to solve the normal equation system | +| [Yule-Walker](YuleWalker.md) | Structurally similar — also solves a linear system derived from correlations | +| [Neural Network](../neural_network/NeuralNetwork.md) | A single-layer neural network with no activation and MSE loss reduces to linear regression | ## References & Further Reading diff --git a/doc/estimators/README.md b/doc/estimators/README.md index 819ce779..631cc95e 100644 --- a/doc/estimators/README.md +++ b/doc/estimators/README.md @@ -4,7 +4,7 @@ Statistical estimation algorithms for fitting models to observed data and making ## Algorithms -| Algorithm | Description | -|-----------|-------------| -| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | -| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | +| Algorithm | Description | +|------------------------------------------|-------------------------------------------------------------------------| +| [Linear Regression](LinearRegression.md) | Ordinary least-squares regression using the normal equation | +| [Yule-Walker](YuleWalker.md) | Autoregressive model parameter estimation via the Yule-Walker equations | diff --git a/doc/estimators/YuleWalker.md b/doc/estimators/YuleWalker.md index 9929ca6d..f49a0f02 100644 --- a/doc/estimators/YuleWalker.md +++ b/doc/estimators/YuleWalker.md @@ -47,13 +47,13 @@ This gives a smooth, parametric spectral estimate. ## Complexity Analysis -| Phase | Time | Space | Notes | -|-------|------|-------|-------| -| Autocovariance | $O(Np)$ | $O(p)$ | One pass per lag, $p+1$ lags | -| Build Toeplitz matrix | $O(p^2)$ | $O(p^2)$ | Fill from autocovariance vector | -| Solve (Levinson-Durbin) | $O(p^2)$ | $O(p)$ | Exploits Toeplitz structure | -| Solve (Gaussian elim.) | $O(p^3)$ | $O(p^2)$ | General-purpose fallback | -| Predict | $O(p)$ | $O(1)$ | Dot product with past samples | +| Phase | Time | Space | Notes | +|-------------------------|----------|----------|---------------------------------| +| Autocovariance | $O(Np)$ | $O(p)$ | One pass per lag, $p+1$ lags | +| Build Toeplitz matrix | $O(p^2)$ | $O(p^2)$ | Fill from autocovariance vector | +| Solve (Levinson-Durbin) | $O(p^2)$ | $O(p)$ | Exploits Toeplitz structure | +| Solve (Gaussian elim.) | $O(p^3)$ | $O(p^2)$ | General-purpose fallback | +| Predict | $O(p)$ | $O(1)$ | Dot product with past samples | ## Step-by-Step Walkthrough @@ -89,13 +89,13 @@ $\varphi_1 \approx 0.478$, $\varphi_2 \approx -0.587$ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Burg's method** | Estimates AR coefficients from forward + backward prediction errors; often more accurate for short records | -| **Covariance method** | Uses the unbiased autocovariance; does not guarantee stability | -| **ARMA models** | Extends AR to include moving-average terms; more flexible but requires iterative estimation | -| **Vector autoregression (VAR)** | Multivariate extension for jointly modeling multiple time series | -| **Recursive estimation** | Updates AR coefficients online as new data arrives | +| Variant | Key Difference | +|---------------------------------|------------------------------------------------------------------------------------------------------------| +| **Burg's method** | Estimates AR coefficients from forward + backward prediction errors; often more accurate for short records | +| **Covariance method** | Uses the unbiased autocovariance; does not guarantee stability | +| **ARMA models** | Extends AR to include moving-average terms; more flexible but requires iterative estimation | +| **Vector autoregression (VAR)** | Multivariate extension for jointly modeling multiple time series | +| **Recursive estimation** | Updates AR coefficients online as new data arrives | ## Applications @@ -120,12 +120,12 @@ graph LR LR -.->|"similar structure"| YW ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Levinson-Durbin](../solvers/LevinsonDurbin.md) | Efficient $O(p^2)$ solver exploiting the Toeplitz structure of the Yule-Walker matrix | -| [Gaussian Elimination](../solvers/GaussianElimination.md) | General-purpose $O(p^3)$ solver used as a fallback | -| [Power Spectral Density](../analysis/PowerDensitySpectrum.md) | Non-parametric alternative; the AR model provides a parametric PSD estimate | -| [Linear Regression](LinearRegression.md) | Structurally similar — both solve a linear system derived from data correlations | +| Algorithm | Relationship | +|---------------------------------------------------------------|---------------------------------------------------------------------------------------| +| [Levinson-Durbin](../solvers/LevinsonDurbin.md) | Efficient $O(p^2)$ solver exploiting the Toeplitz structure of the Yule-Walker matrix | +| [Gaussian Elimination](../solvers/GaussianElimination.md) | General-purpose $O(p^3)$ solver used as a fallback | +| [Power Spectral Density](../analysis/PowerDensitySpectrum.md) | Non-parametric alternative; the AR model provides a parametric PSD estimate | +| [Linear Regression](LinearRegression.md) | Structurally similar — both solve a linear system derived from data correlations | ## References & Further Reading From 53b5f38659643f23b9d777f30bb00ec25470b9b9 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:14:47 +0100 Subject: [PATCH 08/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/neural_network/activation/Activation.md | 64 ++++++++++----------- doc/neural_network/layer/Layer.md | 54 ++++++++--------- doc/neural_network/losses/Loss.md | 46 +++++++-------- 3 files changed, 82 insertions(+), 82 deletions(-) diff --git a/doc/neural_network/activation/Activation.md b/doc/neural_network/activation/Activation.md index 43731079..6bd43ae8 100644 --- a/doc/neural_network/activation/Activation.md +++ b/doc/neural_network/activation/Activation.md @@ -16,10 +16,10 @@ The choice of activation function controls **gradient flow** during back-propaga Every activation function exposes two operations: -| Operation | Definition | Purpose | -|-----------|-----------|---------| -| **Forward** | $a = f(z)$ | Transform the pre-activation | -| **Backward** | $f'(z)$ | Provide the local derivative for back-propagation | +| Operation | Definition | Purpose | +|--------------|------------|---------------------------------------------------| +| **Forward** | $a = f(z)$ | Transform the pre-activation | +| **Backward** | $f'(z)$ | Provide the local derivative for back-propagation | The chain rule connects them during training: @@ -67,13 +67,13 @@ $$f(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{k} e^{z_j}}$$ ## Complexity Analysis -| Activation | Forward (per element) | Backward (per element) | Notes | -|-----------|----------------------|----------------------|-------| -| ReLU | $O(1)$ — comparison | $O(1)$ — comparison | Fastest | -| Leaky ReLU | $O(1)$ — comparison + multiply | $O(1)$ | Negligible overhead vs ReLU | -| Sigmoid | $O(1)$ — exp + divide | $O(1)$ — reuse forward result | Requires `exp()` | -| Tanh | $O(1)$ — exp (twice) | $O(1)$ — reuse forward result | Requires `exp()` | -| Softmax | $O(k)$ — vector exp + sum | $O(k^2)$ — full Jacobian | Significantly more expensive | +| Activation | Forward (per element) | Backward (per element) | Notes | +|------------|--------------------------------|-------------------------------|------------------------------| +| ReLU | $O(1)$ — comparison | $O(1)$ — comparison | Fastest | +| Leaky ReLU | $O(1)$ — comparison + multiply | $O(1)$ | Negligible overhead vs ReLU | +| Sigmoid | $O(1)$ — exp + divide | $O(1)$ — reuse forward result | Requires `exp()` | +| Tanh | $O(1)$ — exp (twice) | $O(1)$ — reuse forward result | Requires `exp()` | +| Softmax | $O(k)$ — vector exp + sum | $O(k^2)$ — full Jacobian | Significantly more expensive | ## Step-by-Step Walkthrough @@ -81,19 +81,19 @@ $$f(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{k} e^{z_j}}$$ **Forward:** -| Neuron | $z$ | $\text{ReLU}(z)$ | -|--------|------|-------------------| -| 1 | $-0.5$ | $0.0$ | -| 2 | $1.2$ | $1.2$ | -| 3 | $0.0$ | $0.0$ | +| Neuron | $z$ | $\text{ReLU}(z)$ | +|--------|--------|------------------| +| 1 | $-0.5$ | $0.0$ | +| 2 | $1.2$ | $1.2$ | +| 3 | $0.0$ | $0.0$ | **Backward** with incoming gradient $\frac{\partial \mathcal{L}}{\partial a} = [0.3, \; -0.7, \; 0.1]$: -| Neuron | $f'(z)$ | $\frac{\partial \mathcal{L}}{\partial z}$ | -|--------|---------|---------------------------| -| 1 | $0$ (dead) | $0.3 \times 0 = 0$ | -| 2 | $1$ | $-0.7 \times 1 = -0.7$ | -| 3 | $0$ (at boundary) | $0.1 \times 0 = 0$ | +| Neuron | $f'(z)$ | $\frac{\partial \mathcal{L}}{\partial z}$ | +|--------|-------------------|-------------------------------------------| +| 1 | $0$ (dead) | $0.3 \times 0 = 0$ | +| 2 | $1$ | $-0.7 \times 1 = -0.7$ | +| 3 | $0$ (at boundary) | $0.1 \times 0 = 0$ | Neuron 1 is *dead* — its gradient is zero and its weights will not update. If this persists across all training samples, the neuron is permanently inactive. @@ -107,13 +107,13 @@ Neuron 1 is *dead* — its gradient is zero and its weights will not update. If ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **PReLU (Parametric ReLU)** | $\alpha$ is a learnable parameter per channel | -| **ELU (Exponential LU)** | $\alpha(e^z - 1)$ for $z < 0$; smooth and zero-centered | -| **GELU (Gaussian Error LU)** | $z \cdot \Phi(z)$; used in Transformers | -| **Swish / SiLU** | $z \cdot \sigma(z)$; smooth, non-monotonic | -| **Hard Sigmoid / Hard Tanh** | Piece-wise linear approximations; no transcendentals | +| Variant | Key Difference | +|------------------------------|---------------------------------------------------------| +| **PReLU (Parametric ReLU)** | $\alpha$ is a learnable parameter per channel | +| **ELU (Exponential LU)** | $\alpha(e^z - 1)$ for $z < 0$; smooth and zero-centered | +| **GELU (Gaussian Error LU)** | $z \cdot \Phi(z)$; used in Transformers | +| **Swish / SiLU** | $z \cdot \sigma(z)$; smooth, non-monotonic | +| **Hard Sigmoid / Hard Tanh** | Piece-wise linear approximations; no transcendentals | ## Applications @@ -136,11 +136,11 @@ graph TD NN --> Loss ``` -| Component | Relationship | -|-----------|-------------| -| [Dense Layer](../layer/Layer.md) | Applies the activation function after the affine transformation | +| Component | Relationship | +|---------------------------------------|------------------------------------------------------------------------------------------| +| [Dense Layer](../layer/Layer.md) | Applies the activation function after the affine transformation | | [Neural Network](../NeuralNetwork.md) | Activations enable the non-linear function approximation that makes deep networks useful | -| [Loss Functions](../losses/Loss.md) | The output activation must match the loss: Sigmoid + BCE, Softmax + CCE | +| [Loss Functions](../losses/Loss.md) | The output activation must match the loss: Sigmoid + BCE, Softmax + CCE | ## References & Further Reading diff --git a/doc/neural_network/layer/Layer.md b/doc/neural_network/layer/Layer.md index 87160c19..85ef9da6 100644 --- a/doc/neural_network/layer/Layer.md +++ b/doc/neural_network/layer/Layer.md @@ -42,11 +42,11 @@ For a layer with 128 inputs and 64 outputs: $P = 64 \times 129 = 8{,}256$ parame ## Complexity Analysis -| Operation | Time | Space | -|-----------|------|-------| -| Forward ($W a + b$) | $O(m \cdot n)$ | $O(m)$ output + $O(m)$ cached $z$ | -| Backward ($\delta$, $\nabla W$, $\nabla b$) | $O(m \cdot n)$ | $O(m \cdot n)$ weight gradient | -| Total parameters | — | $O(m \cdot n + m)$ | +| Operation | Time | Space | +|---------------------------------------------|----------------|-----------------------------------| +| Forward ($W a + b$) | $O(m \cdot n)$ | $O(m)$ output + $O(m)$ cached $z$ | +| Backward ($\delta$, $\nabla W$, $\nabla b$) | $O(m \cdot n)$ | $O(m \cdot n)$ weight gradient | +| Total parameters | — | $O(m \cdot n + m)$ | The matrix-vector product dominates both passes. For embedded networks (e.g. $n = 32, m = 16$), a single forward pass takes ~512 multiply-accumulate operations. @@ -58,19 +58,19 @@ $$W = \begin{bmatrix} 0.5 & -0.3 & 0.8 \\ 0.1 & 0.7 & -0.2 \end{bmatrix}, \quad **Forward:** -| Step | Computation | Result | -|------|-------------|--------| -| $z = W a_{\text{in}} + b$ | $[0.5 - 0.15 - 0.8 + 0.1,\; 0.1 + 0.35 + 0.2 - 0.1]$ | $[-0.35,\; 0.55]^T$ | -| $a_{\text{out}} = \text{ReLU}(z)$ | $[\max(0, -0.35),\; \max(0, 0.55)]$ | $[0.0,\; 0.55]^T$ | +| Step | Computation | Result | +|-----------------------------------|------------------------------------------------------|---------------------| +| $z = W a_{\text{in}} + b$ | $[0.5 - 0.15 - 0.8 + 0.1,\; 0.1 + 0.35 + 0.2 - 0.1]$ | $[-0.35,\; 0.55]^T$ | +| $a_{\text{out}} = \text{ReLU}(z)$ | $[\max(0, -0.35),\; \max(0, 0.55)]$ | $[0.0,\; 0.55]^T$ | **Backward** with $\frac{\partial \mathcal{L}}{\partial a_{\text{out}}} = [0.2,\; -0.4]^T$: -| Step | Computation | Result | -|------|-------------|--------| -| $\delta = \nabla a_{\text{out}} \odot \text{ReLU}'(z)$ | $[0.2 \cdot 0,\; -0.4 \cdot 1]$ | $[0,\; -0.4]^T$ | -| $\nabla W = \delta \, a_{\text{in}}^T$ | row 1: all zeros; row 2: $-0.4 \times [1, 0.5, -1]$ | $\begin{bmatrix}0 & 0 & 0\\-0.4 & -0.2 & 0.4\end{bmatrix}$ | -| $\nabla b = \delta$ | — | $[0,\; -0.4]^T$ | -| $\nabla a_{\text{in}} = W^T \delta$ | $W^T [0, -0.4]^T$ | $[-0.04,\; -0.28,\; 0.08]^T$ | +| Step | Computation | Result | +|--------------------------------------------------------|-----------------------------------------------------|------------------------------------------------------------| +| $\delta = \nabla a_{\text{out}} \odot \text{ReLU}'(z)$ | $[0.2 \cdot 0,\; -0.4 \cdot 1]$ | $[0,\; -0.4]^T$ | +| $\nabla W = \delta \, a_{\text{in}}^T$ | row 1: all zeros; row 2: $-0.4 \times [1, 0.5, -1]$ | $\begin{bmatrix}0 & 0 & 0\\-0.4 & -0.2 & 0.4\end{bmatrix}$ | +| $\nabla b = \delta$ | — | $[0,\; -0.4]^T$ | +| $\nabla a_{\text{in}} = W^T \delta$ | $W^T [0, -0.4]^T$ | $[-0.04,\; -0.28,\; 0.08]^T$ | ## Pitfalls & Edge Cases @@ -82,13 +82,13 @@ $$W = \begin{bmatrix} 0.5 & -0.3 & 0.8 \\ 0.1 & 0.7 & -0.2 \end{bmatrix}, \quad ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Convolutional layer** | Weight sharing across spatial positions; $O(k^2 \cdot c)$ parameters per filter instead of $O(n \cdot m)$ | -| **Recurrent layer** | Shares weights across time steps; adds a hidden state feedback connection | -| **Batch normalization layer** | Normalizes activations to zero mean and unit variance; accelerates training | -| **Dropout layer** | Randomly zeros activations during training; regularization effect | -| **Sparse layer** | Only a subset of connections exist; reduces parameter count and computation | +| Variant | Key Difference | +|-------------------------------|-----------------------------------------------------------------------------------------------------------| +| **Convolutional layer** | Weight sharing across spatial positions; $O(k^2 \cdot c)$ parameters per filter instead of $O(n \cdot m)$ | +| **Recurrent layer** | Shares weights across time steps; adds a hidden state feedback connection | +| **Batch normalization layer** | Normalizes activations to zero mean and unit variance; accelerates training | +| **Dropout layer** | Randomly zeros activations during training; regularization effect | +| **Sparse layer** | Only a subset of connections exist; reduces parameter count and computation | ## Applications @@ -113,11 +113,11 @@ graph TD Layer -.->|"no activation, MSE loss"| LR ``` -| Component | Relationship | -|-----------|-------------| -| [Activation Functions](../activation/Activation.md) | Applied element-wise after the affine transformation | -| [Model](../model/Model.md) | Chains multiple dense layers into a network | -| [Optimizer](../optimizer/Optimizer.md) | Updates $W$ and $b$ using the computed gradients | +| Component | Relationship | +|-----------------------------------------------------------|----------------------------------------------------------------------------------------| +| [Activation Functions](../activation/Activation.md) | Applied element-wise after the affine transformation | +| [Model](../model/Model.md) | Chains multiple dense layers into a network | +| [Optimizer](../optimizer/Optimizer.md) | Updates $W$ and $b$ using the computed gradients | | [Linear Regression](../../estimators/LinearRegression.md) | A dense layer with identity activation and MSE loss is equivalent to linear regression | ## References & Further Reading diff --git a/doc/neural_network/losses/Loss.md b/doc/neural_network/losses/Loss.md index c13bc3f1..db3f0ea5 100644 --- a/doc/neural_network/losses/Loss.md +++ b/doc/neural_network/losses/Loss.md @@ -49,12 +49,12 @@ $$\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = -\frac{y_i}{\hat{y}_i}$$ ## Complexity Analysis -| Loss | Forward | Backward | Notes | -|------|---------|----------|-------| -| MSE | $O(m)$ | $O(m)$ | Cheapest; no transcendentals | -| MAE | $O(m)$ | $O(m)$ | Requires `sign()` | -| BCE | $O(m)$ | $O(m)$ | Requires `log()` | -| CCE | $O(k)$ | $O(k)$ | Requires `log()` | +| Loss | Forward | Backward | Notes | +|------|---------|----------|------------------------------| +| MSE | $O(m)$ | $O(m)$ | Cheapest; no transcendentals | +| MAE | $O(m)$ | $O(m)$ | Requires `sign()` | +| BCE | $O(m)$ | $O(m)$ | Requires `log()` | +| CCE | $O(k)$ | $O(k)$ | Requires `log()` | All losses are $O(m)$ where $m$ is the output dimension. The computational cost is negligible compared to the dense layer matrix products. @@ -69,10 +69,10 @@ $$\mathcal{L} = -(0 \cdot \log 0.1 + 1 \cdot \log 0.7 + 0 \cdot \log 0.2) = -\lo **CCE Backward:** | $i$ | $y_i$ | $\hat{y}_i$ | $\partial \mathcal{L}/\partial \hat{y}_i = -y_i / \hat{y}_i$ | -|-----|--------|-------------|----------------------------------------------| -| 1 | 0 | 0.1 | $0$ | -| 2 | 1 | 0.7 | $-1.429$ | -| 3 | 0 | 0.2 | $0$ | +|-----|-------|-------------|--------------------------------------------------------------| +| 1 | 0 | 0.1 | $0$ | +| 2 | 1 | 0.7 | $-1.429$ | +| 3 | 0 | 0.2 | $0$ | The gradient is non-zero only for the true class, and its magnitude $1/\hat{y}_2$ grows as the prediction *worsens* — providing a strong corrective signal. @@ -92,13 +92,13 @@ MSE gives a much weaker signal and does not account for the probabilistic nature ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Huber loss** | Quadratic for small errors, linear for large; robust regression | -| **Focal loss** | Down-weights well-classified examples; addresses class imbalance | -| **KL divergence** | Measures distance between two distributions; used in variational inference | -| **Hinge loss** | Margin-based; used in SVMs and some neural classifiers | -| **Contrastive loss** | Learns similarity metrics; used in Siamese networks | +| Variant | Key Difference | +|----------------------|----------------------------------------------------------------------------| +| **Huber loss** | Quadratic for small errors, linear for large; robust regression | +| **Focal loss** | Down-weights well-classified examples; addresses class imbalance | +| **KL divergence** | Measures distance between two distributions; used in variational inference | +| **Hinge loss** | Margin-based; used in SVMs and some neural classifiers | +| **Contrastive loss** | Learns similarity metrics; used in Siamese networks | ## Applications @@ -125,12 +125,12 @@ graph TD Loss -.->|"MSE + normal equation"| LR ``` -| Component | Relationship | -|-----------|-------------| -| [Activation Functions](../activation/Activation.md) | Output activation must match: Sigmoid ↔ BCE, Softmax ↔ CCE, identity ↔ MSE | -| [Optimizer](../optimizer/Optimizer.md) | Uses $\nabla \mathcal{L}$ to update parameters | -| [Regularization](../regularization/Regularization.md) | Adds a penalty term to the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda \Omega(\theta)$ | -| [Linear Regression](../../estimators/LinearRegression.md) | Solved analytically when the loss is MSE and the model is linear | +| Component | Relationship | +|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------| +| [Activation Functions](../activation/Activation.md) | Output activation must match: Sigmoid ↔ BCE, Softmax ↔ CCE, identity ↔ MSE | +| [Optimizer](../optimizer/Optimizer.md) | Uses $\nabla \mathcal{L}$ to update parameters | +| [Regularization](../regularization/Regularization.md) | Adds a penalty term to the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda \Omega(\theta)$ | +| [Linear Regression](../../estimators/LinearRegression.md) | Solved analytically when the loss is MSE and the model is linear | ## References & Further Reading From d312efe0b22872d32633c12829d65bbce65a58ee Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:44:16 +0100 Subject: [PATCH 09/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/neural_network/NeuralNetwork.md | 78 +++++++++---------- doc/neural_network/model/Model.md | 58 +++++++------- doc/neural_network/optimizer/Optimizer.md | 66 ++++++++-------- .../regularization/Regularization.md | 64 +++++++-------- 4 files changed, 133 insertions(+), 133 deletions(-) diff --git a/doc/neural_network/NeuralNetwork.md b/doc/neural_network/NeuralNetwork.md index 30241e4d..09ffec75 100644 --- a/doc/neural_network/NeuralNetwork.md +++ b/doc/neural_network/NeuralNetwork.md @@ -25,11 +25,11 @@ where $W_\ell \in \mathbb{R}^{n_\ell \times n_{\ell-1}}$ are weights, $b_\ell \i Training minimizes a scalar loss $\mathcal{L}(\hat{y}, y)$ that measures how far the prediction $\hat{y}$ is from the target $y$. Common choices: -| Loss | Formula | Use Case | -|------|---------|----------| -| MSE | $\frac{1}{m}\sum(\hat{y}_i - y_i)^2$ | Regression | -| BCE | $-\sum[y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i)]$ | Binary classification | -| CCE | $-\sum y_i \log \hat{y}_i$ | Multi-class classification | +| Loss | Formula | Use Case | +|------|--------------------------------------------------------|----------------------------| +| MSE | $\frac{1}{m}\sum(\hat{y}_i - y_i)^2$ | Regression | +| BCE | $-\sum[y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i)]$ | Binary classification | +| CCE | $-\sum y_i \log \hat{y}_i$ | Multi-class classification | ### Backpropagation @@ -52,11 +52,11 @@ where $\eta$ is the learning rate. More sophisticated optimizers (momentum, Adam ## Complexity Analysis -| Phase | Time | Space | -|-------|------|-------| -| Forward pass | $O\!\left(\sum_{\ell=1}^L n_\ell \cdot n_{\ell-1}\right)$ | $O\!\left(\sum n_\ell\right)$ activations | -| Backward pass | Same as forward | Same + gradient storage | -| Parameter update | $O(P)$ | $O(P)$ optimizer state | +| Phase | Time | Space | +|------------------|-----------------------------------------------------------|-------------------------------------------| +| Forward pass | $O\!\left(\sum_{\ell=1}^L n_\ell \cdot n_{\ell-1}\right)$ | $O\!\left(\sum n_\ell\right)$ activations | +| Backward pass | Same as forward | Same + gradient storage | +| Parameter update | $O(P)$ | $O(P)$ optimizer state | where $P = \sum_\ell (n_\ell \cdot n_{\ell-1} + n_\ell)$ is the total parameter count. For small embedded networks ($P < 10{,}000$), both passes complete in microseconds. @@ -78,22 +78,22 @@ graph LR **Epoch 0 — Forward pass** with input $x = [1, 0]^T$, target $y = 1$: -| Step | Computation | Result | -|------|-------------|--------| -| Hidden pre-activation | $z_1 = W_1 x + b_1$ | $[0.3, -0.1]^T$ | -| Hidden activation | $a_1 = \text{ReLU}(z_1)$ | $[0.3, 0.0]^T$ | -| Output pre-activation | $z_2 = W_2 a_1 + b_2$ | $[0.15]$ | -| Output activation | $\hat{y} = \sigma(z_2)$ | $[0.537]$ | -| Loss | $\mathcal{L} = -(y\log\hat{y} + (1-y)\log(1-\hat{y}))$ | $0.621$ | +| Step | Computation | Result | +|-----------------------|--------------------------------------------------------|-----------------| +| Hidden pre-activation | $z_1 = W_1 x + b_1$ | $[0.3, -0.1]^T$ | +| Hidden activation | $a_1 = \text{ReLU}(z_1)$ | $[0.3, 0.0]^T$ | +| Output pre-activation | $z_2 = W_2 a_1 + b_2$ | $[0.15]$ | +| Output activation | $\hat{y} = \sigma(z_2)$ | $[0.537]$ | +| Loss | $\mathcal{L} = -(y\log\hat{y} + (1-y)\log(1-\hat{y}))$ | $0.621$ | **Epoch 0 — Backward pass:** -| Step | Computation | Result | -|------|-------------|--------| -| Output gradient | $\delta_2 = \hat{y} - y$ | $[-0.463]$ | -| $\nabla W_2$ | $\delta_2 \cdot a_1^T$ | $[-0.139, 0]$ | -| Hidden gradient | $\delta_1 = W_2^T \delta_2 \odot \text{ReLU}'(z_1)$ | $[-0.231, 0]^T$ | -| $\nabla W_1$ | $\delta_1 \cdot x^T$ | $[[-0.231, 0], [0, 0]]$ | +| Step | Computation | Result | +|-----------------|-----------------------------------------------------|-------------------------| +| Output gradient | $\delta_2 = \hat{y} - y$ | $[-0.463]$ | +| $\nabla W_2$ | $\delta_2 \cdot a_1^T$ | $[-0.139, 0]$ | +| Hidden gradient | $\delta_1 = W_2^T \delta_2 \odot \text{ReLU}'(z_1)$ | $[-0.231, 0]^T$ | +| $\nabla W_1$ | $\delta_1 \cdot x^T$ | $[[-0.231, 0], [0, 0]]$ | **Update:** $W \leftarrow W - 0.1 \cdot \nabla W$. After ~500 epochs, the network correctly classifies all four XOR inputs. @@ -108,13 +108,13 @@ graph LR ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Convolutional Neural Network (CNN)** | Layers share weights spatially; efficient for image/signal data | -| **Recurrent Neural Network (RNN)** | Layers share weights across time steps; models sequences | -| **Residual Network (ResNet)** | Skip connections mitigate vanishing gradients in very deep networks | -| **Transformer** | Attention-based; no recurrence; state-of-the-art for sequences | -| **Quantized Neural Network** | Weights and activations in low-bit integers; optimal for MCU deployment | +| Variant | Key Difference | +|----------------------------------------|-------------------------------------------------------------------------| +| **Convolutional Neural Network (CNN)** | Layers share weights spatially; efficient for image/signal data | +| **Recurrent Neural Network (RNN)** | Layers share weights across time steps; models sequences | +| **Residual Network (ResNet)** | Skip connections mitigate vanishing gradients in very deep networks | +| **Transformer** | Attention-based; no recurrence; state-of-the-art for sequences | +| **Quantized Neural Network** | Weights and activations in low-bit integers; optimal for MCU deployment | ## Applications @@ -146,15 +146,15 @@ graph TD NN -.->|"single-layer, linear activation, MSE loss"| LR ``` -| Component | Relationship | -|-----------|-------------| -| [Dense Layer](layer/Layer.md) | The fundamental building block; computes affine transformations | -| [Activation Functions](activation/Activation.md) | Introduce non-linearity after each layer | -| [Loss Functions](losses/Loss.md) | Define the training objective | -| [Optimizer](optimizer/Optimizer.md) | Drives parameter updates via gradient descent | -| [Regularization](regularization/Regularization.md) | Penalizes complexity to prevent overfitting | -| [Model](model/Model.md) | Composes layers into a trainable pipeline | -| [Linear Regression](../estimators/LinearRegression.md) | Special case: single layer, identity activation, MSE loss | +| Component | Relationship | +|--------------------------------------------------------|-----------------------------------------------------------------| +| [Dense Layer](layer/Layer.md) | The fundamental building block; computes affine transformations | +| [Activation Functions](activation/Activation.md) | Introduce non-linearity after each layer | +| [Loss Functions](losses/Loss.md) | Define the training objective | +| [Optimizer](optimizer/Optimizer.md) | Drives parameter updates via gradient descent | +| [Regularization](regularization/Regularization.md) | Penalizes complexity to prevent overfitting | +| [Model](model/Model.md) | Composes layers into a trainable pipeline | +| [Linear Regression](../estimators/LinearRegression.md) | Special case: single layer, identity activation, MSE loss | ## References & Further Reading diff --git a/doc/neural_network/model/Model.md b/doc/neural_network/model/Model.md index 53d1e473..ab47b34e 100644 --- a/doc/neural_network/model/Model.md +++ b/doc/neural_network/model/Model.md @@ -55,12 +55,12 @@ graph TD ## Complexity Analysis -| Operation | Time | Space | -|-----------|------|-------| -| Forward pass | $O(P)$ | $O(\sum n_\ell)$ cached activations | -| Backward pass | $O(P)$ | $O(P)$ gradients | -| `GetParameters()` | $O(P)$ | $O(P)$ flat vector | -| `SetParameters()` | $O(P)$ | — | +| Operation | Time | Space | +|-------------------|--------|-------------------------------------| +| Forward pass | $O(P)$ | $O(\sum n_\ell)$ cached activations | +| Backward pass | $O(P)$ | $O(P)$ gradients | +| `GetParameters()` | $O(P)$ | $O(P)$ flat vector | +| `SetParameters()` | $O(P)$ | — | All operations scale linearly with the total parameter count $P$. @@ -70,21 +70,21 @@ All operations scale linearly with the total parameter count $P$. **Compile-time verification chain:** -| Check | Condition | Status | -|-------|-----------|--------| -| Layer 1 input size = Model input size | $2 = 2$ | ✓ | -| Layer 1 output size = Layer 2 input size | $3 = 3$ | ✓ | -| Layer 2 output size = Model output size | $1 = 1$ | ✓ | -| All types derive from `Layer` | type trait check | ✓ | +| Check | Condition | Status | +|------------------------------------------|------------------|--------| +| Layer 1 input size = Model input size | $2 = 2$ | ✓ | +| Layer 1 output size = Layer 2 input size | $3 = 3$ | ✓ | +| Layer 2 output size = Model output size | $1 = 1$ | ✓ | +| All types derive from `Layer` | type trait check | ✓ | **Parameter layout** ($P = 3 \times 3 + 3 + 1 \times 4 + 1 = 16$): -| Index | Parameter | -|-------|-----------| -| 0–5 | $W_1$ (3×2 = 6 elements) | -| 6–8 | $b_1$ (3 elements) | -| 9–11 | $W_2$ (1×3 = 3 elements) | -| 12 | $b_2$ (1 element) | +| Index | Parameter | +|-------|--------------------------| +| 0–5 | $W_1$ (3×2 = 6 elements) | +| 6–8 | $b_1$ (3 elements) | +| 9–11 | $W_2$ (1×3 = 3 elements) | +| 12 | $b_2$ (1 element) | **Forward pass** with $x = [1.0, 0.5]^T$: @@ -108,12 +108,12 @@ All operations scale linearly with the total parameter count $P$. ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| +| Variant | Key Difference | +|--------------------------------|------------------------------------------------------------------------------------| | **Sequential model (dynamic)** | Layers stored in a container; dimension checked at runtime instead of compile time | -| **Functional API** | Supports branching and merging (DAG topology instead of linear chain) | -| **Residual model** | Adds skip connections: $a_{\ell+2} = f_{\ell+1}(a_\ell) + a_\ell$ | -| **Recurrent model** | Unrolls the same layer across time steps | +| **Functional API** | Supports branching and merging (DAG topology instead of linear chain) | +| **Residual model** | Adds skip connections: $a_{\ell+2} = f_{\ell+1}(a_\ell) + a_\ell$ | +| **Recurrent model** | Unrolls the same layer across time steps | ## Applications @@ -140,12 +140,12 @@ graph TD Model --> NN ``` -| Component | Relationship | -|-----------|-------------| -| [Dense Layer](../layer/Layer.md) | The Model is a sequence of layers stored in a `std::tuple` | -| [Loss Functions](../losses/Loss.md) | Measures prediction error; the Model delegates loss computation to a Loss object | -| [Optimizer](../optimizer/Optimizer.md) | Receives the flat parameter/gradient vectors from the Model and returns updated parameters | -| [Regularization](../regularization/Regularization.md) | Added to the loss before optimization | +| Component | Relationship | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------| +| [Dense Layer](../layer/Layer.md) | The Model is a sequence of layers stored in a `std::tuple` | +| [Loss Functions](../losses/Loss.md) | Measures prediction error; the Model delegates loss computation to a Loss object | +| [Optimizer](../optimizer/Optimizer.md) | Receives the flat parameter/gradient vectors from the Model and returns updated parameters | +| [Regularization](../regularization/Regularization.md) | Added to the loss before optimization | ## References & Further Reading diff --git a/doc/neural_network/optimizer/Optimizer.md b/doc/neural_network/optimizer/Optimizer.md index 5d30fbca..ff3557e5 100644 --- a/doc/neural_network/optimizer/Optimizer.md +++ b/doc/neural_network/optimizer/Optimizer.md @@ -28,11 +28,11 @@ For non-convex losses (typical in neural networks), gradient descent converges t ### Learning Rate Sensitivity -| $\eta$ | Behavior | -|--------|----------| -| Too small ($\eta \ll 1/L$) | Slow convergence, many iterations wasted | -| Optimal ($\eta \approx 1/L$) | Fastest reliable convergence | -| Too large ($\eta > 2/L$) | Oscillation and divergence | +| $\eta$ | Behavior | +|------------------------------|------------------------------------------| +| Too small ($\eta \ll 1/L$) | Slow convergence, many iterations wasted | +| Optimal ($\eta \approx 1/L$) | Fastest reliable convergence | +| Too large ($\eta > 2/L$) | Oscillation and divergence | ```mermaid graph LR @@ -45,11 +45,11 @@ graph LR ## Complexity Analysis -| Operation | Time | Space | -|-----------|------|-------| -| One gradient evaluation | $O(P)$ per parameter | $O(P)$ gradient vector | -| One parameter update | $O(P)$ | In-place | -| Total training (T iterations) | $O(T \cdot P)$ | $O(P)$ working memory | +| Operation | Time | Space | +|-------------------------------|----------------------|------------------------| +| One gradient evaluation | $O(P)$ per parameter | $O(P)$ gradient vector | +| One parameter update | $O(P)$ | In-place | +| Total training (T iterations) | $O(T \cdot P)$ | $O(P)$ working memory | Memory overhead is minimal: only the current parameter vector, the gradient vector, and the optimizer result. No momentum buffers or second-moment estimates. @@ -59,19 +59,19 @@ Memory overhead is minimal: only the current parameter vector, the gradient vect **Iteration 1:** -| Step | Computation | Result | -|------|-------------|--------| -| Gradient | $\nabla \mathcal{L} = [2\theta_1, 2\theta_2]$ | $[4.0, -2.0]$ | -| Update | $\theta_1 = \theta_0 - 0.1 \cdot \nabla\mathcal{L}$ | $[1.6, -0.8]$ | -| Loss | $\mathcal{L}(\theta_1) = 1.6^2 + 0.8^2$ | $3.20$ | +| Step | Computation | Result | +|----------|-----------------------------------------------------|---------------| +| Gradient | $\nabla \mathcal{L} = [2\theta_1, 2\theta_2]$ | $[4.0, -2.0]$ | +| Update | $\theta_1 = \theta_0 - 0.1 \cdot \nabla\mathcal{L}$ | $[1.6, -0.8]$ | +| Loss | $\mathcal{L}(\theta_1) = 1.6^2 + 0.8^2$ | $3.20$ | **Iteration 2:** -| Step | Computation | Result | -|------|-------------|--------| -| Gradient | $[3.2, -1.6]$ | | -| Update | $[1.28, -0.64]$ | | -| Loss | $2.048$ | | +| Step | Computation | Result | +|----------|-----------------|--------| +| Gradient | $[3.2, -1.6]$ | | +| Update | $[1.28, -0.64]$ | | +| Loss | $2.048$ | | **Pattern:** Each iteration multiplies the loss by $(1 - 2\eta)^2 = 0.64$. After 20 iterations, $\mathcal{L} \approx 0.0003$. @@ -95,14 +95,14 @@ graph LR ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **SGD (Stochastic Gradient Descent)** | Uses a random mini-batch per iteration; noise helps escape local minima | -| **SGD with Momentum** | Accumulates a velocity: $v_{t+1} = \mu v_t - \eta \nabla\mathcal{L}$; smooths out oscillations | -| **Nesterov Momentum** | Evaluates gradient at the *lookahead* position $\theta + \mu v$; faster convergence | -| **AdaGrad** | Per-parameter adaptive learning rate based on accumulated squared gradients | -| **RMSProp** | Exponentially decaying average of squared gradients; handles non-stationary objectives | -| **Adam** | Combines momentum and RMSProp with bias correction; most popular adaptive method | +| Variant | Key Difference | +|---------------------------------------|------------------------------------------------------------------------------------------------| +| **SGD (Stochastic Gradient Descent)** | Uses a random mini-batch per iteration; noise helps escape local minima | +| **SGD with Momentum** | Accumulates a velocity: $v_{t+1} = \mu v_t - \eta \nabla\mathcal{L}$; smooths out oscillations | +| **Nesterov Momentum** | Evaluates gradient at the *lookahead* position $\theta + \mu v$; faster convergence | +| **AdaGrad** | Per-parameter adaptive learning rate based on accumulated squared gradients | +| **RMSProp** | Exponentially decaying average of squared gradients; handles non-stationary objectives | +| **Adam** | Combines momentum and RMSProp with bias correction; most popular adaptive method | ## Applications @@ -127,11 +127,11 @@ graph TD Opt -.->|"analytical solution at η→∞, 1 step"| LR ``` -| Component | Relationship | -|-----------|-------------| -| [Loss Functions](../losses/Loss.md) | Provides the `Cost()` and `Gradient()` the optimizer calls each iteration | -| [Model](../model/Model.md) | Passes initial parameters to the optimizer and receives optimized parameters back | -| [Regularization](../regularization/Regularization.md) | Adds a penalty gradient to $\nabla\mathcal{L}$, biasing the optimizer toward simpler models | +| Component | Relationship | +|-----------------------------------------------------------|---------------------------------------------------------------------------------------------------| +| [Loss Functions](../losses/Loss.md) | Provides the `Cost()` and `Gradient()` the optimizer calls each iteration | +| [Model](../model/Model.md) | Passes initial parameters to the optimizer and receives optimized parameters back | +| [Regularization](../regularization/Regularization.md) | Adds a penalty gradient to $\nabla\mathcal{L}$, biasing the optimizer toward simpler models | | [Linear Regression](../../estimators/LinearRegression.md) | For MSE on a linear model, gradient descent converges to the same solution as the normal equation | ## References & Further Reading diff --git a/doc/neural_network/regularization/Regularization.md b/doc/neural_network/regularization/Regularization.md index 75ca8a9b..98990ceb 100644 --- a/doc/neural_network/regularization/Regularization.md +++ b/doc/neural_network/regularization/Regularization.md @@ -32,12 +32,12 @@ $$\frac{\partial \Omega_{L1}}{\partial \theta_i} = \operatorname{sign}(\theta_i) ### Comparison -| Property | L1 | L2 | -|----------|-----------|-----------| -| Penalty shape | Diamond (corners at axes) | Sphere | -| Sparsity | Promotes exact zeros | Shrinks toward zero but rarely reaches it | -| Gradient at $\theta_i = 0$ | Undefined (sub-gradient) | Zero | -| Best for | Feature selection, sparse models | General-purpose weight control | +| Property | L1 | L2 | +|----------------------------|----------------------------------|-------------------------------------------| +| Penalty shape | Diamond (corners at axes) | Sphere | +| Sparsity | Promotes exact zeros | Shrinks toward zero but rarely reaches it | +| Gradient at $\theta_i = 0$ | Undefined (sub-gradient) | Zero | +| Best for | Feature selection, sparse models | General-purpose weight control | ### Geometric Interpretation @@ -49,12 +49,12 @@ where $c$ is determined by $\lambda$. L1 constrains $\theta$ to a diamond, so th ## Complexity Analysis -| Operation | Time | Space | -|-----------|------|-------| +| Operation | Time | Space | +|-----------------------|--------|--------| | $\Omega_{L2}(\theta)$ | $O(P)$ | $O(1)$ | -| $\nabla \Omega_{L2}$ | $O(P)$ | $O(P)$ | +| $\nabla \Omega_{L2}$ | $O(P)$ | $O(P)$ | | $\Omega_{L1}(\theta)$ | $O(P)$ | $O(1)$ | -| $\nabla \Omega_{L1}$ | $O(P)$ | $O(P)$ | +| $\nabla \Omega_{L1}$ | $O(P)$ | $O(P)$ | Regularization adds negligible computational cost — one pass over the parameter vector per training iteration. @@ -64,19 +64,19 @@ Regularization adds negligible computational cost — one pass over the paramete **L2 Regularization:** -| Step | Computation | Result | -|------|-------------|--------| -| Penalty | $\frac{1}{2}(0.64 + 0.09 + 0.25) = 0.49$ | $\Omega_{L2} = 0.49$ | -| Gradient | $[0.8, -0.3, 0.5]$ | Added to $\nabla\mathcal{L}$ | -| Contribution to loss | $0.1 \times 0.49 = 0.049$ | | +| Step | Computation | Result | +|----------------------|------------------------------------------|------------------------------| +| Penalty | $\frac{1}{2}(0.64 + 0.09 + 0.25) = 0.49$ | $\Omega_{L2} = 0.49$ | +| Gradient | $[0.8, -0.3, 0.5]$ | Added to $\nabla\mathcal{L}$ | +| Contribution to loss | $0.1 \times 0.49 = 0.049$ | | **L1 Regularization:** -| Step | Computation | Result | -|------|-------------|--------| -| Penalty | $0.8 + 0.3 + 0.5 = 1.6$ | $\Omega_{L1} = 1.6$ | -| Gradient | $[1, -1, 1]$ | Added to $\nabla\mathcal{L}$ | -| Contribution to loss | $0.1 \times 1.6 = 0.16$ | | +| Step | Computation | Result | +|----------------------|-------------------------|------------------------------| +| Penalty | $0.8 + 0.3 + 0.5 = 1.6$ | $\Omega_{L1} = 1.6$ | +| Gradient | $[1, -1, 1]$ | Added to $\nabla\mathcal{L}$ | +| Contribution to loss | $0.1 \times 1.6 = 0.16$ | | **After several L1 updates** ($\eta = 0.1$, $\lambda = 0.1$): the $\theta_2 = -0.3$ component, already small, is driven to exactly zero. The model effectively prunes that connection. @@ -90,13 +90,13 @@ Regularization adds negligible computational cost — one pass over the paramete ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Elastic Net** | $\Omega = \alpha \|\theta\|_1 + (1-\alpha)\|\theta\|_2^2$; combines L1 sparsity with L2 smoothness | -| **Dropout** | Randomly zeroes activations during training; implicit ensemble regularization | -| **Early stopping** | Halts training before overfitting; regularization without modifying the loss | -| **Data augmentation** | Expands the training set with transformed copies; reduces overfitting by increasing data diversity | -| **Spectral normalization** | Constrains the spectral norm of weight matrices; stabilizes GAN training | +| Variant | Key Difference | +|----------------------------|----------------------------------------------------------------------------------------------------| +| **Elastic Net** | $\Omega = \alpha \|\theta\|_1 + (1-\alpha)\|\theta\|_2^2$; combines L1 sparsity with L2 smoothness | +| **Dropout** | Randomly zeroes activations during training; implicit ensemble regularization | +| **Early stopping** | Halts training before overfitting; regularization without modifying the loss | +| **Data augmentation** | Expands the training set with transformed copies; reduces overfitting by increasing data diversity | +| **Spectral normalization** | Constrains the spectral norm of weight matrices; stabilizes GAN training | | **Weight clipping** | Hard constraint: $|\theta_i| \le c$; used in Wasserstein GANs | ## Applications @@ -122,11 +122,11 @@ graph TD Reg -.->|"L2 + MSE = Ridge regression"| LR ``` -| Component | Relationship | -|-----------|-------------| -| [Loss Functions](../losses/Loss.md) | Regularization is a penalty *added to* the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda\Omega$ | -| [Optimizer](../optimizer/Optimizer.md) | Receives the combined gradient $\nabla\mathcal{L} + \lambda\nabla\Omega$ | -| [Linear Regression](../../estimators/LinearRegression.md) | L2-regularized MSE with a linear model is **Ridge regression**; L1 is **Lasso** | +| Component | Relationship | +|-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| [Loss Functions](../losses/Loss.md) | Regularization is a penalty *added to* the loss: $\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda\Omega$ | +| [Optimizer](../optimizer/Optimizer.md) | Receives the combined gradient $\nabla\mathcal{L} + \lambda\nabla\Omega$ | +| [Linear Regression](../../estimators/LinearRegression.md) | L2-regularized MSE with a linear model is **Ridge regression**; L1 is **Lasso** | ## References & Further Reading From 1faf9d7b59ae475b64071e4da31eb1fe887a09e0 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:46:48 +0100 Subject: [PATCH 10/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/neural_network/README.md | 18 +++++----- .../DiscreteAlgebraicRiccatiEquation.md | 28 +++++++-------- doc/solvers/DurandKerner.md | 28 +++++++-------- doc/solvers/GaussianElimination.md | 34 +++++++++---------- doc/solvers/LevinsonDurbin.md | 28 +++++++-------- doc/solvers/README.md | 12 +++---- doc/windowing/README.md | 4 +-- 7 files changed, 76 insertions(+), 76 deletions(-) diff --git a/doc/neural_network/README.md b/doc/neural_network/README.md index 10a96e61..21f3569f 100644 --- a/doc/neural_network/README.md +++ b/doc/neural_network/README.md @@ -4,12 +4,12 @@ Components for building, training, and evaluating feed-forward neural networks e ## Components -| Component | Description | -|-----------|-------------| -| [Neural Network Overview](NeuralNetwork.md) | Architecture, training loop, and how the components fit together | -| [Layers](layer/Layer.md) | Dense (fully connected) layer with forward and backward pass | -| [Activation Functions](activation/Activation.md) | Non-linear element-wise transforms: ReLU, LeakyReLU, Sigmoid, Tanh, Softmax | -| [Loss Functions](losses/Loss.md) | Objective functions: MSE, MAE, Binary Cross-Entropy, Categorical Cross-Entropy | -| [Optimizers](optimizer/Optimizer.md) | Parameter update strategies: Gradient Descent | -| [Regularization](regularization/Regularization.md) | Complexity penalties: L1 (Lasso) and L2 (Ridge) | -| [Model](model/Model.md) | Variadic-template model composing layers, optimizer, and loss into a trainable pipeline | +| Component | Description | +|----------------------------------------------------|-----------------------------------------------------------------------------------------| +| [Neural Network Overview](NeuralNetwork.md) | Architecture, training loop, and how the components fit together | +| [Layers](layer/Layer.md) | Dense (fully connected) layer with forward and backward pass | +| [Activation Functions](activation/Activation.md) | Non-linear element-wise transforms: ReLU, LeakyReLU, Sigmoid, Tanh, Softmax | +| [Loss Functions](losses/Loss.md) | Objective functions: MSE, MAE, Binary Cross-Entropy, Categorical Cross-Entropy | +| [Optimizers](optimizer/Optimizer.md) | Parameter update strategies: Gradient Descent | +| [Regularization](regularization/Regularization.md) | Complexity penalties: L1 (Lasso) and L2 (Ridge) | +| [Model](model/Model.md) | Variadic-template model composing layers, optimizer, and loss into a trainable pipeline | diff --git a/doc/solvers/DiscreteAlgebraicRiccatiEquation.md b/doc/solvers/DiscreteAlgebraicRiccatiEquation.md index 9219ca45..6fff506a 100644 --- a/doc/solvers/DiscreteAlgebraicRiccatiEquation.md +++ b/doc/solvers/DiscreteAlgebraicRiccatiEquation.md @@ -45,10 +45,10 @@ $$K = \left(R + B^T P B\right)^{-1} B^T P A$$ ## Complexity Analysis -| Phase | Time | Space | Notes | -|-------|------|-------|-------| +| Phase | Time | Space | Notes | +|---------------|------------------------|----------|--------------------------------------------------------| | Per iteration | $O(n^3 + n^2 m + m^3)$ | $O(n^2)$ | Matrix multiplications + one $m \times m$ linear solve | -| Total solver | $O(I(n^3 + m^3))$ | $O(n^2)$ | $I$ iterations (typically 10–30) | +| Total solver | $O(I(n^3 + m^3))$ | $O(n^2)$ | $I$ iterations (typically 10–30) | **Why $O(n^3)$:** Each iteration involves $n \times n$ matrix products ($A^T P A$) and an $m \times m$ linear solve (for $S^{-1}$). When $m \ll n$, the matrix products dominate. @@ -77,12 +77,12 @@ $$K = \left(R + B^T P B\right)^{-1} B^T P A$$ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Continuous ARE (CARE)** | For continuous-time systems; different matrix equation | -| **Newton's method for DARE** | Quadratic convergence but requires solving a Sylvester equation per iteration | -| **Schur method** | Eigendecomposition-based; finds the solution in one pass but requires $O(n^3)$ eigenvalue computation | -| **Doubling algorithm** | $O(\log I)$ convergence via matrix sign function; useful for large systems | +| Variant | Key Difference | +|------------------------------|-------------------------------------------------------------------------------------------------------| +| **Continuous ARE (CARE)** | For continuous-time systems; different matrix equation | +| **Newton's method for DARE** | Quadratic convergence but requires solving a Sylvester equation per iteration | +| **Schur method** | Eigendecomposition-based; finds the solution in one pass but requires $O(n^3)$ eigenvalue computation | +| **Doubling algorithm** | $O(\log I)$ convergence via matrix sign function; useful for large systems | ## Applications @@ -104,11 +104,11 @@ graph LR DARE --> KF ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Gaussian Elimination](GaussianElimination.md) | Used at each iteration to solve the $m \times m$ linear sub-system | -| [LQR Controller](../controllers/Lqr.md) | Direct consumer — extracts optimal gain $K$ from the DARE solution matrix $P$ | -| [Kalman Filter](../filters/active/KalmanFilter.md) | Dual problem — the steady-state Kalman gain is computed by a transposed DARE | +| Algorithm | Relationship | +|----------------------------------------------------|-------------------------------------------------------------------------------| +| [Gaussian Elimination](GaussianElimination.md) | Used at each iteration to solve the $m \times m$ linear sub-system | +| [LQR Controller](../controllers/Lqr.md) | Direct consumer — extracts optimal gain $K$ from the DARE solution matrix $P$ | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Dual problem — the steady-state Kalman gain is computed by a transposed DARE | ## References & Further Reading diff --git a/doc/solvers/DurandKerner.md b/doc/solvers/DurandKerner.md index 8a653def..47dea80b 100644 --- a/doc/solvers/DurandKerner.md +++ b/doc/solvers/DurandKerner.md @@ -40,10 +40,10 @@ with angular positions offset by 0.4 radians to break symmetry. If $R < 0.1$, it ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| Per iteration | $O(n^2)$ | $O(n)$ | Evaluating $P$ and the denominator product for all $n$ roots | -| Total | $O(n^2 k)$ | $O(n)$ | $k$ iterations until convergence (typically $k \ll n$) | +| Case | Time | Space | Notes | +|---------------|------------|--------|--------------------------------------------------------------| +| Per iteration | $O(n^2)$ | $O(n)$ | Evaluating $P$ and the denominator product for all $n$ roots | +| Total | $O(n^2 k)$ | $O(n)$ | $k$ iterations until convergence (typically $k \ll n$) | **Why $O(n^2)$:** For each of the $n$ roots, computing the denominator product requires multiplying $n-1$ terms. @@ -80,13 +80,13 @@ After ~15–20 iterations the roots converge to $z \approx \{1, 2, 3\}$ (imagina ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Aberth-Ehrlich method** | Similar simultaneous iteration but includes a correction term that improves convergence for clustered roots | -| **Jenkins-Traub** | Sequential algorithm (one root at a time) with superior convergence for difficult polynomials; standard in numerical libraries | -| **Companion matrix + eigenvalues** | Converts to an eigenvalue problem; robust but $O(n^3)$ | -| **Laguerre's method** | Converges cubically for simple roots; sequential (extracts one root at a time, then deflates) | -| **Muller's method** | Uses quadratic interpolation; works for non-polynomial equations too | +| Variant | Key Difference | +|------------------------------------|--------------------------------------------------------------------------------------------------------------------------------| +| **Aberth-Ehrlich method** | Similar simultaneous iteration but includes a correction term that improves convergence for clustered roots | +| **Jenkins-Traub** | Sequential algorithm (one root at a time) with superior convergence for difficult polynomials; standard in numerical libraries | +| **Companion matrix + eigenvalues** | Converts to an eigenvalue problem; robust but $O(n^3)$ | +| **Laguerre's method** | Converges cubically for simple roots; sequential (extracts one root at a time, then deflates) | +| **Muller's method** | Uses quadratic interpolation; works for non-polynomial equations too | ## Applications @@ -106,9 +106,9 @@ graph LR GE -.->|"companion matrix alternative"| DK ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Root Locus](../analysis/RootLocus.md) | Primary consumer — calls Durand-Kerner to find characteristic polynomial roots at each gain step | +| Algorithm | Relationship | +|------------------------------------------------|-------------------------------------------------------------------------------------------------------| +| [Root Locus](../analysis/RootLocus.md) | Primary consumer — calls Durand-Kerner to find characteristic polynomial roots at each gain step | | [Gaussian Elimination](GaussianElimination.md) | Alternative approach: form the companion matrix and compute eigenvalues (requires a different solver) | ## References & Further Reading diff --git a/doc/solvers/GaussianElimination.md b/doc/solvers/GaussianElimination.md index e6a455f4..01adea36 100644 --- a/doc/solvers/GaussianElimination.md +++ b/doc/solvers/GaussianElimination.md @@ -37,11 +37,11 @@ For $AX = B$ where $B$ has $m$ columns, each column is solved independently. ## Complexity Analysis -| Phase | Time | Space | Notes | -|-------|------|-------|-------| -| Forward elimination | $O(n^3)$ | $O(n^2)$ | In-place on copies of $A$ and $b$ | -| Back-substitution | $O(n^2)$ | $O(n)$ | | -| Multi-column solve | $O(n^3 + n^2 m)$ | $O(n^2)$ | $m$ back-substitutions | +| Phase | Time | Space | Notes | +|---------------------|------------------|----------|-----------------------------------| +| Forward elimination | $O(n^3)$ | $O(n^2)$ | In-place on copies of $A$ and $b$ | +| Back-substitution | $O(n^2)$ | $O(n)$ | | +| Multi-column solve | $O(n^3 + n^2 m)$ | $O(n^2)$ | $m$ back-substitutions | **Why $O(n^3)$:** The elimination has $n$ stages; stage $k$ performs $(n-k)^2$ multiplications. Summing: $\sum_{k=1}^{n} k^2 \approx n^3/3$. @@ -86,13 +86,13 @@ Solve from the bottom up: $x_3 = 1$, $x_2 = 3$, $x_1 = 2$. ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Full pivoting** | Pivots on both rows and columns; more stable but rarely needed in practice | -| **LU factorization** | Stores the $L$ and $U$ factors for reuse; solves multiple right-hand sides efficiently | -| **Cholesky factorization** | Specialized for symmetric positive-definite matrices; $O(n^3/6)$ instead of $O(n^3/3)$ | -| **Gauss-Jordan elimination** | Reduces to reduced row echelon form (identity matrix); used for matrix inversion | -| **Iterative refinement** | Solves once, then iteratively corrects the residual to improve accuracy | +| Variant | Key Difference | +|------------------------------|----------------------------------------------------------------------------------------| +| **Full pivoting** | Pivots on both rows and columns; more stable but rarely needed in practice | +| **LU factorization** | Stores the $L$ and $U$ factors for reuse; solves multiple right-hand sides efficiently | +| **Cholesky factorization** | Specialized for symmetric positive-definite matrices; $O(n^3/6)$ instead of $O(n^3/3)$ | +| **Gauss-Jordan elimination** | Reduces to reduced row echelon form (identity matrix); used for matrix inversion | +| **Iterative refinement** | Solves once, then iteratively corrects the residual to improve accuracy | ## Applications @@ -115,11 +115,11 @@ graph LR LD -.->|"Toeplitz-specialized alternative"| GE ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Linear Regression](../estimators/LinearRegression.md) | Uses Gaussian elimination to solve the normal equation | -| [DARE Solver](DiscreteAlgebraicRiccatiEquation.md) | Calls Gaussian elimination at each Riccati iteration | -| [Levinson-Durbin](LevinsonDurbin.md) | Specialized $O(n^2)$ solver for Toeplitz systems; Gaussian elimination is the $O(n^3)$ fallback | +| Algorithm | Relationship | +|--------------------------------------------------------|-------------------------------------------------------------------------------------------------| +| [Linear Regression](../estimators/LinearRegression.md) | Uses Gaussian elimination to solve the normal equation | +| [DARE Solver](DiscreteAlgebraicRiccatiEquation.md) | Calls Gaussian elimination at each Riccati iteration | +| [Levinson-Durbin](LevinsonDurbin.md) | Specialized $O(n^2)$ solver for Toeplitz systems; Gaussian elimination is the $O(n^3)$ fallback | ## References & Further Reading diff --git a/doc/solvers/LevinsonDurbin.md b/doc/solvers/LevinsonDurbin.md index 7d062e2f..7d050025 100644 --- a/doc/solvers/LevinsonDurbin.md +++ b/doc/solvers/LevinsonDurbin.md @@ -41,9 +41,9 @@ If $|\mu_k| < 1$ for all $k$, the corresponding AR model is stable (all poles in ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| All | $O(n^2)$ | $O(n)$ | Versus $O(n^3)$ for general solvers | +| Case | Time | Space | Notes | +|------|----------|--------|-------------------------------------| +| All | $O(n^2)$ | $O(n)$ | Versus $O(n^3)$ for general solvers | **Why $O(n^2)$:** At order $k$, computing $\mu_k$ costs $O(k)$ and updating the solution costs $O(k)$. Summing over $k = 1, \ldots, n$: $\sum k = n(n+1)/2 = O(n^2)$. @@ -85,13 +85,13 @@ $\varphi^{(2)} = [0.5, 0, 0]$ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Split Levinson** | Replaces the two-vector recursion with a single vector; slightly more efficient | -| **Block Levinson** | Solves block-Toeplitz systems (matrix entries instead of scalars) | -| **Burg's method** | Computes reflection coefficients from data rather than autocovariances; often more accurate for short records | -| **Schur algorithm** | Computes reflection coefficients without forming the full solution; useful for VLSI implementations | -| **Superfast Toeplitz solvers** | $O(n \log^2 n)$ algorithms based on FFT and divide-and-conquer | +| Variant | Key Difference | +|--------------------------------|---------------------------------------------------------------------------------------------------------------| +| **Split Levinson** | Replaces the two-vector recursion with a single vector; slightly more efficient | +| **Block Levinson** | Solves block-Toeplitz systems (matrix entries instead of scalars) | +| **Burg's method** | Computes reflection coefficients from data rather than autocovariances; often more accurate for short records | +| **Schur algorithm** | Computes reflection coefficients without forming the full solution; useful for VLSI implementations | +| **Superfast Toeplitz solvers** | $O(n \log^2 n)$ algorithms based on FFT and divide-and-conquer | ## Applications @@ -114,10 +114,10 @@ graph LR LD -.->|"parametric PSD"| PSD ``` -| Algorithm | Relationship | -|-----------|-------------| -| [Yule-Walker](../estimators/YuleWalker.md) | Primary consumer — produces the Toeplitz system that Levinson-Durbin solves | -| [Gaussian Elimination](GaussianElimination.md) | General $O(n^3)$ alternative that ignores Toeplitz structure | +| Algorithm | Relationship | +|---------------------------------------------------------------|------------------------------------------------------------------------------------------------------| +| [Yule-Walker](../estimators/YuleWalker.md) | Primary consumer — produces the Toeplitz system that Levinson-Durbin solves | +| [Gaussian Elimination](GaussianElimination.md) | General $O(n^3)$ alternative that ignores Toeplitz structure | | [Power Spectral Density](../analysis/PowerDensitySpectrum.md) | Levinson-Durbin enables parametric PSD estimation as an alternative to Welch's non-parametric method | ## References & Further Reading diff --git a/doc/solvers/README.md b/doc/solvers/README.md index afde6723..e65d77a5 100644 --- a/doc/solvers/README.md +++ b/doc/solvers/README.md @@ -4,9 +4,9 @@ Numerical solvers for linear systems, polynomial roots, and matrix equations. ## Algorithms -| Algorithm | Description | -|-----------|-------------| -| [Gaussian Elimination](GaussianElimination.md) | Direct solver for dense linear systems using partial pivoting | -| [Levinson-Durbin](LevinsonDurbin.md) | Fast solver for Toeplitz linear systems exploiting structural symmetry | -| [Durand-Kerner](DurandKerner.md) | Simultaneous iterative root-finder for polynomials | -| [Discrete Algebraic Riccati Equation](DiscreteAlgebraicRiccatiEquation.md) | Iterative solver for the DARE arising in LQR and Kalman filter design | +| Algorithm | Description | +|----------------------------------------------------------------------------|------------------------------------------------------------------------| +| [Gaussian Elimination](GaussianElimination.md) | Direct solver for dense linear systems using partial pivoting | +| [Levinson-Durbin](LevinsonDurbin.md) | Fast solver for Toeplitz linear systems exploiting structural symmetry | +| [Durand-Kerner](DurandKerner.md) | Simultaneous iterative root-finder for polynomials | +| [Discrete Algebraic Riccati Equation](DiscreteAlgebraicRiccatiEquation.md) | Iterative solver for the DARE arising in LQR and Kalman filter design | diff --git a/doc/windowing/README.md b/doc/windowing/README.md index a9848050..20d26440 100644 --- a/doc/windowing/README.md +++ b/doc/windowing/README.md @@ -4,6 +4,6 @@ Window functions for reducing spectral leakage in frequency-domain analysis. ## Algorithms -| Algorithm | Description | -|-----------|-------------| +| Algorithm | Description | +|-------------------------------|---------------------------------------------------------------------------| | [Window Functions](window.md) | Rectangular, Hamming, Hanning, and Blackman windows for FFT preprocessing | From cda122ce4410efcf5fb101fd8e79173d2c9ce82a Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:49:20 +0100 Subject: [PATCH 11/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/windowing/window.md | 76 ++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/doc/windowing/window.md b/doc/windowing/window.md index fc82a96a..9813746d 100644 --- a/doc/windowing/window.md +++ b/doc/windowing/window.md @@ -14,12 +14,12 @@ A symmetric window of length $N$ is a sequence $w[n],\; n = 0, 1, \ldots, N-1$, ### Common Windows -| Window | Definition | Main-Lobe Width | Peak Side Lobe | -|--------|-----------|-----------------|----------------| -| **Rectangular** | $w[n] = 1$ | $2/N$ | $-13$ dB | -| **Hamming** | $w[n] = 0.54 - 0.46\cos\!\left(\frac{2\pi n}{N-1}\right)$ | $4/N$ | $-43$ dB | -| **Hann** | $w[n] = 0.5\left(1 - \cos\!\left(\frac{2\pi n}{N-1}\right)\right)$ | $4/N$ | $-32$ dB | -| **Blackman** | $w[n] = 0.42 - 0.5\cos\!\left(\frac{2\pi n}{N-1}\right) + 0.08\cos\!\left(\frac{4\pi n}{N-1}\right)$ | $6/N$ | $-58$ dB | +| Window | Definition | Main-Lobe Width | Peak Side Lobe | +|-----------------|------------------------------------------------------------------------------------------------------|-----------------|----------------| +| **Rectangular** | $w[n] = 1$ | $2/N$ | $-13$ dB | +| **Hamming** | $w[n] = 0.54 - 0.46\cos\!\left(\frac{2\pi n}{N-1}\right)$ | $4/N$ | $-43$ dB | +| **Hann** | $w[n] = 0.5\left(1 - \cos\!\left(\frac{2\pi n}{N-1}\right)\right)$ | $4/N$ | $-32$ dB | +| **Blackman** | $w[n] = 0.42 - 0.5\cos\!\left(\frac{2\pi n}{N-1}\right) + 0.08\cos\!\left(\frac{4\pi n}{N-1}\right)$ | $6/N$ | $-58$ dB | ### Frequency-Domain Perspective @@ -39,20 +39,20 @@ The **processing gain** $PG$ compares the noise bandwidth of the window to the r $$PG = \frac{\left(\sum w[n]\right)^2}{N \sum w[n]^2}$$ -| Window | Processing Gain | -|--------|----------------| -| Rectangular | 1.00 | -| Hamming | 0.73 | -| Hann | 0.67 | -| Blackman | 0.57 | +| Window | Processing Gain | +|-------------|-----------------| +| Rectangular | 1.00 | +| Hamming | 0.73 | +| Hann | 0.67 | +| Blackman | 0.57 | ## Complexity Analysis -| Operation | Time | Space | -|-----------|------|-------| -| Generate $N$ window coefficients | $O(N)$ | $O(N)$ | -| Apply window (element-wise multiply) | $O(N)$ | $O(1)$ extra | -| Pre-computed lookup | $O(1)$ per sample | $O(N)$ | +| Operation | Time | Space | +|--------------------------------------|-------------------|--------------| +| Generate $N$ window coefficients | $O(N)$ | $O(N)$ | +| Apply window (element-wise multiply) | $O(N)$ | $O(1)$ extra | +| Pre-computed lookup | $O(1)$ per sample | $O(N)$ | Window generation is dominated by trigonometric evaluations ($\cos$). For repeated use at a fixed $N$, pre-compute and store the coefficients in a lookup table. @@ -63,15 +63,15 @@ Window generation is dominated by trigonometric evaluations ($\cos$). For repeat **Step 1 — Generate the Hann window** | $n$ | $w[n] = 0.5(1 - \cos(2\pi n / 7))$ | -|-----|--------------------------------------| -| 0 | 0.000 | -| 1 | 0.188 | -| 2 | 0.611 | -| 3 | 0.950 | -| 4 | 0.950 | -| 5 | 0.611 | -| 6 | 0.188 | -| 7 | 0.000 | +|-----|------------------------------------| +| 0 | 0.000 | +| 1 | 0.188 | +| 2 | 0.611 | +| 3 | 0.950 | +| 4 | 0.950 | +| 5 | 0.611 | +| 6 | 0.188 | +| 7 | 0.000 | **Step 2 — Element-wise multiply** @@ -108,13 +108,13 @@ graph LR ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Kaiser window** | Parameterized by $\beta$; allows continuous trade-off between main-lobe width and side-lobe level | -| **Flat-top window** | Near-zero amplitude error at the cost of very wide main lobe; used for calibration | -| **Gaussian window** | Smooth, no side-lobe discontinuities; parameterized by $\sigma$ | -| **Dolph–Chebyshev** | Equiripple side lobes at a prescribed level; optimal for a given main-lobe width | -| **DPSS (Slepian)** | Maximum energy concentration in a given bandwidth; used in multi-taper spectral estimation | +| Variant | Key Difference | +|---------------------|---------------------------------------------------------------------------------------------------| +| **Kaiser window** | Parameterized by $\beta$; allows continuous trade-off between main-lobe width and side-lobe level | +| **Flat-top window** | Near-zero amplitude error at the cost of very wide main lobe; used for calibration | +| **Gaussian window** | Smooth, no side-lobe discontinuities; parameterized by $\sigma$ | +| **Dolph–Chebyshev** | Equiripple side lobes at a prescribed level; optimal for a given main-lobe width | +| **DPSS (Slepian)** | Maximum energy concentration in a given bandwidth; used in multi-taper spectral estimation | ## Applications @@ -137,11 +137,11 @@ graph TD W --> DCT ``` -| Algorithm | Relationship | -|-----------|-------------| -| [FFT](../analysis/FastFourierTransform.md) | Window is applied *before* the FFT to reduce spectral leakage | -| [Power Density Spectrum](../analysis/PowerDensitySpectrum.md) | Built-in windowing per segment in Welch's method | -| [DCT](../analysis/DiscreteCosineTransform.md) | DCT's implicit symmetry provides partial leakage suppression, but windowing still helps | +| Algorithm | Relationship | +|---------------------------------------------------------------|-----------------------------------------------------------------------------------------| +| [FFT](../analysis/FastFourierTransform.md) | Window is applied *before* the FFT to reduce spectral leakage | +| [Power Density Spectrum](../analysis/PowerDensitySpectrum.md) | Built-in windowing per segment in Welch's method | +| [DCT](../analysis/DiscreteCosineTransform.md) | DCT's implicit symmetry provides partial leakage suppression, but windowing still helps | ## References & Further Reading From 817e319aeb4f7427cae17cef0fca6a83f80fb4cc Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:50:14 +0100 Subject: [PATCH 12/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/analysis/RootLocus.md | 6 ++--- doc/filters/active/KalmanFilter.md | 36 +++++++++++++++--------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/doc/analysis/RootLocus.md b/doc/analysis/RootLocus.md index e6e1c6a8..7c3b80a6 100644 --- a/doc/analysis/RootLocus.md +++ b/doc/analysis/RootLocus.md @@ -39,9 +39,9 @@ At each gain step, the roots of $D(s) + K_i \cdot N(s) = 0$ are found using the ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| All | $O(N_g \cdot n^2 \cdot k)$ | $O(N_g \cdot n)$ | $N_g$ = gain steps, $n$ = polynomial order, $k$ = Durand-Kerner iterations per step | +| Case | Time | Space | Notes | +|------|----------------------------|------------------|-------------------------------------------------------------------------------------| +| All | $O(N_g \cdot n^2 \cdot k)$ | $O(N_g \cdot n)$ | $N_g$ = gain steps, $n$ = polynomial order, $k$ = Durand-Kerner iterations per step | **Why:** At each of the $N_g$ gain steps, a degree-$n$ polynomial is solved via Durand-Kerner, which performs $k$ iterations each costing $O(n^2)$ (evaluating the polynomial and computing the denominator product for all $n$ roots). diff --git a/doc/filters/active/KalmanFilter.md b/doc/filters/active/KalmanFilter.md index ba950886..0b6f7d17 100644 --- a/doc/filters/active/KalmanFilter.md +++ b/doc/filters/active/KalmanFilter.md @@ -48,11 +48,11 @@ The Kalman filter is the **minimum mean-square error (MMSE)** estimator among al ## Complexity Analysis -| Operation | Time | Space | Notes | -|-----------|------|-------|-------| -| Predict | $O(n^2)$ | $O(n^2)$ | Matrix multiply $F P F^T$ | -| Update | $O(n^2 m + m^3)$ | $O(nm)$ | Dominated by $S^{-1}$ ($m \times m$ inversion) and gain computation | -| Total per step | $O(n^2 m + m^3)$ | $O(n^2 + nm)$ | For $m \ll n$, approximately $O(n^2)$ | +| Operation | Time | Space | Notes | +|----------------|------------------|---------------|---------------------------------------------------------------------| +| Predict | $O(n^2)$ | $O(n^2)$ | Matrix multiply $F P F^T$ | +| Update | $O(n^2 m + m^3)$ | $O(nm)$ | Dominated by $S^{-1}$ ($m \times m$ inversion) and gain computation | +| Total per step | $O(n^2 m + m^3)$ | $O(n^2 + nm)$ | For $m \ll n$, approximately $O(n^2)$ | For typical embedded use with $n \leq 10$ and $m \leq 5$, each step completes in microseconds. @@ -97,14 +97,14 @@ The filter quickly moves toward the measurement because the initial covariance $ ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Extended Kalman Filter (EKF)** | Linearizes nonlinear $f(x)$ and $h(x)$ around the current estimate | -| **Unscented Kalman Filter (UKF)** | Propagates sigma points through nonlinearities; avoids explicit Jacobians | -| **Square-root Kalman Filter** | Maintains $\sqrt{P}$ instead of $P$ for improved numerical stability | -| **Information Filter** | Works with the inverse covariance (information matrix); better for multi-sensor fusion | -| **Kalman Smoother** | Uses future measurements to refine past estimates (offline, non-causal) | -| **Adaptive Kalman Filter** | Estimates $Q$ and $R$ online from innovation statistics | +| Variant | Key Difference | +|-----------------------------------|----------------------------------------------------------------------------------------| +| **Extended Kalman Filter (EKF)** | Linearizes nonlinear $f(x)$ and $h(x)$ around the current estimate | +| **Unscented Kalman Filter (UKF)** | Propagates sigma points through nonlinearities; avoids explicit Jacobians | +| **Square-root Kalman Filter** | Maintains $\sqrt{P}$ instead of $P$ for improved numerical stability | +| **Information Filter** | Works with the inverse covariance (information matrix); better for multi-sensor fusion | +| **Kalman Smoother** | Uses future measurements to refine past estimates (offline, non-causal) | +| **Adaptive Kalman Filter** | Estimates $Q$ and $R$ online from innovation statistics | ## Applications @@ -128,11 +128,11 @@ graph LR KF -->|"filtered measurement"| PID ``` -| Algorithm | Relationship | -|-----------|-------------| -| [LQR Controller](../controllers/Lqr.md) | The Kalman filter + LQR = LQG (Linear Quadratic Gaussian), the separation principle | -| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | The steady-state Kalman gain can be found by solving a DARE (dual of the LQR DARE) | -| [PID Controller](../controllers/Pid.md) | Kalman-filtered measurements can serve as the PID's process variable input | +| Algorithm | Relationship | +|---------------------------------------------------------------|-------------------------------------------------------------------------------------| +| [LQR Controller](../controllers/Lqr.md) | The Kalman filter + LQR = LQG (Linear Quadratic Gaussian), the separation principle | +| [DARE Solver](../solvers/DiscreteAlgebraicRiccatiEquation.md) | The steady-state Kalman gain can be found by solving a DARE (dual of the LQR DARE) | +| [PID Controller](../controllers/Pid.md) | Kalman-filtered measurements can serve as the PID's process variable input | ## References & Further Reading From 1f0763b1299e8aa1cef76fa438b22bc95a6121d0 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:50:54 +0100 Subject: [PATCH 13/15] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .github/workflows/validate-docs.yml | 2 +- doc/analysis/RootLocus.md | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/validate-docs.yml b/.github/workflows/validate-docs.yml index d2de9089..8937b353 100644 --- a/.github/workflows/validate-docs.yml +++ b/.github/workflows/validate-docs.yml @@ -14,7 +14,7 @@ jobs: - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: - python-version: '3.12' + python-version: "3.12" - name: Validate documentation structure run: python scripts/validate-docs.py diff --git a/doc/analysis/RootLocus.md b/doc/analysis/RootLocus.md index 7c3b80a6..33b5f1d8 100644 --- a/doc/analysis/RootLocus.md +++ b/doc/analysis/RootLocus.md @@ -86,12 +86,12 @@ As $K$ increases: the two poles approach each other on the real axis, meet betwe ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Complementary root locus** | Traces roots for $K < 0$ (positive feedback) | -| **Root contour** | Varies two or more parameters simultaneously | -| **Discrete root locus** | Same concept applied to $z$-domain polynomials for digital control | -| **Evans rules** | Analytical rules for sketching the root locus by hand (angle/magnitude criteria) | +| Variant | Key Difference | +|------------------------------|----------------------------------------------------------------------------------| +| **Complementary root locus** | Traces roots for $K < 0$ (positive feedback) | +| **Root contour** | Varies two or more parameters simultaneously | +| **Discrete root locus** | Same concept applied to $z$-domain polynomials for digital control | +| **Evans rules** | Analytical rules for sketching the root locus by hand (angle/magnitude criteria) | ## Applications From 214270fbfac66d14810418848fb2d29538d28f51 Mon Sep 17 00:00:00 2001 From: gfs Date: Fri, 20 Mar 2026 23:51:39 +0100 Subject: [PATCH 14/15] Apply suggestion from @github-actions[bot] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/filters/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/filters/README.md b/doc/filters/README.md index 532b9783..8fcd6d82 100644 --- a/doc/filters/README.md +++ b/doc/filters/README.md @@ -8,8 +8,8 @@ Digital filtering algorithms for noise reduction, state estimation, and signal c Filters that incorporate feedback and a dynamic internal model of the system. -| Algorithm | Description | -|-----------|-------------| +| Algorithm | Description | +|-----------------------------------------|--------------------------------------------------------------------------| | [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise | ### Passive Filters From 2c7ab733cb531022d1878e411347a7a7102418b2 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Fri, 20 Mar 2026 22:58:40 +0000 Subject: [PATCH 15/15] process review comments --- doc/neural_network/model/Model.md | 4 ++-- doc/neural_network/regularization/Regularization.md | 2 +- doc/solvers/GaussianElimination.md | 10 +++++----- scripts/validate-docs.py | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/doc/neural_network/model/Model.md b/doc/neural_network/model/Model.md index ab47b34e..007c5204 100644 --- a/doc/neural_network/model/Model.md +++ b/doc/neural_network/model/Model.md @@ -77,7 +77,7 @@ All operations scale linearly with the total parameter count $P$. | Layer 2 output size = Model output size | $1 = 1$ | ✓ | | All types derive from `Layer` | type trait check | ✓ | -**Parameter layout** ($P = 3 \times 3 + 3 + 1 \times 4 + 1 = 16$): +**Parameter layout** ($P = 3(2 + 1) + 1(3 + 1) = 9 + 4 = 13$): | Index | Parameter | |-------|--------------------------| @@ -96,7 +96,7 @@ All operations scale linearly with the total parameter count $P$. 1. Layer 2 backward → produces $\nabla W_2$, $\nabla b_2$, and $\delta_1 = W_2^T \delta_2 \odot \text{ReLU}'(z_1)$ 2. Layer 1 backward → produces $\nabla W_1$, $\nabla b_1$ -**Optimizer** receives the full $\nabla \theta \in \mathbb{R}^{16}$ and updates $\theta$. +**Optimizer** receives the full $\nabla \theta \in \mathbb{R}^{13}$ and updates $\theta$. ## Pitfalls & Edge Cases diff --git a/doc/neural_network/regularization/Regularization.md b/doc/neural_network/regularization/Regularization.md index 98990ceb..a9953f32 100644 --- a/doc/neural_network/regularization/Regularization.md +++ b/doc/neural_network/regularization/Regularization.md @@ -97,7 +97,7 @@ Regularization adds negligible computational cost — one pass over the paramete | **Early stopping** | Halts training before overfitting; regularization without modifying the loss | | **Data augmentation** | Expands the training set with transformed copies; reduces overfitting by increasing data diversity | | **Spectral normalization** | Constrains the spectral norm of weight matrices; stabilizes GAN training | -| **Weight clipping** | Hard constraint: $|\theta_i| \le c$; used in Wasserstein GANs | +| **Weight clipping** | Hard constraint: $\left\|\theta_i\right\| \le c$; used in Wasserstein GANs | ## Applications diff --git a/doc/solvers/GaussianElimination.md b/doc/solvers/GaussianElimination.md index 01adea36..de855490 100644 --- a/doc/solvers/GaussianElimination.md +++ b/doc/solvers/GaussianElimination.md @@ -59,8 +59,8 @@ $$\begin{bmatrix} -3 & -1 & 2 \\ 2 & 1 & -1 \\ -2 & 1 & 2 \end{bmatrix}, \quad b **Step 2 — Eliminate below pivot** -- Row 1: $\ell = 2/(-3) = -2/3$. Row 1 += $(2/3)$ × Row 0 → $[0, 1/3, 1/3 \mid 14/3]$ -- Row 2: $\ell = -2/(-3) = 2/3$. Row 2 -= $(2/3)$ × Row 0 → $[0, 5/3, 2/3 \mid 13/3]$ +- Row 1: $\ell = 2/(-3) = -2/3$. Row 1 += $(2/3)$ × Row 0 → $[0,\; 1/3,\; 1/3 \mid 2/3]$ +- Row 2: $\ell = -2/(-3) = 2/3$. Row 2 -= $(2/3)$ × Row 0 → $[0,\; 5/3,\; 2/3 \mid 13/3]$ **Step 3 — Column 1: pivot selection** @@ -68,13 +68,13 @@ $|1/3| < |5/3|$. Swap rows 1 and 2. **Step 4 — Eliminate below:** -Row 1 -= $(1/5)$ × Row 2 → upper-triangular form. +$\ell = (1/3)/(5/3) = 1/5$. Row 2 -= $(1/5)$ × Row 1 → $[0,\; 0,\; 1/5 \mid -1/5]$. Upper-triangular form reached. **Step 5 — Back-substitution:** -Solve from the bottom up: $x_3 = 1$, $x_2 = 3$, $x_1 = 2$. +$$x_3 = \frac{-1/5}{1/5} = -1, \qquad x_2 = \frac{13/3 - (2/3)(-1)}{5/3} = 3, \qquad x_1 = \frac{-11 - (-1)(3) - 2(-1)}{-3} = 2$$ -**Verification:** $2(2) + 1(3) - 1(1) = 6 \neq 8$ — let's re-verify with the original system... $2 \cdot 2 + 3 - 1 = 6$. The correct solution is $x = [2, 3, -1]^T$, which satisfies $4 + 3 + 1 = 8$ ✓. +**Verification:** $2(2) + 1(3) + (-1)(-1) = 8$ ✓, $\;-3(2) - 1(3) + 2(-1) = -11$ ✓, $\;-2(2) + 1(3) + 2(-1) = -3$ ✓. ## Pitfalls & Edge Cases diff --git a/scripts/validate-docs.py b/scripts/validate-docs.py index 05d8103a..9e9ac4ad 100644 --- a/scripts/validate-docs.py +++ b/scripts/validate-docs.py @@ -5,8 +5,8 @@ for the required section headings defined in the template. Exit codes: - 0 — all files pass - 1 — one or more files have missing sections + 0 — all files pass, or no algorithm documentation files found + 1 — doc directory is missing, or one or more files have missing sections """ import pathlib @@ -55,8 +55,8 @@ def main() -> int: ) if not md_files: - print("WARNING: no algorithm documentation files found.", file=sys.stderr) - return 1 + print("WARNING: no algorithm documentation files found.") + return 0 failures: list[tuple[pathlib.Path, list[str]]] = [] for path in md_files: