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