3-phase PV router
Loading...
Searching...
No Matches
datalog_math.h
Go to the documentation of this file.
1
24
25#ifndef DATALOG_MATH_H
26#define DATALOG_MATH_H
27
28#include <stdint.h>
29
30#include "energy_bucket.h"
31#include "mult_asm.h"
32
33namespace Datalog
34{
45inline int16_t watts(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
46{
47 const bool negative{ averagePower < 0 };
48 const uint32_t magnitude{ static_cast< uint32_t >(negative ? -averagePower : averagePower) };
49
50 uint32_t product; // (magnitude x calFixed) >> 8, at most 2^26
51 multU24x16_to32_hi8(product, magnitude, calFixed);
52
53 const uint8_t remaining{ static_cast< uint8_t >(shift - 8) };
54 uint32_t rounded{ (product + (static_cast< uint32_t >(1) << (remaining - 1))) >> remaining };
55 if (rounded > INT16_MAX)
56 {
57 rounded = INT16_MAX;
58 }
59
60 const auto result{ static_cast< int16_t >(rounded) };
61 return negative ? static_cast< int16_t >(-result) : result;
62}
63
76constexpr uint8_t powerShift(const uint32_t maxSampleSets)
77{
78 return maxSampleSets > (static_cast< uint32_t >(INT32_MAX) >> 17) ? 4 : 0;
79}
80
95template< uint8_t SHIFT, typename Count >
96inline int32_t averagePower(const int32_t sum, const Count sampleSets)
97{
98 const auto n{ static_cast< int32_t >(sampleSets) }; // a signed division: the sum is signed
99 if constexpr (SHIFT == 0)
100 {
101 return sum / n;
102 }
103 else
104 {
105 const int32_t quotient{ sum / n };
106 const int32_t remainder{ sum % n }; // |remainder| < n: x 2^SHIFT fits
107 return quotient * (static_cast< int32_t >(1) << SHIFT) + remainder * (static_cast< int32_t >(1) << SHIFT) / n;
108 }
109}
110
111#ifdef __AVR__
112using uint24_t = __uint24;
113#else
114using uint24_t = uint32_t;
115#endif
116
117#ifdef __AVR__
118// The assembly of squareRoot(), as string literals to concatenate.
119
122#define DATALOG_SQRT_NORMALISE \
123 "tst %D[val] \n\t" \
124 "brne 6f \n\t" \
125 "5: \n\t" \
126 "mov %D[val], %C[val] \n\t" \
127 "mov %C[val], %B[val] \n\t" \
128 "mov %B[val], %A[val] \n\t" \
129 "clr %A[val] \n\t" \
130 "subi %[shift], -4 \n\t" \
131 "tst %D[val] \n\t" \
132 "breq 5b \n\t" \
133 "6: \n\t" \
134 "cpi %D[val], 0x40 \n\t" \
135 "brsh 7f \n\t" \
136 "lsl %A[val] \n\t" \
137 "rol %B[val] \n\t" \
138 "rol %C[val] \n\t" \
139 "rol %D[val] \n\t" \
140 "lsl %A[val] \n\t" \
141 "rol %B[val] \n\t" \
142 "rol %C[val] \n\t" \
143 "rol %D[val] \n\t" \
144 "inc %[shift] \n\t" \
145 "rjmp 6b \n\t" \
146 "7: \n\t"
147
150#define DATALOG_SQRT_DIGITS \
151 "clr %A[rem] \n\t" \
152 "clr %B[rem] \n\t" \
153 "clr %C[rem] \n\t" \
154 "clr %A[twice] \n\t" \
155 "clr %B[twice] \n\t" \
156 "clr %C[twice] \n\t" \
157 "ldi %[bytes], 4 \n\t" \
158 "1: \n\t" \
159 "ldi %[bits], 4 \n\t" \
160 "2: \n\t" \
161 "lsl %D[val] \n\t" \
162 "rol %A[rem] \n\t" \
163 "rol %B[rem] \n\t" \
164 "rol %C[rem] \n\t" \
165 "lsl %D[val] \n\t" \
166 "rol %A[rem] \n\t" \
167 "rol %B[rem] \n\t" \
168 "rol %C[rem] \n\t" \
169 "lsl %A[twice] \n\t" \
170 "rol %B[twice] \n\t" \
171 "rol %C[twice] \n\t" \
172 "cp %A[twice], %A[rem] \n\t" \
173 "cpc %B[twice], %B[rem] \n\t" \
174 "cpc %C[twice], %C[rem] \n\t" \
175 "brcc 3f \n\t" \
176 "sec \n\t" \
177 "sbc %A[rem], %A[twice] \n\t" \
178 "sbc %B[rem], %B[twice] \n\t" \
179 "sbc %C[rem], %C[twice] \n\t" \
180 "ori %A[twice], 2 \n\t" \
181 "3: \n\t" \
182 "dec %[bits] \n\t" \
183 "brne 2b \n\t" \
184 "mov %D[val], %C[val] \n\t" \
185 "mov %C[val], %B[val] \n\t" \
186 "mov %B[val], %A[val] \n\t" \
187 "dec %[bytes] \n\t" \
188 "brne 1b \n\t"
189
190#define DATALOG_SQRT_OPERANDS \
191 [rem] "=&r"(remainder), [twice] "=&d"(twiceRoot), [val] "+d"(value), [bytes] "=&d"(bytes), [bits] "=&d"(bits), [shift] "+d"(shift)
192#endif
193
212template< bool Normalise >
213inline uint16_t squareRoot(uint32_t value, uint8_t& fractionBits)
214{
215 uint8_t shift{ 0 };
216 uint24_t remainder;
217 uint24_t twiceRoot;
218
219 if (Normalise && !value)
220 {
221 fractionBits = 0;
222 return 0;
223 }
224
225#ifdef __AVR__
226 uint8_t bytes;
227 uint8_t bits;
228 if constexpr (Normalise)
229 {
230 asm(DATALOG_SQRT_NORMALISE DATALOG_SQRT_DIGITS:DATALOG_SQRT_OPERANDS : : "cc");
231 }
232 else
233 {
234 asm(DATALOG_SQRT_DIGITS:DATALOG_SQRT_OPERANDS : : "cc");
235 }
236#else
237 if constexpr (Normalise)
238 {
239 while (value < (1UL << 24)) // whole bytes, 4 bits of the root each
240 {
241 value <<= 8;
242 shift += 4;
243 }
244 while (value < (1UL << 30)) // then pairs of bits, 1 bit of the root each
245 {
246 value <<= 2;
247 ++shift;
248 }
249 }
250 remainder = 0;
251 twiceRoot = 0;
252 for (uint8_t step = 16; step; --step)
253 {
254 remainder = (remainder << 2) | (value >> 30); // bring down the next two bits
255 value <<= 2;
256 twiceRoot <<= 1; // root <<= 1
257 if (remainder > twiceRoot) // remainder >= 2 x root + 1
258 {
259 remainder -= twiceRoot + 1;
260 twiceRoot |= 2; // root |= 1
261 }
262 }
263#endif
264
265 fractionBits = shift;
266 auto root{ static_cast< uint16_t >(twiceRoot >> 1) };
267 // remainder = value - root^2: round up when value >= (root + 0.5)^2 = root^2 + root + 0.25
268 if ((remainder > root) && (root < UINT16_MAX))
269 {
270 ++root;
271 }
272 return root;
273}
274
275#ifdef __AVR__
276#undef DATALOG_SQRT_NORMALISE
277#undef DATALOG_SQRT_DIGITS
278#undef DATALOG_SQRT_OPERANDS
279#endif
280
287inline uint16_t isqrt(const uint32_t value)
288{
289 uint8_t fractionBits;
290 return squareRoot< false >(value, fractionBits);
291}
292
300inline uint16_t sqrtScaled(const uint32_t meanSquare, uint8_t& fractionBits)
301{
302 return squareRoot< true >(meanSquare, fractionBits);
303}
304
314constexpr uint16_t vrmsFactor(const uint8_t datalogPeriodInSeconds)
315{
316 return datalogPeriodInSeconds > 10 ? 400 : 100;
317}
318
325template< uint8_t N >
326constexpr uint8_t voltageShift(const uint16_t factor, const float (&cal)[N])
327{
328 return Energy::shiftFor(static_cast< float >(factor) * Energy::largestOf(cal));
329}
330
337template< uint8_t N >
338constexpr bool isValidVoltageCalibration(const uint16_t factor, const float (&cal)[N])
339{
340 for (const auto value : cal)
341 {
342 if (!(value > 0.0F))
343 {
344 return false;
345 }
346 }
347 return voltageShift(factor, cal) <= 16;
348}
349
358inline uint16_t vrms(const uint32_t meanSquare, const uint16_t calFixed, const uint8_t shift)
359{
360 uint8_t fractionBits;
361 const uint16_t root{ sqrtScaled(meanSquare, fractionBits) };
362
363 uint32_t product;
364 multU16x16_to32(product, root, calFixed);
365
366 // rounded shift by (fractionBits + shift), without overflowing the 32 bits of product:
367 // whole bytes first (byte moves on AVR), then the remaining bits one by one
368 uint8_t total{ static_cast< uint8_t >(fractionBits + shift) };
369 if (total)
370 {
371 --total; // the last bit is shifted out after the rounding
372 if (total >= 16)
373 {
374 product >>= 16;
375 total -= 16;
376 }
377 if (total >= 8)
378 {
379 product >>= 8;
380 total -= 8;
381 }
382 product = ((product >> total) + 1) >> 1;
383 }
384 return product > UINT16_MAX ? UINT16_MAX : static_cast< uint16_t >(product);
385}
386
390template< uint8_t N >
392{
393 uint16_t value[N];
394 uint8_t shift;
395};
396
402template< uint8_t N >
403constexpr FixedCalibration< N > powerCalibration(const float (&cal)[N])
404{
405 FixedCalibration< N > fixed{};
406 fixed.shift = Energy::calibrationShift(cal);
407 for (uint8_t phase = 0; phase < N; ++phase)
408 {
409 fixed.value[phase] = Energy::toFixed(cal[phase], fixed.shift);
410 }
411 return fixed;
412}
413
421template< uint8_t N >
422constexpr FixedCalibration< N > voltageCalibration(const uint16_t factor, const float (&cal)[N])
423{
424 FixedCalibration< N > fixed{};
425 fixed.shift = voltageShift(factor, cal);
426 for (uint8_t phase = 0; phase < N; ++phase)
427 {
428 fixed.value[phase] = Energy::toFixed(static_cast< float >(factor) * cal[phase], fixed.shift);
429 }
430 return fixed;
431}
432} // namespace Datalog
433
434#endif /* DATALOG_MATH_H */
Integer arithmetic of the energy bucket.
static void multU16x16_to32(uint32_t &result, A a, B b)
Optimized 16×16→32 unsigned multiplication with assembly.
Definition mult_asm.h:97
static void multU24x16_to32_hi8(uint32_t &result, A a, B b)
Optimized 24×16→40 unsigned multiplication, returning bits 8..39.
Definition mult_asm.h:144
Assembly-optimized multiplication functions for AVR microcontrollers.
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.
uint32_t uint24_t
constexpr uint8_t voltageShift(const uint16_t factor, const float(&cal)[N])
Largest shift that keeps every (factor x calibration value) within 16 bits.
uint16_t squareRoot(uint32_t value, uint8_t &fractionBits)
Square root, rounded to the nearest integer, of the value or of the value normalised.
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.
constexpr uint8_t shiftFor(const float largest)
Largest shift that keeps a value within 16 bits once scaled by 2^shift.
constexpr float largestOf(const float(&cal)[N])
Largest of the calibration values.
Calibration values of all phases in 16-bit fixed point, with their shared shift.