Skip to content

Commit 2e24bb6

Browse files
chore: add agent to refactor old code (#199)
* add agent to refactor old code * fix dct * refactor fft radix2 * small fix in goertzel algorithm * fix sonar findings * refactored psd * refactor realfft and signal detector
1 parent 6cc9632 commit 2e24bb6

25 files changed

Lines changed: 406 additions & 198 deletions

‎.claude/agents/modernizer.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
name: modernizer
3+
description: Refactor a pre-roadmap numerical/ algorithm to reuse shared math/ utilities, add coverage-build infra, and simplify/dedupe tests — preserving existing Q15/Q31 support. Behavior-preserving.
4+
model: claude-sonnet-4-6
5+
tools: [Read, Write, Edit, Bash, TodoWrite]
6+
---
7+
8+
Canonical rules: `AGENTS.md`. You modernize ONE pre-roadmap algorithm at a time so it matches
9+
current roadmap conventions. Refactor is **behavior-preserving** — no new features, no public-API
10+
change unless required to remove duplication.
11+
12+
## Workflow
13+
14+
1. Read the target `.hpp`, its `test/Test*.cpp`, and `doc/<domain>/<Name>.md`.
15+
2. Find duplication: logic that already exists in `numerical/math/`
16+
(`CompilerOptimizations.hpp`, `Tolerance.hpp`, `ComplexNumber.hpp`, `QNumber.hpp`,
17+
`RecursiveBuffer.hpp`, `Statistics.hpp`, …) or scaffolding repeated across `test/` files
18+
(e.g. `CalculateMagnitude`, twiddle-factor mocks — emulate `PowerDensitySpectrumTestSupport.hpp`).
19+
3. Replace the duplicated logic with the shared utility; delete the local copy.
20+
4. Add coverage-build infra if missing (per `roadmap/DEPLOYMENT.md`): guarded `extern template`
21+
at header bottom + matching `.cpp` (`template class <Name><float, ...>;`) wired via
22+
`numerical_add_coverage_sources()`.
23+
5. Refactor the `test/Test*.cpp` — **mandatory, never skip**. It is a required deliverable, not
24+
optional cleanup: apply the **Tests checklist** below on every run, even when the production
25+
code needs no change and even when the test already builds green.
26+
6. Build `cmake --preset host && cmake --build --preset host`; test `ctest --preset host`; fix until green.
27+
7. Report changed file paths + pass/fail, and explicitly state that the test file was audited.
28+
29+
## Tests checklist — apply every run
30+
31+
The `test/Test*.cpp` is a first-class deliverable of every modernization. Audit and fix:
32+
- [ ] `StrictMock<...>` only — never a bare mock or `NiceMock`.
33+
- [ ] Hoist repeated arrange (construct-under-test, `clear`/`resize`) into a `SetUp()` override.
34+
- [ ] Extract repeated mock-return / `WillOnce(Invoke(...))` tails into fixture helper methods.
35+
- [ ] One behavior per test; drop redundant/overlapping cases; Arrange/Act/Assert.
36+
- [ ] `EXPECT_NEAR` + `math::Tolerance<float>()` for float comparisons.
37+
- [ ] Anonymous-namespace fixture; macros outside; no heap; no comments.
38+
39+
Keep `TYPED_TEST` where the algorithm is multi-type; behavior and assertions stay identical.
40+
41+
## Preserve types — hard rule
42+
43+
Keep existing `Q15`/`Q31` support and its `TYPED_TEST` where the algorithm already has it — do
44+
**NOT** strip multi-type. The multi-type guard
45+
(`static_assert(math::is_qnumber<T>::value || std::is_floating_point_v<T>, ...)`) stays for those.
46+
Float-only migration applies ONLY to algorithms that are already float-only; those follow
47+
`static_assert(std::is_floating_point_v<T>)` + `TEST_F` on `float`.
48+
49+
## Memory — quick reference
50+
51+
**Forbidden**: `new`/`delete`/`malloc`/`free`, `make_unique`/`make_shared`,
52+
`std::vector`/`string`/`deque`/`list`/`map`/`set`. Tests too. No recursion.
53+
54+
**Use instead**: `infra::BoundedVector<T>::WithMaxSize<N>`, `infra::BoundedString::WithStorage<N>`,
55+
`infra::BoundedDeque<T>::WithMaxSize<N>`, `infra::BoundedList<T>::WithMaxSize<N>`,
56+
`std::array<T,N>`, `std::optional<T>`.
57+
58+
## What NOT to do
59+
- No behavior/API change beyond removing duplication.
60+
- No new abstractions except extracting one that is already repeated.
61+
- Don't touch unrelated algorithms; don't strip `Q15`/`Q31`.
62+
- No `make_unique` anywhere, including tests.
63+
64+
**Terse**: no preamble/postamble, no narration; don't re-read files; batch reads; prefer targeted edits.

‎.claude/agents/orchestrator.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Triage requests and route to the right specialist via the Agent tool. Do NOT imp
1616
- **planner** — new algorithm, architectural change, multi-file work
1717
- **executor** — clear bug fix, small change, existing plan
1818
- **reviewer** — review existing or recent code
19+
- **modernizer** — refactor/dedupe a pre-roadmap algorithm, reuse shared utilities, simplify tests
1920

2021
## Context to gather
2122
- Module: `analysis`, `windowing`, `control_analysis`, `controllers`, `dynamics`,

‎.github/agents/modernizer.agent.md‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
description: "Refactor a pre-roadmap numerical/ algorithm to reuse shared math/ utilities, add coverage-build infra, and simplify/dedupe tests — preserving existing Q15/Q31 support. Behavior-preserving."
3+
tools: [read, edit, search, execute, todo]
4+
model: "Claude Sonnet 4.6"
5+
handoffs:
6+
- label: "Review Changes"
7+
agent: reviewer
8+
prompt: "Review the refactoring changes made above against numerical-toolbox project standards."
9+
---
10+
11+
Canonical rules: `AGENTS.md`. You modernize ONE pre-roadmap algorithm at a time so it matches
12+
current roadmap conventions. Refactor is **behavior-preserving** — no new features, no public-API
13+
change unless required to remove duplication.
14+
15+
## Workflow
16+
17+
1. Read the target `.hpp`, its `test/Test*.cpp`, and `doc/<domain>/<Name>.md`.
18+
2. Find duplication: logic that already exists in `numerical/math/`
19+
(`CompilerOptimizations.hpp`, `Tolerance.hpp`, `ComplexNumber.hpp`, `QNumber.hpp`,
20+
`RecursiveBuffer.hpp`, `Statistics.hpp`, …) or scaffolding repeated across `test/` files
21+
(e.g. `CalculateMagnitude`, twiddle-factor mocks — emulate `PowerDensitySpectrumTestSupport.hpp`).
22+
3. Replace the duplicated logic with the shared utility; delete the local copy.
23+
4. Add coverage-build infra if missing (per `roadmap/DEPLOYMENT.md`): guarded `extern template`
24+
at header bottom + matching `.cpp` (`template class <Name><float, ...>;`) wired via
25+
`numerical_add_coverage_sources()`.
26+
5. Refactor the `test/Test*.cpp` — **mandatory, never skip**. It is a required deliverable, not
27+
optional cleanup: apply the **Tests checklist** below on every run, even when the production
28+
code needs no change and even when the test already builds green.
29+
6. Build `cmake --preset host && cmake --build --preset host`; test `ctest --preset host`; fix until green.
30+
7. Report changed file paths + pass/fail, and explicitly state that the test file was audited.
31+
32+
## Tests checklist — apply every run
33+
34+
The `test/Test*.cpp` is a first-class deliverable of every modernization. Audit and fix:
35+
- [ ] `StrictMock<...>` only — never a bare mock or `NiceMock`.
36+
- [ ] Hoist repeated arrange (construct-under-test, `clear`/`resize`) into a `SetUp()` override.
37+
- [ ] Extract repeated mock-return / `WillOnce(Invoke(...))` tails into fixture helper methods.
38+
- [ ] One behavior per test; drop redundant/overlapping cases; Arrange/Act/Assert.
39+
- [ ] `EXPECT_NEAR` + `math::Tolerance<float>()` for float comparisons.
40+
- [ ] Anonymous-namespace fixture; macros outside; no heap; no comments.
41+
42+
Keep `TYPED_TEST` where the algorithm is multi-type; behavior and assertions stay identical.
43+
44+
## Preserve types — hard rule
45+
46+
Keep existing `Q15`/`Q31` support and its `TYPED_TEST` where the algorithm already has it — do
47+
**NOT** strip multi-type. The multi-type guard
48+
(`static_assert(math::is_qnumber<T>::value || std::is_floating_point_v<T>, ...)`) stays for those.
49+
Float-only migration applies ONLY to algorithms that are already float-only; those follow
50+
`static_assert(std::is_floating_point_v<T>)` + `TEST_F` on `float`.
51+
52+
## Memory — quick reference
53+
54+
**Forbidden**: `new`/`delete`/`malloc`/`free`, `make_unique`/`make_shared`,
55+
`std::vector`/`string`/`deque`/`list`/`map`/`set`. Tests too. No recursion.
56+
57+
**Use instead**: `infra::BoundedVector<T>::WithMaxSize<N>`, `infra::BoundedString::WithStorage<N>`,
58+
`infra::BoundedDeque<T>::WithMaxSize<N>`, `infra::BoundedList<T>::WithMaxSize<N>`,
59+
`std::array<T,N>`, `std::optional<T>`.
60+
61+
## What NOT to do
62+
- No behavior/API change beyond removing duplication.
63+
- No new abstractions except extracting one that is already repeated.
64+
- Don't touch unrelated algorithms; don't strip `Q15`/`Q31`.
65+
- No `make_unique` anywhere, including tests.
66+
67+
**Terse**: no preamble/postamble, no narration; don't re-read files; batch reads; prefer targeted edits.

‎.github/agents/orchestrator.agent.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
description: "Triage development tasks in numerical-toolbox and route to planner, executor, or reviewer. Start here for any new feature, bug fix, or code review."
33
tools: [read, search, web, agent]
44
model: "Claude Sonnet 4.6"
5-
agents: [planner, executor, reviewer]
5+
agents: [planner, executor, reviewer, modernizer]
66
handoffs:
77
- label: "Plan Implementation"
88
agent: planner
@@ -13,6 +13,9 @@ handoffs:
1313
- label: "Review Code"
1414
agent: reviewer
1515
prompt: "Review the code changes described above against numerical-toolbox project standards."
16+
- label: "Modernize Legacy Algorithm"
17+
agent: modernizer
18+
prompt: "Refactor the pre-roadmap algorithm described above to reuse shared utilities and simplify tests, following numerical-toolbox conventions."
1619
---
1720

1821
Triage requests and route to the right specialist. Do NOT implement or plan yourself.
@@ -26,6 +29,7 @@ Triage requests and route to the right specialist. Do NOT implement or plan your
2629
- **planner** — new algorithm, architectural change, multi-file work
2730
- **executor** — clear bug fix, small change, existing plan
2831
- **reviewer** — review existing or recent code
32+
- **modernizer** — refactor/dedupe a pre-roadmap algorithm, reuse shared utilities, simplify tests
2933

3034
## Context to gather
3135
- Module: `analysis`, `windowing`, `control_analysis`, `controllers`, `dynamics`,

‎TESTING.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,15 @@ Canonical rules still apply ([AGENTS.md](AGENTS.md), [testing.instructions.md](.
7272
## Per-family detail
7373

7474
### 1. Signal transforms — `analysis/`
75-
`FastFourierTransformRadix2Impl`, `RealFft`, `DiscreteCosineTransform`, `GoertzelAlgorithm`,
75+
`FastFourierTransformRadix2Impl`, `RealFastFourierTransform`, `DiscreteCosineTransform`, `GoertzelAlgorithm`,
7676
`ConvolutionCorrelation`, `PowerDensitySpectrum`, `SignalDetectors`, `windowing/`.
7777

7878
- **M1 accuracy** — known transform pairs: δ[n] → flat spectrum; single sinusoid → single bin at its
7979
frequency with correct magnitude; DC → energy only in bin 0.
8080
- **M7 Parseval / energy** — `Σ|x|² ≈ (1/N)·Σ|X|²`; assert residual near 0.
8181
- **M1 linearity** — `F(a·x + b·y) = a·F(x) + b·F(y)`.
8282
- **M1 round-trip** — `Inverse(Forward(x)) ≈ x`; assert reconstruction RMSE.
83-
- **M7 symmetry** — real input ⇒ conjugate-symmetric spectrum (RealFft): `X[N-k] = conj(X[k])`.
83+
- **M7 symmetry** — real input ⇒ conjugate-symmetric spectrum (RealFastFourierTransform): `X[N-k] = conj(X[k])`.
8484
- **Convolution** — matches the direct sum; `x * δ = x`; commutativity; output length.
8585
- **PSD** — non-negative; total power = signal variance; spectral peak at the tone's frequency.
8686
- **Goertzel** — single-bin magnitude equals the full-FFT bin.

‎doc/analysis/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Signal analysis algorithms for frequency-domain decomposition and spectral estim
77
| Algorithm | Description |
88
|---------------------------------------------------------|--------------------------------------------------------------------------------------------------|
99
| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm |
10-
| [Real-Input FFT](RealFft.md) | Length-N real FFT via even/odd split into two N/2-point complex DFTs, halving compute and memory |
10+
| [Real-Input FFT](RealFastFourierTransform.md) | Length-N real FFT via even/odd split into two N/2-point complex DFTs, halving compute and memory |
1111
| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method |
1212
| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT |
1313
| [Signal Detectors](SignalDetectors.md) | Peak hold, zero-crossing counter, and RMS envelope detectors for real-time signal monitoring |
File renamed without changes.

‎numerical/analysis/CMakeLists.txt‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,17 @@ target_sources(numerical.analysis PRIVATE
1919
FastFourierTransformRadix2Impl.hpp
2020
GoertzelAlgorithm.hpp
2121
PowerDensitySpectrum.hpp
22-
RealFft.hpp
22+
RealFastFourierTransform.hpp
2323
SignalDetectors.hpp
2424
)
2525

2626
numerical_add_coverage_sources(numerical.analysis
2727
ConvolutionCorrelation.cpp
28+
DiscreteCosineTransform.cpp
2829
FastFourierTransformRadix2Impl.cpp
2930
GoertzelAlgorithm.cpp
3031
PowerDensitySpectrum.cpp
31-
RealFft.cpp
32+
RealFastFourierTransform.cpp
3233
SignalDetectors.cpp
3334
)
3435

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#include "numerical/analysis/DiscreteCosineTransform.hpp"
2+
#include "numerical/math/QNumber.hpp"
3+
4+
namespace analysis
5+
{
6+
template class DiscreteConsineTransform<float, 8>;
7+
template class DiscreteConsineTransform<math::Q15, 8>;
8+
template class DiscreteConsineTransform<math::Q31, 8>;
9+
}

‎numerical/analysis/DiscreteCosineTransform.hpp‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,18 @@
66

77
#include "infra/util/BoundedVector.hpp"
88
#include "numerical/analysis/FastFourierTransform.hpp"
9+
#include "numerical/math/CompilerOptimizations.hpp"
910
#include "numerical/math/ComplexNumber.hpp"
1011
#include <cmath>
12+
#include <numbers>
1113

1214
namespace analysis
1315
{
1416
template<typename QNumberType, std::size_t Length>
1517
class DiscreteConsineTransform
1618
{
1719
static_assert((Length & (Length - 1)) == 0, "DiscreteConsineTransform size must be a power of 2");
18-
static_assert(math::is_qnumber<QNumberType>::value || std::is_floating_point<QNumberType>::value,
20+
static_assert(math::is_qnumber<QNumberType>::value || std::is_floating_point_v<QNumberType>,
1921
"DiscreteConsineTransform can only be instantiated with math::QNumber types or floating point.");
2022

2123
public:
@@ -30,7 +32,6 @@ namespace analysis
3032
FastFourierTransform<QNumberType>& fft;
3133
typename infra::BoundedVector<QNumberType>::template WithMaxSize<Length> output;
3234
typename VectorComplex::template WithMaxSize<Length> complexBuffer;
33-
static constexpr float PI = 3.14159265358979323846f;
3435
};
3536

3637
// Implementation //
@@ -54,7 +55,7 @@ namespace analysis
5455

5556
for (std::size_t k = 1; k < Length; ++k)
5657
{
57-
float angle = -k * PI / (2.0f * Length);
58+
float angle = -static_cast<float>(k) * std::numbers::pi_v<float> / (2.0f * Length);
5859
float scale = 2.0f / std::sqrt(static_cast<float>(Length));
5960

6061
float real = math::ToFloat(fftResult[k].Real());
@@ -73,7 +74,7 @@ namespace analysis
7374

7475
for (std::size_t k = 1; k < Length; ++k)
7576
{
76-
float angle = k * PI / (2.0f * Length);
77+
float angle = static_cast<float>(k) * std::numbers::pi_v<float> / (2.0f * static_cast<float>(Length));
7778
float scale = std::sqrt(static_cast<float>(Length)) / 2.0f;
7879

7980
float value = math::ToFloat(input[k]) * scale;
@@ -82,4 +83,10 @@ namespace analysis
8283

8384
return fft.Inverse(complexBuffer);
8485
}
86+
87+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
88+
extern template class DiscreteConsineTransform<float, 8>;
89+
extern template class DiscreteConsineTransform<math::Q15, 8>;
90+
extern template class DiscreteConsineTransform<math::Q31, 8>;
91+
#endif
8592
}

0 commit comments

Comments
 (0)