GeographicLib  1.40
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Utility.hpp
Go to the documentation of this file.
1 /**
2  * \file Utility.hpp
3  * \brief Header for GeographicLib::Utility class
4  *
5  * Copyright (c) Charles Karney (2011-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_UTILITY_HPP)
11 #define GEOGRAPHICLIB_UTILITY_HPP 1
12 
14 #include <iomanip>
15 #include <vector>
16 #include <sstream>
17 #include <cctype>
18 #include <ctime>
19 
20 #if defined(_MSC_VER)
21 // Squelch warnings about constant conditional expressions and unsafe gmtime
22 # pragma warning (push)
23 # pragma warning (disable: 4127 4996)
24 #endif
25 
26 namespace GeographicLib {
27 
28  /**
29  * \brief Some utility routines for %GeographicLib
30  *
31  * Example of use:
32  * \include example-Utility.cpp
33  **********************************************************************/
35  private:
36  static bool gregorian(int y, int m, int d) {
37  // The original cut over to the Gregorian calendar in Pope Gregory XIII's
38  // time had 1582-10-04 followed by 1582-10-15. Here we implement the
39  // switch over used by the English-speaking world where 1752-09-02 was
40  // followed by 1752-09-14. We also assume that the year always begins
41  // with January 1, whereas in reality it often was reckoned to begin in
42  // March.
43  return 100 * (100 * y + m) + d >= 17520914; // or 15821004
44  }
45  static bool gregorian(int s) {
46  return s >= 639799; // 1752-09-14
47  }
48  public:
49 
50  /**
51  * Convert a date to the day numbering sequentially starting with
52  * 0001-01-01 as day 1.
53  *
54  * @param[in] y the year (must be positive).
55  * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1.
56  * @param[in] d the day of the month (must be positive). Default = 1.
57  * @return the sequential day number.
58  **********************************************************************/
59  static int day(int y, int m = 1, int d = 1) {
60  // Convert from date to sequential day and vice versa
61  //
62  // Here is some code to convert a date to sequential day and vice
63  // versa. The sequential day is numbered so that January 1, 1 AD is day 1
64  // (a Saturday). So this is offset from the "Julian" day which starts the
65  // numbering with 4713 BC.
66  //
67  // This is inspired by a talk by John Conway at the John von Neumann
68  // National Supercomputer Center when he described his Doomsday algorithm
69  // for figuring the day of the week. The code avoids explicitly doing ifs
70  // (except for the decision of whether to use the Julian or Gregorian
71  // calendar). Instead the equivalent result is achieved using integer
72  // arithmetic. I got this idea from the routine for the day of the week
73  // in MACLisp (I believe that that routine was written by Guy Steele).
74  //
75  // There are three issues to take care of
76  //
77  // 1. the rules for leap years,
78  // 2. the inconvenient placement of leap days at the end of February,
79  // 3. the irregular pattern of month lengths.
80  //
81  // We deal with these as follows:
82  //
83  // 1. Leap years are given by simple rules which are straightforward to
84  // accommodate.
85  //
86  // 2. We simplify the calculations by moving January and February to the
87  // previous year. Here we internally number the months March–December,
88  // January, February as 0–9, 10, 11.
89  //
90  // 3. The pattern of month lengths from March through January is regular
91  // with a 5-month period—31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31. The
92  // 5-month period is 153 days long. Since February is now at the end of
93  // the year, we don't need to include its length in this part of the
94  // calculation.
95  bool greg = gregorian(y, m, d);
96  y += (m + 9) / 12 - 1; // Move Jan and Feb to previous year,
97  m = (m + 9) % 12; // making March month 0.
98  return
99  (1461 * y) / 4 // Julian years converted to days. Julian year is 365 +
100  // 1/4 = 1461/4 days.
101  // Gregorian leap year corrections. The 2 offset with respect to the
102  // Julian calendar synchronizes the vernal equinox with that at the time
103  // of the Council of Nicea (325 AD).
104  + (greg ? (y / 100) / 4 - (y / 100) + 2 : 0)
105  + (153 * m + 2) / 5 // The zero-based start of the m'th month
106  + d - 1 // The zero-based day
107  - 305; // The number of days between March 1 and December 31.
108  // This makes 0001-01-01 day 1
109  }
110 
111  /**
112  * Convert a date to the day numbering sequentially starting with
113  * 0001-01-01 as day 1.
114  *
115  * @param[in] y the year (must be positive).
116  * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1.
117  * @param[in] d the day of the month (must be positive). Default = 1.
118  * @param[in] check whether to check the date.
119  * @exception GeographicErr if the date is invalid and \e check is true.
120  * @return the sequential day number.
121  **********************************************************************/
122  static int day(int y, int m, int d, bool check) {
123  int s = day(y, m, d);
124  if (!check)
125  return s;
126  int y1, m1, d1;
127  date(s, y1, m1, d1);
128  if (!(s > 0 && y == y1 && m == m1 && d == d1))
129  throw GeographicErr("Invalid date " +
130  str(y) + "-" + str(m) + "-" + str(d)
131  + (s > 0 ? "; use " +
132  str(y1) + "-" + str(m1) + "-" + str(d1) :
133  " before 0001-01-01"));
134  return s;
135  }
136 
137  /**
138  * Given a day (counting from 0001-01-01 as day 1), return the date.
139  *
140  * @param[in] s the sequential day number (must be positive)
141  * @param[out] y the year.
142  * @param[out] m the month, Jan = 1, etc.
143  * @param[out] d the day of the month.
144  **********************************************************************/
145  static void date(int s, int& y, int& m, int& d) {
146  int c = 0;
147  bool greg = gregorian(s);
148  s += 305; // s = 0 on March 1, 1BC
149  if (greg) {
150  s -= 2; // The 2 day Gregorian offset
151  // Determine century with the Gregorian rules for leap years. The
152  // Gregorian year is 365 + 1/4 - 1/100 + 1/400 = 146097/400 days.
153  c = (4 * s + 3) / 146097;
154  s -= (c * 146097) / 4; // s = 0 at beginning of century
155  }
156  y = (4 * s + 3) / 1461; // Determine the year using Julian rules.
157  s -= (1461 * y) / 4; // s = 0 at start of year, i.e., March 1
158  y += c * 100; // Assemble full year
159  m = (5 * s + 2) / 153; // Determine the month
160  s -= (153 * m + 2) / 5; // s = 0 at beginning of month
161  d = s + 1; // Determine day of month
162  y += (m + 2) / 12; // Move Jan and Feb back to original year
163  m = (m + 2) % 12 + 1; // Renumber the months so January = 1
164  }
165 
166  /**
167  * Given a date as a string in the format yyyy, yyyy-mm, or yyyy-mm-dd,
168  * return the numeric values for the year, month, and day. No checking is
169  * done on these values. The string "now" is interpreted as the present
170  * date (in UTC).
171  *
172  * @param[in] s the date in string format.
173  * @param[out] y the year.
174  * @param[out] m the month, Jan = 1, etc.
175  * @param[out] d the day of the month.
176  * @exception GeographicErr is \e s is malformed.
177  **********************************************************************/
178  static void date(const std::string& s, int& y, int& m, int& d) {
179  if (s == "now") {
180  std::time_t t = std::time(0);
181  struct tm* now = gmtime(&t);
182  y = now->tm_year + 1900;
183  m = now->tm_mon + 1;
184  d = now->tm_mday;
185  return;
186  }
187  int y1, m1 = 1, d1 = 1;
188  const char* digits = "0123456789";
189  std::string::size_type p1 = s.find_first_not_of(digits);
190  if (p1 == std::string::npos)
191  y1 = num<int>(s);
192  else if (s[p1] != '-')
193  throw GeographicErr("Delimiter not hyphen in date " + s);
194  else if (p1 == 0)
195  throw GeographicErr("Empty year field in date " + s);
196  else {
197  y1 = num<int>(s.substr(0, p1));
198  if (++p1 == s.size())
199  throw GeographicErr("Empty month field in date " + s);
200  std::string::size_type p2 = s.find_first_not_of(digits, p1);
201  if (p2 == std::string::npos)
202  m1 = num<int>(s.substr(p1));
203  else if (s[p2] != '-')
204  throw GeographicErr("Delimiter not hyphen in date " + s);
205  else if (p2 == p1)
206  throw GeographicErr("Empty month field in date " + s);
207  else {
208  m1 = num<int>(s.substr(p1, p2 - p1));
209  if (++p2 == s.size())
210  throw GeographicErr("Empty day field in date " + s);
211  d1 = num<int>(s.substr(p2));
212  }
213  }
214  y = y1; m = m1; d = d1;
215  }
216 
217  /**
218  * Given the date, return the day of the week.
219  *
220  * @param[in] y the year (must be positive).
221  * @param[in] m the month, Jan = 1, etc. (must be positive).
222  * @param[in] d the day of the month (must be positive).
223  * @return the day of the week with Sunday, Monday--Saturday = 0,
224  * 1--6.
225  **********************************************************************/
226  static int dow(int y, int m, int d) { return dow(day(y, m, d)); }
227 
228  /**
229  * Given the sequential day, return the day of the week.
230  *
231  * @param[in] s the sequential day (must be positive).
232  * @return the day of the week with Sunday, Monday--Saturday = 0,
233  * 1--6.
234  **********************************************************************/
235  static int dow(int s) {
236  return (s + 5) % 7; // The 5 offset makes day 1 (0001-01-01) a Saturday.
237  }
238 
239  /**
240  * Convert a string representing a date to a fractional year.
241  *
242  * @tparam T the type of the argument.
243  * @param[in] s the string to be converted.
244  * @exception GeographicErr if \e s can't be interpreted as a date.
245  * @return the fractional year.
246  *
247  * The string is first read as an ordinary number (e.g., 2010 or 2012.5);
248  * if this is successful, the value is returned. Otherwise the string
249  * should be of the form yyyy-mm or yyyy-mm-dd and this is converted to a
250  * number with 2010-01-01 giving 2010.0 and 2012-07-03 giving 2012.5.
251  **********************************************************************/
252  template<typename T> static T fractionalyear(const std::string& s) {
253  try {
254  return num<T>(s);
255  }
256  catch (const std::exception&) {
257  }
258  int y, m, d;
259  date(s, y, m, d);
260  int t = day(y, m, d, true);
261  return T(y) + T(t - day(y)) / T(day(y + 1) - day(y));
262  }
263 
264  /**
265  * Convert a object of type T to a string.
266  *
267  * @tparam T the type of the argument.
268  * @param[in] x the value to be converted.
269  * @param[in] p the precision used (default &minus;1).
270  * @exception std::bad_alloc if memory for the string can't be allocated.
271  * @return the string representation.
272  *
273  * If \e p &ge; 0, then the number fixed format is used with p bits of
274  * precision. With p < 0, there is no manipulation of the format.
275  **********************************************************************/
276  template<typename T> static std::string str(T x, int p = -1) {
277  std::ostringstream s;
278  if (p >= 0) s << std::fixed << std::setprecision(p);
279  s << x; return s.str();
280  }
281 
282  /**
283  * Convert a Math::real object to a string.
284  *
285  * @param[in] x the value to be converted.
286  * @param[in] p the precision used (default &minus;1).
287  * @exception std::bad_alloc if memory for the string can't be allocated.
288  * @return the string representation.
289  *
290  * If \e p &ge; 0, then the number fixed format is used with p bits of
291  * precision. With p < 0, there is no manipulation of the format. This is
292  * an overload of str<T> which deals with inf and nan.
293  **********************************************************************/
294  static std::string str(Math::real x, int p = -1) {
295  if (!Math::isfinite(x))
296  return x < 0 ? std::string("-inf") :
297  (x > 0 ? std::string("inf") : std::string("nan"));
298  std::ostringstream s;
299  if (p >= 0) s << std::fixed << std::setprecision(p);
300  s << x; return s.str();
301  }
302 
303  /**
304  * Convert a string to an object of type T.
305  *
306  * @tparam T the type of the return value.
307  * @param[in] s the string to be converted.
308  * @exception GeographicErr is \e s is not readable as a T.
309  * @return object of type T
310  **********************************************************************/
311  template<typename T> static T num(const std::string& s) {
312  T x;
313  std::string errmsg;
314  do { // Executed once (provides the ability to break)
315  std::istringstream is(s);
316  if (!(is >> x)) {
317  errmsg = "Cannot decode " + s;
318  break;
319  }
320  int pos = int(is.tellg()); // Returns -1 at end of string?
321  if (!(pos < 0 || pos == int(s.size()))) {
322  errmsg = "Extra text " + s.substr(pos) + " at end of " + s;
323  break;
324  }
325  return x;
326  } while (false);
327  x = std::numeric_limits<T>::is_integer ? 0 : nummatch<T>(s);
328  if (x == 0)
329  throw GeographicErr(errmsg);
330  return x;
331  }
332 
333  /**
334  * Match "nan" and "inf" (and variants thereof) in a string.
335  *
336  * @tparam T the type of the return value.
337  * @param[in] s the string to be matched.
338  * @return appropriate special value (&plusmn;&infin;, nan) or 0 if none is
339  * found.
340  **********************************************************************/
341  template<typename T> static T nummatch(const std::string& s) {
342  if (s.length() < 3)
343  return 0;
344  std::string t;
345  t.resize(s.length());
346  std::transform(s.begin(), s.end(), t.begin(), (int(*)(int))std::toupper);
347  for (size_t i = s.length(); i--;)
348  t[i] = char(std::toupper(s[i]));
349  int sign = t[0] == '-' ? -1 : 1;
350  std::string::size_type p0 = t[0] == '-' || t[0] == '+' ? 1 : 0;
351  std::string::size_type p1 = t.find_last_not_of('0');
352  if (p1 == std::string::npos || p1 + 1 < p0 + 3)
353  return 0;
354  // Strip off sign and trailing 0s
355  t = t.substr(p0, p1 + 1 - p0); // Length at least 3
356  if (t == "NAN" || t == "1.#QNAN" || t == "1.#SNAN" || t == "1.#IND" ||
357  t == "1.#R")
358  return Math::NaN<T>();
359  else if (t == "INF" || t == "1.#INF")
360  return sign * Math::infinity<T>();
361  return 0;
362  }
363 
364  /**
365  * Read a simple fraction, e.g., 3/4, from a string to an object of type T.
366  *
367  * @tparam T the type of the return value.
368  * @param[in] s the string to be converted.
369  * @exception GeographicErr is \e s is not readable as a fraction of type T.
370  * @return object of type T
371  **********************************************************************/
372  template<typename T> static T fract(const std::string& s) {
373  std::string::size_type delim = s.find('/');
374  return
375  !(delim != std::string::npos && delim >= 1 && delim + 2 <= s.size()) ?
376  num<T>(s) :
377  // delim in [1, size() - 2]
378  num<T>(s.substr(0, delim)) / num<T>(s.substr(delim + 1));
379  }
380 
381  /**
382  * Lookup up a character in a string.
383  *
384  * @param[in] s the string to be searched.
385  * @param[in] c the character to look for.
386  * @return the index of the first occurrence character in the string or
387  * &minus;1 is the character is not present.
388  *
389  * \e c is converted to upper case before search \e s. Therefore, it is
390  * intended that \e s should not contain any lower case letters.
391  **********************************************************************/
392  static int lookup(const std::string& s, char c) {
393  std::string::size_type r = s.find(char(toupper(c)));
394  return r == std::string::npos ? -1 : int(r);
395  }
396 
397  /**
398  * Read data of type ExtT from a binary stream to an array of type IntT.
399  * The data in the file is in (bigendp ? big : little)-endian format.
400  *
401  * @tparam ExtT the type of the objects in the binary stream (external).
402  * @tparam IntT the type of the objects in the array (internal).
403  * @tparam bigendp true if the external storage format is big-endian.
404  * @param[in] str the input stream containing the data of type ExtT
405  * (external).
406  * @param[out] array the output array of type IntT (internal).
407  * @param[in] num the size of the array.
408  * @exception GeographicErr if the data cannot be read.
409  **********************************************************************/
410  template<typename ExtT, typename IntT, bool bigendp>
411  static inline void readarray(std::istream& str,
412  IntT array[], size_t num) {
413 #if GEOGRAPHICLIB_PRECISION < 4
414  if (sizeof(IntT) == sizeof(ExtT) &&
415  std::numeric_limits<IntT>::is_integer ==
416  std::numeric_limits<ExtT>::is_integer)
417  {
418  // Data is compatible (aside from the issue of endian-ness).
419  str.read(reinterpret_cast<char *>(array), num * sizeof(ExtT));
420  if (!str.good())
421  throw GeographicErr("Failure reading data");
422  if (bigendp != Math::bigendian) { // endian mismatch -> swap bytes
423  for (size_t i = num; i--;)
424  array[i] = Math::swab<IntT>(array[i]);
425  }
426  }
427  else
428 #endif
429  {
430  const int bufsize = 1024; // read this many values at a time
431  ExtT buffer[bufsize]; // temporary buffer
432  int k = int(num); // data values left to read
433  int i = 0; // index into output array
434  while (k) {
435  int n = (std::min)(k, bufsize);
436  str.read(reinterpret_cast<char *>(buffer), n * sizeof(ExtT));
437  if (!str.good())
438  throw GeographicErr("Failure reading data");
439  for (int j = 0; j < n; ++j)
440  // fix endian-ness and cast to IntT
441  array[i++] = IntT(bigendp == Math::bigendian ? buffer[j] :
442  Math::swab<ExtT>(buffer[j]));
443  k -= n;
444  }
445  }
446  return;
447  }
448 
449  /**
450  * Read data of type ExtT from a binary stream to a vector array of type
451  * IntT. The data in the file is in (bigendp ? big : little)-endian
452  * format.
453  *
454  * @tparam ExtT the type of the objects in the binary stream (external).
455  * @tparam IntT the type of the objects in the array (internal).
456  * @tparam bigendp true if the external storage format is big-endian.
457  * @param[in] str the input stream containing the data of type ExtT
458  * (external).
459  * @param[out] array the output vector of type IntT (internal).
460  * @exception GeographicErr if the data cannot be read.
461  **********************************************************************/
462  template<typename ExtT, typename IntT, bool bigendp>
463  static inline void readarray(std::istream& str,
464  std::vector<IntT>& array) {
465  if (array.size() > 0)
466  readarray<ExtT, IntT, bigendp>(str, &array[0], array.size());
467  }
468 
469  /**
470  * Write data in an array of type IntT as type ExtT to a binary stream.
471  * The data in the file is in (bigendp ? big : little)-endian format.
472  *
473  * @tparam ExtT the type of the objects in the binary stream (external).
474  * @tparam IntT the type of the objects in the array (internal).
475  * @tparam bigendp true if the external storage format is big-endian.
476  * @param[out] str the output stream for the data of type ExtT (external).
477  * @param[in] array the input array of type IntT (internal).
478  * @param[in] num the size of the array.
479  * @exception GeographicErr if the data cannot be written.
480  **********************************************************************/
481  template<typename ExtT, typename IntT, bool bigendp>
482  static inline void writearray(std::ostream& str,
483  const IntT array[], size_t num) {
484 #if GEOGRAPHICLIB_PRECISION < 4
485  if (sizeof(IntT) == sizeof(ExtT) &&
486  std::numeric_limits<IntT>::is_integer ==
487  std::numeric_limits<ExtT>::is_integer &&
488  bigendp == Math::bigendian)
489  {
490  // Data is compatible (including endian-ness).
491  str.write(reinterpret_cast<const char *>(array), num * sizeof(ExtT));
492  if (!str.good())
493  throw GeographicErr("Failure writing data");
494  }
495  else
496 #endif
497  {
498  const int bufsize = 1024; // write this many values at a time
499  ExtT buffer[bufsize]; // temporary buffer
500  int k = int(num); // data values left to write
501  int i = 0; // index into output array
502  while (k) {
503  int n = (std::min)(k, bufsize);
504  for (int j = 0; j < n; ++j)
505  // cast to ExtT and fix endian-ness
506  buffer[j] = bigendp == Math::bigendian ? ExtT(array[i++]) :
507  Math::swab<ExtT>(ExtT(array[i++]));
508  str.write(reinterpret_cast<const char *>(buffer), n * sizeof(ExtT));
509  if (!str.good())
510  throw GeographicErr("Failure writing data");
511  k -= n;
512  }
513  }
514  return;
515  }
516 
517  /**
518  * Write data in an array of type IntT as type ExtT to a binary stream.
519  * The data in the file is in (bigendp ? big : little)-endian format.
520  *
521  * @tparam ExtT the type of the objects in the binary stream (external).
522  * @tparam IntT the type of the objects in the array (internal).
523  * @tparam bigendp true if the external storage format is big-endian.
524  * @param[out] str the output stream for the data of type ExtT (external).
525  * @param[in] array the input vector of type IntT (internal).
526  * @exception GeographicErr if the data cannot be written.
527  **********************************************************************/
528  template<typename ExtT, typename IntT, bool bigendp>
529  static inline void writearray(std::ostream& str,
530  std::vector<IntT>& array) {
531  if (array.size() > 0)
532  writearray<ExtT, IntT, bigendp>(str, &array[0], array.size());
533  }
534 
535  /**
536  * Parse a KEY VALUE line.
537  *
538  * @param[in] line the input line.
539  * @param[out] key the key.
540  * @param[out] val the value.
541  * @exception std::bad_alloc if memory for the internal strings can't be
542  * allocated.
543  * @return whether a key was found.
544  *
545  * A # character and everything after it are discarded. If the result is
546  * just white space, the routine returns false (and \e key and \e val are
547  * not set). Otherwise the first token is taken to be the key and the rest
548  * of the line (trimmed of leading and trailing white space) is the value.
549  **********************************************************************/
550  static bool ParseLine(const std::string& line,
551  std::string& key, std::string& val);
552 
553  /**
554  * Set the binary precision of a real number.
555  *
556  * @param[in] ndigits the number of bits of precision. If ndigits is 0
557  * (the default), then determine the precision from the environment
558  * variable GEOGRAPHICLIB_DIGITS. If this is undefined, use ndigits =
559  * 256 (i.e., about 77 decimal digits).
560  * @return the resulting number of bits of precision.
561  *
562  * This only has an effect when GEOGRAPHICLIB_PRECISION == 5.
563  **********************************************************************/
564  static int set_digits(int ndigits = 0);
565 
566  };
567 
568 } // namespace GeographicLib
569 
570 #if defined(_MSC_VER)
571 # pragma warning (pop)
572 #endif
573 
574 #endif // GEOGRAPHICLIB_UTILITY_HPP
static T fract(const std::string &s)
Definition: Utility.hpp:372
static int day(int y, int m, int d, bool check)
Definition: Utility.hpp:122
#define GEOGRAPHICLIB_EXPORT
Definition: Constants.hpp:69
static void readarray(std::istream &str, std::vector< IntT > &array)
Definition: Utility.hpp:463
static void readarray(std::istream &str, IntT array[], size_t num)
Definition: Utility.hpp:411
Some utility routines for GeographicLib.
Definition: Utility.hpp:34
static void date(const std::string &s, int &y, int &m, int &d)
Definition: Utility.hpp:178
static bool isfinite(T x)
Definition: Math.hpp:446
static T fractionalyear(const std::string &s)
Definition: Utility.hpp:252
static void writearray(std::ostream &str, std::vector< IntT > &array)
Definition: Utility.hpp:529
static T nummatch(const std::string &s)
Definition: Utility.hpp:341
static void writearray(std::ostream &str, const IntT array[], size_t num)
Definition: Utility.hpp:482
static std::string str(Math::real x, int p=-1)
Definition: Utility.hpp:294
static int dow(int s)
Definition: Utility.hpp:235
static void date(int s, int &y, int &m, int &d)
Definition: Utility.hpp:145
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
static std::string str(T x, int p=-1)
Definition: Utility.hpp:276
static int dow(int y, int m, int d)
Definition: Utility.hpp:226
static const bool bigendian
Definition: Math.hpp:208
static T num(const std::string &s)
Definition: Utility.hpp:311
Exception handling for GeographicLib.
Definition: Constants.hpp:361
Header for GeographicLib::Constants class.
static int lookup(const std::string &s, char c)
Definition: Utility.hpp:392
static int day(int y, int m=1, int d=1)
Definition: Utility.hpp:59