REDAC HybridController
Firmware for LUCIDAC/REDAC Teensy
Loading...
Searching...
No Matches
statistics.cpp
Go to the documentation of this file.
1// Copyright (c) 2024 anabrid GmbH
2// Contact: https://www.anabrid.com/licensing/
3//
4// SPDX-License-Identifier: MIT OR GPL-2.0-or-later
5
6#include "utils/statistics.h"
7
8#include <cmath>
9
10// Input pairs consist of <x, y>
11// Returns y = a + b * x
12// where a is the first element, b the second and the third element is R^2
13std::tuple<float, float, float> regression(const std::vector<std::pair<float, float>> &data) {
14 float a = 0.0f, b = 0.0f;
15 float x_avg = 0.0f, y_avg = 0.0f;
16
17 for (size_t i = 0; i < data.size(); i++) {
18 x_avg += data[i].first;
19 y_avg += data[i].second;
20 }
21
22 x_avg /= data.size();
23 y_avg /= data.size();
24
25 float p = 0.0f, q = 0.0f;
26
27 for (size_t i = 0; i < data.size(); i++) {
28 p += (data[i].first - x_avg) * (data[i].second - y_avg);
29 q += (data[i].first - x_avg) * (data[i].first - x_avg);
30 }
31
32 b = p / q;
33 a = y_avg - b * x_avg;
34
35 float r_sq = 1.0f;
36
37 p = q = 0.0f;
38
39 for (size_t i = 0; i < data.size(); i++) {
40 p += (data[i].second - (a + data[i].first * b)) * (data[i].second - (a + data[i].first * b));
41 q += (data[i].second - y_avg) * (data[i].second - y_avg);
42 }
43
44 r_sq -= p / q;
45
46 return {a, b, r_sq};
47}
48
49// Standard deviation
50// Returns <average, standard deviation>
51std::tuple<float, float> std_dev(const std::vector<float> &data) {
52 float avg = vector_sum(data);
53 avg /= data.size();
54
55 float dev = 0.0f;
56 for (size_t i = 0; i < data.size(); i++)
57 dev += (data[i] - avg) * (data[i] - avg);
58
59 dev /= data.size();
60 dev = sqrt(dev);
61
62 return std::make_tuple(avg, dev);
63}
64
65// Calculates the mean square error of a data set, compared to an expected value data set
66float mean_sq_error(const std::vector<float> &data, const std::vector<float> &expected) {
67 if (data.size() != expected.size())
68 return -1;
69
70 float sum = 0.0f;
71
72 for (size_t i = 0; i < data.size(); i++)
73 sum += (data[i] - expected[i]) * (data[i] - expected[i]);
74
75 return sum / data.size();
76}
std::tuple< float, float, float > regression(const std::vector< std::pair< float, float > > &data)
float mean_sq_error(const std::vector< float > &data, const std::vector< float > &expected)
std::tuple< float, float > std_dev(const std::vector< float > &data)