-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWMM_SubLibrary.c
More file actions
3538 lines (3016 loc) · 122 KB
/
WMM_SubLibrary.c
File metadata and controls
3538 lines (3016 loc) · 122 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "WMMHeader.h"
/*
* ABSTRACT
*
* The purpose of WMM Subroutine Library is to support the World Magnetic Model (WMM) 2010-2015.
*
*
*
* REUSE NOTES
*
* WMM Subroutine Library is intended for reuse by any application that requires
* Computation of Geomagnetic field from WMM model.
*
* REFERENCES
*
* Further information on Geoid can be found in the WMM Technical Documents.
*
*
* LICENSES
*
* The WMM source code is in the public domain and not licensed or under copyright.
* The information and software may be used freely by the public. As required by 17 U.S.C. 403,
* third parties producing copyrighted works consisting predominantly of the material produced by
* U.S. government agencies must provide notice with such work(s) identifying the U.S. Government material
* incorporated and stating that such material is not subject to copyright protection.
*
* RESTRICTIONS
*
* WMM Subroutine library has no restrictions.
*
* ENVIRONMENT
*
* WMM Subroutine library was tested in the following environments
*
* 1. Red Hat Linux with GCC Compiler
* 2. MS Windows XP with CodeGear C++ compiler
* 3. Sun Solaris with GCC Compiler
*
*
* MODIFICATIONS
*
* Date Version
* ---- -----------
* Jul 15, 2009 0.1
* Nov 17, 2009 0.2
Nov 23, 2009 0.3
Jan 28, 2010 1.0
* Contact Information
* Sponsoring Government Agency
* National Geospatial-Intelligence Agency
* PRG / CSAT, M.S. L-41
* 3838 Vogel Road
* Arnold, MO 63010
* Attn: Craig Rollins
* Phone: (314) 263-4186
* Email: Craig.M.Rollins@Nga.Mil
* National Geophysical Data Center
* NOAA EGC/2
* 325 Broadway
* Boulder, CO 80303 USA
* Attn: Susan McLean
* Phone: (303) 497-6478
* Email: Susan.McLean@noaa.gov
* Software and Model Support
* National Geophysical Data Center
* NOAA EGC/2
* 325 Broadway"
* Boulder, CO 80303 USA
* Attn: Manoj Nair or Stefan Maus
* Phone: (303) 497-6522 or -6522
* Email: Manoj.C.Nair@noaa.gov or Stefan.Maus@noaa.gov
* URL: http://www.ngdc.noaa.gov/Geomagnetic/WMM/DoDWMM.shtml
* For more details on the subroutines, please consult the WMM
* Technical Documentations at
* http://www.ngdc.noaa.gov/Geomagnetic/WMM/DoDWMM.shtml
* Nov 23, 2009
* Written by Manoj C Nair and Adam Woods
* Manoj.C.Nair@Noaa.Gov
*/
int WMM_AssociatedLegendreFunction(WMMtype_CoordSpherical CoordSpherical, int nMax, WMMtype_LegendreFunction *LegendreFunction)
/* Computes all of the Schmidt-semi normalized associated Legendre
functions up to degree nMax. If nMax <= 16, function WMM_PcupLow is used.
Otherwise WMM_PcupHigh is called.
INPUT CoordSpherical A data structure with the following elements
double lambda; ( longitude)
double phig; ( geocentric latitude )
double r; ( distance from the center of the ellipsoid)
nMax integer ( Maxumum degree of spherical harmonic secular model)
LegendreFunction Pointer to data structure with the following elements
double *Pcup; ( pointer to store Legendre Function )
double *dPcup; ( pointer to store Derivative of Lagendre function )
OUTPUT LegendreFunction Calculated Legendre variables in the data structure
*/
{
double sin_phi;
int FLAG = 1;
sin_phi = sin ( DEG2RAD ( CoordSpherical.phig ) ); /* sin (geocentric latitude) */
if (nMax <= 16 || (1 - fabs(sin_phi)) < 1.0e-10 ) /* If nMax is less tha 16 or at the poles */
FLAG = WMM_PcupLow(LegendreFunction->Pcup,LegendreFunction->dPcup,sin_phi, nMax);
else FLAG = WMM_PcupHigh(LegendreFunction->Pcup,LegendreFunction->dPcup,sin_phi, nMax);
if (FLAG == 0) /* Error while computing Legendre variables*/
return FALSE;
return TRUE;
} /*WMM_AssociatedLegendreFunction */
int WMM_CalculateGeoMagneticElements(WMMtype_MagneticResults *MagneticResultsGeo, WMMtype_GeoMagneticElements *GeoMagneticElements)
/* Calculate all the Geomagnetic elements from X,Y and Z components
INPUT MagneticResultsGeo Pointer to data structure with the following elements
double Bx; ( North )
double By; ( East )
double Bz; ( Down )
OUTPUT GeoMagneticElements Pointer to data structure with the following elements
double Decl; (Angle between the magnetic field vector and true north, positive east)
double Incl; Angle between the magnetic field vector and the horizontal plane, positive down
double F; Magnetic Field Strength
double H; Horizontal Magnetic Field Strength
double X; Northern component of the magnetic field vector
double Y; Eastern component of the magnetic field vector
double Z; Downward component of the magnetic field vector
CALLS : none
*/
{
GeoMagneticElements->X = MagneticResultsGeo->Bx;
GeoMagneticElements->Y = MagneticResultsGeo->By;
GeoMagneticElements->Z = MagneticResultsGeo->Bz;
GeoMagneticElements->H = sqrt (MagneticResultsGeo->Bx* MagneticResultsGeo->Bx + MagneticResultsGeo->By * MagneticResultsGeo->By);
GeoMagneticElements->F = sqrt (GeoMagneticElements->H*GeoMagneticElements->H + MagneticResultsGeo->Bz * MagneticResultsGeo->Bz);
GeoMagneticElements->Decl = RAD2DEG(atan2 (GeoMagneticElements->Y , GeoMagneticElements->X));
GeoMagneticElements->Incl = RAD2DEG(atan2 (GeoMagneticElements->Z , GeoMagneticElements->H));
return TRUE;
} /*WMM_CalculateGeoMagneticElements */
int WMM_CalculateGridVariation(WMMtype_CoordGeodetic location, WMMtype_GeoMagneticElements *elements)
/*Computes the grid variation for |latitudes| > WMM_MAX_LAT_DEGREE
Grivation (or grid variation) is the angle between grid north and
magnetic north. This routine calculates Grivation for the Polar Stereographic
projection for polar locations (Latitude => |55| deg). Otherwise, it computes the grid
variation in UTM projection system. However, the UTM projection codes may be used to compute
the grid variation at any latitudes.
INPUT location Data structure with the following elements
double lambda; (longitude)
double phi; ( geodetic latitude)
double HeightAboveEllipsoid; (height above the ellipsoid (HaE) )
double HeightAboveGeoid;(height above the Geoid )
OUTPUT elements Data structure with the following elements updated
double GV; ( The Grid Variation )
CALLS : WMM_GetTransverseMercator
*/
{
WMMtype_UTMParameters UTMParameters;
if(location.phi >= WMM_PS_MAX_LAT_DEGREE)
{
elements->GV = elements->Decl - location.lambda;
return 1;
}
else if(location.phi <= WMM_PS_MIN_LAT_DEGREE)
{
elements->GV = elements->Decl + location.lambda;
return 1;
}
else
{
WMM_GetTransverseMercator(location, &UTMParameters);
elements->GV = elements->Decl - UTMParameters.ConvergenceOfMeridians;
}
return 0;
} /*WMM_CalculateGridVariation*/
int WMM_CalculateSecularVariation(WMMtype_MagneticResults MagneticVariation, WMMtype_GeoMagneticElements *MagneticElements)
/*This takes the Magnetic Variation in x, y, and z and uses it to calculate the secular variation of each of the Geomagnetic elements.
INPUT MagneticVariation Data structure with the following elements
double Bx; ( North )
double By; ( East )
double Bz; ( Down )
OUTPUT MagneticElements Pointer to the data structure with the following elements updated
double Decldot; Yearly Rate of change in declination
double Incldot; Yearly Rate of change in inclination
double Fdot; Yearly rate of change in Magnetic field strength
double Hdot; Yearly rate of change in horizontal field strength
double Xdot; Yearly rate of change in the northern component
double Ydot; Yearly rate of change in the eastern component
double Zdot; Yearly rate of change in the downward component
double GVdot;Yearly rate of chnage in grid variation
CALLS : none
*/
{
MagneticElements->Xdot = MagneticVariation.Bx;
MagneticElements->Ydot = MagneticVariation.By;
MagneticElements->Zdot = MagneticVariation.Bz;
MagneticElements->Hdot = (MagneticElements->X * MagneticElements->Xdot + MagneticElements->Y * MagneticElements->Ydot) / MagneticElements->H; //See equation 19 in the WMM technical report
MagneticElements->Fdot = (MagneticElements->X * MagneticElements->Xdot + MagneticElements->Y * MagneticElements->Ydot + MagneticElements->Z * MagneticElements->Zdot) / MagneticElements->F;
MagneticElements->Decldot = 180.0 / M_PI * (MagneticElements->X * MagneticElements->Ydot - MagneticElements->Y * MagneticElements->Xdot) / (MagneticElements->H * MagneticElements->H);
MagneticElements->Incldot = 180.0 / M_PI * (MagneticElements->H * MagneticElements->Zdot - MagneticElements->Z * MagneticElements->Hdot) / (MagneticElements->F * MagneticElements->F);
MagneticElements->GVdot = MagneticElements->Decldot;
return TRUE;
} /*WMM_CalculateSecularVariation*/
int WMM_CheckGeographicPole(WMMtype_CoordGeodetic *CoordGeodetic)
/* Check if the latitude is equal to -90 or 90. If it is,
offset it by 1e-5 to avoid division by zero. This is not currently used in the Geomagnetic
main function. This may be used to avoid calling WMM_SummationSpecial.
The function updates the input data structure.
INPUT CoordGeodetic Pointer to the data structure with the following elements
double lambda; (longitude)
double phi; ( geodetic latitude)
double HeightAboveEllipsoid; (height above the ellipsoid (HaE) )
double HeightAboveGeoid;(height above the Geoid )
OUTPUT CoordGeodetic Pointer to the data structure with the following elements updates
double phi; ( geodetic latitude)
CALLS : none
*/
{
CoordGeodetic->phi = CoordGeodetic->phi < (-90.0 + WMM_GEO_POLE_TOLERANCE) ? (-90.0 + WMM_GEO_POLE_TOLERANCE) : CoordGeodetic->phi;
CoordGeodetic->phi = CoordGeodetic->phi > ( 90.0 - WMM_GEO_POLE_TOLERANCE) ? ( 90.0 - WMM_GEO_POLE_TOLERANCE) : CoordGeodetic->phi;
return TRUE;
} /*WMM_CheckGeographicPole*/
int WMM_ComputeSphericalHarmonicVariables( WMMtype_Ellipsoid Ellip, WMMtype_CoordSpherical CoordSpherical, int nMax, WMMtype_SphericalHarmonicVariables *SphVariables)
/* Computes Spherical variables
Variables computed are (a/r)^(n+2), cos_m(lamda) and sin_m(lambda) for spherical harmonic
summations. (Equations 10-12 in the WMM Technical Report)
INPUT Ellip data structure with the following elements
double a; semi-major axis of the ellipsoid
double b; semi-minor axis of the ellipsoid
double fla; flattening
double epssq; first eccentricity squared
double eps; first eccentricity
double re; mean radius of ellipsoid
CoordSpherical A data structure with the following elements
double lambda; ( longitude)
double phig; ( geocentric latitude )
double r; ( distance from the center of the ellipsoid)
nMax integer ( Maxumum degree of spherical harmonic secular model)\
OUTPUT SphVariables Pointer to the data structure with the following elements
double RelativeRadiusPower[WMM_MAX_MODEL_DEGREES+1]; [earth_reference_radius_km sph. radius ]^n
double cos_mlambda[WMM_MAX_MODEL_DEGREES+1]; cp(m) - cosine of (mspherical coord. longitude)
double sin_mlambda[WMM_MAX_MODEL_DEGREES+1]; sp(m) - sine of (mspherical coord. longitude)
CALLS : none
*/
{
double cos_lambda, sin_lambda;
int m, n;
cos_lambda = cos(DEG2RAD(CoordSpherical.lambda));
sin_lambda = sin(DEG2RAD(CoordSpherical.lambda));
/* for n = 0 ... model_order, compute (Radius of Earth / Spherica radius r)^(n+2)
for n 1..nMax-1 (this is much faster than calling pow MAX_N+1 times). */
SphVariables->RelativeRadiusPower[0] = (Ellip.re / CoordSpherical.r) * (Ellip.re / CoordSpherical.r);
for (n = 1; n <= nMax; n++)
{
SphVariables->RelativeRadiusPower[n] = SphVariables->RelativeRadiusPower[n-1] * (Ellip.re / CoordSpherical.r);
}
/*
Compute cos(m*lambda), sin(m*lambda) for m = 0 ... nMax
cos(a + b) = cos(a)*cos(b) - sin(a)*sin(b)
sin(a + b) = cos(a)*sin(b) + sin(a)*cos(b)
*/
SphVariables->cos_mlambda[0] = 1.0;
SphVariables->sin_mlambda[0] = 0.0;
SphVariables->cos_mlambda[1] = cos_lambda;
SphVariables->sin_mlambda[1] = sin_lambda;
for (m = 2; m <= nMax; m++)
{
SphVariables->cos_mlambda[m] = SphVariables->cos_mlambda[m-1]*cos_lambda - SphVariables->sin_mlambda[m-1]*sin_lambda;
SphVariables->sin_mlambda[m] = SphVariables->cos_mlambda[m-1]*sin_lambda + SphVariables->sin_mlambda[m-1]*cos_lambda;
}
return TRUE;
} /*WMM_ComputeSphericalHarmonicVariables*/
int WMM_DateToYear (WMMtype_Date *CalendarDate, char *Error)
/* Converts a given calendar date into a decimal year,
it also outputs an error string if there is a problem
INPUT CalendarDate Pointer to the data structure with the following elements
int Year;
int Month;
int Day;
double DecimalYear; decimal years
OUTPUT CalendarDate Pointer to the data structure with the following elements updated
double DecimalYear; decimal years
Error pointer to an error string
CALLS : none
*/
{
int temp = 0; /*Total number of days */
int MonthDays[13];
int ExtraDay = 0;
int i;
if((CalendarDate->Year%4 == 0 && CalendarDate->Year%100 != 0) || CalendarDate->Year%400 == 0)
ExtraDay = 1;
MonthDays[0] = 0;
MonthDays[1] = 31;
MonthDays[2] = 28 + ExtraDay;
MonthDays[3] = 31;
MonthDays[4] = 30;
MonthDays[5] = 31;
MonthDays[6] = 30;
MonthDays[7] = 31;
MonthDays[8] = 31;
MonthDays[9] = 30;
MonthDays[10] = 31;
MonthDays[11] = 30;
MonthDays[12] = 31;
for(i = 1; i <= CalendarDate->Month; i++)
temp+=MonthDays[i-1];
temp+=CalendarDate->Day;
CalendarDate->DecimalYear = CalendarDate->Year + (temp-1)/(365.0 + ExtraDay);
return TRUE;
} /*WMM_DateToYear*/
void WMM_DegreeToDMSstring (double DegreesOfArc, int UnitDepth, char *DMSstring)
/*This converts a given decimal degree into a DMS string.
INPUT DegreesOfArc decimal degree
UnitDepth ??
OUPUT DMSstring pointer to DMSString
CALLS : none
*/
{
int DMS[3], i;
double temp = DegreesOfArc;
char tempstring[20] = "";
char tempstring2[20] = "";
strcpy(DMSstring, "");
if(UnitDepth >= 3)
WMM_Error(21);
for(i = 0; i < UnitDepth; i++)
{
DMS[i] = (int) temp;
switch(i)
{
case 0:
strcpy(tempstring2, "Deg");
break;
case 1:
strcpy(tempstring2, "Min");
break;
case 2:
strcpy(tempstring2, "Sec");
break;
}
temp = (temp - DMS[i])*60;
if(i == UnitDepth - 1 && temp >= 30)
DMS[i]++;
sprintf(tempstring, "%4d%4s", DMS[i], tempstring2);
strcat(DMSstring, tempstring);
}
} /*WMM_DegreeToDMSstring*/
void WMM_DMSstringToDegree (char *DMSstring, double *DegreesOfArc)
/*This converts a given DMS string into decimal degrees.
INPUT DMSstring pointer to DMSString
OUTPUT DegreesOfArc decimal degree
CALLS : none
*/
{
int second, minute, degree, sign = 1, j = 0;
j = sscanf(DMSstring, "%d, %d, %d", °ree, &minute, &second);
if (j != 3)
sscanf(DMSstring, "%d %d %d", °ree, &minute, &second);
if(degree < 0)
sign = -1;
degree = degree * sign;
*DegreesOfArc = sign * (degree + minute / 60.0 + second / 3600.0);
} /*WMM_DMSstringToDegree*/
void WMM_Error(int control)
/*This prints WMM errors.
INPUT control Error look up number
OUTPUT none
CALLS : none
*/
{
switch(control)
{
case 1:
printf("\nError allocating in WMM_AllocateLegendreFunctionMemory.\n");
break;
case 2:
printf("\nError allocating in WMM_AllocateModelMemory.\n");
break;
case 3:
printf("\nError allocating in WMM_InitializeGeoid\n");
break;
case 4:
printf("\nError in setting default values.\n");
break;
case 5:
printf("\nError initializing Geoid.\n");
break;
case 6:
printf("\nError opening WMM.COF\n.");
break;
case 7:
printf("\nError opening WMMSV.COF\n.");
break;
case 8:
printf("\nError reading Magnetic Model.\n");
break;
case 9:
printf("\nError printing Command Prompt introduction.\n");
break;
case 10:
printf("\nError converting from geodetic co-ordinates to spherical co-ordinates.\n");
break;
case 11:
printf("\nError in time modifying the Magnetic model\n");
break;
case 12:
printf("\nError in Geomagnetic\n");
break;
case 13:
printf("\nError printing user data\n");\
break;
case 14:
printf("\nError allocating in WMM_SummationSpecial\n");
break;
case 15:
printf("\nError allocating in WMM_SecVarSummationSpecial\n");
break;
case 16:
printf("\nError in opening EGM9615.BIN file\n");
break;
case 17:
printf("\nError: Latitude OR Longitude out of range in WMM_GetGeoidHeight\n");
break;
case 18:
printf("\nError allocating in WMM_PcupHigh\n");
break;
case 19:
printf("\nError allocating in WMM_PcupLow\n");
break;
case 20:
printf("\nError opening coefficient file\n");
break;
case 21:
printf("\nError: UnitDepth too large\n");
break;
case 22:
printf("\nYour system needs Big endian version of EGM9615.BIN. \n");
printf("Please download this file from http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml. \n");
printf("Replace the existing EGM9615.BIN file with the downloaded one\n");
break;
}
} /*WMM_Error*/
int WMM_FreeMemory(WMMtype_MagneticModel *MagneticModel, WMMtype_MagneticModel *TimedMagneticModel, WMMtype_LegendreFunction *LegendreFunction)
/* Free memory used by WMM functions. Only to be called at the end of the main function.
INPUT : MagneticModel pointer to data structure with the following elements
double EditionDate;
double epoch; Base time of Geomagnetic model epoch (yrs)
char ModelName[20];
double *Main_Field_Coeff_G; C - Gauss coefficients of main geomagnetic model (nT)
double *Main_Field_Coeff_H; C - Gauss coefficients of main geomagnetic model (nT)
double *Secular_Var_Coeff_G; CD - Gauss coefficients of secular geomagnetic model (nT/yr)
double *Secular_Var_Coeff_H; CD - Gauss coefficients of secular geomagnetic model (nT/yr)
int nMax; Maximum degree of spherical harmonic model
int nMaxSecVar; Maxumum degree of spherical harmonic secular model
int SecularVariationUsed; Whether or not the magnetic secular variation vector will be needed by program
TimedMagneticModel Pointer to data structure similar to the first input.
LegendreFunction Pointer to data structure with the following elements
double *Pcup; ( pointer to store Legendre Function )
double *dPcup; ( pointer to store Derivative of Lagendre function )
OUTPUT none
CALLS : none
*/
{
if (MagneticModel->Main_Field_Coeff_G)
{
free(MagneticModel->Main_Field_Coeff_G);
MagneticModel->Main_Field_Coeff_G = NULL;
}
if (MagneticModel->Main_Field_Coeff_H)
{
free(MagneticModel->Main_Field_Coeff_H);
MagneticModel->Main_Field_Coeff_H = NULL;
}
if (MagneticModel->Secular_Var_Coeff_G)
{
free(MagneticModel->Secular_Var_Coeff_G);
MagneticModel->Secular_Var_Coeff_G = NULL;
}
if (MagneticModel->Secular_Var_Coeff_H)
{
free(MagneticModel->Secular_Var_Coeff_H);
MagneticModel->Secular_Var_Coeff_H = NULL;
}
if (MagneticModel)
{
free(MagneticModel);
MagneticModel = NULL;
}
if (TimedMagneticModel->Main_Field_Coeff_G)
{
free(TimedMagneticModel->Main_Field_Coeff_G);
TimedMagneticModel->Main_Field_Coeff_G = NULL;
}
if (TimedMagneticModel->Main_Field_Coeff_H)
{
free(TimedMagneticModel->Main_Field_Coeff_H);
TimedMagneticModel->Main_Field_Coeff_H = NULL;
}
if (TimedMagneticModel->Secular_Var_Coeff_G)
{
free(TimedMagneticModel->Secular_Var_Coeff_G);
TimedMagneticModel->Secular_Var_Coeff_G = NULL;
}
if (TimedMagneticModel->Secular_Var_Coeff_H)
{
free(TimedMagneticModel->Secular_Var_Coeff_H);
TimedMagneticModel->Secular_Var_Coeff_H = NULL;
}
if (TimedMagneticModel)
{
free(TimedMagneticModel);
TimedMagneticModel = NULL;
}
if(LegendreFunction->Pcup)
{
free(LegendreFunction->Pcup);
LegendreFunction->Pcup = NULL;
}
if(LegendreFunction->dPcup)
{
free(LegendreFunction->dPcup);
LegendreFunction->dPcup = NULL;
}
if(LegendreFunction)
{
free(LegendreFunction);
LegendreFunction = NULL;
}
return TRUE;
} /*WMM_FreeMemory */
int WMM_FreeMagneticModelMemory(WMMtype_MagneticModel *MagneticModel)
/* Free the magnetic model memory used by WMM functions.
INPUT : MagneticModel pointer to data structure with the following elements
double EditionDate;
double epoch; Base time of Geomagnetic model epoch (yrs)
char ModelName[20];
double *Main_Field_Coeff_G; C - Gauss coefficients of main geomagnetic model (nT)
double *Main_Field_Coeff_H; C - Gauss coefficients of main geomagnetic model (nT)
double *Secular_Var_Coeff_G; CD - Gauss coefficients of secular geomagnetic model (nT/yr)
double *Secular_Var_Coeff_H; CD - Gauss coefficients of secular geomagnetic model (nT/yr)
int nMax; Maximum degree of spherical harmonic model
int nMaxSecVar; Maxumum degree of spherical harmonic secular model
int SecularVariationUsed; Whether or not the magnetic secular variation vector will be needed by program
OUTPUT none
CALLS : none
*/
{
if (MagneticModel->Main_Field_Coeff_G)
{
free(MagneticModel->Main_Field_Coeff_G);
MagneticModel->Main_Field_Coeff_G = NULL;
}
if (MagneticModel->Main_Field_Coeff_H)
{
free(MagneticModel->Main_Field_Coeff_H);
MagneticModel->Main_Field_Coeff_H = NULL;
}
if (MagneticModel->Secular_Var_Coeff_G)
{
free(MagneticModel->Secular_Var_Coeff_G);
MagneticModel->Secular_Var_Coeff_G = NULL;
}
if (MagneticModel->Secular_Var_Coeff_H)
{
free(MagneticModel->Secular_Var_Coeff_H);
MagneticModel->Secular_Var_Coeff_H = NULL;
}
if (MagneticModel)
{
free(MagneticModel);
MagneticModel = NULL;
}
return TRUE;
} /*WMM_FreeMagneticModelMemory */
int WMM_FreeLegendreMemory(WMMtype_LegendreFunction *LegendreFunction)
/* Free the Legendre Coefficients memory used by WMM functions.
INPUT : LegendreFunction Pointer to data structure with the following elements
double *Pcup; ( pointer to store Legendre Function )
double *dPcup; ( pointer to store Derivative of Lagendre function )
OUTPUT none
CALLS : none
*/
{
if(LegendreFunction->Pcup)
{
free(LegendreFunction->Pcup);
LegendreFunction->Pcup = NULL;
}
if(LegendreFunction->dPcup)
{
free(LegendreFunction->dPcup);
LegendreFunction->dPcup = NULL;
}
if(LegendreFunction)
{
free(LegendreFunction);
LegendreFunction = NULL;
}
return TRUE;
} /*WMM_FreeLegendreMemory */
int WMM_GeodeticToSpherical(WMMtype_Ellipsoid Ellip, WMMtype_CoordGeodetic CoordGeodetic, WMMtype_CoordSpherical *CoordSpherical)
/* Converts Geodetic coordinates to Spherical coordinates
INPUT Ellip data structure with the following elements
double a; semi-major axis of the ellipsoid
double b; semi-minor axis of the ellipsoid
double fla; flattening
double epssq; first eccentricity squared
double eps; first eccentricity
double re; mean radius of ellipsoid
CoordGeodetic Pointer to the data structure with the following elements updates
double lambda; ( longitude )
double phi; ( geodetic latitude )
double HeightAboveEllipsoid; ( height above the WGS84 ellipsoid (HaE) )
double HeightAboveGeoid; (height above the EGM96 Geoid model )
OUTPUT CoordSpherical Pointer to the data structure with the following elements
double lambda; ( longitude)
double phig; ( geocentric latitude )
double r; ( distance from the center of the ellipsoid)
CALLS : none
*/
{
double CosLat, SinLat, rc, xp, zp; /*all local variables */
/*
** Convert geodetic coordinates, (defined by the WGS-84
** reference ellipsoid), to Earth Centered Earth Fixed Cartesian
** coordinates, and then to spherical coordinates.
*/
CosLat = cos(DEG2RAD(CoordGeodetic.phi));
SinLat = sin(DEG2RAD(CoordGeodetic.phi));
/* compute the local radius of curvature on the WGS-84 reference ellipsoid */
rc = Ellip.a / sqrt(1.0 - Ellip.epssq * SinLat * SinLat);
/* compute ECEF Cartesian coordinates of specified point (for longitude=0) */
xp = (rc + CoordGeodetic.HeightAboveEllipsoid) * CosLat;
zp = (rc*(1.0 - Ellip.epssq) + CoordGeodetic.HeightAboveEllipsoid) * SinLat;
/* compute spherical radius and angle lambda and phi of specified point */
CoordSpherical->r = sqrt(xp * xp + zp * zp);
CoordSpherical->phig = RAD2DEG(asin(zp / CoordSpherical->r)); /* geocentric latitude */
CoordSpherical->lambda = CoordGeodetic.lambda; /* longitude */
return TRUE;
}/*WMM_GeodeticToSpherical*/
/*Geoid Functions */
int WMM_InitializeGeoid(WMMtype_Geoid *Geoid)
/*
* The function reads Geoid data from the file EMG9615.BIN in
* the current directory and builds the Geoid grid from it.
* If the Geoid file can not be found or accessed, an error is printed
* and function returns false code. If the file is incomplete
* or improperly formatted, an error is printed
* and function returns false code.
INPUT Pointer to data structure Geoid with the following elements
int NumbGeoidCols ; ( 360 degrees of longitude at 15 minute spacing )
int NumbGeoidRows ; ( 180 degrees of latitude at 15 minute spacing )
int NumbHeaderItems ; ( min, max lat, min, max long, lat, long spacing )
int ScaleFactor; ( 4 grid cells per degree at 15 minute spacing )
float *GeoidHeightBuffer; (Pointer to the memory to store the Geoid elevation data )
int NumbGeoidElevs; (number of points in the gridded file )
int Geoid_Initialized ; ( indicates successful initialization )
OUPUT Pointer to data structure Geoid with the following elements updated
int NumbGeoidCols ; ( 360 degrees of longitude at 15 minute spacing )
int NumbGeoidRows ; ( 180 degrees of latitude at 15 minute spacing )
int NumbHeaderItems ; ( min, max lat, min, max long, lat, long spacing )
int ScaleFactor; ( 4 grid cells per degree at 15 minute spacing )
float *GeoidHeightBuffer; (Pointer to the memory to store the Geoid elevation data )
int NumbGeoidElevs; (number of points in the gridded file )
CALLS : none
*/
{
int ElevationsRead , SwabType, Index;
FILE *GeoidHeightFile;
if (Geoid->Geoid_Initialized)
{
return (TRUE);
}
else
{
Geoid->GeoidHeightBuffer = ( float *) malloc ( (Geoid->NumbGeoidElevs + 1) * sizeof(float) );
if (!Geoid->GeoidHeightBuffer){
WMM_Error(3);
// printf("error allocating in WMM_InitializeGeoid\n");
return (FALSE);
}
/* Open the File READONLY, or Return Error Condition. EMG9615.BIN is binary
dump of the ascii file WW15MGH.GRD. This file contains EGM96 Geoid heights
in 15x15 min resolution. The binary file supplied with the WMM package is
Little Endian. Now check the system to determine its Endianness*/
if (( GeoidHeightFile = fopen( "EGM9615.BIN" , "rb" ) ) == NULL)
{
WMM_Error(16);
//printf("Error in opening EGM9615.BIN file\n");
return (FALSE);
}
ElevationsRead = fread(Geoid->GeoidHeightBuffer, sizeof(float), Geoid->NumbGeoidElevs, GeoidHeightFile);
if (ElevationsRead != Geoid->NumbGeoidElevs)
{
WMM_Error(3);
//printf("Error in Geoid initilazation\n");
return ( FALSE );
}
fclose(GeoidHeightFile);
SwabType = WMM_swab_type(); /* Returns the Edianness of the system */
/* WMM_swab_type() returns
0 : Big Endian (less common)
1 : Small Endian (most common)
2 : PDP (middle) Endian - not supported by WMM Software
*/
if (SwabType == 0)
{ /* The system is Big Endian */
for (Index = 0; Index < ElevationsRead; Index ++)
/* Convert the float values from Small Endian to Big Endian */
Geoid->GeoidHeightBuffer[Index] = (float)WMM_FloatSwap(Geoid->GeoidHeightBuffer[Index]);
/* Geoid->GeoidHeightBuffer[Index] = Geoid->GeoidHeightBuffer[Index];*/
}
Geoid->Geoid_Initialized = 1;
}
return ( TRUE );
} /*WMM_InitializeGeoid*/
int WMM_GetGeoidHeight (double Latitude,
double Longitude,
double *DeltaHeight ,
WMMtype_Geoid *Geoid)
/*
* The function WMM_GetGeoidHeight returns the height of the
* EGM96 geiod above or below the WGS84 ellipsoid,
* at the specified geodetic coordinates,
* using a grid of height adjustments from the EGM96 gravity model.
*
* Latitude : Geodetic latitude in radians (input)
* Longitude : Geodetic longitude in radians (input)
* DeltaHeight : Height Adjustment, in meters. (output)
* Geoid : WMMtype_Geoid with Geoid grid (input)
CALLS : none
*/
{
long Index;
double DeltaX, DeltaY;
double ElevationSE, ElevationSW, ElevationNE, ElevationNW;
double OffsetX, OffsetY;
double PostX, PostY;
double UpperY, LowerY;
int Error_Code = 0;
if (!Geoid->Geoid_Initialized)
{
WMM_Error(5);
//printf("Geoid not initialized\n");
return (FALSE);
}
if ((Latitude < -90) || (Latitude > 90))
{ /* Latitude out of range */
Error_Code |= 1;
}
if ((Longitude < -180) || (Longitude > 360))
{ /* Longitude out of range */
Error_Code |= 1;
}
if (!Error_Code)
{ /* no errors */
/* Compute X and Y Offsets into Geoid Height Array: */
if (Longitude < 0.0)
{
OffsetX = ( Longitude + 360.0 ) *Geoid->ScaleFactor;
}
else
{
OffsetX = Longitude * Geoid->ScaleFactor;
}
OffsetY = ( 90.0 - Latitude ) * Geoid->ScaleFactor;
/* Find Four Nearest Geoid Height Cells for specified Latitude, Longitude; */
/* Assumes that (0,0) of Geoid Height Array is at Northwest corner: */
PostX = floor( OffsetX );
if ((PostX + 1) == Geoid->NumbGeoidCols)
PostX--;
PostY = floor( OffsetY );
if ((PostY + 1) == Geoid->NumbGeoidRows)
PostY--;
Index = (long)(PostY * Geoid->NumbGeoidCols + PostX);
ElevationNW = ( double ) Geoid->GeoidHeightBuffer[ Index ];
ElevationNE = ( double ) Geoid->GeoidHeightBuffer[ Index+ 1 ];
Index = (long)((PostY + 1) * Geoid->NumbGeoidCols + PostX);
ElevationSW = ( double ) Geoid->GeoidHeightBuffer[ Index ];
ElevationSE = ( double ) Geoid->GeoidHeightBuffer[ Index + 1 ];
/* Perform Bi-Linear Interpolation to compute Height above Ellipsoid: */
DeltaX = OffsetX - PostX;
DeltaY = OffsetY - PostY;
UpperY = ElevationNW + DeltaX * ( ElevationNE - ElevationNW );
LowerY = ElevationSW + DeltaX * ( ElevationSE - ElevationSW );
*DeltaHeight = UpperY + DeltaY * ( LowerY - UpperY );
}
else
{
WMM_Error(17);
//printf("Latitude OR Longitude out of range in WMM_GetGeoidHeight\n");
return (FALSE);
}
return TRUE;
} /*WMM_GetGeoidHeight*/
int WMM_ConvertGeoidToEllipsoidHeight (WMMtype_CoordGeodetic *CoordGeodetic, WMMtype_Geoid *Geoid)
/*
* The function Convert_Geoid_To_Ellipsoid_Height converts the specified WGS84
* Geoid height at the specified geodetic coordinates to the equivalent
* ellipsoid height, using the EGM96 gravity model.
*
* CoordGeodetic->phi : Geodetic latitude in degress (input)
* CoordGeodetic->lambda : Geodetic longitude in degrees (input)
* CoordGeodetic->HeightAboveEllipsoid : Ellipsoid height, in kilometers (output)
* CoordGeodetic->HeightAboveGeoid: Geoid height, in kilometers (input)
*
CALLS : WMM_GetGeoidHeight (
*/
{
double DeltaHeight;
int Error_Code;
if (Geoid->UseGeoid == 1) { /* Geoid correction required */
Error_Code = WMM_GetGeoidHeight ( CoordGeodetic->phi, CoordGeodetic->lambda, &DeltaHeight, Geoid );
CoordGeodetic->HeightAboveEllipsoid = CoordGeodetic->HeightAboveGeoid + DeltaHeight / 1000; /* Input and output should be kilometers,
However WMM_GetGeoidHeight returns Geoid height in meters - Hence division by 1000 */
}
else /* Geoid correction not required, copy the MSL height to Ellipsoid height */
{
CoordGeodetic->HeightAboveEllipsoid = CoordGeodetic->HeightAboveGeoid;
Error_Code = TRUE;
}
return ( Error_Code );
} /* WMM_ConvertGeoidToEllipsoidHeight*/
char WMM_GeomagIntroduction(WMMtype_MagneticModel *MagneticModel)
/*Prints the introduction to the Geomagnetic program. It needs the Magnetic model for the epoch.
* INPUT MagneticModel : WMMtype_MagneticModel With Model epoch (input)
OUTPUT ans (char) user selection
CALLS : none
*/
{
char help = 'h';
char ans;
printf("\n\n Welcome to the World Magnetic Model (WMM) %d C-Program\n\n", (int)MagneticModel->epoch);
printf(" --- Version 1.0, DATE Jan 28, 2010 ---\n\n");
printf("\n This program estimates the strength and direction of ");
printf("\n Earth's main Magnetic field for a given point/area.");
while(help != 'c' && help != 'C')
{
printf("\n Enter h for help and contact information or c to continue.");
printf ("\n >");
scanf("%c%*[^\n]",&help);
getchar();
if ((help == 'h') || (help == 'H'))
{
printf("\n Help information ");
printf("\n The World Magnetic Model (WMM) for %d", (int)MagneticModel->epoch);
printf("\n is a model of Earth's main Magnetic field. The WMM");
printf("\n is recomputed every five (5) years, in years divisible by ");
printf("\n five (i.e. 2005, 2010). See the contact information below");