Debian Codegraph @

metar/Datatypes.py

raw symbols SCIP
1 # Copyright (c) 2004,2018 Python-Metar Developers.
2 # Distributed under the terms of the BSD 2-Clause License.
3 # SPDX-License-Identifier: BSD-2-Clause
4 """Python classes to represent dimensioned quantities used in weather reports."""
5 import re
6 from math import pi, sin, cos, atan2
7
8 # exceptions
9
10
11 class UnitsError(Exception):
12 """Exception raised when unrecognized units are used."""
13
14 pass
15
16
17 # regexp to match fractions (used by distance class)
18 # [Note: numerator of fraction must be single digit.]
19
20 FRACTION_RE = re.compile(r"^((?P<int>\d+)\s*)?(?P<num>\d)/(?P<den>\d+)$")
21
22 # classes representing dimensioned values in METAR reports
23
24
25 class temperature(object):
26 """A class representing a temperature value."""
27
28 legal_units = ["F", "C", "K"]
29
30 def __init__(self, value, units="C"):
31 if not units.upper() in temperature.legal_units:
32 raise UnitsError("unrecognized temperature unit: '" + units + "'")
33 self._units = units.upper()
34 try:
35 self._value = float(value)
36 except ValueError:
37 if value.startswith("M"):
38 self._value = -float(value[1:])
39 else:
40 raise ValueError("temperature must be integer: '" + str(value) + "'")
41
42 def __str__(self):
43 return self.string()
44
45 def value(self, units=None):
46 """Return the temperature in the specified units."""
47 if units is None:
48 return self._value
49 else:
50 if not units.upper() in temperature.legal_units:
51 raise UnitsError("unrecognized temperature unit: '" + units + "'")
52 units = units.upper()
53 if self._units == "C":
54 celsius_value = self._value
55 elif self._units == "F":
56 celsius_value = (self._value - 32.0) / 1.8
57 elif self._units == "K":
58 celsius_value = self._value - 273.15
59 if units == "C":
60 return celsius_value
61 elif units == "K":
62 return 273.15 + celsius_value
63 elif units == "F":
64 return 32.0 + celsius_value * 1.8
65
66 def string(self, units=None):
67 """Return a string representation of the temperature, using the given units."""
68 if units is None:
69 units = self._units
70 else:
71 if not units.upper() in temperature.legal_units:
72 raise UnitsError("unrecognized temperature unit: '" + units + "'")
73 units = units.upper()
74 val = self.value(units)
75 if units == "C":
76 return "%.1f C" % val
77 elif units == "F":
78 return "%.1f F" % val
79 elif units == "K":
80 return "%.1f K" % val
81
82
83 class pressure(object):
84 """A class representing a barometric pressure value."""
85
86 legal_units = ["MB", "HPA", "IN"]
87
88 def __init__(self, value, units="HPA"):
89 if not units.upper() in pressure.legal_units:
90 raise UnitsError("unrecognized pressure unit: '" + units + "'")
91 self._value = float(value)
92 self._units = units.upper()
93
94 def __str__(self):
95 return self.string()
96
97 def value(self, units=None):
98 """Return the pressure in the specified units."""
99 if units is None:
100 return self._value
101 else:
102 if not units.upper() in pressure.legal_units:
103 raise UnitsError("unrecognized pressure unit: '" + units + "'")
104 units = units.upper()
105 if units == self._units:
106 return self._value
107 if self._units == "IN":
108 hpa_value = self._value * 33.86398
109 else:
110 hpa_value = self._value
111 if units == "HPA" or units == "MB":
112 return hpa_value
113 elif units == "IN":
114 return hpa_value / 33.86398
115 else:
116 raise UnitsError("unrecognized pressure unit: '" + units + "'")
117
118 def string(self, units=None):
119 """Return a string representation of the pressure, using the given units."""
120 if not units:
121 units = self._units
122 else:
123 if units.upper() not in pressure.legal_units:
124 raise UnitsError("unrecognized pressure unit: '" + units + "'")
125 units = units.upper()
126 val = self.value(units)
127 if units == "HPA":
128 return "%.1f hPa" % val
129 elif units == "MB":
130 return "%.1f mb" % val
131 elif units == "IN":
132 return "%.2f inches" % val
133
134
135 class speed(object):
136 """A class representing a wind speed value."""
137
138 legal_units = ["KT", "MPS", "KMH", "MPH"]
139 legal_gtlt = [">", "<"]
140
141 def __init__(self, value, units=None, gtlt=None):
142 if not units:
143 self._units = "MPS"
144 else:
145 if units.upper() not in speed.legal_units:
146 raise UnitsError("unrecognized speed unit: '" + units + "'")
147 self._units = units.upper()
148 if gtlt and gtlt not in speed.legal_gtlt:
149 raise ValueError(
150 "unrecognized greater-than/less-than symbol: '" + gtlt + "'"
151 )
152 self._gtlt = gtlt
153 self._value = float(value)
154
155 def __str__(self):
156 return self.string()
157
158 def value(self, units=None):
159 """Return the speed in the specified units."""
160 if not units:
161 return self._value
162 else:
163 if not units.upper() in speed.legal_units:
164 raise UnitsError("unrecognized speed unit: '" + units + "'")
165 units = units.upper()
166 if units == self._units:
167 return self._value
168 if self._units == "KMH":
169 mps_value = self._value / 3.6
170 elif self._units == "KT":
171 mps_value = self._value * 0.514444
172 elif self._units == "MPH":
173 mps_value = self._value * 0.447000
174 else:
175 mps_value = self._value
176 if units == "KMH":
177 return mps_value * 3.6
178 elif units == "KT":
179 return mps_value / 0.514444
180 elif units == "MPH":
181 return mps_value / 0.447000
182 elif units == "MPS":
183 return mps_value
184
185 def string(self, units=None):
186 """Return a string representation of the speed in the given units."""
187 if not units:
188 units = self._units
189 else:
190 if units.upper() not in speed.legal_units:
191 raise UnitsError("unrecognized speed unit: '" + units + "'")
192 units = units.upper()
193 val = self.value(units)
194 if units == "KMH":
195 text = "%.0f km/h" % val
196 elif units == "KT":
197 text = "%.0f knots" % val
198 elif units == "MPH":
199 text = "%.0f mph" % val
200 elif units == "MPS":
201 text = "%.0f mps" % val
202 if self._gtlt == ">":
203 text = "greater than " + text
204 elif self._gtlt == "<":
205 text = "less than " + text
206 return text
207
208
209 class distance(object):
210 """A class representing a distance value."""
211
212 legal_units = ["SM", "MI", "M", "KM", "FT", "IN"]
213 legal_gtlt = [">", "<"]
214
215 def __init__(self, value, units=None, gtlt=None):
216 if not units:
217 self._units = "M"
218 else:
219 if units.upper() not in distance.legal_units:
220 raise UnitsError("unrecognized distance unit: '" + units + "'")
221 self._units = units.upper()
222
223 try:
224 if value.startswith("M"):
225 value = value[1:]
226 gtlt = "<"
227 elif value.startswith("P"):
228 value = value[1:]
229 gtlt = ">"
230 except:
231 pass
232 if gtlt and gtlt not in distance.legal_gtlt:
233 raise ValueError(
234 "unrecognized greater-than/less-than symbol: '" + gtlt + "'"
235 )
236 self._gtlt = gtlt
237 try:
238 self._value = float(value)
239 self._num = None
240 self._den = None
241 except ValueError:
242 mf = FRACTION_RE.match(value)
243 if not mf:
244 raise ValueError("distance is not parseable: '" + str(value) + "'")
245 df = mf.groupdict()
246 self._num = int(df["num"])
247 self._den = int(df["den"])
248 self._value = float(self._num) / float(self._den)
249 if df["int"]:
250 self._value += float(df["int"])
251
252 def __str__(self):
253 return self.string()
254
255 def value(self, units=None):
256 """Return the distance in the specified units."""
257 if not units:
258 return self._value
259 else:
260 if not units.upper() in distance.legal_units:
261 raise UnitsError("unrecognized distance unit: '" + units + "'")
262 units = units.upper()
263 if units == self._units:
264 return self._value
265 if self._units == "SM" or self._units == "MI":
266 m_value = self._value * 1609.344
267 elif self._units == "FT":
268 m_value = self._value / 3.28084
269 elif self._units == "IN":
270 m_value = self._value / 39.3701
271 elif self._units == "KM":
272 m_value = self._value * 1000
273 else:
274 m_value = self._value
275 if units == "SM" or units == "MI":
276 return m_value / 1609.344
277 elif units == "FT":
278 return m_value * 3.28084
279 elif units == "IN":
280 return m_value * 39.3701
281 elif units == "KM":
282 return m_value / 1000
283 elif units == "M":
284 return m_value
285
286 def string(self, units=None):
287 """Return a string representation of the distance in the given units."""
288 if not units:
289 units = self._units
290 else:
291 if not units.upper() in distance.legal_units:
292 raise UnitsError("unrecognized distance unit: '" + units + "'")
293 units = units.upper()
294 if self._num and self._den and units == self._units:
295 val = int(self._value - self._num / self._den)
296 if val:
297 text = "%d %d/%d" % (val, self._num, self._den)
298 else:
299 text = "%d/%d" % (self._num, self._den)
300 else:
301 if units == "KM":
302 text = "%.1f" % self.value(units)
303 else:
304 text = "%.0f" % self.value(units)
305 if units == "SM" or units == "MI":
306 text += " miles"
307 elif units == "M":
308 text += " meters"
309 elif units == "KM":
310 text += " km"
311 elif units == "FT":
312 text += " feet"
313 elif units == "IN":
314 text += " inches"
315 if self._gtlt == ">":
316 text = "greater than " + text
317 elif self._gtlt == "<":
318 text = "less than " + text
319 return text
320
321
322 class direction(object):
323 """A class representing a compass direction."""
324
325 compass_dirs = {
326 "N": 0.0,
327 "NNE": 22.5,
328 "NE": 45.0,
329 "ENE": 67.5,
330 "E": 90.0,
331 "ESE": 112.5,
332 "SE": 135.0,
333 "SSE": 157.5,
334 "S": 180.0,
335 "SSW": 202.5,
336 "SW": 225.0,
337 "WSW": 247.5,
338 "W": 270.0,
339 "WNW": 292.5,
340 "NW": 315.0,
341 "NNW": 337.5,
342 }
343
344 def __init__(self, d):
345 if d in direction.compass_dirs:
346 self._compass = d
347 self._degrees = direction.compass_dirs[d]
348 else:
349 self._compass = None
350 value = float(d)
351 if value < 0.0 or value > 360.0:
352 raise ValueError("direction must be 0..360: '" + str(value) + "'")
353 self._degrees = value
354
355 def __str__(self):
356 return self.string()
357
358 def value(self):
359 """Return the numerical direction, in degrees."""
360 return self._degrees
361
362 def string(self):
363 """Return a string representation of the numerical direction."""
364 return "%.0f degrees" % self._degrees
365
366 def compass(self):
367 """Return the compass direction, e.g., "N", "ESE", etc.)."""
368 if not self._compass:
369 degrees = 22.5 * round(self._degrees / 22.5)
370 if degrees == 360.0:
371 self._compass = "N"
372 else:
373 for name, d in direction.compass_dirs.items():
374 if d == degrees:
375 self._compass = name
376 break
377 return self._compass
378
379
380 class precipitation(object):
381 """A class representing a precipitation value."""
382
383 legal_units = ["IN", "CM"]
384 legal_gtlt = [">", "<"]
385
386 def __init__(self, value, units=None, gtlt=None):
387 if not units:
388 self._units = "IN"
389 else:
390 if not units.upper() in precipitation.legal_units:
391 raise UnitsError("unrecognized precipitation unit: '" + units + "'")
392 self._units = units.upper()
393
394 try:
395 if value.startswith("M"):
396 value = value[1:]
397 gtlt = "<"
398 elif value.startswith("P"):
399 value = value[1:]
400 gtlt = ">"
401 except:
402 pass
403 if gtlt and gtlt not in precipitation.legal_gtlt:
404 raise ValueError(
405 "unrecognized greater-than/less-than symbol: '" + gtlt + "'"
406 )
407 self._gtlt = gtlt
408 self._value = float(value)
409 # In METAR world, a string of just four or three zeros denotes trace
410 self._istrace = value in ["0000", "000"]
411
412 def __str__(self):
413 return self.string()
414
415 def value(self, units=None):
416 """Return the precipitation in the specified units."""
417 if not units:
418 return self._value
419 else:
420 if not units.upper() in precipitation.legal_units:
421 raise UnitsError("unrecognized precipitation unit: '" + units + "'")
422 units = units.upper()
423 if units == self._units:
424 return self._value
425 if self._units == "CM":
426 i_value = self._value * 2.54
427 else:
428 i_value = self._value
429 if units == "CM":
430 return i_value * 2.54
431 else:
432 return i_value
433
434 def string(self, units=None):
435 """Return a string representation of the precipitation in the given units."""
436 if not units:
437 units = self._units
438 else:
439 if not units.upper() in precipitation.legal_units:
440 raise UnitsError("unrecognized precipitation unit: '" + units + "'")
441 units = units.upper()
442 # A trace is a trace in any units
443 if self._istrace:
444 return "Trace"
445 text = "%.2f" % self.value(units)
446 if units == "CM":
447 text += "cm"
448 else:
449 text += "in"
450 if self._gtlt == ">":
451 text = "greater than " + text
452 elif self._gtlt == "<":
453 text = "less than " + text
454 return text
455
456 def istrace(self):
457 """Return a boolean on if this precipitation was a trace"""
458 return self._istrace
459
460
461 class position(object):
462 """A class representing a location on the earth's surface."""
463
464 def __init__(self, latitude=None, longitude=None):
465 self.latitude = latitude
466 self.longitude = longitude
467
468 def __str__(self):
469 return self.string()
470
471 def getdirection(self, position2):
472 """
473 Calculate the initial direction to another location. (The direction
474 typically changes as you trace the great circle path to that location.)
475 See <http://www.movable-type.co.uk/scripts/LatLong.html>.
476 """
477 lat1 = self.latitude
478 long1 = self.longitude
479 lat2 = position2.latitude
480 long2 = position2.longitude
481 s = -sin(long1 - long2) * cos(lat2)
482 c = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(long1 - long2)
483 d = atan2(s, c) * 180.0 / pi
484 if d < 0.0:
485 d += 360.0
486 return direction(d)