Skip to content

Commit 3ec1708

Browse files
chore: add simulator for pid (#93)
* add simulator for pid * fix coverage and megalinter * fix github instructions * process review comments
1 parent 3399820 commit 3ec1708

30 files changed

Lines changed: 3078 additions & 12 deletions

‎.github/copilot-instructions.md‎

Lines changed: 110 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,91 @@ When implementing or modifying algorithms:
118118
- Aim for high code coverage, especially in numerical algorithms
119119
- Verify numerical accuracy and stability
120120
- Test edge cases and boundary conditions
121-
- Example typed test pattern:
121+
122+
#### Test Macro Rules (cppcheck compliance)
123+
124+
- **NEVER use plain `TEST()` macro** — cppcheck cannot parse it and will report `syntaxError`
125+
- **Use `TYPED_TEST`** when testing with multiple numeric types
126+
- **Use `TEST_F`** when testing with a single type or a fixture
127+
- Fixture class and type aliases go inside an anonymous `namespace {}`
128+
- Test macros (`TEST_F`, `TYPED_TEST`) go **outside** the anonymous namespace
129+
- Include `<gtest/gtest.h>` (not `<gmock/gmock.h>`) unless gmock matchers are needed
130+
131+
#### Typed Test Pattern (multiple types)
132+
122133
```cpp
123-
template<typename T>
124-
class TestAlgorithm : public testing::Test {};
125-
126-
using TestedTypes = ::testing::Types<float, math::Q15, math::Q31>;
127-
TYPED_TEST_SUITE(TestAlgorithm, TestedTypes);
128-
134+
#include "numerical/solvers/GaussianElimination.hpp"
135+
#include <gtest/gtest.h>
136+
137+
namespace
138+
{
139+
template<typename T>
140+
class TestAlgorithm : public ::testing::Test
141+
{
142+
protected:
143+
solvers::GaussianElimination<T, 3> solver;
144+
};
145+
146+
using TestTypes = ::testing::Types<float, math::Q15, math::Q31>;
147+
TYPED_TEST_SUITE(TestAlgorithm, TestTypes);
148+
}
149+
129150
TYPED_TEST(TestAlgorithm, computes_correct_result)
130151
{
131-
// Test with TypeParam
152+
// Use TypeParam for the type, this->solver for fixture members
132153
}
133154
```
134155

156+
#### Fixture Test Pattern (single type)
157+
158+
```cpp
159+
#include "numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp"
160+
#include <gtest/gtest.h>
161+
162+
namespace
163+
{
164+
class TestDare : public ::testing::Test
165+
{
166+
protected:
167+
solvers::DiscreteAlgebraicRiccatiEquation<float, 2, 1> solver;
168+
};
169+
}
170+
171+
TEST_F(TestDare, solves_simple_system)
172+
{
173+
// Use this->solver for fixture members
174+
}
175+
```
176+
177+
#### Coverage for Template Code
178+
179+
Header-only templates are compiled into test executables, which do **not** have `--coverage` flags.
180+
To get coverage, template code must be explicitly instantiated in a `.cpp` file that is part of the library (which **does** have coverage flags).
181+
182+
1. **Add `extern template` declarations** at the bottom of the header (prevents implicit instantiation in other TUs):
183+
```cpp
184+
// In Algorithm.hpp, at the bottom of the namespace, after all template definitions
185+
extern template class Algorithm<float, 3>;
186+
extern template class Algorithm<math::Q15, 3>;
187+
}
188+
```
189+
190+
2. **Create a matching `.cpp` file** with explicit instantiation (compiled with `--coverage` as part of the library):
191+
```cpp
192+
// Algorithm.cpp
193+
#include "numerical/domain/Algorithm.hpp"
194+
195+
namespace domain
196+
{
197+
template class Algorithm<float, 3>;
198+
template class Algorithm<math::Q15, 3>;
199+
}
200+
```
201+
202+
3. **Add the `.cpp` file to `CMakeLists.txt`** in `target_sources`
203+
204+
4. **Instantiate all specializations used by tests** — each `extern template` in the header must have a matching `template class` in the `.cpp` file
205+
135206
## Common Patterns
136207

137208
### Instead of this (BAD):
@@ -273,14 +344,41 @@ When implementing a new algorithm:
273344

274345
## Compiler Optimizations and SIMD
275346

347+
### Mandatory Optimizations for `numerical/` Headers
348+
349+
All header files under `numerical/` that contain algorithm implementations **must** include both:
350+
351+
1. **File-level `#pragma GCC optimize`** — placed immediately after `#pragma once` and includes:
352+
```cpp
353+
#pragma once
354+
355+
#if defined(__GNUC__) || defined(__clang__)
356+
#pragma GCC optimize("O3", "fast-math")
357+
#endif
358+
```
359+
360+
2. **`OPTIMIZE_FOR_SPEED` macro** on hot-path method definitions (e.g., `Filter()`, `Compute()`, `Calculate()`, `Solve()`):
361+
```cpp
362+
#include "numerical/math/CompilerOptimizations.hpp"
363+
364+
template<typename T, std::size_t N>
365+
OPTIMIZE_FOR_SPEED T Algorithm<T, N>::Compute(T input)
366+
{
367+
// performance-critical implementation
368+
}
369+
```
370+
371+
The `#pragma GCC optimize` applies `-O3` and `-ffast-math` to the entire translation unit even in Debug builds, while `OPTIMIZE_FOR_SPEED` additionally forces inlining and marks functions as hot for the linker.
372+
276373
### Optimization Macros
277374

278-
The library provides compiler-specific optimization hints:
375+
Defined in `numerical/math/CompilerOptimizations.hpp`:
279376

280377
- **OPTIMIZE_FOR_SPEED**: For performance-critical algorithms (PID, filters)
281-
- GCC: `-O3`, `-ffast-math`, `hot`, `flatten` attributes
282-
- Clang: `hot`, `flatten` attributes
283-
- Enables aggressive inlining and optimization
378+
- GCC: `-O3`, `-ffast-math`, `hot`, `always_inline` attributes
379+
- Clang: `hot`, `always_inline` attributes
380+
- MSVC/other: no-op
381+
- Only active when `NumericalToolbox_ENABLE_OPTIMIZATIONS` is defined
284382
- **ALWAYS_INLINE_HOT**: Forces inlining for frequently-called hot-path code
285383
- **ALWAYS_INLINE**: Forces inlining without hot attribute
286384

‎.vscode/launch.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,26 @@
4141
}
4242
]
4343
},
44+
{
45+
"name": "PID Controller Simulator",
46+
"type": "cppdbg",
47+
"request": "launch",
48+
"program": "${workspaceFolder}/build/host/simulator/controllers/PidController/Debug/numerical.simulator.controllers.pid_controller",
49+
"args": [],
50+
"stopAtEntry": false,
51+
"cwd": "${workspaceFolder}",
52+
"environment": [],
53+
"externalConsole": false,
54+
"MIMode": "gdb",
55+
"miDebuggerPath": "/usr/bin/gdb",
56+
"setupCommands": [
57+
{
58+
"description": "Enable pretty-printing for gdb",
59+
"text": "-enable-pretty-printing",
60+
"ignoreFailures": true
61+
}
62+
]
63+
},
4464
{
4565
"name": "Linux Debug",
4666
"type": "cppdbg",

‎doc/analysis/RootLocus.md‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# Root Locus Analysis
2+
3+
## Process Overview
4+
5+
```mermaid
6+
graph TD
7+
A[Input: Open-Loop Numerator N(s), Denominator D(s)] --> B[Find Open-Loop Poles and Zeros]
8+
B --> C[Generate Logarithmic Gain Sweep]
9+
C --> D[For Each Gain K]
10+
D --> E[Form Characteristic Polynomial: D(s) + K·N(s)]
11+
E --> F[Find Roots using Durand-Kerner]
12+
F --> G[Store Roots as Locus Branches]
13+
G --> H{More Gain Steps?}
14+
H -->|Yes| D
15+
H -->|No| I[Compute Closed-Loop Poles at Current Gain]
16+
I --> J[Return Result]
17+
```
18+
19+
## Mathematical Background
20+
21+
### Root Locus Definition
22+
23+
The root locus shows how the closed-loop poles of a feedback system move in the complex plane as a scalar gain $K$ varies. Given an open-loop transfer function:
24+
25+
$$G(s) = K \cdot \frac{N(s)}{D(s)}$$
26+
27+
the closed-loop characteristic equation is:
28+
29+
$$D(s) + K \cdot N(s) = 0$$
30+
31+
The root locus plots the solutions of this equation for $K \in [K_{\min}, K_{\max}]$.
32+
33+
### Properties
34+
35+
- **Starting points** ($K \to 0$): Roots converge to the open-loop poles (roots of $D(s)$)
36+
- **Ending points** ($K \to \infty$): Roots converge to the open-loop zeros (roots of $N(s)$) or diverge to infinity
37+
- **Number of branches**: Equal to the order of $D(s)$
38+
- **Symmetry**: Complex roots appear in conjugate pairs for real-coefficient polynomials
39+
40+
### Gain Sweep
41+
42+
The gain is swept logarithmically to provide even resolution across decades:
43+
44+
$$K_i = 10^{\log_{10}(K_{\min}) + \frac{i}{N-1} \cdot (\log_{10}(K_{\max}) - \log_{10}(K_{\min}))}$$
45+
46+
where $N$ is `MaxGainSteps` and $i \in [0, N-1]$.
47+
48+
## API
49+
50+
```cpp
51+
#include "numerical/analysis/RootLocus.hpp"
52+
53+
analysis::RootLocus<float, 5, 100> rootLocus;
54+
55+
// Open-loop transfer function: K * (s + 1) / (s^3 + 3s^2 + 2s)
56+
std::array<float, 2> numerator = { 1.0f, 1.0f }; // s + 1
57+
std::array<float, 4> denominator = { 1.0f, 3.0f, 2.0f, 0.0f }; // s^3 + 3s^2 + 2s
58+
59+
auto result = rootLocus.Calculate(
60+
infra::MakeRange(numerator),
61+
infra::MakeRange(denominator),
62+
1.0f, // currentGain
63+
0.001f, // gainMin
64+
50.0f); // gainMax
65+
66+
// result.openLoopPoles: roots of denominator
67+
// result.openLoopZeros: roots of numerator
68+
// result.closedLoopPoles: roots of D(s) + currentGain * N(s)
69+
// result.loci[branch][step]: complex root at each gain step
70+
// result.gains[step]: gain value at each step
71+
```
72+
73+
### Template Parameters
74+
75+
| Parameter | Description |
76+
|-----------|-------------|
77+
| `T` | Floating-point type (`float` or `double`) |
78+
| `MaxOrder` | Maximum polynomial order (number of branches) |
79+
| `MaxGainSteps` | Number of gain steps in the sweep (must be > 1) |
80+
81+
### Calculate Parameters
82+
83+
| Parameter | Default | Description |
84+
|-----------|---------|-------------|
85+
| `numerator` | — | Open-loop numerator polynomial coefficients (descending power) |
86+
| `denominator` | — | Open-loop denominator polynomial coefficients (descending power) |
87+
| `currentGain` | — | Gain at which to compute closed-loop poles |
88+
| `gainMin` | 0.001 | Minimum gain for the sweep (must be > 0) |
89+
| `gainMax` | 50 | Maximum gain for the sweep (must be > gainMin) |
90+
91+
### Preconditions
92+
93+
- `gainMin > 0` (logarithmic sweep requires positive gains)
94+
- `gainMax > gainMin`
95+
- `denominator.size() >= numerator.size()` (proper or strictly proper transfer function)
96+
- `MaxGainSteps > 1` (enforced at compile time)
97+
98+
### Result Structure
99+
100+
| Field | Type | Description |
101+
|-------|------|-------------|
102+
| `loci` | `array<LociBranch, MaxOrder>` | Root positions for each branch at each gain step |
103+
| `activeBranches` | `size_t` | Number of active locus branches (= denominator order) |
104+
| `gains` | `GainVector` | Gain values at each step |
105+
| `openLoopPoles` | `RootVector` | Poles of the open-loop system |
106+
| `openLoopZeros` | `RootVector` | Zeros of the open-loop system |
107+
| `closedLoopPoles` | `RootVector` | Poles at `currentGain` |
108+
| `currentGain` | `T` | The current gain value |
109+
110+
### Complexity
111+
112+
- **Time**: $O(N \cdot n^2 \cdot k)$ where $N$ = gain steps, $n$ = polynomial order, $k$ = Durand-Kerner iterations
113+
- **Space**: $O(N \cdot n)$ for storing all locus branches
114+
115+
## Numerical Considerations
116+
117+
- **Logarithmic gain sweep**: Provides uniform resolution across gain decades; requires strictly positive gains
118+
- **Branch tracking**: Roots at each gain step are sorted by Durand-Kerner's default ordering (real part ascending). For smooth branch visualization, the UI may need to apply additional nearest-neighbor matching between consecutive steps
119+
- **Polynomial addition**: `PolyAdd` pads the shorter polynomial (numerator) with leading zeros to align with the longer one (denominator), requiring `denominator.size() >= numerator.size()`
120+
- **Root finding accuracy**: Inherits convergence properties from the Durand-Kerner solver; see [DurandKerner.md](DurandKerner.md) for details

‎doc/solvers/DurandKerner.md‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Durand-Kerner Polynomial Root Finder
2+
3+
## Process Overview
4+
5+
```mermaid
6+
graph TD
7+
A[Input Polynomial Coefficients] --> B{Empty or Zero-Order?}
8+
B -->|Yes| C[Return Empty Roots]
9+
B -->|No| D{First-Order?}
10+
D -->|Yes| E[Direct Solution: -c₁/c₀]
11+
D -->|No| F[Initialize Roots on Circle]
12+
F --> G[Iterative Refinement]
13+
G --> H{Converged or Max Iterations?}
14+
H -->|No| G
15+
H -->|Yes| I[Sort Roots by Real Part]
16+
I --> J[Return Roots]
17+
```
18+
19+
## Mathematical Background
20+
21+
### Polynomial Representation
22+
23+
The polynomial is represented in descending power order:
24+
25+
$$P(z) = c_0 z^n + c_1 z^{n-1} + \cdots + c_{n-1} z + c_n$$
26+
27+
where the coefficients array is `[c₀, c₁, ..., cₙ]` with `c₀ ≠ 0` (leading coefficient).
28+
29+
### Durand-Kerner Method
30+
31+
The Durand-Kerner method (also known as Weierstrass iteration) simultaneously refines all roots of a polynomial. Given current root estimates $z_0, z_1, \ldots, z_{n-1}$, each root is updated:
32+
33+
$$z_r^{(k+1)} = z_r^{(k)} - \frac{P(z_r^{(k)})}{\prod_{j \neq r} (z_r^{(k)} - z_j^{(k)})}$$
34+
35+
This is equivalent to applying Newton's method but using the other root estimates to factor out known roots from the denominator, avoiding explicit polynomial deflation.
36+
37+
### Initial Root Placement
38+
39+
Roots are initialized uniformly on a circle of radius:
40+
41+
$$R = \left| \frac{c_n}{c_0} \right|^{1/n}$$
42+
43+
with an angular offset of 0.4 radians to break symmetry. If $R < 0.1$, it defaults to 1.0.
44+
45+
### Convergence
46+
47+
- **Quadratic convergence** when roots are well-separated
48+
- **Linear convergence** near repeated roots
49+
- Terminates when all corrections $|z_r^{(k+1)} - z_r^{(k)}| < \epsilon$ (default $\epsilon = 10^{-6}$)
50+
- Maximum iteration limit (default 200) prevents infinite loops
51+
52+
## API
53+
54+
```cpp
55+
#include "numerical/solvers/DurandKerner.hpp"
56+
57+
solvers::DurandKerner<float, 10> solver;
58+
59+
// Coefficients for z^3 - 6z^2 + 11z - 6 = (z-1)(z-2)(z-3)
60+
std::array<float, 4> coeffs = { 1.0f, -6.0f, 11.0f, -6.0f };
61+
auto roots = solver.Solve(infra::MakeRange(coeffs));
62+
// roots ≈ {1+0j, 2+0j, 3+0j}
63+
```
64+
65+
### Template Parameters
66+
67+
| Parameter | Description |
68+
|-----------|-------------|
69+
| `T` | Floating-point type (`float` or `double`) |
70+
| `MaxOrder` | Maximum polynomial degree supported |
71+
72+
### Solve Parameters
73+
74+
| Parameter | Default | Description |
75+
|-----------|---------|-------------|
76+
| `coefficients` | — | Polynomial coefficients in descending power order |
77+
| `maxIterations` | 200 | Maximum number of Durand-Kerner iterations |
78+
| `tolerance` | 1e-6 | Convergence threshold for root corrections |
79+
80+
### Preconditions
81+
82+
- `coefficients` must not be empty
83+
- Leading coefficient `coefficients[0]` must be non-zero
84+
- Polynomial order must not exceed `MaxOrder`
85+
86+
### Complexity
87+
88+
- **Time**: $O(n^2 \cdot k)$ where $n$ is polynomial order and $k$ is iteration count
89+
- **Space**: $O(n)$ — roots stored in `BoundedVector`
90+
91+
## Numerical Considerations
92+
93+
- **Near-degenerate denominators**: When two root estimates are very close ($|z_r - z_j| < 10^{-15}$), the difference is excluded from the denominator product to avoid division by near-zero
94+
- **Root sorting**: Results are sorted by real part (ascending), with imaginary part as tiebreaker
95+
- **Fixed-point**: Only floating-point types (`float`, `double`) are supported due to the complex arithmetic requirements
96+
- **Ill-conditioned polynomials**: Polynomials with clustered or repeated roots may converge slowly; increase `maxIterations` if needed

0 commit comments

Comments
 (0)