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