GeographicLib  1.49
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-2017) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * https://geographiclib.sourceforge.io/
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 char* const DMS::hemispheres_ = "SNWE";
23  const char* const DMS::signs_ = "-+";
24  const char* const DMS::digits_ = "0123456789";
25  const char* const DMS::dmsindicators_ = "D'\":";
26  const char* const DMS::components_[] = {"degrees", "minutes", "seconds"};
27 
28  Math::real DMS::Decode(const std::string& dms, flag& ind) {
29  string dmsa = dms;
30  replace(dmsa, "\xc2\xb0", 'd'); // U+00b0 degree symbol
31  replace(dmsa, "\xc2\xba", 'd'); // U+00ba alt symbol
32  replace(dmsa, "\xe2\x81\xb0", 'd'); // U+2070 sup zero
33  replace(dmsa, "\xcb\x9a", 'd'); // U+02da ring above
34  replace(dmsa, "\xe2\x80\xb2", '\''); // U+2032 prime
35  replace(dmsa, "\xc2\xb4", '\''); // U+00b4 acute accent
36  replace(dmsa, "\xe2\x80\x99", '\''); // U+2019 right single quote
37  replace(dmsa, "\xe2\x80\xb3", '"'); // U+2033 double prime
38  replace(dmsa, "\xe2\x80\x9d", '"'); // U+201d right double quote
39  replace(dmsa, "\xe2\x88\x92", '-'); // U+2212 minus sign
40  replace(dmsa, "\xb0", 'd'); // 0xb0 bare degree symbol
41  replace(dmsa, "\xba", 'd'); // 0xba bare alt symbol
42  replace(dmsa, "\xb4", '\''); // 0xb4 bare acute accent
43  replace(dmsa, "''", '"'); // '' -> "
44  string::size_type
45  beg = 0,
46  end = unsigned(dmsa.size());
47  while (beg < end && isspace(dmsa[beg]))
48  ++beg;
49  while (beg < end && isspace(dmsa[end - 1]))
50  --end;
51  // The trimmed string in [beg, end)
52  real v = 0;
53  int i = 0;
54  flag ind1 = NONE;
55  // p is pointer to the next piece that needs decoding
56  for (string::size_type p = beg, pb; p < end; p = pb, ++i) {
57  string::size_type pa = p;
58  // Skip over initial hemisphere letter (for i == 0)
59  if (i == 0 && Utility::lookup(hemispheres_, dmsa[pa]) >= 0)
60  ++pa;
61  // Skip over initial sign (checking for it if i == 0)
62  if (i > 0 || (pa < end && Utility::lookup(signs_, dmsa[pa]) >= 0))
63  ++pa;
64  // Find next sign
65  pb = min(dmsa.find_first_of(signs_, pa), end);
66  flag ind2 = NONE;
67  v += InternalDecode(dmsa.substr(p, pb - p), ind2);
68  if (ind1 == NONE)
69  ind1 = ind2;
70  else if (!(ind2 == NONE || ind1 == ind2))
71  throw GeographicErr("Incompatible hemisphere specifies in " +
72  dmsa.substr(beg, pb - beg));
73  }
74  if (i == 0)
75  throw GeographicErr("Empty or incomplete DMS string " +
76  dmsa.substr(beg, end - beg));
77  ind = ind1;
78  return v;
79  }
80 
81  Math::real DMS::InternalDecode(const std::string& dmsa, flag& ind) {
82  const int maxcomponents = 3;
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[maxcomponents] = {0, 0, 0};
126  real fpieces[maxcomponents] = {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 >= maxcomponents) {
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 " + string(components_[k]) +
162  " component in " + dmsa.substr(beg, end - beg);
163  break;
164  } else if (unsigned(k) < npiece) {
165  errormsg = string(components_[k]) + " component follows "
166  + string(components_[npiece - 1]) + " component in "
167  + dmsa.substr(beg, end - beg);
168  break;
169  }
170  if (ncurrent == 0) {
171  errormsg = "Missing numbers in " + string(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  if (npiece >= maxcomponents) {
186  errormsg = "More than 3 DMS components in "
187  + dmsa.substr(beg, end - beg);
188  break;
189  }
190  icurrent = fcurrent = 0;
191  ncurrent = digcount = intcount = 0;
192  }
193  } else if (Utility::lookup(signs_, x) >= 0) {
194  errormsg = "Internal sign in DMS string "
195  + dmsa.substr(beg, end - beg);
196  break;
197  } else {
198  errormsg = "Illegal character " + Utility::str(x) + " in DMS string "
199  + dmsa.substr(beg, end - beg);
200  break;
201  }
202  }
203  if (!errormsg.empty())
204  break;
205  if (Utility::lookup(dmsindicators_, dmsa[p - 1]) < 0) {
206  if (npiece >= maxcomponents) {
207  errormsg = "Extra text following seconds in DMS string "
208  + dmsa.substr(beg, end - beg);
209  break;
210  }
211  if (ncurrent == 0) {
212  errormsg = "Missing numbers in trailing component of "
213  + dmsa.substr(beg, end - beg);
214  break;
215  }
216  if (digcount > 0) {
217  istringstream s(dmsa.substr(p - intcount - digcount,
218  intcount + digcount));
219  s >> fcurrent;
220  icurrent = 0;
221  }
222  ipieces[npiece] = icurrent;
223  fpieces[npiece] = icurrent + fcurrent;
224  }
225  if (pointseen && digcount == 0) {
226  errormsg = "Decimal point in non-terminal component of "
227  + dmsa.substr(beg, end - beg);
228  break;
229  }
230  // Note that we accept 59.999999... even though it rounds to 60.
231  if (ipieces[1] >= 60 || fpieces[1] > 60 ) {
232  errormsg = "Minutes " + Utility::str(fpieces[1])
233  + " not in range [0, 60)";
234  break;
235  }
236  if (ipieces[2] >= 60 || fpieces[2] > 60) {
237  errormsg = "Seconds " + Utility::str(fpieces[2])
238  + " not in range [0, 60)";
239  break;
240  }
241  ind = ind1;
242  // Assume check on range of result is made by calling routine (which
243  // might be able to offer a better diagnostic).
244  return real(sign) *
245  ( fpieces[2] != 0 ?
246  (60*(60*fpieces[0] + fpieces[1]) + fpieces[2]) / 3600 :
247  ( fpieces[1] != 0 ?
248  (60*fpieces[0] + fpieces[1]) / 60 : fpieces[0] ) );
249  } while (false);
250  real val = Utility::nummatch<real>(dmsa);
251  if (val == 0)
252  throw GeographicErr(errormsg);
253  else
254  ind = NONE;
255  return val;
256  }
257 
258  void DMS::DecodeLatLon(const std::string& stra, const std::string& strb,
259  real& lat, real& lon,
260  bool longfirst) {
261  real a, b;
262  flag ia, ib;
263  a = Decode(stra, ia);
264  b = Decode(strb, ib);
265  if (ia == NONE && ib == NONE) {
266  // Default to lat, long unless longfirst
267  ia = longfirst ? LONGITUDE : LATITUDE;
268  ib = longfirst ? LATITUDE : LONGITUDE;
269  } else if (ia == NONE)
270  ia = flag(LATITUDE + LONGITUDE - ib);
271  else if (ib == NONE)
272  ib = flag(LATITUDE + LONGITUDE - ia);
273  if (ia == ib)
274  throw GeographicErr("Both " + stra + " and "
275  + strb + " interpreted as "
276  + (ia == LATITUDE ? "latitudes" : "longitudes"));
277  real
278  lat1 = ia == LATITUDE ? a : b,
279  lon1 = ia == LATITUDE ? b : a;
280  if (abs(lat1) > 90)
281  throw GeographicErr("Latitude " + Utility::str(lat1)
282  + "d not in [-90d, 90d]");
283  lat = lat1;
284  lon = lon1;
285  }
286 
287  Math::real DMS::DecodeAngle(const std::string& angstr) {
288  flag ind;
289  real ang = Decode(angstr, ind);
290  if (ind != NONE)
291  throw GeographicErr("Arc angle " + angstr
292  + " includes a hemisphere, N/E/W/S");
293  return ang;
294  }
295 
296  Math::real DMS::DecodeAzimuth(const std::string& azistr) {
297  flag ind;
298  real azi = Decode(azistr, ind);
299  if (ind == LATITUDE)
300  throw GeographicErr("Azimuth " + azistr
301  + " has a latitude hemisphere, N/S");
302  return Math::AngNormalize(azi);
303  }
304 
305  string DMS::Encode(real angle, component trailing, unsigned prec, flag ind,
306  char dmssep) {
307  // Assume check on range of input angle has been made by calling
308  // routine (which might be able to offer a better diagnostic).
309  if (!Math::isfinite(angle))
310  return angle < 0 ? string("-inf") :
311  (angle > 0 ? string("inf") : string("nan"));
312 
313  // 15 - 2 * trailing = ceiling(log10(2^53/90/60^trailing)).
314  // This suffices to give full real precision for numbers in [-90,90]
315  prec = min(15 + Math::extra_digits() - 2 * unsigned(trailing), prec);
316  real scale = 1;
317  for (unsigned i = 0; i < unsigned(trailing); ++i)
318  scale *= 60;
319  for (unsigned i = 0; i < prec; ++i)
320  scale *= 10;
321  if (ind == AZIMUTH)
322  angle -= floor(angle/360) * 360;
323  int sign = angle < 0 ? -1 : 1;
324  angle *= sign;
325 
326  // Break off integer part to preserve precision in manipulation of
327  // fractional part.
328  real
329  idegree = floor(angle),
330  fdegree = (angle - idegree) * scale + real(0.5);
331  {
332  // Implement the "round ties to even" rule
333  real f = floor(fdegree);
334  fdegree = (f == fdegree && fmod(f, real(2)) == 1) ? f - 1 : f;
335  }
336  fdegree /= scale;
337  if (fdegree >= 1) {
338  idegree += 1;
339  fdegree -= 1;
340  }
341  real pieces[3] = {fdegree, 0, 0};
342  for (unsigned i = 1; i <= unsigned(trailing); ++i) {
343  real
344  ip = floor(pieces[i - 1]),
345  fp = pieces[i - 1] - ip;
346  pieces[i] = fp * 60;
347  pieces[i - 1] = ip;
348  }
349  pieces[0] += idegree;
350  ostringstream s;
351  s << fixed << setfill('0');
352  if (ind == NONE && sign < 0)
353  s << '-';
354  switch (trailing) {
355  case DEGREE:
356  if (ind != NONE)
357  s << setw(1 + min(int(ind), 2) + prec + (prec ? 1 : 0));
358  s << Utility::str(pieces[0], prec);
359  // Don't include degree designator (d) if it is the trailing component.
360  break;
361  default:
362  if (ind != NONE)
363  s << setw(1 + min(int(ind), 2));
364  s << int(pieces[0])
365  << (dmssep ? dmssep : char(tolower(dmsindicators_[0])));
366  switch (trailing) {
367  case MINUTE:
368  s << setw(2 + prec + (prec ? 1 : 0)) << Utility::str(pieces[1], prec);
369  if (!dmssep)
370  s << char(tolower(dmsindicators_[1]));
371  break;
372  case SECOND:
373  s << setw(2)
374  << int(pieces[1])
375  << (dmssep ? dmssep : char(tolower(dmsindicators_[1])))
376  << setw(2 + prec + (prec ? 1 : 0)) << Utility::str(pieces[2], prec);
377  if (!dmssep)
378  s << char(tolower(dmsindicators_[2]));
379  break;
380  default:
381  break;
382  }
383  }
384  if (ind != NONE && ind != AZIMUTH)
385  s << hemispheres_[(ind == LATITUDE ? 0 : 2) + (sign < 0 ? 0 : 1)];
386  return s.str();
387  }
388 
389 } // namespace GeographicLib
real
GeographicLib::Math::real real
Definition: GeodSolve.cpp:31
GeographicLib::Math::AngNormalize
static T AngNormalize(T x)
Definition: Math.hpp:440
GeographicLib::Math::extra_digits
static int extra_digits()
Definition: Math.hpp:187
GeographicLib::Utility::str
static std::string str(T x, int p=-1)
Definition: Utility.hpp:276
GeographicLib
Namespace for GeographicLib.
Definition: Accumulator.cpp:12
GeographicLib::DMS::DecodeLatLon
static void DecodeLatLon(const std::string &dmsa, const std::string &dmsb, real &lat, real &lon, bool longfirst=false)
Definition: DMS.cpp:258
GeographicLib::DMS::DecodeAngle
static Math::real DecodeAngle(const std::string &angstr)
Definition: DMS.cpp:287
GeographicLib::Math::isfinite
static bool isfinite(T x)
Definition: Math.hpp:806
GeographicLib::DMS::Decode
static Math::real Decode(const std::string &dms, flag &ind)
Definition: DMS.cpp:28
GeographicLib::GeographicErr
Exception handling for GeographicLib.
Definition: Constants.hpp:389
GeographicLib::Utility::lookup
static int lookup(const std::string &s, char c)
Definition: Utility.hpp:459
GeographicLib::Math::real
double real
Definition: Math.hpp:129
GeographicLib::DMS::Encode
static std::string Encode(real angle, component trailing, unsigned prec, flag ind=NONE, char dmssep=char(0))
Definition: DMS.cpp:305
Utility.hpp
Header for GeographicLib::Utility class.
GeographicLib::DMS::flag
flag
Definition: DMS.hpp:41
GeographicLib::DMS::component
component
Definition: DMS.hpp:73
std
Definition: NearestNeighbor.hpp:814
GeographicLib::DMS::DecodeAzimuth
static Math::real DecodeAzimuth(const std::string &azistr)
Definition: DMS.cpp:296
DMS.hpp
Header for GeographicLib::DMS class.