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
11
12#include <unity.h>
13
14#include <math.h>
15
16#include "energy_bucket.h" // Real header - pure C++
17
18void setUp(void) {}
19void tearDown(void) {}
20
21// ============================================================================
22// Helpers
23// ============================================================================
24
25static constexpr int32_t FULL_SCALE{ 1L << 18 }; // |V_ADC x I_ADC| never exceeds this
26
28static double reference(int32_t averagePower, float cal)
29{
30 return static_cast< double >(averagePower) * cal * (1 << Energy::FRACTION_BITS);
31}
32
34static double quantisationError(float cal, uint8_t shift)
35{
36 const double exact{ static_cast< double >(cal) * ldexp(1.0, shift) };
37 return fabs(Energy::toFixed(cal, shift) - exact) / exact;
38}
39
40// A real-world calibration set, and two extremes around it
41static constexpr float typicalCal[]{ 0.042346F, 0.043453F, 0.042969F };
42static constexpr float largeCal[]{ 0.1F, 0.1F, 0.1F };
43static constexpr float smallCal[]{ 0.02F, 0.02F, 0.02F };
44
45// ============================================================================
46// Calibration quantisation
47// ============================================================================
48
50{
51 constexpr uint8_t shift{ Energy::calibrationShift(typicalCal) }; // must be constexpr
52
53 TEST_ASSERT_EQUAL_UINT8(20, shift);
54}
55
57{
58 TEST_ASSERT_EQUAL_UINT8(19, Energy::calibrationShift(largeCal));
59 TEST_ASSERT_EQUAL_UINT8(21, Energy::calibrationShift(smallCal));
60}
61
63{
64 // phases share one shift, so their contributions add up in the same unit
65 static constexpr float mixed[]{ 0.02F, 0.1F, 0.05F };
66
67 TEST_ASSERT_EQUAL_UINT8(19, Energy::calibrationShift(mixed));
68}
69
71{
72 constexpr uint8_t shift{ Energy::calibrationShift(typicalCal) };
73
74 // at least 2^15, at most 2^16 - 1: no bit wasted, none lost
75 TEST_ASSERT_GREATER_OR_EQUAL_UINT32(32768, Energy::toFixed(0.043453F, shift));
76 TEST_ASSERT_LESS_OR_EQUAL_UINT32(65535, Energy::toFixed(0.043453F, shift));
77}
78
80{
81 constexpr uint16_t fixed{ Energy::toFixed(0.042346F, 20) }; // must be constexpr
82
83 TEST_ASSERT_EQUAL_UINT16(44403, fixed); // 0.042346 x 2^20 = 44403.0
84 TEST_ASSERT_EQUAL_UINT16(52429, Energy::toFixed(0.05F, 20)); // 52428.8 -> 52429
85}
86
88{
89 // sweep single-phase calibrations from 0.005 to 0.5: the normalised shift keeps the
90 // error below 0.002%, far below what a calibration against a meter can achieve
91 for (float cal = 0.005F; cal < 0.5F; cal *= 1.07F)
92 {
93 const float set[]{ cal };
94 TEST_ASSERT_TRUE_MESSAGE(quantisationError(cal, Energy::calibrationShift(set)) < 2e-5, "quantisation error too large");
95 }
96}
97
99{
100 constexpr uint8_t shift{ Energy::calibrationShift(typicalCal) };
101
102 for (const float cal : typicalCal)
103 {
104 TEST_ASSERT_TRUE(quantisationError(cal, shift) < 1e-5);
105 }
106}
107
109{
110 constexpr bool valid{ Energy::isValidCalibration(typicalCal) }; // must be constexpr
111
112 TEST_ASSERT_TRUE(valid);
113 TEST_ASSERT_TRUE(Energy::isValidCalibration(largeCal));
114 TEST_ASSERT_TRUE(Energy::isValidCalibration(smallCal));
115}
116
118{
119 static constexpr float withZero[]{ 0.05F, 0.0F, 0.05F };
120 static constexpr float withNegative[]{ 0.05F, -0.05F, 0.05F };
121 static constexpr float huge[]{ 10.0F, 10.0F, 10.0F }; // leaves too few fractional bits
122
123 TEST_ASSERT_FALSE(Energy::isValidCalibration(withZero));
124 TEST_ASSERT_FALSE(Energy::isValidCalibration(withNegative));
125 TEST_ASSERT_FALSE(Energy::isValidCalibration(huge));
126}
127
128// ============================================================================
129// Contribution of one cycle, against the float reference
130// ============================================================================
131
133static void checkAgainstReference(const float (&cal)[3])
134{
135 const uint8_t shift{ Energy::calibrationShift(cal) };
136
137 for (uint8_t phase = 0; phase < 3; ++phase)
138 {
139 const uint16_t calFixed{ Energy::toFixed(cal[phase], shift) };
140
141 for (int32_t power = -FULL_SCALE; power <= FULL_SCALE; power += 997)
142 {
143 const double expected{ reference(power, cal[phase]) };
144 const double actual{ static_cast< double >(Energy::contribution(power, calFixed, shift)) };
145
146 // one unit of rounding, plus the calibration quantisation
147 TEST_ASSERT_TRUE_MESSAGE(fabs(actual - expected) <= 1.0 + fabs(expected) * 2e-5, "contribution differs from the float reference");
148 }
149 }
150}
151
156
162
164{
165 const uint8_t shift{ Energy::calibrationShift(typicalCal) };
166
167 TEST_ASSERT_EQUAL_INT32(0, Energy::contribution(0, Energy::toFixed(typicalCal[0], shift), shift));
168}
169
171{
172 // the product needs ~35 bits: a 32-bit intermediate would wrap here
173 const uint8_t shift{ Energy::calibrationShift(largeCal) };
174 const uint16_t calFixed{ Energy::toFixed(largeCal[0], shift) };
175
176 TEST_ASSERT_INT32_WITHIN(2, lround(reference(FULL_SCALE, largeCal[0])), Energy::contribution(FULL_SCALE, calFixed, shift));
177 TEST_ASSERT_INT32_WITHIN(2, lround(reference(-FULL_SCALE, largeCal[0])), Energy::contribution(-FULL_SCALE, calFixed, shift));
178}
179
181static int32_t generalRounding(int32_t power, uint16_t calFixed, uint8_t shift)
182{
183 const bool negative{ power < 0 };
184 const uint64_t magnitude{ static_cast< uint64_t >(negative ? -static_cast< int64_t >(power) : power) };
185 const uint64_t product{ (magnitude * calFixed) >> 8 };
186 const uint8_t remaining{ static_cast< uint8_t >(shift - Energy::FRACTION_BITS - 8) };
187 const auto rounded{ static_cast< int32_t >((product + (1ULL << (remaining - 1))) >> remaining) };
188 return negative ? -rounded : rounded;
189}
190
192{
193 // remaining = shift - 12. From 9 on, contribution() rounds with a byte move and a short
194 // shift; below, with the general form. Both must give exactly the general rounding, for
195 // any |power| below 2^24 (the per-sample path) and any calFixed.
196 uint32_t lcg{ 12345 };
197 const auto next = [&lcg]()
198 {
199 lcg = lcg * 1664525UL + 1013904223UL;
200 return lcg;
201 };
202
203 for (uint8_t shift = 17; shift <= 28; ++shift) // remaining 5..16
204 {
205 const uint8_t remaining{ static_cast< uint8_t >(shift - 12) };
206
207 // rounding edges: with calFixed = 256, product == |power|
208 for (int32_t k = 0; k < 64; ++k)
209 {
210 for (int32_t d = -1; d <= 1; ++d)
211 {
212 const int64_t edge{ (static_cast< int64_t >(k) << remaining) + (1L << (remaining - 1)) + d };
213 if ((edge < 0) || (edge >= (1L << 24)))
214 continue;
215 const auto power{ static_cast< int32_t >(edge) };
216 TEST_ASSERT_EQUAL_INT32(generalRounding(power, 256, shift), Energy::contribution(power, 256, shift));
217 TEST_ASSERT_EQUAL_INT32(generalRounding(-power, 256, shift), Energy::contribution(-power, 256, shift));
218 }
219 }
220
221 // random powers and calibration values, including the largest ones
222 for (uint16_t i = 0; i < 20000; ++i)
223 {
224 const auto power{ static_cast< int32_t >(next() & 0xFFFFFFUL) * ((next() & 1) ? 1 : -1) };
225 const auto calFixed{ static_cast< uint16_t >((i < 100) ? 65535 - i : next() >> 16) };
226 TEST_ASSERT_EQUAL_INT32(generalRounding(power, calFixed, shift), Energy::contribution(power, calFixed, shift));
227 }
228 }
229}
230
232{
233 // import and export must weigh the same, or the bucket drifts one way
234 const uint8_t shift{ Energy::calibrationShift(typicalCal) };
235 const uint16_t calFixed{ Energy::toFixed(typicalCal[1], shift) };
236
237 for (int32_t power = 1; power <= FULL_SCALE; power += 1009)
238 {
239 TEST_ASSERT_EQUAL_INT32(-Energy::contribution(power, calFixed, shift), Energy::contribution(-power, calFixed, shift));
240 }
241}
242
244{
245 // 3000 cycles (1 min at 50 Hz) of a slowly varying load: rounding must not accumulate
246 const uint8_t shift{ Energy::calibrationShift(typicalCal) };
247 const uint16_t calFixed{ Energy::toFixed(typicalCal[2], shift) };
248
249 int64_t bucket{ 0 };
250 double expected{ 0.0 };
251
252 for (int32_t cycle = 0; cycle < 3000; ++cycle)
253 {
254 const int32_t power{ static_cast< int32_t >(20000.0 + 15000.0 * sin(cycle * 0.01)) + (cycle % 7) };
255 bucket += Energy::contribution(power, calFixed, shift);
256 expected += reference(power, typicalCal[2]);
257 }
258
259 TEST_ASSERT_TRUE_MESSAGE(fabs(static_cast< double >(bucket) - expected) <= fabs(expected) * 2e-5 + 64.0, "the integer bucket drifts from the float one");
260}
261
262// ============================================================================
263// Per-sample calibration: cal / n in one table, no division in the ISR
264// ============================================================================
265
266// sample sets per mains cycle: ~32 at 50 Hz, ~26.7 at 60 Hz, with margin
267static constexpr uint8_t N_MIN_50HZ{ 28 };
268static constexpr uint8_t N_MAX_50HZ{ 36 };
269
271static double exactReference(int32_t sumP, uint8_t n, float cal)
272{
273 return static_cast< double >(sumP) / n * cal * (1 << Energy::FRACTION_BITS);
274}
275
277{
278 constexpr auto table{ Energy::toFixedPerSample< N_MIN_50HZ, N_MAX_50HZ >(typicalCal) }; // must be constexpr
279
280 TEST_ASSERT_EQUAL_UINT8(25, table.shift);
281 // at n = 32, cal / 32 x 2^25 == cal x 2^20: the step-1 constants again
282 TEST_ASSERT_EQUAL_UINT16(44403, table.value[0][32 - N_MIN_50HZ]);
283 TEST_ASSERT_EQUAL_UINT16(45564, table.value[1][32 - N_MIN_50HZ]);
284 TEST_ASSERT_EQUAL_UINT16(45056, table.value[2][32 - N_MIN_50HZ]);
285}
286
288{
289 constexpr auto table{ Energy::toFixedPerSample< 20, 32 >(typicalCal) };
290
291 TEST_ASSERT_EQUAL_UINT8(24, table.shift);
292 TEST_ASSERT_EQUAL_UINT16(22202, table.value[0][32 - 20]);
293}
294
296{
298
299 // the largest entry is the largest calibration over the smallest n
300 TEST_ASSERT_GREATER_OR_EQUAL_UINT32(32768, table.value[1][0]);
301 TEST_ASSERT_LESS_OR_EQUAL_UINT32(65535, table.value[1][0]);
302}
303
305{
307
308 for (uint8_t phase = 0; phase < 3; ++phase)
309 {
310 for (uint8_t n = N_MIN_50HZ; n <= N_MAX_50HZ; ++n)
311 {
312 const int32_t fullScale{ static_cast< int32_t >(n) * FULL_SCALE };
313
314 for (int32_t sumP = -fullScale; sumP <= fullScale; sumP += 49999)
315 {
316 const double expected{ exactReference(sumP, n, typicalCal[phase]) };
317 const double actual{ static_cast< double >(Energy::contribution(sumP, table.value[phase][n - N_MIN_50HZ], table.shift)) };
318
319 // one unit of rounding, plus the quantisation of cal / n (coarsest at the largest n)
320 TEST_ASSERT_TRUE_MESSAGE(fabs(actual - expected) <= 1.0 + fabs(expected) * 4e-5, "per-sample contribution differs from the exact reference");
321 }
322 }
323 }
324}
325
327{
328 // the fallback (out-of-range n) divides first: both paths must agree within the
329 // truncation of that division (< 1 raw unit, i.e. < 1 bucket unit), their two
330 // roundings, and their two calibration quantisations (which may point opposite ways)
332 constexpr uint8_t shift{ Energy::calibrationShift(typicalCal) };
333 constexpr uint16_t calFixed{ Energy::toFixed(typicalCal[0], shift) };
334
335 for (uint8_t n = N_MIN_50HZ; n <= N_MAX_50HZ; ++n)
336 {
337 for (int32_t sumP = -static_cast< int32_t >(n) * FULL_SCALE; sumP <= static_cast< int32_t >(n) * FULL_SCALE; sumP += 77777)
338 {
339 const int32_t direct{ Energy::contribution(sumP, table.value[0][n - N_MIN_50HZ], table.shift) };
340 const int32_t divided{ Energy::contribution(sumP / n, calFixed, shift) };
341
342 TEST_ASSERT_TRUE_MESSAGE(fabs(static_cast< double >(direct - divided)) <= 2.0 + fabs(static_cast< double >(divided)) * 6e-5, "the per-sample and division paths disagree");
343 }
344 }
345}
346
348{
349 // n outside the table (start-up, missing phase): the ISR rescales the sum to NMin
350 // samples, (sumP / n) x NMin, and uses the NMin entry - same shift, no second path
352 static constexpr uint8_t unexpected[]{ 1, 5, 20, 27, 37, 64, 100, 255 };
353
354 for (const uint8_t n : unexpected)
355 {
356 for (int32_t average = -FULL_SCALE; average <= FULL_SCALE; average += 9973)
357 {
358 // with a remainder, so that the division truncates as it does in the ISR
359 const int32_t sumP{ average * n + ((average < 0) ? -(n - 1) : (n - 1)) };
360 const int32_t rescaled{ (sumP / n) * N_MIN_50HZ };
361 const double expected{ exactReference(sumP, n, typicalCal[1]) };
362 const double actual{ static_cast< double >(Energy::contribution(rescaled, table.value[1][0], table.shift)) };
363
364 // one unit of rounding, < 1 unit of truncation, plus the quantisation
365 TEST_ASSERT_TRUE_MESSAGE(fabs(actual - expected) <= 2.0 + fabs(expected) * 4e-5, "the fallback differs from the exact reference");
366 }
367 }
368}
369
371{
372 // the largest sum the ISR can hand over: N_MAX samples at full scale
374 const int32_t sumP{ static_cast< int32_t >(N_MAX_50HZ) * FULL_SCALE };
375 const uint16_t calOverN{ table.value[0][N_MAX_50HZ - N_MIN_50HZ] };
376
377 // same contract as elsewhere (1 unit + quantisation); an overflow would be off by orders of magnitude
378 const double expected{ exactReference(sumP, N_MAX_50HZ, largeCal[0]) };
379
380 TEST_ASSERT_TRUE(fabs(Energy::contribution(sumP, calOverN, table.shift) - expected) <= 1.0 + expected * 4e-5);
381 TEST_ASSERT_TRUE(fabs(Energy::contribution(-sumP, calOverN, table.shift) + expected) <= 1.0 + expected * 4e-5);
382}
383
385{
386 // 3000 cycles with n wandering around 32, as it does between zero crossings
388
389 int64_t bucket{ 0 };
390 double expected{ 0.0 };
391
392 for (int32_t cycle = 0; cycle < 3000; ++cycle)
393 {
394 const uint8_t n{ static_cast< uint8_t >(31 + cycle % 3) };
395 const int32_t sumP{ n * static_cast< int32_t >(20000.0 + 15000.0 * sin(cycle * 0.01)) + (cycle % 11) };
396
397 bucket += Energy::contribution(sumP, table.value[2][n - N_MIN_50HZ], table.shift);
398 expected += exactReference(sumP, n, typicalCal[2]);
399 }
400
401 TEST_ASSERT_TRUE_MESSAGE(fabs(static_cast< double >(bucket) - expected) <= fabs(expected) * 4e-5 + 64.0, "the per-sample bucket drifts from the exact one");
402}
403
404// ============================================================================
405// Units
406// ============================================================================
407
409{
410 constexpr int32_t exportAdjustment{ Energy::fromWatts(20) }; // must be constexpr
411
412 TEST_ASSERT_EQUAL_INT32(20 << Energy::FRACTION_BITS, exportAdjustment);
413 TEST_ASSERT_EQUAL_INT32(-(50 << Energy::FRACTION_BITS), Energy::fromWatts(-50));
414}
415
417{
418 // 1 Wh working zone at 60 Hz, the largest configuration: 3600 J x 60 cycles/s
419 constexpr int32_t capacity{ Energy::fromWatts(3600L * 60) };
420
421 TEST_ASSERT_EQUAL_INT32(3600L * 60 * (1L << Energy::FRACTION_BITS), capacity);
422}
423
424/* the exact value, rounded half away from zero, over the whole bucket and beyond */
425template< uint8_t SUPPLY_FREQUENCY >
427{
428 const int32_t capacity{ Energy::fromWatts(3600L * SUPPLY_FREQUENCY) };
429 const double unitsPerJoule{ static_cast< double >(SUPPLY_FREQUENCY << Energy::FRACTION_BITS) };
430
431 for (int32_t units = -2 * capacity; units <= 2 * capacity; units += 7)
432 {
433 const auto expected{ static_cast< int32_t >(llround(units * 100.0 / unitsPerJoule)) };
435 {
436 TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, Energy::toHundredthsOfJoule< SUPPLY_FREQUENCY >(units), "units");
437 }
438 }
439}
440
442{
443 static_assert(Energy::toHundredthsOfJoule< 50 >(800) == 100, "800 units = 1 J at 50 Hz");
444 static_assert(Energy::toHundredthsOfJoule< 50 >(4) == 1, "half a hundredth rounds up");
445 static_assert(Energy::toHundredthsOfJoule< 50 >(-4) == -1, "and away from zero");
446 static_assert(Energy::toHundredthsOfJoule< 50 >(3) == 0, "below half rounds down");
447
449}
450
452{
453 static_assert(Energy::toHundredthsOfJoule< 60 >(960) == 100, "960 units = 1 J at 60 Hz");
454 static_assert(Energy::toHundredthsOfJoule< 60 >(-960) == -100, "sign symmetric");
455
457}
458
459// ============================================================================
460
461int main(int, char **)
462{
463 UNITY_BEGIN();
464
474
482
491
496
497 return UNITY_END();
498}
constexpr uint8_t SUPPLY_FREQUENCY
void setUp(void)
Definition test_main.cpp:27
void tearDown(void)
Definition test_main.cpp:28
uint8_t i
Integer arithmetic of the energy bucket.
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.
constexpr uint8_t FRACTION_BITS
int32_t contribution(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
Contribution of one mains cycle of one phase to the bucket.
constexpr PerSampleCalibration< NMin, NMax, N > toFixedPerSample(const float(&cal)[N])
Build the per-sample calibration table at compile time.
constexpr int32_t toHundredthsOfJoule(const int32_t units)
An energy in bucket units, in hundredths of a joule (for the datalog).
constexpr bool isValidCalibration(const float(&cal)[N])
Check that the calibration values can be represented.
constexpr int32_t fromWatts(const int32_t watts)
A power in watts, in bucket units per mains cycle.
static constexpr float smallCal[]
Definition test_main.cpp:32
static constexpr int32_t FULL_SCALE
Definition test_main.cpp:26
static constexpr float largeCal[]
Definition test_main.cpp:33
int main(void)
void test_valid_calibration_accepts_realistic_values(void)
void test_contribution_matches_the_reference_for_extreme_calibrations(void)
static void checkAgainstReference(const float(&cal)[3])
Every average power from -FULL_SCALE to +FULL_SCALE, in uneven steps.
void test_hundredths_of_joule_at_50Hz(void)
static double exactReference(int32_t sumP, uint8_t n, float cal)
The exact energy of one cycle: no truncating division, in bucket units.
static double quantisationError(float cal, uint8_t shift)
Relative error of a quantised calibration value.
Definition test_main.cpp:34
void test_no_drift_over_one_minute(void)
void test_per_sample_shift_for_60Hz(void)
void test_largest_value_fills_16_bits(void)
Definition test_main.cpp:70
static constexpr float typicalCal[]
Definition test_main.cpp:41
void test_per_sample_largest_value_fills_16_bits(void)
void test_toFixed_rounds_to_nearest(void)
Definition test_main.cpp:79
void test_contribution_rounding_shortcut_is_exact(void)
void test_per_sample_contribution_matches_the_exact_reference(void)
static constexpr uint8_t N_MIN_50HZ
void test_contribution_at_full_scale_does_not_overflow(void)
void test_shift_for_a_typical_calibration(void)
Definition test_main.cpp:49
void test_per_sample_shift_and_values(void)
void test_contribution_is_sign_symmetric(void)
static double reference(int32_t averagePower, float cal)
The float arithmetic being replaced, in bucket units.
Definition test_main.cpp:28
void test_valid_calibration_rejects_zero_negative_and_huge_values(void)
void test_shift_for_large_and_small_values(void)
Definition test_main.cpp:56
void test_per_sample_agrees_with_the_division_path(void)
void test_fromWatts_scales_by_the_fraction_bits(void)
void checkHundredthsOfJoule()
void test_bucket_capacity_fits_in_32_bits(void)
void test_per_sample_fallback_for_an_unexpected_cycle_length(void)
void test_contribution_of_zero_is_zero(void)
void test_shift_follows_the_largest_value(void)
Definition test_main.cpp:62
void test_typical_set_quantisation_error(void)
Definition test_main.cpp:98
void test_quantisation_error_is_negligible(void)
Definition test_main.cpp:87
void test_per_sample_no_drift_over_one_minute(void)
static constexpr uint8_t N_MAX_50HZ
static int32_t generalRounding(int32_t power, uint16_t calFixed, uint8_t shift)
contribution() with the general rounding, (product + 2^(r-1)) >> r, in 64 bits.
void test_contribution_matches_the_reference_for_a_typical_calibration(void)
void test_hundredths_of_joule_at_60Hz(void)
void test_per_sample_full_scale_does_not_overflow(void)
static void cycle(RemoteLoadCore< NumUnits > &core, const LoadStates(&states)[NumLoads])
Run one mains cycle: feed the states to the core, for the given map.
Definition test_main.cpp:26