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
12
13#include <unity.h>
14
15#include <math.h>
16
17#include "datalog_math.h" // Real header - pure C++
18
19void setUp(void) {}
20void tearDown(void) {}
21
22// ============================================================================
23// Helpers
24// ============================================================================
25
26static constexpr int32_t FULL_SCALE{ 1L << 18 }; // |V_ADC x I_ADC| never exceeds this
27
28// Power calibrations: old board, new board with 50 A and 20 A CTs, and two extremes
29static constexpr float oldBoardCal[]{ 0.05F, 0.05F, 0.05F };
30static constexpr float newBoard50Cal[]{ 0.1432025F, 0.1432025F, 0.1432025F };
31static constexpr float newBoard20Cal[]{ 0.057281F, 0.057281F, 0.057281F };
32static constexpr float smallCal[]{ 0.02F, 0.02F, 0.02F };
33static constexpr float largeCal[]{ 0.5F, 0.5F, 0.5F };
34
35// Voltage calibrations: old board (per phase) and new board
36static constexpr float oldBoardVCal[]{ 0.8151F, 0.8184F, 0.8195F };
37static constexpr float newBoardVCal[]{ 0.888065256F, 0.888065256F, 0.888065256F };
38
40static double referenceWatts(int32_t averagePower, float cal)
41{
42 return -static_cast< double >(averagePower) * cal;
43}
44
46static double referenceVrms(uint32_t meanSquare, uint16_t factor, float cal)
47{
48 return static_cast< double >(factor) * cal * sqrt(static_cast< double >(meanSquare));
49}
50
59template< uint8_t N >
60static double worstWattsError(const float (&cal)[N])
61{
62 const auto fixed{ Datalog::powerCalibration(cal) };
63 double worst{ 0.0 };
64 for (int32_t average = -FULL_SCALE; average <= FULL_SCALE; average += 97)
65 {
66 const double expected{ referenceWatts(average, cal[0]) };
67 if (fabs(expected) > INT16_MAX)
68 {
69 continue; // saturated, tested separately
70 }
71 const double error{ fabs(Datalog::watts(-average, fixed.value[0], fixed.shift) - expected) - fabs(expected) * ldexp(1.0, -16) };
72 if (error > worst)
73 {
74 worst = error;
75 }
76 }
77 return worst;
78}
79
88template< uint8_t N >
89static double worstVrmsError(uint16_t factor, const float (&cal)[N], uint32_t maxMeanSquare)
90{
91 const auto fixed{ Datalog::voltageCalibration(factor, cal) };
92 double worst{ 0.0 };
93 for (uint8_t phase = 0; phase < N; ++phase)
94 {
95 for (uint32_t meanSquare = 0; meanSquare <= maxMeanSquare; meanSquare += 13)
96 {
97 const double expected{ referenceVrms(meanSquare, factor, cal[phase]) };
98 const double error{ fabs(Datalog::vrms(meanSquare, fixed.value[phase], fixed.shift) - expected) - expected * ldexp(1.0, -14) };
99 if (error > worst)
100 {
101 worst = error;
102 }
103 }
104 }
105 return worst;
106}
107
108// ============================================================================
109// Integer square root
110// ============================================================================
111
117{
118 for (uint32_t root = 0; root <= UINT16_MAX; ++root)
119 {
120 const uint32_t square{ root * root };
121 if (root > 1) // r^2 - 1 >= (r - 0.5)^2 from r = 2 on (sqrt(0) = 0)
122 {
123 TEST_ASSERT_EQUAL_UINT16(root, Datalog::isqrt(square - 1));
124 }
125 TEST_ASSERT_EQUAL_UINT16(root, Datalog::isqrt(square));
126 TEST_ASSERT_EQUAL_UINT16(root, Datalog::isqrt(square + root)); // up to UINT32_MAX
127 if (root < UINT16_MAX) // 65535^2 + 65536 = 2^32 wraps
128 {
129 TEST_ASSERT_EQUAL_UINT16(root + 1, Datalog::isqrt(square + root + 1));
130 }
131 }
132}
133
136{
137 constexpr uint32_t STRIDE{ 2147 }; // odd, and not a multiple of small primes: hits all residues
138 uint32_t value{ 0 };
139 for (uint32_t i = 0; i < (UINT32_MAX / STRIDE); ++i, value += STRIDE)
140 {
141 const auto expected{ static_cast< uint32_t >(lround(sqrt(static_cast< double >(value)))) };
142 if (Datalog::isqrt(value) != (expected > UINT16_MAX ? UINT16_MAX : expected))
143 {
144 TEST_FAIL_MESSAGE("isqrt() differs from round(sqrt())");
145 }
146 }
147}
148
150{
151 TEST_ASSERT_EQUAL_UINT16(0, Datalog::isqrt(0));
152 TEST_ASSERT_EQUAL_UINT16(1, Datalog::isqrt(1));
153 TEST_ASSERT_EQUAL_UINT16(1, Datalog::isqrt(2)); // 1.414
154 TEST_ASSERT_EQUAL_UINT16(2, Datalog::isqrt(3)); // 1.732
155 TEST_ASSERT_EQUAL_UINT16(46341, Datalog::isqrt(1UL << 31)); // 46340.95
156 TEST_ASSERT_EQUAL_UINT16(32768, Datalog::isqrt(1UL << 30)); // smallest normalised value
157 TEST_ASSERT_EQUAL_UINT16(32768, Datalog::isqrt(0x40008000UL)); // 32768.4999962: rounds down
158 TEST_ASSERT_EQUAL_UINT16(32769, Datalog::isqrt(0x40008001UL)); // 32768.5000114: rounds up
159}
160
162{
163 TEST_ASSERT_EQUAL_UINT16(UINT16_MAX, Datalog::isqrt(UINT32_MAX)); // 65535.99999 rounds to 65536
164}
165
167{
168 uint8_t fractionBits;
169 for (uint32_t value = 1; value < (1UL << 30); value = value * 3 + 1)
170 {
171 const uint16_t root{ Datalog::sqrtScaled(value, fractionBits) };
172 TEST_ASSERT_GREATER_OR_EQUAL_UINT16(1U << 15, root);
173 TEST_ASSERT_FLOAT_WITHIN(0.5, sqrt(static_cast< double >(value)) * ldexp(1.0, fractionBits), root);
174 }
175}
176
178{
179 uint8_t fractionBits{ 99 };
180 TEST_ASSERT_EQUAL_UINT16(0, Datalog::sqrtScaled(0, fractionBits));
181 TEST_ASSERT_EQUAL_UINT8(0, fractionBits);
182}
183
184// ============================================================================
185// Power
186// ============================================================================
187
189{
190 constexpr auto fixed{ Datalog::powerCalibration(oldBoardCal) }; // must be constexpr
191
192 TEST_ASSERT_EQUAL_UINT8(Energy::calibrationShift(oldBoardCal), fixed.shift);
193 TEST_ASSERT_EQUAL_UINT16(Energy::toFixed(0.05F, fixed.shift), fixed.value[0]);
194}
195
197{
198 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstWattsError(oldBoardCal));
199}
200
202{
203 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstWattsError(newBoard50Cal));
204 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstWattsError(newBoard20Cal));
205}
206
208{
209 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstWattsError(smallCal));
210 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstWattsError(largeCal));
211}
212
214{
215 const auto fixed{ Datalog::powerCalibration(newBoard50Cal) };
216 for (int32_t average = 0; average <= 200000; average += 101)
217 {
218 TEST_ASSERT_EQUAL_INT16(-Datalog::watts(average, fixed.value[0], fixed.shift), Datalog::watts(-average, fixed.value[0], fixed.shift));
219 }
220}
221
223{
224 const auto fixed{ Datalog::powerCalibration(largeCal) }; // 2^18 x 0.5 = 131072 W
225 TEST_ASSERT_EQUAL_INT16(INT16_MAX, Datalog::watts(FULL_SCALE, fixed.value[0], fixed.shift));
226 TEST_ASSERT_EQUAL_INT16(-INT16_MAX, Datalog::watts(-FULL_SCALE, fixed.value[0], fixed.shift));
227}
228
230{
231 // the float code truncated, the integer code rounds
232 const auto fixed{ Datalog::powerCalibration(oldBoardCal) };
233 for (int32_t sumP = -FULL_SCALE; sumP <= FULL_SCALE; sumP += 89)
234 {
235 auto truncated{ static_cast< int16_t >(sumP * oldBoardCal[0]) };
236 truncated *= -1;
237 TEST_ASSERT_INT_WITHIN(1, truncated, Datalog::watts(-sumP, fixed.value[0], fixed.shift));
238 }
239}
240
241// ============================================================================
242// RMS voltage
243// ============================================================================
244
246{
247 // full-span sines average 2^17 per sample: up to 16383 sample sets fit in 31 bits unshifted
248 TEST_ASSERT_EQUAL_UINT8(0, Datalog::powerShift(16383));
249 TEST_ASSERT_EQUAL_UINT8(4, Datalog::powerShift(16384));
250 // 3-phase, 36 sets per cycle at most at 50 Hz: 5 s and 9 s unshifted, 10 s and 30 s shifted
251 TEST_ASSERT_EQUAL_UINT8(0, Datalog::powerShift(5UL * 50 * 36));
252 TEST_ASSERT_EQUAL_UINT8(0, Datalog::powerShift(9UL * 50 * 36));
253 TEST_ASSERT_EQUAL_UINT8(4, Datalog::powerShift(10UL * 50 * 36));
254 TEST_ASSERT_EQUAL_UINT8(4, Datalog::powerShift(30UL * 50 * 36));
255}
256
258{
259 // shifted by 4, a sample adds at most 2^14: the 54000 sets of 30 s stay below 2^31
260 const uint32_t sets{ 30UL * 50 * 36 };
261 TEST_ASSERT_TRUE(static_cast< uint64_t >(sets) * ((1UL << 18) >> Datalog::powerShift(sets)) <= INT32_MAX);
262}
263
265{
266 TEST_ASSERT_EQUAL_INT32(-142, Datalog::averagePower< 0 >(-1000, 7));
267 TEST_ASSERT_EQUAL_INT32(142, Datalog::averagePower< 0 >(1000, 7));
268 TEST_ASSERT_EQUAL_INT32(0, Datalog::averagePower< 0 >(0, 9000));
269}
270
272{
273 // sum x 16 / n truncated toward zero, over the whole range of a 30 s period
274 const int32_t sums[]{ 0, 1, -1, 15, -15, 123456789, -123456789, 54000L * 16384 - 1, -(54000L * 16384 - 1), 3374, -3374 };
275 const uint16_t counts[]{ 1, 7, 9000, 16383, 16384, 54000, UINT16_MAX };
276 for (const int32_t sum : sums)
277 {
278 for (const uint16_t n : counts)
279 {
280 const auto exact{ static_cast< int32_t >(static_cast< int64_t >(sum) * 16 / n) };
281 TEST_ASSERT_EQUAL_INT32(exact, Datalog::averagePower< 4 >(sum, n));
282 }
283 }
284}
285
288static void checkShiftedAverage(const int32_t amplitude, const int32_t offset, const int32_t noise, const int32_t delta)
289{
290 const uint16_t n{ 30U * 50 * 32 };
291 uint32_t lcg{ 12345 };
292 int32_t scaled{ 0 };
293 int64_t exact{ 0 };
294 for (uint16_t i = 0; i != n; ++i)
295 {
296 lcg = lcg * 1664525UL + 1013904223UL;
297 const int32_t dither{ noise ? static_cast< int32_t >(lcg >> 16) % (2 * noise + 1) - noise : 0 };
298 const auto instP{ static_cast< int32_t >(lround(offset + amplitude * sin(2.0 * M_PI * i / 32.0 + 0.1))) + dither };
299 scaled += (instP + 8) >> 4;
300 exact += instP;
301 }
302 TEST_ASSERT_INT32_WITHIN(delta, static_cast< int32_t >(exact / n), Datalog::averagePower< 4 >(scaled, n));
303}
304
306{
307 // any signal, even a constant or a sine repeating the same samples: within 8 step^2 (half of 16)
308 const int32_t amplitudes[]{ 0, 1, 7, 100, 5000, 131072 };
309 const int32_t offsets[]{ 0, 3, -3, 1000, -77777, 131071 };
310 for (const int32_t amplitude : amplitudes)
311 {
312 for (const int32_t offset : offsets)
313 {
314 checkShiftedAverage(amplitude, offset, 0, 8);
315 }
316 }
317}
318
320{
321 // with the noise of real samples (here +-64 step^2), the rounding averages out: within 1 step^2
322 const int32_t amplitudes[]{ 0, 100, 5000, 131072 };
323 const int32_t offsets[]{ 0, 3, -3, 1000, -77777 };
324 for (const int32_t amplitude : amplitudes)
325 {
326 for (const int32_t offset : offsets)
327 {
328 checkShiftedAverage(amplitude, offset, 64, 1);
329 }
330 }
331}
332
334{
335 constexpr auto fixed{ Datalog::voltageCalibration(100, oldBoardVCal) }; // must be constexpr
336
337 TEST_ASSERT_EQUAL_UINT8(9, fixed.shift); // 81.95 x 2^9 = 41958 fills the 16 bits
338 TEST_ASSERT_GREATER_OR_EQUAL_UINT16(1U << 15, fixed.value[2]);
339}
340
342{
343 // 5 s datalog: V^2 unscaled, V_ADC up to 512 (old board: 230 V ~ 282 steps rms)
344 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstVrmsError(100, oldBoardVCal, 512UL * 512UL));
345 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstVrmsError(100, newBoardVCal, 512UL * 512UL));
346}
347
349{
350 // datalog > 10 s: V^2 scaled down by 16, the result scaled up by 4
351 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstVrmsError(400, oldBoardVCal, 512UL * 512UL / 16));
352 TEST_ASSERT_LESS_OR_EQUAL_FLOAT(0.5F, worstVrmsError(400, newBoardVCal, 512UL * 512UL / 16));
353}
354
356{
357 const auto fixed{ Datalog::voltageCalibration(100, newBoardVCal) };
358 const double steps{ 230.0 / newBoardVCal[0] }; // rms ADC steps for 230 V
359 const auto meanSquare{ static_cast< uint32_t >(steps * steps) };
360
361 TEST_ASSERT_INT_WITHIN(1, lround(referenceVrms(meanSquare, 100, newBoardVCal[0])), Datalog::vrms(meanSquare, fixed.value[0], fixed.shift));
362 TEST_ASSERT_INT_WITHIN(2, 23000, Datalog::vrms(meanSquare, fixed.value[0], fixed.shift));
363}
364
366{
367 const auto fixed{ Datalog::voltageCalibration(100, newBoardVCal) };
368 TEST_ASSERT_EQUAL_UINT16(0, Datalog::vrms(0, fixed.value[0], fixed.shift));
369}
370
372{
373 const auto fixed{ Datalog::voltageCalibration(400, newBoardVCal) };
374 TEST_ASSERT_EQUAL_UINT16(UINT16_MAX, Datalog::vrms(UINT32_MAX, fixed.value[0], fixed.shift));
375}
376
378{
379 static_assert(Datalog::vrmsFactor(5) == 100, "must be constexpr");
380 TEST_ASSERT_EQUAL_UINT16(100, Datalog::vrmsFactor(1));
381 TEST_ASSERT_EQUAL_UINT16(100, Datalog::vrmsFactor(10)); // V^2 unscaled up to 10 s
382 TEST_ASSERT_EQUAL_UINT16(400, Datalog::vrmsFactor(11)); // V^2 / 16 above: root / 4
383 TEST_ASSERT_EQUAL_UINT16(400, Datalog::vrmsFactor(40));
384}
385
387{
388 static constexpr float zeroCal[]{ 0.8F, 0.0F, 0.8F };
389 static constexpr float negativeCal[]{ 0.8F, 0.8F, -0.8F };
390 static constexpr float tinyCal[]{ 0.0001F, 0.0001F, 0.0001F };
391
392 static_assert(Datalog::isValidVoltageCalibration(100, oldBoardVCal), "old board");
393 static_assert(Datalog::isValidVoltageCalibration(400, newBoardVCal), "new board, long period");
394 TEST_ASSERT_FALSE(Datalog::isValidVoltageCalibration(100, zeroCal));
395 TEST_ASSERT_FALSE(Datalog::isValidVoltageCalibration(100, negativeCal));
396 TEST_ASSERT_FALSE(Datalog::isValidVoltageCalibration(100, tinyCal)); // shift > 16
397}
398
399int main(int argc, char** argv)
400{
401 (void)argc;
402 (void)argv;
403
404 UNITY_BEGIN();
405
408 RUN_TEST(test_isqrt_edge_cases);
411 RUN_TEST(test_sqrtScaled_of_zero);
412
420
427
431 RUN_TEST(test_vrms_at_230_V);
432 RUN_TEST(test_vrms_of_zero);
433 RUN_TEST(test_vrms_saturates);
436
437 return UNITY_END();
438}
Integer arithmetic of the datalog: power and RMS voltage per phase.
void setUp(void)
Definition test_main.cpp:27
void tearDown(void)
Definition test_main.cpp:28
uint8_t i
constexpr uint16_t vrmsFactor(const uint8_t datalogPeriodInSeconds)
Scaling of the datalog voltage, Vrms_L_x100.
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.
constexpr bool isValidVoltageCalibration(const uint16_t factor, const float(&cal)[N])
Check that the voltage calibration values can be represented.
constexpr uint8_t powerShift(const uint32_t maxSampleSets)
The shift by which the ISR scales the power down before adding it to the datalog sum.
int32_t averagePower(const int32_t sum, const Count sampleSets)
The average power of a datalog period, back at the x1 scale of V_ADC x I_ADC.
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.
constexpr uint8_t calibrationShift(const float(&cal)[N])
Largest shift that keeps every calibration value within 16 bits.
constexpr uint16_t toFixed(const float cal, const uint8_t shift)
A calibration value as a 16-bit fixed-point constant.
void test_voltage_calibration_is_constexpr(void)
static constexpr float newBoard50Cal[]
Definition test_main.cpp:30
void test_power_shift_follows_the_sample_count(void)
void test_isqrt_at_every_boundary(void)
Every rounding boundary of every root: round(sqrt(x)) changes from r to r + 1 between r^2 + r and r^2...
void test_power_calibration_is_constexpr(void)
void test_vrms_matches_the_reference_short_period(void)
void test_watts_saturates_beyond_int16(void)
static double referenceVrms(uint32_t meanSquare, uint16_t factor, float cal)
The float arithmetic being replaced, in hundredths of a volt (x4 for long periods).
Definition test_main.cpp:46
static constexpr float oldBoardCal[]
Definition test_main.cpp:29
void test_average_power_shifted_is_the_exact_average(void)
void test_shifted_sum_keeps_the_average_of_a_noisy_signal_over_30_s(void)
static double referenceWatts(int32_t averagePower, float cal)
The float arithmetic being replaced, in watts (import = +ve).
Definition test_main.cpp:40
void test_vrms_of_zero(void)
void test_watts_matches_the_reference_extremes(void)
static void checkShiftedAverage(const int32_t amplitude, const int32_t offset, const int32_t noise, const int32_t delta)
void test_watts_differs_from_the_float_code_by_at_most_1_W(void)
void test_isqrt_matches_the_reference(void)
2 million values over the whole 32-bit range, against sqrt() in double precision (exact here).
static constexpr float smallCal[]
Definition test_main.cpp:32
static double worstWattsError(const float(&cal)[N])
Largest error of watts() against the reference, over the full input range, beyond what the 16-bit cal...
Definition test_main.cpp:60
void test_isqrt_edge_cases(void)
void test_sqrtScaled_keeps_15_significant_bits(void)
void test_average_power_unshifted_is_the_quotient(void)
void test_isqrt_of_the_largest_value_saturates(void)
static constexpr int32_t FULL_SCALE
Definition test_main.cpp:26
void test_shifted_sum_is_within_half_the_shift_over_30_s(void)
void test_watts_is_sign_symmetric(void)
void test_watts_matches_the_reference_old_board(void)
static constexpr float largeCal[]
Definition test_main.cpp:33
static constexpr float oldBoardVCal[]
Definition test_main.cpp:36
void test_vrms_factor_follows_the_scaling_of_the_isr(void)
void test_watts_matches_the_reference_new_board(void)
void test_vrms_matches_the_reference_long_period(void)
void test_vrms_at_230_V(void)
static constexpr float newBoard20Cal[]
Definition test_main.cpp:31
void test_power_shift_keeps_30_s_of_any_signal_in_32_bits(void)
static constexpr float newBoardVCal[]
Definition test_main.cpp:37
void test_sqrtScaled_of_zero(void)
static double worstVrmsError(uint16_t factor, const float(&cal)[N], uint32_t maxMeanSquare)
Largest error of vrms() against the reference, from 0 to the largest ADC voltage, beyond what the 16-...
Definition test_main.cpp:89
void test_valid_voltage_calibration(void)
void test_vrms_saturates(void)
int main(void)