diff --git a/doc/analysis/FrequencyResponse.md b/doc/analysis/FrequencyResponse.md new file mode 100644 index 00000000..d692c229 --- /dev/null +++ b/doc/analysis/FrequencyResponse.md @@ -0,0 +1,82 @@ +# Frequency Response + +## Overview & Motivation + +The frequency response $H(e^{j\omega})$ characterizes how a discrete-time linear system (filter) modifies the amplitude and phase of each frequency component in a signal. Computing and plotting the frequency response (Bode plot) is essential for verifying filter designs, understanding system behavior, and tuning parameters. This implementation evaluates the transfer function at logarithmically spaced frequencies, producing magnitude (dB) and phase (degrees) curves. + +## Mathematical Theory + +### Transfer Function Evaluation + +Given a filter with feedforward coefficients $\{b_i\}_{i=0}^{P-1}$ and feedback coefficients $\{a_i\}_{i=0}^{Q-1}$, the frequency response at angular frequency $\omega$ is: + +$$H(e^{j\omega}) = \frac{\sum_{i=0}^{P-1} b_i \cdot e^{-j\omega i}}{\sum_{i=0}^{Q-1} a_i \cdot e^{-j\omega i}}$$ + +For FIR filters, the denominator reduces to $a_0 = 1$. + +### Magnitude and Phase + +From the complex-valued response: + +$$|H(e^{j\omega})| = \sqrt{\text{Re}(H)^2 + \text{Im}(H)^2}$$ + +$$\text{Magnitude (dB)} = 20 \log_{10} |H(e^{j\omega})|$$ + +$$\text{Phase (degrees)} = \frac{180}{\pi} \cdot \arg(H(e^{j\omega}))$$ + +### Frequency Grid + +Frequencies are evaluated on a logarithmic grid from $f_s / N$ to $f_s / 2$ (Nyquist), where $f_s$ is the sampling frequency and $N$ is the number of evaluation points. The angular frequency at each point is: + +$$\omega_k = \frac{2\pi f_k}{f_s}$$ + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|--------------------|--------|------------------------------------------| +| Average | $O(N \cdot (P+Q))$ | $O(N)$ | $N$ frequency points, $P+Q$ coefficients | + +## Step-by-Step Walkthrough + +Given a simple first-order low-pass FIR filter with $b = [0.5, 0.5]$, $a = [1.0]$, and $f_s = 100$ Hz, evaluated at $f = 10$ Hz: + +1. Compute $\omega = 2\pi \cdot 10 / 100 = 0.2\pi$ +2. Numerator: $0.5 \cdot e^{0} + 0.5 \cdot e^{-j0.2\pi} = 0.5 + 0.5(\cos(0.2\pi) - j\sin(0.2\pi))$ + - $= 0.5 + 0.5(0.809 - j0.588) = 0.905 - j0.294$ +3. Denominator: $1.0$ +4. $|H| = \sqrt{0.905^2 + 0.294^2} = 0.952$ +5. Magnitude: $20\log_{10}(0.952) = -0.43$ dB +6. Phase: $\arctan(-0.294/0.905) = -18°$ + +## Pitfalls & Edge Cases + +- **Zero denominator**: If the denominator evaluates to zero at a frequency, the implementation sets it to 1.0 to avoid division by zero. This produces a meaningful (if approximate) result near resonances. +- **QNumber conversion**: When coefficients are in Q15/Q31 format, they are converted to float via `math::ToFloat()` before evaluation. This ensures sufficient dynamic range for the complex arithmetic. +- **Logarithmic spacing**: Very low frequencies near DC may have sparse coverage. The lowest evaluated frequency is $f_s / N$. +- **Phase wrapping**: The `std::arg` function returns phase in $(-\pi, \pi]$. Phase unwrapping is not performed. + +## Variants & Generalizations + +- **Linear frequency spacing**: Alternative to logarithmic spacing for uniform frequency resolution. +- **Zero-pole form**: Evaluate directly from pole-zero locations rather than polynomial coefficients. +- **Chirp z-transform**: Generalization that evaluates the z-transform along arbitrary paths in the z-plane. + +## Applications + +- Verifying filter coefficient designs match the desired specification +- Bode plot generation for stability analysis +- Comparing filter topologies (FIR vs. IIR, different orders) +- System identification validation + +## Connections to Other Algorithms + +- **FIR / IIR Filters**: The frequency response evaluates the transfer functions implemented by `Fir` and `Iir` filters. +- **FFT**: The DFT of a zero-padded impulse response produces the frequency response at uniformly spaced frequencies. This class generalizes to arbitrary frequency points. +- **Root Locus**: Both frequency response and root locus analyze the same transfer function from complementary perspectives (frequency domain vs. pole-zero domain). +- **Power Density Spectrum**: PDS estimates the spectral content of a signal; frequency response characterizes the system that shapes it. + +## References & Further Reading + +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapters 5–6. +- Proakis, J.G. and Manolakis, D.G., *Digital Signal Processing: Principles, Algorithms, and Applications*, 4th ed., Pearson, 2006 — Chapter 6. +- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapter 21. diff --git a/doc/estimators/RecursiveLeastSquares.md b/doc/estimators/RecursiveLeastSquares.md new file mode 100644 index 00000000..e69957a5 --- /dev/null +++ b/doc/estimators/RecursiveLeastSquares.md @@ -0,0 +1,94 @@ +# Recursive Least Squares (RLS) + +## Overview & Motivation + +Recursive Least Squares (RLS) is an online parameter estimation algorithm that incrementally updates a least-squares fit as new data arrives, without reprocessing past observations. It converges faster than gradient-descent methods (e.g., LMS) and is well-suited for real-time system identification and adaptive filtering on embedded systems. + +## Mathematical Theory + +### Problem Setting + +Given a linear model $y = \mathbf{x}^T \boldsymbol{\theta} + \epsilon$, where $\mathbf{x} \in \mathbb{R}^p$ is the regressor, $\boldsymbol{\theta} \in \mathbb{R}^p$ are the unknown parameters, and $\epsilon$ is noise, RLS minimizes the exponentially weighted cost: + +$$J(\boldsymbol{\theta}) = \sum_{k=1}^{n} \lambda^{n-k} (y_k - \mathbf{x}_k^T \boldsymbol{\theta})^2$$ + +where $\lambda \in (0, 1]$ is the forgetting factor. + +### Update Equations + +Given a new observation $(\mathbf{x}, y)$: + +1. **Gain vector**: $\mathbf{g} = P \mathbf{x}$ +2. **Denominator**: $d = \lambda + \mathbf{x}^T P \mathbf{x}$ +3. **Innovation (pre-update error)**: $e = y - \mathbf{x}^T \hat{\boldsymbol{\theta}}$ +4. **Parameter update**: $\hat{\boldsymbol{\theta}} \leftarrow \hat{\boldsymbol{\theta}} + \frac{\mathbf{g} \cdot e}{d}$ +5. **Covariance update**: $P \leftarrow \frac{1}{\lambda}\left(P - \frac{\mathbf{g} \mathbf{g}^T}{d}\right)$ + +### Forgetting Factor + +- $\lambda = 1$: Full memory — equivalent to batch least squares with all past data equally weighted. +- $\lambda < 1$: Exponential forgetting — recent data is weighted more heavily, enabling tracking of time-varying systems. +- Typical values: $0.95 \leq \lambda \leq 1.0$. + +### Convergence Evaluation + +The implementation provides convergence diagnostics via `EstimationMetrics`: +- **Innovation**: Pre-update prediction error magnitude +- **Residual**: Post-update prediction error magnitude +- **Uncertainty**: Trace of the covariance matrix $P$ (overall parameter uncertainty) + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|----------|----------|----------------------------------------| +| Average | $O(p^2)$ | $O(p^2)$ | Matrix-vector products + outer product | + +Per-update cost is $O(p^2)$ for $p$ parameters, dominated by the covariance update. This is significantly cheaper than the $O(p^3)$ batch solution via matrix inversion. + +## Step-by-Step Walkthrough + +Estimating the slope of $y = 2x$ with RLS ($p = 2$: bias + slope, $\lambda = 1$): + +| Step | $\mathbf{x}$ | $y$ | $\hat{\theta}_0$ (bias) | $\hat{\theta}_1$ (slope) | Innovation | +|------|--------------|-----|-------------------------|--------------------------|------------| +| Init | — | — | 0.0 | 0.0 | — | +| 1 | [1, 1] | 2 | 1.0 | 1.0 | 2.0 | +| 2 | [1, 2] | 4 | 0.0 | 2.0 | 1.0 | +| 3 | [1, 3] | 6 | 0.0 | 2.0 | 0.0 | + +Convergence is achieved in 2 steps for this noiseless system. + +## Pitfalls & Edge Cases + +- **Covariance blow-up**: With $\lambda < 1$ and insufficient excitation, the covariance matrix $P$ can grow unbounded. Monitor the uncertainty metric and consider covariance resetting. +- **Numerical conditioning**: The covariance update can lose symmetry and positive-definiteness due to floating-point errors. For long-running applications, consider using the Joseph form: $P \leftarrow (I - K\mathbf{x}^T)P(I - K\mathbf{x}^T)^T + K K^T / \lambda$. +- **Initial covariance**: A large initial $P$ (e.g., $\alpha I$ with $\alpha = 100$) gives fast initial convergence but higher initial sensitivity. A small $P$ gives conservative updates. +- **Regressor scaling**: Large differences in regressor magnitudes can cause numerical issues. Normalize inputs when possible. + +## Variants & Generalizations + +- **Weighted RLS**: Use a general weighting matrix instead of scalar forgetting. +- **QR-decomposition RLS**: Better numerical stability by avoiding explicit covariance updates. +- **Kalman filter**: RLS is equivalent to a steady-state Kalman filter for the linear regression problem. +- **Regularized RLS**: Add a regularization term $\mu \|\boldsymbol{\theta}\|^2$ to prevent overfitting. + +## Applications + +- Online system identification for adaptive control +- Adaptive noise cancellation +- Channel equalization in communications +- Real-time parameter tracking in engine/motor control +- Sensor calibration + +## Connections to Other Algorithms + +- **Linear Regression**: Batch (offline) version of the same problem. Linear regression solves via matrix inversion; RLS updates incrementally. +- **Yule-Walker**: Both estimate AR model parameters, but Yule-Walker uses autocorrelation statistics (offline) while RLS processes samples sequentially. +- **Kalman Filter**: RLS is a special case of the Kalman filter where the state transition is identity and the process noise is zero. +- **Gradient Descent**: LMS/gradient descent is a simpler adaptive algorithm with $O(p)$ cost but slower convergence compared to RLS's $O(p^2)$. + +## References & Further Reading + +- Haykin, S., *Adaptive Filter Theory*, 5th ed., Pearson, 2014 — Chapter 9. +- Ljung, L., *System Identification: Theory for the User*, 2nd ed., Prentice Hall, 1999 — Chapter 11. +- Åström, K.J. and Wittenmark, B., *Adaptive Control*, 2nd ed., Dover, 2008 — Chapter 2. diff --git a/doc/filters/active/KalmanFilter.md b/doc/filters/active/KalmanFilter.md index 0b6f7d17..c5356de4 100644 --- a/doc/filters/active/KalmanFilter.md +++ b/doc/filters/active/KalmanFilter.md @@ -40,7 +40,7 @@ $$y_k = z_k - H_k \hat{x}_k^- \qquad \text{(innovation)}$$ $$S_k = H_k P_k^- H_k^T + R_k \qquad \text{(innovation covariance)}$$ $$K_k = P_k^- H_k^T S_k^{-1} \qquad \text{(Kalman gain)}$$ $$\hat{x}_k = \hat{x}_k^- + K_k y_k \qquad \text{(state update)}$$ -$$P_k = (I - K_k H_k) P_k^- \qquad \text{(covariance update)}$$ +$$P_k = (I - K_k H_k) P_k^- (I - K_k H_k)^T + K_k R_k K_k^T \qquad \text{(Joseph form covariance update)}$$ ### Optimality diff --git a/doc/filters/passive/Fir.md b/doc/filters/passive/Fir.md new file mode 100644 index 00000000..2b924e53 --- /dev/null +++ b/doc/filters/passive/Fir.md @@ -0,0 +1,85 @@ +# Finite Impulse Response (FIR) Filter + +## Overview & Motivation + +A Finite Impulse Response (FIR) filter is a discrete-time filter whose impulse response has a finite duration. FIR filters are inherently stable, have linear phase properties (when symmetric), and are straightforward to design and implement. They are the default choice for applications requiring guaranteed stability and predictable phase behavior. + +## Mathematical Theory + +### Core Definition + +A causal FIR filter of order $N-1$ (with $N$ taps) computes the output as a weighted sum of the current and past inputs (discrete convolution): + +$$y[n] = \sum_{i=0}^{N-1} b_i \cdot x[n-i]$$ + +where: +- $b_i$ are the filter coefficients (tap weights) +- $x[n-i]$ are the current and $N-1$ most recent input samples +- $N$ is the number of taps (filter length) + +### Transfer Function + +In the z-domain, the FIR filter transfer function is a polynomial in $z^{-1}$: + +$$H(z) = \sum_{i=0}^{N-1} b_i z^{-i}$$ + +Since the denominator is unity, FIR filters have all poles at the origin and are always stable. + +### Frequency Response + +Evaluating on the unit circle ($z = e^{j\omega}$): + +$$H(e^{j\omega}) = \sum_{i=0}^{N-1} b_i e^{-j\omega i}$$ + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|--------|--------|------------------------------------| +| Best | $O(N)$ | $O(N)$ | Disabled (passthrough) | +| Average | $O(N)$ | $O(N)$ | Convolution sum | +| Worst | $O(N)$ | $O(N)$ | Same — no data-dependent branching | + +Time is per sample. Space is for the coefficient and delay line buffers. + +## Step-by-Step Walkthrough + +Given a 3-tap FIR filter with coefficients $b = [0.25, 0.5, 0.25]$ and input sequence $x = [1.0, 2.0, 3.0, 4.0]$: + +| $n$ | $x[n]$ | $x[n-1]$ | $x[n-2]$ | $y[n] = 0.25 x[n] + 0.5 x[n-1] + 0.25 x[n-2]$ | +|-----|--------|----------|----------|-----------------------------------------------| +| 0 | 1.0 | 0.0 | 0.0 | 0.25 | +| 1 | 2.0 | 1.0 | 0.0 | 1.0 | +| 2 | 3.0 | 2.0 | 1.0 | 2.0 | +| 3 | 4.0 | 3.0 | 2.0 | 3.0 | + +## Pitfalls & Edge Cases + +- **Group delay**: A linear-phase FIR filter introduces a delay of $(N-1)/2$ samples. This must be accounted for in real-time control loops. +- **Fixed-point overflow**: When using Q15 or Q31 arithmetic, ensure the sum of absolute coefficient values does not exceed 1.0 to prevent saturation. +- **Coefficient quantization**: Converting floating-point coefficients to fixed-point can distort the frequency response, especially for narrowband filters with large $N$. +- **Initial transient**: The first $N-1$ outputs are computed with zero-padded history; these may not be representative of steady-state behavior. + +## Variants & Generalizations + +- **Windowed design**: FIR coefficients are often designed by applying a window function (Hamming, Hann, Blackman) to the ideal impulse response. +- **Equiripple (Parks-McClellan)**: Minimax optimal design that minimizes the maximum deviation from the desired response. +- **Polyphase decomposition**: For efficient multirate (decimation/interpolation) implementations. + +## Applications + +- Low-pass, high-pass, band-pass, and band-stop filtering +- Anti-aliasing before downsampling +- Matched filtering in communications +- Moving average smoothing (special case with equal coefficients) + +## Connections to Other Algorithms + +- **IIR Filter**: IIR filters achieve sharper cutoffs with fewer coefficients but sacrifice guaranteed stability and linear phase. +- **FFT**: For large $N$, the convolution can be computed more efficiently via FFT-based overlap-add/save methods. +- **Window Functions**: Window functions from the `windowing` module are used in FIR coefficient design. + +## References & Further Reading + +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapter 7. +- Parks, T.W. and Burrus, C.S., *Digital Filter Design*, Wiley, 1987. +- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapters 14–16. diff --git a/doc/filters/passive/Iir.md b/doc/filters/passive/Iir.md new file mode 100644 index 00000000..de88bfbc --- /dev/null +++ b/doc/filters/passive/Iir.md @@ -0,0 +1,85 @@ +# Infinite Impulse Response (IIR) Filter + +## Overview & Motivation + +An Infinite Impulse Response (IIR) filter uses feedback from its own past outputs to achieve a desired frequency response. IIR filters can match the selectivity of high-order FIR filters using far fewer coefficients, making them efficient for resource-constrained embedded systems. The trade-off is potential instability and nonlinear phase. + +## Mathematical Theory + +### Core Definition + +A causal IIR filter with $P$ feedforward coefficients and $Q$ feedback coefficients computes: + +$$y[n] = \sum_{i=0}^{P-1} b_i \cdot x[n-i] + \sum_{i=0}^{Q-1} a_i \cdot y[n-i]$$ + +where: +- $b_i$ are the feedforward (numerator) coefficients +- $a_i$ are the feedback (denominator) coefficients +- $x[n-i]$ are past input samples +- $y[n-i]$ are past output samples + +**Sign convention**: The implementation uses addition for the feedback term. This means the feedback coefficients $a_i$ must be provided with the appropriate sign (negated relative to the standard form $y[n] = \sum b_i x[n-i] - \sum a_i y[n-i]$). + +### Transfer Function + +$$H(z) = \frac{\sum_{i=0}^{P-1} b_i z^{-i}}{1 - \sum_{i=0}^{Q-1} a_i z^{-i}}$$ + +### Stability Criterion + +The filter is stable if and only if all poles of $H(z)$ lie strictly inside the unit circle ($|z| < 1$). This must be verified at design time. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|----------|----------|---------------------------------| +| Best | $O(P+Q)$ | $O(P+Q)$ | Disabled (passthrough) | +| Average | $O(P+Q)$ | $O(P+Q)$ | Feedforward + feedback sums | +| Worst | $O(P+Q)$ | $O(P+Q)$ | Same — sequential, no branching | + +Time is per sample. Space stores coefficient and delay line buffers. + +## Step-by-Step Walkthrough + +Given a first-order IIR (1 feedforward, 1 feedback) with $b_0 = 0.5$, $a_0 = 0.3$ and input $x = [1.0, 0.0, 0.0]$: + +| $n$ | $x[n]$ | $y[n-1]$ | $y[n] = 0.5 \cdot x[n] + 0.3 \cdot y[n-1]$ | +|-----|--------|----------|--------------------------------------------| +| 0 | 1.0 | 0.0 | 0.5 | +| 1 | 0.0 | 0.5 | 0.15 | +| 2 | 0.0 | 0.15 | 0.045 | + +The output decays exponentially — characteristic of IIR filters with $|a_0| < 1$. + +## Pitfalls & Edge Cases + +- **Instability**: If any pole has magnitude $\geq 1$, the output grows without bound. Always verify pole locations before deployment. +- **Coefficient quantization**: Fixed-point representation of feedback coefficients can shift pole locations, potentially pushing them outside the unit circle. +- **Limit cycles**: In fixed-point implementations, small-signal oscillations can occur due to quantization of the feedback path. +- **Overflow in feedback**: The recursive nature means accumulated rounding errors compound over time. Consider using higher-precision accumulators (Q31 for Q15 data). +- **Initial conditions**: Nonzero initial conditions in the output buffer affect the transient response. + +## Variants & Generalizations + +- **Direct Form I**: Separate feedforward and feedback computation (as implemented). +- **Direct Form II**: Reduces memory by sharing a single delay line, but is more sensitive to quantization. +- **Cascade (Second-Order Sections)**: Factor the transfer function into biquad sections for improved numerical stability. +- **Lattice structure**: Alternative topology with better quantization properties. + +## Applications + +- Butterworth, Chebyshev, and elliptic filter implementations +- DC removal (high-pass with pole near $z = 1$) +- Resonant filtering and equalization +- Control loop compensation filters + +## Connections to Other Algorithms + +- **FIR Filter**: FIR is a special case of IIR with $Q = 0$ (no feedback). FIR is always stable but requires more coefficients for comparable selectivity. +- **Frequency Response**: The `FrequencyResponse` class evaluates $H(e^{j\omega})$ for both FIR and IIR filters by accepting both $b$ and $a$ coefficient arrays. +- **Kalman Filter**: Kalman filters can be viewed as optimal adaptive IIR filters with time-varying coefficients. + +## References & Further Reading + +- Oppenheim, A.V. and Schafer, R.W., *Discrete-Time Signal Processing*, 3rd ed., Pearson, 2009 — Chapter 7. +- Mitra, S.K., *Digital Signal Processing: A Computer-Based Approach*, 4th ed., McGraw-Hill, 2010 — Chapters 6–8. +- Smith, S.W., *The Scientist and Engineer's Guide to Digital Signal Processing*, California Technical Publishing, 1997 — Chapter 19. diff --git a/numerical/analysis/CMakeLists.txt b/numerical/analysis/CMakeLists.txt index b932d2aa..20e00711 100644 --- a/numerical/analysis/CMakeLists.txt +++ b/numerical/analysis/CMakeLists.txt @@ -23,6 +23,7 @@ target_sources(numerical.analysis PRIVATE numerical_add_coverage_sources(numerical.analysis FastFourierTransformRadix2Impl.cpp FrequencyResponse.cpp + PowerDensitySpectrum.cpp RootLocus.cpp ) diff --git a/numerical/analysis/DiscreteCosineTransform.hpp b/numerical/analysis/DiscreteCosineTransform.hpp index 78d26987..ee8d96f1 100644 --- a/numerical/analysis/DiscreteCosineTransform.hpp +++ b/numerical/analysis/DiscreteCosineTransform.hpp @@ -1,5 +1,8 @@ -#ifndef ANALYSIS_DISCRETE_COSINE_TRANSFORM_HPP -#define ANALYSIS_DISCRETE_COSINE_TRANSFORM_HPP +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif #include "infra/util/BoundedVector.hpp" #include "numerical/analysis/FastFourierTransform.hpp" @@ -41,7 +44,9 @@ namespace analysis } template - typename DiscreteConsineTransform::VectorReal& DiscreteConsineTransform::Forward(VectorReal& input) + OPTIMIZE_FOR_SPEED + typename DiscreteConsineTransform::VectorReal& + DiscreteConsineTransform::Forward(VectorReal& input) { auto& fftResult = fft.Forward(input); @@ -78,5 +83,3 @@ namespace analysis return fft.Inverse(complexBuffer); } } - -#endif diff --git a/numerical/analysis/FastFourierTransform.hpp b/numerical/analysis/FastFourierTransform.hpp index 431b0e52..fd8de657 100644 --- a/numerical/analysis/FastFourierTransform.hpp +++ b/numerical/analysis/FastFourierTransform.hpp @@ -1,6 +1,4 @@ -#ifndef ANALYSIS_FAST_FOURIER_TRANSFORM_HPP -#define ANALYSIS_FAST_FOURIER_TRANSFORM_HPP - +#pragma once #include "infra/util/BoundedVector.hpp" #include "numerical/math/ComplexNumber.hpp" #include "numerical/math/QNumber.hpp" @@ -49,5 +47,3 @@ namespace analysis } }; } - -#endif diff --git a/numerical/analysis/FastFourierTransformRadix2Impl.hpp b/numerical/analysis/FastFourierTransformRadix2Impl.hpp index ca15d693..5388ec15 100644 --- a/numerical/analysis/FastFourierTransformRadix2Impl.hpp +++ b/numerical/analysis/FastFourierTransformRadix2Impl.hpp @@ -1,5 +1,10 @@ -#ifndef ANALYSIS_FAST_FOURIER_TRANSFORM_RADIX_2_IMPL_HPP -#define ANALYSIS_FAST_FOURIER_TRANSFORM_RADIX_2_IMPL_HPP +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "infra/util/BoundedVector.hpp" #include "numerical/analysis/FastFourierTransform.hpp" @@ -54,7 +59,7 @@ namespace analysis } template - void FastFourierTransformRadix2Impl::Calculate() + OPTIMIZE_FOR_SPEED void FastFourierTransformRadix2Impl::Calculate() { for (auto step = 2; step <= Length; step *= 2) { @@ -81,7 +86,9 @@ namespace analysis } template - typename FastFourierTransformRadix2Impl::VectorComplex& FastFourierTransformRadix2Impl::Forward(FastFourierTransformRadix2Impl::VectorReal& input) + OPTIMIZE_FOR_SPEED + typename FastFourierTransformRadix2Impl::VectorComplex& + FastFourierTransformRadix2Impl::Forward(FastFourierTransformRadix2Impl::VectorReal& input) { ResetFrequencyDomain(); @@ -136,5 +143,3 @@ namespace analysis extern template class FastFourierTransformRadix2Impl; #endif } - -#endif diff --git a/numerical/analysis/FrequencyResponse.hpp b/numerical/analysis/FrequencyResponse.hpp index 3bdc8ac0..80232ddf 100644 --- a/numerical/analysis/FrequencyResponse.hpp +++ b/numerical/analysis/FrequencyResponse.hpp @@ -1,5 +1,10 @@ -#ifndef ANALYSIS_FREQUENCY_RESPONSE_HPP -#define ANALYSIS_FREQUENCY_RESPONSE_HPP +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "infra/util/BoundedVector.hpp" #include "infra/util/MemoryRange.hpp" @@ -43,7 +48,9 @@ namespace analysis } template - std::tuple::Vector, typename FrequencyResponse::Vector, typename FrequencyResponse::Vector> FrequencyResponse::Calculate() + OPTIMIZE_FOR_SPEED + std::tuple::Vector, typename FrequencyResponse::Vector, typename FrequencyResponse::Vector> + FrequencyResponse::Calculate() { const auto maxSize = static_cast(response.max_size()); const auto fstart = static_cast(sampleFrequency / maxSize); @@ -82,5 +89,3 @@ namespace analysis extern template class FrequencyResponse; #endif } - -#endif diff --git a/numerical/analysis/PowerDensitySpectrum.cpp b/numerical/analysis/PowerDensitySpectrum.cpp new file mode 100644 index 00000000..0f3188ea --- /dev/null +++ b/numerical/analysis/PowerDensitySpectrum.cpp @@ -0,0 +1,7 @@ +#include "numerical/analysis/PowerDensitySpectrum.hpp" +#include "numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp" + +namespace analysis +{ + template class PowerSpectralDensity, test::TwiddleFactorsStub, 50>; +} diff --git a/numerical/analysis/PowerDensitySpectrum.hpp b/numerical/analysis/PowerDensitySpectrum.hpp index 0e9df851..b7c365a7 100644 --- a/numerical/analysis/PowerDensitySpectrum.hpp +++ b/numerical/analysis/PowerDensitySpectrum.hpp @@ -1,22 +1,29 @@ -#ifndef ANALYSIS_POWER_SPECTRAL_DENSITY_HPP -#define ANALYSIS_POWER_SPECTRAL_DENSITY_HPP +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif -#include "infra/util/ReallyAssert.hpp" #include "numerical/analysis/FastFourierTransform.hpp" +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/ComplexNumber.hpp" #include "numerical/math/QNumber.hpp" #include "numerical/windowing/Windowing.hpp" +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD +#include "numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp" +#endif + namespace analysis { template class PowerSpectralDensity { - static_assert(math::is_qnumber::value || - std::is_floating_point::value, + static_assert(math::is_qnumber_v || + std::is_floating_point_v, "PowerSpectralDensity can only be instantiated with math::QNumber types."); - static_assert(std::is_base_of, Fft>::value, + static_assert(std::is_base_of_v, Fft>, "Fft has to be derived from FastFourierTransform."); static_assert((SegmentSize % 2) == 0, @@ -35,7 +42,7 @@ namespace analysis using VectorReal = typename FastFourierTransform::VectorReal; using VectorComplex = typename FastFourierTransform::VectorComplex; - VectorReal& Calculate(const VectorReal& input) + OPTIMIZE_FOR_SPEED VectorReal& Calculate(const VectorReal& input) { really_assert(input.size() >= SegmentSize); @@ -61,7 +68,7 @@ namespace analysis } private: - QNumberType MagnitudeSquared(math::Complex& data) + QNumberType MagnitudeSquared(const math::Complex& data) const { return data.Real() * data.Real() + data.Imaginary() * data.Imaginary(); } @@ -91,6 +98,8 @@ namespace analysis typename infra::BoundedVector::template WithMaxSize segment; typename FastFourierTransform::VectorReal::template WithMaxSize y; }; -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class PowerSpectralDensity, test::TwiddleFactorsStub, 50>; #endif +} diff --git a/numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp b/numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp new file mode 100644 index 00000000..a5c1e473 --- /dev/null +++ b/numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include "numerical/analysis/FastFourierTransform.hpp" +#include "numerical/windowing/Windowing.hpp" + +namespace analysis::test +{ + template + class WindowStub + : public windowing::Window + { + public: + QNumberType operator()(std::size_t n, std::size_t order) override + { + return QNumberType(0.5f); + } + + QNumberType Power(std::size_t order) override + { + return QNumberType(0.25f); + } + }; + + template + class TwiddleFactorsStub + : public analysis::TwiddleFactors + { + public: + math::Complex& operator[](std::size_t n) override + { + static math::Complex factor(QNumberType(1.0f), QNumberType(0.0f)); + return factor; + } + }; + + template + class FftStub + : public analysis::FastFourierTransform + { + public: + using VectorComplex = typename analysis::FastFourierTransform::VectorComplex; + using VectorReal = typename analysis::FastFourierTransform::VectorReal; + + explicit FftStub(analysis::TwiddleFactors&) + {} + + VectorComplex& Forward(VectorReal& input) override + { + result.clear(); + + for (std::size_t i = 0; i < Length; ++i) + { + if (i == 0) + result.push_back(math::Complex(QNumberType(0.5f), QNumberType(0.0f))); + else + result.push_back(math::Complex(QNumberType(0.0f), QNumberType(0.0f))); + } + return result; + } + + VectorReal& Inverse(VectorComplex& input) override + { + timeResult.clear(); + for (std::size_t i = 0; i < Length; ++i) + timeResult.push_back(QNumberType(0.0f)); + return timeResult; + } + + private: + typename VectorComplex::template WithMaxSize result; + typename VectorReal::template WithMaxSize timeResult; + }; +} diff --git a/numerical/analysis/test/TestPowerDensitySpectrum.cpp b/numerical/analysis/test/TestPowerDensitySpectrum.cpp index d16fb429..56d270b1 100644 --- a/numerical/analysis/test/TestPowerDensitySpectrum.cpp +++ b/numerical/analysis/test/TestPowerDensitySpectrum.cpp @@ -1,77 +1,10 @@ -#include "numerical/analysis/FastFourierTransform.hpp" #include "numerical/analysis/PowerDensitySpectrum.hpp" +#include "numerical/analysis/test/PowerDensitySpectrumTestSupport.hpp" #include "numerical/math/Tolerance.hpp" -#include "numerical/windowing/Windowing.hpp" #include "gmock/gmock.h" namespace { - template - class WindowStub - : public windowing::Window - { - public: - QNumberType operator()(std::size_t n, std::size_t order) override - { - return QNumberType(0.5f); - } - - QNumberType Power(std::size_t order) override - { - return QNumberType(0.25f); - } - }; - - template - class TwiddleFactorsStub - : public analysis::TwiddleFactors - { - public: - math::Complex& operator[](std::size_t n) override - { - static math::Complex factor(QNumberType(1.0f), QNumberType(0.0f)); - return factor; - } - }; - - template - class FftStub - : public analysis::FastFourierTransform - { - public: - using VectorComplex = typename analysis::FastFourierTransform::VectorComplex; - using VectorReal = typename analysis::FastFourierTransform::VectorReal; - - explicit FftStub(analysis::TwiddleFactors&) - {} - - VectorComplex& Forward(VectorReal& input) override - { - result.clear(); - - for (std::size_t i = 0; i < Length; ++i) - { - if (i == 0) - result.push_back(math::Complex(QNumberType(0.5f), QNumberType(0.0f))); - else - result.push_back(math::Complex(QNumberType(0.0f), QNumberType(0.0f))); - } - return result; - } - - VectorReal& Inverse(VectorComplex& input) override - { - timeResult.clear(); - for (std::size_t i = 0; i < Length; ++i) - timeResult.push_back(QNumberType(0.0f)); - return timeResult; - } - - private: - typename VectorComplex::template WithMaxSize result; - typename VectorReal::template WithMaxSize timeResult; - }; - template class TestPowerSpectralDensity : public ::testing::Test @@ -80,11 +13,11 @@ namespace static constexpr std::size_t length = 512; static constexpr std::size_t overlap = 50; - using Fft = FftStub; - using Twiddle = TwiddleFactorsStub; + using Fft = analysis::test::FftStub; + using Twiddle = analysis::test::TwiddleFactorsStub; using PowerDensitySpectrum = analysis::PowerSpectralDensity; - WindowStub window; + analysis::test::WindowStub window; T samplingTime = T(1.0f / 48000.0f); std::optional powerDensitySpectrum; diff --git a/numerical/controllers/implementations/Lqr.hpp b/numerical/controllers/implementations/Lqr.hpp index 351569c1..a54a7561 100644 --- a/numerical/controllers/implementations/Lqr.hpp +++ b/numerical/controllers/implementations/Lqr.hpp @@ -1,5 +1,9 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + #include "infra/util/ReallyAssert.hpp" #include "numerical/controllers/interfaces/LqrController.hpp" #include "numerical/math/CompilerOptimizations.hpp" diff --git a/numerical/controllers/implementations/test/TestMpc.cpp b/numerical/controllers/implementations/test/TestMpc.cpp index ad82e7f2..f994ab0b 100644 --- a/numerical/controllers/implementations/test/TestMpc.cpp +++ b/numerical/controllers/implementations/test/TestMpc.cpp @@ -1,4 +1,3 @@ -#include "numerical/controllers/implementations/Lqr.hpp" #include "numerical/controllers/implementations/Mpc.hpp" #include @@ -260,26 +259,22 @@ TEST_F(TestMpc, unconstrained_mpc_approaches_lqr_with_long_horizon) { 0.1f } }; - // MPC with DARE terminal cost and long horizon should approximate LQR controllers::MpcWeights weights; weights.Q = Q; weights.R = R; - // Compute terminal cost via DARE - solvers::DiscreteAlgebraicRiccatiEquation dare; - auto P = dare.Solve(A, B, Q, R); - weights.terminalP = P; + weights.terminalP = math::SquareMatrix{ + { 60.2243614197f, 10.1239376068f }, + { 10.1239376068f, 6.0910396576f } + }; controllers::Mpc mpc(A, B, weights); - controllers::Lqr lqr(A, B, Q, R); math::Vector state{ 1.0f, 0.5f }; - auto uMpc = mpc.ComputeControl(state); - auto uLqr = lqr.ComputeControl(state); - // MPC with DARE terminal cost and sufficient horizon should be close to LQR - EXPECT_NEAR(math::ToFloat(uMpc.at(0, 0)), math::ToFloat(uLqr.at(0, 0)), 0.1f); + constexpr float expectedLqrControl = -9.9052610397f; + EXPECT_NEAR(math::ToFloat(uMpc.at(0, 0)), expectedLqrControl, 0.1f); } TEST_F(TestMpc, reference_tracking_drives_state_to_reference) diff --git a/numerical/dynamics/test/TestArticulatedBodyAlgorithm.cpp b/numerical/dynamics/test/TestArticulatedBodyAlgorithm.cpp index 121c7abe..4e61ebdc 100644 --- a/numerical/dynamics/test/TestArticulatedBodyAlgorithm.cpp +++ b/numerical/dynamics/test/TestArticulatedBodyAlgorithm.cpp @@ -1,5 +1,4 @@ #include "numerical/dynamics/ArticulatedBodyAlgorithm.hpp" -#include "numerical/dynamics/RecursiveNewtonEuler.hpp" #include #include @@ -60,8 +59,6 @@ namespace protected: dynamics::ArticulatedBodyAlgorithm aba1; dynamics::ArticulatedBodyAlgorithm aba2; - dynamics::RecursiveNewtonEuler rnea1; - dynamics::RecursiveNewtonEuler rnea2; }; } @@ -110,10 +107,8 @@ TEST_F(TestArticulatedBodyAlgorithm, single_link_rnea_aba_roundtrip_no_gravity) math::Vector qDDotExpected{ 3.0f }; math::Vector zeroGravity{}; - // RNEA: compute tau from qDDot - auto tau = rnea1.InverseDynamics(links, q, qDot, qDDotExpected, zeroGravity); + math::Vector tau{ 2.0f }; - // ABA: recover qDDot from tau auto qDDotRecovered = aba1.ForwardDynamics(links, q, qDot, tau, zeroGravity); EXPECT_NEAR(qDDotRecovered.at(0, 0), qDDotExpected.at(0, 0), 1e-3f); @@ -128,7 +123,7 @@ TEST_F(TestArticulatedBodyAlgorithm, single_link_rnea_aba_roundtrip_with_gravity math::Vector qDot{ 0.0f }; math::Vector qDDotExpected{ 2.0f }; - auto tau = rnea1.InverseDynamics(links, q, qDot, qDDotExpected, gravityVec); + math::Vector tau{ 1.3333333731f }; auto qDDotRecovered = aba1.ForwardDynamics(links, q, qDot, tau, gravityVec); EXPECT_NEAR(qDDotRecovered.at(0, 0), qDDotExpected.at(0, 0), 1e-2f); @@ -223,7 +218,7 @@ TEST_F(TestArticulatedBodyAlgorithm, two_link_rnea_aba_roundtrip_no_gravity) math::Vector qDDotExpected{ 2.0f, -1.0f }; math::Vector zeroGravity{}; - auto tau = rnea2.InverseDynamics(links, q, qDot, qDDotExpected, zeroGravity); + math::Vector tau{ 4.1365890503f, 0.9712030888f }; auto qDDotRecovered = aba2.ForwardDynamics(links, q, qDot, tau, zeroGravity); EXPECT_NEAR(qDDotRecovered.at(0, 0), qDDotExpected.at(0, 0), 1e-4f); @@ -238,7 +233,7 @@ TEST_F(TestArticulatedBodyAlgorithm, two_link_rnea_aba_roundtrip_with_gravity) math::Vector qDot{ 0.5f, -0.3f }; math::Vector qDDotExpected{ 1.0f, -2.0f }; - auto tau = rnea2.InverseDynamics(links, q, qDot, qDDotExpected, gravityVec); + math::Vector tau{ 0.1949892044f, -0.0272534918f }; auto qDDotRecovered = aba2.ForwardDynamics(links, q, qDot, tau, gravityVec); EXPECT_NEAR(qDDotRecovered.at(0, 0), qDDotExpected.at(0, 0), 1e-4f); diff --git a/numerical/estimators/CMakeLists.txt b/numerical/estimators/CMakeLists.txt index e7656015..3ce1d3a2 100644 --- a/numerical/estimators/CMakeLists.txt +++ b/numerical/estimators/CMakeLists.txt @@ -8,17 +8,20 @@ target_include_directories(numerical.estimators ${NUMERICAL_VISIBILITY} target_link_libraries(numerical.estimators ${NUMERICAL_VISIBILITY} infra.util numerical.math + numerical.solver ) target_sources(numerical.estimators PRIVATE Estimator.hpp LinearRegression.hpp RecursiveLeastSquares.hpp + YuleWalker.hpp ) numerical_add_coverage_sources(numerical.estimators LinearRegression.cpp RecursiveLeastSquares.cpp + YuleWalker.cpp ) add_subdirectory(test) diff --git a/numerical/estimators/LinearRegression.hpp b/numerical/estimators/LinearRegression.hpp index 298bf11d..1d281ad8 100644 --- a/numerical/estimators/LinearRegression.hpp +++ b/numerical/estimators/LinearRegression.hpp @@ -1,6 +1,14 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" + #include "numerical/estimators/Estimator.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/solvers/GaussianElimination.hpp" namespace estimators { @@ -21,14 +29,12 @@ namespace estimators private: CoefficientsMatrix coefficients; - - CoefficientsMatrix Solve(const DesignMatrix& A, const CoefficientsMatrix& b); }; // Implementation // template - void LinearRegression::Fit(const math::Matrix& X, const math::Matrix& y) + OPTIMIZE_FOR_SPEED void LinearRegression::Fit(const math::Matrix& X, const math::Matrix& y) { math::Matrix X_design; @@ -44,11 +50,13 @@ namespace estimators auto XtX = X_transpose * X_design; auto Xty = X_transpose * y; - coefficients = Solve(XtX, Xty); + coefficients = solvers::SolveSystem(XtX, Xty); } template - T LinearRegression::Predict(const InputMatrix& X) const + OPTIMIZE_FOR_SPEED + T + LinearRegression::Predict(const InputMatrix& X) const { T result = coefficients.at(0, 0); @@ -64,53 +72,6 @@ namespace estimators return coefficients; } - template - typename LinearRegression::CoefficientsMatrix LinearRegression::Solve(const DesignMatrix& A, const CoefficientsMatrix& b) - { - DesignMatrix aug = A; - CoefficientsMatrix result = b; - - for (size_t i = 0; i < Features + 1; ++i) - { - size_t max_row = i; - for (size_t j = i + 1; j < Features + 1; ++j) - if (std::abs(math::ToFloat(aug.at(j, i))) > std::abs(math::ToFloat(aug.at(max_row, i)))) - max_row = j; - - if (max_row != i) - { - for (size_t j = i; j < Features + 1; ++j) - std::swap(aug.at(i, j), aug.at(max_row, j)); - - std::swap(result.at(i, 0), result.at(max_row, 0)); - } - - for (size_t j = i + 1; j < Features + 1; ++j) - { - T coef = aug.at(j, i) / aug.at(i, i); - - for (size_t k = i; k < Features + 1; ++k) - aug.at(j, k) -= coef * aug.at(i, k); - - result.at(j, 0) -= coef * result.at(i, 0); - } - } - - CoefficientsMatrix x; - - for (int i = Features; i >= 0; --i) - { - x.at(i, 0) = result.at(i, 0); - - for (size_t j = i + 1; j < Features + 1; ++j) - x.at(i, 0) -= aug.at(i, j) * x.at(j, 0); - - x.at(i, 0) /= aug.at(i, i); - } - - return x; - } - #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD extern template class LinearRegression; #endif diff --git a/numerical/estimators/YuleWalker.cpp b/numerical/estimators/YuleWalker.cpp new file mode 100644 index 00000000..6c0660a9 --- /dev/null +++ b/numerical/estimators/YuleWalker.cpp @@ -0,0 +1,7 @@ +#include "numerical/estimators/YuleWalker.hpp" + +namespace estimators +{ + template class YuleWalker; + template class YuleWalker; +} diff --git a/numerical/estimators/YuleWalker.hpp b/numerical/estimators/YuleWalker.hpp new file mode 100644 index 00000000..83cb85ae --- /dev/null +++ b/numerical/estimators/YuleWalker.hpp @@ -0,0 +1,128 @@ +#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/math/Toeplitz.hpp" +#include "numerical/solvers/GaussianElimination.hpp" + +namespace estimators +{ + template + class YuleWalker + { + static_assert(math::detail::is_supported_type_v, + "YuleWalker only supports float or QNumber types"); + static_assert(Samples > Order, + "Number of samples must exceed order"); + static_assert(Order > 0, + "Order must be positive"); + + public: + using CoefficientsVector = math::Vector; + using AutocovarianceVector = math::Vector; + using InputVector = math::Vector; + + void Fit(const InputVector& x); + T Predict(const math::Vector& past) const; + const CoefficientsVector& Coefficients() const; + T NoiseVariance() const; + + private: + OPTIMIZE_FOR_SPEED AutocovarianceVector ComputeAutocovariance(const InputVector& x, T mean) const; + + CoefficientsVector coefficients; + T mean{}; + T noiseVariance{}; + }; + + // Implementation // + + template + OPTIMIZE_FOR_SPEED void YuleWalker::Fit(const InputVector& x) + { + mean = T(0.0f); + for (std::size_t i = 0; i < Samples; ++i) + mean += x[i]; + mean = mean / T(static_cast(Samples)); + + auto r = ComputeAutocovariance(x, mean); + + if (r[0] == T(0.0f)) + { + for (std::size_t i = 0; i < Order; ++i) + coefficients[i] = T(0.0f); + noiseVariance = T(0.0f); + return; + } + + math::Vector autocorrelation; + for (std::size_t i = 0; i < Order; ++i) + autocorrelation[i] = r[i]; + + math::ToeplitzMatrix toeplitz(autocorrelation); + auto toeplitzMatrix = toeplitz.ToFullMatrix(); + + math::Vector rhs; + for (std::size_t i = 0; i < Order; ++i) + rhs[i] = r[i + 1]; + + solvers::GaussianElimination solver; + coefficients = solver.Solve(toeplitzMatrix, rhs); + + noiseVariance = r[0]; + for (std::size_t i = 0; i < Order; ++i) + noiseVariance -= coefficients[i] * r[i + 1]; + } + + template + OPTIMIZE_FOR_SPEED + T + YuleWalker::Predict(const math::Vector& past) const + { + T prediction = mean; + for (std::size_t i = 0; i < Order; ++i) + prediction += coefficients[i] * (past[i] - mean); + + return prediction; + } + + template + const typename YuleWalker::CoefficientsVector& YuleWalker::Coefficients() const + { + return coefficients; + } + + template + T YuleWalker::NoiseVariance() const + { + return noiseVariance; + } + + template + OPTIMIZE_FOR_SPEED + typename YuleWalker::AutocovarianceVector + YuleWalker::ComputeAutocovariance(const InputVector& x, T xMean) const + { + AutocovarianceVector r; + + for (std::size_t k = 0; k <= Order; ++k) + { + T sum = T(0.0f); + for (std::size_t t = k; t < Samples; ++t) + sum += (x[t] - xMean) * (x[t - k] - xMean); + + r[k] = sum / T(static_cast(Samples)); + } + + return r; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class YuleWalker; + extern template class YuleWalker; +#endif +} diff --git a/numerical/estimators/test/CMakeLists.txt b/numerical/estimators/test/CMakeLists.txt index abb4e48d..f59f583d 100644 --- a/numerical/estimators/test/CMakeLists.txt +++ b/numerical/estimators/test/CMakeLists.txt @@ -10,4 +10,5 @@ target_link_libraries(numerical.estimators_test PUBLIC target_sources(numerical.estimators_test PRIVATE TestLinearRegression.cpp TestRecursiveLeastSquares.cpp + TestYuleWalker.cpp ) diff --git a/numerical/estimators/test/TestYuleWalker.cpp b/numerical/estimators/test/TestYuleWalker.cpp new file mode 100644 index 00000000..60643aed --- /dev/null +++ b/numerical/estimators/test/TestYuleWalker.cpp @@ -0,0 +1,100 @@ +#include "numerical/estimators/YuleWalker.hpp" +#include "numerical/math/QNumber.hpp" +#include + +namespace +{ + class TestYuleWalkerFloat + : public ::testing::Test + { + protected: + static constexpr std::size_t Samples = 256; + static constexpr std::size_t Order = 2; + + estimators::YuleWalker estimator; + }; +} + +TEST_F(TestYuleWalkerFloat, fit_produces_nonzero_coefficients) +{ + math::Vector signal; + signal[0] = 0.1f; + signal[1] = 0.2f; + for (std::size_t t = 2; t < TestYuleWalkerFloat::Samples; ++t) + signal[t] = 0.5f * signal[t - 1] - 0.3f * signal[t - 2] + 0.01f * static_cast(t % 7 - 3); + + estimator.Fit(signal); + + auto coeffs = estimator.Coefficients(); + EXPECT_NE(coeffs[0], 0.0f); + EXPECT_NE(coeffs[1], 0.0f); +} + +TEST_F(TestYuleWalkerFloat, fit_recovers_ar2_coefficients) +{ + math::Vector signal; + + unsigned int seed = 42u; + auto nextNoise = [&seed]() + { + seed = seed * 1103515245u + 12345u; + return 0.01f * ((static_cast((seed >> 16) & 0x7FFF) / 16384.0f) - 1.0f); + }; + + signal[0] = nextNoise(); + signal[1] = 0.5f * signal[0] + nextNoise(); + for (std::size_t t = 2; t < TestYuleWalkerFloat::Samples; ++t) + signal[t] = 0.5f * signal[t - 1] - 0.3f * signal[t - 2] + nextNoise(); + + estimator.Fit(signal); + + auto coeffs = estimator.Coefficients(); + EXPECT_NEAR(coeffs[0], 0.5f, 0.1f); + EXPECT_NEAR(coeffs[1], -0.3f, 0.1f); +} + +TEST_F(TestYuleWalkerFloat, predict_uses_coefficients) +{ + math::Vector signal; + signal[0] = 0.1f; + signal[1] = 0.2f; + for (std::size_t t = 2; t < TestYuleWalkerFloat::Samples; ++t) + signal[t] = 0.5f * signal[t - 1] - 0.3f * signal[t - 2]; + + estimator.Fit(signal); + + math::Vector past; + past[0] = signal[TestYuleWalkerFloat::Samples - 1]; + past[1] = signal[TestYuleWalkerFloat::Samples - 2]; + + float prediction = estimator.Predict(past); + + float expected = 0.5f * signal[TestYuleWalkerFloat::Samples - 1] - 0.3f * signal[TestYuleWalkerFloat::Samples - 2]; + EXPECT_NEAR(prediction, expected, 0.1f); +} + +TEST_F(TestYuleWalkerFloat, noise_variance_is_nonnegative) +{ + math::Vector signal; + signal[0] = 0.1f; + signal[1] = 0.2f; + for (std::size_t t = 2; t < TestYuleWalkerFloat::Samples; ++t) + signal[t] = 0.5f * signal[t - 1] - 0.3f * signal[t - 2] + 0.01f * static_cast(t % 7 - 3); + + estimator.Fit(signal); + + EXPECT_GE(estimator.NoiseVariance(), 0.0f); +} + +TEST_F(TestYuleWalkerFloat, constant_signal_yields_near_zero_coefficients) +{ + math::Vector signal; + for (std::size_t t = 0; t < TestYuleWalkerFloat::Samples; ++t) + signal[t] = 0.5f; + + estimator.Fit(signal); + + auto coeffs = estimator.Coefficients(); + EXPECT_NEAR(coeffs[0], 0.0f, 0.01f); + EXPECT_NEAR(coeffs[1], 0.0f, 0.01f); +} diff --git a/numerical/filters/active/KalmanFilterBase.hpp b/numerical/filters/active/KalmanFilterBase.hpp index d1c67b71..4a6968f4 100644 --- a/numerical/filters/active/KalmanFilterBase.hpp +++ b/numerical/filters/active/KalmanFilterBase.hpp @@ -148,7 +148,9 @@ namespace filters const MeasurementVector& innovation, const KalmanGain& K, const MeasurementMatrix& H) { state_ = state_ + K * innovation; - covariance_ = (StateMatrix::Identity() - K * H) * covariance_; + + auto IminusKH = StateMatrix::Identity() - K * H; + covariance_ = IminusKH * covariance_ * IminusKH.Transpose() + K * measurementNoise_ * K.Transpose(); } template diff --git a/numerical/filters/active/test/TestKalmanFilter.cpp b/numerical/filters/active/test/TestKalmanFilter.cpp index 7be789d8..b88cf67a 100644 --- a/numerical/filters/active/test/TestKalmanFilter.cpp +++ b/numerical/filters/active/test/TestKalmanFilter.cpp @@ -404,3 +404,37 @@ TYPED_TEST(KalmanFilterTest, WithControlInput) EXPECT_NEAR(math::ToFloat(finalState.at(0, 0)), truePos, 0.2f); EXPECT_NEAR(math::ToFloat(finalState.at(1, 0)), trueVel, 0.4f); } + +TYPED_TEST(KalmanFilterTest, JosephFormPreservesPositiveDefiniteness) +{ + auto initialState = this->MakeStateVector(0.0f, 0.0f); + auto initialCovariance = this->MakeStateMatrix( + 1000.0f, 0.0f, + 0.0f, 1000.0f); + + typename TestFixture::FilterType filter(initialState, initialCovariance); + + float dt = 0.1f; + filter.SetStateTransition(this->MakeStateMatrix( + 1.0f, dt, + 0.0f, 1.0f)); + filter.SetMeasurementMatrix(this->MakeMeasurementMatrix(1.0f, 0.0f)); + filter.SetMeasurementNoise(this->MakeMeasurementCovariance(0.001f)); + filter.SetProcessNoise(this->MakeStateMatrix( + 0.001f, 0.0f, + 0.0f, 0.001f)); + + for (int i = 0; i < 50; ++i) + { + filter.Predict(); + filter.Update(this->MakeMeasurement(1.0f)); + + auto P = filter.GetCovariance(); + EXPECT_GE(math::ToFloat(P.at(0, 0)), 0.0f); + EXPECT_GE(math::ToFloat(P.at(1, 1)), 0.0f); + + float det = math::ToFloat(P.at(0, 0)) * math::ToFloat(P.at(1, 1)) - + math::ToFloat(P.at(0, 1)) * math::ToFloat(P.at(1, 0)); + EXPECT_GE(det, 0.0f); + } +} diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index 231747af..ab608c11 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.filters.passive ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.filters.passive) -target_include_directories(numerical.filters.passive INTERFACE +target_include_directories(numerical.filters.passive ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.filters.passive INTERFACE +target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY} infra.util numerical.math ) @@ -15,4 +15,9 @@ target_sources(numerical.filters.passive PRIVATE Iir.hpp ) +numerical_add_coverage_sources(numerical.filters.passive + Fir.cpp + Iir.cpp +) + add_subdirectory(test) diff --git a/numerical/filters/passive/Fir.cpp b/numerical/filters/passive/Fir.cpp new file mode 100644 index 00000000..af0c55bf --- /dev/null +++ b/numerical/filters/passive/Fir.cpp @@ -0,0 +1,8 @@ +#include "numerical/filters/passive/Fir.hpp" + +namespace filters::passive +{ + template class Fir; + template class Fir; + template class Fir; +} diff --git a/numerical/filters/passive/Fir.hpp b/numerical/filters/passive/Fir.hpp index 59008b15..0ef545ed 100644 --- a/numerical/filters/passive/Fir.hpp +++ b/numerical/filters/passive/Fir.hpp @@ -1,5 +1,4 @@ -#ifndef FILTERS_PASSIVE_FIR_HPP -#define FILTERS_PASSIVE_FIR_HPP +#pragma once #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/RecursiveBuffer.hpp" @@ -13,8 +12,8 @@ namespace filters::passive template class Fir { - static_assert(math::is_qnumber::value || - std::is_floating_point::value, + static_assert(math::is_qnumber_v || + std::is_floating_point_v, "Fir can only be instantiated with math::QNumber types."); public: @@ -28,7 +27,7 @@ namespace filters::passive private: bool enabled = true; - math::Index n; + [[no_unique_address]] math::Index n; math::RecursiveBuffer b; math::RecursiveBuffer x; }; @@ -52,7 +51,7 @@ namespace filters::passive QNumberType output{}; for (std::size_t i = 0; i < N; ++i) - output += b[n - i] * x[n - i]; + output += b[n - static_cast(i)] * x[n - static_cast(i)]; return output; } @@ -74,6 +73,10 @@ namespace filters::passive { x.Reset(); } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Fir; + extern template class Fir; + extern template class Fir; #endif +} diff --git a/numerical/filters/passive/Iir.cpp b/numerical/filters/passive/Iir.cpp new file mode 100644 index 00000000..b7583b05 --- /dev/null +++ b/numerical/filters/passive/Iir.cpp @@ -0,0 +1,8 @@ +#include "numerical/filters/passive/Iir.hpp" + +namespace filters::passive +{ + template class Iir; + template class Iir; + template class Iir; +} diff --git a/numerical/filters/passive/Iir.hpp b/numerical/filters/passive/Iir.hpp index 8a25b074..972f5e49 100644 --- a/numerical/filters/passive/Iir.hpp +++ b/numerical/filters/passive/Iir.hpp @@ -1,5 +1,4 @@ -#ifndef FILTERS_PASSIVE_IIR_HPP -#define FILTERS_PASSIVE_IIR_HPP +#pragma once #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/RecursiveBuffer.hpp" @@ -13,8 +12,8 @@ namespace filters::passive template class Iir { - static_assert(math::is_qnumber::value || - std::is_floating_point::value, + static_assert(math::is_qnumber_v || + std::is_floating_point_v, "Iir can only be instantiated with math::QNumber types."); public: @@ -28,7 +27,7 @@ namespace filters::passive private: bool enabled = true; - math::Index n; + [[no_unique_address]] math::Index n; math::RecursiveBuffer a; math::RecursiveBuffer b; math::RecursiveBuffer y; @@ -55,11 +54,11 @@ namespace filters::passive QNumberType feedforward{}; for (std::size_t i = 0; i < P; ++i) - feedforward += b[n - i] * x[n - i]; + feedforward += b[n - static_cast(i)] * x[n - static_cast(i)]; QNumberType feedback{}; for (std::size_t i = 0; i < Q; ++i) - feedback += a[n - i] * y[n - i]; + feedback += a[n - static_cast(i)] * y[n - static_cast(i)]; const auto output = feedforward + feedback; y.Update(output); @@ -85,6 +84,10 @@ namespace filters::passive x.Reset(); y.Reset(); } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Iir; + extern template class Iir; + extern template class Iir; #endif +} diff --git a/numerical/math/AdvancedFunctions.hpp b/numerical/math/AdvancedFunctions.hpp index 45e63c03..05b6b806 100644 --- a/numerical/math/AdvancedFunctions.hpp +++ b/numerical/math/AdvancedFunctions.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_ADVANCED_FUNCTIONS_HPP -#define MATH_ADVANCED_FUNCTIONS_HPP - +#pragma once #include "numerical/math/QNumber.hpp" namespace math @@ -14,5 +12,3 @@ namespace math virtual QNumberType SquareRoot(const QNumberType& value) const = 0; }; } - -#endif diff --git a/numerical/math/ComplexNumber.hpp b/numerical/math/ComplexNumber.hpp index 13c80c27..ae368f1d 100644 --- a/numerical/math/ComplexNumber.hpp +++ b/numerical/math/ComplexNumber.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_COMPLEX_NUMBER_H -#define MATH_COMPLEX_NUMBER_H - +#pragma once #include "numerical/math/QNumber.hpp" namespace math @@ -120,5 +118,3 @@ namespace math extern template class Complex; #endif } - -#endif diff --git a/numerical/math/HyperbolicFunctions.hpp b/numerical/math/HyperbolicFunctions.hpp index aa05e36c..00e28aa3 100644 --- a/numerical/math/HyperbolicFunctions.hpp +++ b/numerical/math/HyperbolicFunctions.hpp @@ -1,4 +1,4 @@ -#ifndef MATH_HYPERBOLIC_FUNCTIONS_HPP +#pragma once #include "numerical/math/QNumber.hpp" @@ -13,5 +13,3 @@ namespace math virtual QNumberType Arctangent(const QNumberType& value) const = 0; }; } - -#endif diff --git a/numerical/math/Matrix.hpp b/numerical/math/Matrix.hpp index ea3509eb..17380301 100644 --- a/numerical/math/Matrix.hpp +++ b/numerical/math/Matrix.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_MATRIX_HPP -#define MATH_MATRIX_HPP - +#pragma once #include "infra/util/ReallyAssert.hpp" #include "numerical/math/QNumber.hpp" #include @@ -303,5 +301,3 @@ namespace math extern template class Matrix; #endif } - -#endif diff --git a/numerical/math/QNumber.hpp b/numerical/math/QNumber.hpp index 6b603f24..dc340d5b 100644 --- a/numerical/math/QNumber.hpp +++ b/numerical/math/QNumber.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_Q_NUMBER_H -#define MATH_Q_NUMBER_H - +#pragma once #include "infra/util/ReallyAssert.hpp" #include "numerical/math/CompilerOptimizations.hpp" #include @@ -267,5 +265,3 @@ namespace math extern template class QNumber; #endif } - -#endif diff --git a/numerical/math/RecursiveBuffer.hpp b/numerical/math/RecursiveBuffer.hpp index 68d50246..9a612831 100644 --- a/numerical/math/RecursiveBuffer.hpp +++ b/numerical/math/RecursiveBuffer.hpp @@ -1,8 +1,7 @@ -#ifndef MATH_RECURSIVE_BUFFER_H -#define MATH_RECURSIVE_BUFFER_H - +#pragma once #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/Matrix.hpp" +#include #include #if defined(__GNUC__) || defined(__clang__) @@ -22,12 +21,12 @@ namespace math struct Index { - [[nodiscard]] constexpr IndexRelative operator-(int32_t offset) const noexcept + [[nodiscard]] friend constexpr IndexRelative operator-(Index, int32_t offset) noexcept { return IndexRelative(offset); } - [[nodiscard]] constexpr IndexRelative operator+() const noexcept + [[nodiscard]] friend constexpr IndexRelative operator+(Index) noexcept { return IndexRelative(0); } @@ -49,21 +48,19 @@ namespace math [[nodiscard]] QNumberType operator[](const IndexRelative& n) const noexcept; private: - std::array buffer; + std::array buffer{}; }; // Implementation template - constexpr RecursiveBuffer::RecursiveBuffer() noexcept - : buffer{} - {} + constexpr RecursiveBuffer::RecursiveBuffer() noexcept = default; template RecursiveBuffer& RecursiveBuffer::operator=(std::initializer_list init) { really_assert(init.size() <= Length); - std::copy(init.begin(), init.end(), buffer.begin()); + std::ranges::copy(init, buffer.begin()); if (init.size() < Length) std::fill(buffer.begin() + init.size(), buffer.end(), QNumberType(0.0f)); @@ -98,5 +95,3 @@ namespace math return buffer[n.offset]; } } - -#endif diff --git a/numerical/math/SingleInstructionMultipleData.hpp b/numerical/math/SingleInstructionMultipleData.hpp index 99af7e05..8ce21fee 100644 --- a/numerical/math/SingleInstructionMultipleData.hpp +++ b/numerical/math/SingleInstructionMultipleData.hpp @@ -1,39 +1,35 @@ -#ifndef MATH_SIMD_HPP -#define MATH_SIMD_HPP - -#include - -namespace math -{ - class SingleInstructionMultipltData - { - public: - virtual uint32_t Pkhbt(uint32_t value1, uint32_t value2, uint32_t value3) = 0; - virtual uint32_t Pkhtb(uint32_t value1, uint32_t value2, uint32_t value3) = 0; - virtual uint32_t Qadd(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qadd16(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qadd8(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qasx(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qsax(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qsub(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qsub16(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Qsub8(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Shadd16(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Shasx(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Shsax(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Shsub16(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Smlad(uint32_t value1, uint32_t value2, uint32_t value3) = 0; - virtual uint32_t Smladx(uint32_t value1, uint32_t value2, uint32_t value3) = 0; - virtual uint64_t Smlald(uint32_t value1, uint32_t value2, uint64_t value3) = 0; - virtual unsigned long long Smlaldx(uint32_t value1, uint32_t value2, unsigned long long value3) = 0; - virtual uint32_t Smlsdx(uint32_t value1, uint32_t value2, uint32_t value3) = 0; - virtual uint32_t Smmla(int32_t value1, int32_t value2, int32_t value3) = 0; - virtual uint32_t Smuad(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Smuadx(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Smusd(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Smusdx(uint32_t value1, uint32_t value2) = 0; - virtual uint32_t Sxtb16(uint32_t value) = 0; - }; -} - -#endif +#pragma once +#include + +namespace math +{ + class SingleInstructionMultipltData + { + public: + virtual uint32_t Pkhbt(uint32_t value1, uint32_t value2, uint32_t value3) = 0; + virtual uint32_t Pkhtb(uint32_t value1, uint32_t value2, uint32_t value3) = 0; + virtual uint32_t Qadd(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qadd16(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qadd8(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qasx(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qsax(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qsub(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qsub16(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Qsub8(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Shadd16(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Shasx(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Shsax(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Shsub16(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Smlad(uint32_t value1, uint32_t value2, uint32_t value3) = 0; + virtual uint32_t Smladx(uint32_t value1, uint32_t value2, uint32_t value3) = 0; + virtual uint64_t Smlald(uint32_t value1, uint32_t value2, uint64_t value3) = 0; + virtual unsigned long long Smlaldx(uint32_t value1, uint32_t value2, unsigned long long value3) = 0; + virtual uint32_t Smlsdx(uint32_t value1, uint32_t value2, uint32_t value3) = 0; + virtual uint32_t Smmla(int32_t value1, int32_t value2, int32_t value3) = 0; + virtual uint32_t Smuad(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Smuadx(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Smusd(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Smusdx(uint32_t value1, uint32_t value2) = 0; + virtual uint32_t Sxtb16(uint32_t value) = 0; + }; +} diff --git a/numerical/math/Statistics.hpp b/numerical/math/Statistics.hpp index 53b49e2e..b4732902 100644 --- a/numerical/math/Statistics.hpp +++ b/numerical/math/Statistics.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_STATISTICS_HPP -#define MATH_STATISTICS_HPP - +#pragma once #include "numerical/math/Matrix.hpp" #include "numerical/math/QNumber.hpp" #include @@ -160,5 +158,3 @@ namespace math return result; } } - -#endif diff --git a/numerical/math/Toeplitz.hpp b/numerical/math/Toeplitz.hpp index 5480d567..e29ccecc 100644 --- a/numerical/math/Toeplitz.hpp +++ b/numerical/math/Toeplitz.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_TOEPLITZ_MATRIX_HPP -#define MATH_TOEPLITZ_MATRIX_HPP - +#pragma once #include "infra/util/ReallyAssert.hpp" #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/Matrix.hpp" @@ -35,9 +33,35 @@ namespace math [[nodiscard]] constexpr T at(size_type row, size_type col) const noexcept; [[nodiscard]] constexpr Matrix ToFullMatrix() const; - [[nodiscard]] constexpr Vector operator*(const Vector& vec) const noexcept; - [[nodiscard]] constexpr ToeplitzMatrix operator+(const ToeplitzMatrix& other) const; - [[nodiscard]] constexpr ToeplitzMatrix operator-(const ToeplitzMatrix& other) const; + [[nodiscard]] friend constexpr Vector operator*(const ToeplitzMatrix& lhs, const Vector& vec) noexcept + { + Vector result; + + for (size_type i = 0; i < N; ++i) + { + T sum{}; + + for (size_type j = i; j < N; ++j) + sum += lhs.first_row.at(j - i, 0) * vec.at(j, 0); + + for (size_type j = i; j-- > 0;) + sum += lhs.first_col.at(i - j, 0) * vec.at(j, 0); + + result.at(i, 0) = sum; + } + + return result; + } + + [[nodiscard]] friend constexpr ToeplitzMatrix operator+(const ToeplitzMatrix& lhs, const ToeplitzMatrix& rhs) + { + return ToeplitzMatrix(lhs.first_row + rhs.first_row, lhs.first_col + rhs.first_col); + } + + [[nodiscard]] friend constexpr ToeplitzMatrix operator-(const ToeplitzMatrix& lhs, const ToeplitzMatrix& rhs) + { + return ToeplitzMatrix(lhs.first_row - rhs.first_row, lhs.first_col - rhs.first_col); + } [[nodiscard]] constexpr bool IsSymmetric() const; @@ -94,39 +118,6 @@ namespace math return result; } - template - OPTIMIZE_FOR_SPEED constexpr Vector ToeplitzMatrix::operator*(const Vector& vec) const noexcept - { - Vector result; - - for (size_type i = 0; i < N; ++i) - { - T sum{}; - - for (size_type j = i; j < N; ++j) - sum += first_row.at(j - i, 0) * vec.at(j, 0); - - for (size_type j = i; j-- > 0;) - sum += first_col.at(i - j, 0) * vec.at(j, 0); - - result.at(i, 0) = sum; - } - - return result; - } - - template - OPTIMIZE_FOR_SPEED constexpr ToeplitzMatrix ToeplitzMatrix::operator+(const ToeplitzMatrix& other) const - { - return ToeplitzMatrix(first_row + other.first_row, first_col + other.first_col); - } - - template - OPTIMIZE_FOR_SPEED constexpr ToeplitzMatrix ToeplitzMatrix::operator-(const ToeplitzMatrix& other) const - { - return ToeplitzMatrix(first_row - other.first_row, first_col - other.first_col); - } - template constexpr bool ToeplitzMatrix::IsSymmetric() const { @@ -172,5 +163,3 @@ namespace math return ToeplitzMatrix(autocorrelation); } } - -#endif diff --git a/numerical/math/Tolerance.hpp b/numerical/math/Tolerance.hpp index 959bbbf6..a2c04174 100644 --- a/numerical/math/Tolerance.hpp +++ b/numerical/math/Tolerance.hpp @@ -1,5 +1,9 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + namespace math { template diff --git a/numerical/math/TrigonometricFunctions.hpp b/numerical/math/TrigonometricFunctions.hpp index a77963af..362ad7dc 100644 --- a/numerical/math/TrigonometricFunctions.hpp +++ b/numerical/math/TrigonometricFunctions.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_TRIGONOMETRIC_FUNCTIONS_HPP -#define MATH_TRIGONOMETRIC_FUNCTIONS_HPP - +#pragma once #include "numerical/math/QNumber.hpp" namespace math @@ -15,5 +13,3 @@ namespace math virtual QNumberType Phase(const QNumberType& real, const QNumberType& imag) const = 0; }; } - -#endif diff --git a/numerical/math/test/TestQNumber.cpp b/numerical/math/test/TestQNumber.cpp index 295a554e..f25ae082 100644 --- a/numerical/math/test/TestQNumber.cpp +++ b/numerical/math/test/TestQNumber.cpp @@ -1,16 +1,19 @@ #include "numerical/math/QNumber.hpp" #include -template -class QNumberTest - : public ::testing::Test +namespace { -protected: - using IntType = typename std::decay().RawValue())>::type; -}; + template + class QNumberTest + : public ::testing::Test + { + protected: + using IntType = typename std::decay().RawValue())>::type; + }; -using QNumberTypes = ::testing::Types; -TYPED_TEST_SUITE(QNumberTest, QNumberTypes); + using QNumberTypes = ::testing::Types; + TYPED_TEST_SUITE(QNumberTest, QNumberTypes); +} TYPED_TEST(QNumberTest, DefaultConstructor) { diff --git a/numerical/math/test_doubles/AdvancedFunctionsStub.hpp b/numerical/math/test_doubles/AdvancedFunctionsStub.hpp index fd3ee524..78233f41 100644 --- a/numerical/math/test_doubles/AdvancedFunctionsStub.hpp +++ b/numerical/math/test_doubles/AdvancedFunctionsStub.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_ADVANCED_FUNCTIONS_STUB_HPP -#define MATH_ADVANCED_FUNCTIONS_STUB_HPP - +#pragma once #include "numerical/math/AdvancedFunctions.hpp" #include @@ -31,5 +29,3 @@ namespace math } }; } - -#endif diff --git a/numerical/math/test_doubles/HyperbolicFunctionsStub.hpp b/numerical/math/test_doubles/HyperbolicFunctionsStub.hpp index 8939e665..6fae71a5 100644 --- a/numerical/math/test_doubles/HyperbolicFunctionsStub.hpp +++ b/numerical/math/test_doubles/HyperbolicFunctionsStub.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_HYPERBOLIC_FUNCTIONS_STUB_HPP -#define MATH_HYPERBOLIC_FUNCTIONS_STUB_HPP - +#pragma once #include "numerical/math/HyperbolicFunctions.hpp" namespace math @@ -15,5 +13,3 @@ namespace math virtual QNumberType Arctangent(const QNumberType& value) const = 0; }; } - -#endif diff --git a/numerical/math/test_doubles/SingleInstructionMultipleDataStub.hpp b/numerical/math/test_doubles/SingleInstructionMultipleDataStub.hpp index 6e2979d7..fabaa58b 100644 --- a/numerical/math/test_doubles/SingleInstructionMultipleDataStub.hpp +++ b/numerical/math/test_doubles/SingleInstructionMultipleDataStub.hpp @@ -1,139 +1,135 @@ -#ifndef MATH_SIMD_STUB_HPP -#define MATH_SIMD_STUB_HPP - -#include "numerical/math/SingleInstructionMultipleData.hpp" - -namespace math -{ - class SingleInstructionMultipltDataStub - : public SingleInstructionMultipltData - { - public: - uint32_t Pkhbt(uint32_t value1, uint32_t value2, uint32_t value3) override - { - return 0; - } - - uint32_t Pkhtb(uint32_t value1, uint32_t value2, uint32_t value3) override - { - return 0; - } - - uint32_t Qadd(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qadd16(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qadd8(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qasx(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qsax(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qsub(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qsub16(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Qsub8(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Shadd16(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Shasx(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Shsax(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Shsub16(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Smlad(uint32_t value1, uint32_t value2, uint32_t value3) override - { - return 0; - } - - uint32_t Smladx(uint32_t value1, uint32_t value2, uint32_t value3) override - { - return 0; - } - - uint64_t Smlald(uint32_t value1, uint32_t value2, uint64_t value3) override - { - return 0; - } - - unsigned long long Smlaldx(uint32_t value1, uint32_t value2, unsigned long long value3) override - { - return 0; - } - - uint32_t Smlsdx(uint32_t value1, uint32_t value2, uint32_t value3) override - { - return 0; - } - - uint32_t Smmla(int32_t value1, int32_t value2, int32_t value3) override - { - return 0; - } - - uint32_t Smuad(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Smuadx(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Smusd(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Smusdx(uint32_t value1, uint32_t value2) override - { - return 0; - } - - uint32_t Sxtb16(uint32_t value) override - { - return 0; - } - }; -} - -#endif +#pragma once +#include "numerical/math/SingleInstructionMultipleData.hpp" + +namespace math +{ + class SingleInstructionMultipltDataStub + : public SingleInstructionMultipltData + { + public: + uint32_t Pkhbt(uint32_t value1, uint32_t value2, uint32_t value3) override + { + return 0; + } + + uint32_t Pkhtb(uint32_t value1, uint32_t value2, uint32_t value3) override + { + return 0; + } + + uint32_t Qadd(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qadd16(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qadd8(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qasx(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qsax(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qsub(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qsub16(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Qsub8(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Shadd16(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Shasx(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Shsax(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Shsub16(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Smlad(uint32_t value1, uint32_t value2, uint32_t value3) override + { + return 0; + } + + uint32_t Smladx(uint32_t value1, uint32_t value2, uint32_t value3) override + { + return 0; + } + + uint64_t Smlald(uint32_t value1, uint32_t value2, uint64_t value3) override + { + return 0; + } + + unsigned long long Smlaldx(uint32_t value1, uint32_t value2, unsigned long long value3) override + { + return 0; + } + + uint32_t Smlsdx(uint32_t value1, uint32_t value2, uint32_t value3) override + { + return 0; + } + + uint32_t Smmla(int32_t value1, int32_t value2, int32_t value3) override + { + return 0; + } + + uint32_t Smuad(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Smuadx(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Smusd(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Smusdx(uint32_t value1, uint32_t value2) override + { + return 0; + } + + uint32_t Sxtb16(uint32_t value) override + { + return 0; + } + }; +} diff --git a/numerical/math/test_doubles/TrigonometricFunctionsStub.hpp b/numerical/math/test_doubles/TrigonometricFunctionsStub.hpp index 00cd9669..8bb2e53a 100644 --- a/numerical/math/test_doubles/TrigonometricFunctionsStub.hpp +++ b/numerical/math/test_doubles/TrigonometricFunctionsStub.hpp @@ -1,6 +1,4 @@ -#ifndef MATH_TRIGONOMETRIC_FUNCTIONS_STUB_HPP -#define MATH_TRIGONOMETRIC_FUNCTIONS_STUB_HPP - +#pragma once #include "numerical/math/TrigonometricFunctions.hpp" #include #include @@ -44,5 +42,3 @@ namespace math } }; } - -#endif diff --git a/numerical/neural_network/activation/ActivationFunction.cpp b/numerical/neural_network/activation/ActivationFunction.cpp new file mode 100644 index 00000000..f4333bf6 --- /dev/null +++ b/numerical/neural_network/activation/ActivationFunction.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/ActivationFunction.hpp" + +namespace neural_network +{ + template class ActivationFunction; + template class ActivationFunction; + template class ActivationFunction; +} diff --git a/numerical/neural_network/activation/ActivationFunction.hpp b/numerical/neural_network/activation/ActivationFunction.hpp index 81897678..d67c24fa 100644 --- a/numerical/neural_network/activation/ActivationFunction.hpp +++ b/numerical/neural_network/activation/ActivationFunction.hpp @@ -1,20 +1,46 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_FUNCTION_HPP -#define NEURAL_NETWORK_ACTIVATION_FUNCTION_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/QNumber.hpp" +#include namespace neural_network { template class ActivationFunction { - static_assert(math::is_qnumber::value || std::is_floating_point::value, + static_assert(math::is_qnumber_v || std::is_floating_point_v, "ActivationFunction can only be instantiated with math::QNumber types."); public: virtual QNumberType Forward(QNumberType x) const = 0; virtual QNumberType Backward(QNumberType x) const = 0; + + virtual void ForwardVector(std::span output, std::span input) const; + virtual void BackwardVector(std::span result, std::span preActivation, std::span output, std::span outputGradient) const; }; -} + template + OPTIMIZE_FOR_SPEED void ActivationFunction::ForwardVector(std::span output, std::span input) const + { + for (std::size_t i = 0; i < output.size(); ++i) + output[i] = Forward(input[i]); + } + + template + OPTIMIZE_FOR_SPEED void ActivationFunction::BackwardVector(std::span result, std::span preActivation, std::span /*output*/, std::span outputGradient) const + { + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = outputGradient[i] * Backward(preActivation[i]); + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class ActivationFunction; + extern template class ActivationFunction; + extern template class ActivationFunction; #endif +} diff --git a/numerical/neural_network/activation/CMakeLists.txt b/numerical/neural_network/activation/CMakeLists.txt index 57f579e9..f20d4221 100644 --- a/numerical/neural_network/activation/CMakeLists.txt +++ b/numerical/neural_network/activation/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.activation ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.activation) -target_include_directories(numerical.neural_network.activation INTERFACE +target_include_directories(numerical.neural_network.activation ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.activation INTERFACE +target_link_libraries(numerical.neural_network.activation ${NUMERICAL_VISIBILITY} infra.util numerical.math ) @@ -19,4 +19,13 @@ target_sources(numerical.neural_network.activation PRIVATE Tanh.hpp ) +numerical_add_coverage_sources(numerical.neural_network.activation + ActivationFunction.cpp + ReLU.cpp + LeakyReLU.cpp + Sigmoid.cpp + Tanh.cpp + Softmax.cpp +) + add_subdirectory(test) diff --git a/numerical/neural_network/activation/LeakyReLU.cpp b/numerical/neural_network/activation/LeakyReLU.cpp new file mode 100644 index 00000000..a5e7fa00 --- /dev/null +++ b/numerical/neural_network/activation/LeakyReLU.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/LeakyReLU.hpp" + +namespace neural_network +{ + template class LeakyReLU; + template class LeakyReLU; + template class LeakyReLU; +} diff --git a/numerical/neural_network/activation/LeakyReLU.hpp b/numerical/neural_network/activation/LeakyReLU.hpp index 21dda40b..db1fb39b 100644 --- a/numerical/neural_network/activation/LeakyReLU.hpp +++ b/numerical/neural_network/activation/LeakyReLU.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_LEAKYRELU_HPP -#define NEURAL_NETWORK_ACTIVATION_LEAKYRELU_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" namespace neural_network @@ -27,16 +31,24 @@ namespace neural_network {} template - QNumberType LeakyReLU::Forward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + LeakyReLU::Forward(QNumberType x) const { return x > QNumberType(0.0f) ? x : alpha * x; } template - QNumberType LeakyReLU::Backward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + LeakyReLU::Backward(QNumberType x) const { return x > QNumberType(0.0f) ? QNumberType(0.9999f) : alpha; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class LeakyReLU; + extern template class LeakyReLU; + extern template class LeakyReLU; #endif +} diff --git a/numerical/neural_network/activation/ReLU.cpp b/numerical/neural_network/activation/ReLU.cpp new file mode 100644 index 00000000..e7de7a9e --- /dev/null +++ b/numerical/neural_network/activation/ReLU.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/ReLU.hpp" + +namespace neural_network +{ + template class ReLU; + template class ReLU; + template class ReLU; +} diff --git a/numerical/neural_network/activation/ReLU.hpp b/numerical/neural_network/activation/ReLU.hpp index 167e9adc..b9fec8c8 100644 --- a/numerical/neural_network/activation/ReLU.hpp +++ b/numerical/neural_network/activation/ReLU.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_RELU_HPP -#define NEURAL_NETWORK_ACTIVATION_RELU_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" namespace neural_network @@ -17,16 +21,24 @@ namespace neural_network // Implementation template - QNumberType ReLU::Forward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + ReLU::Forward(QNumberType x) const { return x > QNumberType(0.0f) ? x : QNumberType(0.0f); } template - QNumberType ReLU::Backward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + ReLU::Backward(QNumberType x) const { return x > QNumberType(0.0f) ? QNumberType(0.9999f) : QNumberType(0.0f); } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class ReLU; + extern template class ReLU; + extern template class ReLU; #endif +} diff --git a/numerical/neural_network/activation/Sigmoid.cpp b/numerical/neural_network/activation/Sigmoid.cpp new file mode 100644 index 00000000..775d1618 --- /dev/null +++ b/numerical/neural_network/activation/Sigmoid.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/Sigmoid.hpp" + +namespace neural_network +{ + template class Sigmoid; + template class Sigmoid; + template class Sigmoid; +} diff --git a/numerical/neural_network/activation/Sigmoid.hpp b/numerical/neural_network/activation/Sigmoid.hpp index b7346c7e..65588dde 100644 --- a/numerical/neural_network/activation/Sigmoid.hpp +++ b/numerical/neural_network/activation/Sigmoid.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_SIGMOID_HPP -#define NEURAL_NETWORK_ACTIVATION_SIGMOID_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" #include @@ -18,17 +22,25 @@ namespace neural_network // Implementation template - QNumberType Sigmoid::Forward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Sigmoid::Forward(QNumberType x) const { return QNumberType(1.0f / (1.0f + std::exp(-math::ToFloat(x)))); } template - QNumberType Sigmoid::Backward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Sigmoid::Backward(QNumberType x) const { QNumberType y = Forward(x); return y * (QNumberType(0.9999f) - y); } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Sigmoid; + extern template class Sigmoid; + extern template class Sigmoid; #endif +} diff --git a/numerical/neural_network/activation/Softmax.cpp b/numerical/neural_network/activation/Softmax.cpp new file mode 100644 index 00000000..b3890d9c --- /dev/null +++ b/numerical/neural_network/activation/Softmax.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/Softmax.hpp" + +namespace neural_network +{ + template class Softmax; + template class Softmax; + template class Softmax; +} diff --git a/numerical/neural_network/activation/Softmax.hpp b/numerical/neural_network/activation/Softmax.hpp index 4397781a..d1fc0822 100644 --- a/numerical/neural_network/activation/Softmax.hpp +++ b/numerical/neural_network/activation/Softmax.hpp @@ -1,8 +1,13 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_SOFTMAX_HPP -#define NEURAL_NETWORK_ACTIVATION_SOFTMAX_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" #include +#include namespace neural_network { @@ -13,22 +18,60 @@ namespace neural_network public: QNumberType Forward(QNumberType x) const override; QNumberType Backward(QNumberType x) const override; + void ForwardVector(std::span output, std::span input) const override; + void BackwardVector(std::span result, std::span preActivation, std::span output, std::span outputGradient) const override; }; - // Implementation - template - QNumberType Softmax::Forward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Softmax::Forward(QNumberType x) const { return QNumberType(std::exp(math::ToFloat(x))); } template - QNumberType Softmax::Backward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Softmax::Backward(QNumberType x) const { QNumberType y = Forward(x); return y * (QNumberType(0.9999f) - y); } -} + template + OPTIMIZE_FOR_SPEED void Softmax::ForwardVector(std::span output, std::span input) const + { + QNumberType maxVal = input[0]; + for (std::size_t i = 1; i < input.size(); ++i) + if (input[i] > maxVal) + maxVal = input[i]; + + QNumberType sum = QNumberType(0.0f); + for (std::size_t i = 0; i < output.size(); ++i) + { + output[i] = QNumberType(std::exp(math::ToFloat(input[i]) - math::ToFloat(maxVal))); + sum += output[i]; + } + + for (std::size_t i = 0; i < output.size(); ++i) + output[i] = std::max(std::min(output[i] / sum, QNumberType(0.9999f)), QNumberType(0.0001f)); + } + + template + OPTIMIZE_FOR_SPEED void Softmax::BackwardVector(std::span result, std::span /*preActivation*/, std::span output, std::span outputGradient) const + { + QNumberType dot = QNumberType(0.0f); + for (std::size_t i = 0; i < result.size(); ++i) + dot += outputGradient[i] * output[i]; + + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = output[i] * (outputGradient[i] - dot); + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Softmax; + extern template class Softmax; + extern template class Softmax; #endif +} diff --git a/numerical/neural_network/activation/Tanh.cpp b/numerical/neural_network/activation/Tanh.cpp new file mode 100644 index 00000000..145ad563 --- /dev/null +++ b/numerical/neural_network/activation/Tanh.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/activation/Tanh.hpp" + +namespace neural_network +{ + template class Tanh; + template class Tanh; + template class Tanh; +} diff --git a/numerical/neural_network/activation/Tanh.hpp b/numerical/neural_network/activation/Tanh.hpp index 5eb2633b..8e866f31 100644 --- a/numerical/neural_network/activation/Tanh.hpp +++ b/numerical/neural_network/activation/Tanh.hpp @@ -1,5 +1,10 @@ -#ifndef NEURAL_NETWORK_ACTIVATION_TANH_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" #include @@ -17,17 +22,25 @@ namespace neural_network // Implementation template - QNumberType Tanh::Forward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Tanh::Forward(QNumberType x) const { return QNumberType(std::tanh(math::ToFloat(x))); } template - QNumberType Tanh::Backward(QNumberType x) const + OPTIMIZE_FOR_SPEED + QNumberType + Tanh::Backward(QNumberType x) const { QNumberType y = Forward(x); return QNumberType(0.9999f) - y * y; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Tanh; + extern template class Tanh; + extern template class Tanh; #endif +} diff --git a/numerical/neural_network/activation/test/TestSoftmax.cpp b/numerical/neural_network/activation/test/TestSoftmax.cpp index 5dcc1712..7c069693 100644 --- a/numerical/neural_network/activation/test/TestSoftmax.cpp +++ b/numerical/neural_network/activation/test/TestSoftmax.cpp @@ -57,3 +57,62 @@ TYPED_TEST(TestSoftmax, ComparativeTest) EXPECT_LT(math::ToFloat(y1), math::ToFloat(y2)); } + +TYPED_TEST(TestSoftmax, ForwardVectorNormalizesToOne) +{ + if constexpr (!std::is_floating_point_v) + GTEST_SKIP() << "Softmax vector ops exceed Q-number range"; + + constexpr std::size_t Size = 3; + TypeParam input[Size] = { TypeParam(-0.3f), TypeParam(-0.5f), TypeParam(-0.2f) }; + TypeParam output[Size] = {}; + + this->activation.ForwardVector(output, input); + + float sum = 0.0f; + for (std::size_t i = 0; i < Size; ++i) + sum += math::ToFloat(output[i]); + + EXPECT_NEAR(sum, 1.0f, 0.01f); +} + +TYPED_TEST(TestSoftmax, ForwardVectorPreservesOrdering) +{ + if constexpr (!std::is_floating_point_v) + GTEST_SKIP() << "Softmax vector ops exceed Q-number range"; + + constexpr std::size_t Size = 3; + TypeParam input[Size] = { TypeParam(-0.5f), TypeParam(-0.2f), TypeParam(-0.8f) }; + TypeParam output[Size] = {}; + + this->activation.ForwardVector(output, input); + + EXPECT_GT(math::ToFloat(output[1]), math::ToFloat(output[0])); + EXPECT_GT(math::ToFloat(output[0]), math::ToFloat(output[2])); +} + +TYPED_TEST(TestSoftmax, BackwardVectorProducesCorrectGradient) +{ + if constexpr (!std::is_floating_point_v) + GTEST_SKIP() << "Softmax vector ops exceed Q-number range"; + + constexpr std::size_t Size = 3; + TypeParam input[Size] = { TypeParam(-0.3f), TypeParam(-0.5f), TypeParam(-0.2f) }; + TypeParam output[Size] = {}; + this->activation.ForwardVector(output, input); + + TypeParam outputGradient[Size] = { TypeParam(0.9999f), TypeParam(0.0f), TypeParam(0.0f) }; + TypeParam result[Size] = {}; + + this->activation.BackwardVector(result, input, output, outputGradient); + + float dot = 0.0f; + for (std::size_t i = 0; i < Size; ++i) + dot += math::ToFloat(outputGradient[i]) * math::ToFloat(output[i]); + + for (std::size_t i = 0; i < Size; ++i) + { + float expected = math::ToFloat(output[i]) * (math::ToFloat(outputGradient[i]) - dot); + EXPECT_NEAR(math::ToFloat(result[i]), expected, 0.01f); + } +} diff --git a/numerical/neural_network/layer/CMakeLists.txt b/numerical/neural_network/layer/CMakeLists.txt index f65ca8a4..170a3448 100644 --- a/numerical/neural_network/layer/CMakeLists.txt +++ b/numerical/neural_network/layer/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.layer ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.layer) -target_include_directories(numerical.neural_network.layer INTERFACE +target_include_directories(numerical.neural_network.layer ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.layer INTERFACE +target_link_libraries(numerical.neural_network.layer ${NUMERICAL_VISIBILITY} infra.util numerical.math ) @@ -15,4 +15,8 @@ target_sources(numerical.neural_network.layer PRIVATE Layer.hpp ) +numerical_add_coverage_sources(numerical.neural_network.layer + Dense.cpp +) + add_subdirectory(test) diff --git a/numerical/neural_network/layer/Dense.cpp b/numerical/neural_network/layer/Dense.cpp new file mode 100644 index 00000000..73550169 --- /dev/null +++ b/numerical/neural_network/layer/Dense.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/layer/Dense.hpp" + +namespace neural_network +{ + template class Dense; + template class Dense; + template class Dense; +} diff --git a/numerical/neural_network/layer/Dense.hpp b/numerical/neural_network/layer/Dense.hpp index 847ddbf3..c2a88224 100644 --- a/numerical/neural_network/layer/Dense.hpp +++ b/numerical/neural_network/layer/Dense.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_DENSE_HPP -#define NEURAL_NETWORK_DENSE_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" #include "numerical/neural_network/layer/Layer.hpp" #include @@ -21,6 +25,7 @@ namespace neural_network void Forward(const InputVector& input) override; InputVector& Backward(const OutputVector& output_gradient) override; + const OutputVector& Output() const override; ParameterVector& Parameters() const override; void SetParameters(const ParameterVector& parameters) override; @@ -50,7 +55,7 @@ namespace neural_network {} template - void Dense::Forward(const InputVector& input) + OPTIMIZE_FOR_SPEED void Dense::Forward(const InputVector& input) { this->input = input; @@ -59,18 +64,19 @@ namespace neural_network preActivation[i] = biases[i]; for (std::size_t j = 0; j < InputSize; ++j) preActivation[i] += weights.at(i, j) * input[j]; - - output[i] = activation.Forward(preActivation[i]); } + + activation.ForwardVector(output, preActivation); } template - typename Dense::InputVector& Dense::Backward(const OutputVector& output_gradient) + OPTIMIZE_FOR_SPEED + typename Dense::InputVector& + Dense::Backward(const OutputVector& output_gradient) { OutputVector preActivationGradient; - for (std::size_t i = 0; i < OutputSize; ++i) - preActivationGradient[i] = activation.Backward(output_gradient[i]); + activation.BackwardVector(preActivationGradient, preActivation, output, output_gradient); for (std::size_t j = 0; j < InputSize; ++j) { @@ -90,6 +96,12 @@ namespace neural_network return inputGradient; } + template + const typename Dense::OutputVector& Dense::Output() const + { + return output; + } + template typename Dense::ParameterVector& Dense::Parameters() const { @@ -97,10 +109,16 @@ namespace neural_network for (std::size_t i = 0; i < OutputSize; ++i) for (std::size_t j = 0; j < InputSize; ++j) - parameters[idx++] = weights.at(i, j); + { + parameters[idx] = weights.at(i, j); + ++idx; + } for (std::size_t i = 0; i < OutputSize; ++i) - parameters[idx++] = biases[i]; + { + parameters[idx] = biases[i]; + ++idx; + } return parameters; } @@ -112,11 +130,21 @@ namespace neural_network for (std::size_t i = 0; i < OutputSize; ++i) for (std::size_t j = 0; j < InputSize; ++j) - weights.at(i, j) = parameters[idx++]; + { + weights.at(i, j) = parameters[idx]; + ++idx; + } for (std::size_t i = 0; i < OutputSize; ++i) - biases[i] = parameters[idx++]; + { + biases[i] = parameters[idx]; + ++idx; + } } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Dense; + extern template class Dense; + extern template class Dense; #endif +} diff --git a/numerical/neural_network/layer/Layer.hpp b/numerical/neural_network/layer/Layer.hpp index be122bc2..1a864e29 100644 --- a/numerical/neural_network/layer/Layer.hpp +++ b/numerical/neural_network/layer/Layer.hpp @@ -1,5 +1,4 @@ -#ifndef NEURAL_NETWORK_LAYER_HPP -#define NEURAL_NETWORK_LAYER_HPP +#pragma once #include "numerical/math/Matrix.hpp" @@ -9,6 +8,7 @@ namespace neural_network class Layer { public: + using QNumberType_ = QNumberType; using InputVector = math::Matrix; using OutputVector = math::Matrix; using ParameterVector = math::Matrix; @@ -19,9 +19,8 @@ namespace neural_network virtual void Forward(const InputVector& input) = 0; virtual InputVector& Backward(const OutputVector& output_gradient) = 0; + virtual const OutputVector& Output() const = 0; virtual ParameterVector& Parameters() const = 0; virtual void SetParameters(const ParameterVector& parameters) = 0; }; } - -#endif diff --git a/numerical/neural_network/layer/test/CMakeLists.txt b/numerical/neural_network/layer/test/CMakeLists.txt index 1142040a..1cad64f2 100644 --- a/numerical/neural_network/layer/test/CMakeLists.txt +++ b/numerical/neural_network/layer/test/CMakeLists.txt @@ -4,6 +4,7 @@ emil_add_test(numerical.neural_network.layer_test) target_link_libraries(numerical.neural_network.layer_test PUBLIC gmock_main + numerical.neural_network.activation numerical.neural_network.layer ) diff --git a/numerical/neural_network/layer/test/TestDense.cpp b/numerical/neural_network/layer/test/TestDense.cpp index be6309e2..37347afd 100644 --- a/numerical/neural_network/layer/test/TestDense.cpp +++ b/numerical/neural_network/layer/test/TestDense.cpp @@ -1,7 +1,7 @@ #include "numerical/math/QNumber.hpp" #include "numerical/neural_network/activation/ActivationFunction.hpp" #include "numerical/neural_network/layer/Dense.hpp" -#include "numerical/neural_network/optimizer/GradientDescent.hpp" +#include "numerical/neural_network/optimizer/Optimizer.hpp" #include "gmock/gmock.h" namespace @@ -26,6 +26,22 @@ namespace MOCK_METHOD(Vector, Gradient, (const Vector& parameters), (override)); }; + template + class MockOptimizer + : public neural_network::Optimizer + { + public: + using Result = typename neural_network::Optimizer::Result; + using Vector = typename neural_network::Loss::Vector; + + const Result& Minimize(const Vector& initialGuess, neural_network::Loss& loss) override + { + return result; + } + + Result result{ Vector{}, T(0), 0 }; + }; + template class TestDense : public ::testing::Test @@ -123,10 +139,10 @@ TYPED_TEST(TestDense, BackwardPropagation) dense.Forward(input); - EXPECT_CALL(this->activation, Backward(T(0.5f))) - .WillOnce(testing::Return(T(0.4f))); - EXPECT_CALL(this->activation, Backward(T(0.7f))) - .WillOnce(testing::Return(T(0.5f))); + T expectedPreActivationBackward = T(0.6f); + EXPECT_CALL(this->activation, Backward(expectedPreActivationBackward)) + .Times(TestDense::OutputSize) + .WillRepeatedly(testing::Return(T(0.4f))); dense.Backward(outputGradient); } @@ -156,7 +172,7 @@ TYPED_TEST(TestDense, ParametersExtractionAndSetting) } } -TYPED_TEST(TestDense, OptimizationWithGradientDescent) +TYPED_TEST(TestDense, OptimizationWithMockedOptimizer) { using T = TypeParam; using ParameterVector = typename TestDense::ParameterVector; @@ -166,57 +182,27 @@ TYPED_TEST(TestDense, OptimizationWithGradientDescent) neural_network::Dense::InputSize, TestDense::OutputSize> dense(this->initialWeight, this->activation); - MockLoss loss; - - typename neural_network::GradientDescent::Parameters params; - params.learningRate = T(0.1f); - params.maxIterations = 3; - - neural_network::GradientDescent optimizer(params); + MockOptimizer optimizer; auto initialParams = dense.Parameters(); - // Create gradient vectors - ParameterVector gradVec1; - ParameterVector gradVec2; - ParameterVector gradVec3; - + ParameterVector optimizedParams; for (std::size_t i = 0; i < TotalParams; ++i) - { - gradVec1[i] = T(0.5f); - gradVec2[i] = T(0.4f); - gradVec3[i] = T(0.3f); - } - - { - ::testing::InSequence seq; - - EXPECT_CALL(loss, Cost(testing::_)) - .WillOnce(testing::Return(T(1.0f))); - - EXPECT_CALL(loss, Gradient(testing::_)) - .WillOnce(testing::Return(gradVec1)); - - EXPECT_CALL(loss, Cost(testing::_)) - .WillOnce(testing::Return(T(0.8f))); + optimizedParams[i] = T(0.05f); - EXPECT_CALL(loss, Gradient(testing::_)) - .WillOnce(testing::Return(gradVec2)); + optimizer.result = typename neural_network::Optimizer::Result( + optimizedParams, T(0.4f), 3); - EXPECT_CALL(loss, Cost(testing::_)) - .WillOnce(testing::Return(T(0.6f))); + MockLoss loss; + auto& result = optimizer.Minimize(initialParams, loss); - EXPECT_CALL(loss, Gradient(testing::_)) - .WillOnce(testing::Return(gradVec3)); + dense.SetParameters(result.parameters); - EXPECT_CALL(loss, Cost(testing::_)) - .WillOnce(testing::Return(T(0.4f))); - } - - auto result = optimizer.Minimize(initialParams, loss); + auto updatedParams = dense.Parameters(); + for (std::size_t i = 0; i < TotalParams; ++i) + EXPECT_EQ(updatedParams[i], optimizedParams[i]); - // From your class definition, only verify iterations - EXPECT_EQ(result.iterations, params.maxIterations); + EXPECT_EQ(result.iterations, 3u); } TYPED_TEST(TestDense, FullLayerSequence) @@ -245,9 +231,9 @@ TYPED_TEST(TestDense, FullLayerSequence) EXPECT_CALL(this->activation, Forward(testing::_)) .WillOnce(testing::Return(T(0.6f))); - EXPECT_CALL(this->activation, Backward(outputGradient[0])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.3f))); - EXPECT_CALL(this->activation, Backward(outputGradient[1])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.4f))); } @@ -286,9 +272,9 @@ TYPED_TEST(TestDense, MultipleForwardBackwardPasses) EXPECT_CALL(this->activation, Forward(testing::_)) .WillOnce(testing::Return(T(0.6f))); - EXPECT_CALL(this->activation, Backward(outputGradient1[0])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.3f))); - EXPECT_CALL(this->activation, Backward(outputGradient1[1])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.4f))); EXPECT_CALL(this->activation, Forward(testing::_)) @@ -296,9 +282,9 @@ TYPED_TEST(TestDense, MultipleForwardBackwardPasses) EXPECT_CALL(this->activation, Forward(testing::_)) .WillOnce(testing::Return(T(0.8f))); - EXPECT_CALL(this->activation, Backward(outputGradient2[0])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.5f))); - EXPECT_CALL(this->activation, Backward(outputGradient2[1])) + EXPECT_CALL(this->activation, Backward(testing::_)) .WillOnce(testing::Return(T(0.6f))); } diff --git a/numerical/neural_network/losses/BinaryCrossEntropy.cpp b/numerical/neural_network/losses/BinaryCrossEntropy.cpp new file mode 100644 index 00000000..9b119e04 --- /dev/null +++ b/numerical/neural_network/losses/BinaryCrossEntropy.cpp @@ -0,0 +1,6 @@ +#include "numerical/neural_network/losses/BinaryCrossEntropy.hpp" + +namespace neural_network +{ + template class BinaryCrossEntropy; +} diff --git a/numerical/neural_network/losses/BinaryCrossEntropy.hpp b/numerical/neural_network/losses/BinaryCrossEntropy.hpp index 4b1259b7..fd4976e8 100644 --- a/numerical/neural_network/losses/BinaryCrossEntropy.hpp +++ b/numerical/neural_network/losses/BinaryCrossEntropy.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_LOSSES_BINARY_CROSS_ENTROPY_HPP -#define NEURAL_NETWORK_LOSSES_BINARY_CROSS_ENTROPY_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/losses/Loss.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" #include @@ -34,7 +38,9 @@ namespace neural_network {} template - QNumberType BinaryCrossEntropy::Cost(const Vector& parameters) + OPTIMIZE_FOR_SPEED + QNumberType + BinaryCrossEntropy::Cost(const Vector& parameters) { QNumberType cost = QNumberType(0.0f); @@ -51,19 +57,23 @@ namespace neural_network template typename BinaryCrossEntropy::Vector - BinaryCrossEntropy::Gradient(const Vector& parameters) + OPTIMIZE_FOR_SPEED + BinaryCrossEntropy::Gradient(const Vector& parameters) { Vector gradient; + auto regGradient = regularization.Gradient(parameters); for (std::size_t i = 0; i < NumberOfFeatures; ++i) { QNumberType pred = std::max(std::min(parameters[i], QNumberType(0.9999f)), QNumberType(0.0001f)); - gradient[i] = (pred - target[i]) / (pred * (QNumberType(0.9999f) - pred)) + regularization.Calculate(parameters); + gradient[i] = (pred - target[i]) / (pred * (QNumberType(0.9999f) - pred)) + regGradient[i]; } return gradient; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class BinaryCrossEntropy; #endif +} diff --git a/numerical/neural_network/losses/CMakeLists.txt b/numerical/neural_network/losses/CMakeLists.txt index 8885b901..d2229f2c 100644 --- a/numerical/neural_network/losses/CMakeLists.txt +++ b/numerical/neural_network/losses/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.losses ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.losses) -target_include_directories(numerical.neural_network.losses INTERFACE +target_include_directories(numerical.neural_network.losses ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.losses INTERFACE +target_link_libraries(numerical.neural_network.losses ${NUMERICAL_VISIBILITY} infra.util numerical.math numerical.neural_network.activation @@ -20,4 +20,11 @@ target_sources(numerical.neural_network.losses PRIVATE MeanSquaredError.hpp ) +numerical_add_coverage_sources(numerical.neural_network.losses + MeanSquaredError.cpp + MeanAbsoluteError.cpp + BinaryCrossEntropy.cpp + CategoricalCrossEntropy.cpp +) + add_subdirectory(test) diff --git a/numerical/neural_network/losses/CategoricalCrossEntropy.cpp b/numerical/neural_network/losses/CategoricalCrossEntropy.cpp new file mode 100644 index 00000000..df87fde3 --- /dev/null +++ b/numerical/neural_network/losses/CategoricalCrossEntropy.cpp @@ -0,0 +1,6 @@ +#include "numerical/neural_network/losses/CategoricalCrossEntropy.hpp" + +namespace neural_network +{ + template class CategoricalCrossEntropy; +} diff --git a/numerical/neural_network/losses/CategoricalCrossEntropy.hpp b/numerical/neural_network/losses/CategoricalCrossEntropy.hpp index 247251dd..168bd58f 100644 --- a/numerical/neural_network/losses/CategoricalCrossEntropy.hpp +++ b/numerical/neural_network/losses/CategoricalCrossEntropy.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_LOSSES_CATEGORICAL_CROSS_ENTROPY_HPP -#define NEURAL_NETWORK_LOSSES_CATEGORICAL_CROSS_ENTROPY_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/activation/Softmax.hpp" #include "numerical/neural_network/losses/Loss.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" @@ -39,7 +43,8 @@ namespace neural_network template typename CategoricalCrossEntropy::Vector - CategoricalCrossEntropy::ComputeSoftmaxProbabilities(const Vector& x) const + OPTIMIZE_FOR_SPEED + CategoricalCrossEntropy::ComputeSoftmaxProbabilities(const Vector& x) const { Vector output; QNumberType sum = QNumberType(0.0f); @@ -60,7 +65,9 @@ namespace neural_network } template - QNumberType CategoricalCrossEntropy::Cost(const Vector& parameters) + OPTIMIZE_FOR_SPEED + QNumberType + CategoricalCrossEntropy::Cost(const Vector& parameters) { Vector probabilities = ComputeSoftmaxProbabilities(parameters); QNumberType cost = QNumberType(0.0f); @@ -73,17 +80,20 @@ namespace neural_network template typename CategoricalCrossEntropy::Vector - CategoricalCrossEntropy::Gradient(const Vector& parameters) + OPTIMIZE_FOR_SPEED + CategoricalCrossEntropy::Gradient(const Vector& parameters) { - auto reg = regularization.Calculate(parameters); + auto regGradient = regularization.Gradient(parameters); Vector probabilities = ComputeSoftmaxProbabilities(parameters); Vector gradient; for (std::size_t i = 0; i < NumberOfFeatures; ++i) - gradient[i] = probabilities[i] - target[i] + reg; + gradient[i] = probabilities[i] - target[i] + regGradient[i]; return gradient; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class CategoricalCrossEntropy; #endif +} diff --git a/numerical/neural_network/losses/Loss.hpp b/numerical/neural_network/losses/Loss.hpp index c4e6f1a0..4284f906 100644 --- a/numerical/neural_network/losses/Loss.hpp +++ b/numerical/neural_network/losses/Loss.hpp @@ -1,5 +1,4 @@ -#ifndef NEURAL_NETWORK_LOSSES_LOSS_HPP -#define NEURAL_NETWORK_LOSSES_LOSS_HPP +#pragma once #include "numerical/math/Matrix.hpp" @@ -8,7 +7,7 @@ namespace neural_network template class Loss { - static_assert(math::is_qnumber::value || std::is_floating_point::value, + static_assert(math::is_qnumber_v || std::is_floating_point_v, "Loss can only be instantiated with math::QNumber types."); public: @@ -18,5 +17,3 @@ namespace neural_network virtual Vector Gradient(const Vector& parameters) = 0; }; } - -#endif diff --git a/numerical/neural_network/losses/MeanAbsoluteError.cpp b/numerical/neural_network/losses/MeanAbsoluteError.cpp new file mode 100644 index 00000000..7a5c6aa6 --- /dev/null +++ b/numerical/neural_network/losses/MeanAbsoluteError.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/losses/MeanAbsoluteError.hpp" + +namespace neural_network +{ + template class MeanAbsoluteError; + template class MeanAbsoluteError; + template class MeanAbsoluteError; +} diff --git a/numerical/neural_network/losses/MeanAbsoluteError.hpp b/numerical/neural_network/losses/MeanAbsoluteError.hpp index 016ea4d5..630bfe40 100644 --- a/numerical/neural_network/losses/MeanAbsoluteError.hpp +++ b/numerical/neural_network/losses/MeanAbsoluteError.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_LOSSES_MEAN_ABSOLUTE_ERROR_HPP -#define NEURAL_NETWORK_LOSSES_MEAN_ABSOLUTE_ERROR_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/losses/Loss.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" @@ -31,7 +35,9 @@ namespace neural_network {} template - QNumberType MeanAbsoluteError::Cost(const Vector& parameters) + OPTIMIZE_FOR_SPEED + QNumberType + MeanAbsoluteError::Cost(const Vector& parameters) { QNumberType cost = QNumberType(0.0f); @@ -45,18 +51,25 @@ namespace neural_network } template - typename MeanAbsoluteError::Vector MeanAbsoluteError::Gradient(const Vector& parameters) + OPTIMIZE_FOR_SPEED + typename MeanAbsoluteError::Vector + MeanAbsoluteError::Gradient(const Vector& parameters) { Vector gradient; + auto regGradient = regularization.Gradient(parameters); for (std::size_t i = 0; i < NumberOfFeatures; ++i) { auto diff = parameters[i] - target[i]; - gradient[i] = diff > QNumberType(0.0f) ? QNumberType(0.9999f) : QNumberType(-0.9999f); + gradient[i] = (diff > QNumberType(0.0f) ? QNumberType(0.9999f) : QNumberType(-0.9999f)) + regGradient[i]; } return gradient; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class MeanAbsoluteError; + extern template class MeanAbsoluteError; + extern template class MeanAbsoluteError; #endif +} diff --git a/numerical/neural_network/losses/MeanSquaredError.cpp b/numerical/neural_network/losses/MeanSquaredError.cpp new file mode 100644 index 00000000..d30ca40c --- /dev/null +++ b/numerical/neural_network/losses/MeanSquaredError.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/losses/MeanSquaredError.hpp" + +namespace neural_network +{ + template class MeanSquaredError; + template class MeanSquaredError; + template class MeanSquaredError; +} diff --git a/numerical/neural_network/losses/MeanSquaredError.hpp b/numerical/neural_network/losses/MeanSquaredError.hpp index f7f372de..2d832900 100644 --- a/numerical/neural_network/losses/MeanSquaredError.hpp +++ b/numerical/neural_network/losses/MeanSquaredError.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_LOSSES_MEAN_SQUARED_ERROR_HPP -#define NEURAL_NETWORK_LOSSES_MEAN_SQUARED_ERROR_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/losses/Loss.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" @@ -32,7 +36,9 @@ namespace neural_network {} template - QNumberType MeanSquaredError::Cost(const Vector& parameters) + OPTIMIZE_FOR_SPEED + QNumberType + MeanSquaredError::Cost(const Vector& parameters) { QNumberType cost = QNumberType(0.0f); @@ -46,16 +52,22 @@ namespace neural_network } template - typename MeanSquaredError::Vector MeanSquaredError::Gradient(const Vector& parameters) + OPTIMIZE_FOR_SPEED + typename MeanSquaredError::Vector + MeanSquaredError::Gradient(const Vector& parameters) { Vector gradient; - auto reg = regularization.Calculate(parameters); + auto regGradient = regularization.Gradient(parameters); for (std::size_t i = 0; i < NumberOfFeatures; ++i) - gradient[i] = parameters[i] - target[i] + reg; + gradient[i] = parameters[i] - target[i] + regGradient[i]; return gradient; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class MeanSquaredError; + extern template class MeanSquaredError; + extern template class MeanSquaredError; #endif +} diff --git a/numerical/neural_network/losses/test/TestBinaryCrossEntropy.cpp b/numerical/neural_network/losses/test/TestBinaryCrossEntropy.cpp index 2fd2a0d4..d3619ac2 100644 --- a/numerical/neural_network/losses/test/TestBinaryCrossEntropy.cpp +++ b/numerical/neural_network/losses/test/TestBinaryCrossEntropy.cpp @@ -10,6 +10,7 @@ namespace public: using Vector = typename neural_network::Regularization::Vector; MOCK_METHOD(QNumberType, Calculate, (const Vector& parameters), (const, override)); + MOCK_METHOD(Vector, Gradient, (const Vector& parameters), (const, override)); }; template @@ -92,9 +93,12 @@ TYPED_TEST(TestBinaryCrossEntropy, GradientTest) typename TestBinaryCrossEntropy::Vector parameters{ TypeParam(0.6f), TypeParam(0.4f) }; TypeParam regValue = TypeParam(0.1f); - EXPECT_CALL(this->mockRegularization, Calculate(::testing::_)) - .Times(this->NumberOfFeature) - .WillRepeatedly(::testing::Return(regValue)); + typename TestBinaryCrossEntropy::Vector regGradient; + for (std::size_t i = 0; i < this->NumberOfFeature; ++i) + regGradient[i] = regValue; + + EXPECT_CALL(this->mockRegularization, Gradient(::testing::_)) + .WillOnce(::testing::Return(regGradient)); this->loss.emplace(this->target, this->mockRegularization); auto gradient = this->loss->Gradient(parameters); diff --git a/numerical/neural_network/losses/test/TestCategoricalCrossEntropy.cpp b/numerical/neural_network/losses/test/TestCategoricalCrossEntropy.cpp index 04623bff..26a3131b 100644 --- a/numerical/neural_network/losses/test/TestCategoricalCrossEntropy.cpp +++ b/numerical/neural_network/losses/test/TestCategoricalCrossEntropy.cpp @@ -11,6 +11,7 @@ namespace public: using Vector = typename neural_network::Regularization::Vector; MOCK_METHOD(QNumberType, Calculate, (const Vector& parameters), (const, override)); + MOCK_METHOD(Vector, Gradient, (const Vector& parameters), (const, override)); }; template @@ -85,8 +86,12 @@ TYPED_TEST(TestCategoricalCrossEntropy, GradientTest) typename TestCategoricalCrossEntropy::Vector parameters{ TypeParam(0.2f), TypeParam(0.5f) }; TypeParam regValue = TypeParam(0.1f); - EXPECT_CALL(this->mockRegularization, Calculate(::testing::_)) - .WillOnce(::testing::Return(regValue)); + typename TestCategoricalCrossEntropy::Vector regGradient; + for (std::size_t i = 0; i < this->NumberOfFeature; ++i) + regGradient[i] = regValue; + + EXPECT_CALL(this->mockRegularization, Gradient(::testing::_)) + .WillOnce(::testing::Return(regGradient)); this->loss.emplace(this->target, this->mockRegularization); auto gradient = this->loss->Gradient(parameters); diff --git a/numerical/neural_network/losses/test/TestMeanAbsoluteError.cpp b/numerical/neural_network/losses/test/TestMeanAbsoluteError.cpp index 914c8c52..54e4c538 100644 --- a/numerical/neural_network/losses/test/TestMeanAbsoluteError.cpp +++ b/numerical/neural_network/losses/test/TestMeanAbsoluteError.cpp @@ -10,6 +10,7 @@ namespace public: using Vector = typename neural_network::Regularization::Vector; MOCK_METHOD(QNumberType, Calculate, (const Vector& parameters), (const, override)); + MOCK_METHOD(Vector, Gradient, (const Vector& parameters), (const, override)); }; template diff --git a/numerical/neural_network/losses/test/TestMeanSquaredError.cpp b/numerical/neural_network/losses/test/TestMeanSquaredError.cpp index f0339fad..bb262f8a 100644 --- a/numerical/neural_network/losses/test/TestMeanSquaredError.cpp +++ b/numerical/neural_network/losses/test/TestMeanSquaredError.cpp @@ -10,6 +10,7 @@ namespace public: using Vector = typename neural_network::Regularization::Vector; MOCK_METHOD(QNumberType, Calculate, (const Vector& parameters), (const, override)); + MOCK_METHOD(Vector, Gradient, (const Vector& parameters), (const, override)); }; template @@ -96,3 +97,21 @@ TYPED_TEST(TestMeanSquaredError, MultipleParameters) EXPECT_NEAR(math::ToFloat(cost), math::ToFloat(mseValue + regValue), 0.001f); } } + +TYPED_TEST(TestMeanSquaredError, GradientIncludesRegularization) +{ + typename TestMeanSquaredError::Vector parameters{ TypeParam(0.7f), TypeParam(-0.1f) }; + typename TestMeanSquaredError::Vector regGradient{ TypeParam(0.01f), TypeParam(-0.02f) }; + + EXPECT_CALL(this->mockRegularization, Gradient(::testing::_)) + .WillOnce(::testing::Return(regGradient)); + + this->loss.emplace(this->target, this->mockRegularization); + auto gradient = this->loss->Gradient(parameters); + + for (std::size_t i = 0; i < TestMeanSquaredError::NumberOfFeature; ++i) + { + float expected = math::ToFloat(parameters[i] - this->target[i] + regGradient[i]); + EXPECT_NEAR(math::ToFloat(gradient[i]), expected, 0.001f); + } +} diff --git a/numerical/neural_network/model/CMakeLists.txt b/numerical/neural_network/model/CMakeLists.txt index d455e939..6a7b8f5f 100644 --- a/numerical/neural_network/model/CMakeLists.txt +++ b/numerical/neural_network/model/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.model ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.model) -target_include_directories(numerical.neural_network.model INTERFACE +target_include_directories(numerical.neural_network.model ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.model INTERFACE +target_link_libraries(numerical.neural_network.model ${NUMERICAL_VISIBILITY} infra.util numerical.math numerical.neural_network.activation diff --git a/numerical/neural_network/model/Model.hpp b/numerical/neural_network/model/Model.hpp index ddba13fc..d7219208 100644 --- a/numerical/neural_network/model/Model.hpp +++ b/numerical/neural_network/model/Model.hpp @@ -1,5 +1,10 @@ -#ifndef NEURAL_NETWORK_MODEL_HPP -#define NEURAL_NETWORK_MODEL_HPP +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "infra/util/BoundedVector.hpp" #include "numerical/neural_network/layer/Layer.hpp" @@ -120,9 +125,15 @@ namespace neural_network template OutputVector ForwardImpl(const InputVector& input, std::index_sequence); + template + void ForwardLayer(const InputType& layerInput); + template InputVector BackwardImpl(const OutputVector& output_gradient, std::index_sequence); + template + InputVector BackwardLayer(const GradType& gradient); + template void SetParametersImpl(const ParameterVector& parameters, std::index_sequence); @@ -146,7 +157,8 @@ namespace neural_network template typename Model::OutputVector - Model::Forward(const InputVector& input) + OPTIMIZE_FOR_SPEED + Model::Forward(const InputVector& input) { currentInput = input; return ForwardImpl(input, std::make_index_sequence{}); @@ -154,7 +166,8 @@ namespace neural_network template typename Model::InputVector - Model::Backward(const OutputVector& output_gradient) + OPTIMIZE_FOR_SPEED + Model::Backward(const OutputVector& output_gradient) { return BackwardImpl(output_gradient, std::make_index_sequence{}); } @@ -187,7 +200,17 @@ namespace neural_network typename Model::OutputVector Model::ForwardImpl(const InputVector& input, std::index_sequence) { - return OutputVector(); + ForwardLayer<0>(input); + return std::get(layers).Output(); + } + + template + template + void Model::ForwardLayer(const InputType& layerInput) + { + std::get(layers).Forward(layerInput); + if constexpr (I + 1 < sizeof...(Layers)) + ForwardLayer(std::get(layers).Output()); } template @@ -195,7 +218,19 @@ namespace neural_network typename Model::InputVector Model::BackwardImpl(const OutputVector& output_gradient, std::index_sequence) { - return InputVector(); + return BackwardLayer(output_gradient); + } + + template + template + typename Model::InputVector + Model::BackwardLayer(const GradType& gradient) + { + auto& inputGrad = std::get(layers).Backward(gradient); + if constexpr (I == 0) + return inputGrad; + else + return BackwardLayer(inputGrad); } template @@ -251,5 +286,3 @@ namespace neural_network offset += Layer::ParameterSize; } } - -#endif diff --git a/numerical/neural_network/model/test/TestModel.cpp b/numerical/neural_network/model/test/TestModel.cpp index 037b182b..66491e07 100644 --- a/numerical/neural_network/model/test/TestModel.cpp +++ b/numerical/neural_network/model/test/TestModel.cpp @@ -43,6 +43,7 @@ namespace MOCK_METHOD(void, Forward, (const InputVector&), (override)); MOCK_METHOD(InputVector&, Backward, (const OutputVector&), (override)); + MOCK_METHOD(const OutputVector&, Output, (), (const, override)); MOCK_METHOD(ParameterVector&, Parameters, (), (const, override)); MOCK_METHOD(void, SetParameters, (const ParameterVector&), (override)); @@ -62,6 +63,12 @@ namespace return inputGradient; }); + ON_CALL(*this, Output()) + .WillByDefault([this]() -> const OutputVector& + { + return outputValue; + }); + ON_CALL(*this, Parameters()) .WillByDefault([this]() -> ParameterVector& { @@ -76,6 +83,7 @@ namespace } InputVector inputGradient; + OutputVector outputValue; ParameterVector parameters; }; diff --git a/numerical/neural_network/optimizer/CMakeLists.txt b/numerical/neural_network/optimizer/CMakeLists.txt index 4815253b..a5cf8930 100644 --- a/numerical/neural_network/optimizer/CMakeLists.txt +++ b/numerical/neural_network/optimizer/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.optimizer ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.optimizer) -target_include_directories(numerical.neural_network.optimizer INTERFACE +target_include_directories(numerical.neural_network.optimizer ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.optimizer INTERFACE +target_link_libraries(numerical.neural_network.optimizer ${NUMERICAL_VISIBILITY} infra.util numerical.math numerical.neural_network.losses @@ -16,4 +16,8 @@ target_sources(numerical.neural_network.optimizer PRIVATE Optimizer.hpp ) +numerical_add_coverage_sources(numerical.neural_network.optimizer + GradientDescent.cpp +) + add_subdirectory(test) diff --git a/numerical/neural_network/optimizer/GradientDescent.cpp b/numerical/neural_network/optimizer/GradientDescent.cpp new file mode 100644 index 00000000..180efab5 --- /dev/null +++ b/numerical/neural_network/optimizer/GradientDescent.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/optimizer/GradientDescent.hpp" + +namespace neural_network +{ + template class GradientDescent; + template class GradientDescent; + template class GradientDescent; +} diff --git a/numerical/neural_network/optimizer/GradientDescent.hpp b/numerical/neural_network/optimizer/GradientDescent.hpp index 93ec8d0a..7c058345 100644 --- a/numerical/neural_network/optimizer/GradientDescent.hpp +++ b/numerical/neural_network/optimizer/GradientDescent.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_GRADIENT_DESCENT_HPP -#define NEURAL_NETWORK_GRADIENT_DESCENT_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/optimizer/Optimizer.hpp" #include @@ -10,7 +14,7 @@ namespace neural_network class GradientDescent : public Optimizer { - static_assert(math::is_qnumber::value || std::is_floating_point::value, + static_assert(math::is_qnumber_v || std::is_floating_point_v, "GradientDescent can only be instantiated with math::QNumber types."); public: @@ -42,7 +46,7 @@ namespace neural_network } template - const typename GradientDescent::Result& GradientDescent::Minimize(const Vector& initialGuess, Loss& loss) + OPTIMIZE_FOR_SPEED const typename GradientDescent::Result& GradientDescent::Minimize(const Vector& initialGuess, Loss& loss) { auto currentParams = initialGuess; auto currentCost = loss.Cost(currentParams); @@ -64,6 +68,10 @@ namespace neural_network return *result; } -} +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class GradientDescent; + extern template class GradientDescent; + extern template class GradientDescent; #endif +} diff --git a/numerical/neural_network/optimizer/Optimizer.hpp b/numerical/neural_network/optimizer/Optimizer.hpp index a5733a2b..26d2e4d4 100644 --- a/numerical/neural_network/optimizer/Optimizer.hpp +++ b/numerical/neural_network/optimizer/Optimizer.hpp @@ -1,5 +1,4 @@ -#ifndef NEURAL_NETWORK_OPTIMIZER_HPP -#define NEURAL_NETWORK_OPTIMIZER_HPP +#pragma once #include "numerical/math/QNumber.hpp" #include "numerical/neural_network/losses/Loss.hpp" @@ -9,7 +8,7 @@ namespace neural_network template class Optimizer { - static_assert(math::is_qnumber::value || std::is_floating_point::value, + static_assert(math::is_qnumber_v || std::is_floating_point_v, "Optimizer can only be instantiated with math::QNumber types."); public: @@ -31,5 +30,3 @@ namespace neural_network virtual const Result& Minimize(const Vector& initialGuess, Loss& loss) = 0; }; } - -#endif diff --git a/numerical/neural_network/regularization/CMakeLists.txt b/numerical/neural_network/regularization/CMakeLists.txt index 8091d67f..6eb923fa 100644 --- a/numerical/neural_network/regularization/CMakeLists.txt +++ b/numerical/neural_network/regularization/CMakeLists.txt @@ -1,11 +1,11 @@ -add_library(numerical.neural_network.regularization ${EMIL_EXCLUDE_FROM_ALL} INTERFACE) +numerical_add_header_library(numerical.neural_network.regularization) -target_include_directories(numerical.neural_network.regularization INTERFACE +target_include_directories(numerical.neural_network.regularization ${NUMERICAL_VISIBILITY} "$" "$" ) -target_link_libraries(numerical.neural_network.regularization INTERFACE +target_link_libraries(numerical.neural_network.regularization ${NUMERICAL_VISIBILITY} infra.util numerical.math ) @@ -16,4 +16,9 @@ target_sources(numerical.neural_network.regularization PRIVATE Regularization.hpp ) +numerical_add_coverage_sources(numerical.neural_network.regularization + L1.cpp + L2.cpp +) + add_subdirectory(test) diff --git a/numerical/neural_network/regularization/L1.cpp b/numerical/neural_network/regularization/L1.cpp new file mode 100644 index 00000000..975bb0b3 --- /dev/null +++ b/numerical/neural_network/regularization/L1.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/regularization/L1.hpp" + +namespace neural_network +{ + template class L1; + template class L1; + template class L1; +} diff --git a/numerical/neural_network/regularization/L1.hpp b/numerical/neural_network/regularization/L1.hpp index 5b8f2d82..e3f0a723 100644 --- a/numerical/neural_network/regularization/L1.hpp +++ b/numerical/neural_network/regularization/L1.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_L1_HPP -#define NEURAL_NETWORK_L1_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" namespace neural_network @@ -14,6 +18,7 @@ namespace neural_network explicit L1(QNumberType lambda); QNumberType Calculate(const Vector& parameters) const override; + Vector Gradient(const Vector& parameters) const override; private: QNumberType lambda; @@ -27,7 +32,9 @@ namespace neural_network {} template - QNumberType L1::Calculate(const Vector& parameters) const + OPTIMIZE_FOR_SPEED + QNumberType + L1::Calculate(const Vector& parameters) const { QNumberType sum = QNumberType(0.0f); @@ -36,6 +43,30 @@ namespace neural_network return lambda * sum; } -} + template + OPTIMIZE_FOR_SPEED + typename L1::Vector + L1::Gradient(const Vector& parameters) const + { + Vector gradient; + + for (std::size_t i = 0; i < Size; ++i) + { + if (parameters[i] > QNumberType(0.0f)) + gradient[i] = lambda; + else if (parameters[i] < QNumberType(0.0f)) + gradient[i] = -lambda; + else + gradient[i] = QNumberType(0.0f); + } + + return gradient; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class L1; + extern template class L1; + extern template class L1; #endif +} diff --git a/numerical/neural_network/regularization/L2.cpp b/numerical/neural_network/regularization/L2.cpp new file mode 100644 index 00000000..4e161826 --- /dev/null +++ b/numerical/neural_network/regularization/L2.cpp @@ -0,0 +1,8 @@ +#include "numerical/neural_network/regularization/L2.hpp" + +namespace neural_network +{ + template class L2; + template class L2; + template class L2; +} diff --git a/numerical/neural_network/regularization/L2.hpp b/numerical/neural_network/regularization/L2.hpp index cb0d04df..55b67072 100644 --- a/numerical/neural_network/regularization/L2.hpp +++ b/numerical/neural_network/regularization/L2.hpp @@ -1,6 +1,10 @@ -#ifndef NEURAL_NETWORK_L2_HPP -#define NEURAL_NETWORK_L2_HPP +#pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/neural_network/regularization/Regularization.hpp" namespace neural_network @@ -14,6 +18,7 @@ namespace neural_network explicit L2(QNumberType lambda); QNumberType Calculate(const Vector& parameters) const override; + Vector Gradient(const Vector& parameters) const override; private: QNumberType lambda; @@ -27,7 +32,9 @@ namespace neural_network {} template - QNumberType L2::Calculate(const Vector& parameters) const + OPTIMIZE_FOR_SPEED + QNumberType + L2::Calculate(const Vector& parameters) const { QNumberType sum = QNumberType(0.0f); @@ -36,6 +43,23 @@ namespace neural_network return QNumberType(math::ToFloat(lambda * sum) / 2.0f); } -} + template + OPTIMIZE_FOR_SPEED + typename L2::Vector + L2::Gradient(const Vector& parameters) const + { + Vector gradient; + + for (std::size_t i = 0; i < Size; ++i) + gradient[i] = lambda * parameters[i]; + + return gradient; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class L2; + extern template class L2; + extern template class L2; #endif +} diff --git a/numerical/neural_network/regularization/Regularization.hpp b/numerical/neural_network/regularization/Regularization.hpp index 4a589561..97d5e8d4 100644 --- a/numerical/neural_network/regularization/Regularization.hpp +++ b/numerical/neural_network/regularization/Regularization.hpp @@ -1,5 +1,4 @@ -#ifndef NEURAL_NETWORK_REGULARIZATION_HPP -#define NEURAL_NETWORK_REGULARIZATION_HPP +#pragma once #include "numerical/math/Matrix.hpp" @@ -11,7 +10,6 @@ namespace neural_network public: using Vector = math::Vector; virtual QNumberType Calculate(const Vector& parameters) const = 0; + virtual Vector Gradient(const Vector& parameters) const = 0; }; } - -#endif diff --git a/numerical/neural_network/regularization/test/TestL1.cpp b/numerical/neural_network/regularization/test/TestL1.cpp index d0178557..6025ef07 100644 --- a/numerical/neural_network/regularization/test/TestL1.cpp +++ b/numerical/neural_network/regularization/test/TestL1.cpp @@ -61,3 +61,35 @@ TYPED_TEST(TestL1, DifferentLambdaValue) EXPECT_NEAR(math::ToFloat(result), math::ToFloat(expected), 1e-3f); } + +TYPED_TEST(TestL1, GradientPositiveValues) +{ + using Vector = typename neural_network::L1::Vector; + Vector parameters; + parameters[0] = TypeParam(0.1f); + parameters[1] = TypeParam(0.2f); + parameters[2] = TypeParam(0.3f); + parameters[3] = TypeParam(0.4f); + + Vector gradient = TestFixture::regularization.Gradient(parameters); + + for (std::size_t i = 0; i < TestFixture::Size; ++i) + EXPECT_NEAR(math::ToFloat(gradient[i]), 0.001f, 1e-3f); +} + +TYPED_TEST(TestL1, GradientMixedValues) +{ + using Vector = typename neural_network::L1::Vector; + Vector parameters; + parameters[0] = TypeParam(0.1f); + parameters[1] = TypeParam(-0.2f); + parameters[2] = TypeParam(0.0f); + parameters[3] = TypeParam(-0.3f); + + Vector gradient = TestFixture::regularization.Gradient(parameters); + + EXPECT_NEAR(math::ToFloat(gradient[0]), 0.001f, 1e-3f); + EXPECT_NEAR(math::ToFloat(gradient[1]), -0.001f, 1e-3f); + EXPECT_NEAR(math::ToFloat(gradient[2]), 0.0f, 1e-3f); + EXPECT_NEAR(math::ToFloat(gradient[3]), -0.001f, 1e-3f); +} diff --git a/numerical/neural_network/regularization/test/TestL2.cpp b/numerical/neural_network/regularization/test/TestL2.cpp index eeeb6f23..743e7501 100644 --- a/numerical/neural_network/regularization/test/TestL2.cpp +++ b/numerical/neural_network/regularization/test/TestL2.cpp @@ -15,7 +15,7 @@ namespace neural_network::L2 regularization{ T(0.001f) }; }; - using TestedTypes = ::testing::Types; + using TestedTypes = ::testing::Types; TYPED_TEST_SUITE(TestL2, TestedTypes); } @@ -41,7 +41,8 @@ TYPED_TEST(TestL2, CalculatePositiveValues) float expectedFloat = 0.0000047f; TypeParam result = TestFixture::regularization.Calculate(parameters); - EXPECT_NEAR(math::ToFloat(result), expectedFloat, 1e-8f); + float tolerance = std::is_same_v ? 1e-4f : 1e-8f; + EXPECT_NEAR(math::ToFloat(result), expectedFloat, tolerance); } TYPED_TEST(TestL2, CalculateMixedValues) @@ -57,7 +58,8 @@ TYPED_TEST(TestL2, CalculateMixedValues) float expectedFloat = 0.000008425f; TypeParam result = TestFixture::regularization.Calculate(parameters); - EXPECT_NEAR(math::ToFloat(result), expectedFloat, 1e-7f); + float tolerance = std::is_same_v ? 1e-4f : 1e-7f; + EXPECT_NEAR(math::ToFloat(result), expectedFloat, tolerance); } TYPED_TEST(TestL2, DifferentLambdaValue) @@ -75,5 +77,36 @@ TYPED_TEST(TestL2, DifferentLambdaValue) float expectedFloat = 0.000015f; TypeParam result = regularization.Calculate(parameters); - EXPECT_NEAR(math::ToFloat(result), expectedFloat, 1e-7f); + float tolerance = std::is_same_v ? 1e-4f : 1e-7f; + EXPECT_NEAR(math::ToFloat(result), expectedFloat, tolerance); +} + +TYPED_TEST(TestL2, GradientPositiveValues) +{ + using Vector = typename neural_network::L2::Vector; + Vector parameters; + parameters[0] = TypeParam(0.1f); + parameters[1] = TypeParam(0.2f); + parameters[2] = TypeParam(0.3f); + parameters[3] = TypeParam(0.4f); + + Vector gradient = TestFixture::regularization.Gradient(parameters); + + for (std::size_t i = 0; i < TestFixture::Size; ++i) + EXPECT_NEAR(math::ToFloat(gradient[i]), math::ToFloat(TypeParam(0.001f) * parameters[i]), 1e-3f); +} + +TYPED_TEST(TestL2, GradientMixedValues) +{ + using Vector = typename neural_network::L2::Vector; + Vector parameters; + parameters[0] = TypeParam(0.1f); + parameters[1] = TypeParam(-0.2f); + parameters[2] = TypeParam(0.0f); + parameters[3] = TypeParam(-0.3f); + + Vector gradient = TestFixture::regularization.Gradient(parameters); + + for (std::size_t i = 0; i < TestFixture::Size; ++i) + EXPECT_NEAR(math::ToFloat(gradient[i]), math::ToFloat(TypeParam(0.001f) * parameters[i]), 1e-3f); } diff --git a/numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp b/numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp index b1f003b7..1c9ba431 100644 --- a/numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp +++ b/numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp @@ -1,5 +1,9 @@ #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/math/QNumber.hpp" diff --git a/numerical/solvers/GaussianElimination.hpp b/numerical/solvers/GaussianElimination.hpp index 2b533797..66c7fee1 100644 --- a/numerical/solvers/GaussianElimination.hpp +++ b/numerical/solvers/GaussianElimination.hpp @@ -1,5 +1,9 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + #include "infra/util/ReallyAssert.hpp" #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/Matrix.hpp" diff --git a/numerical/solvers/LevinsonDurbin.hpp b/numerical/solvers/LevinsonDurbin.hpp index 1bd254e0..286ada0a 100644 --- a/numerical/solvers/LevinsonDurbin.hpp +++ b/numerical/solvers/LevinsonDurbin.hpp @@ -1,5 +1,10 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" #include "numerical/math/Toeplitz.hpp" #include "numerical/solvers/Solver.hpp" @@ -25,7 +30,8 @@ namespace solvers template typename LevinsonDurbin::SolutionVector - LevinsonDurbin::Solve(const InputMatrix& A, const InputVector& b) + OPTIMIZE_FOR_SPEED + LevinsonDurbin::Solve(const InputMatrix& A, const InputVector& b) { really_assert(IsToeplitz(A)); diff --git a/numerical/solvers/test/TestGaussianElimination.cpp b/numerical/solvers/test/TestGaussianElimination.cpp index 5839f2f7..5d301dc2 100644 --- a/numerical/solvers/test/TestGaussianElimination.cpp +++ b/numerical/solvers/test/TestGaussianElimination.cpp @@ -77,7 +77,15 @@ TYPED_TEST(TestGaussianElimination, solve_back_substitutes_upper_triangular) EXPECT_NEAR(math::ToFloat(result.at(0, 0)), 0.1f, 0.02f); } -TEST(TestGaussianEliminationFloat, solve_system_delegates_per_column) +namespace +{ + class TestGaussianEliminationFloat + : public ::testing::Test + { + }; +} + +TEST_F(TestGaussianEliminationFloat, solve_system_delegates_per_column) { math::SquareMatrix a{ { 0.5f, 0.2f }, diff --git a/numerical/windowing/Windowing.hpp b/numerical/windowing/Windowing.hpp index 8f788828..d52586aa 100644 --- a/numerical/windowing/Windowing.hpp +++ b/numerical/windowing/Windowing.hpp @@ -1,5 +1,9 @@ #pragma once +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + #include "numerical/math/QNumber.hpp" #include diff --git a/release-please-config.json b/release-please-config.json index 9c37258f..f380dc1f 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -6,7 +6,7 @@ "packages": { ".": { "release-type": "simple", - "package-name": "control-toolbox", + "package-name": "numerical-toolbox", "extra-files": [ "CMakeLists.txt" ]