diff --git a/.vscode/launch.json b/.vscode/launch.json index 4a5c846f..e3823be1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -81,6 +81,26 @@ } ] }, + { + "name": "Kalman Filter Simulator", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/build/host/simulator/filters/KalmanFilter/Debug/numerical.simulator.filters.kalman", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "/usr/bin/gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + }, { "name": "Linux Debug", "type": "cppdbg", diff --git a/doc/filters/README.md b/doc/filters/README.md index 8fcd6d82..4e51db7f 100644 --- a/doc/filters/README.md +++ b/doc/filters/README.md @@ -8,9 +8,11 @@ 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 | -|-----------------------------------------|--------------------------------------------------------------------------| -| [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise | +| Algorithm | Description | +|------------------------------------------------------------|--------------------------------------------------------------------------| +| [Kalman Filter](active/KalmanFilter.md) | Optimal recursive state estimator for linear systems with Gaussian noise | +| [Extended Kalman Filter](active/ExtendedKalmanFilter.md) | Nonlinear state estimator using first-order linearization (Jacobians) | +| [Unscented Kalman Filter](active/UnscentedKalmanFilter.md) | Nonlinear state estimator using sigma points; no Jacobians required | ### Passive Filters diff --git a/doc/filters/active/ExtendedKalmanFilter.md b/doc/filters/active/ExtendedKalmanFilter.md new file mode 100644 index 00000000..8a9673d0 --- /dev/null +++ b/doc/filters/active/ExtendedKalmanFilter.md @@ -0,0 +1,136 @@ +# Extended Kalman Filter + +## Overview & Motivation + +Many real-world systems are **nonlinear**: a pendulum's restoring force is $-\sin\theta$, not $-\theta$; a radar measured range depends on $\sqrt{x^2 + y^2}$, not a linear combination of states. The standard Kalman filter assumes linear dynamics $(x_k = Fx_{k-1})$ and cannot handle this directly. + +The **Extended Kalman Filter (EKF)** extends the Kalman framework to nonlinear systems by **linearizing** the state transition and measurement functions around the current estimate at each step. It uses the same predict–update structure, but replaces the constant system matrices with **Jacobians** evaluated at the current operating point. + +This makes the EKF the simplest and most widely-used nonlinear state estimator — at the cost of requiring the user to supply Jacobian functions and the assumption that linearization remains accurate within the filter's uncertainty. + +## Mathematical Theory + +### Nonlinear State-Space Model + +$$x_k = f(x_{k-1}, u_{k-1}) + w_{k-1}, \quad w \sim \mathcal{N}(0, Q)$$ +$$z_k = h(x_k) + v_k, \quad v \sim \mathcal{N}(0, R)$$ + +where $f(\cdot)$ and $h(\cdot)$ are arbitrary (differentiable) nonlinear functions. + +### Predict Step + +1. Compute the **Jacobian** of $f$ at the current estimate: + +$$F_k = \left.\frac{\partial f}{\partial x}\right|_{\hat{x}_{k-1}}$$ + +2. Nonlinear state prediction: + +$$\hat{x}_k^- = f(\hat{x}_{k-1}, u_{k-1})$$ + +3. Covariance prediction (using the linearized model): + +$$P_k^- = F_k P_{k-1} F_k^T + Q_{k-1}$$ + +### Update Step + +1. Compute the **Jacobian** of $h$ at the predicted state: + +$$H_k = \left.\frac{\partial h}{\partial x}\right|_{\hat{x}_k^-}$$ + +2. Nonlinear innovation: + +$$y_k = z_k - h(\hat{x}_k^-)$$ + +3. Innovation covariance, Kalman gain, state and covariance updates follow the standard Kalman filter equations using the Jacobian $H_k$: + +$$S_k = H_k P_k^- H_k^T + R_k$$ +$$K_k = P_k^- H_k^T S_k^{-1}$$ +$$\hat{x}_k = \hat{x}_k^- + K_k y_k$$ +$$P_k = (I - K_k H_k) P_k^-$$ + +## Complexity Analysis + +| Operation | Time | Space | Notes | +|----------------|-------------------------|---------------|------------------------------------------------------------------| +| Jacobian eval | $O(n^2)$ (user-defined) | $O(n^2)$ | Depends on the specific nonlinear functions | +| Predict | $O(n^2)$ | $O(n^2)$ | Matrix multiply $F P F^T$ plus nonlinear state propagation | +| Update | $O(n^2 m + m^3)$ | $O(nm)$ | Same as standard Kalman — the linearized equations are identical | +| Total per step | $O(n^2 m + m^3)$ | $O(n^2 + nm)$ | Dominated by Jacobian evaluation for complex models | + +## Step-by-Step Walkthrough + +**System:** Estimating angle and angular velocity of a simple pendulum from noisy angle measurements. + +State: $x = \begin{bmatrix} \theta \\ \dot\theta \end{bmatrix}$, $\Delta t = 0.1$ s. + +Nonlinear dynamics: +$$f(x) = \begin{bmatrix} \theta + \dot\theta \Delta t \\ \dot\theta - \sin(\theta) \Delta t \end{bmatrix}$$ + +Jacobian: +$$F = \begin{bmatrix} 1 & \Delta t \\ -\cos(\theta) \Delta t & 1 \end{bmatrix}$$ + +Linear measurement: $h(x) = \theta$, $H = [1 \; 0]$. + +At $\hat{x}_0 = [0.3, 0]^T$: +- **Predict:** $\hat{x}_1^- = [0.3, -0.0296]^T$ (velocity decreases due to restoring force $-\sin 0.3$) +- **Update with $z_1 = 0.28$:** The Kalman gain weights the measurement against the prediction, pulling $\theta$ toward 0.28. + +After 50 iterations the EKF tracks the true pendulum oscillation closely, despite the nonlinear dynamics. + +## Pitfalls & Edge Cases + +- **Linearization error.** The EKF assumes the nonlinearity is approximately linear within the filter's uncertainty. Large initial errors or highly nonlinear systems can cause divergence. +- **Jacobian correctness.** Incorrect Jacobians silently produce wrong estimates. Always validate Jacobians numerically (e.g., finite-difference check) before deploying. +- **Non-observable modes.** If $H$ does not observe all states, convergence of unobserved states depends entirely on the model $f$. +- **Large time steps.** For stiff or fast dynamics, large $\Delta t$ amplifies linearization errors. Reduce the step size or use a higher-order integration scheme. +- **Covariance symmetry.** Numerical drift can break symmetry of $P$; the Joseph form of the covariance update is more robust for long runs. + +## Variants & Generalizations + +- **Iterated EKF (IEKF).** Re-linearizes the measurement function at the updated state estimate and repeats the update step until convergence. Reduces linearization error in the measurement model at the cost of multiple Jacobian evaluations per time step. +- **Second-Order EKF.** Includes second-order terms of the Taylor expansion in the prediction and update equations. Improves accuracy for moderately nonlinear systems but requires Hessians of $f$ and $h$. +- **Error-State EKF.** Tracks a small error state $\delta x$ rather than the full state. Popular in inertial navigation where the nominal trajectory is integrated separately and the filter corrects deviations. +- **EKF with Joseph Form.** Replaces the standard covariance update $P = (I - KH)P^-$ with the symmetric Joseph form $P = (I - KH)P^-(I - KH)^T + KRK^T$ to guarantee positive-definiteness under finite-precision arithmetic. +- **EKF with Control Input.** When the control $u$ is present, the state transition becomes $f(x, u)$ and the Jacobian is $\partial f / \partial x$ evaluated at $(\hat{x}, u)$. This variant is supported directly in the implementation via the `ControlSize` template parameter. + +## Comparison with Other Filters + +| Filter | Jacobian Required? | Accuracy for Nonlinear Systems | Computational Cost | +|---------------|--------------------|--------------------------------|--------------------| +| Kalman Filter | No (linear only) | Exact for linear | Lowest | +| **EKF** | Yes | First-order approximation | Low | +| UKF | No | Second-order approximation | Moderate | +| Particle | No | Arbitrary (Monte Carlo) | High | + +## Applications + +- **Attitude estimation** — Fusing gyroscope and accelerometer for orientation (nonlinear quaternion kinematics). +- **Robot localization** — SLAM (Simultaneous Localization and Mapping) with range-bearing measurements. +- **Pendulum control** — Estimating angle and angular velocity for swing-up or balancing. +- **Battery management** — Nonlinear electrochemical models for state-of-charge estimation. +- **Spacecraft navigation** — Orbit determination from range and range-rate measurements. + +## Connections to Other Algorithms + +```mermaid +graph LR + EKF["Extended Kalman Filter"] + KF["Kalman Filter"] + UKF["Unscented Kalman Filter"] + EL["Euler-Lagrange"] + EKF -->|"linear limit"| KF + UKF -->|"alternative to"| EKF + EL -->|"plant model"| EKF +``` + +| Algorithm | Relationship | +|-----------------------------------------------------|------------------------------------------------------------------------| +| [Kalman Filter](KalmanFilter.md) | The EKF reduces to the standard KF when $f$ and $h$ are linear | +| [Unscented Kalman Filter](UnscentedKalmanFilter.md) | Avoids Jacobians using sigma points; better for highly nonlinear cases | +| [Euler-Lagrange](../../dynamics/EulerLagrange.md) | Provides the nonlinear dynamics model $f(x)$ for mechanical systems | + +## References & Further Reading + +- Simon, D., *Optimal State Estimation: Kalman, H∞, and Nonlinear Approaches*, Wiley, 2006 — Chapters 13–14. +- Bar-Shalom, Y., Li, X.R. and Kirubarajan, T., *Estimation with Applications to Tracking and Navigation*, Wiley, 2001. +- Julier, S.J. and Uhlmann, J.K., "Unscented Filtering and Nonlinear Estimation", *Proceedings of the IEEE*, 92(3), 2004 — Motivation for UKF as EKF alternative. diff --git a/doc/filters/active/UnscentedKalmanFilter.md b/doc/filters/active/UnscentedKalmanFilter.md new file mode 100644 index 00000000..0a2d99a5 --- /dev/null +++ b/doc/filters/active/UnscentedKalmanFilter.md @@ -0,0 +1,156 @@ +# Unscented Kalman Filter + +## Overview & Motivation + +The Extended Kalman Filter (EKF) linearizes nonlinearities using Jacobians. This works well for mild nonlinearities, but the first-order approximation can introduce significant errors when: + +- The nonlinear functions are highly curved (large second derivatives). +- The state uncertainty is large (the linearization point is far from the true state). +- Jacobians are difficult or expensive to derive analytically. + +The **Unscented Kalman Filter (UKF)** addresses all three problems by replacing linearization with a **deterministic sampling** approach. Instead of approximating the nonlinear function, it approximates the *probability distribution* by choosing a small set of carefully weighted sample points — called **sigma points** — and propagating them through the true nonlinear function. The statistics (mean and covariance) are then reconstructed from the transformed points. + +This captures the true mean and covariance to **second-order accuracy** for any nonlinearity, without computing a single Jacobian. + +## Mathematical Theory + +### Sigma Point Generation + +Given state estimate $\hat{x} \in \mathbb{R}^n$ and covariance $P$, generate $2n+1$ sigma points: + +$$\sigma_0 = \hat{x}$$ +$$\sigma_i = \hat{x} + \left(\sqrt{(n + \lambda) P}\right)_i, \quad i = 1, \ldots, n$$ +$$\sigma_{i+n} = \hat{x} - \left(\sqrt{(n + \lambda) P}\right)_i, \quad i = 1, \ldots, n$$ + +where $\left(\sqrt{M}\right)_i$ denotes the $i$-th column of the matrix square root (Cholesky decomposition $M = LL^T$, using columns of $L$), and: + +$$\lambda = \alpha^2 (n + \kappa) - n$$ + +### Weights + +$$w_0^{(m)} = \frac{\lambda}{n + \lambda}, \quad w_0^{(c)} = \frac{\lambda}{n + \lambda} + (1 - \alpha^2 + \beta)$$ +$$w_i^{(m)} = w_i^{(c)} = \frac{1}{2(n + \lambda)}, \quad i = 1, \ldots, 2n$$ + +Parameters: +- $\alpha$: Controls spread of sigma points ($10^{-4} \leq \alpha \leq 1$). Smaller values keep points closer to the mean. +- $\beta$: Incorporates prior knowledge about the distribution ($\beta = 2$ is optimal for Gaussian). +- $\kappa$: Secondary scaling parameter (typically $\kappa = 0$ or $\kappa = 3 - n$). + +### Predict Step + +1. Propagate sigma points through the nonlinear state transition: + +$$\sigma_i^* = f(\sigma_i, u)$$ + +2. Reconstruct predicted state and covariance: + +$$\hat{x}_k^- = \sum_{i=0}^{2n} w_i^{(m)} \sigma_i^*$$ +$$P_k^- = \sum_{i=0}^{2n} w_i^{(c)} (\sigma_i^* - \hat{x}_k^-)(\sigma_i^* - \hat{x}_k^-)^T + Q$$ + +### Update Step + +1. Generate new sigma points from the predicted state $\hat{x}_k^-$ and $P_k^-$. + +2. Transform sigma points through the measurement function: + +$$z_i = h(\sigma_i)$$ + +3. Predicted measurement and covariances: + +$$\hat{z}_k = \sum_{i=0}^{2n} w_i^{(m)} z_i$$ +$$S_k = \sum_{i=0}^{2n} w_i^{(c)} (z_i - \hat{z}_k)(z_i - \hat{z}_k)^T + R$$ +$$P_{xz} = \sum_{i=0}^{2n} w_i^{(c)} (\sigma_i - \hat{x}_k^-)(z_i - \hat{z}_k)^T$$ + +4. Kalman gain and state update: + +$$K_k = P_{xz} S_k^{-1}$$ +$$\hat{x}_k = \hat{x}_k^- + K_k (z_k - \hat{z}_k)$$ +$$P_k = P_k^- - K_k S_k K_k^T$$ + +## Complexity Analysis + +| Operation | Time | Space | Notes | +|----------------------|-----------------------|---------------|--------------------------------------------------| +| Sigma point gen | $O(n^3)$ | $O(n^2)$ | Dominated by Cholesky decomposition | +| State propagation | $O((2n+1) \cdot c_f)$ | $O(n^2)$ | $c_f$ = cost of evaluating $f(x)$ | +| Mean/cov reconstruct | $O(n^2 \cdot (2n+1))$ | $O(n^2)$ | Weighted outer products | +| Update | $O(n^2 m + m^3)$ | $O(nm)$ | Same as standard Kalman for the gain computation | +| Total per step | $O(n^3 + n^2 m)$ | $O(n^2 + nm)$ | Cholesky and sigma point propagation dominate | + +For $n \leq 10$, the additional cost over EKF is small — and the elimination of Jacobian derivation is a significant engineering benefit. + +## Step-by-Step Walkthrough + +**System:** Same pendulum as the EKF example, $x = [\theta, \dot\theta]^T$, $n = 2$, $\Delta t = 0.1$ s. + +**Parameters:** $\alpha = 0.1$, $\beta = 2$, $\kappa = 0$ → $\lambda = -1.98$. + +**Initial:** $\hat{x}_0 = [0.3, 0]^T$, $P_0 = \text{diag}(0.5, 0.5)$. + +1. **Generate 5 sigma points** from $\hat{x}_0$ and $P_0$ using Cholesky of $P_0$. +2. **Propagate** each sigma point through $f(x)$ (pendulum dynamics). +3. **Reconstruct** $\hat{x}_1^-$ and $P_1^-$ from the weighted transformed points. +4. **Generate new sigma points** from $\hat{x}_1^-$ and $P_1^-$. +5. **Transform** through $h(x) = \theta$ for the measurement update. +6. **Compute** $S$, $P_{xz}$, $K$ and update state and covariance. + +The UKF naturally captures the curvature of $-\sin\theta$ without computing $\cos\theta$ — the sigma points "feel" the nonlinearity directly. + +## Pitfalls & Edge Cases + +- **Covariance non-positive-definiteness.** Numerical errors or extreme sigma point spread can make $P$ lose positive-definiteness, causing the Cholesky decomposition to fail. Use a small regularization term or the square-root UKF variant. +- **Alpha tuning.** Very small $\alpha$ (e.g., $10^{-4}$) can cause the zeroth weight $w_0^{(c)}$ to be negative, leading to negative covariance contributions. Larger $\alpha$ (e.g., $0.1$) is safer for low-dimensional systems. +- **Sigma point overflow.** For fixed-point types, the scaled columns $\sqrt{(n+\lambda)P}$ may exceed the representable range. Use float for the UKF or carefully bound the covariance. +- **Non-Gaussian distributions.** The UKF assumes a Gaussian approximation. For multi-modal or heavily skewed distributions, consider particle filters. +- **Computational cost.** For large state dimensions ($n > 20$), the $2n+1$ sigma points and $O(n^3)$ Cholesky become significant. Consider sparsification or reduced-rank approximations. + +## Variants & Generalizations + +- **Square-Root UKF (SR-UKF).** Propagates the Cholesky factor $S$ (where $P = SS^T$) instead of $P$ directly, using QR decompositions and rank-1 Cholesky updates. Guarantees positive-definiteness and improves numerical stability. +- **Augmented UKF.** Augments the state vector with the process and measurement noise vectors, generating sigma points in the joint space. Captures correlations between state and noise at the cost of more sigma points ($2(n + n_w + n_v) + 1$). +- **Reduced Sigma Point Filters.** Use fewer than $2n + 1$ sigma points (e.g., the Spherical Simplex UKF uses $n + 2$ points) to reduce computation for large state dimensions. +- **UKF with Control Input.** The state transition becomes $f(x, u)$ and each sigma point is propagated as $f(\sigma_i, u)$. Supported in the implementation via the `ControlSize` template parameter. +- **Cubature Kalman Filter (CKF).** A special case of the UKF with $\alpha = 1$, $\beta = 0$, $\kappa = 0$, using third-degree spherical-radial cubature rules. Simpler weight computation with no negative weights. + +## Comparison with Other Filters + +| Filter | Jacobian Required? | Accuracy Order | Handles High Nonlinearity? | Computational Cost | +|---------------|--------------------|----------------|----------------------------|--------------------| +| Kalman Filter | No (linear only) | Exact (linear) | No | Lowest | +| EKF | Yes | 1st order | Moderate | Low | +| **UKF** | No | 2nd order | Good | Moderate | +| Particle | No | Arbitrary | Excellent | High | + +## Applications + +- **Attitude estimation** — Quaternion-based orientation estimation (avoiding gimbal lock and Jacobian complexity). +- **Target tracking** — Radar/lidar tracking with range-bearing measurements (highly nonlinear in Cartesian coordinates). +- **Robotics** — State estimation for mobile robots and manipulators with nonlinear kinematics. +- **Chemical processes** — Concentration estimation in nonlinear reaction kinetics. +- **Power systems** — Dynamic state estimation in electrical grids with nonlinear power flow equations. + +## Connections to Other Algorithms + +```mermaid +graph LR + UKF["Unscented Kalman Filter"] + KF["Kalman Filter"] + EKF["Extended Kalman Filter"] + CHO["Cholesky Decomposition"] + UKF -->|"linear limit"| KF + EKF -->|"alternative to"| UKF + CHO -->|"sigma points"| UKF +``` + +| Algorithm | Relationship | +|------------------------------------------------------------------|---------------------------------------------------------------------------------------| +| [Kalman Filter](KalmanFilter.md) | The UKF reduces to the standard KF when $f$ and $h$ are linear | +| [Extended Kalman Filter](ExtendedKalmanFilter.md) | Uses Jacobians instead of sigma points; simpler but less accurate for nonlinear cases | +| [Cholesky Decomposition](../../solvers/CholeskyDecomposition.md) | Used internally to generate sigma points from the covariance matrix | + +## References & Further Reading + +- Julier, S.J. and Uhlmann, J.K., "A New Extension of the Kalman Filter to Nonlinear Systems", in *Proc. AeroSense*, 1997. +- Julier, S.J. and Uhlmann, J.K., "Unscented Filtering and Nonlinear Estimation", *Proceedings of the IEEE*, 92(3), 2004. +- Wan, E.A. and van der Merwe, R., "The Unscented Kalman Filter for Nonlinear Estimation", in *Proc. IEEE Adaptive Systems for Signal Processing*, 2000. +- Simon, D., *Optimal State Estimation: Kalman, H∞, and Nonlinear Approaches*, Wiley, 2006 — Chapter 14. diff --git a/doc/solvers/CholeskyDecomposition.md b/doc/solvers/CholeskyDecomposition.md new file mode 100644 index 00000000..651e1c70 --- /dev/null +++ b/doc/solvers/CholeskyDecomposition.md @@ -0,0 +1,73 @@ +# Cholesky Decomposition + +## Overview & Motivation + +The **Cholesky decomposition** factors a symmetric positive-definite matrix $A$ into the product $A = LL^T$, where $L$ is a lower triangular matrix with positive diagonal entries. This is the matrix equivalent of taking a "square root." + +It is approximately twice as fast as LU decomposition for symmetric positive-definite systems and is numerically stable without pivoting. In this library, it is used primarily by the Unscented Kalman Filter to generate sigma points from the state covariance matrix. + +## Mathematical Theory + +Given $A \in \mathbb{R}^{n \times n}$ symmetric positive-definite, compute $L$ such that $A = LL^T$: + +$$L_{jj} = \sqrt{A_{jj} - \sum_{k=0}^{j-1} L_{jk}^2}$$ + +$$L_{ij} = \frac{1}{L_{jj}} \left( A_{ij} - \sum_{k=0}^{j-1} L_{ik} L_{jk} \right), \quad i > j$$ + +## Complexity Analysis + +| Operation | Time | Space | Notes | +|---------------|------------|----------|-------------------------------------------| +| Decomposition | $O(n^3/6)$ | $O(n^2)$ | Half the cost of general LU decomposition | + +## Step-by-Step Walkthrough + +**Input:** $A = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix}$ (symmetric positive-definite). + +Compute $L$ column by column: + +| Step | Formula | Value | +|----------|-------------------------------------------|-------| +| $L_{00}$ | $\sqrt{A_{00}} = \sqrt{4}$ | $2$ | +| $L_{10}$ | $A_{10} / L_{00} = 2 / 2$ | $1$ | +| $L_{11}$ | $\sqrt{A_{11} - L_{10}^2} = \sqrt{5 - 1}$ | $2$ | + +**Result:** + +$$L = \begin{bmatrix} 2 & 0 \\ 1 & 2 \end{bmatrix}$$ + +**Verify:** $LL^T = \begin{bmatrix} 2 & 0 \\ 1 & 2 \end{bmatrix} \begin{bmatrix} 2 & 1 \\ 0 & 2 \end{bmatrix} = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix} = A$ ✓ + +## Pitfalls & Edge Cases + +- **Non-positive-definite input.** If $A$ is not positive-definite, a diagonal element under the square root will be negative, producing NaN. Always verify the input or add a small regularization $A + \epsilon I$. +- **Numerical precision.** In fixed-point arithmetic, the intermediate sums and square root can lose precision. Use float for the decomposition and convert back if needed. +- **Zero diagonal.** A zero or near-zero diagonal in $L$ indicates a singular or nearly singular matrix. + +## Variants & Generalizations + +- **$LDL^T$ Decomposition.** Avoids the square root by factoring $A = LDL^T$ where $D$ is diagonal. Preferred in fixed-point arithmetic where `sqrt` is expensive or imprecise. +- **Cholesky–Banachiewicz vs Cholesky–Crout.** Two orderings of the same algorithm: row-oriented (Banachiewicz, used in this implementation) vs column-oriented (Crout). Performance differs by cache access pattern. +- **Incomplete Cholesky.** Drops small entries during factorization to produce a sparse approximate factor. Used as a preconditioner for iterative solvers (e.g., conjugate gradient). +- **Rank-1 Update/Downdate.** Given the existing factor $L$ of $A$, efficiently compute the factor of $A + vv^T$ (or $A - vv^T$) in $O(n^2)$ without recomputing from scratch. Central to the square-root UKF. +- **Block Cholesky.** Exploits block structure in large matrices for better cache utilization and parallelism. + +## Applications + +- **Sigma point generation** — The Unscented Kalman Filter uses Cholesky decomposition of the covariance matrix $P = LL^T$ to spread sigma points along the principal uncertainty directions. +- **Solving symmetric positive-definite systems** — Given $Ax = b$, compute $L$, then solve $Ly = b$ (forward substitution) and $L^Tx = y$ (back substitution). Twice as fast as general LU. +- **Multivariate normal sampling** — To generate $x \sim \mathcal{N}(\mu, \Sigma)$, compute $L$ from $\Sigma$ and set $x = \mu + Lz$ where $z \sim \mathcal{N}(0, I)$. +- **Least squares** — The normal equations $A^TAx = A^Tb$ produce a symmetric positive-definite system solvable via Cholesky. +- **Optimization** — Newton-type methods with positive-definite Hessians use Cholesky to compute search directions. + +## Connections to Other Algorithms + +| Algorithm | Relationship | +|-----------------------------------------------------------------------|-------------------------------------------------------------------| +| [Unscented Kalman Filter](../filters/active/UnscentedKalmanFilter.md) | Uses Cholesky to generate sigma points from the covariance matrix | +| [Gaussian Elimination](GaussianElimination.md) | General-purpose alternative; does not exploit symmetry | + +## References & Further Reading + +- Golub, G.H. and Van Loan, C.F., *Matrix Computations*, 4th ed., Johns Hopkins University Press, 2013. +- Press, W.H. et al., *Numerical Recipes*, 3rd ed., Cambridge University Press, 2007 — Section 2.9. diff --git a/doc/solvers/README.md b/doc/solvers/README.md index e65d77a5..1d8228ea 100644 --- a/doc/solvers/README.md +++ b/doc/solvers/README.md @@ -6,6 +6,7 @@ Numerical solvers for linear systems, polynomial roots, and matrix equations. | Algorithm | Description | |----------------------------------------------------------------------------|------------------------------------------------------------------------| +| [Cholesky Decomposition](CholeskyDecomposition.md) | Fast factorization for symmetric positive-definite matrices | | [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 | diff --git a/numerical/filters/active/CMakeLists.txt b/numerical/filters/active/CMakeLists.txt index 358517e3..dfb9c2ba 100644 --- a/numerical/filters/active/CMakeLists.txt +++ b/numerical/filters/active/CMakeLists.txt @@ -1,17 +1,25 @@ -add_library(numerical.filters.active ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +add_library(numerical.filters.active ${EMIL_EXCLUDE_FROM_ALL}) -target_include_directories(numerical.filters.active INTERFACE +target_include_directories(numerical.filters.active PUBLIC "$" "$" ) -target_link_libraries(numerical.filters.active INTERFACE +target_link_libraries(numerical.filters.active PUBLIC infra.util numerical.math + numerical.solver ) target_sources(numerical.filters.active PRIVATE + ExtendedKalmanFilter.cpp + ExtendedKalmanFilter.hpp + KalmanFilter.cpp KalmanFilter.hpp + KalmanFilterBase.cpp + KalmanFilterBase.hpp + UnscentedKalmanFilter.cpp + UnscentedKalmanFilter.hpp ) add_subdirectory(test) diff --git a/numerical/filters/active/ExtendedKalmanFilter.cpp b/numerical/filters/active/ExtendedKalmanFilter.cpp new file mode 100644 index 00000000..698a7040 --- /dev/null +++ b/numerical/filters/active/ExtendedKalmanFilter.cpp @@ -0,0 +1,8 @@ +#include "numerical/filters/active/ExtendedKalmanFilter.hpp" + +namespace filters +{ + template class ExtendedKalmanFilter; + template class ExtendedKalmanFilter; + template class ExtendedKalmanFilter; +} diff --git a/numerical/filters/active/ExtendedKalmanFilter.hpp b/numerical/filters/active/ExtendedKalmanFilter.hpp new file mode 100644 index 00000000..e6e5fc2c --- /dev/null +++ b/numerical/filters/active/ExtendedKalmanFilter.hpp @@ -0,0 +1,121 @@ +#pragma once + +#include "infra/util/Function.hpp" +#include "numerical/filters/active/KalmanFilterBase.hpp" +#include "numerical/math/CompilerOptimizations.hpp" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +namespace filters +{ + template + class ExtendedKalmanFilter + : public KalmanFilterBase + { + using Base = KalmanFilterBase; + + public: + using typename Base::ControlMatrix; + using typename Base::ControlVector; + using typename Base::MeasurementCovariance; + using typename Base::MeasurementMatrix; + using typename Base::MeasurementVector; + using typename Base::StateMatrix; + using typename Base::StateVector; + + using StateTransitionFn = infra::Function; + using StateJacobianFn = infra::Function; + using MeasurementFn = infra::Function; + using MeasurementJacobianFn = infra::Function; + + using StateTransitionWithControlFn = infra::Function; + using StateJacobianWithControlFn = infra::Function; + + ExtendedKalmanFilter(const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionFn f, StateJacobianFn jf, + MeasurementFn h, MeasurementJacobianFn jh) + requires(ControlSize == 0); + + ExtendedKalmanFilter(const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionWithControlFn f, StateJacobianWithControlFn jf, + MeasurementFn h, MeasurementJacobianFn jh) + requires(ControlSize > 0); + + void Predict() + requires(ControlSize == 0); + + void Predict(const ControlVector& u) + requires(ControlSize > 0); + + void Update(const MeasurementVector& measurement); + + private: + StateTransitionFn stateTransitionFn; + StateJacobianFn stateJacobianFn; + StateTransitionWithControlFn stateTransitionWithControlFn; + StateJacobianWithControlFn stateJacobianWithControlFn; + MeasurementFn measurementFn; + MeasurementJacobianFn measurementJacobianFn; + }; + + // Implementation // + + template + ExtendedKalmanFilter::ExtendedKalmanFilter( + const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionFn f, StateJacobianFn jf, + MeasurementFn h, MeasurementJacobianFn jh) + requires(ControlSize == 0) + : Base(initialState, initialCovariance) + , stateTransitionFn(f) + , stateJacobianFn(jf) + , measurementFn(h) + , measurementJacobianFn(jh) + {} + + template + ExtendedKalmanFilter::ExtendedKalmanFilter( + const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionWithControlFn f, StateJacobianWithControlFn jf, + MeasurementFn h, MeasurementJacobianFn jh) + requires(ControlSize > 0) + : Base(initialState, initialCovariance) + , stateTransitionWithControlFn(f) + , stateJacobianWithControlFn(jf) + , measurementFn(h) + , measurementJacobianFn(jh) + {} + + template + OPTIMIZE_FOR_SPEED void ExtendedKalmanFilter::Predict() + requires(ControlSize == 0) + { + auto F = stateJacobianFn(this->state()); + this->state() = stateTransitionFn(this->state()); + this->covariance() = F * this->covariance() * F.Transpose() + this->processNoise(); + } + + template + OPTIMIZE_FOR_SPEED void ExtendedKalmanFilter::Predict(const ControlVector& u) + requires(ControlSize > 0) + { + auto F = stateJacobianWithControlFn(this->state(), u); + this->state() = stateTransitionWithControlFn(this->state(), u); + this->covariance() = F * this->covariance() * F.Transpose() + this->processNoise(); + } + + template + OPTIMIZE_FOR_SPEED void ExtendedKalmanFilter::Update(const MeasurementVector& measurement) + { + auto H = measurementJacobianFn(this->state()); + auto innovation = measurement - measurementFn(this->state()); + auto K = this->ComputeKalmanGain(H); + this->UpdateState(innovation, K, H); + } + + extern template class ExtendedKalmanFilter; + extern template class ExtendedKalmanFilter; + extern template class ExtendedKalmanFilter; +} diff --git a/numerical/filters/active/KalmanFilter.cpp b/numerical/filters/active/KalmanFilter.cpp new file mode 100644 index 00000000..677cb3c6 --- /dev/null +++ b/numerical/filters/active/KalmanFilter.cpp @@ -0,0 +1,9 @@ +#include "numerical/filters/active/KalmanFilter.hpp" + +namespace filters +{ + template class KalmanFilter; + template class KalmanFilter; + template class KalmanFilter; + template class KalmanFilter; +} diff --git a/numerical/filters/active/KalmanFilter.hpp b/numerical/filters/active/KalmanFilter.hpp index 1a56bab3..eab3e3f2 100644 --- a/numerical/filters/active/KalmanFilter.hpp +++ b/numerical/filters/active/KalmanFilter.hpp @@ -1,139 +1,102 @@ -#ifndef FILTERS_ACTIVE_KALMAN_FILTER_HPP -#define FILTERS_ACTIVE_KALMAN_FILTER_HPP +#pragma once -#include "numerical/math/Matrix.hpp" +#include "numerical/filters/active/KalmanFilterBase.hpp" +#include "numerical/math/CompilerOptimizations.hpp" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif namespace filters { - namespace detail - { - template - inline constexpr bool is_kalman_supported_v = - std::disjunction_v< - std::is_same, - std::is_same, - std::is_same>; - } - - template + template class KalmanFilter + : public KalmanFilterBase { - static_assert(detail::is_kalman_supported_v, - "KalmanFilter only supports float, Q15, or Q31 types"); - static_assert(math::detail::is_valid_dimensions_v, - "State dimensions must be positive"); - static_assert(math::detail::is_valid_dimensions_v, - "Measurement dimensions must be positive"); + using Base = KalmanFilterBase; public: - using StateMatrix = math::SquareMatrix; - using StateVector = math::Vector; - using MeasurementMatrix = math::Matrix; - using MeasurementVector = math::Vector; - using MeasurementCovariance = math::SquareMatrix; + using typename Base::ControlMatrix; + using typename Base::ControlVector; + using typename Base::MeasurementCovariance; + using typename Base::MeasurementMatrix; + using typename Base::MeasurementVector; + using typename Base::StateMatrix; + using typename Base::StateVector; KalmanFilter(const StateVector& initialState, const StateMatrix& initialCovariance); void SetStateTransition(const StateMatrix& F); - void SetProcessNoise(const StateMatrix& Q); void SetMeasurementMatrix(const MeasurementMatrix& H); - void SetMeasurementNoise(const MeasurementCovariance& R); + + void SetControlInputMatrix(const ControlMatrix& B) + requires(ControlSize > 0); + void Predict(); + + void Predict(const ControlVector& u) + requires(ControlSize > 0); + void Update(const MeasurementVector& measurement); - [[nodiscard]] const StateVector& GetState() const; - [[nodiscard]] const StateMatrix& GetCovariance() const; private: - StateVector state; - StateMatrix covariance; - StateMatrix stateTransition; - StateMatrix processNoise; - MeasurementMatrix measurementMatrix; - MeasurementCovariance measurementNoise; + StateMatrix stateTransition = StateMatrix::Identity(); + MeasurementMatrix measurementMatrix{}; + [[no_unique_address]] ControlMatrix controlInputMatrix{}; }; // Implementation // - template - KalmanFilter::KalmanFilter( + template + KalmanFilter::KalmanFilter( const StateVector& initialState, const StateMatrix& initialCovariance) - : state(initialState) - , covariance(initialCovariance) - , stateTransition(StateMatrix::Identity()) - , processNoise(StateMatrix::Identity()) - , measurementMatrix(MeasurementMatrix()) - , measurementNoise(MeasurementCovariance::Identity()) + : Base(initialState, initialCovariance) {} - template - void KalmanFilter::SetStateTransition(const StateMatrix& F) + template + void KalmanFilter::SetStateTransition(const StateMatrix& F) { stateTransition = F; } - template - void KalmanFilter::SetProcessNoise(const StateMatrix& Q) - { - processNoise = Q; - } - - template - void KalmanFilter::SetMeasurementMatrix(const MeasurementMatrix& H) + template + void KalmanFilter::SetMeasurementMatrix(const MeasurementMatrix& H) { measurementMatrix = H; } - template - void KalmanFilter::SetMeasurementNoise(const MeasurementCovariance& R) + template + void KalmanFilter::SetControlInputMatrix(const ControlMatrix& B) + requires(ControlSize > 0) { - measurementNoise = R; + controlInputMatrix = B; } - template - void KalmanFilter::Predict() + template + OPTIMIZE_FOR_SPEED void KalmanFilter::Predict() { - // State prediction: x̂ₖ₋ = Fₖ₋₁x̂ₖ₋₁ - state = stateTransition * state; - - // Covariance prediction: Pₖ₋ = Fₖ₋₁Pₖ₋₁Fₖ₋₁ᵀ + Qₖ₋₁ - covariance = stateTransition * covariance * stateTransition.Transpose() + processNoise; + this->state() = stateTransition * this->state(); + this->covariance() = stateTransition * this->covariance() * stateTransition.Transpose() + this->processNoise(); } - template - void KalmanFilter::Update(const MeasurementVector& measurement) + template + OPTIMIZE_FOR_SPEED void KalmanFilter::Predict(const ControlVector& u) + requires(ControlSize > 0) { - // Innovation/measurement residual: yₖ = zₖ - Hₖx̂ₖ₋ - auto innovation = measurement - (measurementMatrix * state); - - // Innovation covariance: Sₖ = HₖPₖ₋Hₖᵀ + Rₖ - auto innovationCovariance = measurementMatrix * covariance * measurementMatrix.Transpose() + measurementNoise; - - // Optimal Kalman gain: Kₖ = Pₖ₋Hₖᵀ(Sₖ)⁻¹ - // Note: For this implementation, we're assuming the inverse exists - // In practice, you might want to add checks or use pseudo-inverse - auto kalmanGain = covariance * measurementMatrix.Transpose() * innovationCovariance; - - // State update: x̂ₖ = x̂ₖ₋ + Kₖyₖ - state = state + kalmanGain * innovation; - - // Covariance update: Pₖ = (I - KₖHₖ)Pₖ₋ - auto identity = StateMatrix::Identity(); - covariance = (identity - kalmanGain * measurementMatrix) * covariance; + this->state() = stateTransition * this->state() + controlInputMatrix * u; + this->covariance() = stateTransition * this->covariance() * stateTransition.Transpose() + this->processNoise(); } - template - const typename KalmanFilter::StateVector& - KalmanFilter::GetState() const + template + OPTIMIZE_FOR_SPEED void KalmanFilter::Update(const MeasurementVector& measurement) { - return state; + auto innovation = measurement - (measurementMatrix * this->state()); + auto K = this->ComputeKalmanGain(measurementMatrix); + this->UpdateState(innovation, K, measurementMatrix); } - template - const typename KalmanFilter::StateMatrix& - KalmanFilter::GetCovariance() const - { - return covariance; - } + extern template class KalmanFilter; + extern template class KalmanFilter; + extern template class KalmanFilter; + extern template class KalmanFilter; } - -#endif diff --git a/numerical/filters/active/KalmanFilterBase.cpp b/numerical/filters/active/KalmanFilterBase.cpp new file mode 100644 index 00000000..54f2df1e --- /dev/null +++ b/numerical/filters/active/KalmanFilterBase.cpp @@ -0,0 +1,9 @@ +#include "numerical/filters/active/KalmanFilterBase.hpp" + +namespace filters +{ + template class KalmanFilterBase; + template class KalmanFilterBase; + template class KalmanFilterBase; + template class KalmanFilterBase; +} diff --git a/numerical/filters/active/KalmanFilterBase.hpp b/numerical/filters/active/KalmanFilterBase.hpp new file mode 100644 index 00000000..ca259d90 --- /dev/null +++ b/numerical/filters/active/KalmanFilterBase.hpp @@ -0,0 +1,172 @@ +#pragma once + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include "numerical/solvers/GaussianElimination.hpp" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +namespace filters +{ + namespace detail + { + template + inline constexpr bool is_kalman_supported_v = + std::disjunction_v< + std::is_same, + std::is_same, + std::is_same>; + } + + namespace detail + { + template + struct ControlType + { + using Matrix = math::Matrix; + using Vector = math::Vector; + }; + + template + struct ControlType + { + struct Matrix + {}; + + struct Vector + {}; + }; + } + + template + class KalmanFilterBase + { + static_assert(detail::is_kalman_supported_v, + "KalmanFilter only supports float, Q15, or Q31 types"); + static_assert(math::detail::is_valid_dimensions_v, + "State dimensions must be positive"); + static_assert(math::detail::is_valid_dimensions_v, + "Measurement dimensions must be positive"); + + public: + using StateMatrix = math::SquareMatrix; + using StateVector = math::Vector; + using MeasurementMatrix = math::Matrix; + using MeasurementVector = math::Vector; + using MeasurementCovariance = math::SquareMatrix; + using KalmanGain = math::Matrix; + using ControlMatrix = typename detail::ControlType::Matrix; + using ControlVector = typename detail::ControlType::Vector; + + void SetProcessNoise(const StateMatrix& Q); + void SetMeasurementNoise(const MeasurementCovariance& R); + + [[nodiscard]] const StateVector& GetState() const; + [[nodiscard]] const StateMatrix& GetCovariance() const; + + protected: + KalmanFilterBase(const StateVector& initialState, const StateMatrix& initialCovariance); + + KalmanGain ComputeKalmanGain(const MeasurementMatrix& H) const; + void UpdateState(const MeasurementVector& innovation, const KalmanGain& K, const MeasurementMatrix& H); + + StateVector& state() + { + return state_; + } + + const StateVector& state() const + { + return state_; + } + + StateMatrix& covariance() + { + return covariance_; + } + + const StateMatrix& covariance() const + { + return covariance_; + } + + const StateMatrix& processNoise() const + { + return processNoise_; + } + + const MeasurementCovariance& measurementNoise() const + { + return measurementNoise_; + } + + private: + StateVector state_; + StateMatrix covariance_; + StateMatrix processNoise_ = StateMatrix::Identity(); + MeasurementCovariance measurementNoise_ = MeasurementCovariance::Identity(); + }; + + // Implementation // + + template + KalmanFilterBase::KalmanFilterBase( + const StateVector& initialState, const StateMatrix& initialCovariance) + : state_(initialState) + , covariance_(initialCovariance) + {} + + template + void KalmanFilterBase::SetProcessNoise(const StateMatrix& Q) + { + processNoise_ = Q; + } + + template + void KalmanFilterBase::SetMeasurementNoise(const MeasurementCovariance& R) + { + measurementNoise_ = R; + } + + template + OPTIMIZE_FOR_SPEED + typename KalmanFilterBase::KalmanGain + KalmanFilterBase::ComputeKalmanGain(const MeasurementMatrix& H) const + { + auto S = H * covariance_ * H.Transpose() + measurementNoise_; + + // Solve S Kᵀ = H P instead of explicit K = P Hᵀ S⁻¹ (S is symmetric) + auto KTranspose = solvers::SolveSystem(S, H * covariance_); + + return KTranspose.Transpose(); + } + + template + OPTIMIZE_FOR_SPEED void KalmanFilterBase::UpdateState( + const MeasurementVector& innovation, const KalmanGain& K, const MeasurementMatrix& H) + { + state_ = state_ + K * innovation; + covariance_ = (StateMatrix::Identity() - K * H) * covariance_; + } + + template + const typename KalmanFilterBase::StateVector& + KalmanFilterBase::GetState() const + { + return state_; + } + + template + const typename KalmanFilterBase::StateMatrix& + KalmanFilterBase::GetCovariance() const + { + return covariance_; + } + + extern template class KalmanFilterBase; + extern template class KalmanFilterBase; + extern template class KalmanFilterBase; + extern template class KalmanFilterBase; +} diff --git a/numerical/filters/active/UnscentedKalmanFilter.cpp b/numerical/filters/active/UnscentedKalmanFilter.cpp new file mode 100644 index 00000000..ba78a53d --- /dev/null +++ b/numerical/filters/active/UnscentedKalmanFilter.cpp @@ -0,0 +1,8 @@ +#include "numerical/filters/active/UnscentedKalmanFilter.hpp" + +namespace filters +{ + template class UnscentedKalmanFilter; + template class UnscentedKalmanFilter; + template class UnscentedKalmanFilter; +} diff --git a/numerical/filters/active/UnscentedKalmanFilter.hpp b/numerical/filters/active/UnscentedKalmanFilter.hpp new file mode 100644 index 00000000..bfa80c04 --- /dev/null +++ b/numerical/filters/active/UnscentedKalmanFilter.hpp @@ -0,0 +1,278 @@ +#pragma once + +#include "infra/util/Function.hpp" +#include "numerical/filters/active/KalmanFilterBase.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/solvers/CholeskyDecomposition.hpp" +#include +#include + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +namespace filters +{ + struct UkfParameters + { + float alpha = 1e-3f; + float beta = 2.0f; + float kappa = 0.0f; + }; + + template + class UnscentedKalmanFilter + : public KalmanFilterBase + { + using Base = KalmanFilterBase; + + static constexpr std::size_t SigmaPointCount = 2 * StateSize + 1; + + public: + using typename Base::ControlVector; + using typename Base::MeasurementCovariance; + using typename Base::MeasurementMatrix; + using typename Base::MeasurementVector; + using typename Base::StateMatrix; + using typename Base::StateVector; + + using StateTransitionFn = infra::Function; + using MeasurementFn = infra::Function; + + using StateTransitionWithControlFn = infra::Function; + + UnscentedKalmanFilter(const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionFn f, MeasurementFn h, + UkfParameters params = UkfParameters{}) + requires(ControlSize == 0); + + UnscentedKalmanFilter(const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionWithControlFn f, MeasurementFn h, + UkfParameters params = UkfParameters{}) + requires(ControlSize > 0); + + void Predict() + requires(ControlSize == 0); + + void Predict(const ControlVector& u) + requires(ControlSize > 0); + + void Update(const MeasurementVector& measurement); + + private: + void ComputeWeights(); + void GenerateSigmaPoints(std::array& sigmaPoints) const; + void PredictFromPropagatedSigmaPoints(const std::array& sigmaPoints); + + template + math::Vector ComputeWeightedMean( + const std::array, SigmaPointCount>& points) const; + + template + math::SquareMatrix ComputeWeightedCovariance( + const std::array, SigmaPointCount>& points, + const math::Vector& mean) const; + + math::Matrix ComputeWeightedCrossCovariance( + const std::array& statePoints, + const StateVector& stateMean, + const std::array& measurementPoints, + const MeasurementVector& measurementMean) const; + + StateTransitionFn stateTransitionFn; + StateTransitionWithControlFn stateTransitionWithControlFn; + MeasurementFn measurementFn; + + UkfParameters parameters; + float lambda; + std::array weightsMean; + std::array weightsCovariance; + }; + + // Implementation // + + template + UnscentedKalmanFilter::UnscentedKalmanFilter( + const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionFn f, MeasurementFn h, + UkfParameters params) + requires(ControlSize == 0) + : Base(initialState, initialCovariance) + , stateTransitionFn(f) + , measurementFn(h) + , parameters(params) + { + ComputeWeights(); + } + + template + UnscentedKalmanFilter::UnscentedKalmanFilter( + const StateVector& initialState, const StateMatrix& initialCovariance, + StateTransitionWithControlFn f, MeasurementFn h, + UkfParameters params) + requires(ControlSize > 0) + : Base(initialState, initialCovariance) + , stateTransitionWithControlFn(f) + , measurementFn(h) + , parameters(params) + { + ComputeWeights(); + } + + template + void UnscentedKalmanFilter::ComputeWeights() + { + constexpr auto n = static_cast(StateSize); + lambda = parameters.alpha * parameters.alpha * (n + parameters.kappa) - n; + + weightsMean[0] = lambda / (n + lambda); + weightsCovariance[0] = lambda / (n + lambda) + (1.0f - parameters.alpha * parameters.alpha + parameters.beta); + + for (std::size_t i = 1; i < SigmaPointCount; ++i) + { + weightsMean[i] = 1.0f / (2.0f * (n + lambda)); + weightsCovariance[i] = 1.0f / (2.0f * (n + lambda)); + } + } + + template + void UnscentedKalmanFilter::GenerateSigmaPoints( + std::array& sigmaPoints) const + { + constexpr auto n = static_cast(StateSize); + float scaleFactor = std::sqrt(n + lambda); + auto L = solvers::CholeskyDecomposition(this->covariance()); + + sigmaPoints[0] = this->state(); + + // σᵢ = x̂ ± √(n+λ) · column_i(L) + for (std::size_t i = 0; i < StateSize; ++i) + { + StateVector column; + for (std::size_t j = 0; j < StateSize; ++j) + column.at(j, 0) = QNumberType(math::ToFloat(L.at(j, i)) * scaleFactor); + + sigmaPoints[i + 1] = this->state() + column; + sigmaPoints[i + 1 + StateSize] = this->state() - column; + } + } + + template + template + math::Vector + UnscentedKalmanFilter::ComputeWeightedMean( + const std::array, SigmaPointCount>& points) const + { + math::Vector result; + for (std::size_t i = 0; i < SigmaPointCount; ++i) + for (std::size_t j = 0; j < VectorSize; ++j) + result.at(j, 0) = QNumberType( + math::ToFloat(result.at(j, 0)) + + weightsMean[i] * math::ToFloat(points[i].at(j, 0))); + return result; + } + + template + template + math::SquareMatrix + UnscentedKalmanFilter::ComputeWeightedCovariance( + const std::array, SigmaPointCount>& points, + const math::Vector& mean) const + { + math::SquareMatrix result; + for (std::size_t i = 0; i < SigmaPointCount; ++i) + { + auto diff = points[i] - mean; + auto outer = diff * diff.Transpose(); + for (std::size_t r = 0; r < Size; ++r) + for (std::size_t c = 0; c < Size; ++c) + result.at(r, c) = QNumberType( + math::ToFloat(result.at(r, c)) + + weightsCovariance[i] * math::ToFloat(outer.at(r, c))); + } + return result; + } + + template + math::Matrix + UnscentedKalmanFilter::ComputeWeightedCrossCovariance( + const std::array& statePoints, + const StateVector& stateMean, + const std::array& measurementPoints, + const MeasurementVector& measurementMean) const + { + math::Matrix result; + for (std::size_t i = 0; i < SigmaPointCount; ++i) + { + auto stateDiff = statePoints[i] - stateMean; + auto measDiff = measurementPoints[i] - measurementMean; + auto outer = stateDiff * measDiff.Transpose(); + for (std::size_t r = 0; r < StateSize; ++r) + for (std::size_t c = 0; c < MeasurementSize; ++c) + result.at(r, c) = QNumberType( + math::ToFloat(result.at(r, c)) + + weightsCovariance[i] * math::ToFloat(outer.at(r, c))); + } + return result; + } + + template + void UnscentedKalmanFilter::PredictFromPropagatedSigmaPoints( + const std::array& sigmaPoints) + { + this->state() = ComputeWeightedMean(sigmaPoints); + this->covariance() = ComputeWeightedCovariance(sigmaPoints, this->state()) + this->processNoise(); + } + + template + OPTIMIZE_FOR_SPEED void UnscentedKalmanFilter::Predict() + requires(ControlSize == 0) + { + std::array sigmaPoints; + GenerateSigmaPoints(sigmaPoints); + + for (std::size_t i = 0; i < SigmaPointCount; ++i) + sigmaPoints[i] = stateTransitionFn(sigmaPoints[i]); + + PredictFromPropagatedSigmaPoints(sigmaPoints); + } + + template + OPTIMIZE_FOR_SPEED void UnscentedKalmanFilter::Predict(const ControlVector& u) + requires(ControlSize > 0) + { + std::array sigmaPoints; + GenerateSigmaPoints(sigmaPoints); + + for (std::size_t i = 0; i < SigmaPointCount; ++i) + sigmaPoints[i] = stateTransitionWithControlFn(sigmaPoints[i], u); + + PredictFromPropagatedSigmaPoints(sigmaPoints); + } + + template + OPTIMIZE_FOR_SPEED void UnscentedKalmanFilter::Update(const MeasurementVector& measurement) + { + std::array sigmaPoints; + GenerateSigmaPoints(sigmaPoints); + + std::array measurementSigmaPoints; + for (std::size_t i = 0; i < SigmaPointCount; ++i) + measurementSigmaPoints[i] = measurementFn(sigmaPoints[i]); + + auto predictedMeasurement = ComputeWeightedMean(measurementSigmaPoints); + auto S = ComputeWeightedCovariance(measurementSigmaPoints, predictedMeasurement) + this->measurementNoise(); + auto Pxz = ComputeWeightedCrossCovariance(sigmaPoints, this->state(), measurementSigmaPoints, predictedMeasurement); + + // Solve K via Sᵀ Kᵀ = Pxzᵀ (avoids explicit S⁻¹) + auto K = solvers::SolveSystem(S, Pxz.Transpose()).Transpose(); + + auto innovation = measurement - predictedMeasurement; + this->state() = this->state() + K * innovation; + this->covariance() = this->covariance() - K * S * K.Transpose(); + } + + extern template class UnscentedKalmanFilter; + extern template class UnscentedKalmanFilter; + extern template class UnscentedKalmanFilter; +} diff --git a/numerical/filters/active/test/CMakeLists.txt b/numerical/filters/active/test/CMakeLists.txt index a64267b8..a7d67b56 100644 --- a/numerical/filters/active/test/CMakeLists.txt +++ b/numerical/filters/active/test/CMakeLists.txt @@ -8,5 +8,7 @@ target_link_libraries(numerical.filters.active_test PUBLIC ) target_sources(numerical.filters.active_test PRIVATE + TestExtendedKalmanFilter.cpp TestKalmanFilter.cpp + TestUnscentedKalmanFilter.cpp ) diff --git a/numerical/filters/active/test/TestExtendedKalmanFilter.cpp b/numerical/filters/active/test/TestExtendedKalmanFilter.cpp new file mode 100644 index 00000000..72b937d6 --- /dev/null +++ b/numerical/filters/active/test/TestExtendedKalmanFilter.cpp @@ -0,0 +1,353 @@ +#include "numerical/filters/active/ExtendedKalmanFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include + +namespace +{ + template + bool AreVectorsNear(const math::Vector& a, + const math::Vector& b, + float epsilon) + { + for (std::size_t i = 0; i < Size; ++i) + if (std::abs(math::ToFloat(a.at(i, 0)) - math::ToFloat(b.at(i, 0))) >= epsilon) + return false; + + return true; + } + + // Linear state transition: x_new = F * x (constant velocity model) + using StateVec2 = math::Vector; + using MeasVec1 = math::Vector; + using StateMat2 = math::SquareMatrix; + using MeasMat2x1 = math::Matrix; + + constexpr float dt = 0.1f; + + StateVec2 LinearStateTransition(const StateVec2& x) + { + return StateVec2{ + { float(x.at(0, 0) + dt * x.at(1, 0)) }, + { x.at(1, 0) } + }; + } + + StateMat2 LinearStateJacobian(const StateVec2& /*x*/) + { + return StateMat2{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + } + + MeasVec1 LinearMeasurement(const StateVec2& x) + { + return MeasVec1{ { x.at(0, 0) } }; + } + + MeasMat2x1 LinearMeasurementJacobian(const StateVec2& /*x*/) + { + return MeasMat2x1{ { 1.0f, 0.0f } }; + } + + // Nonlinear state transition: position += velocity*dt, velocity += -sin(position)*dt + StateVec2 NonlinearStateTransition(const StateVec2& x) + { + float pos = x.at(0, 0); + float vel = x.at(1, 0); + return StateVec2{ + { pos + vel * dt }, + { vel - std::sin(pos) * dt } + }; + } + + StateMat2 NonlinearStateJacobian(const StateVec2& x) + { + float pos = x.at(0, 0); + return StateMat2{ + { 1.0f, dt }, + { -std::cos(pos) * dt, 1.0f } + }; + } + + // State transition with control input + using ControlVec1 = math::Vector; + + StateVec2 StateTransitionWithControl(const StateVec2& x, const ControlVec1& u) + { + float pos = x.at(0, 0); + float vel = x.at(1, 0); + return StateVec2{ + { pos + vel * dt }, + { vel + u.at(0, 0) * dt } + }; + } + + StateMat2 StateJacobianWithControl(const StateVec2& /*x*/, const ControlVec1& /*u*/) + { + return StateMat2{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + } + + template + class ExtendedKalmanFilterTest + : public ::testing::Test + { + protected: + float tolerance = math::Tolerance(); + + using EkfType = filters::ExtendedKalmanFilter; + using EkfWithControlType = filters::ExtendedKalmanFilter; + using StateVector = typename EkfType::StateVector; + using StateMatrix = typename EkfType::StateMatrix; + using MeasurementVector = typename EkfType::MeasurementVector; + using MeasurementCovariance = typename EkfType::MeasurementCovariance; + }; + + using TestTypes = ::testing::Types; + TYPED_TEST_SUITE(ExtendedKalmanFilterTest, TestTypes); +} + +TYPED_TEST(ExtendedKalmanFilterTest, LinearSystemMatchesKalmanFilter) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + typename TestFixture::EkfType ekf(initialState, initialP, + LinearStateTransition, LinearStateJacobian, + LinearMeasurement, LinearMeasurementJacobian); + + ekf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + ekf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + float truePos = 0.0f; + float trueVel = 0.5f; + + for (int i = 0; i < 10; ++i) + { + truePos += trueVel * dt; + ekf.Predict(); + ekf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ekf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.4f); +} + +TYPED_TEST(ExtendedKalmanFilterTest, ThreeStateSystemTracksAcceleration) +{ + using StateVec3 = math::Vector; + using StateMat3 = math::SquareMatrix; + using MeasVec = math::Vector; + using MeasCov = math::SquareMatrix; + using MeasMat = math::Matrix; + using Ekf3 = filters::ExtendedKalmanFilter; + + auto transition = [](const StateVec3& x) -> StateVec3 + { + return StateVec3{ + { TypeParam(math::ToFloat(x.at(0, 0)) + math::ToFloat(x.at(1, 0)) * dt) }, + { TypeParam(math::ToFloat(x.at(1, 0)) + math::ToFloat(x.at(2, 0)) * dt) }, + { x.at(2, 0) } + }; + }; + + auto jacobian = [](const StateVec3& /*x*/) -> StateMat3 + { + return StateMat3{ + { TypeParam(1.0f), TypeParam(dt), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(1.0f), TypeParam(dt) }, + { TypeParam(0.0f), TypeParam(0.0f), TypeParam(1.0f) } + }; + }; + + auto measurementFn = [](const StateVec3& x) -> MeasVec + { + return MeasVec{ { x.at(0, 0) } }; + }; + + auto measurementJac = [](const StateVec3& /*x*/) -> MeasMat + { + return MeasMat{ { TypeParam(1.0f), TypeParam(0.0f), TypeParam(0.0f) } }; + }; + + auto initialState = StateVec3{ { TypeParam(0.0f) }, { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMat3{ + { TypeParam(1.0f), TypeParam(0.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(1.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.0f), TypeParam(1.0f) } + }; + + Ekf3 ekf(initialState, initialP, transition, jacobian, measurementFn, measurementJac); + ekf.SetProcessNoise(StateMat3{ + { TypeParam(0.01f), TypeParam(0.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.0f), TypeParam(0.01f) } }); + ekf.SetMeasurementNoise(MeasCov{ { TypeParam(0.1f) } }); + + float trueAcc = 0.5f; + float trueVel3 = 0.0f; + float truePos3 = 0.0f; + + for (int i = 0; i < 30; ++i) + { + trueVel3 += trueAcc * dt; + truePos3 += trueVel3 * dt; + + ekf.Predict(); + ekf.Update(MeasVec{ { TypeParam(truePos3) } }); + } + + auto finalState3 = ekf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState3.at(0, 0)), truePos3, 0.15f); + EXPECT_NEAR(math::ToFloat(finalState3.at(1, 0)), trueVel3, 0.3f); + EXPECT_NEAR(math::ToFloat(finalState3.at(2, 0)), trueAcc, 0.5f); +} + +TYPED_TEST(ExtendedKalmanFilterTest, NonlinearPredictionUpdatesState) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.1f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + typename TestFixture::EkfType ekf(initialState, initialP, + NonlinearStateTransition, NonlinearStateJacobian, + LinearMeasurement, LinearMeasurementJacobian); + + ekf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + + ekf.Predict(); + + auto predicted = ekf.GetState(); + // Position should increase slightly (initial velocity is 0, small position) + // Velocity should become slightly negative (restoring force: -sin(0.1)*dt ≈ -0.01) + EXPECT_NEAR(math::ToFloat(predicted.at(0, 0)), 0.1f, 0.05f); + EXPECT_LT(math::ToFloat(predicted.at(1, 0)), 0.0f); +} + +TYPED_TEST(ExtendedKalmanFilterTest, UpdateReducesCovariance) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + typename TestFixture::EkfType ekf(initialState, initialP, + LinearStateTransition, LinearStateJacobian, + LinearMeasurement, LinearMeasurementJacobian); + + ekf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + auto covBefore = ekf.GetCovariance(); + ekf.Update(typename TestFixture::MeasurementVector{ { TypeParam(0.5f) } }); + auto covAfter = ekf.GetCovariance(); + + EXPECT_LT(math::ToFloat(covAfter.at(0, 0)), math::ToFloat(covBefore.at(0, 0))); +} + +TYPED_TEST(ExtendedKalmanFilterTest, NonlinearTrackingConverges) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + typename TestFixture::EkfType ekf(initialState, initialP, + NonlinearStateTransition, NonlinearStateJacobian, + LinearMeasurement, LinearMeasurementJacobian); + + ekf.SetProcessNoise(StateMatrix{ + { TypeParam(0.001f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.001f) } }); + ekf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.1f) } }); + + // Simulate a pendulum-like system + float truePos = 0.3f; + float trueVel = 0.0f; + + for (int i = 0; i < 50; ++i) + { + float newVel = trueVel - std::sin(truePos) * dt; + float newPos = truePos + trueVel * dt; + truePos = newPos; + trueVel = newVel; + + ekf.Predict(); + ekf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ekf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.1f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.2f); +} + +TYPED_TEST(ExtendedKalmanFilterTest, WithControlInput) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + typename TestFixture::EkfWithControlType ekf(initialState, initialP, + StateTransitionWithControl, StateJacobianWithControl, + LinearMeasurement, LinearMeasurementJacobian); + + ekf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + ekf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + // Apply constant acceleration + ControlVec1 controlInput{ { 1.0f } }; + + float truePos = 0.0f; + float trueVel = 0.0f; + + for (int i = 0; i < 10; ++i) + { + trueVel += 1.0f * dt; + truePos += trueVel * dt; + + ekf.Predict(controlInput); + ekf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ekf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.4f); +} diff --git a/numerical/filters/active/test/TestKalmanFilter.cpp b/numerical/filters/active/test/TestKalmanFilter.cpp index 7feebe7e..7be789d8 100644 --- a/numerical/filters/active/test/TestKalmanFilter.cpp +++ b/numerical/filters/active/test/TestKalmanFilter.cpp @@ -1,27 +1,30 @@ #include "numerical/filters/active/KalmanFilter.hpp" +#include "numerical/math/Tolerance.hpp" #include namespace { - template - bool AreVectorsNear(const math::Vector& a, - const math::Vector& b, - float epsilon = 1e-4f) + template + bool AreVectorsNear(const math::Vector& a, + const math::Vector& b, + float epsilon) { - for (size_t i = 0; i < 3; ++i) - return (std::abs(math::ToFloat(a.at(i, 0)) - math::ToFloat(b.at(i, 0))) < epsilon); + for (std::size_t i = 0; i < Size; ++i) + if (std::abs(math::ToFloat(a.at(i, 0)) - math::ToFloat(b.at(i, 0))) >= epsilon) + return false; return true; } - template - bool AreMatricesNear(const math::Matrix& a, - const math::Matrix& b, - float epsilon = 1e-4f) + template + bool AreMatricesNear(const math::Matrix& a, + const math::Matrix& b, + float epsilon) { - for (size_t i = 0; i < 3; ++i) - for (size_t j = 0; j < 3; ++j) - return (std::abs(math::ToFloat(a.at(i, j)) - math::ToFloat(b.at(i, j))) < epsilon); + for (std::size_t i = 0; i < Rows; ++i) + for (std::size_t j = 0; j < Cols; ++j) + if (std::abs(math::ToFloat(a.at(i, j)) - math::ToFloat(b.at(i, j))) >= epsilon) + return false; return true; } @@ -31,169 +34,183 @@ namespace : public ::testing::Test { protected: - static constexpr size_t StateSize = 3; - static constexpr size_t MeasurementSize = 1; + static constexpr std::size_t StateSize = 2; + static constexpr std::size_t MeasurementSize = 1; using FilterType = filters::KalmanFilter; using StateVector = typename FilterType::StateVector; using StateMatrix = typename FilterType::StateMatrix; using MeasurementVector = typename FilterType::MeasurementVector; using MeasurementMatrix = typename FilterType::MeasurementMatrix; + using MeasurementCovariance = typename FilterType::MeasurementCovariance; + + float tolerance = math::Tolerance(); static T MakeValue(float f) { return T(f); } - StateVector MakeStateVector(float x, float v, float a) + StateVector MakeStateVector(float x, float v) { return StateVector{ { MakeValue(x) }, - { MakeValue(v) }, - { MakeValue(a) } + { MakeValue(v) } }; } StateMatrix MakeStateMatrix( - float a11, float a12, float a13, - float a21, float a22, float a23, - float a31, float a32, float a33) + float a11, float a12, + float a21, float a22) { return StateMatrix{ - { MakeValue(a11), MakeValue(a12), MakeValue(a13) }, - { MakeValue(a21), MakeValue(a22), MakeValue(a23) }, - { MakeValue(a31), MakeValue(a32), MakeValue(a33) } + { MakeValue(a11), MakeValue(a12) }, + { MakeValue(a21), MakeValue(a22) } }; } - MeasurementMatrix MakeMeasurementMatrix(float h1, float h2, float h3) + MeasurementMatrix MakeMeasurementMatrix(float h1, float h2) { return MeasurementMatrix{ - { MakeValue(h1), MakeValue(h2), MakeValue(h3) } + { MakeValue(h1), MakeValue(h2) } }; } - MeasurementVector MakeMeasurement(float z) + MeasurementCovariance MakeMeasurementCovariance(float r) { - return MeasurementVector{ { MakeValue(z) } }; + return MeasurementCovariance{ + { MakeValue(r) } + }; } - StateMatrix MakeConstantAccelerationModel(float dt) + MeasurementVector MakeMeasurement(float z) { - float dt2_2 = dt * dt * 0.5f; - return MakeStateMatrix( - 0.1f, dt, dt2_2, - 0.0f, 0.1f, dt, - 0.0f, 0.0f, 0.1f); + return MeasurementVector{ { MakeValue(z) } }; } }; - using TestTypes = ::testing::Types; + using TestTypes = ::testing::Types; TYPED_TEST_SUITE(KalmanFilterTest, TestTypes); } TYPED_TEST(KalmanFilterTest, DefaultInitialization) { - auto initialState = this->MakeStateVector(0.0f, 0.0f, 0.0f); + auto initialState = this->MakeStateVector(0.0f, 0.0f); auto initialCovariance = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); + 0.1f, 0.0f, + 0.0f, 0.1f); typename TestFixture::FilterType filter(initialState, initialCovariance); - EXPECT_TRUE(AreVectorsNear(filter.GetState(), initialState)); - EXPECT_TRUE(AreMatricesNear(filter.GetCovariance(), initialCovariance)); + EXPECT_TRUE(AreVectorsNear(filter.GetState(), initialState, this->tolerance)); + EXPECT_TRUE(AreMatricesNear(filter.GetCovariance(), initialCovariance, this->tolerance)); } -TYPED_TEST(KalmanFilterTest, PredictConstantAcceleration) +TYPED_TEST(KalmanFilterTest, PredictConstantVelocity) { - auto initialState = this->MakeStateVector(0.0f, 0.01f, 0.005f); + auto initialState = this->MakeStateVector(0.0f, 0.1f); auto initialCovariance = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); + 0.1f, 0.0f, + 0.0f, 0.1f); typename TestFixture::FilterType filter(initialState, initialCovariance); float dt = 0.1f; - filter.SetStateTransition(this->MakeConstantAccelerationModel(dt)); + filter.SetStateTransition(this->MakeStateMatrix( + 1.0f, dt, + 0.0f, 1.0f)); filter.Predict(); - auto expectedState = this->MakeStateVector( - 0.001025f, - 0.0105f, - 0.005f); - - EXPECT_TRUE(AreVectorsNear(filter.GetState(), expectedState)); + // x_new = [0 + 0.1*0.1, 0.1] = [0.01, 0.1] + auto expectedState = this->MakeStateVector(0.01f, 0.1f); + EXPECT_TRUE(AreVectorsNear(filter.GetState(), expectedState, this->tolerance)); } -TYPED_TEST(KalmanFilterTest, UpdateWithPositionMeasurement) +TYPED_TEST(KalmanFilterTest, UpdateCorrectlyFusesInformation) { - auto initialState = this->MakeStateVector(0.0f, 0.1f, 0.05f); + // Position-velocity system, measure position only + auto initialState = this->MakeStateVector(0.0f, 0.0f); auto initialCovariance = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); + 0.5f, 0.0f, + 0.0f, 0.5f); typename TestFixture::FilterType filter(initialState, initialCovariance); + filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(1.0f, 0.0f)); + filter.SetMeasurementNoise(this->MakeMeasurementCovariance(0.5f)); - auto measurementMatrix = this->MakeMeasurementMatrix(0.1f, 0.0f, 0.0f); - filter.SetMeasurementMatrix(measurementMatrix); - - auto measurement = this->MakeMeasurement(0.1f); - filter.Update(measurement); + // Measurement of position = 0.5 + filter.Update(this->MakeMeasurement(0.5f)); auto updatedState = filter.GetState(); - EXPECT_GT(math::ToFloat(updatedState.at(0, 0)), math::ToFloat(initialState.at(0, 0))); + // With equal P and R, the gain should be ~0.5, so state should be ~0.25 + float posEstimate = math::ToFloat(updatedState.at(0, 0)); + EXPECT_GT(posEstimate, 0.0f); + EXPECT_LT(posEstimate, 0.5f); + + // Covariance should decrease after update + auto updatedP = filter.GetCovariance(); + EXPECT_LT(math::ToFloat(updatedP.at(0, 0)), 0.5f); } -TYPED_TEST(KalmanFilterTest, FullTrajectory) +TYPED_TEST(KalmanFilterTest, FullPredictUpdateCycle) { - auto initialState = this->MakeStateVector(0.0f, 0.0f, 0.0f); + auto initialState = this->MakeStateVector(0.0f, 0.0f); auto initialCovariance = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); + 0.5f, 0.0f, + 0.0f, 0.5f); typename TestFixture::FilterType filter(initialState, initialCovariance); float dt = 0.1f; - filter.SetStateTransition(this->MakeConstantAccelerationModel(dt)); - filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(0.1f, 0.0f, 0.0f)); - - auto processNoise = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); - filter.SetProcessNoise(processNoise); - - std::vector measurements = { 0.01f, 0.02f, 0.035f, 0.05f }; - - for (float measurement : measurements) + filter.SetStateTransition(this->MakeStateMatrix( + 1.0f, dt, + 0.0f, 1.0f)); + filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(1.0f, 0.0f)); + filter.SetMeasurementNoise(this->MakeMeasurementCovariance(0.5f)); + filter.SetProcessNoise(this->MakeStateMatrix( + 0.01f, 0.0f, + 0.0f, 0.01f)); + + // Simulate 10 steps - estimator should track object moving at velocity ~1.0 + float truePos = 0.0f; + float trueVel = 0.5f; + + for (int i = 0; i < 10; ++i) { + truePos += trueVel * dt; + float measurement = truePos; + filter.Predict(); filter.Update(this->MakeMeasurement(measurement)); - - auto state = filter.GetState(); - EXPECT_LE(math::ToFloat(state.at(0, 0)), measurement); } + + auto finalState = filter.GetState(); + float posEstimate = math::ToFloat(finalState.at(0, 0)); + float velEstimate = math::ToFloat(finalState.at(1, 0)); + + EXPECT_NEAR(posEstimate, truePos, 0.2f); + EXPECT_NEAR(velEstimate, trueVel, 0.4f); } TYPED_TEST(KalmanFilterTest, CovarianceEvolution) { - auto initialState = this->MakeStateVector(0.0f, 0.0f, 0.0f); + auto initialState = this->MakeStateVector(0.0f, 0.0f); auto initialCovariance = this->MakeStateMatrix( - 0.1f, 0.0f, 0.0f, - 0.0f, 0.1f, 0.0f, - 0.0f, 0.0f, 0.1f); + 0.5f, 0.0f, + 0.0f, 0.5f); typename TestFixture::FilterType filter(initialState, initialCovariance); float dt = 0.1f; - filter.SetStateTransition(this->MakeConstantAccelerationModel(dt)); - filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(0.1f, 0.0f, 0.0f)); + filter.SetStateTransition(this->MakeStateMatrix( + 1.0f, dt, + 0.0f, 1.0f)); + filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(1.0f, 0.0f)); + filter.SetMeasurementNoise(this->MakeMeasurementCovariance(0.5f)); + filter.SetProcessNoise(this->MakeStateMatrix( + 0.01f, 0.0f, + 0.0f, 0.01f)); filter.Predict(); auto predictedCovariance = filter.GetCovariance(); @@ -203,3 +220,187 @@ TYPED_TEST(KalmanFilterTest, CovarianceEvolution) auto updatedCovariance = filter.GetCovariance(); EXPECT_LT(math::ToFloat(updatedCovariance.at(0, 0)), math::ToFloat(predictedCovariance.at(0, 0))); } + +TYPED_TEST(KalmanFilterTest, PredictOnlyGrowsCovariance) +{ + auto initialState = this->MakeStateVector(0.0f, 0.0f); + auto initialCovariance = this->MakeStateMatrix( + 0.1f, 0.0f, + 0.0f, 0.1f); + + typename TestFixture::FilterType filter(initialState, initialCovariance); + + filter.SetStateTransition(this->MakeStateMatrix( + 1.0f, 0.1f, + 0.0f, 1.0f)); + filter.SetProcessNoise(this->MakeStateMatrix( + 0.01f, 0.0f, + 0.0f, 0.01f)); + + for (int i = 0; i < 5; ++i) + filter.Predict(); + + auto P = filter.GetCovariance(); + EXPECT_GT(math::ToFloat(P.at(0, 0)), 0.1f); + EXPECT_GT(math::ToFloat(P.at(1, 1)), 0.1f); +} + +TYPED_TEST(KalmanFilterTest, ThreeStateConstantAcceleration) +{ + using T = TypeParam; + using Filter3 = filters::KalmanFilter; + using StateVec3 = math::Vector; + using StateMat3 = math::SquareMatrix; + using MeasMat = math::Matrix; + using MeasCov = math::SquareMatrix; + using MeasVec = math::Vector; + + float dt = 0.1f; + + auto initialState = StateVec3{ { T(0.0f) }, { T(0.0f) }, { T(0.0f) } }; + auto initialP = StateMat3{ + { T(1.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(1.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(1.0f) } + }; + + Filter3 filter(initialState, initialP); + + filter.SetStateTransition(StateMat3{ + { T(1.0f), T(dt), T(0.5f * dt * dt) }, + { T(0.0f), T(1.0f), T(dt) }, + { T(0.0f), T(0.0f), T(1.0f) } }); + filter.SetMeasurementMatrix(MeasMat{ { T(1.0f), T(0.0f), T(0.0f) } }); + filter.SetMeasurementNoise(MeasCov{ { T(0.1f) } }); + filter.SetProcessNoise(StateMat3{ + { T(0.01f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.01f), T(0.0f) }, + { T(0.0f), T(0.0f), T(0.01f) } }); + + float trueAcc = 1.0f; + float trueVel = 0.0f; + float truePos = 0.0f; + + for (int i = 0; i < 20; ++i) + { + trueVel += trueAcc * dt; + truePos += trueVel * dt; + + filter.Predict(); + filter.Update(MeasVec{ { T(truePos) } }); + } + + auto finalState = filter.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.3f); +} + +TYPED_TEST(KalmanFilterTest, FourStateTwoMeasurement) +{ + using T = TypeParam; + using Filter4 = filters::KalmanFilter; + using StateVec4 = math::Vector; + using StateMat4 = math::SquareMatrix; + using MeasMat = math::Matrix; + using MeasCov = math::SquareMatrix; + using MeasVec = math::Vector; + + float dt = 0.1f; + + auto initialState = StateVec4{ { T(0.0f) }, { T(0.0f) }, { T(0.0f) }, { T(0.0f) } }; + auto initialP = StateMat4{ + { T(1.0f), T(0.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(1.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(1.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(0.0f), T(1.0f) } + }; + + Filter4 filter(initialState, initialP); + + // State: [x, vx, y, vy], constant velocity model + filter.SetStateTransition(StateMat4{ + { T(1.0f), T(dt), T(0.0f), T(0.0f) }, + { T(0.0f), T(1.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(1.0f), T(dt) }, + { T(0.0f), T(0.0f), T(0.0f), T(1.0f) } }); + + // Measure x and y positions + filter.SetMeasurementMatrix(MeasMat{ + { T(1.0f), T(0.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(1.0f), T(0.0f) } }); + + filter.SetMeasurementNoise(MeasCov{ + { T(0.1f), T(0.0f) }, + { T(0.0f), T(0.1f) } }); + filter.SetProcessNoise(StateMat4{ + { T(0.01f), T(0.0f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.01f), T(0.0f), T(0.0f) }, + { T(0.0f), T(0.0f), T(0.01f), T(0.0f) }, + { T(0.0f), T(0.0f), T(0.0f), T(0.01f) } }); + + float trueX = 0.0f, trueVx = 0.5f; + float trueY = 0.0f, trueVy = 0.3f; + + for (int i = 0; i < 20; ++i) + { + trueX += trueVx * dt; + trueY += trueVy * dt; + + filter.Predict(); + filter.Update(MeasVec{ { T(trueX) }, { T(trueY) } }); + } + + auto finalState = filter.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), trueX, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(2, 0)), trueY, 0.2f); +} + +TYPED_TEST(KalmanFilterTest, WithControlInput) +{ + using T = TypeParam; + using FilterCtrl = filters::KalmanFilter; + using StateVec = math::Vector; + using StateMat = math::SquareMatrix; + using MeasMat = math::Matrix; + using MeasCov = math::SquareMatrix; + using MeasVec = math::Vector; + using CtrlMat = math::Matrix; + using CtrlVec = math::Vector; + + float dt = 0.1f; + + auto initialState = StateVec{ { T(0.0f) }, { T(0.0f) } }; + auto initialP = StateMat{ + { T(0.5f), T(0.0f) }, + { T(0.0f), T(0.5f) } + }; + + FilterCtrl filter(initialState, initialP); + + filter.SetStateTransition(StateMat{ + { T(1.0f), T(dt) }, + { T(0.0f), T(1.0f) } }); + filter.SetControlInputMatrix(CtrlMat{ + { T(0.5f * dt * dt) }, + { T(dt) } }); + filter.SetMeasurementMatrix(MeasMat{ { T(1.0f), T(0.0f) } }); + filter.SetMeasurementNoise(MeasCov{ { T(0.1f) } }); + filter.SetProcessNoise(StateMat{ + { T(0.01f), T(0.0f) }, + { T(0.0f), T(0.01f) } }); + + CtrlVec controlInput{ { T(1.0f) } }; + float truePos = 0.0f, trueVel = 0.0f; + + for (int i = 0; i < 10; ++i) + { + trueVel += 1.0f * dt; + truePos += trueVel * dt; + + filter.Predict(controlInput); + filter.Update(MeasVec{ { T(truePos) } }); + } + + auto finalState = filter.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.4f); +} diff --git a/numerical/filters/active/test/TestUnscentedKalmanFilter.cpp b/numerical/filters/active/test/TestUnscentedKalmanFilter.cpp new file mode 100644 index 00000000..2848725c --- /dev/null +++ b/numerical/filters/active/test/TestUnscentedKalmanFilter.cpp @@ -0,0 +1,310 @@ +#include "numerical/filters/active/UnscentedKalmanFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include + +namespace +{ + using StateVec2 = math::Vector; + using MeasVec1 = math::Vector; + using StateMat2 = math::SquareMatrix; + + constexpr float dt = 0.1f; + + // Linear state transition for comparison with KF + StateVec2 LinearStateTransition(const StateVec2& x) + { + return StateVec2{ + { float(x.at(0, 0) + dt * x.at(1, 0)) }, + { x.at(1, 0) } + }; + } + + MeasVec1 LinearMeasurement(const StateVec2& x) + { + return MeasVec1{ { x.at(0, 0) } }; + } + + // Nonlinear pendulum-like system: position += velocity*dt, velocity += -sin(position)*dt + StateVec2 NonlinearStateTransition(const StateVec2& x) + { + float pos = x.at(0, 0); + float vel = x.at(1, 0); + return StateVec2{ + { pos + vel * dt }, + { vel - std::sin(pos) * dt } + }; + } + + // State transition with control input + using ControlVec1 = math::Vector; + + StateVec2 StateTransitionWithControl(const StateVec2& x, const ControlVec1& u) + { + float pos = x.at(0, 0); + float vel = x.at(1, 0); + return StateVec2{ + { pos + vel * dt }, + { vel + u.at(0, 0) * dt } + }; + } + + template + class UnscentedKalmanFilterTest + : public ::testing::Test + { + protected: + float tolerance = math::Tolerance(); + + using UkfType = filters::UnscentedKalmanFilter; + using UkfWithControlType = filters::UnscentedKalmanFilter; + using StateVector = typename UkfType::StateVector; + using StateMatrix = typename UkfType::StateMatrix; + using MeasurementVector = typename UkfType::MeasurementVector; + using MeasurementCovariance = typename UkfType::MeasurementCovariance; + }; + + using TestTypes = ::testing::Types; + TYPED_TEST_SUITE(UnscentedKalmanFilterTest, TestTypes); +} + +TYPED_TEST(UnscentedKalmanFilterTest, LinearSystemTracksConstantVelocity) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + params.beta = 2.0f; + params.kappa = 0.0f; + + typename TestFixture::UkfType ukf(initialState, initialP, + LinearStateTransition, LinearMeasurement, params); + + ukf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + ukf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + float truePos = 0.0f; + float trueVel = 0.5f; + + for (int i = 0; i < 10; ++i) + { + truePos += trueVel * dt; + ukf.Predict(); + ukf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ukf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.5f); +} + +TYPED_TEST(UnscentedKalmanFilterTest, PredictGrowsCovariance) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.1f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.1f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.1f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + + typename TestFixture::UkfType ukf(initialState, initialP, + LinearStateTransition, LinearMeasurement, params); + + ukf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + + auto covBefore = ukf.GetCovariance(); + ukf.Predict(); + auto covAfter = ukf.GetCovariance(); + + EXPECT_GT(math::ToFloat(covAfter.at(0, 0)), math::ToFloat(covBefore.at(0, 0))); +} + +TYPED_TEST(UnscentedKalmanFilterTest, UpdateReducesCovariance) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + + typename TestFixture::UkfType ukf(initialState, initialP, + LinearStateTransition, LinearMeasurement, params); + + ukf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + auto covBefore = ukf.GetCovariance(); + ukf.Update(typename TestFixture::MeasurementVector{ { TypeParam(0.5f) } }); + auto covAfter = ukf.GetCovariance(); + + EXPECT_LT(math::ToFloat(covAfter.at(0, 0)), math::ToFloat(covBefore.at(0, 0))); +} + +TYPED_TEST(UnscentedKalmanFilterTest, NonlinearTrackingConverges) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + params.beta = 2.0f; + params.kappa = 0.0f; + + typename TestFixture::UkfType ukf(initialState, initialP, + NonlinearStateTransition, LinearMeasurement, params); + + ukf.SetProcessNoise(StateMatrix{ + { TypeParam(0.001f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.001f) } }); + ukf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.1f) } }); + + // Simulate a pendulum-like system + float truePos = 0.3f; + float trueVel = 0.0f; + + for (int i = 0; i < 50; ++i) + { + float newVel = trueVel - std::sin(truePos) * dt; + float newPos = truePos + trueVel * dt; + truePos = newPos; + trueVel = newVel; + + ukf.Predict(); + ukf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ukf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.1f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.2f); +} + +TYPED_TEST(UnscentedKalmanFilterTest, WithControlInput) +{ + using StateVector = typename TestFixture::StateVector; + using StateMatrix = typename TestFixture::StateMatrix; + using MeasurementCovariance = typename TestFixture::MeasurementCovariance; + + auto initialState = StateVector{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMatrix{ + { TypeParam(0.5f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.5f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + + typename TestFixture::UkfWithControlType ukf(initialState, initialP, + StateTransitionWithControl, LinearMeasurement, params); + + ukf.SetProcessNoise(StateMatrix{ + { TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f) } }); + ukf.SetMeasurementNoise(MeasurementCovariance{ { TypeParam(0.5f) } }); + + ControlVec1 controlInput{ { 1.0f } }; + + float truePos = 0.0f; + float trueVel = 0.0f; + + for (int i = 0; i < 10; ++i) + { + trueVel += 1.0f * dt; + truePos += trueVel * dt; + + ukf.Predict(controlInput); + ukf.Update(typename TestFixture::MeasurementVector{ { TypeParam(truePos) } }); + } + + auto finalState = ukf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); + EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.5f); +} + +TYPED_TEST(UnscentedKalmanFilterTest, ThreeStateConstantAcceleration) +{ + using StateVec3 = math::Vector; + using StateMat3 = math::SquareMatrix; + using MeasVec = math::Vector; + using MeasCov = math::SquareMatrix; + using Ukf3 = filters::UnscentedKalmanFilter; + + auto transition = [](const StateVec3& x) -> StateVec3 + { + return StateVec3{ + { TypeParam(math::ToFloat(x.at(0, 0)) + math::ToFloat(x.at(1, 0)) * dt) }, + { TypeParam(math::ToFloat(x.at(1, 0)) + math::ToFloat(x.at(2, 0)) * dt) }, + { x.at(2, 0) } + }; + }; + + auto measurementFn = [](const StateVec3& x) -> MeasVec + { + return MeasVec{ { x.at(0, 0) } }; + }; + + auto initialState = StateVec3{ { TypeParam(0.0f) }, { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + auto initialP = StateMat3{ + { TypeParam(1.0f), TypeParam(0.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(1.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.0f), TypeParam(1.0f) } + }; + + filters::UkfParameters params; + params.alpha = 1e-1f; + params.beta = 2.0f; + params.kappa = 0.0f; + + Ukf3 ukf(initialState, initialP, transition, measurementFn, params); + + ukf.SetProcessNoise(StateMat3{ + { TypeParam(0.01f), TypeParam(0.0f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.01f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.0f), TypeParam(0.01f) } }); + ukf.SetMeasurementNoise(MeasCov{ { TypeParam(0.1f) } }); + + float trueAcc = 0.5f; + float trueVel3 = 0.0f; + float truePos3 = 0.0f; + + for (int i = 0; i < 30; ++i) + { + trueVel3 += trueAcc * dt; + truePos3 += trueVel3 * dt; + + ukf.Predict(); + ukf.Update(MeasVec{ { TypeParam(truePos3) } }); + } + + auto finalState3 = ukf.GetState(); + EXPECT_NEAR(math::ToFloat(finalState3.at(0, 0)), truePos3, 0.15f); + EXPECT_NEAR(math::ToFloat(finalState3.at(1, 0)), trueVel3, 0.3f); +} diff --git a/numerical/solvers/CMakeLists.txt b/numerical/solvers/CMakeLists.txt index dffc8a43..26c9eaaf 100644 --- a/numerical/solvers/CMakeLists.txt +++ b/numerical/solvers/CMakeLists.txt @@ -11,6 +11,7 @@ target_link_libraries(numerical.solver PUBLIC ) target_sources(numerical.solver PRIVATE + CholeskyDecomposition.hpp DiscreteAlgebraicRiccatiEquation.cpp DiscreteAlgebraicRiccatiEquation.hpp DurandKerner.cpp diff --git a/numerical/solvers/CholeskyDecomposition.hpp b/numerical/solvers/CholeskyDecomposition.hpp new file mode 100644 index 00000000..24a10423 --- /dev/null +++ b/numerical/solvers/CholeskyDecomposition.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +namespace solvers +{ + // Precondition: A must be symmetric positive-definite + template + OPTIMIZE_FOR_SPEED math::SquareMatrix CholeskyDecomposition(const math::SquareMatrix& A) + { + math::SquareMatrix L; + + for (std::size_t i = 0; i < N; ++i) + { + for (std::size_t j = 0; j <= i; ++j) + { + float sum = 0.0f; + + for (std::size_t k = 0; k < j; ++k) + sum += math::ToFloat(L.at(i, k)) * math::ToFloat(L.at(j, k)); + + if (i == j) + L.at(i, j) = T(std::sqrt(math::ToFloat(A.at(i, i)) - sum)); + else + L.at(i, j) = T((math::ToFloat(A.at(i, j)) - sum) / math::ToFloat(L.at(j, j))); + } + } + + return L; + } +} diff --git a/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index 568ea259..ac0aaabb 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -2,3 +2,4 @@ add_subdirectory(utils) add_subdirectory(analysis) add_subdirectory(controllers) add_subdirectory(dynamics) +add_subdirectory(filters) diff --git a/simulator/filters/CMakeLists.txt b/simulator/filters/CMakeLists.txt new file mode 100644 index 00000000..c0fee27c --- /dev/null +++ b/simulator/filters/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(KalmanFilter) diff --git a/simulator/filters/KalmanFilter/CMakeLists.txt b/simulator/filters/KalmanFilter/CMakeLists.txt new file mode 100644 index 00000000..3f033bd7 --- /dev/null +++ b/simulator/filters/KalmanFilter/CMakeLists.txt @@ -0,0 +1,24 @@ +find_package(Qt6 REQUIRED COMPONENTS Widgets) + +add_subdirectory(application) +add_subdirectory(view) + +add_executable(numerical.simulator.filters.kalman) +emil_build_for(numerical.simulator.filters.kalman HOST All PREREQUISITE_BOOL NUMERICAL_TOOLBOX_BUILD_SIMULATOR) + +target_link_libraries(numerical.simulator.filters.kalman PRIVATE + numerical.simulator.filters.kalman.application + numerical.simulator.filters.kalman.view +) + +target_sources(numerical.simulator.filters.kalman PRIVATE + Main.cpp +) + +if(MSVC) + target_compile_options(numerical.simulator.filters.kalman PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.filters.kalman PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/filters/KalmanFilter/Main.cpp b/simulator/filters/KalmanFilter/Main.cpp new file mode 100644 index 00000000..0f96b39a --- /dev/null +++ b/simulator/filters/KalmanFilter/Main.cpp @@ -0,0 +1,12 @@ +#include "simulator/filters/KalmanFilter/view/KalmanMainWindow.hpp" +#include + +int main(int argc, char* argv[]) +{ + QApplication app(argc, argv); + + simulator::filters::view::KalmanMainWindow window; + window.show(); + + return app.exec(); +} diff --git a/simulator/filters/KalmanFilter/application/CMakeLists.txt b/simulator/filters/KalmanFilter/application/CMakeLists.txt new file mode 100644 index 00000000..43bc08b6 --- /dev/null +++ b/simulator/filters/KalmanFilter/application/CMakeLists.txt @@ -0,0 +1,25 @@ +add_library(numerical.simulator.filters.kalman.application STATIC) + +target_include_directories(numerical.simulator.filters.kalman.application PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.filters.kalman.application PUBLIC + numerical.filters.active +) + +target_sources(numerical.simulator.filters.kalman.application PRIVATE + KalmanFilterSimulator.cpp + KalmanFilterSimulator.hpp + PendulumPlant.cpp + PendulumPlant.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.filters.kalman.application PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.filters.kalman.application PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp new file mode 100644 index 00000000..83b0b8b4 --- /dev/null +++ b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp @@ -0,0 +1,157 @@ +#include "simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp" +#include "numerical/filters/active/ExtendedKalmanFilter.hpp" +#include "numerical/filters/active/KalmanFilter.hpp" +#include "numerical/filters/active/UnscentedKalmanFilter.hpp" +#include +#include + +namespace simulator::filters +{ + namespace + { + using StateVec = math::Vector; + using StateMat = math::SquareMatrix; + using MeasVec = math::Vector; + using MeasCov = math::SquareMatrix; + + void ReserveResults(SimulationResult& result, std::size_t steps) + { + result.time.reserve(steps); + result.trueTheta.reserve(steps); + result.trueThetaDot.reserve(steps); + result.measuredTheta.reserve(steps); + + auto reserveTrace = [steps](EstimatorTrace& trace) + { + trace.theta.reserve(steps); + trace.thetaDot.reserve(steps); + trace.covarianceTheta.reserve(steps); + }; + + reserveTrace(result.kf); + reserveTrace(result.ekf); + reserveTrace(result.ukf); + } + + template + void RecordFilterEstimate(EstimatorTrace& trace, FilterType& filter, const MeasVec& measurement) + { + filter.Predict(); + filter.Update(measurement); + trace.theta.push_back(filter.GetState().at(0, 0)); + trace.thetaDot.push_back(filter.GetState().at(1, 0)); + trace.covarianceTheta.push_back(filter.GetCovariance().at(0, 0)); + } + } + + SimulationResult KalmanFilterSimulator::Run(const SimulationConfig& config) + { + SimulationResult result; + + float g = config.pendulum.gravity; + float L = config.pendulum.length; + float b = config.pendulum.damping; + float dt = config.dt; + + auto pendulumTransition = [g, L, b, dt](const StateVec& x) -> StateVec + { + float theta = x.at(0, 0); + float thetaDot = x.at(1, 0); + float thetaDotDot = -(g / L) * std::sin(theta) - b * thetaDot; + return StateVec{ + { theta + thetaDot * dt }, + { thetaDot + thetaDotDot * dt } + }; + }; + + auto pendulumJacobian = [g, L, b, dt](const StateVec& x) -> StateMat + { + float theta = x.at(0, 0); + return StateMat{ + { 1.0f, dt }, + { -(g / L) * std::cos(theta) * dt, 1.0f - b * dt } + }; + }; + + auto measurementFn = [](const StateVec& x) -> MeasVec + { + return MeasVec{ { x.at(0, 0) } }; + }; + + auto measurementJacobian = [](const StateVec& /*x*/) -> math::Matrix + { + return math::Matrix{ { 1.0f, 0.0f } }; + }; + + auto initialState = StateVec{ { config.initialTheta }, { config.initialThetaDot } }; + auto initialP = StateMat{ + { 0.5f, 0.0f }, + { 0.0f, 0.5f } + }; + + float qVar = config.processNoiseStdDev * config.processNoiseStdDev; + auto Q = StateMat{ + { qVar, 0.0f }, + { 0.0f, qVar } + }; + + float rVar = config.measurementNoiseStdDev * config.measurementNoiseStdDev; + auto R = MeasCov{ { rVar } }; + + ::filters::KalmanFilter kf(initialState, initialP); + kf.SetStateTransition(StateMat{ + { 1.0f, dt }, + { -(g / L) * dt, 1.0f - b * dt } }); + kf.SetMeasurementMatrix(math::Matrix{ { 1.0f, 0.0f } }); + kf.SetProcessNoise(Q); + kf.SetMeasurementNoise(R); + + ::filters::ExtendedKalmanFilter ekf(initialState, initialP, + pendulumTransition, pendulumJacobian, + measurementFn, measurementJacobian); + ekf.SetProcessNoise(Q); + ekf.SetMeasurementNoise(R); + + ::filters::UkfParameters ukfParams; + ukfParams.alpha = 1e-1f; + ukfParams.beta = 2.0f; + ukfParams.kappa = 0.0f; + + ::filters::UnscentedKalmanFilter ukf(initialState, initialP, + pendulumTransition, measurementFn, ukfParams); + ukf.SetProcessNoise(Q); + ukf.SetMeasurementNoise(R); + + PendulumPlant plant(config.pendulum); + plant.Reset(config.initialTheta, config.initialThetaDot); + + std::size_t steps = static_cast(config.duration / config.dt); + ReserveResults(result, steps); + + std::mt19937 rng(42); + std::normal_distribution measurementNoise(0.0f, config.measurementNoiseStdDev); + std::normal_distribution processNoise(0.0f, config.processNoiseStdDev); + + for (std::size_t i = 0; i < steps; ++i) + { + float t = static_cast(i) * config.dt; + + float noisyTorque = processNoise(rng); + auto trueState = plant.Step(noisyTorque, dt); + float noisyTheta = trueState.theta + measurementNoise(rng); + + result.time.push_back(t); + result.trueTheta.push_back(trueState.theta); + result.trueThetaDot.push_back(trueState.thetaDot); + result.measuredTheta.push_back(noisyTheta); + + auto measurement = MeasVec{ { noisyTheta } }; + + RecordFilterEstimate(result.kf, kf, measurement); + RecordFilterEstimate(result.ekf, ekf, measurement); + RecordFilterEstimate(result.ukf, ukf, measurement); + } + + return result; + } +} diff --git a/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp new file mode 100644 index 00000000..8b166748 --- /dev/null +++ b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include "simulator/filters/KalmanFilter/application/PendulumPlant.hpp" +#include + +namespace simulator::filters +{ + struct SimulationConfig + { + float duration = 10.0f; + float dt = 0.01f; + float initialTheta = 0.5f; + float initialThetaDot = 0.0f; + float measurementNoiseStdDev = 0.1f; + float processNoiseStdDev = 0.01f; + PendulumParameters pendulum; + }; + + struct EstimatorTrace + { + std::vector theta; + std::vector thetaDot; + std::vector covarianceTheta; + }; + + struct SimulationResult + { + std::vector time; + std::vector trueTheta; + std::vector trueThetaDot; + std::vector measuredTheta; + EstimatorTrace kf; + EstimatorTrace ekf; + EstimatorTrace ukf; + }; + + class KalmanFilterSimulator + { + public: + SimulationResult Run(const SimulationConfig& config); + }; +} diff --git a/simulator/filters/KalmanFilter/application/PendulumPlant.cpp b/simulator/filters/KalmanFilter/application/PendulumPlant.cpp new file mode 100644 index 00000000..eddc643d --- /dev/null +++ b/simulator/filters/KalmanFilter/application/PendulumPlant.cpp @@ -0,0 +1,36 @@ +#include "simulator/filters/KalmanFilter/application/PendulumPlant.hpp" + +namespace simulator::filters +{ + PendulumPlant::PendulumPlant(PendulumParameters params) + : parameters(params) + {} + + PendulumState PendulumPlant::Step(float torque, float dt) + { + // θ'' = -(g/L)sin(θ) - b θ' + τ/(mL²) + float g = parameters.gravity; + float L = parameters.length; + float b = parameters.damping; + float m = parameters.mass; + + float thetaDotDot = -(g / L) * std::sin(state.theta) - b * state.thetaDot + torque / (m * L * L); + + // Semi-implicit Euler integration + state.thetaDot += thetaDotDot * dt; + state.theta += state.thetaDot * dt; + + return state; + } + + void PendulumPlant::Reset(float theta0, float thetaDot0) + { + state.theta = theta0; + state.thetaDot = thetaDot0; + } + + PendulumState PendulumPlant::GetState() const + { + return state; + } +} diff --git a/simulator/filters/KalmanFilter/application/PendulumPlant.hpp b/simulator/filters/KalmanFilter/application/PendulumPlant.hpp new file mode 100644 index 00000000..209f4566 --- /dev/null +++ b/simulator/filters/KalmanFilter/application/PendulumPlant.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace simulator::filters +{ + struct PendulumParameters + { + float length = 1.0f; + float mass = 1.0f; + float damping = 0.1f; + float gravity = 9.81f; + }; + + struct PendulumState + { + float theta = 0.0f; + float thetaDot = 0.0f; + }; + + class PendulumPlant + { + public: + explicit PendulumPlant(PendulumParameters params = PendulumParameters{}); + + PendulumState Step(float torque, float dt); + void Reset(float theta0, float thetaDot0); + PendulumState GetState() const; + + private: + PendulumParameters parameters; + PendulumState state; + }; +} diff --git a/simulator/filters/KalmanFilter/view/CMakeLists.txt b/simulator/filters/KalmanFilter/view/CMakeLists.txt new file mode 100644 index 00000000..cfe4ba3b --- /dev/null +++ b/simulator/filters/KalmanFilter/view/CMakeLists.txt @@ -0,0 +1,32 @@ +add_library(numerical.simulator.filters.kalman.view STATIC) + +target_include_directories(numerical.simulator.filters.kalman.view PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.filters.kalman.view PUBLIC + numerical.simulator.filters.kalman.application + Qt6::Widgets +) + +set_target_properties(numerical.simulator.filters.kalman.view PROPERTIES + AUTOMOC ON +) + +target_sources(numerical.simulator.filters.kalman.view PRIVATE + KalmanChartWidget.cpp + KalmanChartWidget.hpp + KalmanConfigPanel.cpp + KalmanConfigPanel.hpp + KalmanMainWindow.cpp + KalmanMainWindow.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.filters.kalman.view PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.filters.kalman.view PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/filters/KalmanFilter/view/KalmanChartWidget.cpp b/simulator/filters/KalmanFilter/view/KalmanChartWidget.cpp new file mode 100644 index 00000000..86b28f95 --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanChartWidget.cpp @@ -0,0 +1,259 @@ +#include "simulator/filters/KalmanFilter/view/KalmanChartWidget.hpp" +#include +#include +#include +#include + +namespace simulator::filters::view +{ + KalmanChartWidget::KalmanChartWidget(const QString& title, QWidget* parent) + : QWidget(parent) + , chartTitle(title) + { + setMinimumSize(400, 300); + } + + void KalmanChartWidget::SetData(const SimulationResult& result) + { + data = result; + + if (!data.time.empty()) + maxTime = data.time.back(); + + minValue = std::numeric_limits::max(); + maxValue = std::numeric_limits::lowest(); + + auto updateRange = [this](const std::vector& values) + { + for (float v : values) + { + minValue = std::min(minValue, v); + maxValue = std::max(maxValue, v); + } + }; + + if (chartTitle.contains("Angle")) + { + updateRange(data.trueTheta); + updateRange(data.measuredTheta); + updateRange(data.kf.theta); + updateRange(data.ekf.theta); + updateRange(data.ukf.theta); + } + else if (chartTitle.contains("Velocity")) + { + updateRange(data.trueThetaDot); + updateRange(data.kf.thetaDot); + updateRange(data.ekf.thetaDot); + updateRange(data.ukf.thetaDot); + } + else if (chartTitle.contains("Covariance")) + { + updateRange(data.kf.covarianceTheta); + updateRange(data.ekf.covarianceTheta); + updateRange(data.ukf.covarianceTheta); + } + else if (chartTitle.contains("Error")) + { + kfError.clear(); + ekfError.clear(); + ukfError.clear(); + kfError.reserve(data.trueTheta.size()); + ekfError.reserve(data.trueTheta.size()); + ukfError.reserve(data.trueTheta.size()); + + for (std::size_t i = 0; i < data.trueTheta.size(); ++i) + { + kfError.push_back(std::abs(data.kf.theta[i] - data.trueTheta[i])); + ekfError.push_back(std::abs(data.ekf.theta[i] - data.trueTheta[i])); + ukfError.push_back(std::abs(data.ukf.theta[i] - data.trueTheta[i])); + } + + updateRange(kfError); + updateRange(ekfError); + updateRange(ukfError); + } + + float margin = (maxValue - minValue) * 0.1f; + if (margin < 0.01f) + margin = 0.1f; + minValue -= margin; + maxValue += margin; + + update(); + } + + void KalmanChartWidget::paintEvent(QPaintEvent* /*event*/) + { + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.fillRect(rect(), Qt::white); + + QRect plotArea(60, 30, width() - 80, height() - 70); + + DrawAxes(painter, plotArea); + DrawGridLines(painter, plotArea); + + if (data.time.empty()) + return; + + if (chartTitle.contains("Angle")) + { + DrawTimeSeries(painter, plotArea, data.time, data.measuredTheta, QColor(200, 200, 200), 1); + DrawTimeSeries(painter, plotArea, data.time, data.trueTheta, Qt::black, 2); + DrawTimeSeries(painter, plotArea, data.time, data.kf.theta, Qt::blue, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ekf.theta, Qt::red, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ukf.theta, QColor(0, 150, 0), 2); + } + else if (chartTitle.contains("Velocity")) + { + DrawTimeSeries(painter, plotArea, data.time, data.trueThetaDot, Qt::black, 2); + DrawTimeSeries(painter, plotArea, data.time, data.kf.thetaDot, Qt::blue, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ekf.thetaDot, Qt::red, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ukf.thetaDot, QColor(0, 150, 0), 2); + } + else if (chartTitle.contains("Covariance")) + { + DrawTimeSeries(painter, plotArea, data.time, data.kf.covarianceTheta, Qt::blue, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ekf.covarianceTheta, Qt::red, 2); + DrawTimeSeries(painter, plotArea, data.time, data.ukf.covarianceTheta, QColor(0, 150, 0), 2); + } + else if (chartTitle.contains("Error")) + { + DrawTimeSeries(painter, plotArea, data.time, kfError, Qt::blue, 2); + DrawTimeSeries(painter, plotArea, data.time, ekfError, Qt::red, 2); + DrawTimeSeries(painter, plotArea, data.time, ukfError, QColor(0, 150, 0), 2); + } + + DrawLegend(painter, plotArea); + } + + void KalmanChartWidget::DrawAxes(QPainter& painter, const QRect& plotArea) + { + painter.setPen(QPen(Qt::black, 1)); + painter.drawRect(plotArea); + + painter.setFont(QFont("Sans", 10, QFont::Bold)); + painter.drawText(plotArea, Qt::AlignHCenter | Qt::AlignTop, chartTitle); + + painter.setFont(QFont("Sans", 8)); + + // Y-axis labels + for (int i = 0; i <= 4; ++i) + { + float val = minValue + (maxValue - minValue) * static_cast(i) / 4.0f; + int y = plotArea.bottom() - static_cast((val - minValue) / (maxValue - minValue) * plotArea.height()); + painter.drawText(5, y + 4, QString::number(static_cast(val), 'f', 2)); + } + + // X-axis labels + for (int i = 0; i <= 5; ++i) + { + float t = maxTime * static_cast(i) / 5.0f; + int x = plotArea.left() + static_cast(t / maxTime * plotArea.width()); + painter.drawText(x - 15, plotArea.bottom() + 15, QString::number(static_cast(t), 'f', 1) + "s"); + } + } + + void KalmanChartWidget::DrawGridLines(QPainter& painter, const QRect& plotArea) + { + painter.setPen(QPen(QColor(230, 230, 230), 1, Qt::DashLine)); + + for (int i = 1; i <= 4; ++i) + { + int y = plotArea.top() + plotArea.height() * i / 5; + painter.drawLine(plotArea.left(), y, plotArea.right(), y); + } + + for (int i = 1; i <= 4; ++i) + { + int x = plotArea.left() + plotArea.width() * i / 5; + painter.drawLine(x, plotArea.top(), x, plotArea.bottom()); + } + } + + void KalmanChartWidget::DrawLegend(QPainter& painter, const QRect& plotArea) + { + painter.setFont(QFont("Sans", 8)); + + struct LegendEntry + { + const char* label; + QColor color; + }; + + std::vector entries; + + if (chartTitle.contains("Angle")) + { + entries = { { "Measurement", QColor(200, 200, 200) }, + { "True", Qt::black }, + { "KF", Qt::blue }, + { "EKF", Qt::red }, + { "UKF", QColor(0, 150, 0) } }; + } + else if (chartTitle.contains("Velocity")) + { + entries = { { "True", Qt::black }, + { "KF", Qt::blue }, + { "EKF", Qt::red }, + { "UKF", QColor(0, 150, 0) } }; + } + else + { + entries = { { "KF", Qt::blue }, + { "EKF", Qt::red }, + { "UKF", QColor(0, 150, 0) } }; + } + + int legendX = plotArea.right() - 120; + int legendY = plotArea.top() + 20; + + painter.fillRect(legendX - 5, legendY - 5, + 125, static_cast(entries.size()) * 18 + 10, + QColor(255, 255, 255, 220)); + + for (std::size_t i = 0; i < entries.size(); ++i) + { + int y = legendY + static_cast(i) * 18; + painter.setPen(QPen(entries[i].color, 2)); + painter.drawLine(legendX, y + 6, legendX + 20, y + 6); + painter.setPen(Qt::black); + painter.drawText(legendX + 25, y + 10, entries[i].label); + } + } + + void KalmanChartWidget::DrawTimeSeries(QPainter& painter, const QRect& plotArea, + const std::vector& time, + const std::vector& values, + const QColor& color, int lineWidth) + { + if (time.size() < 2 || values.size() < 2) + return; + + painter.setPen(QPen(color, lineWidth)); + + float yRange = maxValue - minValue; + if (yRange < 1e-6f) + yRange = 1.0f; + + // Downsample for rendering if too many points + std::size_t step = std::max(std::size_t(1), time.size() / static_cast(plotArea.width())); + + QPoint prev; + bool first = true; + + for (std::size_t i = 0; i < time.size(); i += step) + { + int x = plotArea.left() + static_cast((time[i] / maxTime) * plotArea.width()); + int y = plotArea.bottom() - static_cast(((values[i] - minValue) / yRange) * plotArea.height()); + + QPoint current(x, y); + if (!first) + painter.drawLine(prev, current); + + prev = current; + first = false; + } + } +} diff --git a/simulator/filters/KalmanFilter/view/KalmanChartWidget.hpp b/simulator/filters/KalmanFilter/view/KalmanChartWidget.hpp new file mode 100644 index 00000000..d103b461 --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanChartWidget.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp" +#include + +namespace simulator::filters::view +{ + class KalmanChartWidget + : public QWidget + { + Q_OBJECT + + public: + explicit KalmanChartWidget(const QString& title, QWidget* parent = nullptr); + + void SetData(const SimulationResult& result); + + protected: + void paintEvent(QPaintEvent* event) override; + + private: + void DrawAxes(QPainter& painter, const QRect& plotArea); + void DrawGridLines(QPainter& painter, const QRect& plotArea); + void DrawLegend(QPainter& painter, const QRect& plotArea); + void DrawTimeSeries(QPainter& painter, const QRect& plotArea, + const std::vector& time, + const std::vector& values, + const QColor& color, int width = 1); + + QString chartTitle; + SimulationResult data; + std::vector kfError; + std::vector ekfError; + std::vector ukfError; + float minValue = 0.0f; + float maxValue = 0.0f; + float maxTime = 0.0f; + }; + + class ThetaChartWidget : public KalmanChartWidget + { + public: + explicit ThetaChartWidget(QWidget* parent = nullptr) + : KalmanChartWidget("Angle (θ) Estimation", parent) + {} + }; + + class ThetaDotChartWidget : public KalmanChartWidget + { + public: + explicit ThetaDotChartWidget(QWidget* parent = nullptr) + : KalmanChartWidget("Angular Velocity (θ̇) Estimation", parent) + {} + }; + + class CovarianceChartWidget : public KalmanChartWidget + { + public: + explicit CovarianceChartWidget(QWidget* parent = nullptr) + : KalmanChartWidget("Position Covariance P(θ,θ)", parent) + {} + }; + + class ErrorChartWidget : public KalmanChartWidget + { + public: + explicit ErrorChartWidget(QWidget* parent = nullptr) + : KalmanChartWidget("Estimation Error |θ̂ - θ|", parent) + {} + }; +} diff --git a/simulator/filters/KalmanFilter/view/KalmanConfigPanel.cpp b/simulator/filters/KalmanFilter/view/KalmanConfigPanel.cpp new file mode 100644 index 00000000..8f1377af --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanConfigPanel.cpp @@ -0,0 +1,87 @@ +#include "simulator/filters/KalmanFilter/view/KalmanConfigPanel.hpp" +#include +#include + +namespace simulator::filters::view +{ + KalmanConfigPanel::KalmanConfigPanel(QWidget* parent) + : QWidget(parent) + { + auto* mainLayout = new QVBoxLayout(this); + + // Simulation group + auto* simGroup = new QGroupBox("Simulation", this); + auto* simLayout = new QFormLayout(simGroup); + + durationSpin = CreateSpinBox(1.0, 60.0, 10.0, 1.0, 1); + dtSpin = CreateSpinBox(0.001, 0.1, 0.01, 0.001, 3); + thetaSpin = CreateSpinBox(-3.14, 3.14, 0.5, 0.1, 2); + thetaDotSpin = CreateSpinBox(-10.0, 10.0, 0.0, 0.1, 2); + + simLayout->addRow("Duration (s):", durationSpin); + simLayout->addRow("Time Step (s):", dtSpin); + simLayout->addRow("Initial θ (rad):", thetaSpin); + simLayout->addRow("Initial θ̇ (rad/s):", thetaDotSpin); + + mainLayout->addWidget(simGroup); + + // Noise group + auto* noiseGroup = new QGroupBox("Noise", this); + auto* noiseLayout = new QFormLayout(noiseGroup); + + measNoiseSpin = CreateSpinBox(0.0, 1.0, 0.1, 0.01, 3); + procNoiseSpin = CreateSpinBox(0.0, 1.0, 0.01, 0.001, 3); + + noiseLayout->addRow("Measurement σ:", measNoiseSpin); + noiseLayout->addRow("Process σ:", procNoiseSpin); + + mainLayout->addWidget(noiseGroup); + + // Pendulum group + auto* pendGroup = new QGroupBox("Pendulum", this); + auto* pendLayout = new QFormLayout(pendGroup); + + lengthSpin = CreateSpinBox(0.1, 10.0, 1.0, 0.1, 2); + massSpin = CreateSpinBox(0.1, 10.0, 1.0, 0.1, 2); + dampingSpin = CreateSpinBox(0.0, 5.0, 0.1, 0.01, 3); + + pendLayout->addRow("Length (m):", lengthSpin); + pendLayout->addRow("Mass (kg):", massSpin); + pendLayout->addRow("Damping:", dampingSpin); + + mainLayout->addWidget(pendGroup); + + // Compute button + auto* computeBtn = new QPushButton("Compute", this); + computeBtn->setMinimumHeight(40); + connect(computeBtn, &QPushButton::clicked, this, &KalmanConfigPanel::ComputeRequested); + mainLayout->addWidget(computeBtn); + + mainLayout->addStretch(); + } + + SimulationConfig KalmanConfigPanel::GetConfig() const + { + SimulationConfig config; + config.duration = static_cast(durationSpin->value()); + config.dt = static_cast(dtSpin->value()); + config.initialTheta = static_cast(thetaSpin->value()); + config.initialThetaDot = static_cast(thetaDotSpin->value()); + config.measurementNoiseStdDev = static_cast(measNoiseSpin->value()); + config.processNoiseStdDev = static_cast(procNoiseSpin->value()); + config.pendulum.length = static_cast(lengthSpin->value()); + config.pendulum.mass = static_cast(massSpin->value()); + config.pendulum.damping = static_cast(dampingSpin->value()); + return config; + } + + QDoubleSpinBox* KalmanConfigPanel::CreateSpinBox(double min, double max, double value, double step, int decimals) + { + auto* spinBox = new QDoubleSpinBox(this); + spinBox->setRange(min, max); + spinBox->setValue(value); + spinBox->setSingleStep(step); + spinBox->setDecimals(decimals); + return spinBox; + } +} diff --git a/simulator/filters/KalmanFilter/view/KalmanConfigPanel.hpp b/simulator/filters/KalmanFilter/view/KalmanConfigPanel.hpp new file mode 100644 index 00000000..6e701e8b --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanConfigPanel.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp" +#include +#include +#include +#include +#include + +namespace simulator::filters::view +{ + class KalmanConfigPanel + : public QWidget + { + Q_OBJECT + + public: + explicit KalmanConfigPanel(QWidget* parent = nullptr); + + SimulationConfig GetConfig() const; + + signals: + void ComputeRequested(); + + private: + QDoubleSpinBox* CreateSpinBox(double min, double max, double value, double step, int decimals); + + QDoubleSpinBox* durationSpin; + QDoubleSpinBox* dtSpin; + QDoubleSpinBox* thetaSpin; + QDoubleSpinBox* thetaDotSpin; + QDoubleSpinBox* measNoiseSpin; + QDoubleSpinBox* procNoiseSpin; + QDoubleSpinBox* lengthSpin; + QDoubleSpinBox* massSpin; + QDoubleSpinBox* dampingSpin; + }; +} diff --git a/simulator/filters/KalmanFilter/view/KalmanMainWindow.cpp b/simulator/filters/KalmanFilter/view/KalmanMainWindow.cpp new file mode 100644 index 00000000..cae4f82e --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanMainWindow.cpp @@ -0,0 +1,66 @@ +#include "simulator/filters/KalmanFilter/view/KalmanMainWindow.hpp" +#include +#include +#include + +namespace simulator::filters::view +{ + KalmanMainWindow::KalmanMainWindow(QWidget* parent) + : QMainWindow(parent) + { + setWindowTitle("Kalman Filter Simulator — Pendulum"); + resize(1280, 900); + + auto* splitter = new QSplitter(Qt::Horizontal, this); + + configPanel = new KalmanConfigPanel(splitter); + configPanel->setMaximumWidth(350); + + tabWidget = new QTabWidget(splitter); + + thetaChart = new ThetaChartWidget(tabWidget); + thetaDotChart = new ThetaDotChartWidget(tabWidget); + covarianceChart = new CovarianceChartWidget(tabWidget); + errorChart = new ErrorChartWidget(tabWidget); + + tabWidget->addTab(thetaChart, "Angle (θ)"); + tabWidget->addTab(thetaDotChart, "Velocity (θ̇)"); + tabWidget->addTab(covarianceChart, "Covariance"); + tabWidget->addTab(errorChart, "Error"); + + splitter->addWidget(configPanel); + splitter->addWidget(tabWidget); + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + setCentralWidget(splitter); + + statusBar()->showMessage("Configure parameters and press Compute"); + + connect(configPanel, &KalmanConfigPanel::ComputeRequested, this, &KalmanMainWindow::OnComputeRequested); + } + + void KalmanMainWindow::OnComputeRequested() + { + try + { + auto config = configPanel->GetConfig(); + auto result = simulator.Run(config); + + thetaChart->SetData(result); + thetaDotChart->SetData(result); + covarianceChart->SetData(result); + errorChart->SetData(result); + + statusBar()->showMessage( + QString("Simulation complete — %1 steps, dt=%2s") + .arg(result.time.size()) + .arg(static_cast(config.dt), 0, 'f', 3)); + } + catch (const std::exception& e) + { + QMessageBox::warning(this, "Simulation Error", e.what()); + statusBar()->showMessage("Simulation failed"); + } + } +} diff --git a/simulator/filters/KalmanFilter/view/KalmanMainWindow.hpp b/simulator/filters/KalmanFilter/view/KalmanMainWindow.hpp new file mode 100644 index 00000000..64838333 --- /dev/null +++ b/simulator/filters/KalmanFilter/view/KalmanMainWindow.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "simulator/filters/KalmanFilter/application/KalmanFilterSimulator.hpp" +#include "simulator/filters/KalmanFilter/view/KalmanChartWidget.hpp" +#include "simulator/filters/KalmanFilter/view/KalmanConfigPanel.hpp" +#include +#include + +namespace simulator::filters::view +{ + class KalmanMainWindow + : public QMainWindow + { + Q_OBJECT + + public: + explicit KalmanMainWindow(QWidget* parent = nullptr); + + private: + void OnComputeRequested(); + + KalmanFilterSimulator simulator; + KalmanConfigPanel* configPanel; + QTabWidget* tabWidget; + ThetaChartWidget* thetaChart; + ThetaDotChartWidget* thetaDotChart; + CovarianceChartWidget* covarianceChart; + ErrorChartWidget* errorChart; + }; +}