1 //
2 // Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5
6 #include "MathUtils.hpp"
7 #include <vector>
8 #include <cmath>
9 #include <cstdio>
10
FftF32(std::vector<float> & input,std::vector<float> & fftOutput)11 void MathUtils::FftF32(std::vector<float>& input,
12 std::vector<float>& fftOutput)
13 {
14 const int inputLength = input.size();
15
16 for (int k = 0; k <= inputLength / 2; k++)
17 {
18 float sumReal = 0, sumImag = 0;
19
20 for (int t = 0; t < inputLength; t++)
21 {
22 float angle = 2 * M_PI * t * k / inputLength;
23 sumReal += input[t] * cosf(angle);
24 sumImag += -input[t] * sinf(angle);
25 }
26
27 /* Arrange output to [real0, realN/2, real1, im1, real2, im2, ...] */
28 if (k == 0)
29 {
30 fftOutput[0] = sumReal;
31 }
32 else if (k == inputLength / 2)
33 {
34 fftOutput[1] = sumReal;
35 }
36 else
37 {
38 fftOutput[k*2] = sumReal;
39 fftOutput[k*2 + 1] = sumImag;
40 };
41 }
42 }
43
DotProductF32(const float * srcPtrA,float * srcPtrB,const int srcLen)44 float MathUtils::DotProductF32(const float* srcPtrA, float* srcPtrB,
45 const int srcLen)
46 {
47 float output = 0.f;
48
49 for (int i = 0; i < srcLen; ++i)
50 {
51 output += *srcPtrA++ * *srcPtrB++;
52 }
53 return output;
54 }
55
ComplexMagnitudeSquaredF32(const float * ptrSrc,int srcLen,float * ptrDst,int dstLen)56 bool MathUtils::ComplexMagnitudeSquaredF32(const float* ptrSrc,
57 int srcLen,
58 float* ptrDst,
59 int dstLen)
60 {
61 if (dstLen < srcLen/2)
62 {
63 printf("dstLen must be greater than srcLen/2");
64 return false;
65 }
66
67 for (int j = 0; j < dstLen; ++j)
68 {
69 const float real = *ptrSrc++;
70 const float im = *ptrSrc++;
71 *ptrDst++ = real*real + im*im;
72 }
73 return true;
74 }
75
VecLogarithmF32(std::vector<float> & input,std::vector<float> & output)76 void MathUtils::VecLogarithmF32(std::vector <float>& input,
77 std::vector <float>& output)
78 {
79 for (auto in = input.begin(), out = output.begin();
80 in != input.end(); ++in, ++out)
81 {
82 *out = logf(*in);
83 }
84 }
85
MeanF32(const float * ptrSrc,const uint32_t srcLen)86 float MathUtils::MeanF32(const float* ptrSrc, const uint32_t srcLen)
87 {
88 if (!srcLen)
89 {
90 return 0.f;
91 }
92
93 float acc = std::accumulate(ptrSrc, ptrSrc + srcLen, 0.0);
94 return acc/srcLen;
95 }
96
StdDevF32(const float * ptrSrc,uint32_t srcLen,float mean)97 float MathUtils::StdDevF32(const float* ptrSrc, uint32_t srcLen, float mean)
98 {
99 if (!srcLen)
100 {
101 return 0.f;
102 }
103 auto VarianceFunction = [mean, srcLen](float acc, const float value) {
104 return acc + (((value - mean) * (value - mean))/ srcLen);
105 };
106
107 float acc = std::accumulate(ptrSrc, ptrSrc + srcLen, 0.0,
108 VarianceFunction);
109 return sqrtf(acc);
110 }
111
112