Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
calibration.hpp
Go to the documentation of this file.
1/**
2 * @file calibration.hpp
3 * @brief Source calibration: fit, standard, routine
4 *
5 * A source reads a little off, for example from a divider's tolerance or an
6 * op-amp's offset. Calibration measures the source against known
7 * references and stores the correction as a line - scale and offset - that
8 * the app applies to every later reading.
9 *
10 * - LinearFit: the correction, apply(measured) = measured * scale + offset.
11 * - fit_points(): least squares over 2..N captured points.
12 * - VOctStandard: what a reference means in octaves (1 V per octave).
13 * - PointCalibration: the routine: begin, capture, capture, done.
14 *
15 * One shape drives every calibration an app runs - a button calls advance(),
16 * another cancel(), and the UI slot polls state() for the LED. The library
17 * holds no storage: fit() is POD, and the app writes it wherever it keeps
18 * its calibration.
19 *
20 * Usage - two-point V/Oct on a 1 V and 3 V reference:
21 * @code
22 * constexpr float REFS[] = {1.0f, 3.0f}; // volts
23 * sbl::control::PointCalibration<2> cal{REFS};
24 *
25 * cal.begin(); // button: start
26 * cal.capture(jack.value()); // button: patch 1 V, capture
27 * cal.capture(jack.value()); // button: patch 3 V, capture -> Done
28 * float pitch = cal.apply(jack.value()); // corrected, from now on
29 * @endcode
30 *
31 * Loading a stored fit skips the routine entirely: cal.set_fit(saved).
32 */
33
34#ifndef SBL_CONTROL_CALIBRATION_HPP_
35#define SBL_CONTROL_CALIBRATION_HPP_
36
37#include <cstdint>
38
39namespace sbl::control {
40
41// The correction
42
43/** A measured signal to a corrected one. Identity until a fit is computed or loaded. */
44struct LinearFit {
45 float scale = 1.0f; /**< multiplies the measured value */
46 float offset = 0.0f; /**< added after scaling */
47
48 /**
49 * @brief Correct a measured value
50 * @param measured Measured value
51 * @return measured * scale + offset
52 */
53 constexpr float apply(float measured) const { return measured * scale + offset; }
54};
55
56/**
57 * @brief Least-squares line through captured points
58 *
59 * @param measured what the source read at each reference
60 * @param expected what it should have read (the standard's answer)
61 * @param n 2 or more
62 * @param out the fit, untouched when the points are degenerate
63 * @return false if n < 2 or every measurement is the same value
64 */
65inline bool fit_points(const float* measured, const float* expected, uint8_t n, LinearFit& out) {
66 if (n < 2) {
67 return false;
68 }
69
70 float sum_x = 0.0f, sum_y = 0.0f;
71 for (uint8_t i = 0; i < n; ++i) {
72 sum_x += measured[i];
73 sum_y += expected[i];
74 }
75 const float inv_n = 1.0f / static_cast<float>(n);
76 const float mean_x = sum_x * inv_n;
77 const float mean_y = sum_y * inv_n;
78
79 float cov = 0.0f, var = 0.0f;
80 for (uint8_t i = 0; i < n; ++i) {
81 const float dx = measured[i] - mean_x;
82 cov += dx * (expected[i] - mean_y);
83 var += dx * dx;
84 }
85 if (var <= 1e-12f) {
86 return false; // every point read the same: no line
87 }
88
89 out.scale = cov / var;
90 out.offset = mean_y - out.scale * mean_x;
91 return true;
92}
93
94// What a reference means
95
96/**
97 * @brief 1 V per octave: the library's pitch is octaves (CvMapping::VOct)
98 *
99 * References are volts. A standard with a different scale - 1.2 V per
100 * octave, or a Hz-per-volt input - supplies its own `expected`.
101 */
103 static constexpr float OCTAVES_PER_VOLT = 1.0f; /**< 1 V per octave */
104
105 /**
106 * @brief The value a reference should read once corrected
107 * @param volts Reference voltage
108 * @return Octaves
109 */
110 static constexpr float expected(float volts) { return volts * OCTAVES_PER_VOLT; }
111};
112
113// The routine
114
115/** Where a PointCalibration is in its routine. */
116enum class CalState : uint8_t {
117 Idle, /**< not calibrating; fit() is whatever was loaded or measured */
118 Capturing, /**< waiting for the next reference point */
119 Done, /**< a fit was computed; accept() or cancel() */
120 Failed, /**< the points were degenerate; cancel() to restore */
121};
122
123/**
124 * @brief Capture N reference points, then fit
125 *
126 * The app decides when a reading has settled and calls capture() with the
127 * source's current reading. The last capture computes the fit. cancel() restores
128 * the fit that was in force when begin() was called, so an abandoned
129 * calibration costs nothing.
130 */
131template<uint8_t N, typename Standard = VOctStandard>
133 static_assert(N >= 2, "a line needs two points");
134
135public:
136 /** @param references the reference values, in the standard's units */
137 explicit PointCalibration(const float (&references)[N]) {
138 for (uint8_t i = 0; i < N; ++i) {
139 references_[i] = references[i];
140 }
141 }
142
143 /** Start capturing at point 0, remembering the current fit. */
144 void begin() {
145 backup_ = fit_;
146 point_ = 0;
147 state_ = CalState::Capturing;
148 }
149
150 /**
151 * @brief Record the source's reading for the current reference
152 * @param measured The source's reading, uncorrected
153 * @return true when this capture completed the calibration
154 */
155 bool capture(float measured) {
156 if (state_ != CalState::Capturing) {
157 return false;
158 }
159 measured_[point_] = measured;
160 ++point_;
161 if (point_ < N) {
162 return false;
163 }
164
165 float expected[N];
166 for (uint8_t i = 0; i < N; ++i) {
167 expected[i] = Standard::expected(references_[i]);
168 }
169
170 LinearFit fitted;
171 if (fit_points(measured_, expected, N, fitted)) {
172 fit_ = fitted;
173 state_ = CalState::Done;
174 } else {
175 state_ = CalState::Failed;
176 }
177 return true;
178 }
179
180 /** Leave the routine, keeping the new fit (the app persists it). */
181 void accept() {
182 if (state_ == CalState::Done) {
183 state_ = CalState::Idle;
184 }
185 }
186
187 /** Abandon: restore the fit from before begin(). */
188 void cancel() {
189 fit_ = backup_;
190 state_ = CalState::Idle;
191 point_ = 0;
192 }
193
194 /**
195 * @brief Correct a reading; identity until a fit is computed or loaded
196 * @param measured Measured value
197 * @return The corrected value
198 */
199 float apply(float measured) const { return fit_.apply(measured); }
200
201 /** @brief Where the routine is */
202 CalState state() const { return state_; }
203 /** @brief True while capturing points */
204 bool active() const { return state_ == CalState::Capturing; }
205
206 /** @brief Points captured so far: the index of the reference to patch next, for the UI */
207 uint8_t point() const { return point_; }
208 /** @brief Points the routine captures */
209 static constexpr uint8_t points() { return N; }
210
211 /** @brief The reference the app should patch for the current point */
212 float reference() const { return references_[point_ < N ? point_ : N - 1]; }
213
214 /** @brief The current fit */
215 const LinearFit& fit() const { return fit_; }
216
217 /**
218 * @brief Load a stored fit (boot) or install one by hand
219 * @param fit The fit to use
220 */
221 void set_fit(const LinearFit& fit) { fit_ = fit; }
222
223private:
224 float references_[N]{};
225 float measured_[N]{};
226 LinearFit fit_{};
227 LinearFit backup_{};
228 uint8_t point_ = 0;
229 CalState state_ = CalState::Idle;
230};
231
232} // namespace sbl::control
233
234#endif // SBL_CONTROL_CALIBRATION_HPP_
Capture N reference points, then fit.
PointCalibration(const float(&references)[N])
void set_fit(const LinearFit &fit)
Load a stored fit (boot) or install one by hand.
CalState state() const
Where the routine is.
bool capture(float measured)
Record the source's reading for the current reference.
const LinearFit & fit() const
The current fit.
float reference() const
The reference the app should patch for the current point.
uint8_t point() const
Points captured so far: the index of the reference to patch next, for the UI.
float apply(float measured) const
Correct a reading; identity until a fit is computed or loaded.
static constexpr uint8_t points()
Points the routine captures.
bool active() const
True while capturing points.
The control stack: scheduler, event queue, merge, CC mapping, calibration.
bool fit_points(const float *measured, const float *expected, uint8_t n, LinearFit &out)
Least-squares line through captured points.
constexpr float apply(float measured) const
Correct a measured value.
1 V per octave: the library's pitch is octaves (CvMapping::VOct)
static constexpr float OCTAVES_PER_VOLT
static constexpr float expected(float volts)
The value a reference should read once corrected.