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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions .github/agents/executor.agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---

Expand All @@ -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

Expand Down
13 changes: 8 additions & 5 deletions .github/agents/planner.agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -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
6 changes: 4 additions & 2 deletions .github/agents/reviewer.agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down
36 changes: 29 additions & 7 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -114,6 +114,30 @@ These are the most important architectural directives in this codebase. Every ne
- **Naming convention**: Targets follow `numerical.simulator.<domain>.<algorithm>.<layer>` (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": "<SimulatorName> Simulator",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/host/simulator/<domain>/<SimulatorFolder>/Debug/numerical.simulator.<domain>.<snake_case_name>",
"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

Expand Down Expand Up @@ -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`

Expand Down
2 changes: 1 addition & 1 deletion .github/instructions/numerical-cpp.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
20 changes: 20 additions & 0 deletions .vscode/launch.json
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
147 changes: 147 additions & 0 deletions doc/optimization/BayesianOptimization.md
Original file line number Diff line number Diff line change
@@ -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.
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved

## 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

7 changes: 4 additions & 3 deletions doc/optimization/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Loading
Loading