blob: e6ca2ccffaa24bed65ade0862de7d00f44e6d52c [file] [log] [blame]
Mathias Agopian984826c2011-05-17 22:54:42 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18
19#include <utils/Log.h>
20
21#include "Fusion.h"
22
23namespace android {
24
25// -----------------------------------------------------------------------
26
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -070027/*
28 * gyroVAR gives the measured variance of the gyro's output per
29 * Hz (or variance at 1 Hz). This is an "intrinsic" parameter of the gyro,
30 * which is independent of the sampling frequency.
31 *
32 * The variance of gyro's output at a given sampling period can be
33 * calculated as:
34 * variance(T) = gyroVAR / T
35 *
36 * The variance of the INTEGRATED OUTPUT at a given sampling period can be
37 * calculated as:
38 * variance_integrate_output(T) = gyroVAR * T
39 *
40 */
41static const float gyroVAR = 1e-7; // (rad/s)^2 / Hz
42static const float biasVAR = 1e-8; // (rad/s)^2 / s (guessed)
43
44/*
45 * Standard deviations of accelerometer and magnetometer
46 */
Mathias Agopian33015422011-05-27 18:18:13 -070047static const float accSTDEV = 0.05f; // m/s^2 (measured 0.08 / CDD 0.05)
48static const float magSTDEV = 0.5f; // uT (measured 0.7 / CDD 0.5)
Mathias Agopian984826c2011-05-17 22:54:42 -070049
Max Brauna01b4e22011-08-17 18:22:52 -070050static const float SYMMETRY_TOLERANCE = 1e-10f;
Mathias Agopian33015422011-05-27 18:18:13 -070051
Michael Johnson3e87d8d2011-08-19 11:47:08 -070052/*
53 * Accelerometer updates will not be performed near free fall to avoid ill-conditioning and
54 * div by zeros.
55 * Threshhold: 10% of g, in m/s^2
56 */
57static const float FREE_FALL_THRESHOLD = 0.981f;
58static const float FREE_FALL_THRESHOLD_SQ = FREE_FALL_THRESHOLD*FREE_FALL_THRESHOLD;
59
60/*
61 * The geomagnetic-field should be between 30uT and 60uT.
62 * Fields strengths greater than this likely indicate a local magnetic disturbance which
63 * we do not want to update into the fused frame.
64 */
65static const float MAX_VALID_MAGNETIC_FIELD = 100; // uT
66static const float MAX_VALID_MAGNETIC_FIELD_SQ = MAX_VALID_MAGNETIC_FIELD*MAX_VALID_MAGNETIC_FIELD;
67
68/*
69 * Values of the field smaller than this should be ignored in fusion to avoid ill-conditioning.
70 * This state can happen with anomalous local magnetic disturbances canceling the Earth field.
71 */
72static const float MIN_VALID_MAGNETIC_FIELD = 10; // uT
73static const float MIN_VALID_MAGNETIC_FIELD_SQ = MIN_VALID_MAGNETIC_FIELD*MIN_VALID_MAGNETIC_FIELD;
74
75/*
76 * If the cross product of two vectors has magnitude squared less than this, we reject it as
77 * invalid due to alignment of the vectors.
78 * This threshold is used to check for the case where the magnetic field sample is parallel to
79 * the gravity field, which can happen in certain places due to magnetic field disturbances.
80 */
81static const float MIN_VALID_CROSS_PRODUCT_MAG = 1.0e-3;
82static const float MIN_VALID_CROSS_PRODUCT_MAG_SQ =
83 MIN_VALID_CROSS_PRODUCT_MAG*MIN_VALID_CROSS_PRODUCT_MAG;
84
Mathias Agopian33015422011-05-27 18:18:13 -070085// -----------------------------------------------------------------------
Mathias Agopian984826c2011-05-17 22:54:42 -070086
87template <typename TYPE, size_t C, size_t R>
88static mat<TYPE, R, R> scaleCovariance(
89 const mat<TYPE, C, R>& A,
90 const mat<TYPE, C, C>& P) {
91 // A*P*transpose(A);
92 mat<TYPE, R, R> APAt;
93 for (size_t r=0 ; r<R ; r++) {
94 for (size_t j=r ; j<R ; j++) {
95 double apat(0);
96 for (size_t c=0 ; c<C ; c++) {
97 double v(A[c][r]*P[c][c]*0.5);
98 for (size_t k=c+1 ; k<C ; k++)
99 v += A[k][r] * P[c][k];
100 apat += 2 * v * A[c][j];
101 }
102 APAt[j][r] = apat;
103 APAt[r][j] = apat;
104 }
105 }
106 return APAt;
107}
108
109template <typename TYPE, typename OTHER_TYPE>
110static mat<TYPE, 3, 3> crossMatrix(const vec<TYPE, 3>& p, OTHER_TYPE diag) {
111 mat<TYPE, 3, 3> r;
112 r[0][0] = diag;
113 r[1][1] = diag;
114 r[2][2] = diag;
115 r[0][1] = p.z;
116 r[1][0] =-p.z;
117 r[0][2] =-p.y;
118 r[2][0] = p.y;
119 r[1][2] = p.x;
120 r[2][1] =-p.x;
121 return r;
122}
123
Mathias Agopian984826c2011-05-17 22:54:42 -0700124
125template<typename TYPE, size_t SIZE>
126class Covariance {
127 mat<TYPE, SIZE, SIZE> mSumXX;
128 vec<TYPE, SIZE> mSumX;
129 size_t mN;
130public:
131 Covariance() : mSumXX(0.0f), mSumX(0.0f), mN(0) { }
132 void update(const vec<TYPE, SIZE>& x) {
133 mSumXX += x*transpose(x);
134 mSumX += x;
135 mN++;
136 }
137 mat<TYPE, SIZE, SIZE> operator()() const {
138 const float N = 1.0f / mN;
139 return mSumXX*N - (mSumX*transpose(mSumX))*(N*N);
140 }
141 void reset() {
142 mN = 0;
143 mSumXX = 0;
144 mSumX = 0;
145 }
146 size_t getCount() const {
147 return mN;
148 }
149};
150
151// -----------------------------------------------------------------------
152
153Fusion::Fusion() {
Mathias Agopian33015422011-05-27 18:18:13 -0700154 Phi[0][1] = 0;
155 Phi[1][1] = 1;
Mathias Agopian984826c2011-05-17 22:54:42 -0700156
157 Ba.x = 0;
158 Ba.y = 0;
159 Ba.z = 1;
160
161 Bm.x = 0;
162 Bm.y = 1;
163 Bm.z = 0;
164
165 init();
166}
167
168void Fusion::init() {
Mathias Agopian984826c2011-05-17 22:54:42 -0700169 mInitState = 0;
Max Brauna01b4e22011-08-17 18:22:52 -0700170
Mathias Agopian33015422011-05-27 18:18:13 -0700171 mGyroRate = 0;
Max Brauna01b4e22011-08-17 18:22:52 -0700172
Mathias Agopian984826c2011-05-17 22:54:42 -0700173 mCount[0] = 0;
174 mCount[1] = 0;
175 mCount[2] = 0;
Max Brauna01b4e22011-08-17 18:22:52 -0700176
Mathias Agopian984826c2011-05-17 22:54:42 -0700177 mData = 0;
178}
179
Mathias Agopian33015422011-05-27 18:18:13 -0700180void Fusion::initFusion(const vec4_t& q, float dT)
181{
182 // initial estimate: E{ x(t0) }
183 x0 = q;
184 x1 = 0;
185
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -0700186 // process noise covariance matrix: G.Q.Gt, with
187 //
188 // G = | -1 0 | Q = | q00 q10 |
189 // | 0 1 | | q01 q11 |
190 //
191 // q00 = sv^2.dt + 1/3.su^2.dt^3
192 // q10 = q01 = 1/2.su^2.dt^2
193 // q11 = su^2.dt
194 //
Mathias Agopian33015422011-05-27 18:18:13 -0700195
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -0700196 // variance of integrated output at 1/dT Hz
197 // (random drift)
198 const float q00 = gyroVAR * dT;
199
200 // variance of drift rate ramp
201 const float q11 = biasVAR * dT;
202
203 const float u = q11 / dT;
204 const float q10 = 0.5f*u*dT*dT;
Mathias Agopian33015422011-05-27 18:18:13 -0700205 const float q01 = q10;
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -0700206
207 GQGt[0][0] = q00; // rad^2
Mathias Agopian33015422011-05-27 18:18:13 -0700208 GQGt[1][0] = -q10;
209 GQGt[0][1] = -q01;
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -0700210 GQGt[1][1] = q11; // (rad/s)^2
Mathias Agopian33015422011-05-27 18:18:13 -0700211
212 // initial covariance: Var{ x(t0) }
Mathias Agopianeaf2d0b2011-06-13 16:00:49 -0700213 // TODO: initialize P correctly
Mathias Agopian33015422011-05-27 18:18:13 -0700214 P = 0;
215}
216
Mathias Agopian984826c2011-05-17 22:54:42 -0700217bool Fusion::hasEstimate() const {
218 return (mInitState == (MAG|ACC|GYRO));
219}
220
Mathias Agopian33015422011-05-27 18:18:13 -0700221bool Fusion::checkInitComplete(int what, const vec3_t& d, float dT) {
222 if (hasEstimate())
Mathias Agopian984826c2011-05-17 22:54:42 -0700223 return true;
224
225 if (what == ACC) {
226 mData[0] += d * (1/length(d));
227 mCount[0]++;
228 mInitState |= ACC;
229 } else if (what == MAG) {
230 mData[1] += d * (1/length(d));
231 mCount[1]++;
232 mInitState |= MAG;
233 } else if (what == GYRO) {
Mathias Agopian33015422011-05-27 18:18:13 -0700234 mGyroRate = dT;
235 mData[2] += d*dT;
Mathias Agopian984826c2011-05-17 22:54:42 -0700236 mCount[2]++;
237 if (mCount[2] == 64) {
238 // 64 samples is good enough to estimate the gyro drift and
239 // doesn't take too much time.
240 mInitState |= GYRO;
241 }
242 }
243
244 if (mInitState == (MAG|ACC|GYRO)) {
245 // Average all the values we collected so far
246 mData[0] *= 1.0f/mCount[0];
247 mData[1] *= 1.0f/mCount[1];
248 mData[2] *= 1.0f/mCount[2];
249
250 // calculate the MRPs from the data collection, this gives us
251 // a rough estimate of our initial state
252 mat33_t R;
253 vec3_t up(mData[0]);
254 vec3_t east(cross_product(mData[1], up));
255 east *= 1/length(east);
256 vec3_t north(cross_product(up, east));
257 R << east << north << up;
Mathias Agopian33015422011-05-27 18:18:13 -0700258 const vec4_t q = matrixToQuat(R);
Mathias Agopian984826c2011-05-17 22:54:42 -0700259
Mathias Agopian33015422011-05-27 18:18:13 -0700260 initFusion(q, mGyroRate);
Mathias Agopian984826c2011-05-17 22:54:42 -0700261 }
262
263 return false;
264}
265
266void Fusion::handleGyro(const vec3_t& w, float dT) {
Mathias Agopian33015422011-05-27 18:18:13 -0700267 if (!checkInitComplete(GYRO, w, dT))
Mathias Agopian984826c2011-05-17 22:54:42 -0700268 return;
269
Mathias Agopian33015422011-05-27 18:18:13 -0700270 predict(w, dT);
Mathias Agopian984826c2011-05-17 22:54:42 -0700271}
272
273status_t Fusion::handleAcc(const vec3_t& a) {
Mathias Agopian33015422011-05-27 18:18:13 -0700274 // ignore acceleration data if we're close to free-fall
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700275 if (length_squared(a) < FREE_FALL_THRESHOLD_SQ) {
276 LOGW("handleAcc: near free fall, not updating!");
Mathias Agopian984826c2011-05-17 22:54:42 -0700277 return BAD_VALUE;
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700278 }
Mathias Agopian984826c2011-05-17 22:54:42 -0700279
280 if (!checkInitComplete(ACC, a))
281 return BAD_VALUE;
282
Mathias Agopian984826c2011-05-17 22:54:42 -0700283 const float l = 1/length(a);
284 update(a*l, Ba, accSTDEV*l);
285 return NO_ERROR;
286}
287
288status_t Fusion::handleMag(const vec3_t& m) {
289 // the geomagnetic-field should be between 30uT and 60uT
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700290 // reject if too large to avoid spurious magnetic sources
291 const float magFieldSq = length_squared(m);
292 if (magFieldSq > MAX_VALID_MAGNETIC_FIELD_SQ) {
293 LOGW("handleMag: magnetic field too large, not updating!");
Mathias Agopian984826c2011-05-17 22:54:42 -0700294 return BAD_VALUE;
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700295 } else if (magFieldSq < MIN_VALID_MAGNETIC_FIELD_SQ) {
296 // Also reject if too small since we will get ill-defined (zero mag) cross-products below
297 LOGW("handleMag: magnetic field too small, not updating!");
298 return BAD_VALUE;
299 }
Mathias Agopian984826c2011-05-17 22:54:42 -0700300
301 if (!checkInitComplete(MAG, m))
302 return BAD_VALUE;
303
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700304 // Orthogonalize the magnetic field to the gravity field, mapping it into tangent to Earth.
Mathias Agopian984826c2011-05-17 22:54:42 -0700305 const vec3_t up( getRotationMatrix() * Ba );
306 const vec3_t east( cross_product(m, up) );
Michael Johnson3e87d8d2011-08-19 11:47:08 -0700307
308 // If the m and up vectors align, the cross product magnitude will approach 0.
309 // Reject this case as well to avoid div by zero problems and ill-conditioning below.
310 if (length_squared(east) < MIN_VALID_CROSS_PRODUCT_MAG_SQ) {
311 LOGW("handleMag: magnetic field too aligned with up vector, not updating!");
312 return BAD_VALUE;
313 }
314
315 // If we have created an orthogonal magnetic field successfully, then pass it in as the update.
Mathias Agopian984826c2011-05-17 22:54:42 -0700316 vec3_t north( cross_product(up, east) );
317
318 const float l = 1 / length(north);
319 north *= l;
320
Mathias Agopian984826c2011-05-17 22:54:42 -0700321 update(north, Bm, magSTDEV*l);
322 return NO_ERROR;
323}
324
Max Brauna01b4e22011-08-17 18:22:52 -0700325void Fusion::checkState() {
326 // P needs to stay positive semidefinite or the fusion diverges. When we
327 // detect divergence, we reset the fusion.
328 // TODO(braun): Instead, find the reason for the divergence and fix it.
329
330 if (!isPositiveSemidefinite(P[0][0], SYMMETRY_TOLERANCE) ||
331 !isPositiveSemidefinite(P[1][1], SYMMETRY_TOLERANCE)) {
332 LOGW("Sensor fusion diverged; resetting state.");
Mathias Agopian984826c2011-05-17 22:54:42 -0700333 P = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700334 }
Mathias Agopian984826c2011-05-17 22:54:42 -0700335}
336
Mathias Agopian33015422011-05-27 18:18:13 -0700337vec4_t Fusion::getAttitude() const {
338 return x0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700339}
340
341vec3_t Fusion::getBias() const {
Mathias Agopian33015422011-05-27 18:18:13 -0700342 return x1;
Mathias Agopian984826c2011-05-17 22:54:42 -0700343}
344
345mat33_t Fusion::getRotationMatrix() const {
Mathias Agopian33015422011-05-27 18:18:13 -0700346 return quatToMatrix(x0);
Mathias Agopian984826c2011-05-17 22:54:42 -0700347}
348
Mathias Agopian33015422011-05-27 18:18:13 -0700349mat34_t Fusion::getF(const vec4_t& q) {
350 mat34_t F;
351 F[0].x = q.w; F[1].x =-q.z; F[2].x = q.y;
352 F[0].y = q.z; F[1].y = q.w; F[2].y =-q.x;
353 F[0].z =-q.y; F[1].z = q.x; F[2].z = q.w;
354 F[0].w =-q.x; F[1].w =-q.y; F[2].w =-q.z;
Mathias Agopian984826c2011-05-17 22:54:42 -0700355 return F;
356}
357
Mathias Agopian33015422011-05-27 18:18:13 -0700358void Fusion::predict(const vec3_t& w, float dT) {
359 const vec4_t q = x0;
360 const vec3_t b = x1;
361 const vec3_t we = w - b;
362 const vec4_t dq = getF(q)*((0.5f*dT)*we);
363 x0 = normalize_quat(q + dq);
Mathias Agopian984826c2011-05-17 22:54:42 -0700364
Mathias Agopian33015422011-05-27 18:18:13 -0700365 // P(k+1) = F*P(k)*Ft + G*Q*Gt
Mathias Agopian984826c2011-05-17 22:54:42 -0700366
Mathias Agopian33015422011-05-27 18:18:13 -0700367 // Phi = | Phi00 Phi10 |
368 // | 0 1 |
369 const mat33_t I33(1);
370 const mat33_t I33dT(dT);
371 const mat33_t wx(crossMatrix(we, 0));
372 const mat33_t wx2(wx*wx);
373 const float lwedT = length(we)*dT;
374 const float ilwe = 1/length(we);
375 const float k0 = (1-cosf(lwedT))*(ilwe*ilwe);
376 const float k1 = sinf(lwedT);
Mathias Agopian984826c2011-05-17 22:54:42 -0700377
Mathias Agopian33015422011-05-27 18:18:13 -0700378 Phi[0][0] = I33 - wx*(k1*ilwe) + wx2*k0;
379 Phi[1][0] = wx*k0 - I33dT - wx2*(ilwe*ilwe*ilwe)*(lwedT-k1);
Mathias Agopian984826c2011-05-17 22:54:42 -0700380
Mathias Agopian33015422011-05-27 18:18:13 -0700381 P = Phi*P*transpose(Phi) + GQGt;
Max Brauna01b4e22011-08-17 18:22:52 -0700382
383 checkState();
Mathias Agopian984826c2011-05-17 22:54:42 -0700384}
385
386void Fusion::update(const vec3_t& z, const vec3_t& Bi, float sigma) {
Mathias Agopian33015422011-05-27 18:18:13 -0700387 vec4_t q(x0);
Mathias Agopian984826c2011-05-17 22:54:42 -0700388 // measured vector in body space: h(p) = A(p)*Bi
Mathias Agopian33015422011-05-27 18:18:13 -0700389 const mat33_t A(quatToMatrix(q));
Mathias Agopian984826c2011-05-17 22:54:42 -0700390 const vec3_t Bb(A*Bi);
391
392 // Sensitivity matrix H = dh(p)/dp
393 // H = [ L 0 ]
Mathias Agopian33015422011-05-27 18:18:13 -0700394 const mat33_t L(crossMatrix(Bb, 0));
Mathias Agopian984826c2011-05-17 22:54:42 -0700395
Mathias Agopian33015422011-05-27 18:18:13 -0700396 // gain...
397 // K = P*Ht / [H*P*Ht + R]
398 vec<mat33_t, 2> K;
Mathias Agopian984826c2011-05-17 22:54:42 -0700399 const mat33_t R(sigma*sigma);
400 const mat33_t S(scaleCovariance(L, P[0][0]) + R);
401 const mat33_t Si(invert(S));
402 const mat33_t LtSi(transpose(L)*Si);
Mathias Agopian984826c2011-05-17 22:54:42 -0700403 K[0] = P[0][0] * LtSi;
404 K[1] = transpose(P[1][0])*LtSi;
405
Mathias Agopian33015422011-05-27 18:18:13 -0700406 // update...
Mathias Agopian984826c2011-05-17 22:54:42 -0700407 // P -= K*H*P;
408 const mat33_t K0L(K[0] * L);
409 const mat33_t K1L(K[1] * L);
410 P[0][0] -= K0L*P[0][0];
411 P[1][1] -= K1L*P[1][0];
412 P[1][0] -= K0L*P[1][0];
Mathias Agopian33015422011-05-27 18:18:13 -0700413 P[0][1] = transpose(P[1][0]);
414
415 const vec3_t e(z - Bb);
416 const vec3_t dq(K[0]*e);
417 const vec3_t db(K[1]*e);
418
419 q += getF(q)*(0.5f*dq);
420 x0 = normalize_quat(q);
421 x1 += db;
Max Brauna01b4e22011-08-17 18:22:52 -0700422
423 checkState();
Mathias Agopian984826c2011-05-17 22:54:42 -0700424}
425
426// -----------------------------------------------------------------------
427
428}; // namespace android
429