diff --git a/.github/agents/executor.agent.md b/.github/agents/executor.agent.md index 443d6d4c..a7e55725 100644 --- a/.github/agents/executor.agent.md +++ b/.github/agents/executor.agent.md @@ -240,10 +240,12 @@ namespace filters::passive **ALWAYS update documentation for every change:** - Create or update `doc/{domain}/{AlgorithmName}.md` for every new or modified algorithm -- Use `doc/TEMPLATE.md` as the starting template for new documentation files -- Include: mathematical background, implementation details, usage examples, numerical properties +- Use `doc/TEMPLATE.md` as the starting template — follow its structure exactly +- Documentation is **design-first**: cover mathematical theory, algorithm behaviour, complexity, pitfalls, and connections to other algorithms +- **Do NOT add implementation details** (class names, template parameters, header paths) +- **Do NOT add usage code examples** — the implementation follows the doc, not the other way around - Update `doc/{domain}/README.md` if a new algorithm is added -- Documentation must stay in sync with code changes +- Keep documentation in sync with algorithmic changes --- @@ -256,8 +258,9 @@ namespace filters::passive 5. **Create or update tests** using `TYPED_TEST` pattern for every change 6. **Update `CMakeLists.txt`** if new files were added 7. **Update documentation** in `doc/` for every algorithm added or changed -8. **Build and test**: run `cmake --build --preset host` and `ctest --preset host` -9. **Hand off to reviewer** using the handoff button +8. **Add launch configuration** to `.vscode/launch.json` if a new simulator was created — follow the existing `cppdbg` entry pattern; insert before the generic `"Linux Debug"` entry +9. **Build and test**: run `cmake --build --preset host` and `ctest --preset host` +10. **Hand off to reviewer** using the handoff button ## What NOT to Do diff --git a/.github/agents/planner.agent.md b/.github/agents/planner.agent.md index 4d7be809..5ae95192 100644 --- a/.github/agents/planner.agent.md +++ b/.github/agents/planner.agent.md @@ -67,13 +67,15 @@ For each file to create or modify, specify: #### Documentation Update - Documentation file to create or update: `doc/{domain}/{AlgorithmName}.md` -- Mathematical background section -- Implementation details and considerations -- Usage examples +- Follow `doc/TEMPLATE.md` structure exactly +- Mathematical background: theory, derivations, complexity, pitfalls, connections - Numerical properties and limitations (stability, range, precision) +- **No implementation details** (class names, template parameters, header paths) +- **No usage code examples** — docs describe algorithm design; implementation follows from them #### Build Integration - `CMakeLists.txt` changes using `numerical_add_header_library()` and `numerical_add_coverage_sources()` +- If a new simulator is created: add a `cppdbg` launch entry to `.vscode/launch.json` following the existing pattern (program path, GDB setup, insert before `"Linux Debug"`) - Build commands: `cmake --preset host && cmake --build --preset host` - Test commands: `ctest --preset host` @@ -148,8 +150,9 @@ Before finalizing, verify the plan against these constraints: ### Documentation — ALWAYS UPDATED - [ ] `doc/{domain}/{AlgorithmName}.md` created or updated for every change +- [ ] Follows `doc/TEMPLATE.md` structure - [ ] Mathematical background with equations -- [ ] Implementation details and considerations -- [ ] Usage examples with code snippets - [ ] Numerical properties: stability, range, precision, real-time suitability +- [ ] No implementation details (class names, template params, header paths) +- [ ] No usage code examples or code snippets - [ ] README in domain's `doc/{domain}/README.md` updated if needed diff --git a/.github/agents/reviewer.agent.md b/.github/agents/reviewer.agent.md index 57d71d14..b98ee0c1 100644 --- a/.github/agents/reviewer.agent.md +++ b/.github/agents/reviewer.agent.md @@ -160,9 +160,10 @@ End with a summary: total criticals, warnings, suggestions, and overall verdict ### 13. Documentation Alignment (CRITICAL) - [ ] `doc/{domain}/{AlgorithmName}.md` exists and is up-to-date for every changed algorithm +- [ ] Follows `doc/TEMPLATE.md` structure - [ ] Documentation includes mathematical background (equations, formulas) -- [ ] Documentation includes implementation details and considerations -- [ ] Documentation includes usage examples with code snippets +- [ ] Documentation does **not** include implementation details (class names, template params, header paths) +- [ ] Documentation does **not** include usage code examples or code snippets - [ ] Documentation includes numerical properties: stability, range, precision, real-time suitability - [ ] `doc/{domain}/README.md` updated if a new algorithm was added - [ ] README references correct numeric type support @@ -176,6 +177,7 @@ End with a summary: total criticals, warnings, suggestions, and overall verdict - [ ] `target_link_libraries` uses `${NUMERICAL_VISIBILITY}` variable - [ ] No circular dependencies between targets - [ ] Test subdirectory added via `add_subdirectory(test)` +- [ ] If a new simulator was created: `.vscode/launch.json` has a new `cppdbg` entry with the correct program path and inserted before the generic `"Linux Debug"` entry ### 15. Code Quality Tools (WARNING) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index d806f6c5..935bcaee 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -73,11 +73,11 @@ Place code here when it is: When implementing or modifying algorithms: - **ALWAYS UPDATE DOCUMENTATION**: Each algorithm must have corresponding documentation in `doc/` -- Include mathematical background and theory -- Provide implementation details and considerations -- Add usage examples and expected behaviors -- Document numerical properties and limitations -- Keep documentation in sync with code changes +- Follow the structure defined in `doc/TEMPLATE.md` exactly +- Documentation is **design-first**: describe mathematical theory, algorithm behaviour, complexity, pitfalls, and connections — not how the code is written +- **Do NOT include implementation details** (e.g., class names, template parameters, header paths) +- **Do NOT include usage examples or code snippets** — the implementation must follow what the doc describes, not the other way around +- Keep documentation in sync with algorithmic changes (not code-level changes) ## Design Principles @@ -114,6 +114,30 @@ These are the most important architectural directives in this codebase. Every ne - **Naming convention**: Targets follow `numerical.simulator...` (e.g., `numerical.simulator.controllers.lqr.application`). - **Library code reuse**: Use `numerical_add_header_library()` and `numerical_add_coverage_sources()` from `cmake/NumericalHeaderLibrary.cmake` for all `numerical/` targets. - **Compiler options blocks**: Every simulator target repeats the same MSVC/GCC warning suppression — keep this consistent across all targets. +- **Launch configuration**: Every new simulator MUST have a corresponding entry added to `.vscode/launch.json`. Follow the existing pattern exactly: + ```json + { + "name": " Simulator", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/build/host/simulator///Debug/numerical.simulator..", + "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 + } + ] + } + ``` + Insert the new entry before the generic `"Linux Debug"` configuration, which must remain last. ## Coding Style and Patterns @@ -402,8 +426,6 @@ When implementing a new algorithm: 4. **Write comprehensive tests** for all numeric types 5. **Document in `doc/`** with: - Mathematical background - - Implementation details - - Usage examples - Numerical considerations (stability, range, precision) 6. **Consider SIMD optimizations** where applicable using `math::SingleInstructionMultipleData` diff --git a/.github/instructions/numerical-cpp.instructions.md b/.github/instructions/numerical-cpp.instructions.md index d1da5a17..9cbefcbf 100644 --- a/.github/instructions/numerical-cpp.instructions.md +++ b/.github/instructions/numerical-cpp.instructions.md @@ -74,6 +74,6 @@ Apply `OPTIMIZE_FOR_SPEED` (from `numerical/math/CompilerOptimizations.hpp`) on ## Documentation — MANDATORY -For every algorithm added or modified, update the corresponding `doc/{domain}/{AlgorithmName}.md` file. Include mathematical background, implementation details, usage examples, and numerical properties. +For every algorithm added or modified, update the corresponding `doc/{domain}/{AlgorithmName}.md` file. Follow `doc/TEMPLATE.md` exactly. Documentation is **design-first**: cover mathematical background, algorithm behaviour, complexity, pitfalls, and connections. Do **not** include implementation details, class names, template parameters, or usage code examples — docs describe the algorithm design; code follows from it. Full details: [copilot-instructions.md](../../.github/copilot-instructions.md) diff --git a/.vscode/launch.json b/.vscode/launch.json index d985297b..1bf9936c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -221,6 +221,26 @@ } ] }, + { + "name": "Bayesian MPC Calibration Simulator", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/build/host/simulator/controllers/BayesianMpcCalibration/Debug/numerical.simulator.controllers.bayesian_mpc_calibration", + "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/optimization/BayesianOptimization.md b/doc/optimization/BayesianOptimization.md new file mode 100644 index 00000000..36a24fdc --- /dev/null +++ b/doc/optimization/BayesianOptimization.md @@ -0,0 +1,147 @@ +# Bayesian Optimization + +## Overview & Motivation + +Bayesian Optimization (BO) is a gradient-free, sample-efficient strategy for optimizing +black-box functions that are expensive to evaluate. Unlike gradient-based methods (gradient +descent, Adam), BO does not require access to derivatives. It is ideal for calibrating +numerical controllers, tuning hyperparameters, or any optimization task where each function +evaluation is costly — for example, running a full closed-loop simulation. + +BO maintains a probabilistic surrogate model (typically a Gaussian Process) of the objective +function. At each iteration, it uses an acquisition function to select the next query point +that balances exploration (uncertain regions) with exploitation (promising regions). After +evaluating the true objective at that point, the surrogate is updated and the process repeats. + +## Mathematical Theory + +### Gaussian Process Surrogate + +A Gaussian Process (GP) defines a distribution over functions: + +$$f \sim \mathcal{GP}(m(\mathbf{x}), k(\mathbf{x}, \mathbf{x}'))$$ + +With zero mean $m = 0$ and squared-exponential (RBF) kernel: + +$$k(\mathbf{x}, \mathbf{x}') = \sigma_f^2 \exp\!\left(-\frac{\|\mathbf{x} - \mathbf{x}'\|^2}{2\ell^2}\right)$$ + +where $\ell$ is the length-scale and $\sigma_f^2$ is the signal variance. + +Given $n$ observations $\{(\mathbf{x}_i, y_i)\}$, the GP posterior at a new point $\mathbf{x}_*$ is Gaussian: + +$$p(f_* | \mathbf{X}, \mathbf{y}, \mathbf{x}_*) = \mathcal{N}(\mu_*, \sigma_*^2)$$ + +$$\mu_* = \mathbf{k}_*^T (\mathbf{K} + \sigma_n^2 \mathbf{I})^{-1} \mathbf{y}$$ + +$$\sigma_*^2 = k_{**} - \mathbf{k}_*^T (\mathbf{K} + \sigma_n^2 \mathbf{I})^{-1} \mathbf{k}_*$$ + +where: +- $\mathbf{K}_{ij} = k(\mathbf{x}_i, \mathbf{x}_j)$ is the $n \times n$ kernel matrix +- $\mathbf{k}_{*,i} = k(\mathbf{x}_*, \mathbf{x}_i)$ is the cross-kernel vector +- $\sigma_n^2$ is the observation noise variance + +### Expected Improvement Acquisition Function + +For minimization, the Expected Improvement (EI) at $\mathbf{x}$ given best observed value $f^* = \min_i y_i$ is: + +$$\text{EI}(\mathbf{x}) = \mathbb{E}[\max(f^* - f(\mathbf{x}), 0)]$$ + +For a GP surrogate this evaluates analytically: + +$$\text{EI}(\mathbf{x}) = (f^* - \mu_*)\,\Phi(z) + \sigma_*\,\phi(z), \quad z = \frac{f^* - \mu_*}{\sigma_*}$$ + +where $\Phi$ is the standard normal CDF and $\phi$ is the PDF. + +### Fixed-Size GP Implementation + +To avoid dynamic memory allocation, the kernel matrix is pre-allocated at compile-time with +maximum capacity $M$. When only $n < M$ observations are present, the +inactive rows and columns are padded with an identity block, preserving positive-definiteness +and allowing Gaussian elimination with the full $M \times M$ system. The resulting alpha vector +$\boldsymbol{\alpha} = (\mathbf{K} + \sigma_n^2 \mathbf{I})^{-1} \mathbf{y}$ has zeros in the +inactive entries. + +## Complexity Analysis + +| Case | Time per iteration | Space | Notes | +|---------|----------------------|---------------|--------------------------------| +| Best | $O(M^3)$ | $O(M^2 + NP)$ | Dominated by GP solve | +| Average | $O(M^3 + C \cdot P)$ | $O(M^2 + NP)$ | $C$ candidates, $P$ parameters | +| Worst | $O(M^3 + C \cdot P)$ | $O(M^2 + NP)$ | Same as average | + +Where $M$ = maximum observations, $C$ = candidate count, $P$ = parameter count, $N$ = current number of observations. + +All memory is pre-allocated at compile-time on the stack — no dynamic allocation required. + +## Step-by-Step Walkthrough + +**Example**: minimize $f(x) = (x - 0.5)^2$ on $x \in [0, 1]$. + +1. **Initialization**: draw 2 random points, e.g. $x_1 = 0.12$, $x_2 = 0.87$. +2. **Evaluate**: $y_1 = 0.1444$, $y_2 = 0.1369$. Best so far $f^* = 0.1369$. +3. **Build GP**: compute $2 \times 2$ kernel matrix $\mathbf{K}$ with hyperparameters + $\ell=1$, $\sigma_f=1$, $\sigma_n=0.01$. +4. **Solve**: $\boldsymbol{\alpha} = (\mathbf{K} + \sigma_n^2 \mathbf{I})^{-1} \mathbf{y}$. +5. **Maximize EI**: sample 100 candidates uniformly, compute $\text{EI}(x_k)$ for each, + select $x_3 = \arg\max \text{EI}$. +6. **Evaluate**: $y_3 = f(x_3)$. Update GP. Repeat. +7. **Convergence** (after 20 iterations): best point converges near $x = 0.5$. + +## Pitfalls & Edge Cases + +- **GP kernel matrix conditioning**: If two observations are nearly identical, $\mathbf{K} + \sigma_n^2 \mathbf{I}$ + can be ill-conditioned. The noise variance $\sigma_n^2$ acts as a regularizer; set it $\geq 10^{-3}$ for stability. +- **Exploration vs exploitation**: A small candidate sample count (below ~30) may miss the EI maximum in high dimensions. + Increase the candidate count for $P > 3$ parameters. +- **Bounds scaling**: EI maximization by uniform sampling from $[-1, 1]^P$ assumes a normalized search space. + Provide appropriate bounds and the optimizer will rescale internally. +- **Fixed capacity**: The maximum observation budget is a compile-time parameter. Set it large enough for the intended + number of BO iterations. Exceeding the capacity at runtime triggers a precondition failure. + +## Variants & Generalizations + +- **Upper Confidence Bound (UCB)**: alternative to EI: $\text{UCB}(\mathbf{x}) = \mu_* - \kappa \sigma_*$. + More explicit trade-off via $\kappa$. +- **GP hyperparameter optimization**: Maximize the log marginal likelihood over $\ell$, $\sigma_f$, $\sigma_n$ + to adapt the surrogate to the observed data automatically. +- **Gradient-enhanced BO**: When gradients are available, use GP regression on $(f, \nabla f)$ jointly + for faster convergence. +- **Batch BO**: Select $q > 1$ candidates per iteration (parallel evaluations) using the $q$-EI criterion. + +## Applications + +- Controller weight tuning (e.g., MPC state/control cost weights Q, R) +- Hyperparameter optimisation for machine learning models +- Experiment design in system identification +- Any engineering optimisation where each evaluation is costly (simulation, hardware in the loop) + +## Connections to Other Algorithms + +- **Gaussian Process (GP)**: The surrogate model is a GP; the Kalman filter is formally equivalent to + GP regression with a Markovian kernel. +- **Gaussian Elimination / Cholesky**: Used to solve the GP kernel system $(\mathbf{K} + \sigma_n^2 \mathbf{I})\boldsymbol{\alpha} = \mathbf{y}$. +- **Gradient Descent**: BO is the gradient-free counterpart — preferred when the objective is non-differentiable + or noisy. +- **Expectation-Maximisation (EM)**: Both maintain a probabilistic model refined by data; EM operates on + latent-variable likelihood while BO operates on a surrogate of an arbitrary black-box. + +## Numerical Properties + +- **Real-time suitability**: No — the $O(M^3)$ GP linear solve at each iteration precludes hard real-time use. + Suitable for offline calibration or non-real-time configuration stages. +- **Precision**: Floating-point arithmetic only. Gaussian process kernels require transcendental + functions — exponential, complementary error function, square root — that are incompatible with + fixed-point representations. The kernel matrix inversion loses precision for very flat kernels + ($\ell \gg$ domain width). Length-scale should remain in the range $[0.1, 10]$ relative to the + normalised parameter domain. +- **Noise regularisation**: The diagonal noise term $\sigma_n^2 \mathbf{I}$ must be positive to keep the + kernel matrix positive-definite; values below $10^{-3}$ risk ill-conditioning. +- **Memory**: All storage is pre-allocated at compile-time — the maximum observation budget and the + candidate count are both compile-time parameters. No dynamic allocation is required. + +## References & Further Reading + +- Brochu, Cora, de Freitas, "A Tutorial on Bayesian Optimization of Expensive Cost Functions", 2010 +- Rasmussen & Williams, *Gaussian Processes for Machine Learning*, MIT Press, 2006 — Chapter 2 (GP regression), Chapter 5 (model selection) +- Snoek, Larochelle, Adams, "Practical Bayesian Optimization of Machine Learning Algorithms", NeurIPS 2012 + diff --git a/doc/optimization/README.md b/doc/optimization/README.md index 47d18349..a0872f03 100644 --- a/doc/optimization/README.md +++ b/doc/optimization/README.md @@ -4,6 +4,7 @@ General-purpose optimization algorithms for parameter fitting, training, and con ## Algorithms -| Algorithm | Description | -|----------------------------------|----------------------------------------------------------------| -| [Gradient Descent](Optimizer.md) | Iterative batch optimization via gradient-based weight updates | +| Algorithm | Description | +|--------------------------------------------------|---------------------------------------------------------------------------------------------| +| [Bayesian Optimization](BayesianOptimization.md) | Gradient-free global optimization using Gaussian Process surrogate and Expected Improvement | +| [Gradient Descent](Optimizer.md) | Iterative batch optimization via gradient-based weight updates | diff --git a/numerical/estimators/offline/ExpectationMaximization.hpp b/numerical/estimators/offline/ExpectationMaximization.hpp index e8c1452a..22bc237a 100644 --- a/numerical/estimators/offline/ExpectationMaximization.hpp +++ b/numerical/estimators/offline/ExpectationMaximization.hpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace estimators { @@ -66,8 +67,20 @@ namespace estimators const std::array& observations, std::size_t numSteps); - static StateMatrix SymmetrizeState(const StateMatrix& M); - static MeasurementCovariance SymmetrizeMeasurement(const MeasurementCovariance& M); + OPTIMIZE_FOR_SPEED std::pair ComputeTransitionUpdate( + const StateMatrix& transitionCrossCov, + const StateMatrix& laggedStateCov, + const StateMatrix& currentStateCov, + std::size_t numSteps) const; + + OPTIMIZE_FOR_SPEED std::pair ComputeObservationUpdate( + const math::Matrix& obsStateCrossCov, + const StateMatrix& fullStateCov, + const MeasurementCovariance& obsOuterSum, + std::size_t numSteps) const; + + template + static math::SquareMatrix Symmetrize(const math::SquareMatrix& M); }; // Implementation // @@ -123,12 +136,12 @@ namespace estimators const std::array& observations, std::size_t numSteps) { - StateMatrix A{}; - StateMatrix B{}; - StateMatrix C{}; - StateMatrix D{}; - math::Matrix W{}; - MeasurementCovariance sumZZT{}; + StateMatrix transitionCrossCov{}; + StateMatrix laggedStateCov{}; + StateMatrix currentStateCov{}; + StateMatrix fullStateCov{}; + math::Matrix obsStateCrossCov{}; + MeasurementCovariance obsOuterSum{}; for (std::size_t t = 0; t < numSteps; ++t) { @@ -137,42 +150,22 @@ namespace estimators const auto xxT = xS * xS.Transpose(); const auto PxxT = PS + xxT; - // S2 / B: t = 0 .. T-2 if (t < numSteps - 1) - B += PxxT; + laggedStateCov += PxxT; - // S3_F / C and S1 / A: t = 1 .. T-1 if (t >= 1) { - C += PxxT; - A += smootherOutput.lagCrossCovariances[t] + xS * smootherOutput.smoothedMeans[t - 1].Transpose(); + currentStateCov += PxxT; + transitionCrossCov += smootherOutput.lagCrossCovariances[t] + xS * smootherOutput.smoothedMeans[t - 1].Transpose(); } - // S3_H / D, W, sumZZT: t = 0 .. T-1 - D += PxxT; - W += observations[t] * xS.Transpose(); - sumZZT += observations[t] * observations[t].Transpose(); + fullStateCov += PxxT; + obsStateCrossCov += observations[t] * xS.Transpose(); + obsOuterSum += observations[t] * observations[t].Transpose(); } - // F_new = A * B^{-1} → SolveSystem(B, A^T)^T - const auto F_new = solvers::SolveSystem( - B, A.Transpose()) - .Transpose(); - - // Q_new = (C - F_new * A^T) / (T-1), symmetrized + PD-regularized - const float invTm1 = 1.0f / static_cast(numSteps - 1); - auto Q_new = SymmetrizeState((C - F_new * A.Transpose()) * invTm1); - Q_new += StateMatrix::Identity() * 1e-6f; - - // H_new = W * D^{-1} → SolveSystem(D, W^T)^T - const auto H_new = solvers::SolveSystem( - D, W.Transpose()) - .Transpose(); - - // R_new = (sumZZT - H_new * W^T) / T, symmetrized + PD-regularized - const float invT = 1.0f / static_cast(numSteps); - auto R_new = SymmetrizeMeasurement((sumZZT - H_new * W.Transpose()) * invT); - R_new += MeasurementCovariance::Identity() * 1e-6f; + const auto [F_new, Q_new] = ComputeTransitionUpdate(transitionCrossCov, laggedStateCov, currentStateCov, numSteps); + const auto [H_new, R_new] = ComputeObservationUpdate(obsStateCrossCov, fullStateCov, obsOuterSum, numSteps); return EmParameters{ F_new, @@ -185,15 +178,47 @@ namespace estimators } template - typename ExpectationMaximization::StateMatrix - ExpectationMaximization::SymmetrizeState(const StateMatrix& M) + OPTIMIZE_FOR_SPEED + std::pair::StateMatrix, + typename ExpectationMaximization::StateMatrix> + ExpectationMaximization::ComputeTransitionUpdate( + const StateMatrix& transitionCrossCov, + const StateMatrix& laggedStateCov, + const StateMatrix& currentStateCov, + std::size_t numSteps) const + { + const auto F_new = solvers::SolveSystem( + laggedStateCov, transitionCrossCov.Transpose()) + .Transpose(); + const float invTm1 = 1.0f / static_cast(numSteps - 1); + auto Q_new = Symmetrize((currentStateCov - F_new * transitionCrossCov.Transpose()) * invTm1); + Q_new += StateMatrix::Identity() * 1e-6f; + return { F_new, Q_new }; + } + + template + OPTIMIZE_FOR_SPEED + std::pair::MeasurementMatrix, + typename ExpectationMaximization::MeasurementCovariance> + ExpectationMaximization::ComputeObservationUpdate( + const math::Matrix& obsStateCrossCov, + const StateMatrix& fullStateCov, + const MeasurementCovariance& obsOuterSum, + std::size_t numSteps) const { - return (M + M.Transpose()) * 0.5f; + const auto H_new = solvers::SolveSystem( + fullStateCov, obsStateCrossCov.Transpose()) + .Transpose(); + const float invT = 1.0f / static_cast(numSteps); + auto R_new = Symmetrize((obsOuterSum - H_new * obsStateCrossCov.Transpose()) * invT); + R_new += MeasurementCovariance::Identity() * 1e-6f; + return { H_new, R_new }; } template - typename ExpectationMaximization::MeasurementCovariance - ExpectationMaximization::SymmetrizeMeasurement(const MeasurementCovariance& M) + template + math::SquareMatrix + ExpectationMaximization::Symmetrize(const math::SquareMatrix& M) { return (M + M.Transpose()) * 0.5f; } diff --git a/numerical/filters/active/KalmanSmoother.hpp b/numerical/filters/active/KalmanSmoother.hpp index fb72c1fc..16ab2123 100644 --- a/numerical/filters/active/KalmanSmoother.hpp +++ b/numerical/filters/active/KalmanSmoother.hpp @@ -73,6 +73,15 @@ namespace filters const MeasurementMatrix& H, std::size_t numSteps, SmootherOutput& output); + + [[nodiscard]] OPTIMIZE_FOR_SPEED float ComputeLogLikelihoodContribution( + const MeasurementVector& innovation, + const MeasurementCovariance& innovationCovariance) const; + + [[nodiscard]] OPTIMIZE_FOR_SPEED StateMatrix ComputeSmootherGain( + const StateMatrix& filteredCovariance, + const StateMatrix& stateTransition, + const StateMatrix& predictedCovariance) const; }; // Implementation // @@ -114,7 +123,6 @@ namespace filters predictedCovariances_[0] = initialCovariance; float logLikelihood = 0.0f; - const float logTwoPi = std::log(2.0f * std::numbers::pi_v); for (std::size_t t = 0; t < numSteps; ++t) { @@ -135,18 +143,7 @@ namespace filters kalmanGains_[t] = K; - // Log-likelihood contribution: -0.5 * (log det S + nu^T S^{-1} nu + M*log(2pi)) - const auto L = solvers::CholeskyDecomposition(S); - const auto S_inv_nu = solvers::SolveSystem(S, nu); - float logDetS = 0.0f; - float quadForm = 0.0f; - for (std::size_t i = 0; i < MeasurementSize; ++i) - { - logDetS += std::log(L.at(i, i)); - quadForm += nu.at(i, 0) * S_inv_nu.at(i, 0); - } - logDetS *= 2.0f; - logLikelihood += -0.5f * (logDetS + quadForm + static_cast(MeasurementSize) * logTwoPi); + logLikelihood += ComputeLogLikelihoodContribution(nu, S); if (t < numSteps - 1) { @@ -174,11 +171,7 @@ namespace filters for (std::size_t t = numSteps - 2;; --t) { // RTS smoother gain: G_t = P_{t|t} F^T (P_{t+1|t})^{-1} - // Solve P_{t+1|t} * G_t^T = F * P_{t|t} then transpose - const auto G_t = solvers::SolveSystem( - predictedCovariances_[t + 1], - F * filteredCovariances_[t]) - .Transpose(); + const auto G_t = ComputeSmootherGain(filteredCovariances_[t], F, predictedCovariances_[t + 1]); const auto deltaP = output.smoothedCovariances[t + 1] - predictedCovariances_[t + 1]; output.smoothedMeans[t] = filteredMeans_[t] + G_t * (output.smoothedMeans[t + 1] - predictedMeans_[t + 1]); @@ -207,6 +200,39 @@ namespace filters } } + template + OPTIMIZE_FOR_SPEED float + KalmanSmoother::ComputeLogLikelihoodContribution( + const MeasurementVector& innovation, + const MeasurementCovariance& innovationCovariance) const + { + static const float log2pi = std::log(2.0f * std::numbers::pi_v); + const auto L = solvers::CholeskyDecomposition(innovationCovariance); + const auto sInvNu = solvers::SolveSystem(innovationCovariance, innovation); + float logDetS = 0.0f; + float quadForm = 0.0f; + for (std::size_t i = 0; i < MeasurementSize; ++i) + { + logDetS += std::log(L.at(i, i)); + quadForm += innovation.at(i, 0) * sInvNu.at(i, 0); + } + logDetS *= 2.0f; + return -0.5f * (logDetS + quadForm + static_cast(MeasurementSize) * log2pi); + } + + template + OPTIMIZE_FOR_SPEED + typename KalmanSmoother::StateMatrix + KalmanSmoother::ComputeSmootherGain( + const StateMatrix& filteredCovariance, + const StateMatrix& stateTransition, + const StateMatrix& predictedCovariance) const + { + return solvers::SolveSystem( + predictedCovariance, stateTransition * filteredCovariance) + .Transpose(); + } + #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD extern template class KalmanSmoother<2, 1, 10>; extern template class KalmanSmoother<4, 2, 20>; diff --git a/numerical/optimization/BayesianOptimization.cpp b/numerical/optimization/BayesianOptimization.cpp new file mode 100644 index 00000000..ee9ccf3c --- /dev/null +++ b/numerical/optimization/BayesianOptimization.cpp @@ -0,0 +1,7 @@ +#include "numerical/optimization/BayesianOptimization.hpp" + +namespace optimization +{ + template class BayesianOptimization<1, 10, 50>; + template class BayesianOptimization<2, 30, 200>; +} diff --git a/numerical/optimization/BayesianOptimization.hpp b/numerical/optimization/BayesianOptimization.hpp new file mode 100644 index 00000000..38dc2af7 --- /dev/null +++ b/numerical/optimization/BayesianOptimization.hpp @@ -0,0 +1,300 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include "numerical/optimization/BlackBoxObjective.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include +#include +#include +#include +#include + +namespace optimization +{ + struct GpHyperparameters + { + float lengthScale = 1.0f; + float signalVariance = 1.0f; + float noiseVariance = 1e-2f; + }; + + template + class BayesianOptimization + { + static_assert(NumParams > 0, "NumParams must be positive"); + static_assert(MaxObservations >= 2, "MaxObservations must be at least 2"); + static_assert(NumCandidates > 0, "NumCandidates must be positive"); + + public: + using ParameterVector = math::Vector; + using BoundsArray = std::array, NumParams>; + + struct Result + { + ParameterVector bestPoint; + float bestValue; + std::size_t evaluations; + }; + + BayesianOptimization(const BoundsArray& bounds, + const GpHyperparameters& hyperparameters, + uint64_t seed = 42ULL); + + void AddObservation(const ParameterVector& point, float value); + + [[nodiscard]] std::pair GpPredict(const ParameterVector& query) const; + + [[nodiscard]] float ExpectedImprovement(const ParameterVector& query, float bestValue) const; + + OPTIMIZE_FOR_SPEED ParameterVector MaximizeAcquisition(float bestValue); + + OPTIMIZE_FOR_SPEED Result Optimize(BlackBoxObjective& objective, + std::size_t numIterations); + + [[nodiscard]] const std::array& GetObservedValues() const; + [[nodiscard]] std::size_t GetNumObservations() const; + + private: + [[nodiscard]] static float SquaredExpKernel(const ParameterVector& a, + const ParameterVector& b, + const GpHyperparameters& hp); + + void RebuildKernelMatrix(); + + OPTIMIZE_FOR_SPEED ParameterVector LcgSample(); + + [[nodiscard]] static float NormalCdf(float z); + [[nodiscard]] static float NormalPdf(float z); + + BoundsArray bounds_; + GpHyperparameters hyperparameters_; + uint64_t lcgState_; + std::size_t numObservations_{ 0 }; + + std::array observedPoints_{}; + std::array observedValues_{}; + math::SquareMatrix kernelMatrix_{}; + math::Vector alpha_{}; + }; + + // Implementation // + + template + BayesianOptimization::BayesianOptimization( + const BoundsArray& bounds, + const GpHyperparameters& hyperparameters, + uint64_t seed) + : bounds_(bounds) + , hyperparameters_(hyperparameters) + , lcgState_(seed) + { + for (std::size_t d = 0; d < NumParams; ++d) + really_assert(bounds_[d].first < bounds_[d].second); + + kernelMatrix_ = math::SquareMatrix::Identity(); + } + + template + void BayesianOptimization::AddObservation( + const ParameterVector& point, float value) + { + really_assert(numObservations_ < MaxObservations); + observedPoints_[numObservations_] = point; + observedValues_[numObservations_] = value; + ++numObservations_; + RebuildKernelMatrix(); + } + + template + void BayesianOptimization::RebuildKernelMatrix() + { + for (std::size_t i = 0; i < MaxObservations; ++i) + { + for (std::size_t j = 0; j < MaxObservations; ++j) + { + if (i < numObservations_ && j < numObservations_) + { + float k = SquaredExpKernel(observedPoints_[i], observedPoints_[j], hyperparameters_); + if (i == j) + k += hyperparameters_.noiseVariance * hyperparameters_.noiseVariance; + kernelMatrix_.at(i, j) = k; + } + else + { + kernelMatrix_.at(i, j) = (i == j) ? 1.0f : 0.0f; + } + } + } + + math::Vector yPadded{}; + for (std::size_t i = 0; i < numObservations_; ++i) + yPadded.at(i, 0) = observedValues_[i]; + + alpha_ = solvers::SolveSystem(kernelMatrix_, yPadded); + } + + template + std::pair + BayesianOptimization::GpPredict( + const ParameterVector& query) const + { + math::Vector kStar{}; + for (std::size_t i = 0; i < numObservations_; ++i) + kStar.at(i, 0) = SquaredExpKernel(query, observedPoints_[i], hyperparameters_); + + float mu = 0.0f; + for (std::size_t i = 0; i < MaxObservations; ++i) + mu += kStar.at(i, 0) * alpha_.at(i, 0); + + const auto v = solvers::SolveSystem(kernelMatrix_, kStar); + + const float kSS = hyperparameters_.signalVariance * hyperparameters_.signalVariance; + float vDotKStar = 0.0f; + for (std::size_t i = 0; i < MaxObservations; ++i) + vDotKStar += v.at(i, 0) * kStar.at(i, 0); + + const float sigma2 = std::max(0.0f, kSS - vDotKStar); + return { mu, std::sqrt(sigma2) }; + } + + template + float BayesianOptimization::ExpectedImprovement( + const ParameterVector& query, float bestValue) const + { + if (numObservations_ == 0) + return 0.0f; + + const auto [mu, sigma] = GpPredict(query); + + if (sigma <= 0.0f) + return 0.0f; + + const float z = (bestValue - mu) / sigma; + return (bestValue - mu) * NormalCdf(z) + sigma * NormalPdf(z); + } + + template + OPTIMIZE_FOR_SPEED + typename BayesianOptimization::ParameterVector + BayesianOptimization::MaximizeAcquisition(float bestValue) + { + ParameterVector bestCandidate = LcgSample(); + float bestEI = ExpectedImprovement(bestCandidate, bestValue); + + for (std::size_t c = 1; c < NumCandidates; ++c) + { + const auto candidate = LcgSample(); + const float ei = ExpectedImprovement(candidate, bestValue); + if (ei > bestEI) + { + bestEI = ei; + bestCandidate = candidate; + } + } + + return bestCandidate; + } + + template + OPTIMIZE_FOR_SPEED + typename BayesianOptimization::Result + BayesianOptimization::Optimize( + BlackBoxObjective& objective, + std::size_t numIterations) + { + really_assert(numIterations > 0 && numObservations_ + numIterations <= MaxObservations); + + const std::size_t explorationCount = std::min(std::size_t{ 5 }, numIterations / 3 + 1); + + for (std::size_t i = 0; i < explorationCount; ++i) + { + const auto point = LcgSample(); + const float val = objective.Evaluate(point); + AddObservation(point, val); + } + + for (std::size_t i = explorationCount; i < numIterations; ++i) + { + float bestValue = observedValues_[0]; + for (std::size_t j = 1; j < numObservations_; ++j) + bestValue = std::min(bestValue, observedValues_[j]); + + const auto next = MaximizeAcquisition(bestValue); + const float val = objective.Evaluate(next); + AddObservation(next, val); + } + + std::size_t bestIdx = 0; + for (std::size_t j = 1; j < numObservations_; ++j) + if (observedValues_[j] < observedValues_[bestIdx]) + bestIdx = j; + + return Result{ observedPoints_[bestIdx], observedValues_[bestIdx], numObservations_ }; + } + + template + const std::array& + BayesianOptimization::GetObservedValues() const + { + return observedValues_; + } + + template + std::size_t BayesianOptimization::GetNumObservations() const + { + return numObservations_; + } + + template + float BayesianOptimization::SquaredExpKernel( + const ParameterVector& a, + const ParameterVector& b, + const GpHyperparameters& hp) + { + float dist2 = 0.0f; + for (std::size_t d = 0; d < NumParams; ++d) + { + const float diff = a.at(d, 0) - b.at(d, 0); + dist2 += diff * diff; + } + return hp.signalVariance * hp.signalVariance * + std::exp(-dist2 / (2.0f * hp.lengthScale * hp.lengthScale)); + } + + template + OPTIMIZE_FOR_SPEED + typename BayesianOptimization::ParameterVector + BayesianOptimization::LcgSample() + { + ParameterVector result{}; + for (std::size_t d = 0; d < NumParams; ++d) + { + lcgState_ = lcgState_ * 6364136223846793005ULL + 1442695040888963407ULL; + const float t = static_cast(lcgState_ >> 11) * (1.0f / static_cast(1ULL << 53)); + result.at(d, 0) = bounds_[d].first + t * (bounds_[d].second - bounds_[d].first); + } + return result; + } + + template + float BayesianOptimization::NormalCdf(float z) + { + return 0.5f * std::erfc(-z * std::numbers::sqrt2_v * 0.5f); + } + + template + float BayesianOptimization::NormalPdf(float z) + { + return std::exp(-0.5f * z * z) / std::sqrt(2.0f * std::numbers::pi_v); + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class BayesianOptimization<1, 10, 50>; + extern template class BayesianOptimization<2, 30, 200>; +#endif +} diff --git a/numerical/optimization/BlackBoxObjective.hpp b/numerical/optimization/BlackBoxObjective.hpp new file mode 100644 index 00000000..1c6e8d20 --- /dev/null +++ b/numerical/optimization/BlackBoxObjective.hpp @@ -0,0 +1,21 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/Matrix.hpp" +#include + +namespace optimization +{ + template + class BlackBoxObjective + { + public: + using ParameterVector = math::Vector; + + virtual ~BlackBoxObjective() = default; + virtual float Evaluate(const ParameterVector& params) = 0; + }; +} diff --git a/numerical/optimization/CMakeLists.txt b/numerical/optimization/CMakeLists.txt index 4a7e1662..0d3bc605 100644 --- a/numerical/optimization/CMakeLists.txt +++ b/numerical/optimization/CMakeLists.txt @@ -9,14 +9,18 @@ target_link_libraries(numerical.optimization ${NUMERICAL_VISIBILITY} infra.util numerical.math numerical.neural_network.losses + numerical.solver ) target_sources(numerical.optimization PRIVATE + BayesianOptimization.hpp + BlackBoxObjective.hpp GradientDescent.hpp Optimizer.hpp ) numerical_add_coverage_sources(numerical.optimization + BayesianOptimization.cpp GradientDescent.cpp ) diff --git a/numerical/optimization/test/CMakeLists.txt b/numerical/optimization/test/CMakeLists.txt index a07d1c19..e29b97d2 100644 --- a/numerical/optimization/test/CMakeLists.txt +++ b/numerical/optimization/test/CMakeLists.txt @@ -8,5 +8,6 @@ target_link_libraries(numerical.optimization_test PUBLIC ) target_sources(numerical.optimization_test PRIVATE + TestBayesianOptimization.cpp TestGradientDescent.cpp ) diff --git a/numerical/optimization/test/TestBayesianOptimization.cpp b/numerical/optimization/test/TestBayesianOptimization.cpp new file mode 100644 index 00000000..db91e877 --- /dev/null +++ b/numerical/optimization/test/TestBayesianOptimization.cpp @@ -0,0 +1,148 @@ +#include "numerical/optimization/BayesianOptimization.hpp" +#include "numerical/optimization/BlackBoxObjective.hpp" +#include +#include + +namespace +{ + class TestBayesianOptimization1D : public ::testing::Test + { + protected: + static constexpr std::size_t NumParams = 1; + static constexpr std::size_t MaxObs = 10; + static constexpr std::size_t NumCandidates = 50; + + using Bo = optimization::BayesianOptimization; + using ParamVec = Bo::ParameterVector; + + optimization::GpHyperparameters hp{ 0.5f, 1.0f, 0.01f }; + Bo::BoundsArray bounds{ std::make_pair(-3.0f, 3.0f) }; + Bo bo{ bounds, hp, 99991ULL }; + }; + + class TestBayesianOptimization2D : public ::testing::Test + { + protected: + static constexpr std::size_t NumParams = 2; + static constexpr std::size_t MaxObs = 20; + static constexpr std::size_t NumCandidates = 100; + + using Bo = optimization::BayesianOptimization; + using ParamVec = Bo::ParameterVector; + + optimization::GpHyperparameters hp{ 0.8f, 1.0f, 0.01f }; + Bo::BoundsArray bounds{ + std::make_pair(-2.0f, 2.0f), + std::make_pair(-2.0f, 2.0f) + }; + Bo bo{ bounds, hp, 12345ULL }; + }; + + class QuadraticObjective : public optimization::BlackBoxObjective<1> + { + public: + float Evaluate(const math::Vector& params) override + { + const float x = params.at(0, 0); + return x * x; + } + }; + + class BowlObjective : public optimization::BlackBoxObjective<2> + { + public: + float Evaluate(const math::Vector& params) override + { + const float dx = params.at(0, 0) - 0.4f; + const float dy = params.at(1, 0) + 0.3f; + return dx * dx + dy * dy; + } + }; +} + +TEST_F(TestBayesianOptimization1D, gp_predict_returns_finite_mean_and_nonneg_std_after_observations) +{ + bo.AddObservation(ParamVec{ { -1.0f } }, 1.0f); + bo.AddObservation(ParamVec{ { 0.0f } }, 0.0f); + bo.AddObservation(ParamVec{ { 1.0f } }, 1.0f); + + const auto [mu, sigma] = bo.GpPredict(ParamVec{ { 0.5f } }); + + EXPECT_TRUE(std::isfinite(mu)); + EXPECT_GE(sigma, 0.0f); +} + +TEST_F(TestBayesianOptimization1D, expected_improvement_is_nonnegative) +{ + bo.AddObservation(ParamVec{ { -1.0f } }, 1.0f); + bo.AddObservation(ParamVec{ { 0.0f } }, 0.0f); + + const float bestValue = 0.0f; + const float ei = bo.ExpectedImprovement(ParamVec{ { 2.0f } }, bestValue); + + EXPECT_GE(ei, 0.0f); +} + +TEST_F(TestBayesianOptimization1D, expected_improvement_is_zero_before_observations) +{ + const float ei = bo.ExpectedImprovement(ParamVec{ { 0.5f } }, 0.0f); + + EXPECT_FLOAT_EQ(ei, 0.0f); +} + +TEST_F(TestBayesianOptimization1D, gp_mean_approximates_observed_value_at_observed_point) +{ + bo.AddObservation(ParamVec{ { 1.0f } }, 1.0f); + bo.AddObservation(ParamVec{ { -1.0f } }, 1.0f); + bo.AddObservation(ParamVec{ { 0.5f } }, 0.25f); + + const auto [mu, sigma] = bo.GpPredict(ParamVec{ { 1.0f } }); + + EXPECT_NEAR(mu, 1.0f, 0.2f); +} + +TEST_F(TestBayesianOptimization1D, optimize_1d_quadratic_finds_point_near_zero) +{ + QuadraticObjective objective; + + const auto result = bo.Optimize(objective, 8); + + EXPECT_LT(std::abs(result.bestPoint.at(0, 0)), 0.5f); +} + +TEST_F(TestBayesianOptimization1D, maximize_acquisition_returns_point_within_bounds) +{ + bo.AddObservation(ParamVec{ { 0.0f } }, 0.1f); + bo.AddObservation(ParamVec{ { 1.0f } }, 1.0f); + + const auto candidate = bo.MaximizeAcquisition(0.1f); + + EXPECT_GE(candidate.at(0, 0), -3.0f); + EXPECT_LE(candidate.at(0, 0), 3.0f); +} + +TEST_F(TestBayesianOptimization2D, optimize_2d_bowl_finds_point_near_known_min) +{ + BowlObjective objective; + + const auto result = bo.Optimize(objective, 18); + + const float dx = result.bestPoint.at(0, 0) - 0.4f; + const float dy = result.bestPoint.at(1, 0) + 0.3f; + EXPECT_LT(std::sqrt(dx * dx + dy * dy), 0.6f); +} + +TEST_F(TestBayesianOptimization2D, all_sampled_candidates_stay_within_bounds) +{ + bo.AddObservation(ParamVec{ { 0.0f }, { 0.0f } }, 0.25f); + bo.AddObservation(ParamVec{ { 1.0f }, { -1.0f } }, 2.1f); + + for (std::size_t i = 0; i < 5; ++i) + { + const auto candidate = bo.MaximizeAcquisition(0.25f); + EXPECT_GE(candidate.at(0, 0), -2.0f); + EXPECT_LE(candidate.at(0, 0), 2.0f); + EXPECT_GE(candidate.at(1, 0), -2.0f); + EXPECT_LE(candidate.at(1, 0), 2.0f); + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/CMakeLists.txt b/simulator/controllers/BayesianMpcCalibration/CMakeLists.txt new file mode 100644 index 00000000..3a3c9178 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/CMakeLists.txt @@ -0,0 +1,24 @@ +find_package(Qt6 REQUIRED COMPONENTS Widgets) + +add_subdirectory(application) +add_subdirectory(view) + +add_executable(numerical.simulator.controllers.bayesian_mpc_calibration) +emil_build_for(numerical.simulator.controllers.bayesian_mpc_calibration HOST All PREREQUISITE_BOOL NUMERICAL_TOOLBOX_BUILD_SIMULATOR) + +target_link_libraries(numerical.simulator.controllers.bayesian_mpc_calibration PRIVATE + numerical.simulator.controllers.bayesian_mpc_calibration.application + numerical.simulator.controllers.bayesian_mpc_calibration.view +) + +target_sources(numerical.simulator.controllers.bayesian_mpc_calibration PRIVATE + Main.cpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/BayesianMpcCalibration/Main.cpp b/simulator/controllers/BayesianMpcCalibration/Main.cpp new file mode 100644 index 00000000..cb78c2e1 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/Main.cpp @@ -0,0 +1,12 @@ +#include "simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.hpp" +#include + +int main(int argc, char* argv[]) +{ + QApplication app(argc, argv); + + simulator::controllers::view::BayesianMpcCalibrationView window; + window.show(); + + return app.exec(); +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.cpp b/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.cpp new file mode 100644 index 00000000..2ff2b3c3 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.cpp @@ -0,0 +1,110 @@ +#include "simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.hpp" +#include "numerical/controllers/implementations/Mpc.hpp" +#include + +namespace simulator::controllers +{ + CalibrationSimulationResults BayesianMpcCalibrationSimulator::Run( + const CalibrationSimulationConfig& config) + { + CalibrationSimulationResults results{}; + + DoubleIntegratorPlant plant(config.plant); + const auto A_true = plant.GetA(); + const auto B_true = plant.GetB(); + + std::array observations{}; + plant.GenerateObservations( + config.numTrainingSteps, config.plantSeed, + observations, results.truePositions); + + const std::size_t effectiveSteps = std::min(config.numTrainingSteps, MaxSteps); + results.timeAxis.reserve(effectiveSteps); + results.rawMeasurements.reserve(effectiveSteps); + for (std::size_t t = 0; t < effectiveSteps; ++t) + { + results.timeAxis.push_back(static_cast(t) * config.plant.dt); + results.rawMeasurements.push_back(observations[t].at(0, 0)); + } + + const auto initialGuess = BuildInitialEmGuess(config.plant); + + EmKfPipeline emPipeline; + const auto emKfResult = emPipeline.Run( + observations, effectiveSteps, initialGuess, config.emKf); + + results.emLogLikelihoodHistory = emKfResult.logLikelihoodHistory; + results.emConverged = emKfResult.emResult.converged; + results.emIterations = emKfResult.emResult.iterations; + + const auto F_est = emKfResult.emResult.parameters.F; + + MpcBoCalibrator boCalibrator; + const auto boResult = boCalibrator.Calibrate(F_est, B_true, A_true, config.mpcBo); + + results.boIseHistory = boResult.iseHistory; + results.optimalQ = boResult.optimalQ; + results.optimalR = boResult.optimalR; + results.finalIse = boResult.finalIse; + + RunFinalStepResponse(A_true, B_true, F_est, + boResult.optimalQ, boResult.optimalR, config.plant.dt, results); + + return results; + } + + EmKfPipeline::EmParameters BayesianMpcCalibrationSimulator::BuildInitialEmGuess( + const DoubleIntegratorConfig& plantConfig) const + { + using StateMatrix = math::SquareMatrix; + using MeasurementMatrix = math::Matrix; + using StateVector = math::Vector; + using MeasCovariance = math::SquareMatrix; + + EmKfPipeline::EmParameters guess{}; + guess.F = StateMatrix::Identity(); + guess.H = MeasurementMatrix{ { 1.0f, 0.0f } }; + guess.Q = StateMatrix::Identity() * (plantConfig.sigmaQ * plantConfig.sigmaQ); + guess.R = MeasCovariance{ { plantConfig.sigmaR * plantConfig.sigmaR } }; + guess.initialState = StateVector{}; + guess.initialCovariance = StateMatrix::Identity(); + return guess; + } + + void BayesianMpcCalibrationSimulator::RunFinalStepResponse( + const math::SquareMatrix& A_true, + const math::Matrix& B_true, + const math::SquareMatrix& F_est, + float optimalQ, + float optimalR, + float dt, + CalibrationSimulationResults& results) const + { + using WeightsType = ::controllers::MpcWeights; + WeightsType weights; + weights.Q = math::SquareMatrix::Identity() * optimalQ; + weights.R = math::SquareMatrix{ { optimalR } }; + + ::controllers::Mpc mpc(F_est, B_true, weights); + const math::Vector ref{ { 1.0f }, { 0.0f } }; + mpc.SetReference(ref); + + math::Vector state{}; + results.stepResponseTime.reserve(StepResponseSteps); + results.stepResponsePosition.reserve(StepResponseSteps); + results.stepResponseVelocity.reserve(StepResponseSteps); + results.stepResponseControl.reserve(StepResponseSteps); + + for (std::size_t k = 0; k < StepResponseSteps; ++k) + { + results.stepResponseTime.push_back(static_cast(k) * dt); + results.stepResponsePosition.push_back(state.at(0, 0)); + results.stepResponseVelocity.push_back(state.at(1, 0)); + + const auto u = mpc.ComputeControl(state); + results.stepResponseControl.push_back(u.at(0, 0)); + + state = A_true * state + B_true * u; + } + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.hpp b/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.hpp new file mode 100644 index 00000000..dd2af461 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.hpp" +#include "simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.hpp" +#include "simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.hpp" +#include + +namespace simulator::controllers +{ + struct CalibrationSimulationConfig + { + DoubleIntegratorConfig plant; + EmKfConfig emKf; + MpcBoCalibratorConfig mpcBo; + std::size_t numTrainingSteps = 150; + uint32_t plantSeed = 42U; + }; + + struct CalibrationSimulationResults + { + std::vector timeAxis; + std::vector rawMeasurements; + std::vector truePositions; + + std::vector emLogLikelihoodHistory; + bool emConverged = false; + std::size_t emIterations = 0; + + std::vector boIseHistory; + float optimalQ = 1.0f; + float optimalR = 1.0f; + float finalIse = 0.0f; + + std::vector stepResponseTime; + std::vector stepResponsePosition; + std::vector stepResponseVelocity; + std::vector stepResponseControl; + }; + + class BayesianMpcCalibrationSimulator + { + public: + CalibrationSimulationResults Run(const CalibrationSimulationConfig& config); + + private: + static constexpr std::size_t MaxSteps = DoubleIntegratorPlant::MaxSteps; + static constexpr std::size_t StepResponseSteps = 100; + + using MeasurementVector = math::Vector; + + EmKfPipeline::EmParameters BuildInitialEmGuess(const DoubleIntegratorConfig& plantConfig) const; + + void RunFinalStepResponse( + const math::SquareMatrix& A_true, + const math::Matrix& B_true, + const math::SquareMatrix& F_est, + float optimalQ, + float optimalR, + float dt, + CalibrationSimulationResults& results) const; + }; +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/CMakeLists.txt b/simulator/controllers/BayesianMpcCalibration/application/CMakeLists.txt new file mode 100644 index 00000000..151afd30 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/CMakeLists.txt @@ -0,0 +1,33 @@ +add_library(numerical.simulator.controllers.bayesian_mpc_calibration.application STATIC) + +target_include_directories(numerical.simulator.controllers.bayesian_mpc_calibration.application PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.bayesian_mpc_calibration.application PUBLIC + numerical.controllers.implementations + numerical.estimators.offline + numerical.filters.active + numerical.optimization + numerical.solver +) + +target_sources(numerical.simulator.controllers.bayesian_mpc_calibration.application PRIVATE + BayesianMpcCalibrationSimulator.cpp + BayesianMpcCalibrationSimulator.hpp + DoubleIntegratorPlant.cpp + DoubleIntegratorPlant.hpp + EmKfPipeline.cpp + EmKfPipeline.hpp + MpcBoCalibrator.cpp + MpcBoCalibrator.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration.application PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration.application PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.cpp b/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.cpp new file mode 100644 index 00000000..260c03c3 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.cpp @@ -0,0 +1,48 @@ +#include "simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.hpp" +#include + +namespace simulator::controllers +{ + DoubleIntegratorPlant::DoubleIntegratorPlant(const DoubleIntegratorConfig& config) + : config_(config) + { + const float dt = config.dt; + A_ = math::SquareMatrix{ { 1.0f, dt }, { 0.0f, 1.0f } }; + B_ = math::Matrix{ { 0.5f * dt * dt }, { dt } }; + } + + math::SquareMatrix DoubleIntegratorPlant::GetA() const + { + return A_; + } + + math::Matrix DoubleIntegratorPlant::GetB() const + { + return B_; + } + + void DoubleIntegratorPlant::GenerateObservations( + std::size_t numSteps, + uint32_t seed, + std::array& observations, + std::vector& truePositions) const + { + std::mt19937 rng(seed); + std::normal_distribution processNoise(0.0f, config_.sigmaQ); + std::normal_distribution measurementNoise(0.0f, config_.sigmaR); + + StateVector state{ { 0.0f }, { 0.0f } }; + truePositions.clear(); + truePositions.reserve(numSteps); + + for (std::size_t t = 0; t < numSteps && t < MaxSteps; ++t) + { + truePositions.push_back(state.at(0, 0)); + + observations[t].at(0, 0) = state.at(0, 0) + measurementNoise(rng); + + StateVector noise{ { processNoise(rng) }, { processNoise(rng) } }; + state = A_ * state + noise; + } + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.hpp b/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.hpp new file mode 100644 index 00000000..401ec7fb --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/DoubleIntegratorPlant.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "numerical/math/Matrix.hpp" +#include +#include +#include +#include + +namespace simulator::controllers +{ + struct DoubleIntegratorConfig + { + float dt = 0.05f; + float sigmaQ = 0.01f; + float sigmaR = 0.5f; + }; + + class DoubleIntegratorPlant + { + public: + static constexpr std::size_t MaxSteps = 200; + + using StateVector = math::Vector; + using InputVector = math::Vector; + using MeasurementVector = math::Vector; + + explicit DoubleIntegratorPlant(const DoubleIntegratorConfig& config); + + [[nodiscard]] math::SquareMatrix GetA() const; + [[nodiscard]] math::Matrix GetB() const; + + void GenerateObservations( + std::size_t numSteps, + uint32_t seed, + std::array& observations, + std::vector& truePositions) const; + + private: + math::SquareMatrix A_; + math::Matrix B_; + DoubleIntegratorConfig config_; + }; +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.cpp b/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.cpp new file mode 100644 index 00000000..989d785c --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.cpp @@ -0,0 +1,44 @@ +#include "simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.hpp" +#include +#include + +namespace simulator::controllers +{ + EmKfResult EmKfPipeline::Run( + const std::array& observations, + std::size_t numSteps, + const EmParameters& initialGuess, + const EmKfConfig& config) + { + EmKfResult result{}; + result.logLikelihoodHistory.reserve(config.maxEmIterations); + + EmParameters currentParams = initialGuess; + float prevLogLikelihood = std::numeric_limits::lowest(); + + for (std::size_t iter = 0; iter < config.maxEmIterations; ++iter) + { + const auto stepResult = em_.Run(observations, numSteps, currentParams, 1, + std::numeric_limits::lowest()); + + result.logLikelihoodHistory.push_back(stepResult.logLikelihood); + currentParams = stepResult.parameters; + + if (std::abs(stepResult.logLikelihood - prevLogLikelihood) < config.convergenceTolerance) + { + result.emResult = stepResult; + result.emResult.iterations = iter + 1; + result.emResult.converged = true; + return result; + } + + prevLogLikelihood = stepResult.logLikelihood; + } + + result.emResult.parameters = currentParams; + result.emResult.logLikelihood = prevLogLikelihood; + result.emResult.iterations = config.maxEmIterations; + result.emResult.converged = false; + return result; + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.hpp b/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.hpp new file mode 100644 index 00000000..05316238 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/EmKfPipeline.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include "numerical/estimators/offline/ExpectationMaximization.hpp" +#include "numerical/math/Matrix.hpp" +#include +#include +#include + +namespace simulator::controllers +{ + struct EmKfConfig + { + std::size_t maxEmIterations = 50; + float convergenceTolerance = 1e-4f; + }; + + struct EmKfResult + { + estimators::ExpectationMaximization<2, 1, 200>::EmResult emResult; + std::vector logLikelihoodHistory; + }; + + class EmKfPipeline + { + public: + static constexpr std::size_t MaxSteps = 200; + using MeasurementVector = math::Vector; + using EmType = estimators::ExpectationMaximization<2, 1, MaxSteps>; + using EmParameters = EmType::EmParameters; + + EmKfResult Run( + const std::array& observations, + std::size_t numSteps, + const EmParameters& initialGuess, + const EmKfConfig& config); + + private: + EmType em_; + }; +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.cpp b/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.cpp new file mode 100644 index 00000000..d2e71812 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.cpp @@ -0,0 +1,83 @@ +#include "simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.hpp" +#include "numerical/controllers/implementations/Mpc.hpp" +#include +#include + +namespace simulator::controllers +{ + MpcBoCalibrator::IseObjective::IseObjective( + const math::SquareMatrix& F, + const math::Matrix& B, + const math::SquareMatrix& A_true, + std::size_t closedLoopSteps) + : F_(F) + , B_(B) + , A_true_(A_true) + , closedLoopSteps_(closedLoopSteps) + {} + + float MpcBoCalibrator::IseObjective::Evaluate(const math::Vector& params) + { + const float q = std::max(params.at(0, 0), 0.01f); + const float r = std::max(params.at(1, 0), 0.001f); + return RunClosedLoopIse(q, r); + } + + float MpcBoCalibrator::IseObjective::RunClosedLoopIse(float q, float r) const + { + using WeightsType = ::controllers::MpcWeights; + WeightsType weights; + weights.Q = math::SquareMatrix::Identity() * q; + weights.R = math::SquareMatrix{ { r } }; + + ::controllers::Mpc mpc(F_, B_, weights); + + const math::Vector ref{ { 1.0f }, { 0.0f } }; + mpc.SetReference(ref); + + math::Vector state{ { 0.0f }, { 0.0f } }; + float ise = 0.0f; + + for (std::size_t k = 0; k < closedLoopSteps_; ++k) + { + const auto u = mpc.ComputeControl(state); + state = A_true_ * state + B_ * u; + + const float ep = state.at(0, 0) - ref.at(0, 0); + const float ev = state.at(1, 0) - ref.at(1, 0); + ise += ep * ep + ev * ev; + } + + return ise; + } + + MpcBoResult MpcBoCalibrator::Calibrate( + const math::SquareMatrix& F_est, + const math::Matrix& B_true, + const math::SquareMatrix& A_true, + const MpcBoCalibratorConfig& config) + { + IseObjective objective(F_est, B_true, A_true, config.closedLoopSteps); + + optimization::GpHyperparameters hp{ 2.0f, 1.0f, 0.05f }; + Bo::BoundsArray bounds{ + std::make_pair(config.qMin, config.qMax), + std::make_pair(config.rMin, config.rMax) + }; + Bo bo(bounds, hp, config.seed); + + really_assert(config.boIterations > 0 && config.boIterations <= BoMaxObs); + const auto boResult = bo.Optimize(objective, config.boIterations); + + MpcBoResult result{}; + result.optimalQ = boResult.bestPoint.at(0, 0); + result.optimalR = boResult.bestPoint.at(1, 0); + result.finalIse = boResult.bestValue; + + result.iseHistory.reserve(bo.GetNumObservations()); + for (std::size_t i = 0; i < bo.GetNumObservations(); ++i) + result.iseHistory.push_back(bo.GetObservedValues()[i]); + + return result; + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.hpp b/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.hpp new file mode 100644 index 00000000..4b2f620d --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/application/MpcBoCalibrator.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include "numerical/math/Matrix.hpp" +#include "numerical/optimization/BayesianOptimization.hpp" +#include "numerical/optimization/BlackBoxObjective.hpp" +#include +#include +#include + +namespace simulator::controllers +{ + struct MpcBoCalibratorConfig + { + float qMin = 0.1f; + float qMax = 100.0f; + float rMin = 0.01f; + float rMax = 10.0f; + std::size_t boIterations = 25; + std::size_t closedLoopSteps = 50; + uint64_t seed = 7777ULL; + }; + + struct MpcBoResult + { + float optimalQ; + float optimalR; + float finalIse; + std::vector iseHistory; + }; + + class MpcBoCalibrator + { + public: + static constexpr std::size_t BoNumParams = 2; + static constexpr std::size_t BoMaxObs = 30; + static constexpr std::size_t BoNumCandidates = 200; + + using Bo = optimization::BayesianOptimization; + + MpcBoResult Calibrate( + const math::SquareMatrix& F_est, + const math::Matrix& B_true, + const math::SquareMatrix& A_true, + const MpcBoCalibratorConfig& config); + + private: + class IseObjective : public optimization::BlackBoxObjective + { + public: + IseObjective( + const math::SquareMatrix& F, + const math::Matrix& B, + const math::SquareMatrix& A_true, + std::size_t closedLoopSteps); + + float Evaluate(const math::Vector& params) override; + + private: + float RunClosedLoopIse(float q, float r) const; + + math::SquareMatrix F_; + math::Matrix B_; + math::SquareMatrix A_true_; + std::size_t closedLoopSteps_; + }; + }; +} diff --git a/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.cpp b/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.cpp new file mode 100644 index 00000000..ace30740 --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.cpp @@ -0,0 +1,226 @@ +#include "simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulator::controllers::view +{ + BayesianMpcCalibrationView::BayesianMpcCalibrationView(QWidget* parent) + : QMainWindow(parent) + { + setWindowTitle("Bayesian MPC Calibration Simulator"); + resize(1400, 900); + SetupUi(); + } + + void BayesianMpcCalibrationView::SetupUi() + { + auto* splitter = new QSplitter(Qt::Horizontal, this); + + auto* controlPanel = new QGroupBox("Configuration", splitter); + auto* formLayout = new QFormLayout(controlPanel); + + dtSpinBox_ = new QDoubleSpinBox(controlPanel); + dtSpinBox_->setRange(0.01, 0.5); + dtSpinBox_->setSingleStep(0.01); + dtSpinBox_->setValue(0.05); + dtSpinBox_->setDecimals(3); + formLayout->addRow("dt (s):", dtSpinBox_); + + sigmaQSpinBox_ = new QDoubleSpinBox(controlPanel); + sigmaQSpinBox_->setRange(0.001, 1.0); + sigmaQSpinBox_->setSingleStep(0.001); + sigmaQSpinBox_->setValue(0.01); + sigmaQSpinBox_->setDecimals(4); + formLayout->addRow("Process noise σ_q:", sigmaQSpinBox_); + + sigmaRSpinBox_ = new QDoubleSpinBox(controlPanel); + sigmaRSpinBox_->setRange(0.01, 5.0); + sigmaRSpinBox_->setSingleStep(0.01); + sigmaRSpinBox_->setValue(0.5); + sigmaRSpinBox_->setDecimals(3); + formLayout->addRow("Measurement noise σ_r:", sigmaRSpinBox_); + + emIterationsSpinBox_ = new QSpinBox(controlPanel); + emIterationsSpinBox_->setRange(5, 200); + emIterationsSpinBox_->setValue(50); + formLayout->addRow("EM max iterations:", emIterationsSpinBox_); + + boIterationsSpinBox_ = new QSpinBox(controlPanel); + boIterationsSpinBox_->setRange(5, 29); + boIterationsSpinBox_->setValue(25); + formLayout->addRow("BO evaluations:", boIterationsSpinBox_); + + runButton_ = new QPushButton("Run Pipeline", controlPanel); + formLayout->addRow(runButton_); + + statusLabel_ = new QLabel("Configure parameters and press Run Pipeline", controlPanel); + statusLabel_->setWordWrap(true); + formLayout->addRow(statusLabel_); + + controlPanel->setMaximumWidth(320); + + tabWidget_ = new QTabWidget(splitter); + + observationsChart_ = new widgets::TimeSeriesChartWidget(tabWidget_); + emConvergenceChart_ = new widgets::TimeSeriesChartWidget(tabWidget_); + boConvergenceChart_ = new widgets::TimeSeriesChartWidget(tabWidget_); + stepResponseChart_ = new widgets::TimeSeriesChartWidget(tabWidget_); + + tabWidget_->addTab(observationsChart_, "1. Observations"); + tabWidget_->addTab(emConvergenceChart_, "2. EM Convergence"); + tabWidget_->addTab(boConvergenceChart_, "3. BO Calibration"); + tabWidget_->addTab(stepResponseChart_, "4. Step Response"); + + splitter->addWidget(controlPanel); + splitter->addWidget(tabWidget_); + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + setCentralWidget(splitter); + + connect(runButton_, &QPushButton::clicked, this, &BayesianMpcCalibrationView::OnRunRequested); + } + + void BayesianMpcCalibrationView::OnRunRequested() + { + runButton_->setEnabled(false); + statusLabel_->setText("Running pipeline (EM + BO) ..."); + + try + { + CalibrationSimulationConfig config{}; + config.plant.dt = static_cast(dtSpinBox_->value()); + config.plant.sigmaQ = static_cast(sigmaQSpinBox_->value()); + config.plant.sigmaR = static_cast(sigmaRSpinBox_->value()); + config.emKf.maxEmIterations = static_cast(emIterationsSpinBox_->value()); + config.mpcBo.boIterations = static_cast(boIterationsSpinBox_->value()); + + BayesianMpcCalibrationSimulator simulator; + const auto results = simulator.Run(config); + + DisplayResults(results); + + statusLabel_->setText( + QString("Done. EM: %1 iters (%2) | Opt Q=%3 R=%4 ISE=%5") + .arg(static_cast(results.emIterations)) + .arg(results.emConverged ? "converged" : "max iters") + .arg(static_cast(results.optimalQ), 0, 'f', 2) + .arg(static_cast(results.optimalR), 0, 'f', 2) + .arg(static_cast(results.finalIse), 0, 'e', 3)); + } + catch (const std::exception& ex) + { + QMessageBox::warning(this, "Error", ex.what()); + statusLabel_->setText("Pipeline failed."); + } + + runButton_->setEnabled(true); + } + + void BayesianMpcCalibrationView::DisplayResults(const CalibrationSimulationResults& results) + { + // --- Panel 1: Observations --- + observationsChart_->SetTimeAxis(results.timeAxis); + observationsChart_->SetPanels({ + { + "Observations vs True Position", + "Position", + { + { "True Position", QColor(41, 128, 185), results.truePositions }, + { "Noisy Measurements", QColor(231, 76, 60), results.rawMeasurements }, + }, + 1, + }, + }); + + // --- Panel 2: EM convergence --- + { + std::vector iterAxis; + iterAxis.reserve(results.emLogLikelihoodHistory.size()); + for (std::size_t i = 0; i < results.emLogLikelihoodHistory.size(); ++i) + iterAxis.push_back(static_cast(i + 1)); + + emConvergenceChart_->SetTimeAxis(iterAxis); + emConvergenceChart_->SetPanels({ + { + "EM Log-Likelihood vs Iteration", + "Log-Likelihood", + { + { "Log-Likelihood", QColor(39, 174, 96), results.emLogLikelihoodHistory }, + }, + 1, + }, + }); + } + + // --- Panel 3: BO ISE history (running min) --- + { + std::vector boIterAxis; + std::vector runningMin; + boIterAxis.reserve(results.boIseHistory.size()); + runningMin.reserve(results.boIseHistory.size()); + float curMin = std::numeric_limits::max(); + for (std::size_t i = 0; i < results.boIseHistory.size(); ++i) + { + boIterAxis.push_back(static_cast(i + 1)); + curMin = std::min(curMin, results.boIseHistory[i]); + runningMin.push_back(curMin); + } + + boConvergenceChart_->SetTimeAxis(boIterAxis); + boConvergenceChart_->SetPanels({ + { + "BO: Best ISE Found vs Evaluation", + "ISE", + { + { "All ISE values", QColor(200, 150, 50), results.boIseHistory }, + { "Best so far", QColor(231, 76, 60), runningMin }, + }, + 1, + }, + }); + } + + // --- Panel 4: Step response --- + { + std::vector refLine(results.stepResponseTime.size(), 1.0f); + + stepResponseChart_->SetTimeAxis(results.stepResponseTime); + stepResponseChart_->SetPanels({ + { + "Position", + "m", + { + { "Position", QColor(41, 128, 185), results.stepResponsePosition }, + { "Reference", QColor(150, 150, 150), refLine }, + }, + 2, + }, + { + "Velocity", + "m/s", + { + { "Velocity", QColor(39, 174, 96), results.stepResponseVelocity }, + }, + 1, + }, + { + "Control Input", + "N", + { + { "Control", QColor(231, 76, 60), results.stepResponseControl }, + }, + 1, + }, + }); + } + } +} diff --git a/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.hpp b/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.hpp new file mode 100644 index 00000000..6a902b3e --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/view/BayesianMpcCalibrationView.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include "simulator/controllers/BayesianMpcCalibration/application/BayesianMpcCalibrationSimulator.hpp" +#include "simulator/widgets/TimeSeriesChartWidget.hpp" +#include +#include +#include +#include +#include +#include + +namespace simulator::controllers::view +{ + class BayesianMpcCalibrationView : public QMainWindow + { + Q_OBJECT + + public: + explicit BayesianMpcCalibrationView(QWidget* parent = nullptr); + + private: + void OnRunRequested(); + void SetupUi(); + void DisplayResults(const CalibrationSimulationResults& results); + + widgets::TimeSeriesChartWidget* observationsChart_; + widgets::TimeSeriesChartWidget* emConvergenceChart_; + widgets::TimeSeriesChartWidget* boConvergenceChart_; + widgets::TimeSeriesChartWidget* stepResponseChart_; + + QTabWidget* tabWidget_; + QDoubleSpinBox* dtSpinBox_; + QDoubleSpinBox* sigmaQSpinBox_; + QDoubleSpinBox* sigmaRSpinBox_; + QSpinBox* emIterationsSpinBox_; + QSpinBox* boIterationsSpinBox_; + QPushButton* runButton_; + QLabel* statusLabel_; + }; +} diff --git a/simulator/controllers/BayesianMpcCalibration/view/CMakeLists.txt b/simulator/controllers/BayesianMpcCalibration/view/CMakeLists.txt new file mode 100644 index 00000000..95add30d --- /dev/null +++ b/simulator/controllers/BayesianMpcCalibration/view/CMakeLists.txt @@ -0,0 +1,29 @@ +add_library(numerical.simulator.controllers.bayesian_mpc_calibration.view STATIC) + +target_include_directories(numerical.simulator.controllers.bayesian_mpc_calibration.view PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.bayesian_mpc_calibration.view PUBLIC + numerical.simulator.controllers.bayesian_mpc_calibration.application + numerical.simulator.widgets + Qt6::Widgets +) + +set_target_properties(numerical.simulator.controllers.bayesian_mpc_calibration.view PROPERTIES + AUTOMOC ON +) + +target_sources(numerical.simulator.controllers.bayesian_mpc_calibration.view PRIVATE + BayesianMpcCalibrationView.cpp + BayesianMpcCalibrationView.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration.view PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.bayesian_mpc_calibration.view PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/CMakeLists.txt b/simulator/controllers/CMakeLists.txt index fb757c72..0f242a6d 100644 --- a/simulator/controllers/CMakeLists.txt +++ b/simulator/controllers/CMakeLists.txt @@ -1,4 +1,5 @@ add_subdirectory(common) +add_subdirectory(BayesianMpcCalibration) add_subdirectory(LqrCartPole) add_subdirectory(Mpc) add_subdirectory(PidController)