GeographicLib  1.44
DMS.cpp
Go to the documentation of this file.
1 /**
2  * \file DMS.cpp
3  * \brief Implementation for GeographicLib::DMS class
4  *
5  * Copyright (c) Charles Karney (2008-2015) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * http://geographiclib.sourceforge.net/
8  **********************************************************************/
9 
10 #include <GeographicLib/DMS.hpp>
12 
13 #if defined(_MSC_VER)
14 // Squelch warnings about constant conditional expressions
15 # pragma warning (disable: 4127)
16 #endif
17 
18 namespace GeographicLib {
19 
20  using namespace std;
21 
22  const string DMS::hemispheres_ = "SNWE";
23  const string DMS::signs_ = "-+";
24  const string DMS::digits_ = "0123456789";
25  const string DMS::dmsindicators_ = "D'\":";
26  const string DMS::components_[] = {"degrees", "minutes", "seconds"};
27 
28  Math::real DMS::Decode(const std::string& dms, flag& ind) {
29  string errormsg;
30  string dmsa = dms;
31  replace(dmsa, "\xc2\xb0", 'd'); // U+00b0 degree symbol
32  replace(dmsa, "\xc2\xba", 'd'); // U+00ba alt symbol
33  replace(dmsa, "\xe2\x81\xb0", 'd'); // U+2070 sup zero
34  replace(dmsa, "\xcb\x9a", 'd'); // U+02da ring above
35  replace(dmsa, "\xe2\x80\xb2", '\''); // U+2032 prime
36  replace(dmsa, "\xc2\xb4", '\''); // U+00b4 acute accent
37  replace(dmsa, "\xe2\x80\x99", '\''); // U+2019 right single quote
38  replace(dmsa, "\xe2\x80\xb3", '"'); // U+2033 double prime
39  replace(dmsa, "\xe2\x80\x9d", '"'); // U+201d right double quote
40  replace(dmsa, "\xe2\x88\x92", '-'); // U+2212 minus sign
41  replace(dmsa, "\xb0", 'd'); // 0xb0 bare degree symbol
42  replace(dmsa, "\xba", 'd'); // 0xba bare alt symbol
43  replace(dmsa, "\xb4", '\''); // 0xb4 bare acute accent
44  replace(dmsa, "''", '"'); // '' -> "
45  string::size_type
46  beg = 0,
47  end = unsigned(dmsa.size());
48  while (beg < end && isspace(dmsa[beg]))
49  ++beg;
50  while (beg < end && isspace(dmsa[end - 1]))
51  --end;
52  // The trimmed string in [beg, end)
53  real v = 0;
54  int i = 0;
55  flag ind1 = NONE;
56  // p is pointer to the next piece that needs decoding
57  for (string::size_type p = beg, pb; p < end; p = pb, ++i) {
58  string::size_type pa = p;
59  // Skip over initial hemisphere letter (for i == 0)
60  if (i == 0 && Utility::lookup(hemispheres_, dmsa[pa]) >= 0)
61  ++pa;
62  // Skip over initial sign (checking for it if i == 0)
63  if (i > 0 || (pa < end && Utility::lookup(signs_, dmsa[pa]) >= 0))
64  ++pa;
65  // Find next sign
66  pb = min(dmsa.find_first_of(signs_, pa), end);
67  flag ind2 = NONE;
68  v += InternalDecode(dmsa.substr(p, pb - p), ind2);
69  if (ind1 == NONE)
70  ind1 = ind2;
71  else if (!(ind2 == NONE || ind1 == ind2))
72  throw GeographicErr("Incompatible hemisphere specifies in " +
73  dmsa.substr(beg, pb - beg));
74  }
75  if (i == 0)
76  throw GeographicErr("Empty or incomplete DMS string " +
77  dmsa.substr(beg, end - beg));
78  ind = ind1;
79  return v;
80  }
81 
82  Math::real DMS::InternalDecode(const std::string& dmsa, flag& ind) {
83  string errormsg;
84  do { // Executed once (provides the ability to break)
85  int sign = 1;
86  unsigned
87  beg = 0,
88  end = unsigned(dmsa.size());
89  flag ind1 = NONE;
90  int k = -1;
91  if (end > beg && (k = Utility::lookup(hemispheres_, dmsa[beg])) >= 0) {
92  ind1 = (k / 2) ? LONGITUDE : LATITUDE;
93  sign = k % 2 ? 1 : -1;
94  ++beg;
95  }
96  if (end > beg && (k = Utility::lookup(hemispheres_, dmsa[end-1])) >= 0) {
97  if (k >= 0) {
98  if (ind1 != NONE) {
99  if (toupper(dmsa[beg - 1]) == toupper(dmsa[end - 1]))
100  errormsg = "Repeated hemisphere indicators "
101  + Utility::str(dmsa[beg - 1])
102  + " in " + dmsa.substr(beg - 1, end - beg + 1);
103  else
104  errormsg = "Contradictory hemisphere indicators "
105  + Utility::str(dmsa[beg - 1]) + " and "
106  + Utility::str(dmsa[end - 1]) + " in "
107  + dmsa.substr(beg - 1, end - beg + 1);
108  break;
109  }
110  ind1 = (k / 2) ? LONGITUDE : LATITUDE;
111  sign = k % 2 ? 1 : -1;
112  --end;
113  }
114  }
115  if (end > beg && (k = Utility::lookup(signs_, dmsa[beg])) >= 0) {
116  if (k >= 0) {
117  sign *= k ? 1 : -1;
118  ++beg;
119  }
120  }
121  if (end == beg) {
122  errormsg = "Empty or incomplete DMS string " + dmsa;
123  break;
124  }
125  real ipieces[] = {0, 0, 0};
126  real fpieces[] = {0, 0, 0};
127  unsigned npiece = 0;
128  real icurrent = 0;
129  real fcurrent = 0;
130  unsigned ncurrent = 0, p = beg;
131  bool pointseen = false;
132  unsigned digcount = 0, intcount = 0;
133  while (p < end) {
134  char x = dmsa[p++];
135  if ((k = Utility::lookup(digits_, x)) >= 0) {
136  ++ncurrent;
137  if (digcount > 0)
138  ++digcount; // Count of decimal digits
139  else {
140  icurrent = 10 * icurrent + k;
141  ++intcount;
142  }
143  } else if (x == '.') {
144  if (pointseen) {
145  errormsg = "Multiple decimal points in "
146  + dmsa.substr(beg, end - beg);
147  break;
148  }
149  pointseen = true;
150  digcount = 1;
151  } else if ((k = Utility::lookup(dmsindicators_, x)) >= 0) {
152  if (k >= 3) {
153  if (p == end) {
154  errormsg = "Illegal for : to appear at the end of " +
155  dmsa.substr(beg, end - beg);
156  break;
157  }
158  k = npiece;
159  }
160  if (unsigned(k) == npiece - 1) {
161  errormsg = "Repeated " + components_[k] +
162  " component in " + dmsa.substr(beg, end - beg);
163  break;
164  } else if (unsigned(k) < npiece) {
165  errormsg = components_[k] + " component follows "
166  + components_[npiece - 1] + " component in "
167  + dmsa.substr(beg, end - beg);
168  break;
169  }
170  if (ncurrent == 0) {
171  errormsg = "Missing numbers in " + components_[k] +
172  " component of " + dmsa.substr(beg, end - beg);
173  break;
174  }
175  if (digcount > 0) {
176  istringstream s(dmsa.substr(p - intcount - digcount - 1,
177  intcount + digcount));
178  s >> fcurrent;
179  icurrent = 0;
180  }
181  ipieces[k] = icurrent;
182  fpieces[k] = icurrent + fcurrent;
183  if (p < end) {
184  npiece = k + 1;
185  icurrent = fcurrent = 0;
186  ncurrent = digcount = intcount = 0;
187  }
188  } else if (Utility::lookup(signs_, x) >= 0) {
189  errormsg = "Internal sign in DMS string "
190  + dmsa.substr(beg, end - beg);
191  break;
192  } else {
193  errormsg = "Illegal character " + Utility::str(x) + " in DMS string "
194  + dmsa.substr(beg, end - beg);
195  break;
196  }
197  }
198  if (!errormsg.empty())
199  break;
200  if (Utility::lookup(dmsindicators_, dmsa[p - 1]) < 0) {
201  if (npiece >= 3) {
202  errormsg = "Extra text following seconds in DMS string "
203  + dmsa.substr(beg, end - beg);
204  break;
205  }
206  if (ncurrent == 0) {
207  errormsg = "Missing numbers in trailing component of "
208  + dmsa.substr(beg, end - beg);
209  break;
210  }
211  if (digcount > 0) {
212  istringstream s(dmsa.substr(p - intcount - digcount,
213  intcount + digcount));
214  s >> fcurrent;
215  icurrent = 0;
216  }
217  ipieces[npiece] = icurrent;
218  fpieces[npiece] = icurrent + fcurrent;
219  }
220  if (pointseen && digcount == 0) {
221  errormsg = "Decimal point in non-terminal component of "
222  + dmsa.substr(beg, end - beg);
223  break;
224  }
225  // Note that we accept 59.999999... even though it rounds to 60.
226  if (ipieces[1] >= 60 || fpieces[1] > 60 ) {
227  errormsg = "Minutes " + Utility::str(fpieces[1])
228  + " not in range [0, 60)";
229  break;
230  }
231  if (ipieces[2] >= 60 || fpieces[2] > 60) {
232  errormsg = "Seconds " + Utility::str(fpieces[2])
233  + " not in range [0, 60)";
234  break;
235  }
236  ind = ind1;
237  // Assume check on range of result is made by calling routine (which
238  // might be able to offer a better diagnostic).
239  return real(sign) *
240  ( fpieces[2] ? (60*(60*fpieces[0] + fpieces[1]) + fpieces[2]) / 3600 :
241  ( fpieces[1] ? (60*fpieces[0] + fpieces[1]) / 60 : fpieces[0] ) );
242  } while (false);
243  real val = Utility::nummatch<real>(dmsa);
244  if (val == 0)
245  throw GeographicErr(errormsg);
246  else
247  ind = NONE;
248  return val;
249  }
250 
251  void DMS::DecodeLatLon(const std::string& stra, const std::string& strb,
252  real& lat, real& lon,
253  bool longfirst) {
254  real a, b;
255  flag ia, ib;
256  a = Decode(stra, ia);
257  b = Decode(strb, ib);
258  if (ia == NONE && ib == NONE) {
259  // Default to lat, long unless longfirst
260  ia = longfirst ? LONGITUDE : LATITUDE;
261  ib = longfirst ? LATITUDE : LONGITUDE;
262  } else if (ia == NONE)
263  ia = flag(LATITUDE + LONGITUDE - ib);
264  else if (ib == NONE)
265  ib = flag(LATITUDE + LONGITUDE - ia);
266  if (ia == ib)
267  throw GeographicErr("Both " + stra + " and "
268  + strb + " interpreted as "
269  + (ia == LATITUDE ? "latitudes" : "longitudes"));
270  real
271  lat1 = ia == LATITUDE ? a : b,
272  lon1 = ia == LATITUDE ? b : a;
273  if (abs(lat1) > 90)
274  throw GeographicErr("Latitude " + Utility::str(lat1)
275  + "d not in [-90d, 90d]");
276  lat = lat1;
277  lon = lon1;
278  }
279 
280  Math::real DMS::DecodeAngle(const std::string& angstr) {
281  flag ind;
282  real ang = Decode(angstr, ind);
283  if (ind != NONE)
284  throw GeographicErr("Arc angle " + angstr
285  + " includes a hemisphere, N/E/W/S");
286  return ang;
287  }
288 
289  Math::real DMS::DecodeAzimuth(const std::string& azistr) {
290  flag ind;
291  real azi = Decode(azistr, ind);
292  if (ind == LATITUDE)
293  throw GeographicErr("Azimuth " + azistr
294  + " has a latitude hemisphere, N/S");
295  return Math::AngNormalize(azi);
296  }
297 
298  string DMS::Encode(real angle, component trailing, unsigned prec, flag ind,
299  char dmssep) {
300  // Assume check on range of input angle has been made by calling
301  // routine (which might be able to offer a better diagnostic).
302  if (!Math::isfinite(angle))
303  return angle < 0 ? string("-inf") :
304  (angle > 0 ? string("inf") : string("nan"));
305 
306  // 15 - 2 * trailing = ceiling(log10(2^53/90/60^trailing)).
307  // This suffices to give full real precision for numbers in [-90,90]
308  prec = min(15 + Math::extra_digits() - 2 * unsigned(trailing), prec);
309  real scale = 1;
310  for (unsigned i = 0; i < unsigned(trailing); ++i)
311  scale *= 60;
312  for (unsigned i = 0; i < prec; ++i)
313  scale *= 10;
314  if (ind == AZIMUTH)
315  angle -= floor(angle/360) * 360;
316  int sign = angle < 0 ? -1 : 1;
317  angle *= sign;
318 
319  // Break off integer part to preserve precision in manipulation of
320  // fractional part.
321  real
322  idegree = floor(angle),
323  fdegree = (angle - idegree) * scale + real(0.5);
324  {
325  // Implement the "round ties to even" rule
326  real f = floor(fdegree);
327  fdegree = (f == fdegree && fmod(f, real(2)) == 1) ? f - 1 : f;
328  }
329  fdegree /= scale;
330  if (fdegree >= 1) {
331  idegree += 1;
332  fdegree -= 1;
333  }
334  real pieces[3] = {fdegree, 0, 0};
335  for (unsigned i = 1; i <= unsigned(trailing); ++i) {
336  real
337  ip = floor(pieces[i - 1]),
338  fp = pieces[i - 1] - ip;
339  pieces[i] = fp * 60;
340  pieces[i - 1] = ip;
341  }
342  pieces[0] += idegree;
343  ostringstream s;
344  s << fixed << setfill('0');
345  if (ind == NONE && sign < 0)
346  s << '-';
347  switch (trailing) {
348  case DEGREE:
349  if (ind != NONE)
350  s << setw(1 + min(int(ind), 2) + prec + (prec ? 1 : 0));
351  s << Utility::str(pieces[0], prec);
352  // Don't include degree designator (d) if it is the trailing component.
353  break;
354  default:
355  if (ind != NONE)
356  s << setw(1 + min(int(ind), 2));
357  s << int(pieces[0])
358  << (dmssep ? dmssep : char(tolower(dmsindicators_[0])));
359  switch (trailing) {
360  case MINUTE:
361  s << setw(2 + prec + (prec ? 1 : 0)) << Utility::str(pieces[1], prec);
362  if (!dmssep)
363  s << char(tolower(dmsindicators_[1]));
364  break;
365  case SECOND:
366  s << setw(2)
367  << int(pieces[1])
368  << (dmssep ? dmssep : char(tolower(dmsindicators_[1])))
369  << setw(2 + prec + (prec ? 1 : 0)) << Utility::str(pieces[2], prec);
370  if (!dmssep)
371  s << char(tolower(dmsindicators_[2]));
372  break;
373  default:
374  break;
375  }
376  }
377  if (ind != NONE && ind != AZIMUTH)
378  s << hemispheres_[(ind == LATITUDE ? 0 : 2) + (sign < 0 ? 0 : 1)];
379  return s.str();
380  }
381 
382 } // namespace GeographicLib
static T AngNormalize(T x)
Definition: Math.hpp:451
static Math::real DecodeAngle(const std::string &angstr)
Definition: DMS.cpp:280
GeographicLib::Math::real real
Definition: GeodSolve.cpp:32
Header for GeographicLib::Utility class.
static bool isfinite(T x)
Definition: Math.hpp:768
static int extra_digits()
Definition: Math.hpp:187
static std::string Encode(real angle, component trailing, unsigned prec, flag ind=NONE, char dmssep=char(0))
Definition: DMS.cpp:298
static Math::real DecodeAzimuth(const std::string &azistr)
Definition: DMS.cpp:289
static Math::real Decode(const std::string &dms, flag &ind)
Definition: DMS.cpp:28
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
static std::string str(T x, int p=-1)
Definition: Utility.hpp:276
static void DecodeLatLon(const std::string &dmsa, const std::string &dmsb, real &lat, real &lon, bool longfirst=false)
Definition: DMS.cpp:251
Exception handling for GeographicLib.
Definition: Constants.hpp:386
static int lookup(const std::string &s, char c)
Definition: Utility.hpp:407
Header for GeographicLib::DMS class.