1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! http://www.juddzone.com/ALGORITHMS/least_squares_3D_ellipsoid.html
//! http://www.juddzone.com/ALGORITHMS/least_squares_precision_3D_ellipsoid.html
//! Has detailed examples, but unfortunately they rely on lin alg ops like inverse
//! on n-degree matrices.
//!
//! See also: https://github.com/PaulStoffregen/MotionCal/blob/master/magcal.c
//!
//! the `nalgebra` crate could simplify our matrix operations, but it increases binary size
//! too much.
// todo: Good approach, but you may be limited by embedded here on the matrix inverse. Maybe
// todo loop in nalgebra
use ;
use ;
use nalgebra as na;
use Float;
// todo: In addition to fitting hard and soft iron offsets from ellipsoids,
// todo: You can use the gyro to factor into these.
/// Vectors of attitudes the craft is at while taking elipsoid sample points. Make sure there
/// are several points near each of these prior to calibrating.
/// Dodecahedron vertices.
/// https://math.fandom.com/wiki/Dodecahedron
const PHI: f32 = 1.618_034; // 1/2 + (5/4).sqrt()
// todo: If this doesn't compile:
// use core::cell::OnceCell;
// static SAMPLE_VECS = OnceCell::new();
// SAMPLE_VECS.set().unwrap();
// todo: Normalize these!
pub const SAMPLE_VERTICES: = ;
// The angular distance between neighboring sample vecs. If a quaternion's *up* vec (We chose this
// arbitrarily; any vec will do) is closer than this to a sample vec, we group it with that sample vec.
pub const SAMPLE_VERTEX_ANGLE: f32 = 0.729_727_7;
// We need at least this many samples per category before calibrating.
// Note: We'd ideally like this to be higher, but are experiencing stack overflows eg at 5.
pub const MAG_SAMPLES_PER_CAT: usize = 2;
// // times 2, since we're comparing to perpendicular vectors to each point.
pub const TOTAL_MAG_SAMPLE_PTS: usize = MAG_SAMPLES_PER_CAT * SAMPLE_VERTICES.len * 2;
/// least squares fit to a 3D-ellipsoid
/// Ax^2 + By^2 + Cz^2 + Dxy + Exz + Fyz + Gx + Hy + Iz = 1
///
/// Note that sometimes it is expressed as a solution to
/// Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz = 1
/// where the last six terms have a factor of 2 in them
/// This is in anticipation of forming a matrix with the polynomial coefficients.
/// Those terms with factors of 2 are all off diagonal elements. These contribute
/// two terms when multiplied out (symmetric) so would need to be divided by two
, 9> = zeros;
for i in 0..TOTAL_MAG_SAMPLE_PTS
// column of ones
let K: TOTAL_MAG_SAMPLE_PTS }> = from;
// let K = [1.; TOTAL_MAG_SAMPLE_PTS];
let JT = J.transpose;
let JTJ = JT * J; // 9x9 matrix.
let InvJTJ = JTJ.try_inverse.unwrap;
let ABC = InvJTJ * ;
// Rearrange, move the 1 to the other side
// Ax^2 + By^2 + Cz^2 + Dxy + Exz + Fyz + Gx + Hy + Iz - 1 = 0
// or
// Ax^2 + By^2 + Cz^2 + Dxy + Exz + Fyz + Gx + Hy + Iz + J = 0
// where J = -1
// let mut result = [0.; 10];
// result[0..9].copy_from_slice(ABC[0..9]);
// result[9] = -1.; // J term
}
/// http://www.juddzone.com/ALGORITHMS/least_squares_3D_ellipsoid.html
/// convert the polynomial form of the 3D-ellipsoid to parameters
/// center, axes, and transformation matrix
/// vec is the vector whose elements are the polynomial
/// coefficients A..J
/// returns (center, axes, rotation matrix)
///
/// Algebraic form: X.T * Amat * X --> polynomial form
// "Iterative" appraoch below
// todo: If this approach works and is performant enough, remove the nalg dependency and above code.
// fn mag_dot_acc_err(mag: Vec3,acc: Vec3, mdg: Vec3, params: &[f32; 12]) -> Vec3 {
// // offset and transformation matrix from parameters
// let ofs = Vec3::new(params[0], params[1], params[2]);
//
// // let mat = np.reshape(params[3..12],(3,3));
// // Col-major.
// #[rustfmt::skip]
// let mat = Mat3::new([
// params[3], params[6], params[9],
// params[4], params[7], params[10],
// params[5], params[8], params[11],
// ]);
//
// // subtract offset, then apply transformation matrix
// let mc= mag - ofs;
//
// let mm = mat.dot(mc);
//
// // calculate dot product from corrected mags
// let mdg1 = mm.dot(acc);
//
// mdg-mdg1
//
// }
//
// fn analytic_partial_row(mag: Vec3,acc: Vec3, target: Vec3, params: &[f32; 12]) -> (Vec3, [f32; 12]){
// let err0 = magDotAccErr(mag, acc, target, params);
// // ll = len(params)
// let mut slopeArr = [0.; 12];
//
// slopeArr[0] = -(params[3] * acc.x + params[4] * acc.y + params[5] * acc.z);
// slopeArr[1] = -(params[6] * acc.x + params[7] * acc.y + params[8] * acc.z);
// slopeArr[2] = -(params[9] * acc.x + params[10] * acc.y + params[11] * acc.z);
//
// slopeArr[3] = (mag.x - params[0]) * acc.x;
// slopeArr[4] = (mag.y - params[1]) * acc.x;
// slopeArr[5] = (mag.z - params[2]) * acc.x;
//
// slopeArr[6] = (mag.x - params[0]) * acc.y;
// slopeArr[7] = (mag.y - params[1]) * acc.y;
// slopeArr[8] = (mag.z - params[2]) * acc.y;
//
// slopeArr[9] = (mag.x - params[0]) * acc.z;
// slopeArr[10] = (mag.y - params[1]) * acc.z;
// slopeArr[11] = (mag.z - params[2]) * acc.z;
//
// (err0, slopeArr)
// }
//
// fn numericPartialRow(mag: Vec3,acc: Vec3, target: Vec3, params: &mut [f32; 12], step: usize) -> (Vec3, [f32; 12]) {
// let err0 = mag_dot_acc_err(mag, acc, target, params);
//
// // let ll = params.len();
// const ll: usize = 12;
// let mut slopeArr = [0.; ll];
//
// for ix in 0..ll {
// params[ix] = params[ix] + step[ix];
// errA = mag_dot_acc_err(mag, acc, target, params);
//
// params[ix] = params[ix] - 2.0 * step[ix];
// errB = mag_dot_acc_err(mag, acc, target, params);
//
// params[ix] = params[ix] + step[ix];
// slope = (errB - errA) / (2.0 * step[ix]);
//
// slopeArr[ix] = slope;
// }
//
// (err0, slopeArr)
// }
//
//
// fn ellipsoid_iterate(mag: Vec3,accel: Vec3, verbose: bool) -> ([f32; 12], Vec3) {
//
// let magCorrected= mag.clone();
// // Obtain an estimate of the center and radius
// // For an ellipse we estimate the radius to be the average distance
// // of all data points to the center
// let (centerE,magR,magSTD)= ellipsoid_estimate2(mag,verbose);
//
// // Work with normalized data
// let magScaled=mag/magR;
// let centerScaled = centerE/magR;
//
// let accNorm = accel.to_normalized();
//
// let params = [0.; 12];
// // Use the estimated offsets, but our transformation matrix is unity
// params[0..3].clone_from_slice(&[centerScaled.x, centerScaled.y, centerScaled.z]);
//
// let mat = Mat3::new_identity();
//
// // todo: Probably needs to be recast as row-order to make this work.
// params[3..12].copy_from_slice(mat3.data);
//
// // initial dot based on centered mag, scaled with average radius
// let magCorrected=applyParams12(magScaled,params);
// let (avgDot,stdDot)=mgDot(magCorrected,accNorm);
//
// let nSamples= magScaled.len();
// let sigma = errorEstimate(magScaled,accNorm,avgDot,params);
// if verbose {
// println!("Initial sigma: {}", sigma);
// }
//
// // pre allocate the data. We do not actually need the entire
// // D matrix if we calculate DTD (a 12x12 matrix) within the sample loop
// // Also DTE (dimension 12) can be calculated on the fly.
//
// // let D = [0.]
// let D = np.zeros([nSamples,12]);
// let E= [0.; nSAMPLES];
//
// // If numeric derivatives are used, this step size works with normalized data.
// let step = [1./5_000.; 12];
//
// // Fixed number of iterations for testing. In production you check for convergence
//
// let nLoops= 5;
//
// for iloop in 0..nLoops {
// // Numeric or analytic partials each give the same answer
// for ix in 0..nSamples {
// // (f0,pdiff)=numericPartialRow(magScaled[ix],accNorm[ix],avgDot,params,step,1)
// (f0, pdiff) = analyticPartialRow(magScaled[ix], accNorm[ix], avgDot, params)
// E[ix] = f0;
// D[ix] = pdiff;
// }
// // Use the pseudo-inverse
// DT=D.T;
// DTD=np.dot(DT,D);
// DTE=np.dot(DT,E);
// invDTD=inv(DTD);
// deltas=np.dot(invDTD,DTE);
//
//
// p2=params + deltas;
//
// sigma = errorEstimate(magScaled,accNorm,avgDot,p2);
//
// // add some checking here on the behavior of sigma from loop to loop
// // if satisfied, use the new set of parameters for the next iteration
//
// params=p2;
//
// // recalculste gain (magR) and target dot product
// let magCorrected=applyParams12(magScaled,params);
// let (mc,mcR)=normalize3(magCorrected);
// let (avgDot,stdDot)=mgDot(mc,accNorm);
// magR *= mcR;
// let magScaled=mag/magR;
//
// if verbose {
// println!("iloop: {}, sigma: {}", iloop, sigma);
// }
// }
//
// (params,magR)
//