From 23c26277086c78704a17f0dae86da947816320c0 Mon Sep 17 00:00:00 2001 From: George Gekov Date: Mon, 16 Aug 2021 11:32:10 +0100 Subject: MLECO-2079 Adding the C++ KWS example Signed-off-by: Eanna O Cathain Change-Id: I81899bbfaada32f478c2e2fc6441eabb94d8d0fc --- samples/common/src/Audio/MathUtils.cpp | 111 +++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 samples/common/src/Audio/MathUtils.cpp (limited to 'samples/common/src/Audio/MathUtils.cpp') diff --git a/samples/common/src/Audio/MathUtils.cpp b/samples/common/src/Audio/MathUtils.cpp new file mode 100644 index 0000000000..d91b5098e1 --- /dev/null +++ b/samples/common/src/Audio/MathUtils.cpp @@ -0,0 +1,111 @@ +// +// Copyright © 2021 Arm Ltd and Contributors. All rights reserved. +// SPDX-License-Identifier: MIT +// + +#include "MathUtils.hpp" +#include +#include +#include + +void MathUtils::FftF32(std::vector& input, + std::vector& fftOutput) +{ + const int inputLength = input.size(); + + for (int k = 0; k <= inputLength / 2; k++) + { + float sumReal = 0, sumImag = 0; + + for (int t = 0; t < inputLength; t++) + { + float angle = 2 * M_PI * t * k / inputLength; + sumReal += input[t] * cosf(angle); + sumImag += -input[t] * sinf(angle); + } + + /* Arrange output to [real0, realN/2, real1, im1, real2, im2, ...] */ + if (k == 0) + { + fftOutput[0] = sumReal; + } + else if (k == inputLength / 2) + { + fftOutput[1] = sumReal; + } + else + { + fftOutput[k*2] = sumReal; + fftOutput[k*2 + 1] = sumImag; + }; + } +} + +float MathUtils::DotProductF32(const float* srcPtrA, float* srcPtrB, + const int srcLen) +{ + float output = 0.f; + + for (int i = 0; i < srcLen; ++i) + { + output += *srcPtrA++ * *srcPtrB++; + } + return output; +} + +bool MathUtils::ComplexMagnitudeSquaredF32(const float* ptrSrc, + int srcLen, + float* ptrDst, + int dstLen) +{ + if (dstLen < srcLen/2) + { + printf("dstLen must be greater than srcLen/2"); + return false; + } + + for (int j = 0; j < dstLen; ++j) + { + const float real = *ptrSrc++; + const float im = *ptrSrc++; + *ptrDst++ = real*real + im*im; + } + return true; +} + +void MathUtils::VecLogarithmF32(std::vector & input, + std::vector & output) +{ + for (auto in = input.begin(), out = output.begin(); + in != input.end(); ++in, ++out) + { + *out = logf(*in); + } +} + +float MathUtils::MeanF32(const float* ptrSrc, const uint32_t srcLen) +{ + if (!srcLen) + { + return 0.f; + } + + float acc = std::accumulate(ptrSrc, ptrSrc + srcLen, 0.0); + return acc/srcLen; +} + +float MathUtils::StdDevF32(const float* ptrSrc, uint32_t srcLen, float mean) +{ + if (!srcLen) + { + return 0.f; + } + auto VarianceFunction = [mean, srcLen](float acc, const float value) { + return acc + (((value - mean) * (value - mean))/ srcLen); + }; + + float acc = std::accumulate(ptrSrc, ptrSrc + srcLen, 0.0, + VarianceFunction); + return sqrtf(acc); +} + -- cgit v1.2.1