GeographicLib  1.43
Geoid.hpp
Go to the documentation of this file.
1 /**
2  * \file Geoid.hpp
3  * \brief Header for GeographicLib::Geoid class
4  *
5  * Copyright (c) Charles Karney (2009-2015) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * http://geographiclib.sourceforge.net/
8  **********************************************************************/
9 
10 #if !defined(GEOGRAPHICLIB_GEOID_HPP)
11 #define GEOGRAPHICLIB_GEOID_HPP 1
12 
13 #include <vector>
14 #include <fstream>
16 
17 #if defined(_MSC_VER)
18 // Squelch warnings about dll vs vector and constant conditional expressions
19 # pragma warning (push)
20 # pragma warning (disable: 4251 4127)
21 #endif
22 
23 #if !defined(GEOGRAPHICLIB_GEOID_PGM_PIXEL_WIDTH)
24 /**
25  * The size of the pixel data in the pgm data files for the geoids. 2 is the
26  * standard size corresponding to a maxval 2<sup>16</sup>&minus;1. Setting it
27  * to 4 uses a maxval of 2<sup>32</sup>&minus;1 and changes the extension for
28  * the data files from .pgm to .pgm4. Note that the format of these pgm4 files
29  * is a non-standard extension of the pgm format.
30  **********************************************************************/
31 # define GEOGRAPHICLIB_GEOID_PGM_PIXEL_WIDTH 2
32 #endif
33 
34 namespace GeographicLib {
35 
36  /**
37  * \brief Looking up the height of the geoid above the ellipsoid
38  *
39  * This class evaluates the height of one of the standard geoids, EGM84,
40  * EGM96, or EGM2008 by bilinear or cubic interpolation into a rectangular
41  * grid of data. These geoid models are documented in
42  * - EGM84:
43  * http://earth-info.nga.mil/GandG/wgs84/gravitymod/wgs84_180/wgs84_180.html
44  * - EGM96:
45  * http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/egm96.html
46  * - EGM2008:
47  * http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008
48  *
49  * The geoids are defined in terms of spherical harmonics. However in order
50  * to provide a quick and flexible method of evaluating the geoid heights,
51  * this class evaluates the height by interpolation into a grid of
52  * precomputed values.
53  *
54  * The height of the geoid above the ellipsoid, \e N, is sometimes called the
55  * geoid undulation. It can be used to convert a height above the ellipsoid,
56  * \e h, to the corresponding height above the geoid (the orthometric height,
57  * roughly the height above mean sea level), \e H, using the relations
58  *
59  * &nbsp;&nbsp;&nbsp;\e h = \e N + \e H;
60  * &nbsp;&nbsp;\e H = &minus;\e N + \e h.
61  *
62  * See \ref geoid for details of how to install the data sets, the data
63  * format, estimates of the interpolation errors, and how to use caching.
64  *
65  * In addition to returning the geoid height, the gradient of the geoid can
66  * be calculated. The gradient is defined as the rate of change of the geoid
67  * as a function of position on the ellipsoid. This uses the parameters for
68  * the WGS84 ellipsoid. The gradient defined in terms of the interpolated
69  * heights. As a result of the way that the geoid data is stored, the
70  * calculation of gradients can result in large quantization errors. This is
71  * particularly acute for fine grids, at high latitudes, and for the easterly
72  * gradient. For this reason, the use of this facility is <b>DEPRECATED</b>.
73  * Instead, use the GravityModel class to evaluate the gravity vector.
74  *
75  * This class is typically \e not thread safe in that a single instantiation
76  * cannot be safely used by multiple threads because of the way the object
77  * reads the data set and because it maintains a single-cell cache. If
78  * multiple threads need to calculate geoid heights they should all construct
79  * thread-local instantiations. Alternatively, set the optional \e
80  * threadsafe parameter to true in the constructor. This causes the
81  * constructor to read all the data into memory and to turn off the
82  * single-cell caching which results in a Geoid object which \e is thread
83  * safe.
84  *
85  * Example of use:
86  * \include example-Geoid.cpp
87  *
88  * <a href="GeoidEval.1.html">GeoidEval</a> is a command-line utility
89  * providing access to the functionality of Geoid.
90  **********************************************************************/
91 
93  private:
94  typedef Math::real real;
95 #if GEOGRAPHICLIB_GEOID_PGM_PIXEL_WIDTH != 4
96  typedef unsigned short pixel_t;
97  static const unsigned pixel_size_ = 2;
98  static const unsigned pixel_max_ = 0xffffu;
99 #else
100  typedef unsigned pixel_t;
101  static const unsigned pixel_size_ = 4;
102  static const unsigned pixel_max_ = 0xffffffffu;
103 #endif
104  static const unsigned stencilsize_ = 12;
105  static const unsigned nterms_ = ((3 + 1) * (3 + 2))/2; // for a cubic fit
106  static const int c0_;
107  static const int c0n_;
108  static const int c0s_;
109  static const int c3_[stencilsize_ * nterms_];
110  static const int c3n_[stencilsize_ * nterms_];
111  static const int c3s_[stencilsize_ * nterms_];
112 
113  std::string _name, _dir, _filename;
114  const bool _cubic;
115  const real _a, _e2, _degree, _eps;
116  mutable std::ifstream _file;
117  real _rlonres, _rlatres;
118  std::string _description, _datetime;
119  real _offset, _scale, _maxerror, _rmserror;
120  int _width, _height;
121  unsigned long long _datastart, _swidth;
122  bool _threadsafe;
123  // Area cache
124  mutable std::vector< std::vector<pixel_t> > _data;
125  mutable bool _cache;
126  // NE corner and extent of cache
127  mutable int _xoffset, _yoffset, _xsize, _ysize;
128  // Cell cache
129  mutable int _ix, _iy;
130  mutable real _v00, _v01, _v10, _v11;
131  mutable real _t[nterms_];
132  void filepos(int ix, int iy) const {
133  _file.seekg(
134 #if !(defined(__GNUC__) && __GNUC__ < 4)
135  // g++ 3.x doesn't know about the cast to streamoff.
136  std::ios::streamoff
137 #endif
138  (_datastart +
139  pixel_size_ * (unsigned(iy)*_swidth + unsigned(ix))));
140  }
141  real rawval(int ix, int iy) const {
142  if (ix < 0)
143  ix += _width;
144  else if (ix >= _width)
145  ix -= _width;
146  if (_cache && iy >= _yoffset && iy < _yoffset + _ysize &&
147  ((ix >= _xoffset && ix < _xoffset + _xsize) ||
148  (ix + _width >= _xoffset && ix + _width < _xoffset + _xsize))) {
149  return real(_data[iy - _yoffset]
150  [ix >= _xoffset ? ix - _xoffset : ix + _width - _xoffset]);
151  } else {
152  if (iy < 0 || iy >= _height) {
153  iy = iy < 0 ? -iy : 2 * (_height - 1) - iy;
154  ix += (ix < _width/2 ? 1 : -1) * _width/2;
155  }
156  try {
157  filepos(ix, iy);
158  // initial values to suppress warnings in case get fails
159  char a = 0, b = 0;
160  _file.get(a);
161  _file.get(b);
162  unsigned r = ((unsigned char)(a) << 8) | (unsigned char)(b);
163  if (pixel_size_ == 4) {
164  _file.get(a);
165  _file.get(b);
166  r = (r << 16) | ((unsigned char)(a) << 8) | (unsigned char)(b);
167  }
168  return real(r);
169  }
170  catch (const std::exception& e) {
171  // throw GeographicErr("Error reading " + _filename + ": "
172  // + e.what());
173  // triggers complaints about the "binary '+'" under Visual Studio.
174  // So use '+=' instead.
175  std::string err("Error reading ");
176  err += _filename;
177  err += ": ";
178  err += e.what();
179  throw GeographicErr(err);
180  }
181  }
182  }
183  real height(real lat, real lon, bool gradp,
184  real& grade, real& gradn) const;
185  Geoid(const Geoid&); // copy constructor not allowed
186  Geoid& operator=(const Geoid&); // copy assignment not allowed
187  public:
188 
189  /**
190  * Flags indicating conversions between heights above the geoid and heights
191  * above the ellipsoid.
192  **********************************************************************/
193  enum convertflag {
194  /**
195  * The multiplier for converting from heights above the geoid to heights
196  * above the ellipsoid.
197  **********************************************************************/
198  ELLIPSOIDTOGEOID = -1,
199  /**
200  * No conversion.
201  **********************************************************************/
202  NONE = 0,
203  /**
204  * The multiplier for converting from heights above the ellipsoid to
205  * heights above the geoid.
206  **********************************************************************/
207  GEOIDTOELLIPSOID = 1,
208  };
209 
210  /** \name Setting up the geoid
211  **********************************************************************/
212  ///@{
213  /**
214  * Construct a geoid.
215  *
216  * @param[in] name the name of the geoid.
217  * @param[in] path (optional) directory for data file.
218  * @param[in] cubic (optional) interpolation method; false means bilinear,
219  * true (the default) means cubic.
220  * @param[in] threadsafe (optional), if true, construct a thread safe
221  * object. The default is false
222  * @exception GeographicErr if the data file cannot be found, is
223  * unreadable, or is corrupt.
224  * @exception GeographicErr if \e threadsafe is true but the memory
225  * necessary for caching the data can't be allocated.
226  *
227  * The data file is formed by appending ".pgm" to the name. If \e path is
228  * specified (and is non-empty), then the file is loaded from directory, \e
229  * path. Otherwise the path is given by DefaultGeoidPath(). If the \e
230  * threadsafe parameter is true, the data set is read into memory, the data
231  * file is closed, and single-cell caching is turned off; this results in a
232  * Geoid object which \e is thread safe.
233  **********************************************************************/
234  explicit Geoid(const std::string& name, const std::string& path = "",
235  bool cubic = true, bool threadsafe = false);
236 
237  /**
238  * Set up a cache.
239  *
240  * @param[in] south latitude (degrees) of the south edge of the cached area.
241  * @param[in] west longitude (degrees) of the west edge of the cached area.
242  * @param[in] north latitude (degrees) of the north edge of the cached area.
243  * @param[in] east longitude (degrees) of the east edge of the cached area.
244  * @exception GeographicErr if the memory necessary for caching the data
245  * can't be allocated (in this case, you will have no cache and can try
246  * again with a smaller area).
247  * @exception GeographicErr if there's a problem reading the data.
248  * @exception GeographicErr if this is called on a threadsafe Geoid.
249  *
250  * Cache the data for the specified "rectangular" area bounded by the
251  * parallels \e south and \e north and the meridians \e west and \e east.
252  * \e east is always interpreted as being east of \e west, if necessary by
253  * adding 360&deg; to its value. \e south and \e north should be in
254  * the range [&minus;90&deg;, 90&deg;]; \e west and \e east should
255  * be in the range [&minus;540&deg;, 540&deg;).
256  **********************************************************************/
257  void CacheArea(real south, real west, real north, real east) const;
258 
259  /**
260  * Cache all the data.
261  *
262  * @exception GeographicErr if the memory necessary for caching the data
263  * can't be allocated (in this case, you will have no cache and can try
264  * again with a smaller area).
265  * @exception GeographicErr if there's a problem reading the data.
266  * @exception GeographicErr if this is called on a threadsafe Geoid.
267  *
268  * On most computers, this is fast for data sets with grid resolution of 5'
269  * or coarser. For a 1' grid, the required RAM is 450MB; a 2.5' grid needs
270  * 72MB; and a 5' grid needs 18MB.
271  **********************************************************************/
272  void CacheAll() const { CacheArea(real(-90), real(0),
273  real(90), real(360)); }
274 
275  /**
276  * Clear the cache. This never throws an error. (This does nothing with a
277  * thread safe Geoid.)
278  **********************************************************************/
279  void CacheClear() const;
280 
281  ///@}
282 
283  /** \name Compute geoid heights
284  **********************************************************************/
285  ///@{
286  /**
287  * Compute the geoid height at a point
288  *
289  * @param[in] lat latitude of the point (degrees).
290  * @param[in] lon longitude of the point (degrees).
291  * @exception GeographicErr if there's a problem reading the data; this
292  * never happens if (\e lat, \e lon) is within a successfully cached area.
293  * @return the height of the geoid above the ellipsoid (meters).
294  *
295  * The latitude should be in [&minus;90&deg;, 90&deg;] and
296  * longitude should be in [&minus;540&deg;, 540&deg;).
297  **********************************************************************/
298  Math::real operator()(real lat, real lon) const {
299  real gradn, grade;
300  return height(lat, lon, false, gradn, grade);
301  }
302 
303  /**
304  * Compute the geoid height and gradient at a point
305  *
306  * @param[in] lat latitude of the point (degrees).
307  * @param[in] lon longitude of the point (degrees).
308  * @param[out] gradn northerly gradient (dimensionless).
309  * @param[out] grade easterly gradient (dimensionless).
310  * @exception GeographicErr if there's a problem reading the data; this
311  * never happens if (\e lat, \e lon) is within a successfully cached area.
312  * @return geoid height (meters).
313  *
314  * The latitude should be in [&minus;90&deg;, 90&deg;] and longitude should
315  * be in [&minus;540&deg;, 540&deg;). As a result of the way that the
316  * geoid data is stored, the calculation of gradients can result in large
317  * quantization errors. This is particularly acute for fine grids, at high
318  * latitudes, and for the easterly gradient. For this reason, the
319  * computation of the gradient is <b>DEPRECATED</b>. If you need to
320  * compute the direction of the acceleration due to gravity accurately, you
321  * should use GravityModel::Gravity.
322  **********************************************************************/
323  Math::real operator()(real lat, real lon, real& gradn, real& grade) const {
324  return height(lat, lon, true, gradn, grade);
325  }
326 
327  /**
328  * Convert a height above the geoid to a height above the ellipsoid and
329  * vice versa.
330  *
331  * @param[in] lat latitude of the point (degrees).
332  * @param[in] lon longitude of the point (degrees).
333  * @param[in] h height of the point (degrees).
334  * @param[in] d a Geoid::convertflag specifying the direction of the
335  * conversion; Geoid::GEOIDTOELLIPSOID means convert a height above the
336  * geoid to a height above the ellipsoid; Geoid::ELLIPSOIDTOGEOID means
337  * convert a height above the ellipsoid to a height above the geoid.
338  * @exception GeographicErr if there's a problem reading the data; this
339  * never happens if (\e lat, \e lon) is within a successfully cached area.
340  * @return converted height (meters).
341  **********************************************************************/
342  Math::real ConvertHeight(real lat, real lon, real h,
343  convertflag d) const {
344  real gradn, grade;
345  return h + real(d) * height(lat, lon, true, gradn, grade);
346  }
347 
348  ///@}
349 
350  /** \name Inspector functions
351  **********************************************************************/
352  ///@{
353  /**
354  * @return geoid description, if available, in the data file; if
355  * absent, return "NONE".
356  **********************************************************************/
357  const std::string& Description() const { return _description; }
358 
359  /**
360  * @return date of the data file; if absent, return "UNKNOWN".
361  **********************************************************************/
362  const std::string& DateTime() const { return _datetime; }
363 
364  /**
365  * @return full file name used to load the geoid data.
366  **********************************************************************/
367  const std::string& GeoidFile() const { return _filename; }
368 
369  /**
370  * @return "name" used to load the geoid data (from the first argument of
371  * the constructor).
372  **********************************************************************/
373  const std::string& GeoidName() const { return _name; }
374 
375  /**
376  * @return directory used to load the geoid data.
377  **********************************************************************/
378  const std::string& GeoidDirectory() const { return _dir; }
379 
380  /**
381  * @return interpolation method ("cubic" or "bilinear").
382  **********************************************************************/
383  const std::string Interpolation() const
384  { return std::string(_cubic ? "cubic" : "bilinear"); }
385 
386  /**
387  * @return estimate of the maximum interpolation and quantization error
388  * (meters).
389  *
390  * This relies on the value being stored in the data file. If the value is
391  * absent, return &minus;1.
392  **********************************************************************/
393  Math::real MaxError() const { return _maxerror; }
394 
395  /**
396  * @return estimate of the RMS interpolation and quantization error
397  * (meters).
398  *
399  * This relies on the value being stored in the data file. If the value is
400  * absent, return &minus;1.
401  **********************************************************************/
402  Math::real RMSError() const { return _rmserror; }
403 
404  /**
405  * @return offset (meters).
406  *
407  * This in used in converting from the pixel values in the data file to
408  * geoid heights.
409  **********************************************************************/
410  Math::real Offset() const { return _offset; }
411 
412  /**
413  * @return scale (meters).
414  *
415  * This in used in converting from the pixel values in the data file to
416  * geoid heights.
417  **********************************************************************/
418  Math::real Scale() const { return _scale; }
419 
420  /**
421  * @return true if the object is constructed to be thread safe.
422  **********************************************************************/
423  bool ThreadSafe() const { return _threadsafe; }
424 
425  /**
426  * @return true if a data cache is active.
427  **********************************************************************/
428  bool Cache() const { return _cache; }
429 
430  /**
431  * @return west edge of the cached area; the cache includes this edge.
432  **********************************************************************/
434  return _cache ? ((_xoffset + (_xsize == _width ? 0 : _cubic)
435  + _width/2) % _width - _width/2) / _rlonres :
436  0;
437  }
438 
439  /**
440  * @return east edge of the cached area; the cache excludes this edge.
441  **********************************************************************/
443  return _cache ?
444  CacheWest() +
445  (_xsize - (_xsize == _width ? 0 : 1 + 2 * _cubic)) / _rlonres :
446  0;
447  }
448 
449  /**
450  * @return north edge of the cached area; the cache includes this edge.
451  **********************************************************************/
453  return _cache ? 90 - (_yoffset + _cubic) / _rlatres : 0;
454  }
455 
456  /**
457  * @return south edge of the cached area; the cache excludes this edge
458  * unless it's the south pole.
459  **********************************************************************/
461  return _cache ? 90 - ( _yoffset + _ysize - 1 - _cubic) / _rlatres : 0;
462  }
463 
464  /**
465  * @return \e a the equatorial radius of the WGS84 ellipsoid (meters).
466  *
467  * (The WGS84 value is returned because the supported geoid models are all
468  * based on this ellipsoid.)
469  **********************************************************************/
471  { return Constants::WGS84_a(); }
472 
473  /**
474  * @return \e f the flattening of the WGS84 ellipsoid.
475  *
476  * (The WGS84 value is returned because the supported geoid models are all
477  * based on this ellipsoid.)
478  **********************************************************************/
480  ///@}
481 
482  /// \cond SKIP
483  /**
484  * <b>DEPRECATED</b>
485  * @return \e r the inverse flattening of the WGS84 ellipsoid.
486  **********************************************************************/
487  Math::real InverseFlattening() const
488  { return 1/Constants::WGS84_f(); }
489  /// \endcond
490 
491  /**
492  * @return the default path for geoid data files.
493  *
494  * This is the value of the environment variable GEOGRAPHICLIB_GEOID_PATH,
495  * if set; otherwise, it is $GEOGRAPHICLIB_DATA/geoids if the environment
496  * variable GEOGRAPHICLIB_DATA is set; otherwise, it is a compile-time
497  * default (/usr/local/share/GeographicLib/geoids on non-Windows systems
498  * and C:/ProgramData/GeographicLib/geoids on Windows systems).
499  **********************************************************************/
500  static std::string DefaultGeoidPath();
501 
502  /**
503  * @return the default name for the geoid.
504  *
505  * This is the value of the environment variable GEOGRAPHICLIB_GEOID_NAME,
506  * if set; otherwise, it is "egm96-5". The Geoid class does not use this
507  * function; it is just provided as a convenience for a calling program
508  * when constructing a Geoid object.
509  **********************************************************************/
510  static std::string DefaultGeoidName();
511 
512  };
513 
514 } // namespace GeographicLib
515 
516 #if defined(_MSC_VER)
517 # pragma warning (pop)
518 #endif
519 
520 #endif // GEOGRAPHICLIB_GEOID_HPP
const std::string & GeoidFile() const
Definition: Geoid.hpp:367
Math::real Scale() const
Definition: Geoid.hpp:418
#define GEOGRAPHICLIB_EXPORT
Definition: Constants.hpp:90
Math::real RMSError() const
Definition: Geoid.hpp:402
bool ThreadSafe() const
Definition: Geoid.hpp:423
GeographicLib::Math::real real
Definition: GeodSolve.cpp:32
const std::string Interpolation() const
Definition: Geoid.hpp:383
Math::real Offset() const
Definition: Geoid.hpp:410
const std::string & GeoidName() const
Definition: Geoid.hpp:373
Math::real ConvertHeight(real lat, real lon, real h, convertflag d) const
Definition: Geoid.hpp:342
bool Cache() const
Definition: Geoid.hpp:428
Math::real CacheNorth() const
Definition: Geoid.hpp:452
Math::real MaxError() const
Definition: Geoid.hpp:393
Math::real operator()(real lat, real lon, real &gradn, real &grade) const
Definition: Geoid.hpp:323
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
const std::string & Description() const
Definition: Geoid.hpp:357
Exception handling for GeographicLib.
Definition: Constants.hpp:382
Math::real CacheSouth() const
Definition: Geoid.hpp:460
Header for GeographicLib::Constants class.
Math::real CacheWest() const
Definition: Geoid.hpp:433
Math::real Flattening() const
Definition: Geoid.hpp:479
const std::string & DateTime() const
Definition: Geoid.hpp:362
const std::string & GeoidDirectory() const
Definition: Geoid.hpp:378
void CacheAll() const
Definition: Geoid.hpp:272
Math::real MajorRadius() const
Definition: Geoid.hpp:470
Math::real CacheEast() const
Definition: Geoid.hpp:442
Math::real operator()(real lat, real lon) const
Definition: Geoid.hpp:298
Looking up the height of the geoid above the ellipsoid.
Definition: Geoid.hpp:92