diff --git a/README.md b/README.md index a9744c86..ca2ceee6 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal |--------------------------------------------------------------------|----------------------------------------------------------------------| | [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors, Convolution & Correlation, Goertzel Algorithm | | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | -| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller, Lead-Lag Compensator | +| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller, Lead-Lag Compensator, Luenberger Observer | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | | [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) | | [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter, CIC (Cascaded Integrator-Comb), Notch/Comb Filter | diff --git a/ROADMAP.md b/ROADMAP.md index 4fb1b0ec..90319eac 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | -| 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ | | 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ | | 21 | LMS / NLMS adaptive filter | `estimators/online` | ★★★☆☆ | | 22 | Savitzky-Golay filter | `filters/passive` | ★★★☆☆ | diff --git a/doc/controllers/LuenbergerObserver.md b/doc/controllers/LuenbergerObserver.md new file mode 100644 index 00000000..a32376da --- /dev/null +++ b/doc/controllers/LuenbergerObserver.md @@ -0,0 +1,134 @@ +# Luenberger Observer + +## Overview & Motivation + +State-feedback controllers require the complete state vector, but physical systems typically expose only a few measured outputs. The **Luenberger observer** reconstructs unmeasured states from input and output measurements using a copy of the plant model continuously corrected by the difference between predicted and actual outputs. + +Unlike the Kalman filter, the Luenberger observer is deterministic — it requires no noise statistics and no covariance propagation. For embedded systems with well-characterized models and deterministic environments, it offers the same state reconstruction at a fraction of the computational cost. + +## Mathematical Theory + +### Discrete-Time State-Space System + +$$x[k+1] = A x[k] + B u[k]$$ +$$y[k] = C x[k] + D u[k]$$ + +### Observer Update Law + +The observer maintains a state estimate $\hat{x}[k]$ updated by: + +$$\hat{y}[k] = C \hat{x}[k] + D u[k]$$ +$$\hat{x}[k+1] = A \hat{x}[k] + B u[k] + L (y[k] - \hat{y}[k])$$ + +The term $y[k] - \hat{y}[k]$ is the **innovation** (output prediction error). The gain matrix $L \in \mathbb{R}^{n \times p}$ scales how aggressively the estimate is corrected. + +### Error Dynamics + +Defining the estimation error $e[k] = x[k] - \hat{x}[k]$: + +$$e[k+1] = (A - LC)\, e[k]$$ + +The error decays to zero if and only if all eigenvalues of $(A - LC)$ lie strictly inside the unit circle. Choosing $L$ to place those eigenvalues at desired locations is the **pole placement** problem for observers. + +### Ackermann's Formula (SISO Output) + +For single-output systems ($p = 1$), the observer gain that places eigenvalues of $(A - LC)$ at $\{\mu_1, \dots, \mu_n\}$ is: + +$$L = \varphi_d(A)\, \mathcal{O}^{-1}\, e_n$$ + +where: +- $\varphi_d(z) = \prod_{i=1}^n (z - \mu_i)$ is the desired characteristic polynomial, evaluated at $A$ +- $\mathcal{O} = \begin{bmatrix} C \\ CA \\ \vdots \\ CA^{n-1} \end{bmatrix}$ is the observability matrix +- $e_n = [0, \dots, 0, 1]^T$ is the last standard basis vector + +This is the dual of Ackermann's controller placement formula. + +### Observability Condition + +Ackermann's formula requires $\mathcal{O}$ to be invertible, which holds if and only if the pair $(A, C)$ is **observable**: every state affects the output through some combination of shifts. An unobservable pair makes the formula degenerate — the gain cannot force arbitrary error convergence. + +## Complexity Analysis + +| Phase | Time | Space | Notes | +|--------------------|---------------|----------|-----------------------------------------------------| +| Design (Ackermann) | $O(n^3)$ | $O(n^2)$ | Observability matrix build + linear solve | +| Update (per step) | $O(n^2 + np)$ | $O(n^2)$ | Matrix-vector products; dominant cost is $A\hat{x}$ | + +The design phase is offline. The real-time cost per sample is dominated by the $n \times n$ state-transition multiply. + +## Step-by-Step Walkthrough + +**System:** Double integrator, $n=2$, $p=1$, desired observer poles $\{\mu_1, \mu_2\} = \{0.2,\, 0.3\}$ + +$$A = \begin{bmatrix}1 & 1\\0 & 1\end{bmatrix}, \quad B = \begin{bmatrix}0\\1\end{bmatrix}, \quad C = \begin{bmatrix}1 & 0\end{bmatrix}$$ + +**Step 1 — Build observability matrix:** + +$$\mathcal{O} = \begin{bmatrix}C\\CA\end{bmatrix} = \begin{bmatrix}1 & 0\\1 & 1\end{bmatrix}$$ + +**Step 2 — Evaluate desired polynomial at $A$:** + +$$\varphi_d(z) = (z - 0.2)(z - 0.3) = z^2 - 0.5z + 0.06$$ + +$$\varphi_d(A) = A^2 - 0.5A + 0.06I = \begin{bmatrix}0.56 & 1.5\\0 & 0.56\end{bmatrix}$$ + +**Step 3 — Solve for gain:** + +$$\mathcal{O}^{-1} = \begin{bmatrix}1 & 0\\-1 & 1\end{bmatrix}, \quad \mathcal{O}^{-1} e_2 = \begin{bmatrix}0\\1\end{bmatrix}$$ + +$$L = \varphi_d(A) \cdot \begin{bmatrix}0\\1\end{bmatrix} = \begin{bmatrix}1.5\\0.56\end{bmatrix}$$ + +**Verification:** eigenvalues of $A - LC = \begin{bmatrix}-0.5 & 1\\-0.56 & 1\end{bmatrix}$ are $\{0.2, 0.3\}$. ✓ + +## Pitfalls & Edge Cases + +- **Unobservable pair.** If $\mathcal{O}$ is rank-deficient, the linear solve in Ackermann's formula fails. Verify observability with a rank test before design. +- **Pole placement too aggressive.** Observer poles much faster than the controller poles amplify measurement noise, since every output error is fed back through $L$. Typical practice: observer poles 2–5× faster than controller poles. +- **Deadbeat design** (all poles at zero) converges in exactly $n$ steps but maximizes noise sensitivity and requires large $L$ entries, risking numerical overflow in fixed-point. +- **MIMO output limitation.** Ackermann's formula applies to SISO output ($p=1$). Multi-output systems require alternative pole-placement methods (e.g., Brogan's formula or numerical optimization). +- **Model mismatch.** If the observer plant differs from the true plant, the error dynamics no longer satisfy $e[k+1] = (A-LC)e[k]$ exactly; a bounded steady-state error results rather than zero convergence. + +## Variants & Generalizations + +| Variant | Key Difference | +|----------------------------------|---------------------------------------------------------------------------------------------------| +| **Kalman Filter** | Stochastic design — minimizes covariance rather than placing poles; handles noise statistics | +| **Extended Luenberger Observer** | Linearizes a nonlinear plant around the estimate for quasi-linear operation | +| **Unknown-Input Observer** | Estimates states in the presence of unmeasured disturbances | +| **Reduced-Order Observer** | Estimates only the unmeasured states, using measured outputs directly | +| **Continuous-time observer** | Uses $\dot{\hat{x}} = A\hat{x} + Bu + L(y - C\hat{x})$; same structure, continuous pole placement | + +## Applications + +- **Motor control** — estimating velocity and back-EMF from position and current sensors. +- **Automotive suspension** — reconstructing unsprung mass velocity from chassis accelerometers. +- **Satellite attitude estimation** — inferring angular rates from gyros and star trackers. +- **Observer-based compensator** — pairing with LQR to form the deterministic equivalent of LQG when noise statistics are unavailable. + +## Connections to Other Algorithms + +```mermaid +graph LR + LO["Luenberger Observer"] + LTI["LinearTimeInvariant"] + GE["Gaussian Elimination"] + LQR["LQR Controller"] + KF["Kalman Filter"] + LTI -->|"plant model"| LO + GE -->|"solve O^{-1}"| LO + LO -->|"state estimate"| LQR + KF -.->|"stochastic counterpart"| LO +``` + +| Algorithm | Relationship | +|-----------------------------------------------------------|---------------------------------------------------------------------------| +| [Linear Time-Invariant Model](LinearTimeInvariant.md) | Supplies the $(A, B, C, D)$ matrices used in both design and update steps | +| [Gaussian Elimination](../solvers/GaussianElimination.md) | Solves $\mathcal{O} x = e_n$ inside Ackermann's formula | +| [LQR Controller](Lqr.md) | Primary consumer of the observer's state estimate | +| [Kalman Filter](../filters/active/KalmanFilter.md) | Stochastic counterpart; adds noise covariance propagation | + +## References & Further Reading + +- Luenberger, D.G., "An Introduction to Observers," *IEEE Transactions on Automatic Control*, 16(6), 1971. +- Franklin, G.F., Powell, J.D. and Emami-Naeini, A., *Feedback Control of Dynamic Systems*, 8th ed., Pearson, 2019 — Chapter 7. +- Chen, C.-T., *Linear System Theory and Design*, 4th ed., Oxford University Press, 2013 — Chapter 8. diff --git a/doc/controllers/README.md b/doc/controllers/README.md index 408b740a..1c8a127f 100644 --- a/doc/controllers/README.md +++ b/doc/controllers/README.md @@ -13,3 +13,4 @@ Feedback control algorithms for regulating dynamic systems in real time. | [MPC Controller](Mpc.md) | Model Predictive Controller — receding-horizon optimal control with constraint handling | | [Linear Time-Invariant Model](LinearTimeInvariant.md) | Discrete-time state-space plant model (A, B, C, D) shared across controllers and filters | | [Feedforward / 2-DOF Controller](Feedforward2Dof.md) | Feedforward + feedback wrapper for decoupled reference tracking and disturbance rejection | +| [Luenberger Observer](LuenbergerObserver.md) | Deterministic state estimator using pole placement (Ackermann's formula) to reconstruct unmeasured states | diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index 6bfc6c86..152a7d2c 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -18,6 +18,7 @@ target_sources(numerical.controllers.implementations PRIVATE LeadLagCompensator.hpp Lqg.hpp Lqr.hpp + LuenbergerObserver.hpp Mpc.hpp PidIncremental.hpp SaturationRateLimiter.hpp @@ -30,6 +31,7 @@ numerical_add_coverage_sources(numerical.controllers.implementations LeadLagCompensator.cpp Lqg.cpp Lqr.cpp + LuenbergerObserver.cpp Mpc.cpp PidIncremental.cpp SaturationRateLimiter.cpp diff --git a/numerical/controllers/implementations/LuenbergerObserver.cpp b/numerical/controllers/implementations/LuenbergerObserver.cpp new file mode 100644 index 00000000..af04be6a --- /dev/null +++ b/numerical/controllers/implementations/LuenbergerObserver.cpp @@ -0,0 +1,8 @@ +#include "numerical/controllers/implementations/LuenbergerObserver.hpp" + +namespace controllers +{ + template class LuenbergerObserver; + template class LuenbergerObserver; + template class LuenbergerObserver; +} diff --git a/numerical/controllers/implementations/LuenbergerObserver.hpp b/numerical/controllers/implementations/LuenbergerObserver.hpp new file mode 100644 index 00000000..e8c474cf --- /dev/null +++ b/numerical/controllers/implementations/LuenbergerObserver.hpp @@ -0,0 +1,145 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include +#include +#include + +namespace controllers +{ + template + class LuenbergerObserver + { + static_assert(std::is_floating_point_v, "LuenbergerObserver supports floating-point types"); + static_assert(StateSize > 0, "StateSize must be positive"); + static_assert(InputSize > 0, "InputSize must be positive"); + static_assert(OutputSize > 0, "OutputSize must be positive"); + + public: + using Plant = math::LinearTimeInvariant; + using StateMatrix = math::SquareMatrix; + using GainMatrix = math::Matrix; + using StateVector = math::Vector; + using InputVector = math::Vector; + using OutputVector = math::Vector; + + LuenbergerObserver(const Plant& plant, const GainMatrix& observerGain); + + static GainMatrix AckermannGain(const Plant& plant, const std::array& desiredPoles); + + OPTIMIZE_FOR_SPEED StateVector Update(const InputVector& u, const OutputVector& y); + + [[nodiscard]] const StateVector& Estimate() const; + + void Reset(const StateVector& x0); + + private: + static StateMatrix BuildObservabilityMatrix(const StateMatrix& A, const math::Matrix& C); + static StateMatrix EvaluateCharacteristicPoly(const StateMatrix& A, const std::array& poles); + + Plant plant; + GainMatrix L; + StateVector xhat; + }; + + template + LuenbergerObserver::LuenbergerObserver( + const Plant& plantModel, const GainMatrix& observerGain) + : plant{ plantModel } + , L{ observerGain } + , xhat{} + {} + + template + OPTIMIZE_FOR_SPEED + typename LuenbergerObserver::StateVector + LuenbergerObserver::Update( + const InputVector& u, const OutputVector& y) + { + OutputVector yhat = plant.C * xhat + plant.D * u; + OutputVector innovation = y - yhat; + xhat = plant.A * xhat + plant.B * u + L * innovation; + return xhat; + } + + template + const typename LuenbergerObserver::StateVector& + LuenbergerObserver::Estimate() const + { + return xhat; + } + + template + void LuenbergerObserver::Reset(const StateVector& x0) + { + xhat = x0; + } + + template + typename LuenbergerObserver::StateMatrix + LuenbergerObserver::BuildObservabilityMatrix( + const StateMatrix& A, const math::Matrix& C) + { + static_assert(OutputSize == 1, "Ackermann's formula requires SISO output (OutputSize == 1)"); + StateMatrix O{}; + math::Matrix CAk = C; + for (std::size_t k = 0; k < StateSize; ++k) + { + for (std::size_t col = 0; col < StateSize; ++col) + O.at(k, col) = CAk.at(0, col); + CAk = CAk * A; + } + return O; + } + + template + typename LuenbergerObserver::StateMatrix + LuenbergerObserver::EvaluateCharacteristicPoly( + const StateMatrix& A, const std::array& poles) + { + StateMatrix result = StateMatrix::Identity(); + for (std::size_t i = 0; i < StateSize; ++i) + { + StateMatrix shifted = A; + for (std::size_t r = 0; r < StateSize; ++r) + shifted.at(r, r) = shifted.at(r, r) - poles[i]; + result = result * shifted; + } + return result; + } + + template + typename LuenbergerObserver::GainMatrix + LuenbergerObserver::AckermannGain( + const Plant& plant, const std::array& desiredPoles) + { + static_assert(OutputSize == 1, "Ackermann's formula requires SISO output (OutputSize == 1)"); + + StateMatrix O = BuildObservabilityMatrix(plant.A, plant.C); + StateMatrix phi = EvaluateCharacteristicPoly(plant.A, desiredPoles); + + StateVector eLast{}; + eLast.at(StateSize - 1, 0) = T(1); + + StateVector OinvEn = solvers::SolveSystem(O, eLast); + + StateVector Lgain = phi * OinvEn; + + GainMatrix result{}; + for (std::size_t i = 0; i < StateSize; ++i) + result.at(i, 0) = Lgain.at(i, 0); + return result; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class LuenbergerObserver; + extern template class LuenbergerObserver; + extern template class LuenbergerObserver; +#endif +} diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index 76a50cec..5aa15856 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -15,6 +15,7 @@ target_sources(numerical.controllers_test PRIVATE TestLeadLagCompensator.cpp TestLqg.cpp TestLqr.cpp + TestLuenbergerObserver.cpp TestMpc.cpp TestPidIncremental.cpp TestSaturationRateLimiter.cpp diff --git a/numerical/controllers/implementations/test/TestLuenbergerObserver.cpp b/numerical/controllers/implementations/test/TestLuenbergerObserver.cpp new file mode 100644 index 00000000..ec4cdf55 --- /dev/null +++ b/numerical/controllers/implementations/test/TestLuenbergerObserver.cpp @@ -0,0 +1,216 @@ +#include "numerical/controllers/implementations/LuenbergerObserver.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" +#include "numerical/math/Tolerance.hpp" +#include +#include + +namespace +{ + using Plant21 = math::LinearTimeInvariant; + using Observer = controllers::LuenbergerObserver; + + static Plant21 MakeDoubleIntegrator() + { + Plant21 p{}; + p.A = math::SquareMatrix{ { 1.0f, 1.0f }, { 0.0f, 1.0f } }; + p.B = math::Matrix{ { 0.0f }, { 1.0f } }; + p.C = math::Matrix{ { 1.0f, 0.0f } }; + return p; + } + + static math::Matrix DesignGain() + { + std::array poles{ 0.2f, 0.3f }; + return Observer::AckermannGain(MakeDoubleIntegrator(), poles); + } + + class TestLuenbergerObserver : public ::testing::Test + { + protected: + Plant21 plant{ MakeDoubleIntegrator() }; + Observer observer{ plant, DesignGain() }; + }; +} + +TEST_F(TestLuenbergerObserver, converges_to_true_state) +{ + math::Vector xtrue{ { 1.0f }, { 0.5f } }; + observer.Reset(math::Vector{ { 0.0f }, { 0.0f } }); + math::Vector u{ { 0.0f } }; + + for (int k = 0; k < 30; ++k) + { + math::Vector y = plant.C * xtrue; + observer.Update(u, y); + xtrue = plant.Step(xtrue, u); + } + + auto xhat = observer.Estimate(); + EXPECT_NEAR(xhat.at(0, 0), xtrue.at(0, 0), 1e-2f); + EXPECT_NEAR(xhat.at(1, 0), xtrue.at(1, 0), 1e-2f); +} + +TEST_F(TestLuenbergerObserver, zero_innovation_when_estimate_correct) +{ + math::Vector x{ { 2.0f }, { -1.0f } }; + observer.Reset(x); + math::Vector u{ { 0.5f } }; + + math::Vector y = plant.C * x + plant.D * u; + auto xhat = observer.Update(u, y); + + math::Vector xExpected = plant.Step(x, u); + EXPECT_NEAR(xhat.at(0, 0), xExpected.at(0, 0), math::Tolerance()); + EXPECT_NEAR(xhat.at(1, 0), xExpected.at(1, 0), math::Tolerance()); +} + +TEST_F(TestLuenbergerObserver, ackermann_places_requested_poles) +{ + std::array poles{ 0.2f, 0.3f }; + auto L = Observer::AckermannGain(plant, poles); + + math::SquareMatrix AminusLC = plant.A; + for (std::size_t i = 0; i < 2; ++i) + for (std::size_t j = 0; j < 1; ++j) + for (std::size_t k = 0; k < 2; ++k) + AminusLC.at(i, k) -= L.at(i, j) * plant.C.at(j, k); + + float trace = AminusLC.Trace(); + float det = AminusLC.at(0, 0) * AminusLC.at(1, 1) - AminusLC.at(0, 1) * AminusLC.at(1, 0); + + float expectedTrace = 0.2f + 0.3f; + float expectedDet = 0.2f * 0.3f; + + EXPECT_NEAR(trace, expectedTrace, 1e-3f); + EXPECT_NEAR(det, expectedDet, 1e-3f); +} + +TEST_F(TestLuenbergerObserver, faster_poles_converge_quicker) +{ + math::Vector xtrue{ { 0.0f }, { 0.0f } }; + math::Vector xhatWrong{ { 1.0f }, { 1.0f } }; + math::Vector u{ { 0.0f } }; + + std::array slowPoles{ 0.5f, 0.5f }; + std::array fastPoles{ 0.05f, 0.05f }; + + auto Lslow = Observer::AckermannGain(plant, slowPoles); + auto Lfast = Observer::AckermannGain(plant, fastPoles); + + Observer slowObs{ plant, Lslow }; + Observer fastObs{ plant, Lfast }; + slowObs.Reset(xhatWrong); + fastObs.Reset(xhatWrong); + + constexpr float tol = 0.05f; + int slowSteps = 0; + int fastSteps = 0; + + for (int k = 0; k < 100; ++k) + { + math::Vector y = plant.C * xtrue; + + slowObs.Update(u, y); + fastObs.Update(u, y); + + auto eS0 = slowObs.Estimate().at(0, 0) - xtrue.at(0, 0); + auto eS1 = slowObs.Estimate().at(1, 0) - xtrue.at(1, 0); + auto eF0 = fastObs.Estimate().at(0, 0) - xtrue.at(0, 0); + auto eF1 = fastObs.Estimate().at(1, 0) - xtrue.at(1, 0); + + float normSlow = std::sqrt(eS0 * eS0 + eS1 * eS1); + float normFast = std::sqrt(eF0 * eF0 + eF1 * eF1); + + if (slowSteps == 0 && normSlow < tol) + slowSteps = k + 1; + if (fastSteps == 0 && normFast < tol) + fastSteps = k + 1; + } + + EXPECT_LT(fastSteps, slowSteps); +} + +TEST_F(TestLuenbergerObserver, rejects_initial_error_geometrically) +{ + std::array poles{ 0.2f, 0.3f }; + auto L = Observer::AckermannGain(plant, poles); + Observer obs{ plant, L }; + + math::Vector xtrue{ { 0.0f }, { 0.0f } }; + math::Vector x0hat{ { 1.0f }, { 0.0f } }; + obs.Reset(x0hat); + math::Vector u{ { 0.0f } }; + + auto e0Vec = x0hat; + float e0 = std::sqrt(e0Vec.at(0, 0) * e0Vec.at(0, 0) + e0Vec.at(1, 0) * e0Vec.at(1, 0)); + + math::Vector y = plant.C * xtrue; + obs.Update(u, y); + + auto e1Vec = obs.Estimate(); + float e1 = std::sqrt(e1Vec.at(0, 0) * e1Vec.at(0, 0) + e1Vec.at(1, 0) * e1Vec.at(1, 0)); + + EXPECT_LT(e1, e0); + + for (int k = 0; k < 10; ++k) + { + y = plant.C * xtrue; + obs.Update(u, y); + } + auto eFinalVec = obs.Estimate(); + float eFinal = std::sqrt(eFinalVec.at(0, 0) * eFinalVec.at(0, 0) + eFinalVec.at(1, 0) * eFinalVec.at(1, 0)); + EXPECT_LT(eFinal, 0.1f * e0); +} + +TEST_F(TestLuenbergerObserver, reset_sets_estimate) +{ + math::Vector x0{ { 3.0f }, { -2.0f } }; + observer.Reset(x0); + + EXPECT_NEAR(observer.Estimate().at(0, 0), 3.0f, math::Tolerance()); + EXPECT_NEAR(observer.Estimate().at(1, 0), -2.0f, math::Tolerance()); +} + +TEST_F(TestLuenbergerObserver, tracks_under_input_excitation) +{ + math::Vector xtrue{ { 0.0f }, { 0.0f } }; + observer.Reset(math::Vector{ { 1.0f }, { 0.0f } }); + + std::array inputs{ 0.5f, -0.3f, 0.1f, 0.2f, -0.4f }; + + for (int k = 0; k < 30; ++k) + { + math::Vector u{ { inputs[static_cast(k) % inputs.size()] } }; + math::Vector y = plant.C * xtrue; + observer.Update(u, y); + xtrue = plant.Step(xtrue, u); + } + + auto xhat = observer.Estimate(); + EXPECT_NEAR(xhat.at(0, 0), xtrue.at(0, 0), 5e-2f); + EXPECT_NEAR(xhat.at(1, 0), xtrue.at(1, 0), 5e-2f); +} + +TEST_F(TestLuenbergerObserver, feedthrough_D_accounted_in_output) +{ + Plant21 plantWithD{}; + plantWithD.A = plant.A; + plantWithD.B = plant.B; + plantWithD.C = plant.C; + plantWithD.D = math::Matrix{ { 0.5f } }; + + std::array poles{ 0.2f, 0.3f }; + auto L = Observer::AckermannGain(plantWithD, poles); + Observer obsD{ plantWithD, L }; + + math::Vector x{ { 1.0f }, { 0.5f } }; + obsD.Reset(x); + math::Vector u{ { 2.0f } }; + + math::Vector y = plantWithD.C * x + plantWithD.D * u; + auto xhat = obsD.Update(u, y); + + math::Vector xNext = plantWithD.Step(x, u); + EXPECT_NEAR(xhat.at(0, 0), xNext.at(0, 0), math::Tolerance()); + EXPECT_NEAR(xhat.at(1, 0), xNext.at(1, 0), math::Tolerance()); +} diff --git a/roadmap/controllers/LuenbergerObserver/explanation.md b/roadmap/controllers/LuenbergerObserver/explanation.md deleted file mode 100644 index d0054ef7..00000000 --- a/roadmap/controllers/LuenbergerObserver/explanation.md +++ /dev/null @@ -1,33 +0,0 @@ -# Luenberger Observer — Overview - -## What it is -A deterministic state estimator. Given a plant model `(A, B, C)` and its inputs `u` and outputs -`y`, it runs a copy of the model and continuously corrects that copy using the **innovation** — -the difference between the measured and predicted output — scaled by an observer gain `L`. - -## Why it matters (embedded) -State-feedback controllers (LQR, pole placement) need the *full* state vector, but sensors usually -measure only a few outputs. The Luenberger observer reconstructs the unmeasured states from the -measured ones using nothing but arithmetic — no extra sensors. It is the deterministic, lower-cost -cousin of the Kalman filter (no covariance propagation). - -## How it works (intuition) -Run the model open-loop and it drifts from reality. Feed back the output error through `L` and the -estimate is pulled toward the true state. The estimation error obeys `e[k+1] = (A−L·C)e[k]`, so -choosing `L` to place the eigenvalues of `A−L·C` inside the unit circle makes the error decay. -**Ackermann's formula** computes the `L` that puts those poles exactly where you ask — as long as -the system is observable. - -## Key parameters -- **plant (A, B, C, D)** — the state-space model being observed. -- **observer gain L** — placed via Ackermann's formula from the desired observer poles. -- **desired poles** — set 2–5× faster than the controller poles; faster means quicker convergence - but more noise sensitivity. - -## Reference -D. G. Luenberger, "An Introduction to Observers," *IEEE Trans. Automatic Control*, 16(6), 1971; -Ackermann's formula (Franklin, Powell, Emami-Naeini). - -## See also -`Lqr` / `StateFeedbackController` (consumers of the estimate); `KalmanFilter` (stochastic -counterpart); `ControllabilityObservability` (verify observability before designing `L`). diff --git a/roadmap/controllers/LuenbergerObserver/implementation.md b/roadmap/controllers/LuenbergerObserver/implementation.md deleted file mode 100644 index aaf3ef56..00000000 --- a/roadmap/controllers/LuenbergerObserver/implementation.md +++ /dev/null @@ -1,80 +0,0 @@ -# Luenberger Observer (Pole Placement / Ackermann) — Implementation Pseudocode - -> Roadmap ref: #19 (Tier 3) · Target: `numerical/controllers` · Namespace `controllers` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class LuenbergerObserver: - math::LinearTimeInvariant plant # A,B,C,D - math::Matrix L # observer gain - math::Vector xhat # state estimate -``` - -## Interface - -``` -# Gain designed offline and injected: -LuenbergerObserver(const LinearTimeInvariant& plant, - const Matrix& L) - -# Or designed in-place from desired observer poles (SISO output): -static Matrix AckermannGain( - const LinearTimeInvariant& plant, - const std::array& desiredPoles) - -Vector Update(const InputVector& u, const OutputVector& y) # hot path -const Vector& Estimate() const -void Reset(const Vector& x0) -``` - -## Algorithm (pseudocode) - -``` -function Update(u, y): # OPTIMIZE_FOR_SPEED - yhat = plant.C * xhat + plant.D * u # predicted output - innovation = y - yhat # measurement residual - # x̂[k+1] = A x̂ + B u + L (y - C x̂) - xhat = plant.A * xhat + plant.B * u + L * innovation - return xhat - -function AckermannGain(plant, desiredPoles): - # Dual of controller pole placement (observability form) - O = ObservabilityMatrix(plant.A, plant.C) # [C; CA; ...; CA^(n-1)] - phi = EvaluateCharacteristicPoly(plant.A, desiredPoles) # φ_d(A) - # L = φ_d(A) · O^{-1} · e_last - return phi * Inverse(O) * UnitVectorLast(StateSize) -``` - -## Complexity & memory - -- `Update`: `O(StateSize²)` for the `A·x̂` and `L·innovation` products (dense matrices). -- `AckermannGain` (design-time): `O(StateSize³)` for the observability-matrix solve. -- Memory: `O(StateSize²)` for `A`/`L`, `O(StateSize)` for the estimate — all static. - -## Numerical / embedded notes - -- Place observer poles **faster** than the controller poles (≈2–5×) so estimation error decays - before it corrupts feedback — but not so fast that measurement noise is amplified. -- Requires an **observable** `(A, C)` pair; check with the observability rank test (item 26) before - trusting Ackermann's formula (which assumes full rank). -- Reuse `GaussianElimination` for the `O^{-1}` solve rather than forming an explicit inverse. -- The estimate feeds a `StateFeedbackController` (e.g. `Lqr`); together they form an - observer-based compensator (the deterministic sibling of LQG). -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/controllers/implementations/LuenbergerObserver.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Update`, and - `extern template class LuenbergerObserver;` - under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/controllers/implementations/LuenbergerObserver.cpp` → - `template class LuenbergerObserver;` -- Test: `numerical/controllers/implementations/test/TestLuenbergerObserver.cpp` -- Doc: `doc/controllers/LuenbergerObserver.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestLuenbergerObserver.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/controllers/LuenbergerObserver/tests.md b/roadmap/controllers/LuenbergerObserver/tests.md deleted file mode 100644 index c449ae54..00000000 --- a/roadmap/controllers/LuenbergerObserver/tests.md +++ /dev/null @@ -1,62 +0,0 @@ -# Luenberger Observer — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestLuenbergerObserver : public ::testing::Test: - # 2-state SISO plant (e.g. double integrator), full-state output C = I - math::LinearTimeInvariant plant = MakeDoubleIntegrator() - LuenbergerObserver observer{ plant, DesignGain() } -# each case below is a TEST_F(TestLuenbergerObserver, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -converges_to_true_state: - Arrange: run true plant + observer from different initial conditions - Act: iterate Update(u, y) for K steps - Assert: ||xhat - xtrue|| -> 0 (below tol) - -zero_innovation_when_estimate_correct: - Arrange: seed xhat == xtrue, exact model - Assert: innovation == 0, estimate tracks the plant exactly - -ackermann_places_requested_poles: - Arrange: desired observer poles {0.2, 0.3} - Act: L = AckermannGain(plant, poles) - Assert: eig(A - L·C) ≈ {0.2, 0.3} - -faster_poles_converge_quicker: - Arrange: two gains with poles at 0.5 vs 0.1 - Assert: the 0.1-pole observer reaches tol in fewer steps - -rejects_initial_error_geometrically: - Arrange: initial estimate error e0 - Assert: error magnitude decays like the dominant observer pole per step - -reset_sets_estimate: - Arrange: Reset(x0) - Assert: Estimate() == x0 - -tracks_under_input_excitation: - Arrange: non-zero u sequence - Assert: estimate follows the driven true state - -feedthrough_D_accounted_in_output: - Arrange: plant with D != 0 - Assert: predicted output uses C·x̂ + D·u (innovation correct) -``` - -## Reference vectors - -- Error dynamics `e[k+1] = (A − L·C) e[k]`; eigenvalues must equal the placed poles. -- Double-integrator with poles `{0.2,0.3}` gives a hand-computable `L` as the golden vector. - -## Edge cases - -- Unobservable `(A,C)` — Ackermann's inverse is singular; document/guard the failure. -- Deadbeat poles (all at 0) — the estimate must settle in `StateSize` steps exactly. -- Model mismatch — bounded steady-state error rather than divergence.