GeographicLib  1.35
MagneticModel.cpp
Go to the documentation of this file.
1 /**
2  * \file MagneticModel.cpp
3  * \brief Implementation for GeographicLib::MagneticModel class
4  *
5  * Copyright (c) Charles Karney (2011) <charles@karney.com> and licensed under
6  * the MIT/X11 License. For more information, see
7  * http://geographiclib.sourceforge.net/
8  **********************************************************************/
9 
11 #include <fstream>
15 
16 #if !defined(GEOGRAPHICLIB_DATA)
17 # if defined(_WIN32)
18 # define GEOGRAPHICLIB_DATA \
19  "C:/Documents and Settings/All Users/Application Data/GeographicLib"
20 # else
21 # define GEOGRAPHICLIB_DATA "/usr/local/share/GeographicLib"
22 # endif
23 #endif
24 
25 #if !defined(MAGNETIC_DEFAULT_NAME)
26 # define MAGNETIC_DEFAULT_NAME "wmm2010"
27 #endif
28 
29 #if defined(_MSC_VER)
30 // Squelch warnings about unsafe use of getenv
31 # pragma warning (disable: 4996)
32 #endif
33 
34 namespace GeographicLib {
35 
36  using namespace std;
37 
38  MagneticModel::MagneticModel(const std::string& name,const std::string& path,
39  const Geocentric& earth)
40  : _name(name)
41  , _dir(path)
42  , _description("NONE")
43  , _date("UNKNOWN")
44  , _t0(Math::NaN<real>())
45  , _dt0(1)
46  , _tmin(Math::NaN<real>())
47  , _tmax(Math::NaN<real>())
48  , _a(Math::NaN<real>())
49  , _hmin(Math::NaN<real>())
50  , _hmax(Math::NaN<real>())
51  , _Nmodels(1)
52  , _norm(SphericalHarmonic::SCHMIDT)
53  , _earth(earth)
54  {
55  if (_dir.empty())
56  _dir = DefaultMagneticPath();
57  ReadMetadata(_name);
58  _G.resize(_Nmodels + 1);
59  _H.resize(_Nmodels + 1);
60  {
61  string coeff = _filename + ".cof";
62  ifstream coeffstr(coeff.c_str(), ios::binary);
63  if (!coeffstr.good())
64  throw GeographicErr("Error opening " + coeff);
65  char id[idlength_ + 1];
66  coeffstr.read(id, idlength_);
67  if (!coeffstr.good())
68  throw GeographicErr("No header in " + coeff);
69  id[idlength_] = '\0';
70  if (_id != string(id))
71  throw GeographicErr("ID mismatch: " + _id + " vs " + id);
72  for (int i = 0; i <= _Nmodels; ++i) {
73  int N, M;
74  SphericalEngine::coeff::readcoeffs(coeffstr, N, M, _G[i], _H[i]);
75  if (!(M < 0 || _G[i][0] == 0))
76  throw GeographicErr("A degree 0 term is not permitted");
77  _harm.push_back(SphericalHarmonic(_G[i], _H[i], N, N, M, _a, _norm));
78  }
79  int pos = int(coeffstr.tellg());
80  coeffstr.seekg(0, ios::end);
81  if (pos != coeffstr.tellg())
82  throw GeographicErr("Extra data in " + coeff);
83  }
84  }
85 
86  void MagneticModel::ReadMetadata(const std::string& name) {
87  const char* spaces = " \t\n\v\f\r";
88  _filename = _dir + "/" + name + ".wmm";
89  ifstream metastr(_filename.c_str());
90  if (!metastr.good())
91  throw GeographicErr("Cannot open " + _filename);
92  string line;
93  getline(metastr, line);
94  if (!(line.size() >= 6 && line.substr(0,5) == "WMMF-"))
95  throw GeographicErr(_filename + " does not contain WMMF-n signature");
96  string::size_type n = line.find_first_of(spaces, 5);
97  if (n != string::npos)
98  n -= 5;
99  string version = line.substr(5, n);
100  if (version != "1")
101  throw GeographicErr("Unknown version in " + _filename + ": " + version);
102  string key, val;
103  while (getline(metastr, line)) {
104  if (!Utility::ParseLine(line, key, val))
105  continue;
106  // Process key words
107  if (key == "Name")
108  _name = val;
109  else if (key == "Description")
110  _description = val;
111  else if (key == "ReleaseDate")
112  _date = val;
113  else if (key == "Radius")
114  _a = Utility::num<real>(val);
115  else if (key == "Type") {
116  if (!(val == "Linear" || val == "linear"))
117  throw GeographicErr("Only linear models are supported");
118  } else if (key == "Epoch")
119  _t0 = Utility::num<real>(val);
120  else if (key == "DeltaEpoch")
121  _dt0 = Utility::num<real>(val);
122  else if (key == "NumModels")
123  _Nmodels = Utility::num<int>(val);
124  else if (key == "MinTime")
125  _tmin = Utility::num<real>(val);
126  else if (key == "MaxTime")
127  _tmax = Utility::num<real>(val);
128  else if (key == "MinHeight")
129  _hmin = Utility::num<real>(val);
130  else if (key == "MaxHeight")
131  _hmax = Utility::num<real>(val);
132  else if (key == "Normalization") {
133  if (val == "FULL" || val == "Full" || val == "full")
134  _norm = SphericalHarmonic::FULL;
135  else if (val == "SCHMIDT" || val == "Schmidt" || val == "schmidt")
137  else
138  throw GeographicErr("Unknown normalization " + val);
139  } else if (key == "ByteOrder") {
140  if (val == "Big" || val == "big")
141  throw GeographicErr("Only little-endian ordering is supported");
142  else if (!(val == "Little" || val == "little"))
143  throw GeographicErr("Unknown byte ordering " + val);
144  } else if (key == "ID")
145  _id = val;
146  // else unrecognized keywords are skipped
147  }
148  // Check values
149  if (!(Math::isfinite(_a) && _a > 0))
150  throw GeographicErr("Reference radius must be positive");
151  if (!(_t0 > 0))
152  throw GeographicErr("Epoch time not defined");
153  if (_tmin >= _tmax)
154  throw GeographicErr("Min time exceeds max time");
155  if (_hmin >= _hmax)
156  throw GeographicErr("Min height exceeds max height");
157  if (int(_id.size()) != idlength_)
158  throw GeographicErr("Invalid ID");
159  if (!(_dt0 > 0)) {
160  if (_Nmodels > 1)
161  throw GeographicErr("DeltaEpoch must be positive");
162  else
163  _dt0 = 1;
164  }
165  }
166 
167  void MagneticModel::Field(real t, real lat, real lon, real h, bool diffp,
168  real& Bx, real& By, real& Bz,
169  real& Bxt, real& Byt, real& Bzt) const throw() {
170  t -= _t0;
171  int n = max(min(int(floor(t / _dt0)), _Nmodels - 1), 0);
172  bool interpolate = n + 1 < _Nmodels;
173  t -= n * _dt0;
174  real X, Y, Z;
175  real M[Geocentric::dim2_];
176  _earth.IntForward(lat, lon, h, X, Y, Z, M);
177  real BX0, BY0, BZ0, BX1, BY1, BZ1; // Components in geocentric basis
178  _harm[n](X, Y, Z, BX0, BY0, BZ0);
179  _harm[n + 1](X, Y, Z, BX1, BY1, BZ1);
180  if (interpolate) {
181  // Convert to a time derivative
182  BX1 = (BX1 - BX0) / _dt0;
183  BY1 = (BY1 - BY0) / _dt0;
184  BZ1 = (BZ1 - BZ0) / _dt0;
185  }
186  BX0 += t * BX1;
187  BY0 += t * BY1;
188  BZ0 += t * BZ1;
189  if (diffp) {
190  Geocentric::Unrotate(M, BX1, BY1, BZ1, Bxt, Byt, Bzt);
191  Bxt *= - _a;
192  Byt *= - _a;
193  Bzt *= - _a;
194  }
195  Geocentric::Unrotate(M, BX0, BY0, BZ0, Bx, By, Bz);
196  Bx *= - _a;
197  By *= - _a;
198  Bz *= - _a;
199  }
200 
201  MagneticCircle MagneticModel::Circle(real t, real lat, real h) const {
202  real t1 = t - _t0;
203  int n = max(min(int(floor(t1 / _dt0)), _Nmodels - 1), 0);
204  bool interpolate = n + 1 < _Nmodels;
205  t1 -= n * _dt0;
206  real X, Y, Z, M[Geocentric::dim2_];
207  _earth.IntForward(lat, 0, h, X, Y, Z, M);
208  // Y = 0, cphi = M[7], sphi = M[8];
209 
210  return MagneticCircle(_a, _earth._f, lat, h, t,
211  M[7], M[8], t1, _dt0, interpolate,
212  _harm[n].Circle(X, Z, true),
213  _harm[n + 1].Circle(X, Z, true));
214  }
215 
216  void MagneticModel::FieldComponents(real Bx, real By, real Bz,
217  real Bxt, real Byt, real Bzt,
218  real& H, real& F, real& D, real& I,
219  real& Ht, real& Ft,
220  real& Dt, real& It) throw() {
221  H = Math::hypot(Bx, By);
222  Ht = H ? (Bx * Bxt + By * Byt) / H : Math::hypot(Bxt, Byt);
223  D = (0 - (H ? atan2(-Bx, By) : atan2(-Bxt, Byt))) / Math::degree<real>();
224  Dt = (H ? (By * Bxt - Bx * Byt) / Math::sq(H) : 0) / Math::degree<real>();
225  F = Math::hypot(H, Bz);
226  Ft = F ? (H * Ht + Bz * Bzt) / F : Math::hypot(Ht, Bzt);
227  I = (F ? atan2(-Bz, H) : atan2(-Bzt, Ht)) / Math::degree<real>();
228  It = (F ? (Bz * Ht - H * Bzt) / Math::sq(F) : 0) / Math::degree<real>();
229  }
230 
232  string path;
233  char* magneticpath = getenv("MAGNETIC_PATH");
234  if (magneticpath)
235  path = string(magneticpath);
236  if (path.length())
237  return path;
238  char* datapath = getenv("GEOGRAPHICLIB_DATA");
239  if (datapath)
240  path = string(datapath);
241  return (path.length() ? path : string(GEOGRAPHICLIB_DATA)) + "/magnetic";
242  }
243 
245  string name;
246  char* magneticname = getenv("MAGNETIC_NAME");
247  if (magneticname)
248  name = string(magneticname);
249  return name.length() ? name : string(MAGNETIC_DEFAULT_NAME);
250  }
251 
252 } // namespace GeographicLib
GeographicLib::Math::real real
Definition: GeodSolve.cpp:40
Header for GeographicLib::Utility class.
static bool isfinite(T x)
Definition: Math.hpp:435
Header for GeographicLib::MagneticCircle class.
Mathematical functions needed by GeographicLib.
Definition: Math.hpp:73
Geomagnetic field on a circle of latitude.
MagneticCircle Circle(real t, real lat, real h) const
static void FieldComponents(real Bx, real By, real Bz, real &H, real &F, real &D, real &I)
static void readcoeffs(std::istream &stream, int &N, int &M, std::vector< real > &C, std::vector< real > &S)
Geocentric coordinates
Definition: Geocentric.hpp:61
static T hypot(T x, T y)
Definition: Math.hpp:165
static T sq(T x)
Definition: Math.hpp:153
#define GEOGRAPHICLIB_DATA
Header for GeographicLib::MagneticModel class.
static std::string DefaultMagneticName()
#define MAGNETIC_DEFAULT_NAME
Exception handling for GeographicLib.
Definition: Constants.hpp:320
static std::string DefaultMagneticPath()
Spherical harmonic series.
static bool ParseLine(const std::string &line, std::string &key, std::string &val)
Definition: Utility.cpp:16
Header for GeographicLib::SphericalEngine class.