GeomagneticField.java revision 9066cfe9886ac131c34d59ed0e2d287b0e3c0087
1/*
2 * Copyright (C) 2009 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
17package android.hardware;
18
19import java.util.GregorianCalendar;
20
21/**
22 * This class is used to estimated estimate magnetic field at a given point on
23 * Earth, and in particular, to compute the magnetic declination from true
24 * north.
25 *
26 * <p>This uses the World Magnetic Model produced by the United States National
27 * Geospatial-Intelligence Agency.  More details about the model can be found at
28 * <a href="http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml">http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml</a>.
29 * This class currently uses WMM-2005 which is valid until 2010, but should
30 * produce acceptable results for several years after that.
31 */
32public class GeomagneticField {
33    // The magnetic field at a given point, in nonoteslas in geodetic
34    // coordinates.
35    private float mX;
36    private float mY;
37    private float mZ;
38
39    // Geocentric coordinates -- set by computeGeocentricCoordinates.
40    private float mGcLatitudeRad;
41    private float mGcLongitudeRad;
42    private float mGcRadiusKm;
43
44    // Constants from WGS84 (the coordinate system used by GPS)
45    static private final float EARTH_SEMI_MAJOR_AXIS_KM = 6378.137f;
46    static private final float EARTH_SEMI_MINOR_AXIS_KM = 6356.7523f;
47    static private final float EARTH_REFERENCE_RADIUS_KM = 6371.2f;
48
49    // These coefficients and the formulae used below are from:
50    // NOAA Technical Report: The US/UK World Magnetic Model for 2005-2010
51    static private final float[][] G_COEFF = new float[][] {
52        { 0f },
53        { -29556.8f, -1671.7f },
54        { -2340.6f, 3046.9f, 1657.0f },
55        { 1335.4f, -2305.1f, 1246.7f, 674.0f },
56        { 919.8f, 798.1f, 211.3f, -379.4f, 100.0f },
57        { -227.4f, 354.6f, 208.7f, -136.5f, -168.3f, -14.1f },
58        { 73.2f, 69.7f, 76.7f, -151.2f, -14.9f, 14.6f, -86.3f },
59        { 80.1f, -74.5f, -1.4f, 38.5f, 12.4f, 9.5f, 5.7f, 1.8f },
60        { 24.9f, 7.7f, -11.6f, -6.9f, -18.2f, 10.0f, 9.2f, -11.6f, -5.2f },
61        { 5.6f, 9.9f, 3.5f, -7.0f, 5.1f, -10.8f, -1.3f, 8.8f, -6.7f, -9.1f },
62        { -2.3f, -6.3f, 1.6f, -2.6f, 0.0f, 3.1f, 0.4f, 2.1f, 3.9f, -0.1f, -2.3f },
63        { 2.8f, -1.6f, -1.7f, 1.7f, -0.1f, 0.1f, -0.7f, 0.7f, 1.8f, 0.0f, 1.1f, 4.1f },
64        { -2.4f, -0.4f, 0.2f, 0.8f, -0.3f, 1.1f, -0.5f, 0.4f, -0.3f, -0.3f, -0.1f,
65          -0.3f, -0.1f } };
66
67    static private final float[][] H_COEFF = new float[][] {
68        { 0f },
69        { 0.0f, 5079.8f },
70        { 0.0f, -2594.7f, -516.7f },
71        { 0.0f, -199.9f, 269.3f, -524.2f },
72        { 0.0f, 281.5f, -226.0f, 145.8f, -304.7f },
73        { 0.0f, 42.4f, 179.8f, -123.0f, -19.5f, 103.6f },
74        { 0.0f, -20.3f, 54.7f, 63.6f, -63.4f, -0.1f, 50.4f },
75        { 0.0f, -61.5f, -22.4f, 7.2f, 25.4f, 11.0f, -26.4f, -5.1f },
76        { 0.0f, 11.2f, -21.0f, 9.6f, -19.8f, 16.1f, 7.7f, -12.9f, -0.2f },
77        { 0.0f, -20.1f, 12.9f, 12.6f, -6.7f, -8.1f, 8.0f, 2.9f, -7.9f, 6.0f },
78        { 0.0f, 2.4f, 0.2f, 4.4f, 4.8f, -6.5f, -1.1f, -3.4f, -0.8f, -2.3f, -7.9f },
79        { 0.0f, 0.3f, 1.2f, -0.8f, -2.5f, 0.9f, -0.6f, -2.7f, -0.9f, -1.3f, -2.0f, -1.2f },
80        { 0.0f, -0.4f, 0.3f, 2.4f, -2.6f, 0.6f, 0.3f, 0.0f, 0.0f, 0.3f, -0.9f, -0.4f,
81          0.8f } };
82
83    static private final float[][] DELTA_G = new float[][] {
84        { 0f },
85        { 8.0f, 10.6f },
86        { -15.1f, -7.8f, -0.8f },
87        { 0.4f, -2.6f, -1.2f, -6.5f },
88        { -2.5f, 2.8f, -7.0f, 6.2f, -3.8f },
89        { -2.8f, 0.7f, -3.2f, -1.1f, 0.1f, -0.8f },
90        { -0.7f, 0.4f, -0.3f, 2.3f, -2.1f, -0.6f, 1.4f },
91        { 0.2f, -0.1f, -0.3f, 1.1f, 0.6f, 0.5f, -0.4f, 0.6f },
92        { 0.1f, 0.3f, -0.4f, 0.3f, -0.3f, 0.2f, 0.4f, -0.7f, 0.4f },
93        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
94        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
95        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
96        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } };
97
98    static private final float[][] DELTA_H = new float[][] {
99        { 0f },
100        { 0.0f, -20.9f },
101        { 0.0f, -23.2f, -14.6f },
102        { 0.0f, 5.0f, -7.0f, -0.6f },
103        { 0.0f, 2.2f, 1.6f, 5.8f, 0.1f },
104        { 0.0f, 0.0f, 1.7f, 2.1f, 4.8f, -1.1f },
105        { 0.0f, -0.6f, -1.9f, -0.4f, -0.5f, -0.3f, 0.7f },
106        { 0.0f, 0.6f, 0.4f, 0.2f, 0.3f, -0.8f, -0.2f, 0.1f },
107        { 0.0f, -0.2f, 0.1f, 0.3f, 0.4f, 0.1f, -0.2f, 0.4f, 0.4f },
108        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
109        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
110        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
111        { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } };
112
113    static private final long BASE_TIME =
114        new GregorianCalendar(2005, 1, 1).getTimeInMillis();
115
116    // The ratio between the Gauss-normalized associated Legendre functions and
117    // the Schmid quasi-normalized ones. Compute these once staticly since they
118    // don't depend on input variables at all.
119    static private final float[][] SCHMIDT_QUASI_NORM_FACTORS =
120        computeSchmidtQuasiNormFactors(G_COEFF.length);
121
122    /**
123     * Estimate the magnetic field at a given point and time.
124     *
125     * @param gdLatitudeDeg
126     *            Latitude in WGS84 geodetic coordinates -- positive is east.
127     * @param gdLongitudeDeg
128     *            Longitude in WGS84 geodetic coordinates -- positive is north.
129     * @param altitudeMeters
130     *            Altitude in WGS84 geodetic coordinates, in meters.
131     * @param timeMillis
132     *            Time at which to evaluate the declination, in milliseconds
133     *            since January 1, 1970. (approximate is fine -- the declination
134     *            changes very slowly).
135     */
136    public GeomagneticField(float gdLatitudeDeg,
137                            float gdLongitudeDeg,
138                            float altitudeMeters,
139                            long timeMillis) {
140        final int MAX_N = G_COEFF.length; // Maximum degree of the coefficients.
141
142        // We don't handle the north and south poles correctly -- pretend that
143        // we're not quite at them to avoid crashing.
144        gdLatitudeDeg = Math.min(90.0f - 1e-5f,
145                                 Math.max(-90.0f + 1e-5f, gdLatitudeDeg));
146        computeGeocentricCoordinates(gdLatitudeDeg,
147                                     gdLongitudeDeg,
148                                     altitudeMeters);
149
150        assert G_COEFF.length == H_COEFF.length;
151
152        // Note: LegendreTable computes associated Legendre functions for
153        // cos(theta).  We want the associated Legendre functions for
154        // sin(latitude), which is the same as cos(PI/2 - latitude), except the
155        // derivate will be negated.
156        LegendreTable legendre =
157            new LegendreTable(MAX_N - 1,
158                              (float) (Math.PI / 2.0 - mGcLatitudeRad));
159
160        // Compute a table of (EARTH_REFERENCE_RADIUS_KM / radius)^n for i in
161        // 0..MAX_N-2 (this is much faster than calling Math.pow MAX_N+1 times).
162        float[] relativeRadiusPower = new float[MAX_N + 2];
163        relativeRadiusPower[0] = 1.0f;
164        relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS_KM / mGcRadiusKm;
165        for (int i = 2; i < relativeRadiusPower.length; ++i) {
166            relativeRadiusPower[i] = relativeRadiusPower[i - 1] *
167                relativeRadiusPower[1];
168        }
169
170        // Compute tables of sin(lon * m) and cos(lon * m) for m = 0..MAX_N --
171        // this is much faster than calling Math.sin and Math.com MAX_N+1 times.
172        float[] sinMLon = new float[MAX_N];
173        float[] cosMLon = new float[MAX_N];
174        sinMLon[0] = 0.0f;
175        cosMLon[0] = 1.0f;
176        sinMLon[1] = (float) Math.sin(mGcLongitudeRad);
177        cosMLon[1] = (float) Math.cos(mGcLongitudeRad);
178
179        for (int m = 2; m < MAX_N; ++m) {
180            // Standard expansions for sin((m-x)*theta + x*theta) and
181            // cos((m-x)*theta + x*theta).
182            int x = m >> 1;
183            sinMLon[m] = sinMLon[m-x] * cosMLon[x] + cosMLon[m-x] * sinMLon[x];
184            cosMLon[m] = cosMLon[m-x] * cosMLon[x] - sinMLon[m-x] * sinMLon[x];
185        }
186
187        float inverseCosLatitude = 1.0f / (float) Math.cos(mGcLatitudeRad);
188        float yearsSinceBase =
189            (timeMillis - BASE_TIME) / (365f * 24f * 60f * 60f * 1000f);
190
191        // We now compute the magnetic field strength given the geocentric
192        // location. The magnetic field is the derivative of the potential
193        // function defined by the model. See NOAA Technical Report: The US/UK
194        // World Magnetic Model for 2005-2010 for the derivation.
195        float gcX = 0.0f;  // Geocentric northwards component.
196        float gcY = 0.0f;  // Geocentric eastwards component.
197        float gcZ = 0.0f;  // Geocentric downwards component.
198
199        for (int n = 1; n < MAX_N; n++) {
200            for (int m = 0; m <= n; m++) {
201                // Adjust the coefficients for the current date.
202                float g = G_COEFF[n][m] + yearsSinceBase * DELTA_G[n][m];
203                float h = H_COEFF[n][m] + yearsSinceBase * DELTA_H[n][m];
204
205                // Negative derivative with respect to latitude, divided by
206                // radius.  This looks like the negation of the version in the
207                // NOAA Techincal report because that report used
208                // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the
209                // derivative with respect to theta is negated.
210                gcX += relativeRadiusPower[n+2]
211                    * (g * cosMLon[m] + h * sinMLon[m])
212                    * legendre.mPDeriv[n][m]
213                    * SCHMIDT_QUASI_NORM_FACTORS[n][m];
214
215                // Negative derivative with respect to longitude, divided by
216                // radius.
217                gcY += relativeRadiusPower[n+2] * m
218                    * (g * sinMLon[m] - h * cosMLon[m])
219                    * legendre.mP[n][m]
220                    * SCHMIDT_QUASI_NORM_FACTORS[n][m]
221                    * inverseCosLatitude;
222
223                // Negative derivative with respect to radius.
224                gcZ -= (n + 1) * relativeRadiusPower[n+2]
225                    * (g * cosMLon[m] + h * sinMLon[m])
226                    * legendre.mP[n][m]
227                    * SCHMIDT_QUASI_NORM_FACTORS[n][m];
228            }
229        }
230
231        // Convert back to geodetic coordinates.  This is basically just a
232        // rotation around the Y-axis by the difference in latitudes between the
233        // geocentric frame and the geodetic frame.
234        double latDiffRad = Math.toRadians(gdLatitudeDeg) - mGcLatitudeRad;
235        mX = (float) (gcX * Math.cos(latDiffRad)
236                      + gcZ * Math.sin(latDiffRad));
237        mY = gcY;
238        mZ = (float) (- gcX * Math.sin(latDiffRad)
239                      + gcZ * Math.cos(latDiffRad));
240    }
241
242    /**
243     * @return The X (northward) component of the magnetic field in nanoteslas.
244     */
245    public float getX() {
246        return mX;
247    }
248
249    /**
250     * @return The Y (eastward) component of the magnetic field in nanoteslas.
251     */
252    public float getY() {
253        return mY;
254    }
255
256    /**
257     * @return The Z (downward) component of the magnetic field in nanoteslas.
258     */
259    public float getZ() {
260        return mZ;
261    }
262
263    /**
264     * @return The declination of the horizontal component of the magnetic
265     *         field from true north, in degrees (i.e. positive means the
266     *         magnetic field is rotated east that much from true north).
267     */
268    public float getDeclination() {
269        return (float) Math.toDegrees(Math.atan2(mY, mX));
270    }
271
272    /**
273     * @return The inclination of the magnetic field in degrees -- positive
274     *         means the magnetic field is rotated downwards.
275     */
276    public float getInclination() {
277        return (float) Math.toDegrees(Math.atan2(mZ,
278                                                 getHorizontalStrength()));
279    }
280
281    /**
282     * @return  Horizontal component of the field strength in nonoteslas.
283     */
284    public float getHorizontalStrength() {
285        return (float) Math.sqrt(mX * mX + mY * mY);
286    }
287
288    /**
289     * @return  Total field strength in nanoteslas.
290     */
291    public float getFieldStrength() {
292        return (float) Math.sqrt(mX * mX + mY * mY + mZ * mZ);
293    }
294
295    /**
296     * @param gdLatitudeDeg
297     *            Latitude in WGS84 geodetic coordinates.
298     * @param gdLongitudeDeg
299     *            Longitude in WGS84 geodetic coordinates.
300     * @param altitudeMeters
301     *            Altitude above sea level in WGS84 geodetic coordinates.
302     * @return Geocentric latitude (i.e. angle between closest point on the
303     *         equator and this point, at the center of the earth.
304     */
305    private void computeGeocentricCoordinates(float gdLatitudeDeg,
306                                              float gdLongitudeDeg,
307                                              float altitudeMeters) {
308        float altitudeKm = altitudeMeters / 1000.0f;
309        float a2 = EARTH_SEMI_MAJOR_AXIS_KM * EARTH_SEMI_MAJOR_AXIS_KM;
310        float b2 = EARTH_SEMI_MINOR_AXIS_KM * EARTH_SEMI_MINOR_AXIS_KM;
311        double gdLatRad = Math.toRadians(gdLatitudeDeg);
312        float clat = (float) Math.cos(gdLatRad);
313        float slat = (float) Math.sin(gdLatRad);
314        float tlat = slat / clat;
315        float latRad =
316            (float) Math.sqrt(a2 * clat * clat + b2 * slat * slat);
317
318        mGcLatitudeRad = (float) Math.atan(tlat * (latRad * altitudeKm + b2)
319                                           / (latRad * altitudeKm + a2));
320
321        mGcLongitudeRad = (float) Math.toRadians(gdLongitudeDeg);
322
323        float radSq = altitudeKm * altitudeKm
324            + 2 * altitudeKm * (float) Math.sqrt(a2 * clat * clat +
325                                                 b2 * slat * slat)
326            + (a2 * a2 * clat * clat + b2 * b2 * slat * slat)
327            / (a2 * clat * clat + b2 * slat * slat);
328        mGcRadiusKm = (float) Math.sqrt(radSq);
329    }
330
331
332    /**
333     * Utility class to compute a table of Gauss-normalized associated Legendre
334     * functions P_n^m(cos(theta))
335     */
336    static private class LegendreTable {
337        // These are the Gauss-normalized associated Legendre functions -- that
338        // is, they are normal Legendre functions multiplied by
339        // (n-m)!/(2n-1)!! (where (2n-1)!! = 1*3*5*...*2n-1)
340        public final float[][] mP;
341
342        // Derivative of mP, with respect to theta.
343        public final float[][] mPDeriv;
344
345        /**
346         * @param maxN
347         *            The maximum n- and m-values to support
348         * @param thetaRad
349         *            Returned functions will be Gauss-normalized
350         *            P_n^m(cos(thetaRad)), with thetaRad in radians.
351         */
352        public LegendreTable(int maxN, float thetaRad) {
353            // Compute the table of Gauss-normalized associated Legendre
354            // functions using standard recursion relations. Also compute the
355            // table of derivatives using the derivative of the recursion
356            // relations.
357            float cos = (float) Math.cos(thetaRad);
358            float sin = (float) Math.sin(thetaRad);
359
360            mP = new float[maxN + 1][];
361            mPDeriv = new float[maxN + 1][];
362            mP[0] = new float[] { 1.0f };
363            mPDeriv[0] = new float[] { 0.0f };
364            for (int n = 1; n <= maxN; n++) {
365            	mP[n] = new float[n + 1];
366                mPDeriv[n] = new float[n + 1];
367                for (int m = 0; m <= n; m++) {
368                    if (n == m) {
369                        mP[n][m] = sin * mP[n - 1][m - 1];
370                        mPDeriv[n][m] = cos * mP[n - 1][m - 1]
371                            + sin * mPDeriv[n - 1][m - 1];
372                    } else if (n == 1 || m == n - 1) {
373                        mP[n][m] = cos * mP[n - 1][m];
374                        mPDeriv[n][m] = -sin * mP[n - 1][m]
375                            + cos * mPDeriv[n - 1][m];
376                    } else {
377                        assert n > 1 && m < n - 1;
378                        float k = ((n - 1) * (n - 1) - m * m)
379                            / (float) ((2 * n - 1) * (2 * n - 3));
380                        mP[n][m] = cos * mP[n - 1][m] - k * mP[n - 2][m];
381                        mPDeriv[n][m] = -sin * mP[n - 1][m]
382                            + cos * mPDeriv[n - 1][m] - k * mPDeriv[n - 2][m];
383                    }
384                }
385            }
386        }
387    }
388
389    /**
390     * Compute the ration between the Gauss-normalized associated Legendre
391     * functions and the Schmidt quasi-normalized version. This is equivalent to
392     * sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)!
393     */
394    private static float[][] computeSchmidtQuasiNormFactors(int maxN) {
395        float[][] schmidtQuasiNorm = new float[maxN + 1][];
396        schmidtQuasiNorm[0] = new float[] { 1.0f };
397        for (int n = 1; n <= maxN; n++) {
398            schmidtQuasiNorm[n] = new float[n + 1];
399            schmidtQuasiNorm[n][0] =
400                schmidtQuasiNorm[n - 1][0] * (2 * n - 1) / (float) n;
401            for (int m = 1; m <= n; m++) {
402                schmidtQuasiNorm[n][m] = schmidtQuasiNorm[n][m - 1]
403                    * (float) Math.sqrt((n - m + 1) * (m == 1 ? 2 : 1)
404                                / (float) (n + m));
405            }
406        }
407        return schmidtQuasiNorm;
408    }
409}