| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Licensed under a 3-clause BSD style license - see astropy's LICENSE.rst |
| 3 |
# |
| 4 |
# We include this file here since astropy shoved it around an eventually |
| 5 |
# dropped it without much of a comment. Hunting after the functions |
| 6 |
# included here simply became too tedious. |
| 7 |
|
| 8 |
""" |
| 9 |
This module contains formatting functions that are for internal use in |
| 10 |
astropy.coordinates.angles. Mainly they are conversions from one format |
| 11 |
of data to another. |
| 12 |
""" |
| 13 |
|
| 14 |
from warnings import warn |
| 15 |
|
| 16 |
import numpy as np |
| 17 |
|
| 18 |
from astropy.utils.exceptions import AstropyWarning |
| 19 |
from astropy.utils import format_exception |
| 20 |
from astropy import units as u |
| 21 |
|
| 22 |
|
| 23 |
class RangeError(ValueError): |
| 24 |
""" |
| 25 |
Raised when some part of an angle is out of its valid range. |
| 26 |
""" |
| 27 |
|
| 28 |
|
| 29 |
class BoundsError(RangeError): |
| 30 |
""" |
| 31 |
Raised when an angle is outside of its user-specified bounds. |
| 32 |
""" |
| 33 |
|
| 34 |
|
| 35 |
class IllegalHourError(RangeError): |
| 36 |
""" |
| 37 |
Raised when an hour value is not in the range [0,24). |
| 38 |
|
| 39 |
Parameters |
| 40 |
---------- |
| 41 |
hour : int, float |
| 42 |
|
| 43 |
Examples |
| 44 |
-------- |
| 45 |
|
| 46 |
.. code-block:: python |
| 47 |
|
| 48 |
if not 0 <= hr < 24: |
| 49 |
raise IllegalHourError(hour) |
| 50 |
""" |
| 51 |
def __init__(self, hour): |
| 52 |
self.hour = hour |
| 53 |
|
| 54 |
def __str__(self): |
| 55 |
return f"An invalid value for 'hours' was found ('{self.hour}'); must be in the range [0,24)." |
| 56 |
|
| 57 |
|
| 58 |
class IllegalHourWarning(AstropyWarning): |
| 59 |
""" |
| 60 |
Raised when an hour value is 24. |
| 61 |
|
| 62 |
Parameters |
| 63 |
---------- |
| 64 |
hour : int, float |
| 65 |
""" |
| 66 |
def __init__(self, hour, alternativeactionstr=None): |
| 67 |
self.hour = hour |
| 68 |
self.alternativeactionstr = alternativeactionstr |
| 69 |
|
| 70 |
def __str__(self): |
| 71 |
message = f"'hour' was found to be '{self.hour}', which is not in range (-24, 24)." |
| 72 |
if self.alternativeactionstr is not None: |
| 73 |
message += ' ' + self.alternativeactionstr |
| 74 |
return message |
| 75 |
|
| 76 |
|
| 77 |
class IllegalMinuteError(RangeError): |
| 78 |
""" |
| 79 |
Raised when an minute value is not in the range [0,60]. |
| 80 |
|
| 81 |
Parameters |
| 82 |
---------- |
| 83 |
minute : int, float |
| 84 |
|
| 85 |
Examples |
| 86 |
-------- |
| 87 |
|
| 88 |
.. code-block:: python |
| 89 |
|
| 90 |
if not 0 <= min < 60: |
| 91 |
raise IllegalMinuteError(minute) |
| 92 |
|
| 93 |
""" |
| 94 |
def __init__(self, minute): |
| 95 |
self.minute = minute |
| 96 |
|
| 97 |
def __str__(self): |
| 98 |
return f"An invalid value for 'minute' was found ('{self.minute}'); should be in the range [0,60)." |
| 99 |
|
| 100 |
|
| 101 |
class IllegalMinuteWarning(AstropyWarning): |
| 102 |
""" |
| 103 |
Raised when a minute value is 60. |
| 104 |
|
| 105 |
Parameters |
| 106 |
---------- |
| 107 |
minute : int, float |
| 108 |
""" |
| 109 |
def __init__(self, minute, alternativeactionstr=None): |
| 110 |
self.minute = minute |
| 111 |
self.alternativeactionstr = alternativeactionstr |
| 112 |
|
| 113 |
def __str__(self): |
| 114 |
message = f"'minute' was found to be '{self.minute}', which is not in range [0,60)." |
| 115 |
if self.alternativeactionstr is not None: |
| 116 |
message += ' ' + self.alternativeactionstr |
| 117 |
return message |
| 118 |
|
| 119 |
|
| 120 |
class IllegalSecondError(RangeError): |
| 121 |
""" |
| 122 |
Raised when an second value (time) is not in the range [0,60]. |
| 123 |
|
| 124 |
Parameters |
| 125 |
---------- |
| 126 |
second : int, float |
| 127 |
|
| 128 |
Examples |
| 129 |
-------- |
| 130 |
|
| 131 |
.. code-block:: python |
| 132 |
|
| 133 |
if not 0 <= sec < 60: |
| 134 |
raise IllegalSecondError(second) |
| 135 |
""" |
| 136 |
def __init__(self, second): |
| 137 |
self.second = second |
| 138 |
|
| 139 |
def __str__(self): |
| 140 |
return f"An invalid value for 'second' was found ('{self.second}'); should be in the range [0,60)." |
| 141 |
|
| 142 |
|
| 143 |
class IllegalSecondWarning(AstropyWarning): |
| 144 |
""" |
| 145 |
Raised when a second value is 60. |
| 146 |
|
| 147 |
Parameters |
| 148 |
---------- |
| 149 |
second : int, float |
| 150 |
""" |
| 151 |
def __init__(self, second, alternativeactionstr=None): |
| 152 |
self.second = second |
| 153 |
self.alternativeactionstr = alternativeactionstr |
| 154 |
|
| 155 |
def __str__(self): |
| 156 |
message = f"'second' was found to be '{self.second}', which is not in range [0,60)." |
| 157 |
if self.alternativeactionstr is not None: |
| 158 |
message += ' ' + self.alternativeactionstr |
| 159 |
return message |
| 160 |
|
| 161 |
def _check_hour_range(hrs): |
| 162 |
""" |
| 163 |
Checks that the given value is in the range (-24, 24). |
| 164 |
""" |
| 165 |
if np.any(np.abs(hrs) == 24.): |
| 166 |
warn(IllegalHourWarning(hrs, 'Treating as 24 hr')) |
| 167 |
elif np.any(hrs < -24.) or np.any(hrs > 24.): |
| 168 |
raise IllegalHourError(hrs) |
| 169 |
|
| 170 |
|
| 171 |
def _check_minute_range(m): |
| 172 |
""" |
| 173 |
Checks that the given value is in the range [0,60]. If the value |
| 174 |
is equal to 60, then a warning is raised. |
| 175 |
""" |
| 176 |
if np.any(m == 60.): |
| 177 |
warn(IllegalMinuteWarning(m, 'Treating as 0 min, +1 hr/deg')) |
| 178 |
elif np.any(m < -60.) or np.any(m > 60.): |
| 179 |
# "Error: minutes not in range [-60,60) ({0}).".format(min)) |
| 180 |
raise IllegalMinuteError(m) |
| 181 |
|
| 182 |
|
| 183 |
def _check_second_range(sec): |
| 184 |
""" |
| 185 |
Checks that the given value is in the range [0,60]. If the value |
| 186 |
is equal to 60, then a warning is raised. |
| 187 |
""" |
| 188 |
if np.any(sec == 60.): |
| 189 |
warn(IllegalSecondWarning(sec, 'Treating as 0 sec, +1 min')) |
| 190 |
elif sec is None: |
| 191 |
pass |
| 192 |
elif np.any(sec < -60.) or np.any(sec > 60.): |
| 193 |
# "Error: seconds not in range [-60,60) ({0}).".format(sec)) |
| 194 |
raise IllegalSecondError(sec) |
| 195 |
|
| 196 |
|
| 197 |
def check_hms_ranges(h, m, s): |
| 198 |
""" |
| 199 |
Checks that the given hour, minute and second are all within |
| 200 |
reasonable range. |
| 201 |
""" |
| 202 |
_check_hour_range(h) |
| 203 |
_check_minute_range(m) |
| 204 |
_check_second_range(s) |
| 205 |
return None |
| 206 |
|
| 207 |
|
| 208 |
def degrees_to_dms(d): |
| 209 |
""" |
| 210 |
Convert a floating-point degree value into a ``(degree, arcminute, |
| 211 |
arcsecond)`` tuple. |
| 212 |
""" |
| 213 |
sign = np.copysign(1.0, d) |
| 214 |
|
| 215 |
(df, d) = np.modf(np.abs(d)) # (degree fraction, degree) |
| 216 |
(mf, m) = np.modf(df * 60.) # (minute fraction, minute) |
| 217 |
s = mf * 60. |
| 218 |
|
| 219 |
return np.floor(sign * d), sign * np.floor(m), sign * s |
| 220 |
|
| 221 |
|
| 222 |
def dms_to_degrees(d, m, s=None): |
| 223 |
""" |
| 224 |
Convert degrees, arcminute, arcsecond to a float degrees value. |
| 225 |
""" |
| 226 |
_check_minute_range(m) |
| 227 |
_check_second_range(s) |
| 228 |
|
| 229 |
# if d is a scaler |
| 230 |
d = np.atleast_1d(d) |
| 231 |
m = np.atleast_1d(m) |
| 232 |
s = np.atleast_1d(s) |
| 233 |
dmss = np.array([d,m,s]).T |
| 234 |
sign = [1 for dms in dmss] |
| 235 |
for k in range(0,dmss.size/3): |
| 236 |
# looking for first non zero |
| 237 |
for i in dmss[k]: |
| 238 |
if i!=0: |
| 239 |
sign[k] = np.copysign(1,i); break; |
| 240 |
|
| 241 |
|
| 242 |
try: |
| 243 |
d = np.floor(np.abs(d)) |
| 244 |
if s is None: |
| 245 |
m = np.abs(m) |
| 246 |
s = 0 |
| 247 |
else: |
| 248 |
m = np.floor(np.abs(m)) |
| 249 |
s = np.abs(s) |
| 250 |
except ValueError as err: |
| 251 |
raise ValueError(format_exception( |
| 252 |
"{func}: dms values ({1[0]},{2[1]},{3[2]}) could not be " |
| 253 |
"converted to numbers.", d, m, s)) from err |
| 254 |
|
| 255 |
return sign * (d + m / 60. + s / 3600.) |
| 256 |
|
| 257 |
|
| 258 |
def hms_to_hours(h, m, s=None): |
| 259 |
""" |
| 260 |
Convert hour, minute, second to a float hour value. |
| 261 |
""" |
| 262 |
|
| 263 |
check_hms_ranges(h, m, s) |
| 264 |
|
| 265 |
# determine sign |
| 266 |
sign = np.copysign(1.0, h) |
| 267 |
|
| 268 |
try: |
| 269 |
h = np.floor(np.abs(h)) |
| 270 |
if s is None: |
| 271 |
m = np.abs(m) |
| 272 |
s = 0 |
| 273 |
else: |
| 274 |
m = np.floor(np.abs(m)) |
| 275 |
s = np.abs(s) |
| 276 |
except ValueError as err: |
| 277 |
raise ValueError(format_exception( |
| 278 |
"{func}: HMS values ({1[0]},{2[1]},{3[2]}) could not be " |
| 279 |
"converted to numbers.", h, m, s)) from err |
| 280 |
|
| 281 |
return sign * (h + m / 60. + s / 3600.) |
| 282 |
|
| 283 |
|
| 284 |
def hms_to_degrees(h, m, s): |
| 285 |
""" |
| 286 |
Convert hour, minute, second to a float degrees value. |
| 287 |
""" |
| 288 |
|
| 289 |
return hms_to_hours(h, m, s) * 15. |
| 290 |
|
| 291 |
|
| 292 |
def hms_to_radians(h, m, s): |
| 293 |
""" |
| 294 |
Convert hour, minute, second to a float radians value. |
| 295 |
""" |
| 296 |
|
| 297 |
return u.degree.to(u.radian, hms_to_degrees(h, m, s)) |
| 298 |
|
| 299 |
|
| 300 |
def hms_to_dms(h, m, s): |
| 301 |
""" |
| 302 |
Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)`` |
| 303 |
tuple. |
| 304 |
""" |
| 305 |
|
| 306 |
return degrees_to_dms(hms_to_degrees(h, m, s)) |
| 307 |
|
| 308 |
|
| 309 |
def hours_to_decimal(h): |
| 310 |
""" |
| 311 |
Convert any parseable hour value into a float value. |
| 312 |
""" |
| 313 |
from . import angles |
| 314 |
return angles.Angle(h, unit=u.hourangle).hour |
| 315 |
|
| 316 |
|
| 317 |
def hours_to_radians(h): |
| 318 |
""" |
| 319 |
Convert an angle in Hours to Radians. |
| 320 |
""" |
| 321 |
|
| 322 |
return u.hourangle.to(u.radian, h) |
| 323 |
|
| 324 |
|
| 325 |
def hours_to_hms(h): |
| 326 |
""" |
| 327 |
Convert an floating-point hour value into an ``(hour, minute, |
| 328 |
second)`` tuple. |
| 329 |
""" |
| 330 |
|
| 331 |
sign = np.copysign(1.0, h) |
| 332 |
|
| 333 |
(hf, h) = np.modf(np.abs(h)) # (degree fraction, degree) |
| 334 |
(mf, m) = np.modf(hf * 60.0) # (minute fraction, minute) |
| 335 |
s = mf * 60.0 |
| 336 |
|
| 337 |
return (np.floor(sign * h), sign * np.floor(m), sign * s) |
| 338 |
|
| 339 |
|
| 340 |
def radians_to_degrees(r): |
| 341 |
""" |
| 342 |
Convert an angle in Radians to Degrees. |
| 343 |
""" |
| 344 |
return u.radian.to(u.degree, r) |
| 345 |
|
| 346 |
|
| 347 |
def radians_to_hours(r): |
| 348 |
""" |
| 349 |
Convert an angle in Radians to Hours. |
| 350 |
""" |
| 351 |
return u.radian.to(u.hourangle, r) |
| 352 |
|
| 353 |
|
| 354 |
def radians_to_hms(r): |
| 355 |
""" |
| 356 |
Convert an angle in Radians to an ``(hour, minute, second)`` tuple. |
| 357 |
""" |
| 358 |
|
| 359 |
hours = radians_to_hours(r) |
| 360 |
return hours_to_hms(hours) |
| 361 |
|
| 362 |
|
| 363 |
def radians_to_dms(r): |
| 364 |
""" |
| 365 |
Convert an angle in Radians to an ``(degree, arcminute, |
| 366 |
arcsecond)`` tuple. |
| 367 |
""" |
| 368 |
|
| 369 |
degrees = u.radian.to(u.degree, r) |
| 370 |
return degrees_to_dms(degrees) |
| 371 |
|
| 372 |
|
| 373 |
def sexagesimal_to_string(values, precision=None, pad=False, sep=(':',), |
| 374 |
fields=3): |
| 375 |
""" |
| 376 |
Given an already separated tuple of sexagesimal values, returns |
| 377 |
a string. |
| 378 |
|
| 379 |
See `hours_to_string` and `degrees_to_string` for a higher-level |
| 380 |
interface to this functionality. |
| 381 |
""" |
| 382 |
|
| 383 |
# Check to see if values[0] is negative, using np.copysign to handle -0 |
| 384 |
sign = np.copysign(1.0, values[0]) |
| 385 |
# If the coordinates are negative, we need to take the absolute values. |
| 386 |
# We use np.abs because abs(-0) is -0 |
| 387 |
# TODO: Is this true? (MHvK, 2018-02-01: not on my system) |
| 388 |
values = [np.abs(value) for value in values] |
| 389 |
|
| 390 |
if pad: |
| 391 |
if sign == -1: |
| 392 |
pad = 3 |
| 393 |
else: |
| 394 |
pad = 2 |
| 395 |
else: |
| 396 |
pad = 0 |
| 397 |
|
| 398 |
if not isinstance(sep, tuple): |
| 399 |
sep = tuple(sep) |
| 400 |
|
| 401 |
if fields < 1 or fields > 3: |
| 402 |
raise ValueError( |
| 403 |
"fields must be 1, 2, or 3") |
| 404 |
|
| 405 |
if not sep: # empty string, False, or None, etc. |
| 406 |
sep = ('', '', '') |
| 407 |
elif len(sep) == 1: |
| 408 |
if fields == 3: |
| 409 |
sep = sep + (sep[0], '') |
| 410 |
elif fields == 2: |
| 411 |
sep = sep + ('', '') |
| 412 |
else: |
| 413 |
sep = ('', '', '') |
| 414 |
elif len(sep) == 2: |
| 415 |
sep = sep + ('',) |
| 416 |
elif len(sep) != 3: |
| 417 |
raise ValueError( |
| 418 |
"Invalid separator specification for converting angle to string.") |
| 419 |
|
| 420 |
# Simplify the expression based on the requested precision. For |
| 421 |
# example, if the seconds will round up to 60, we should convert |
| 422 |
# it to 0 and carry upwards. If the field is hidden (by the |
| 423 |
# fields kwarg) we round up around the middle, 30.0. |
| 424 |
if precision is None: |
| 425 |
rounding_thresh = 60.0 - (10.0 ** -8) |
| 426 |
else: |
| 427 |
rounding_thresh = 60.0 - (10.0 ** -precision) |
| 428 |
|
| 429 |
if fields == 3 and values[2] >= rounding_thresh: |
| 430 |
values[2] = 0.0 |
| 431 |
values[1] += 1.0 |
| 432 |
elif fields < 3 and values[2] >= 30.0: |
| 433 |
values[1] += 1.0 |
| 434 |
|
| 435 |
if fields >= 2 and values[1] >= 60.0: |
| 436 |
values[1] = 0.0 |
| 437 |
values[0] += 1.0 |
| 438 |
elif fields < 2 and values[1] >= 30.0: |
| 439 |
values[0] += 1.0 |
| 440 |
|
| 441 |
literal = [] |
| 442 |
last_value = '' |
| 443 |
literal.append('{0:0{pad}.0f}{sep[0]}') |
| 444 |
if fields >= 2: |
| 445 |
literal.append('{1:02d}{sep[1]}') |
| 446 |
if fields == 3: |
| 447 |
if precision is None: |
| 448 |
last_value = f'{abs(values[2]):.8f}' |
| 449 |
last_value = last_value.rstrip('0').rstrip('.') |
| 450 |
else: |
| 451 |
last_value = '{0:.{precision}f}'.format( |
| 452 |
abs(values[2]), precision=precision) |
| 453 |
if len(last_value) == 1 or last_value[1] == '.': |
| 454 |
last_value = '0' + last_value |
| 455 |
literal.append('{last_value}{sep[2]}') |
| 456 |
literal = ''.join(literal) |
| 457 |
return literal.format(np.copysign(values[0], sign), |
| 458 |
int(values[1]), values[2], |
| 459 |
sep=sep, pad=pad, |
| 460 |
last_value=last_value) |
| 461 |
|
| 462 |
|
| 463 |
def hours_to_string(h, precision=5, pad=False, sep=('h', 'm', 's'), |
| 464 |
fields=3): |
| 465 |
""" |
| 466 |
Takes a decimal hour value and returns a string formatted as hms with |
| 467 |
separator specified by the 'sep' parameter. |
| 468 |
|
| 469 |
``h`` must be a scalar. |
| 470 |
""" |
| 471 |
h, m, s = hours_to_hms(h) |
| 472 |
return sexagesimal_to_string((h, m, s), precision=precision, pad=pad, |
| 473 |
sep=sep, fields=fields) |
| 474 |
|
| 475 |
|
| 476 |
def degrees_to_string(d, precision=5, pad=False, sep=':', fields=3): |
| 477 |
""" |
| 478 |
Takes a decimal hour value and returns a string formatted as dms with |
| 479 |
separator specified by the 'sep' parameter. |
| 480 |
|
| 481 |
``d`` must be a scalar. |
| 482 |
""" |
| 483 |
d, m, s = degrees_to_dms(d) |
| 484 |
return sexagesimal_to_string((d, m, s), precision=precision, pad=pad, |
| 485 |
sep=sep, fields=fields) |