/** ****************************************************************************** * @file : GWMA.c * @brief : Gaussian weighted moving average algorithm, * this is a modified code, which is used for filtering * temperature data after collecting from sensors, window * size is 5 and only calculate the center data of sliding * window array, and the data to the left of the center * data is the mirror fill value. * @author : Charles * @date : 2024-11-20 ****************************************************************************** * @attention * * @copyright 2024 by Charles/https://www.charlesyu1997.com * ****************************************************************************** */
#include"GWMA.h" #include"main.h"
/** * @name initGaussianKernelForGWMA * @brief Initialize the Gaussian kernel data array. * @param kernel[] Kernel data array. * @param size Size of kernel data array. * @param sigma Standard deviation of Gaussian. * @return NONE * */ voidinitGaussianKernelForGWMA(float kernel[], int size, float sigma) { float sum = 0.0; int center = size / 2; int i_gwma; for ( i_gwma = 0; i_gwma < size; i_gwma++) { int x = i_gwma - center; kernel[i_gwma] = exp(-(x * x) / (2 * sigma * sigma)); sum += kernel[i_gwma]; } // Normalization for (int i_gwma = 0; i_gwma < size; i_gwma++) { kernel[i_gwma] /= sum; } } /** * @name updateSlidingWindowForGWMA * @brief Update the sliding window data array and remove the oldest data. * @param window[] Sliding window data array. * @param size Size of sliding window data array. * @param newValue A new value which will be inserted to the end of sliding window. * @return NONE * */ voidupdateSlidingWindowForGWMA(float window[], int size, float newValue) { int i_gwma; for ( i_gwma = 1; i_gwma < ((size+1) / 2) ; i_gwma++) { window[i_gwma - 1] = window[i_gwma]; } // Mirror Padding for (i_gwma = (size / 2) ; i_gwma < size; i_gwma++ ) { window[i_gwma] = newValue; // Insert the new value. } } /** * @name calculateConvolutionForGWMA * @brief Calculate convolution and get the result of GWMA. * @param window[] Sliding window data array. * @param size Size of sliding window data array. * @param newValue A new value which will be inserted to the end of sliding window. * @return NONE * */ floatcalculateConvolutionForGWMA(float window[], float kernel[], int size) { float result = 0.0; int i_gwma = 0; for (i_gwma = 0; i_gwma < size; i_gwma++) { result += window[i_gwma] * kernel[i_gwma]; } return result; }