Fusion.cpp revision a83f45c6c734084422f56733c25350625594bc00
1/*
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
27/*
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 */
47static 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)
49
50static const float SYMMETRY_TOLERANCE = 1e-10f;
51
52/*
53 * Accelerometer updates will not be performed near free fall to avoid
54 * ill-conditioning and 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 =
59        FREE_FALL_THRESHOLD*FREE_FALL_THRESHOLD;
60
61/*
62 * The geomagnetic-field should be between 30uT and 60uT.
63 * Fields strengths greater than this likely indicate a local magnetic
64 * disturbance which we do not want to update into the fused frame.
65 */
66static const float MAX_VALID_MAGNETIC_FIELD = 100; // uT
67static const float MAX_VALID_MAGNETIC_FIELD_SQ =
68        MAX_VALID_MAGNETIC_FIELD*MAX_VALID_MAGNETIC_FIELD;
69
70/*
71 * Values of the field smaller than this should be ignored in fusion to avoid
72 * ill-conditioning. This state can happen with anomalous local magnetic
73 * disturbances canceling the Earth field.
74 */
75static const float MIN_VALID_MAGNETIC_FIELD = 10; // uT
76static const float MIN_VALID_MAGNETIC_FIELD_SQ =
77        MIN_VALID_MAGNETIC_FIELD*MIN_VALID_MAGNETIC_FIELD;
78
79/*
80 * If the cross product of two vectors has magnitude squared less than this,
81 * we reject it as invalid due to alignment of the vectors.
82 * This threshold is used to check for the case where the magnetic field sample
83 * is parallel to the gravity field, which can happen in certain places due
84 * to magnetic field disturbances.
85 */
86static const float MIN_VALID_CROSS_PRODUCT_MAG = 1.0e-3;
87static const float MIN_VALID_CROSS_PRODUCT_MAG_SQ =
88    MIN_VALID_CROSS_PRODUCT_MAG*MIN_VALID_CROSS_PRODUCT_MAG;
89
90// -----------------------------------------------------------------------
91
92template <typename TYPE, size_t C, size_t R>
93static mat<TYPE, R, R> scaleCovariance(
94        const mat<TYPE, C, R>& A,
95        const mat<TYPE, C, C>& P) {
96    // A*P*transpose(A);
97    mat<TYPE, R, R> APAt;
98    for (size_t r=0 ; r<R ; r++) {
99        for (size_t j=r ; j<R ; j++) {
100            double apat(0);
101            for (size_t c=0 ; c<C ; c++) {
102                double v(A[c][r]*P[c][c]*0.5);
103                for (size_t k=c+1 ; k<C ; k++)
104                    v += A[k][r] * P[c][k];
105                apat += 2 * v * A[c][j];
106            }
107            APAt[j][r] = apat;
108            APAt[r][j] = apat;
109        }
110    }
111    return APAt;
112}
113
114template <typename TYPE, typename OTHER_TYPE>
115static mat<TYPE, 3, 3> crossMatrix(const vec<TYPE, 3>& p, OTHER_TYPE diag) {
116    mat<TYPE, 3, 3> r;
117    r[0][0] = diag;
118    r[1][1] = diag;
119    r[2][2] = diag;
120    r[0][1] = p.z;
121    r[1][0] =-p.z;
122    r[0][2] =-p.y;
123    r[2][0] = p.y;
124    r[1][2] = p.x;
125    r[2][1] =-p.x;
126    return r;
127}
128
129
130template<typename TYPE, size_t SIZE>
131class Covariance {
132    mat<TYPE, SIZE, SIZE> mSumXX;
133    vec<TYPE, SIZE> mSumX;
134    size_t mN;
135public:
136    Covariance() : mSumXX(0.0f), mSumX(0.0f), mN(0) { }
137    void update(const vec<TYPE, SIZE>& x) {
138        mSumXX += x*transpose(x);
139        mSumX  += x;
140        mN++;
141    }
142    mat<TYPE, SIZE, SIZE> operator()() const {
143        const float N = 1.0f / mN;
144        return mSumXX*N - (mSumX*transpose(mSumX))*(N*N);
145    }
146    void reset() {
147        mN = 0;
148        mSumXX = 0;
149        mSumX = 0;
150    }
151    size_t getCount() const {
152        return mN;
153    }
154};
155
156// -----------------------------------------------------------------------
157
158Fusion::Fusion() {
159    Phi[0][1] = 0;
160    Phi[1][1] = 1;
161
162    Ba.x = 0;
163    Ba.y = 0;
164    Ba.z = 1;
165
166    Bm.x = 0;
167    Bm.y = 1;
168    Bm.z = 0;
169
170    init();
171}
172
173void Fusion::init() {
174    mInitState = 0;
175
176    mGyroRate = 0;
177
178    mCount[0] = 0;
179    mCount[1] = 0;
180    mCount[2] = 0;
181
182    mData = 0;
183}
184
185void Fusion::initFusion(const vec4_t& q, float dT)
186{
187    // initial estimate: E{ x(t0) }
188    x0 = q;
189    x1 = 0;
190
191    // process noise covariance matrix: G.Q.Gt, with
192    //
193    //  G = | -1 0 |        Q = | q00 q10 |
194    //      |  0 1 |            | q01 q11 |
195    //
196    // q00 = sv^2.dt + 1/3.su^2.dt^3
197    // q10 = q01 = 1/2.su^2.dt^2
198    // q11 = su^2.dt
199    //
200
201    // variance of integrated output at 1/dT Hz
202    // (random drift)
203    const float q00 = gyroVAR * dT;
204
205    // variance of drift rate ramp
206    const float q11 = biasVAR * dT;
207
208    const float u   = q11 / dT;
209    const float q10 = 0.5f*u*dT*dT;
210    const float q01 = q10;
211
212    GQGt[0][0] =  q00;      // rad^2
213    GQGt[1][0] = -q10;
214    GQGt[0][1] = -q01;
215    GQGt[1][1] =  q11;      // (rad/s)^2
216
217    // initial covariance: Var{ x(t0) }
218    // TODO: initialize P correctly
219    P = 0;
220}
221
222bool Fusion::hasEstimate() const {
223    return (mInitState == (MAG|ACC|GYRO));
224}
225
226bool Fusion::checkInitComplete(int what, const vec3_t& d, float dT) {
227    if (hasEstimate())
228        return true;
229
230    if (what == ACC) {
231        mData[0] += d * (1/length(d));
232        mCount[0]++;
233        mInitState |= ACC;
234    } else if (what == MAG) {
235        mData[1] += d * (1/length(d));
236        mCount[1]++;
237        mInitState |= MAG;
238    } else if (what == GYRO) {
239        mGyroRate = dT;
240        mData[2] += d*dT;
241        mCount[2]++;
242        if (mCount[2] == 64) {
243            // 64 samples is good enough to estimate the gyro drift and
244            // doesn't take too much time.
245            mInitState |= GYRO;
246        }
247    }
248
249    if (mInitState == (MAG|ACC|GYRO)) {
250        // Average all the values we collected so far
251        mData[0] *= 1.0f/mCount[0];
252        mData[1] *= 1.0f/mCount[1];
253        mData[2] *= 1.0f/mCount[2];
254
255        // calculate the MRPs from the data collection, this gives us
256        // a rough estimate of our initial state
257        mat33_t R;
258        vec3_t up(mData[0]);
259        vec3_t east(cross_product(mData[1], up));
260        east *= 1/length(east);
261        vec3_t north(cross_product(up, east));
262        R << east << north << up;
263        const vec4_t q = matrixToQuat(R);
264
265        initFusion(q, mGyroRate);
266    }
267
268    return false;
269}
270
271void Fusion::handleGyro(const vec3_t& w, float dT) {
272    if (!checkInitComplete(GYRO, w, dT))
273        return;
274
275    predict(w, dT);
276}
277
278status_t Fusion::handleAcc(const vec3_t& a) {
279    // ignore acceleration data if we're close to free-fall
280    if (length_squared(a) < FREE_FALL_THRESHOLD_SQ) {
281        return BAD_VALUE;
282    }
283
284    if (!checkInitComplete(ACC, a))
285        return BAD_VALUE;
286
287    const float l = 1/length(a);
288    update(a*l, Ba, accSTDEV*l);
289    return NO_ERROR;
290}
291
292status_t Fusion::handleMag(const vec3_t& m) {
293    // the geomagnetic-field should be between 30uT and 60uT
294    // reject if too large to avoid spurious magnetic sources
295    const float magFieldSq = length_squared(m);
296    if (magFieldSq > MAX_VALID_MAGNETIC_FIELD_SQ) {
297        return BAD_VALUE;
298    } else if (magFieldSq < MIN_VALID_MAGNETIC_FIELD_SQ) {
299        // Also reject if too small since we will get ill-defined (zero mag)
300        // cross-products below
301        return BAD_VALUE;
302    }
303
304    if (!checkInitComplete(MAG, m))
305        return BAD_VALUE;
306
307    // Orthogonalize the magnetic field to the gravity field, mapping it into
308    // tangent to Earth.
309    const vec3_t up( getRotationMatrix() * Ba );
310    const vec3_t east( cross_product(m, up) );
311
312    // If the m and up vectors align, the cross product magnitude will
313    // approach 0.
314    // Reject this case as well to avoid div by zero problems and
315    // ill-conditioning below.
316    if (length_squared(east) < MIN_VALID_CROSS_PRODUCT_MAG_SQ) {
317        return BAD_VALUE;
318    }
319
320    // If we have created an orthogonal magnetic field successfully,
321    // then pass it in as the update.
322    vec3_t north( cross_product(up, east) );
323
324    const float l = 1 / length(north);
325    north *= l;
326
327    update(north, Bm, magSTDEV*l);
328    return NO_ERROR;
329}
330
331void Fusion::checkState() {
332    // P needs to stay positive semidefinite or the fusion diverges. When we
333    // detect divergence, we reset the fusion.
334    // TODO(braun): Instead, find the reason for the divergence and fix it.
335
336    if (!isPositiveSemidefinite(P[0][0], SYMMETRY_TOLERANCE) ||
337        !isPositiveSemidefinite(P[1][1], SYMMETRY_TOLERANCE)) {
338        LOGW("Sensor fusion diverged; resetting state.");
339        P = 0;
340    }
341}
342
343vec4_t Fusion::getAttitude() const {
344    return x0;
345}
346
347vec3_t Fusion::getBias() const {
348    return x1;
349}
350
351mat33_t Fusion::getRotationMatrix() const {
352    return quatToMatrix(x0);
353}
354
355mat34_t Fusion::getF(const vec4_t& q) {
356    mat34_t F;
357    F[0].x = q.w;   F[1].x =-q.z;   F[2].x = q.y;
358    F[0].y = q.z;   F[1].y = q.w;   F[2].y =-q.x;
359    F[0].z =-q.y;   F[1].z = q.x;   F[2].z = q.w;
360    F[0].w =-q.x;   F[1].w =-q.y;   F[2].w =-q.z;
361    return F;
362}
363
364void Fusion::predict(const vec3_t& w, float dT) {
365    const vec4_t q  = x0;
366    const vec3_t b  = x1;
367    const vec3_t we = w - b;
368    const vec4_t dq = getF(q)*((0.5f*dT)*we);
369    x0 = normalize_quat(q + dq);
370
371    // P(k+1) = F*P(k)*Ft + G*Q*Gt
372
373    //  Phi = | Phi00 Phi10 |
374    //        |   0     1   |
375    const mat33_t I33(1);
376    const mat33_t I33dT(dT);
377    const mat33_t wx(crossMatrix(we, 0));
378    const mat33_t wx2(wx*wx);
379    const float lwedT = length(we)*dT;
380    const float ilwe = 1/length(we);
381    const float k0 = (1-cosf(lwedT))*(ilwe*ilwe);
382    const float k1 = sinf(lwedT);
383
384    Phi[0][0] = I33 - wx*(k1*ilwe) + wx2*k0;
385    Phi[1][0] = wx*k0 - I33dT - wx2*(ilwe*ilwe*ilwe)*(lwedT-k1);
386
387    P = Phi*P*transpose(Phi) + GQGt;
388
389    checkState();
390}
391
392void Fusion::update(const vec3_t& z, const vec3_t& Bi, float sigma) {
393    vec4_t q(x0);
394    // measured vector in body space: h(p) = A(p)*Bi
395    const mat33_t A(quatToMatrix(q));
396    const vec3_t Bb(A*Bi);
397
398    // Sensitivity matrix H = dh(p)/dp
399    // H = [ L 0 ]
400    const mat33_t L(crossMatrix(Bb, 0));
401
402    // gain...
403    // K = P*Ht / [H*P*Ht + R]
404    vec<mat33_t, 2> K;
405    const mat33_t R(sigma*sigma);
406    const mat33_t S(scaleCovariance(L, P[0][0]) + R);
407    const mat33_t Si(invert(S));
408    const mat33_t LtSi(transpose(L)*Si);
409    K[0] = P[0][0] * LtSi;
410    K[1] = transpose(P[1][0])*LtSi;
411
412    // update...
413    // P -= K*H*P;
414    const mat33_t K0L(K[0] * L);
415    const mat33_t K1L(K[1] * L);
416    P[0][0] -= K0L*P[0][0];
417    P[1][1] -= K1L*P[1][0];
418    P[1][0] -= K0L*P[1][0];
419    P[0][1] = transpose(P[1][0]);
420
421    const vec3_t e(z - Bb);
422    const vec3_t dq(K[0]*e);
423    const vec3_t db(K[1]*e);
424
425    q += getF(q)*(0.5f*dq);
426    x0 = normalize_quat(q);
427    x1 += db;
428
429    checkState();
430}
431
432// -----------------------------------------------------------------------
433
434}; // namespace android
435
436