This repository was archived by the owner on Oct 26, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathGeomagnetismLibrary.c
More file actions
2035 lines (1777 loc) · 69.6 KB
/
GeomagnetismLibrary.c
File metadata and controls
2035 lines (1777 loc) · 69.6 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 <ctype.h>
#include <assert.h>
#include "GeomagnetismLibrary.h"
/* $Id: GeomagnetismLibrary.c 1287 2014-12-09 22:55:09Z awoods $
*
* ABSTRACT
*
* The purpose of Geomagnetism Library is primarily to support the World Magnetic Model (WMM) 2015-2020.
* It however is built to be used for spherical harmonic models of the Earth's magnetic field
* generally and supports models even with a large (>>12) number of degrees. It is also used in many
* other geomagnetic models distributed by NGDC.
*
* REUSE NOTES
*
* Geomagnetism Library is intended for reuse by any application that requires
* Computation of Geomagnetic field from a spherical harmonic 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
*
* Geomagnetism library has no restrictions.
*
* ENVIRONMENT
*
* Geomagnetism library was tested in the following environments
*
* 1. Red Hat Linux with GCC Compiler
* 2. MS Windows 7 with MinGW compiler
* 3. Sun Solaris with GCC Compiler
*
*
* 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 Arnaud Chulliat
* Phone: (303) 497-4642 or -6522
* Email: geomag.models@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
* Revision Number: $Revision: 1287 $
* Last changed by: $Author: awoods $
* Last changed on: $Date: 2014-12-09 15:55:09 -0700 (Tue, 09 Dec 2014) $
*/
enum PARAMS {
SHDF,
MODELNAME,
PUBLISHER,
RELEASEDATE,
DATACUTOFF,
MODELSTARTYEAR,
MODELENDYEAR,
EPOCH,
INTSTATICDEG,
INTSECVARDEG,
EXTSTATICDEG,
EXTSECVARDEG,
GEOMAGREFRAD,
NORMALIZATION,
SPATBASFUNC
};
typedef struct {
double *Pcup; /* Legendre Function */
double *dPcup; /* Derivative of Legendre fcn */
} MAGtype_LegendreFunction;
typedef struct {
double Bx; /* North */
double By; /* East */
double Bz; /* Down */
} MAGtype_MagneticResults;
typedef struct {
/* [earth_reference_radius_km / sph. radius ]^n */
double *RelativeRadiusPower;
/*cp(m) - cosine of (m*spherical coord. longitude) */
double *cos_mlambda;
/* sp(m) - sine of (m*spherical coord. longitude) */
double *sin_mlambda;
} MAGtype_SphericalHarmonicVariables;
static char *MAG_Trim(char *str);
static int MAG_readMagneticModel_SHDF(const char *filename,
MAGtype_MagneticModel **magneticmodel);
static MAGtype_LegendreFunction *MAG_AllocateLegendreFunctionMemory(
int NumTerms);
static MAGtype_SphericalHarmonicVariables *MAG_AllocateSphVarMemory(int nMax);
static void MAG_AssignHeaderValues(MAGtype_MagneticModel *model,
char values[][MAXLINELENGTH]);
static int MAG_FreeLegendreMemory(MAGtype_LegendreFunction *LegendreFunction);
static int MAG_FreeSphVarMemory(MAGtype_SphericalHarmonicVariables *SphVar);
/*Conversions, Transformations, and other Calculations*/
static int MAG_CalculateGeoMagneticElements(MAGtype_MagneticResults *
MagneticResultsGeo, MAGtype_GeoMagneticElements * GeoMagneticElements);
static int MAG_CalculateSecularVariationElements(MAGtype_MagneticResults
MagneticVariation, MAGtype_GeoMagneticElements * MagneticElements);
static void MAG_CartesianToGeodetic(MAGtype_Ellipsoid Ellip, double x, double y,
double z, MAGtype_CoordGeodetic * CoordGeodetic);
static int MAG_RotateMagneticVector(MAGtype_CoordSpherical,
MAGtype_CoordGeodetic CoordGeodetic,
MAGtype_MagneticResults MagneticResultsSph,
MAGtype_MagneticResults * MagneticResultsGeo);
static void MAG_SphericalToCartesian(MAGtype_CoordSpherical CoordSpherical,
double *x, double *y, double *z);
/*Spherical Harmonics*/
static int MAG_AssociatedLegendreFunction(MAGtype_CoordSpherical CoordSpherical,
int nMax, MAGtype_LegendreFunction * LegendreFunction);
static int MAG_ComputeSphericalHarmonicVariables(MAGtype_Ellipsoid Ellip,
MAGtype_CoordSpherical CoordSpherical,
int nMax, MAGtype_SphericalHarmonicVariables * SphVariables);
static int MAG_PcupHigh(double *Pcup, double *dPcup, double x, int nMax);
static int MAG_PcupLow(double *Pcup, double *dPcup, double x, int nMax);
static int MAG_SecVarSummation(MAGtype_LegendreFunction * LegendreFunction,
MAGtype_MagneticModel * MagneticModel,
MAGtype_SphericalHarmonicVariables SphVariables,
MAGtype_CoordSpherical CoordSpherical,
MAGtype_MagneticResults * MagneticResults);
static int MAG_SecVarSummationSpecial(MAGtype_MagneticModel * MagneticModel,
MAGtype_SphericalHarmonicVariables SphVariables,
MAGtype_CoordSpherical CoordSpherical,
MAGtype_MagneticResults * MagneticResults);
static int MAG_Summation(MAGtype_LegendreFunction *LegendreFunction,
MAGtype_MagneticModel * MagneticModel,
MAGtype_SphericalHarmonicVariables SphVariables,
MAGtype_CoordSpherical CoordSpherical,
MAGtype_MagneticResults * MagneticResults);
static int MAG_SummationSpecial(MAGtype_MagneticModel *MagneticModel,
MAGtype_SphericalHarmonicVariables SphVariables,
MAGtype_CoordSpherical CoordSpherical,
MAGtype_MagneticResults * MagneticResults);
/******************************************************************************
************************************Wrapper***********************************
* This grouping consists of functions call groups of other functions to do a
* complete calculation of some sort. For example, the MAG_Geomag function
* does everything necessary to compute the geomagnetic elements from a given
* geodetic point in space and magnetic model adjusted for the appropriate
* date. These functions are the external functions necessary to create a
* program that uses or calculates the magnetic field.
******************************************************************************
******************************************************************************/
int
MAG_Geomag(MAGtype_Ellipsoid Ellip, MAGtype_CoordSpherical CoordSpherical,
MAGtype_CoordGeodetic CoordGeodetic,
MAGtype_MagneticModel * TimedMagneticModel,
MAGtype_GeoMagneticElements * GeoMagneticElements)
/*
The main subroutine that calls a sequence of WMM sub-functions to calculate the magnetic field elements for a single point.
The function expects the model coefficients and point coordinates as input and returns the magnetic field elements and
their rate of change. Though, this subroutine can be called successively to calculate a time series, profile or grid
of magnetic field, these are better achieved by the subroutine MAG_Grid.
INPUT: Ellip
CoordSpherical
CoordGeodetic
TimedMagneticModel
OUTPUT : GeoMagneticElements
CALLS: MAG_AllocateLegendreFunctionMemory(NumTerms); ( For storing the ALF functions )
MAG_ComputeSphericalHarmonicVariables( Ellip, CoordSpherical, TimedMagneticModel->nMax, &SphVariables); (Compute Spherical Harmonic variables )
MAG_AssociatedLegendreFunction(CoordSpherical, TimedMagneticModel->nMax, LegendreFunction); Compute ALF
MAG_Summation(LegendreFunction, TimedMagneticModel, SphVariables, CoordSpherical, &MagneticResultsSph); Accumulate the spherical harmonic coefficients
MAG_SecVarSummation(LegendreFunction, TimedMagneticModel, SphVariables, CoordSpherical, &MagneticResultsSphVar); Sum the Secular Variation Coefficients
MAG_RotateMagneticVector(CoordSpherical, CoordGeodetic, MagneticResultsSph, &MagneticResultsGeo); Map the computed Magnetic fields to Geodetic coordinates
MAG_CalculateGeoMagneticElements(&MagneticResultsGeo, GeoMagneticElements); Calculate the Geomagnetic elements
MAG_CalculateSecularVariationElements(MagneticResultsGeoVar, GeoMagneticElements); Calculate the secular variation of each of the Geomagnetic elements
*/
{
MAGtype_LegendreFunction *LegendreFunction;
MAGtype_SphericalHarmonicVariables *SphVariables;
int NumTerms;
MAGtype_MagneticResults MagneticResultsSph, MagneticResultsGeo,
MagneticResultsSphVar, MagneticResultsGeoVar;
NumTerms =
((TimedMagneticModel->nMax + 1) * (TimedMagneticModel->nMax +
2) / 2);
LegendreFunction = MAG_AllocateLegendreFunctionMemory(NumTerms); /* For storing the ALF functions */
SphVariables = MAG_AllocateSphVarMemory(TimedMagneticModel->nMax);
MAG_ComputeSphericalHarmonicVariables(Ellip, CoordSpherical, TimedMagneticModel->nMax, SphVariables); /* Compute Spherical Harmonic variables */
MAG_AssociatedLegendreFunction(CoordSpherical, TimedMagneticModel->nMax, LegendreFunction); /* Compute ALF */
MAG_Summation(LegendreFunction, TimedMagneticModel, *SphVariables, CoordSpherical, &MagneticResultsSph); /* Accumulate the spherical harmonic coefficients */
MAG_SecVarSummation(LegendreFunction, TimedMagneticModel, *SphVariables, CoordSpherical, &MagneticResultsSphVar); /*Sum the Secular Variation Coefficients */
MAG_RotateMagneticVector(CoordSpherical, CoordGeodetic, MagneticResultsSph, &MagneticResultsGeo); /* Map the computed Magnetic fields to Geodeitic coordinates */
MAG_RotateMagneticVector(CoordSpherical, CoordGeodetic, MagneticResultsSphVar, &MagneticResultsGeoVar); /* Map the secular variation field components to Geodetic coordinates */
MAG_CalculateGeoMagneticElements(&MagneticResultsGeo, GeoMagneticElements); /* Calculate the Geomagnetic elements, Equation 19 , WMM Technical report */
MAG_CalculateSecularVariationElements(MagneticResultsGeoVar, GeoMagneticElements); /*Calculate the secular variation of each of the Geomagnetic elements */
MAG_FreeLegendreMemory(LegendreFunction);
MAG_FreeSphVarMemory(SphVariables);
return (TRUE);
} /*MAG_Geomag */
int
MAG_robustReadMagModels(const char *filename,
MAGtype_MagneticModel **magneticmodel)
{
char line[MAXLINELENGTH];
int n, nMax = 0, num_terms, a;
FILE *MODELFILE;
MODELFILE = fopen(filename, "r");
if (MODELFILE == 0) {
return (0);
}
fgets(line, MAXLINELENGTH, MODELFILE);
if (line[0] == '%')
MAG_readMagneticModel_SHDF(filename, magneticmodel);
else {
do {
if (NULL == fgets(line, MAXLINELENGTH, MODELFILE))
break;
a = sscanf(line, "%d", &n);
if (n > nMax && (n < 99999 && a == 1 && n > 0))
nMax = n;
} while (n < 99999 && a == 1);
num_terms = CALCULATE_NUMTERMS(nMax);
(*magneticmodel) = MAG_AllocateModelMemory(num_terms);
(*magneticmodel)->nMax = nMax;
(*magneticmodel)->nMaxSecVar = nMax;
MAG_readMagneticModel(filename, *magneticmodel);
(*magneticmodel)->CoefficientFileEndDate =
(*magneticmodel)->epoch + 5;
}
fclose(MODELFILE);
return (1);
} /*MAG_robustReadMagModels */
/*End of Wrapper Functions*/
/******************************************************************************
********************************User Interface********************************
* This grouping consists of functions which interact with the directly with
* the user and are generally specific to the XXX_point.c, XXX_grid.c, and
* XXX_file.c programs. They deal with input from and output to the user.
******************************************************************************/
void
MAG_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 MAG_LegendreFunctionMemory.\n");
break;
case 2:
printf("\nError allocating in MAG_AllocateModelMemory.\n");
break;
case 3:
printf("\nError allocating in MAG_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 MAG_SummationSpecial\n");
break;
case 15:
printf("\nError allocating in MAG_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 MAG_GetGeoidHeight\n");
break;
case 18:
printf("\nError allocating in MAG_PcupHigh\n");
break;
case 19:
printf("\nError allocating in MAG_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;
}
} /*MAG_Error */
/*End of User Interface functions*/
/******************************************************************************
********************************Memory and File Processing********************
* This grouping consists of functions that read coefficient files into the
* memory, allocate memory, free memory or print models into coefficient files.
******************************************************************************/
MAGtype_LegendreFunction *
MAG_AllocateLegendreFunctionMemory(int NumTerms)
/* Allocate memory for Associated Legendre Function data types.
Should be called before computing Associated Legendre Functions.
INPUT: NumTerms : int : Total number of spherical harmonic coefficients in the model
OUTPUT: Pointer to data structure MAGtype_LegendreFunction with the following elements
double *Pcup; ( pointer to store Legendre Function )
double *dPcup; ( pointer to store Derivative of Legendre function )
FALSE: Failed to allocate memory
CALLS : none
*/
{
MAGtype_LegendreFunction *LegendreFunction;
LegendreFunction =
(MAGtype_LegendreFunction *) calloc(1,
sizeof (MAGtype_LegendreFunction));
if (!LegendreFunction) {
MAG_Error(1);
return (NULL);
}
LegendreFunction->Pcup =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (LegendreFunction->Pcup == 0) {
MAG_Error(1);
return (NULL);
}
LegendreFunction->dPcup =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (LegendreFunction->dPcup == 0) {
MAG_Error(1);
return (NULL);
}
return (LegendreFunction);
} /*MAGtype_LegendreFunction */
MAGtype_MagneticModel *
MAG_AllocateModelMemory(int NumTerms)
/* Allocate memory for WMM Coefficients
* Should be called before reading the model file *
INPUT: NumTerms : int : Total number of spherical harmonic coefficients in the model
OUTPUT: Pointer to data structure MAGtype_MagneticModel 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
FALSE: Failed to allocate memory
CALLS : none
*/
{
MAGtype_MagneticModel *MagneticModel;
int i;
MagneticModel =
(MAGtype_MagneticModel *) calloc(1, sizeof (MAGtype_MagneticModel));
if (MagneticModel == NULL) {
MAG_Error(2);
return (NULL);
}
MagneticModel->Main_Field_Coeff_G =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (MagneticModel->Main_Field_Coeff_G == NULL) {
MAG_Error(2);
return (NULL);
}
MagneticModel->Main_Field_Coeff_H =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (MagneticModel->Main_Field_Coeff_H == NULL) {
MAG_Error(2);
return (NULL);
}
MagneticModel->Secular_Var_Coeff_G =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (MagneticModel->Secular_Var_Coeff_G == NULL) {
MAG_Error(2);
return (NULL);
}
MagneticModel->Secular_Var_Coeff_H =
(double *)malloc((NumTerms + 1) * sizeof (double));
if (MagneticModel->Secular_Var_Coeff_H == NULL) {
MAG_Error(2);
return (NULL);
}
MagneticModel->CoefficientFileEndDate = 0;
MagneticModel->EditionDate = 0;
strcpy(MagneticModel->ModelName, "");
MagneticModel->SecularVariationUsed = 0;
MagneticModel->epoch = 0;
MagneticModel->nMax = 0;
MagneticModel->nMaxSecVar = 0;
for (i = 0; i < NumTerms; i++) {
MagneticModel->Main_Field_Coeff_G[i] = 0;
MagneticModel->Main_Field_Coeff_H[i] = 0;
MagneticModel->Secular_Var_Coeff_G[i] = 0;
MagneticModel->Secular_Var_Coeff_H[i] = 0;
}
return (MagneticModel);
} /*MAG_AllocateModelMemory */
MAGtype_SphericalHarmonicVariables *
MAG_AllocateSphVarMemory(int nMax)
{
MAGtype_SphericalHarmonicVariables *SphVariables;
SphVariables =
(MAGtype_SphericalHarmonicVariables *) calloc(1,
sizeof (MAGtype_SphericalHarmonicVariables));
SphVariables->RelativeRadiusPower =
(double *)malloc((nMax + 1) * sizeof (double));
SphVariables->cos_mlambda =
(double *)malloc((nMax + 1) * sizeof (double));
SphVariables->sin_mlambda =
(double *)malloc((nMax + 1) * sizeof (double));
return (SphVariables);
} /*MAG_AllocateSphVarMemory */
void
MAG_AssignHeaderValues(MAGtype_MagneticModel * model,
char values[][MAXLINELENGTH])
{
/* MAGtype_Date releasedate; */
strcpy(model->ModelName, values[MODELNAME]);
/* releasedate.Year = 0;
releasedate.Day = 0;
releasedate.Month = 0;
releasedate.DecimalYear = 0;
sscanf(values[RELEASEDATE],"%d-%d-%d",&releasedate.Year,&releasedate.Month,&releasedate.Day);
if(MAG_DateToYear (&releasedate, NULL))
model->EditionDate = releasedate.DecimalYear; */
model->epoch = atof(values[MODELSTARTYEAR]);
model->nMax = atoi(values[INTSTATICDEG]);
model->nMaxSecVar = atoi(values[INTSECVARDEG]);
model->CoefficientFileEndDate = atof(values[MODELENDYEAR]);
if (model->nMaxSecVar > 0)
model->SecularVariationUsed = 1;
else
model->SecularVariationUsed = 0;
}
int
MAG_FreeMagneticModelMemory(MAGtype_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);
} /*MAG_FreeMagneticModelMemory */
int
MAG_FreeLegendreMemory(MAGtype_LegendreFunction * LegendreFunction)
/* Free the Legendre Coefficients memory used by the 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);
} /*MAG_FreeLegendreMemory */
int
MAG_FreeSphVarMemory(MAGtype_SphericalHarmonicVariables * SphVar)
/* Free the Spherical Harmonic Variable memory used by the WMM functions.
INPUT : LegendreFunction Pointer to data structure with the following elements
double *RelativeRadiusPower
double *cos_mlambda
double *sin_mlambda
OUTPUT: none
CALLS : none
*/
{
if (SphVar->RelativeRadiusPower) {
free(SphVar->RelativeRadiusPower);
SphVar->RelativeRadiusPower = NULL;
}
if (SphVar->cos_mlambda) {
free(SphVar->cos_mlambda);
SphVar->cos_mlambda = NULL;
}
if (SphVar->sin_mlambda) {
free(SphVar->sin_mlambda);
SphVar->sin_mlambda = NULL;
}
if (SphVar) {
free(SphVar);
SphVar = NULL;
}
return (TRUE);
} /*MAG_FreeSphVarMemory */
int
MAG_readMagneticModel(const char *filename, MAGtype_MagneticModel * MagneticModel)
{
/* READ WORLD Magnetic MODEL SPHERICAL HARMONIC COEFFICIENTS (WMM.cof)
INPUT : filename
MagneticModel : Pointer to the data structure with the following fields required as inputs
nMax : Number of static coefficients
UPDATES : MagneticModel : Pointer to the data structure with the following fields populated
char *ModelName;
double epoch; Base time of Geomagnetic model epoch (yrs)
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)
CALLS : none
*/
FILE *MAG_COF_File;
char c_str[81], c_new[5]; /*these strings are used to read a line from coefficient file */
int i, icomp, m, n, EOF_Flag = 0, index;
double epoch, gnm, hnm, dgnm, dhnm;
MAG_COF_File = fopen(filename, "r");
if (MAG_COF_File == NULL) {
MAG_Error(20);
return (FALSE);
/* should we have a standard error printing routine ? */
}
MagneticModel->Main_Field_Coeff_H[0] = 0.0;
MagneticModel->Main_Field_Coeff_G[0] = 0.0;
MagneticModel->Secular_Var_Coeff_H[0] = 0.0;
MagneticModel->Secular_Var_Coeff_G[0] = 0.0;
fgets(c_str, 80, MAG_COF_File);
sscanf(c_str, "%lf%s", &epoch, MagneticModel->ModelName);
MagneticModel->epoch = epoch;
while (EOF_Flag == 0) {
fgets(c_str, 80, MAG_COF_File);
/* CHECK FOR LAST LINE IN FILE */
for (i = 0; i < 4 && (c_str[i] != '\0'); i++) {
c_new[i] = c_str[i];
c_new[i + 1] = '\0';
}
icomp = strcmp("9999", c_new);
if (icomp == 0) {
EOF_Flag = 1;
break;
}
/* END OF FILE NOT ENCOUNTERED, GET VALUES */
sscanf(c_str, "%d%d%lf%lf%lf%lf", &n, &m, &gnm, &hnm, &dgnm,
&dhnm);
if (m <= n) {
index = (n * (n + 1) / 2 + m);
MagneticModel->Main_Field_Coeff_G[index] = gnm;
MagneticModel->Secular_Var_Coeff_G[index] = dgnm;
MagneticModel->Main_Field_Coeff_H[index] = hnm;
MagneticModel->Secular_Var_Coeff_H[index] = dhnm;
}
}
fclose(MAG_COF_File);
return (TRUE);
} /*MAG_readMagneticModel */
int
MAG_readMagneticModel_Large(const char *filename, const char *filenameSV,
MAGtype_MagneticModel * MagneticModel)
/* To read the high-degree model coefficients (for example, NGDC 720)
INPUT : filename file name for static coefficients
filenameSV file name for secular variation coefficients
MagneticModel : Pointer to the data structure with the following fields required as inputs
nMaxSecVar : Number of secular variation coefficients
nMax : Number of static coefficients
UPDATES : MagneticModel : Pointer to the data structure with the following fields populated
double epoch; Base time of Geomagnetic model epoch (yrs)
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)
CALLS : none
*/
{
FILE *MAG_COF_File;
FILE *MAG_COFSV_File;
char c_str[81], c_str2[81]; /* these strings are used to read a line from coefficient file */
int i, m, n, index, a, b;
double epoch, gnm, hnm, dgnm, dhnm;
MAG_COF_File = fopen(filename, "r");
MAG_COFSV_File = fopen(filenameSV, "r");
if (MAG_COF_File == NULL || MAG_COFSV_File == NULL) {
MAG_Error(20);
return (FALSE);
}
MagneticModel->Main_Field_Coeff_H[0] = 0.0;
MagneticModel->Main_Field_Coeff_G[0] = 0.0;
MagneticModel->Secular_Var_Coeff_H[0] = 0.0;
MagneticModel->Secular_Var_Coeff_G[0] = 0.0;
fgets(c_str, 80, MAG_COF_File);
sscanf(c_str, "%lf%s", &epoch, MagneticModel->ModelName);
MagneticModel->epoch = epoch;
a = CALCULATE_NUMTERMS(MagneticModel->nMaxSecVar);
b = CALCULATE_NUMTERMS(MagneticModel->nMax);
for (i = 0; i < a; i++) {
fgets(c_str, 80, MAG_COF_File);
sscanf(c_str, "%d%d%lf%lf", &n, &m, &gnm, &hnm);
fgets(c_str2, 80, MAG_COFSV_File);
sscanf(c_str2, "%d%d%lf%lf", &n, &m, &dgnm, &dhnm);
if (m <= n) {
index = (n * (n + 1) / 2 + m);
MagneticModel->Main_Field_Coeff_G[index] = gnm;
MagneticModel->Secular_Var_Coeff_G[index] = dgnm;
MagneticModel->Main_Field_Coeff_H[index] = hnm;
MagneticModel->Secular_Var_Coeff_H[index] = dhnm;
}
}
for (i = a; i < b; i++) {
fgets(c_str, 80, MAG_COF_File);
sscanf(c_str, "%d%d%lf%lf", &n, &m, &gnm, &hnm);
if (m <= n) {
index = (n * (n + 1) / 2 + m);
MagneticModel->Main_Field_Coeff_G[index] = gnm;
MagneticModel->Main_Field_Coeff_H[index] = hnm;
}
}
if (MAG_COF_File != NULL && MAG_COFSV_File != NULL) {
fclose(MAG_COF_File);
fclose(MAG_COFSV_File);
}
return (TRUE);
} /*MAG_readMagneticModel_Large */
static int
MAG_readMagneticModel_SHDF(const char *filename,
MAGtype_MagneticModel **magneticmodel)
/*
* MAG_readMagneticModels - Read the Magnetic Models from an SHDF format file
*
* Input:
* filename - Path to the SHDF format model file to be read
*
* Output:
* magneticmodel - magnetic model read from the file
*
* Return value:
* Returns the number of models read from the file.
* -2 implies that internal or external static degree was not found in the file, hence memory cannot be allocated
* -1 implies some error during file processing (I/O)
* 0 implies no models were read from the file
* if ReturnValue > array_size then there were too many models in model file but only <array_size> number were read .
* if ReturnValue <= array_size then the function execution was successful.
*/
{
char paramkeys[NOOFPARAMS][MAXLINELENGTH] = {
"SHDF ",
"ModelName: ",
"Publisher: ",
"ReleaseDate: ",
"DataCutOff: ",
"ModelStartYear: ",
"ModelEndYear: ",
"Epoch: ",
"IntStaticDeg: ",
"IntSecVarDeg: ",
"ExtStaticDeg: ",
"ExtSecVarDeg: ",
"GeoMagRefRad: ",
"Normalization: ",
"SpatBasFunc: "
};
char paramvalues[NOOFPARAMS][MAXLINELENGTH];
char *line = (char *)malloc(MAXLINELENGTH);
char *ptrreset;
char paramvalue[MAXLINELENGTH];
int paramvaluelength = 0;
int paramkeylength = 0;
int i = 0, j = 0;
int newrecord = 1;
int header_index = -1;
int numterms;
int tempint;
int allocationflag = 0;
char coefftype; /* Internal or External (I/E) */
/* For reading coefficients */
int n, m;
double gnm, hnm, dgnm, dhnm;
int index;
FILE *stream;
ptrreset = line;
stream = fopen(filename, READONLYMODE);
if (stream == NULL) {
perror("File open error");
return (header_index);
}
/* Read records from the model file and store header information. */
while (fgets(line, MAXLINELENGTH, stream) != NULL) {
j++;
if (strlen(MAG_Trim(line)) == 0)
continue;
if (*line == '%') {
line++;
if (newrecord) {
if (header_index > -1) {
MAG_AssignHeaderValues(*magneticmodel,
paramvalues);
}
header_index++;
if (header_index >= 1) {
fprintf(stderr,
"Header limit exceeded - too many models in model file. (%d)\n",
header_index);
return (-1);
}
newrecord = 0;
allocationflag = 0;
}
for (i = 0; i < NOOFPARAMS; i++) {
paramkeylength = strlen(paramkeys[i]);
if (!strncmp(line, paramkeys[i],
paramkeylength)) {
paramvaluelength =
strlen(line) - paramkeylength;
strncpy(paramvalue,
line + paramkeylength,
paramvaluelength);
paramvalue[paramvaluelength] = '\0';
strcpy(paramvalues[i], paramvalue);
if (!strcmp(paramkeys[i],
paramkeys[INTSTATICDEG]) ||
!strcmp(paramkeys[i],
paramkeys[EXTSTATICDEG])) {
tempint = atoi(paramvalues[i]);
if (tempint > 0 &&
allocationflag == 0) {
numterms =
CALCULATE_NUMTERMS
(tempint);
(*magneticmodel) =
MAG_AllocateModelMemory
(numterms);
allocationflag = 1;
}
}
break;
}
}
line--;
} else if (*line == '#') {
/* process comments */
} else if (sscanf(line, "%c,%d,%d", &coefftype, &n, &m) == 3) {
if (m == 0) {
sscanf(line, "%c,%d,%d,%lf,,%lf,", &coefftype,
&n, &m, &gnm, &dgnm);
hnm = 0;
dhnm = 0;
} else
sscanf(line, "%c,%d,%d,%lf,%lf,%lf,%lf",
&coefftype, &n, &m, &gnm, &hnm, &dgnm,
&dhnm);
newrecord = 1;
if (!allocationflag) {
fprintf(stderr,
"Degree not found in model. Memory cannot be allocated.\n");
return (_DEGREE_NOT_FOUND);
}
if (m <= n) {
index = (n * (n + 1) / 2 + m);
(*magneticmodel)->Main_Field_Coeff_G[index] =
gnm;
(*magneticmodel)->Secular_Var_Coeff_G[index] =
dgnm;
(*magneticmodel)->Main_Field_Coeff_H[index] =
hnm;
(*magneticmodel)->Secular_Var_Coeff_H[index] =
dhnm;
}
}
}
if (header_index > -1)
MAG_AssignHeaderValues(*magneticmodel, paramvalues);
fclose(stream);
free(ptrreset);
line = NULL;
ptrreset = NULL;
return (header_index + 1);
} /*MAG_readMagneticModel_SHDF */
static char *
MAG_Trim(char *str)
{
char *end;
while (isspace(*str))
str++;
if (*str == 0)
return (str);
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
*(end + 1) = 0;
return (str);
}
/*End of Memory and File Processing functions*/
/******************************************************************************
*************Conversions, Transformations, and other Calculations**************
* This grouping consists of functions that perform unit conversions, coordinate
* transformations and other simple or straightforward calculations that are
* usually easily replicable with a typical scientific calculator.
******************************************************************************/
int
MAG_CalculateGeoMagneticElements(MAGtype_MagneticResults * MagneticResultsGeo,
MAGtype_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