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