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