|
| 1 | +# GitHub Copilot Instructions for Numerical Toolbox |
| 2 | + |
| 3 | +## Project Overview |
| 4 | + |
| 5 | +This is a numerical algorithms library providing digital signal processing (DSP), control algorithms, filters, optimizers, and estimators for embedded systems. The library is designed with strict performance and memory constraints, targeting resource-constrained microcontrollers while maintaining numerical accuracy and real-time determinism. |
| 6 | + |
| 7 | +## Repository Structure |
| 8 | + |
| 9 | +- **numerical/**: Core implementation of algorithms organized by domain: |
| 10 | + - `analysis/`: Signal analysis (FFT, PSD, DCT) |
| 11 | + - `controllers/`: Control algorithms (PID controllers) |
| 12 | + - `estimators/`: Estimation algorithms (Linear Regression, Yule-Walker) |
| 13 | + - `filters/`: Digital filters (FIR, IIR, Kalman) |
| 14 | + - `math/`: Mathematical foundations (QNumber, Matrix, Complex, Trigonometric functions) |
| 15 | + - `neural_network/`: Neural network components (layers, activations, optimizers) |
| 16 | + - `solvers/`: Numerical solvers (Levinson-Durbin) |
| 17 | + - `windowing/`: Window functions for signal processing |
| 18 | +- **examples/**: Demonstrates library usage with practical implementations |
| 19 | +- **doc/**: Comprehensive documentation for each algorithm with mathematical background |
| 20 | +- **embedded-infra-lib/**: Submodule containing infrastructure foundations and utilities for embedded systems |
| 21 | + |
| 22 | +## Critical Constraints |
| 23 | + |
| 24 | +### Memory Management |
| 25 | + |
| 26 | +- **NO HEAP ALLOCATION**: Avoid `new`, `delete`, `malloc`, `free`, and `std::make_unique/std::make_shared` at all costs |
| 27 | +- **NO DYNAMIC CONTAINERS**: Replace standard library containers that use dynamic allocation: |
| 28 | + - Use `infra::BoundedVector` instead of `std::vector` |
| 29 | + - Use `infra::BoundedString` instead of `std::string` |
| 30 | + - Use `infra::BoundedDeque` instead of `std::deque` |
| 31 | + - Use `infra::BoundedList` instead of `std::list` |
| 32 | +- **STATIC ALLOCATION**: All memory must be allocated at compile-time or on the stack |
| 33 | +- **AVOID RECURSION**: Stack usage must be predictable and minimal |
| 34 | + |
| 35 | +### Performance Requirements |
| 36 | + |
| 37 | +- **REAL-TIME CONSTRAINTS**: Code must execute deterministically within strict timing requirements |
| 38 | +- **MINIMIZE BRANCHING**: Reduce conditional statements in critical paths (e.g., FOC control loops) |
| 39 | +- **AVOID VIRTUAL CALLS IN ISR**: Virtual function calls add overhead; avoid in interrupt service routines |
| 40 | +- **INLINE CRITICAL CODE**: Use `inline` for small, frequently-called functions |
| 41 | +- **CONST CORRECTNESS**: Mark all non-mutating methods as `const` for compiler optimization |
| 42 | +- **PREFER CONSTEXPR**: Use `constexpr` for compile-time calculations when possible |
| 43 | + |
| 44 | +### Memory Consumption |
| 45 | + |
| 46 | +- **MINIMIZE FOOTPRINT**: Every byte counts in embedded systems |
| 47 | +- **USE FIXED-SIZE TYPES**: Prefer `uint8_t`, `int32_t`, etc., over `int` for predictable sizing |
| 48 | +- **PACK STRUCTURES**: Use pragma pack or compiler attributes when appropriate |
| 49 | +- **AVOID COPYING**: Use references and move semantics to prevent unnecessary copies |
| 50 | +- **MEASURE SIZE**: Be aware of sizeof() for all data structures |
| 51 | + |
| 52 | +## Code Organization Guidelines |
| 53 | + |
| 54 | +### Core Implementation (`numerical/`) |
| 55 | + |
| 56 | +Place code here when it is: |
| 57 | +- Generic mathematical and numerical algorithms |
| 58 | +- Signal processing and analysis functions |
| 59 | +- Control algorithms (PID, state-space controllers) |
| 60 | +- Digital filters (FIR, IIR, Kalman) |
| 61 | +- Estimators and solvers |
| 62 | +- Neural network components |
| 63 | +- Hardware-agnostic and reusable across projects |
| 64 | +- Organized by domain (analysis, controllers, filters, estimators, math, neural_network, solvers, windowing) |
| 65 | + |
| 66 | +### Examples (`examples/`) |
| 67 | + |
| 68 | +Place code here when it is: |
| 69 | +- Demonstrating proper usage of library components |
| 70 | +- Showing practical implementations and patterns |
| 71 | +- Providing working reference implementations |
| 72 | +- Testing algorithms in realistic scenarios |
| 73 | +- Each example should be self-contained and demonstrate specific features |
| 74 | + |
| 75 | +### Documentation (`doc/`) |
| 76 | + |
| 77 | +When implementing or modifying algorithms: |
| 78 | +- **ALWAYS UPDATE DOCUMENTATION**: Each algorithm must have corresponding documentation in `doc/` |
| 79 | +- Include mathematical background and theory |
| 80 | +- Provide implementation details and considerations |
| 81 | +- Add usage examples and expected behaviors |
| 82 | +- Document numerical properties and limitations |
| 83 | +- Keep documentation in sync with code changes |
| 84 | + |
| 85 | +## Coding Style and Patterns |
| 86 | + |
| 87 | +### Dependency Injection |
| 88 | + |
| 89 | +- Use constructor injection for dependencies |
| 90 | +- Pass interfaces, not concrete implementations when appropriate |
| 91 | +- Example: |
| 92 | + ```cpp |
| 93 | + namespace controllers |
| 94 | + { |
| 95 | + class PidController |
| 96 | + { |
| 97 | + public: |
| 98 | + PidController(PidTunings tunings, PidLimits limits) |
| 99 | + : tunings(tunings), limits(limits) {} |
| 100 | + private: |
| 101 | + PidTunings tunings; |
| 102 | + PidLimits limits; |
| 103 | + }; |
| 104 | + } |
| 105 | + ``` |
| 106 | +
|
| 107 | +### Error Handling |
| 108 | +
|
| 109 | +- Use `infra::Optional` for functions that may not return a value |
| 110 | +- Return error codes or status enums, not exceptions |
| 111 | +- Assert preconditions in debug builds with `assert()` or `really_assert()` |
| 112 | +
|
| 113 | +### Testing |
| 114 | +
|
| 115 | +- Write unit tests using GoogleTest |
| 116 | +- Test with multiple numeric types (float, Q15, Q31) using typed tests |
| 117 | +- Mock dependencies for isolation |
| 118 | +- Aim for high code coverage, especially in numerical algorithms |
| 119 | +- Verify numerical accuracy and stability |
| 120 | +- Test edge cases and boundary conditions |
| 121 | +- Example typed test pattern: |
| 122 | + ```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 | + |
| 129 | + TYPED_TEST(TestAlgorithm, computes_correct_result) |
| 130 | + { |
| 131 | + // Test with TypeParam |
| 132 | + } |
| 133 | + ``` |
| 134 | + |
| 135 | +## Common Patterns |
| 136 | + |
| 137 | +### Instead of this (BAD): |
| 138 | +```cpp |
| 139 | +std::vector<float> samples; |
| 140 | +samples.push_back(value); |
| 141 | + |
| 142 | +std::string message = "Error: " + errorCode; |
| 143 | + |
| 144 | +auto ptr = std::make_unique<Filter>(); |
| 145 | + |
| 146 | +// Using native types without consideration for fixed-point |
| 147 | +float coefficient = 0.5f; |
| 148 | +``` |
| 149 | + |
| 150 | +### Do this (GOOD): |
| 151 | +```cpp |
| 152 | +infra::BoundedVector<float>::WithMaxSize<100> samples; |
| 153 | +samples.push_back(value); |
| 154 | + |
| 155 | +infra::BoundedString::WithStorage<64> message; |
| 156 | +message = "Error: "; |
| 157 | + |
| 158 | +// Stack allocation |
| 159 | +Fir<float> filter; |
| 160 | + |
| 161 | +// Template for multiple numeric types |
| 162 | +template<typename T> |
| 163 | +class Algorithm |
| 164 | +{ |
| 165 | + T coefficient; // Works with float, Q15, Q31 |
| 166 | +}; |
| 167 | +``` |
| 168 | + |
| 169 | +## Additional Guidelines |
| 170 | + |
| 171 | +- **RAII**: Use Resource Acquisition Is Initialization for resource management |
| 172 | +- **INTERFACES**: Define interfaces (pure virtual classes) for testability and flexibility |
| 173 | +- **NAMESPACE**: Use appropriate namespaces by domain: |
| 174 | + - `analysis::` - Signal analysis algorithms |
| 175 | + - `controllers::` - Control system algorithms |
| 176 | + - `estimators::` - Estimation algorithms |
| 177 | + - `filters::passive::` - Passive filters (FIR, IIR) |
| 178 | + - `filters::active::` - Active filters (Kalman) |
| 179 | + - `math::` - Mathematical utilities and functions |
| 180 | + - `neural_network::` - Neural network components |
| 181 | + - `solvers::` - Numerical solvers |
| 182 | + - `windowing::` - Window functions |
| 183 | +- **SELF-DOCUMENTING CODE**: Write clear, self-explanatory code with descriptive names |
| 184 | +- **UNITS**: Be explicit about units (radians, Hz, samples, normalized) in variable names or comments |
| 185 | +- **NUMERICAL TYPES**: Support multiple numeric representations: |
| 186 | + - `float` for floating-point implementations |
| 187 | + - `math::Q15` for 16-bit fixed-point (Q15 format) |
| 188 | + - `math::Q31` for 32-bit fixed-point (Q31 format) |
| 189 | + - Use templates to support all three types when possible |
| 190 | + - Consider fixed-point for performance-critical code on microcontrollers without FPU |
| 191 | +- **ALGORITHM PROPERTIES**: Document and preserve: |
| 192 | + - Numerical stability characteristics |
| 193 | + - Computational complexity (O-notation) |
| 194 | + - Memory requirements |
| 195 | + - Range and precision limitations |
| 196 | + - Real-time suitability |
| 197 | +- **CODE FORMATTING**: Strictly adhere to the rules defined in `.clang-format` for consistent code style |
| 198 | +- **TEMPLATE USAGE**: Use templates for type-generic algorithms while maintaining type safety |
| 199 | +- **CONSTEXPR CALCULATIONS**: Maximize compile-time computation for lookup tables and constants |
| 200 | + |
| 201 | +## Build System |
| 202 | + |
| 203 | +- CMake-based build with presets for different targets |
| 204 | +- Support for host (simulation and testing) and embedded targets |
| 205 | +- Separate build configurations for Debug, Release, RelWithDebInfo |
| 206 | +- GoogleTest for unit testing |
| 207 | +- Optional build of examples via `NUMERICAL_TOOLBOX_BUILD_EXAMPLES` |
| 208 | +- Optional compiler optimizations via `NUMERICAL_TOOLBOX_ENABLE_OPTIMIZATIONS` |
| 209 | + |
| 210 | +## Version Control |
| 211 | + |
| 212 | +- Keep commits atomic and focused |
| 213 | +- Write clear commit messages |
| 214 | +- Update CHANGELOG.md according to release-please conventions |
| 215 | +- When modifying algorithms, update corresponding documentation in `doc/` |
| 216 | + |
| 217 | +## Numerical Algorithm Best Practices |
| 218 | + |
| 219 | +### Fixed-Point Arithmetic |
| 220 | + |
| 221 | +- **Q15 Format**: 16-bit signed fixed-point with 15 fractional bits |
| 222 | + - Range: [-1, 0.9999694824...] |
| 223 | + - Use for moderate precision requirements on 16-bit microcontrollers |
| 224 | +- **Q31 Format**: 32-bit signed fixed-point with 31 fractional bits |
| 225 | + - Range: [-1, 0.9999999995...] |
| 226 | + - Use for higher precision requirements on 32-bit microcontrollers |
| 227 | +- **Overflow Prevention**: Scale intermediate calculations to prevent overflow |
| 228 | +- **Saturation**: Use saturating arithmetic where appropriate |
| 229 | +- **Conversion**: Provide explicit conversion functions between formats |
| 230 | + |
| 231 | +### Algorithm Implementation Pattern |
| 232 | + |
| 233 | +When implementing a new algorithm: |
| 234 | + |
| 235 | +1. **Create interface/base class** if multiple implementations exist |
| 236 | +2. **Implement for float first** to validate mathematical correctness |
| 237 | +3. **Add Q15 and Q31 implementations** using the same interface |
| 238 | +4. **Write comprehensive tests** for all numeric types |
| 239 | +5. **Document in `doc/`** with: |
| 240 | + - Mathematical background |
| 241 | + - Implementation details |
| 242 | + - Usage examples |
| 243 | + - Numerical considerations (stability, range, precision) |
| 244 | +6. **Create example in `examples/`** demonstrating practical usage |
| 245 | +7. **Consider SIMD optimizations** where applicable using `math::SingleInstructionMultipleData` |
| 246 | + |
| 247 | +### Performance Optimization Guidelines |
| 248 | + |
| 249 | +- **Lookup Tables**: Use constexpr lookup tables for transcendental functions |
| 250 | +- **SIMD**: Leverage SIMD instructions when available (ARM NEON, CMSIS-DSP) |
| 251 | +- **Loop Unrolling**: Manually unroll small fixed-size loops for performance |
| 252 | +- **Branch Prediction**: Structure code to favor likely branches first |
| 253 | +- **Cache Locality**: Arrange data structures for sequential access patterns |
| 254 | +- **Compiler Hints**: Use `inline`, `constexpr`, and `[[likely]]`/`[[unlikely]]` attributes |
| 255 | +- **Measure Performance**: Profile before and after optimization |
| 256 | + |
| 257 | +### Numerical Stability |
| 258 | + |
| 259 | +- **Avoid Cancellation**: Restructure equations to avoid subtracting nearly equal numbers |
| 260 | +- **Scale Inputs**: Normalize inputs to expected ranges |
| 261 | +- **Accumulator Precision**: Use higher precision for accumulation (e.g., Q31 accumulator for Q15 data) |
| 262 | +- **Conditional Stability**: Document when algorithms require specific parameter ranges |
| 263 | +- **Test Stability**: Include tests with challenging numerical conditions |
| 264 | + |
| 265 | +### API Design Principles |
| 266 | + |
| 267 | +- **Type Safety**: Use strong types and templates to prevent misuse |
| 268 | +- **Zero-Cost Abstractions**: Design interfaces that compile to optimal code |
| 269 | +- **Compile-Time Configuration**: Use templates for sizes and types when possible |
| 270 | +- **Explicit Conversions**: Avoid implicit conversions between numeric types |
| 271 | +- **Const Correctness**: Mark all non-mutating operations as const |
| 272 | +- **Move Semantics**: Provide move constructors/assignment for large objects (even though we avoid dynamic allocation) |
| 273 | + |
| 274 | +## Compiler Optimizations and SIMD |
| 275 | + |
| 276 | +### Optimization Macros |
| 277 | + |
| 278 | +The library provides compiler-specific optimization hints: |
| 279 | + |
| 280 | +- **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 |
| 284 | +- **ALWAYS_INLINE_HOT**: Forces inlining for frequently-called hot-path code |
| 285 | +- **ALWAYS_INLINE**: Forces inlining without hot attribute |
| 286 | + |
| 287 | +### SIMD Support |
| 288 | + |
| 289 | +- Use `math::SingleInstructionMultipltData` interface for SIMD operations |
| 290 | +- Provides abstraction over ARM SIMD instructions (DSP, NEON) |
| 291 | +- Operations include: packed arithmetic, saturating operations, multiply-accumulate |
| 292 | +- Create test doubles (stubs) for host-based testing |
| 293 | +- Examples: `Pkhbt`, `Qadd16`, `Smlad`, `Smuad` for efficient fixed-point operations |
| 294 | + |
| 295 | +### Cross-Platform Considerations |
| 296 | + |
| 297 | +- Algorithms must work on both host (x86/x64) and target (ARM Cortex-M/A) platforms |
| 298 | +- Use conditional compilation for platform-specific optimizations |
| 299 | +- Provide portable fallback implementations |
| 300 | +- Test on host before deploying to target hardware |
| 301 | +- Be aware of endianness differences when relevant |
| 302 | + |
| 303 | +## Domain-Specific Guidelines |
| 304 | + |
| 305 | +### Signal Processing (Analysis, Filters, Windowing) |
| 306 | + |
| 307 | +- **FFT Implementation**: Prefer radix-2 FFT for power-of-2 sizes |
| 308 | +- **Window Functions**: Apply 0.9999 scaling factor to prevent fixed-point overflow |
| 309 | +- **Filter Design**: Document frequency response characteristics |
| 310 | +- **Coefficient Quantization**: Be aware of quantization effects in fixed-point filters |
| 311 | +- **Buffer Management**: Use `RecursiveBuffer` for delay lines and circular buffers |
| 312 | +- **Spectral Analysis**: Consider window selection for frequency vs. time resolution trade-offs |
| 313 | + |
| 314 | +### Control Systems (PID, State-Space) |
| 315 | + |
| 316 | +- **Sample Time**: Always specify and document the sampling period |
| 317 | +- **Tuning Parameters**: Provide reasonable default ranges and constraints |
| 318 | +- **Anti-Windup**: Implement integrator anti-windup for PID controllers |
| 319 | +- **Saturation**: Clamp outputs to prevent actuator saturation issues |
| 320 | +- **Derivative Filtering**: Consider derivative kick prevention techniques |
| 321 | +- **Discretization**: Document the discretization method used (Tustin, forward Euler, etc.) |
| 322 | + |
| 323 | +### Neural Networks |
| 324 | + |
| 325 | +- **Layer Composition**: Use fluent interface for building networks |
| 326 | +- **Activation Functions**: Provide both forward and derivative implementations |
| 327 | +- **Loss Functions**: Support common losses (MSE, MAE, cross-entropy) |
| 328 | +- **Optimization**: Implement gradient-based optimizers (gradient descent, Adam, etc.) |
| 329 | +- **Weight Initialization**: Provide proper initialization strategies |
| 330 | +- **Fixed-Point Constraints**: Be mindful of dynamic range in activations and weights |
| 331 | + |
| 332 | +### Estimators and Solvers |
| 333 | + |
| 334 | +- **Matrix Operations**: Use efficient algorithms for common operations (LU, Cholesky, etc.) |
| 335 | +- **Numerical Conditioning**: Check and document condition number requirements |
| 336 | +- **Iterative Methods**: Provide convergence criteria and maximum iteration limits |
| 337 | +- **System Identification**: Support AR, MA, ARMA model estimation |
| 338 | +- **Kalman Filtering**: Implement measurement and process noise covariance updates |
0 commit comments