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