GeographicLib  1.40
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
GravityModel.cpp
Go to the documentation of this file.
1 /**
2  * \file GravityModel.cpp
3  * \brief Implementation for GeographicLib::GravityModel class
4  *
5  * Copyright (c) Charles Karney (2011-2012) <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_GRAVITY_DEFAULT_NAME)
25 # define GEOGRAPHICLIB_GRAVITY_DEFAULT_NAME "egm96"
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  GravityModel::GravityModel(const std::string& name,const std::string& path)
38  : _name(name)
39  , _dir(path)
40  , _description("NONE")
41  , _date("UNKNOWN")
42  , _amodel(Math::NaN())
43  , _GMmodel(Math::NaN())
44  , _zeta0(0)
45  , _corrmult(1)
46  , _norm(SphericalHarmonic::FULL)
47  {
48  if (_dir.empty())
49  _dir = DefaultGravityPath();
50  ReadMetadata(_name);
51  {
52  string coeff = _filename + ".cof";
53  ifstream coeffstr(coeff.c_str(), ios::binary);
54  if (!coeffstr.good())
55  throw GeographicErr("Error opening " + coeff);
56  char id[idlength_ + 1];
57  coeffstr.read(id, idlength_);
58  if (!coeffstr.good())
59  throw GeographicErr("No header in " + coeff);
60  id[idlength_] = '\0';
61  if (_id != string(id))
62  throw GeographicErr("ID mismatch: " + _id + " vs " + id);
63  int N, M;
64  SphericalEngine::coeff::readcoeffs(coeffstr, N, M, _Cx, _Sx);
65  if (!(M < 0 || _Cx[0] == 0))
66  throw GeographicErr("A degree 0 term should be zero");
67  _Cx[0] = 1; // Include the 1/r term in the sum
68  _gravitational = SphericalHarmonic(_Cx, _Sx, N, N, M, _amodel, _norm);
69  SphericalEngine::coeff::readcoeffs(coeffstr, N, M, _CC, _CS);
70  if (N < 0) {
71  N = M = 0;
72  _CC.resize(1, real(0));
73  }
74  _CC[0] += _zeta0 / _corrmult;
75  _correction = SphericalHarmonic(_CC, _CS, N, N, M, real(1), _norm);
76  int pos = int(coeffstr.tellg());
77  coeffstr.seekg(0, ios::end);
78  if (pos != coeffstr.tellg())
79  throw GeographicErr("Extra data in " + coeff);
80  }
81  int nmx = _gravitational.Coefficients().nmx();
82  // Adjust the normalization of the normal potential to match the model.
83  real mult = _earth._GM / _GMmodel;
84  real amult = Math::sq(_earth._a / _amodel);
85  // The 0th term in _zonal should be is 1 + _dzonal0. Instead set it to 1
86  // to give exact cancellation with the (0,0) term in the model and account
87  // for _dzonal0 separately.
88  _zonal.clear(); _zonal.push_back(1);
89  _dzonal0 = (_earth.MassConstant() - _GMmodel) / _GMmodel;
90  for (int n = 2; n <= nmx; n += 2) {
91  // Only include as many normal zonal terms as matter. Figuring the limit
92  // in this way works because the coefficients of the normal potential
93  // (which is smooth) decay much more rapidly that the corresponding
94  // coefficient of the model potential (which is bumpy). Typically this
95  // goes out to n = 18.
96  mult *= amult;
97  real
98  r = _Cx[n], // the model term
99  s = - mult * _earth.Jn(n) / sqrt(real(2 * n + 1)), // the normal term
100  t = r - s; // the difference
101  if (t == r) // the normal term is negligible
102  break;
103  _zonal.push_back(0); // index = n - 1; the odd terms are 0
104  _zonal.push_back(s);
105  }
106  int nmx1 = int(_zonal.size()) - 1;
107  _disturbing = SphericalHarmonic1(_Cx, _Sx,
108  _gravitational.Coefficients().N(),
109  nmx, _gravitational.Coefficients().mmx(),
110  _zonal,
111  _zonal, // This is not accessed!
112  nmx1, nmx1, 0,
113  _amodel,
115  }
116 
117  void GravityModel::ReadMetadata(const std::string& name) {
118  const char* spaces = " \t\n\v\f\r";
119  _filename = _dir + "/" + name + ".egm";
120  ifstream metastr(_filename.c_str());
121  if (!metastr.good())
122  throw GeographicErr("Cannot open " + _filename);
123  string line;
124  getline(metastr, line);
125  if (!(line.size() >= 6 && line.substr(0,5) == "EGMF-"))
126  throw GeographicErr(_filename + " does not contain EGMF-n signature");
127  string::size_type n = line.find_first_of(spaces, 5);
128  if (n != string::npos)
129  n -= 5;
130  string version = line.substr(5, n);
131  if (version != "1")
132  throw GeographicErr("Unknown version in " + _filename + ": " + version);
133  string key, val;
134  real a = Math::NaN(), GM = a, omega = a, f = a, J2 = a;
135  while (getline(metastr, line)) {
136  if (!Utility::ParseLine(line, key, val))
137  continue;
138  // Process key words
139  if (key == "Name")
140  _name = val;
141  else if (key == "Description")
142  _description = val;
143  else if (key == "ReleaseDate")
144  _date = val;
145  else if (key == "ModelRadius")
146  _amodel = Utility::num<real>(val);
147  else if (key == "ModelMass")
148  _GMmodel = Utility::num<real>(val);
149  else if (key == "AngularVelocity")
150  omega = Utility::num<real>(val);
151  else if (key == "ReferenceRadius")
152  a = Utility::num<real>(val);
153  else if (key == "ReferenceMass")
154  GM = Utility::num<real>(val);
155  else if (key == "Flattening")
156  f = Utility::fract<real>(val);
157  else if (key == "DynamicalFormFactor")
158  J2 = Utility::fract<real>(val);
159  else if (key == "HeightOffset")
160  _zeta0 = Utility::fract<real>(val);
161  else if (key == "CorrectionMultiplier")
162  _corrmult = Utility::fract<real>(val);
163  else if (key == "Normalization") {
164  if (val == "FULL" || val == "Full" || val == "full")
165  _norm = SphericalHarmonic::FULL;
166  else if (val == "SCHMIDT" || val == "Schmidt" || val == "schmidt")
168  else
169  throw GeographicErr("Unknown normalization " + val);
170  } else if (key == "ByteOrder") {
171  if (val == "Big" || val == "big")
172  throw GeographicErr("Only little-endian ordering is supported");
173  else if (!(val == "Little" || val == "little"))
174  throw GeographicErr("Unknown byte ordering " + val);
175  } else if (key == "ID")
176  _id = val;
177  // else unrecognized keywords are skipped
178  }
179  // Check values
180  if (!(Math::isfinite(_amodel) && _amodel > 0))
181  throw GeographicErr("Model radius must be positive");
182  if (!(Math::isfinite(_GMmodel) && _GMmodel > 0))
183  throw GeographicErr("Model mass constant must be positive");
184  if (!(Math::isfinite(_corrmult) && _corrmult > 0))
185  throw GeographicErr("Correction multiplier must be positive");
186  if (!(Math::isfinite(_zeta0)))
187  throw GeographicErr("Height offset must be finite");
188  if (int(_id.size()) != idlength_)
189  throw GeographicErr("Invalid ID");
190  _earth = NormalGravity(a, GM, omega, f, J2);
191  }
192 
193  Math::real GravityModel::InternalT(real X, real Y, real Z,
194  real& deltaX, real& deltaY, real& deltaZ,
195  bool gradp, bool correct) const {
196  // If correct, then produce the correct T = W - U. Otherwise, neglect the
197  // n = 0 term (which is proportial to the difference in the model and
198  // reference values of GM).
199  if (_dzonal0 == 0)
200  // No need to do the correction
201  correct = false;
202  real T, invR = correct ? 1 / Math::hypot(Math::hypot(X, Y), Z) : 1;
203  if (gradp) {
204  // initial values to suppress warnings
205  deltaX = deltaY = deltaZ = 0;
206  T = _disturbing(-1, X, Y, Z, deltaX, deltaY, deltaZ);
207  real f = _GMmodel / _amodel;
208  deltaX *= f;
209  deltaY *= f;
210  deltaZ *= f;
211  if (correct) {
212  invR = _GMmodel * _dzonal0 * invR * invR * invR;
213  deltaX += X * invR;
214  deltaY += Y * invR;
215  deltaZ += Z * invR;
216  }
217  } else
218  T = _disturbing(-1, X, Y, Z);
219  T = (T / _amodel - (correct ? _dzonal0 : 0) * invR) * _GMmodel;
220  return T;
221  }
222 
223  Math::real GravityModel::V(real X, real Y, real Z,
224  real& GX, real& GY, real& GZ) const {
225  real
226  Vres = _gravitational(X, Y, Z, GX, GY, GZ),
227  f = _GMmodel / _amodel;
228  Vres *= f;
229  GX *= f;
230  GY *= f;
231  GZ *= f;
232  return Vres;
233  }
234 
235  Math::real GravityModel::W(real X, real Y, real Z,
236  real& gX, real& gY, real& gZ) const {
237  real fX, fY,
238  Wres = V(X, Y, Z, gX, gY, gZ) + _earth.Phi(X, Y, fX, fY);
239  gX += fX;
240  gY += fY;
241  return Wres;
242  }
243 
244  void GravityModel::SphericalAnomaly(real lat, real lon, real h,
245  real& Dg01, real& xi, real& eta)
246  const {
247  real X, Y, Z, M[Geocentric::dim2_];
248  _earth.Earth().IntForward(lat, lon, h, X, Y, Z, M);
249  real
250  deltax, deltay, deltaz,
251  T = InternalT(X, Y, Z, deltax, deltay, deltaz, true, false),
252  clam = M[3], slam = -M[0],
253  P = Math::hypot(X, Y),
254  R = Math::hypot(P, Z),
255  // psi is geocentric latitude
256  cpsi = R ? P / R : M[7],
257  spsi = R ? Z / R : M[8];
258  // Rotate cartesian into spherical coordinates
259  real MC[Geocentric::dim2_];
260  Geocentric::Rotation(spsi, cpsi, slam, clam, MC);
261  Geocentric::Unrotate(MC, deltax, deltay, deltaz, deltax, deltay, deltaz);
262  // H+M, Eq 2-151c
263  Dg01 = - deltaz - 2 * T / R;
264  real gammaX, gammaY, gammaZ;
265  _earth.U(X, Y, Z, gammaX, gammaY, gammaZ);
266  real gamma = Math::hypot( Math::hypot(gammaX, gammaY), gammaZ);
267  xi = -(deltay/gamma) / Math::degree();
268  eta = -(deltax/gamma) / Math::degree();
269  }
270 
271  Math::real GravityModel::GeoidHeight(real lat, real lon) const
272  {
273  real X, Y, Z;
274  _earth.Earth().IntForward(lat, lon, 0, X, Y, Z, NULL);
275  real
276  gamma0 = _earth.SurfaceGravity(lat),
277  dummy,
278  T = InternalT(X, Y, Z, dummy, dummy, dummy, false, false),
279  invR = 1 / Math::hypot(Math::hypot(X, Y), Z),
280  correction = _corrmult * _correction(invR * X, invR * Y, invR * Z);
281  // _zeta0 has been included in _correction
282  return T/gamma0 + correction;
283  }
284 
285  Math::real GravityModel::Gravity(real lat, real lon, real h,
286  real& gx, real& gy, real& gz) const {
287  real X, Y, Z, M[Geocentric::dim2_];
288  _earth.Earth().IntForward(lat, lon, h, X, Y, Z, M);
289  real Wres = W(X, Y, Z, gx, gy, gz);
290  Geocentric::Unrotate(M, gx, gy, gz, gx, gy, gz);
291  return Wres;
292  }
293  Math::real GravityModel::Disturbance(real lat, real lon, real h,
294  real& deltax, real& deltay, real& deltaz)
295  const {
296  real X, Y, Z, M[Geocentric::dim2_];
297  _earth.Earth().IntForward(lat, lon, h, X, Y, Z, M);
298  real Tres = InternalT(X, Y, Z, deltax, deltay, deltaz, true, true);
299  Geocentric::Unrotate(M, deltax, deltay, deltaz, deltax, deltay, deltaz);
300  return Tres;
301  }
302 
303  GravityCircle GravityModel::Circle(real lat, real h, unsigned caps) const {
304  if (h != 0)
305  // Disallow invoking GeoidHeight unless h is zero.
306  caps &= ~(CAP_GAMMA0 | CAP_C);
307  real X, Y, Z, M[Geocentric::dim2_];
308  _earth.Earth().IntForward(lat, 0, h, X, Y, Z, M);
309  // Y = 0, cphi = M[7], sphi = M[8];
310  real
311  invR = 1 / Math::hypot(X, Z),
312  gamma0 = (caps & CAP_GAMMA0 ?_earth.SurfaceGravity(lat)
313  : Math::NaN()),
314  fx, fy, fz, gamma;
315  if (caps & CAP_GAMMA) {
316  _earth.U(X, Y, Z, fx, fy, fz); // fy = 0
317  gamma = Math::hypot(fx, fz);
318  } else
319  gamma = Math::NaN();
320  _earth.Phi(X, Y, fx, fy);
321  return GravityCircle(GravityCircle::mask(caps),
322  _earth._a, _earth._f, lat, h, Z, X, M[7], M[8],
323  _amodel, _GMmodel, _dzonal0, _corrmult,
324  gamma0, gamma, fx,
325  caps & CAP_G ?
326  _gravitational.Circle(X, Z, true) :
327  CircularEngine(),
328  // N.B. If CAP_DELTA is set then CAP_T should be too.
329  caps & CAP_T ?
330  _disturbing.Circle(-1, X, Z, (caps & CAP_DELTA) != 0) :
331  CircularEngine(),
332  caps & CAP_C ?
333  _correction.Circle(invR * X, invR * Z, false) :
334  CircularEngine());
335  }
336 
338  string path;
339  char* gravitypath = getenv("GEOGRAPHICLIB_GRAVITY_PATH");
340  if (gravitypath)
341  path = string(gravitypath);
342  if (!path.empty())
343  return path;
344  char* datapath = getenv("GEOGRAPHICLIB_DATA");
345  if (datapath)
346  path = string(datapath);
347  return (!path.empty() ? path : string(GEOGRAPHICLIB_DATA)) + "/gravity";
348  }
349 
351  string name;
352  char* gravityname = getenv("GEOGRAPHICLIB_GRAVITY_NAME");
353  if (gravityname)
354  name = string(gravityname);
355  return !name.empty() ? name : string(GEOGRAPHICLIB_GRAVITY_DEFAULT_NAME);
356  }
357 
358 } // namespace GeographicLib
static T NaN()
Definition: Math.hpp:461
Math::real SurfaceGravity(real lat) const
GeographicLib::Math::real real
Definition: GeodSolve.cpp:32
void SphericalAnomaly(real lat, real lon, real h, real &Dg01, real &xi, real &eta) const
Header for GeographicLib::Utility class.
static bool isfinite(T x)
Definition: Math.hpp:446
CircularEngine Circle(real p, real z, bool gradp) const
Math::real T(real X, real Y, real Z, real &deltaX, real &deltaY, real &deltaZ) const
Mathematical functions needed by GeographicLib.
Definition: Math.hpp:102
Header for GeographicLib::GravityModel class.
Math::real Gravity(real lat, real lon, real h, real &gx, real &gy, real &gz) const
Math::real V(real X, real Y, real Z, real &GX, real &GY, real &GZ) const
#define GEOGRAPHICLIB_DATA
const Geocentric & Earth() const
static void readcoeffs(std::istream &stream, int &N, int &M, std::vector< real > &C, std::vector< real > &S)
CircularEngine Circle(real tau, real p, real z, bool gradp) const
Math::real Disturbance(real lat, real lon, real h, real &deltax, real &deltay, real &deltaz) const
Math::real GeoidHeight(real lat, real lon) const
static T hypot(T x, T y)
Definition: Math.hpp:255
static T sq(T x)
Definition: Math.hpp:244
GravityCircle Circle(real lat, real h, unsigned caps=ALL) const
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
const SphericalEngine::coeff & Coefficients() const
static T degree()
Definition: Math.hpp:228
Spherical harmonic sums for a circle.
static std::string DefaultGravityName()
Exception handling for GeographicLib.
Definition: Constants.hpp:361
static std::string DefaultGravityPath()
Math::real U(real X, real Y, real Z, real &gammaX, real &gammaY, real &gammaZ) const
Spherical harmonic series with a correction to the coefficients.
Math::real Phi(real X, real Y, real &fX, real &fY) const
Spherical harmonic series.
Math::real W(real X, real Y, real Z, real &gX, real &gY, real &gZ) const
Header for GeographicLib::GravityCircle class.
static bool ParseLine(const std::string &line, std::string &key, std::string &val)
Definition: Utility.cpp:22
Header for GeographicLib::SphericalEngine class.
#define GEOGRAPHICLIB_GRAVITY_DEFAULT_NAME
Gravity on a circle of latitude.
Math::real MassConstant() const