3-phase PV router
Loading...
Searching...
No Matches
test_main.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-3.0-or-later
17
18#include <Arduino.h>
19#include <unity.h>
20#include <math.h>
21
22#include "../bench_report.h"
23#include "../halt_after_tests.h"
24
25#include "datalog_math.h"
26
27void setUp(void) {}
28void tearDown(void) {}
29
30// calibration values of the new board (50 A CTs), as runtime arrays like f_powerCal/f_voltageCal
31static volatile float powerCal[]{ 0.1432025F, 0.1432025F, 0.1432025F };
32static volatile float voltageCal[]{ 0.888065256F, 0.888065256F, 0.888065256F };
33
34static constexpr float powerCalConst[]{ 0.1432025F, 0.1432025F, 0.1432025F };
35static constexpr float voltageCalConst[]{ 0.888065256F, 0.888065256F, 0.888065256F };
38
39// inputs: mean squares from 0 V to ~450 V (ADC steps squared), average powers from -2^18 to +2^18
40static const uint32_t meanSquares[]{ 0UL, 1UL, 100UL, 5000UL, 45000UL, 67076UL, 67081UL, 70000UL, 150000UL, 262144UL };
41static const int32_t averagePowers[]{ 0L, 1L, -7L, 350L, -2000L, 8380L, -15000L, 60000L, -120000L, 228000L };
42static constexpr uint8_t N_INPUTS{ 10 };
43
44static volatile uint32_t inMeanSquare;
45static volatile int32_t inAveragePower;
46static volatile uint8_t inPhase;
47static volatile uint32_t out32;
48static volatile int16_t out16;
49
51struct Cycles
52{
53 uint16_t min{ UINT16_MAX };
54 uint16_t max{ 0 };
55 uint32_t sum{ 0 };
56
57 void add(uint16_t cycles)
58 {
59 if (cycles < min)
60 {
61 min = cycles;
62 }
63 if (cycles > max)
64 {
65 max = cycles;
66 }
67 sum += cycles;
68 }
69 uint16_t average() const
70 {
71 return static_cast< uint16_t >(sum / N_INPUTS);
72 }
73};
74
75// Timer1 at the CPU clock: one count per cycle, overflows after 4 ms
76static void startTimer()
77{
78 TCCR1A = 0;
79 TCCR1B = 0;
80 TCNT1 = 0;
81 TCCR1B = _BV(CS10);
82}
83
84// The code between the two reads of TCNT1, with the overhead of the reads subtracted
85#define MEASURE(stats, overhead, code) \
86 do \
87 { \
88 cli(); \
89 startTimer(); \
90 const uint16_t t0{ TCNT1 }; \
91 code; \
92 const uint16_t t1{ TCNT1 }; \
93 sei(); \
94 (stats).add(static_cast< uint16_t >(t1 - t0 - (overhead))); \
95 } while (0)
96
97static uint16_t overhead()
98{
99 Cycles empty;
100 for (uint8_t i = 0; i < N_INPUTS; ++i)
101 {
102 MEASURE(empty, 0, {});
103 }
104 return empty.min;
105}
106
108static void bench(const __FlashStringHelper* avgName, const __FlashStringHelper* maxName, const Cycles& stats)
109{
110 benchCycles(avgName, stats.average());
111 benchCycles(maxName, stats.max);
112}
113
114static void report(const __FlashStringHelper* name, const Cycles& stats)
115{
116 Serial.print(name);
117 Serial.print(F(": min "));
118 Serial.print(stats.min);
119 Serial.print(F(", avg "));
120 Serial.print(stats.average());
121 Serial.print(F(", max "));
122 Serial.print(stats.max);
123 Serial.println(F(" cycles"));
124}
125
126// ============================================================================
127// Correctness on the target: the assembly square root, sqrtScaled() and vrms()
128// ============================================================================
129
140{
141 uint32_t errors{ 0 };
142 uint32_t firstError{ 0 };
143 for (uint32_t root = 0; root <= UINT16_MAX; ++root)
144 {
145 const uint32_t square{ root * root };
146 const auto r{ static_cast< uint16_t >(root) };
147 const uint16_t expected[]{ r, r, r, static_cast< uint16_t >(root < UINT16_MAX ? root + 1 : UINT16_MAX) };
148 const uint32_t values[]{ root > 1 ? square - 1 : square, square, square + root, square + root + 1 }; // sqrt(1 - 1) = 0
149 const uint8_t count{ static_cast< uint8_t >(root < UINT16_MAX ? 4 : 3) }; // 65535^2 + 65536 = 2^32 wraps
150 for (uint8_t i = 0; i < count; ++i)
151 {
152 if ((Datalog::isqrt(values[i]) != expected[i]) && !errors++)
153 {
154 firstError = values[i];
155 }
156 }
157 }
158 if (errors)
159 {
160 Serial.print(F("first wrong value: "));
161 Serial.println(firstError);
162 }
163 TEST_ASSERT_EQUAL_UINT32(0, errors);
164}
165
167{
168 TEST_ASSERT_EQUAL_UINT16(0, Datalog::isqrt(0));
169 TEST_ASSERT_EQUAL_UINT16(1, Datalog::isqrt(1));
170 TEST_ASSERT_EQUAL_UINT16(1, Datalog::isqrt(2)); // 1.414
171 TEST_ASSERT_EQUAL_UINT16(2, Datalog::isqrt(3)); // 1.732
172 TEST_ASSERT_EQUAL_UINT16(2, Datalog::isqrt(4));
173 TEST_ASSERT_EQUAL_UINT16(46341, Datalog::isqrt(1UL << 31)); // 46340.95
174 TEST_ASSERT_EQUAL_UINT16(32768, Datalog::isqrt(1UL << 30)); // smallest normalised value
175 TEST_ASSERT_EQUAL_UINT16(32768, Datalog::isqrt(0x40008000UL)); // 32768.4999962: rounds down
176 TEST_ASSERT_EQUAL_UINT16(32769, Datalog::isqrt(0x40008001UL)); // 32768.5000114: rounds up
177 TEST_ASSERT_EQUAL_UINT16(UINT16_MAX, Datalog::isqrt(65535UL * 65535UL));
178 TEST_ASSERT_EQUAL_UINT16(UINT16_MAX, Datalog::isqrt(UINT32_MAX)); // 65535.99999: saturated
179}
180
183{
184 uint8_t bits;
185 for (uint32_t meanSquare = 1; meanSquare <= 512UL * 512UL; meanSquare = meanSquare * 9 / 8 + 1)
186 {
187 // sqrtScaled: sqrt(x) x 2^bits within 0.5 of the exact value (+ the float's own rounding)
188 const uint16_t root{ Datalog::sqrtScaled(meanSquare, bits) };
189 const float exact{ sqrtf(static_cast< float >(meanSquare)) * static_cast< float >(1UL << bits) };
190 TEST_ASSERT_FLOAT_WITHIN(0.5F + exact * 1.2e-7F, exact, root);
191
192 // vrms: within 1 hundredth of the float code (which truncated)
193 inMeanSquare = meanSquare;
194 const auto reference{ static_cast< uint32_t >(100U * voltageCal[0] * sqrt(inMeanSquare)) };
195 TEST_ASSERT_UINT32_WITHIN(1, reference, Datalog::vrms(inMeanSquare, voltageFixed.value[0], voltageFixed.shift));
196 }
197}
198
199// ============================================================================
200// Square root alone
201// ============================================================================
202
204{
205 const uint16_t ovh{ overhead() };
206 Cycles floatSqrt, intSqrt, scaledSqrt;
207
208 for (uint8_t i = 0; i < N_INPUTS; ++i)
209 {
211 MEASURE(floatSqrt, ovh, out32 = static_cast< uint32_t >(sqrt(inMeanSquare)));
212 MEASURE(intSqrt, ovh, out32 = Datalog::isqrt(inMeanSquare));
213 MEASURE(scaledSqrt, ovh, {
214 uint8_t bits;
216 out16 = bits;
217 });
218 }
219
220 Serial.println(F("--- square root ---"));
221 report(F("float sqrt() "), floatSqrt);
222 report(F("Datalog::isqrt() "), intSqrt);
223 report(F("Datalog::sqrtScaled "), scaledSqrt);
224 bench(F("datalog: isqrt avg"), F("datalog: isqrt max"), intSqrt);
225 bench(F("datalog: sqrtScaled avg"), F("datalog: sqrtScaled max"), scaledSqrt);
226
227 TEST_ASSERT_LESS_OR_EQUAL_UINT16(floatSqrt.max, scaledSqrt.max);
228 TEST_ASSERT_LESS_OR_EQUAL_UINT32(floatSqrt.sum, scaledSqrt.sum);
229}
230
231// ============================================================================
232// The datalog expressions, as they were and as they are
233// ============================================================================
234
236{
237 const uint16_t ovh{ overhead() };
238 Cycles floatVrms, intVrms;
239
240 for (uint8_t i = 0; i < N_INPUTS; ++i)
241 {
243 inPhase = i % 3;
244 MEASURE(floatVrms, ovh, out32 = static_cast< uint32_t >(100U * voltageCal[inPhase] * sqrt(inMeanSquare)));
245 const uint32_t reference{ out32 };
247
248 TEST_ASSERT_UINT32_WITHIN(1, reference, out32); // the float code truncates, vrms() rounds
249 }
250
251 Serial.println(F("--- Vrms_L_x100 ---"));
252 report(F("float (as before) "), floatVrms);
253 report(F("Datalog::vrms() "), intVrms);
254 bench(F("datalog: vrms avg"), F("datalog: vrms max"), intVrms);
255
256 TEST_ASSERT_LESS_OR_EQUAL_UINT16(floatVrms.max, intVrms.max);
257 TEST_ASSERT_LESS_OR_EQUAL_UINT32(floatVrms.sum, intVrms.sum);
258}
259
261{
262 const uint16_t ovh{ overhead() };
263 Cycles floatWatts, intWatts;
264
265 for (uint8_t i = 0; i < N_INPUTS; ++i)
266 {
268 inPhase = i % 3;
269 MEASURE(floatWatts, ovh, {
270 int16_t power = inAveragePower * powerCal[inPhase];
271 power *= -1;
272 out16 = power;
273 });
274 MEASURE(intWatts, ovh, out16 = Datalog::watts(-inAveragePower, powerFixed.value[inPhase], powerFixed.shift));
275 }
276
277 Serial.println(F("--- power_L ---"));
278 report(F("float (as before) "), floatWatts);
279 report(F("Datalog::watts() "), intWatts);
280 bench(F("datalog: watts avg"), F("datalog: watts max"), intWatts);
281
282 TEST_ASSERT_LESS_OR_EQUAL_UINT16(floatWatts.max, intWatts.max);
283 TEST_ASSERT_LESS_OR_EQUAL_UINT32(floatWatts.sum, intWatts.sum);
284}
285
286void setup()
287{
288 delay(1000);
289
290 UNITY_BEGIN();
291
298
299 UNITY_END();
301}
302
303void loop() {}
Machine-readable lines per benchmark result, for the CI performance report.
void benchCycles(const __FlashStringHelper *name, const uint32_t cycles, const uint32_t ops=1)
A result in CPU cycles, reported twice: in microseconds and in cycles.
Integer arithmetic of the datalog: power and RMS voltage per phase.
static constexpr auto powerFixed
Definition test_main.cpp:36
static constexpr auto voltageFixed
Definition test_main.cpp:37
static volatile uint32_t inMeanSquare
Definition test_main.cpp:44
static void startTimer()
Definition test_main.cpp:76
void test_isqrt_is_faster_than_float_sqrt(void)
static constexpr float powerCalConst[]
Definition test_main.cpp:34
static volatile uint32_t out32
Definition test_main.cpp:47
#define MEASURE(stats, overhead, code)
Definition test_main.cpp:85
void setup()
static const uint32_t meanSquares[]
Definition test_main.cpp:40
static const int32_t averagePowers[]
Definition test_main.cpp:41
void test_watts_is_faster_than_the_float_code(void)
static volatile float powerCal[]
Definition test_main.cpp:31
static volatile int32_t inAveragePower
Definition test_main.cpp:45
void test_isqrt_on_avr_edge_cases(void)
static uint16_t overhead()
Definition test_main.cpp:97
void setUp(void)
Definition test_main.cpp:27
void tearDown(void)
Definition test_main.cpp:28
static constexpr uint8_t N_INPUTS
Definition test_main.cpp:42
static volatile int16_t out16
Definition test_main.cpp:48
void test_vrms_on_avr_matches_the_float_code(void)
sqrtScaled() and vrms() on the target, against the float code, over the whole voltage range.
static volatile float voltageCal[]
Definition test_main.cpp:32
static void report(const __FlashStringHelper *name, const Cycles &stats)
static void bench(const __FlashStringHelper *avgName, const __FlashStringHelper *maxName, const Cycles &stats)
The average and worst case of an integer function, for the CI history.
static constexpr float voltageCalConst[]
Definition test_main.cpp:35
void test_isqrt_on_avr_every_boundary(void)
Every rounding boundary of every root, on the target: the assembly loop is exact.
void test_vrms_is_faster_than_the_float_code(void)
static volatile uint8_t inPhase
Definition test_main.cpp:46
void loop()
uint8_t i
Stops the MCU once an embedded test suite has run.
void haltAfterTests()
constexpr FixedCalibration< N > voltageCalibration(const uint16_t factor, const float(&cal)[N])
The voltage calibration in fixed point, for vrms(), built at compile time.
int16_t watts(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
The average power of a phase, in watts.
uint16_t isqrt(const uint32_t value)
Integer square root, rounded to the nearest integer.
constexpr FixedCalibration< N > powerCalibration(const float(&cal)[N])
The power calibration in fixed point, for watts(), built at compile time.
uint16_t vrms(const uint32_t meanSquare, const uint16_t calFixed, const uint8_t shift)
The RMS voltage of a phase.
uint16_t sqrtScaled(const uint32_t meanSquare, uint8_t &fractionBits)
The square root of a mean square, with as many fractional bits as fit.
static double reference(int32_t averagePower, float cal)
The float arithmetic being replaced, in bucket units.
Definition test_main.cpp:28
static Values values
Definition test_main.cpp:41
Cycle statistics of one variant over all inputs.
Definition test_main.cpp:52
uint16_t min
Definition test_main.cpp:53
void add(uint16_t cycles)
Definition test_main.cpp:57
uint16_t average() const
Definition test_main.cpp:69
uint32_t sum
Definition test_main.cpp:55
uint16_t max
Definition test_main.cpp:54