-
Notifications
You must be signed in to change notification settings - Fork 0
/
THDCalculator.cpp
64 lines (57 loc) · 2.08 KB
/
THDCalculator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "THDCalculator.h"
THDCalculator::THDCalculator(double initBaseFrequency, uint8_t initNumberOvertones,
double initSampleFrequency)
: baseFrequency(initBaseFrequency), numberOvertones(initNumberOvertones),
sampleFrequency(initSampleFrequency)
{
// initialize the vector of overtones and their Fourier transform and magnitudes
// to prepare for the THD calculation
initTHDCalculation();
// create the DTFT calculator object
dtft = new DTFT(sampleFrequency);
}
void THDCalculator::calcTHD(double& THD_F, double& THD_R, VectorXd inputSignal)
{
// determine the DTFT for the base frequency and the overtones
dtft->calculateSpectrum(magnitudesOvertones, fourierTransformOvertones,
inputSignal, overtones);
double distortionPower = 0.0;
double totalPower = 0.0;
double basePower;
for(uint8_t k = 1; k < numberOvertones; k++)
distortionPower += std::fabs(fourierTransformOvertones[k] * conj(fourierTransformOvertones[k]));
basePower = std::fabs(fourierTransformOvertones[0] * conj(fourierTransformOvertones[0]));
totalPower = distortionPower + basePower;
THD_F = std::sqrt(distortionPower / basePower);
THD_R = std::sqrt(distortionPower / totalPower);
THD_F= std::min(THD_F,1.0);
THD_R = std::min(THD_R,1.0);
}
void THDCalculator::setNoOvertones(double newNumberOvertones)
{
numberOvertones = newNumberOvertones;
}
void THDCalculator::setBaseFrequency(double newBaseFrequency)
{
baseFrequency = newBaseFrequency;
}
void THDCalculator::updateOvertones()
{
for(uint8_t k = 0; k < numberOvertones; k++)
{
overtones[k] = (k+1) * baseFrequency;
}
}
void THDCalculator::initTHDCalculation()
{
zScalar complexZero(0.0,0.0);
overtones.resize(numberOvertones);
magnitudesOvertones.resize(numberOvertones);
fourierTransformOvertones.resize(numberOvertones);
for(uint8_t k = 0; k < numberOvertones; k++)
{
overtones[k] = (k+1) * baseFrequency;
magnitudesOvertones[k] = 0.0;
fourierTransformOvertones[k] = complexZero;
}
}