blob: bf9908343a1657de71087f6d26be6e440d2e2b71 [file] [log] [blame]
Éanna Ó Catháinc6ab02a2021-04-07 14:35:25 +01001//
2// Copyright © 2020 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
11void 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
44float MathUtils::DotProductF32(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
56bool MathUtils::ComplexMagnitudeSquaredF32(float* ptrSrc,
57 const int srcLen,
58 float* ptrDst,
59 const 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 < srcLen; ++j)
68 {
69 const float real = *ptrSrc++;
70 const float im = *ptrSrc++;
71 *ptrDst++ = real*real + im*im;
72 }
73 return true;
74}
75
76void 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
86float MathUtils::MeanF32(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
97float MathUtils::StdDevF32(float* ptrSrc, const uint32_t srcLen,
98 const float mean)
99{
100 if (!srcLen)
101 {
102 return 0.f;
103 }
104 auto VarianceFunction = [=](float acc, const float value) {
105 return acc + (((value - mean) * (value - mean))/ srcLen);
106 };
107
108 float acc = std::accumulate(ptrSrc, ptrSrc + srcLen, 0.0,
109 VarianceFunction);
110 return sqrtf(acc);
111}
112