/usr/lib/python3/dist-packages/astroplan/observer.py is in python3-astroplan 0.4-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Standard library
import datetime
import warnings
# Third-party
from astropy.coordinates import (EarthLocation, SkyCoord, AltAz, get_sun,
get_moon, Angle, Longitude)
from astropy.extern.six import string_types
import astropy.units as u
from astropy.time import Time
import numpy as np
import pytz
# Package
from .exceptions import TargetNeverUpWarning, TargetAlwaysUpWarning
from .moon import moon_illumination, moon_phase_angle
from .target import get_skycoord, SpecialObjectFlag, SunFlag, MoonFlag
__all__ = ["Observer", "MAGIC_TIME"]
MAGIC_TIME = Time(-999, format='jd')
def _generate_24hr_grid(t0, start, end, N, for_deriv=False):
"""
Generate a nearly linearly spaced grid of time durations.
The midpoints of these grid points will span times from ``t0``+``start``
to ``t0``+``end``, including the end points, which is useful when taking
numerical derivatives.
Parameters
----------
t0 : `~astropy.time.Time`
Time queried for, grid will be built from or up to this time.
start : float
Number of days before/after ``t0`` to start the grid.
end : float
Number of days before/after ``t0`` to end the grid.
N : int
Number of grid points to generate
for_deriv : bool
Generate time series for taking numerical derivative (modify
bounds)?
Returns
-------
`~astropy.time.Time`
"""
if for_deriv:
time_grid = np.concatenate([[start - 1/(N-1)],
np.linspace(start, end, N)[1:-1],
[end + 1/(N-1)]])*u.day
else:
time_grid = np.linspace(start, end, N)*u.day
# broadcast so grid is first index, and remaining shape of t0
# falls in later indices. e.g. if t0 is shape (10), time_grid
# will be shape (N, 10). If t0 is shape (5, 2), time_grid is (N, 5, 2)
while time_grid.ndim <= t0.ndim:
time_grid = time_grid[:, np.newaxis]
# we want to avoid 1D grids since we always want to broadcast against targets
if time_grid.ndim == 1:
time_grid = time_grid[:, np.newaxis]
return t0 + time_grid
class Observer(object):
"""
A container class for information about an observer's location and
environment.
Examples
--------
We can create an observer at Subaru Observatory in Hawaii two ways. First,
locations for some observatories are stored in astroplan, and these can be
accessed by name, like so:
>>> from astroplan import Observer
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
To find out which observatories can be accessed by name, check out
`~astropy.coordinates.EarthLocation.get_site_names`.
Next, you can initialize an observer by specifying the location with
`~astropy.coordinates.EarthLocation`:
>>> from astropy.coordinates import EarthLocation
>>> import astropy.units as u
>>> location = EarthLocation.from_geodetic(-155.4761*u.deg, 19.825*u.deg,
... 4139*u.m)
>>> subaru = Observer(location=location, name="Subaru", timezone="US/Hawaii")
You can also create an observer without an
`~astropy.coordinates.EarthLocation`:
>>> from astroplan import Observer
>>> import astropy.units as u
>>> subaru = Observer(longitude=-155.4761*u.deg, latitude=19.825*u.deg,
... elevation=0*u.m, name="Subaru", timezone="US/Hawaii")
"""
@u.quantity_input(elevation=u.m)
def __init__(self, location=None, timezone='UTC', name=None, latitude=None,
longitude=None, elevation=0*u.m, pressure=None,
relative_humidity=None, temperature=None, description=None):
"""
Parameters
----------
location : `~astropy.coordinates.EarthLocation`
The location (latitude, longitude, elevation) of the observatory.
timezone : str or `datetime.tzinfo` (optional)
The local timezone to assume. If a string, it will be passed
through ``pytz.timezone()`` to produce the timezone object.
name : str
A short name for the telescope, observatory or location.
latitude : float, str, `~astropy.units.Quantity` (optional)
The latitude of the observing location. Should be valid input for
initializing a `~astropy.coordinates.Latitude` object.
longitude : float, str, `~astropy.units.Quantity` (optional)
The longitude of the observing location. Should be valid input for
initializing a `~astropy.coordinates.Longitude` object.
elevation : `~astropy.units.Quantity` (optional), default = 0 meters
The elevation of the observing location, with respect to sea
level. Defaults to sea level.
pressure : `~astropy.units.Quantity` (optional)
The ambient pressure. Defaults to zero (i.e. no atmosphere).
relative_humidity : float (optional)
The ambient relative humidity.
temperature : `~astropy.units.Quantity` (optional)
The ambient temperature.
description : str (optional)
A short description of the telescope, observatory or observing
location.
"""
self.name = name
self.pressure = pressure
self.temperature = temperature
self.relative_humidity = relative_humidity
# If lat/long given instead of EarthLocation, convert them
# to EarthLocation
if location is None and (latitude is not None and
longitude is not None):
self.location = EarthLocation.from_geodetic(longitude, latitude,
elevation)
elif isinstance(location, EarthLocation):
self.location = location
else:
raise TypeError('Observatory location must be specified with '
'either (1) an instance of '
'astropy.coordinates.EarthLocation or (2) '
'latitude and longitude in degrees as '
'accepted by astropy.coordinates.Latitude and '
'astropy.coordinates.Latitude.')
# Accept various timezone inputs, default to UTC
if isinstance(timezone, datetime.tzinfo):
self.timezone = timezone
elif isinstance(timezone, string_types):
self.timezone = pytz.timezone(timezone)
else:
raise TypeError('timezone keyword should be a string, or an '
'instance of datetime.tzinfo')
def __repr__(self):
"""
String representation of the `~astroplan.Observer` object.
Examples
--------
>>> from astroplan import Observer
>>> keck = Observer.at_site("Keck", timezone="US/Hawaii")
>>> print(keck) # doctest: +FLOAT_CMP
<Observer: name='Keck',
location (lon, lat, el)=(-155.478333333 deg, 19.8283333333 deg, 4160.0 m),
timezone=<DstTzInfo 'US/Hawaii' LMT-1 day, 13:29:00 STD>>
"""
class_name = self.__class__.__name__
attr_names = ['name', 'location', 'timezone', 'pressure', 'temperature',
'relative_humidity']
attr_values = [getattr(self, attr) for attr in attr_names]
attributes_strings = []
for name, value in zip(attr_names, attr_values):
if value is not None:
# Format location for easy readability
if name == 'location':
formatted_loc = ["{} {}".format(i.value, i.unit)
for i in value.to_geodetic()]
attributes_strings.append(
"{} (lon, lat, el)=({})".format(
name, ", ".join(formatted_loc)))
else:
if name != 'name':
value = repr(value)
else:
value = "'{}'".format(value)
attributes_strings.append("{}={}".format(name, value))
return "<{}: {}>".format(class_name, ",\n ".join(attributes_strings))
@classmethod
def at_site(cls, site_name, **kwargs):
"""
Initialize an `~astroplan.observer.Observer` object with a site name.
Extra keyword arguments are passed to the `~astroplan.Observer`
constructor (see `~astroplan.Observer` for available keyword
arguments).
Parameters
----------
site_name : str
Observatory name, must be resolvable with
`~astropy.coordinates.EarthLocation.get_site_names`.
Returns
-------
`~astroplan.observer.Observer`
Observer object.
Examples
--------
Initialize an observer at Kitt Peak National Observatory:
>>> from astroplan import Observer
>>> import astropy.units as u
>>> kpno_generic = Observer.at_site('kpno')
>>> kpno_today = Observer.at_site('kpno', pressure=1*u.bar, temperature=0*u.deg_C)
"""
name = kwargs.pop('name', site_name)
if 'location' in kwargs:
raise ValueError("Location kwarg should not be used if "
"initializing an Observer with Observer.at_site()")
return cls(location=EarthLocation.of_site(site_name), name=name, **kwargs)
def astropy_time_to_datetime(self, astropy_time):
"""
Convert the `~astropy.time.Time` object ``astropy_time`` to a
localized `~datetime.datetime` object.
Timezones localized with `pytz`_.
.. _pytz: https://pypi.python.org/pypi/pytz/
Parameters
----------
astropy_time : `~astropy.time.Time`
Scalar or list-like.
Returns
-------
`~datetime.datetime`
Localized datetime, where the timezone of the datetime is
set by the ``timezone`` keyword argument of the
`~astroplan.Observer` constructor.
Examples
--------
Convert an astropy time to a localized `~datetime.datetime`:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
>>> astropy_time = Time('1999-12-31 06:00:00')
>>> print(subaru.astropy_time_to_datetime(astropy_time))
1999-12-30 20:00:00-10:00
"""
if not astropy_time.isscalar:
return [self.astropy_time_to_datetime(t) for t in astropy_time]
# Convert astropy.time.Time to a UTC localized datetime (aware)
utc_datetime = pytz.utc.localize(astropy_time.utc.datetime)
# Convert UTC to local timezone
return self.timezone.normalize(utc_datetime)
def datetime_to_astropy_time(self, date_time):
"""
Convert the `~datetime.datetime` object ``date_time`` to a
`~astropy.time.Time` object.
Timezones localized with `pytz`_. If the ``date_time`` is naive, the
implied timezone is the ``timezone`` structure of ``self``.
Parameters
----------
date_time : `~datetime.datetime` or list-like
Returns
-------
`~astropy.time.Time`
Astropy time object (no timezone information preserved).
Examples
--------
Convert a localized `~datetime.datetime` to a `~astropy.time.Time`
object. Non-localized datetimes are assumed to be UTC.
<Time object: scale='utc' format='datetime' value=1999-12-31 06:00:00>
>>> from astroplan import Observer
>>> import datetime
>>> import pytz
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
>>> hi_date_time = datetime.datetime(2005, 6, 21, 20, 0, 0, 0)
>>> subaru.datetime_to_astropy_time(hi_date_time)
<Time object: scale='utc' format='datetime' value=2005-06-22 06:00:00>
>>> utc_date_time = datetime.datetime(2005, 6, 22, 6, 0, 0, 0,
... tzinfo=pytz.timezone("UTC"))
>>> subaru.datetime_to_astropy_time(utc_date_time)
<Time object: scale='utc' format='datetime' value=2005-06-22 06:00:00>
"""
if hasattr(date_time, '__iter__'):
return Time([self.datetime_to_astropy_time(t) for t in date_time])
# For timezone-naive datetimes, assign local timezone
if date_time.tzinfo is None:
date_time = self.timezone.localize(date_time)
return Time(date_time, location=self.location)
def _is_broadcastable(self, shp1, shp2):
"""Test if two shape tuples are broadcastable"""
if shp1 == shp2:
return True
for a, b in zip(shp1[::-1], shp2[::-1]):
if a == 1 or b == 1 or a == b:
pass
else:
return False
return True
def _preprocess_inputs(self, time, target=None, grid_times_targets=False):
"""
Preprocess time and target inputs
This routine takes the inputs for time and target and attempts to
return a single `~astropy.time.Time` and `~astropy.coordinates.SkyCoord`
for each argument, which may be non-scalar if necessary.
time : `~astropy.time.Time` or other (see below)
The time(s) to use in the calculation. It can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time` object)
target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord`, or list
The target(s) to use in the calculation.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules. Useful for grid searches for rise/set times etc.
"""
# make sure we have a non-scalar time
if not isinstance(time, Time):
time = Time(time)
if target is None:
return time, None
# convert any kind of target argument to non-scalar SkyCoord
target = get_skycoord(target)
if grid_times_targets:
if target.isscalar:
# ensure we have a (1, 1) shape coord
target = SkyCoord(np.tile(target, 1))[:, np.newaxis]
else:
while target.ndim <= time.ndim:
target = target[:, np.newaxis]
elif not self._is_broadcastable(target.shape, time.shape):
raise ValueError('Time and Target arguments cannot be broadcast '
'against each other with shapes {} and {}'
.format(time.shape, target.shape))
return time, target
def altaz(self, time, target=None, obswl=None, grid_times_targets=False):
"""
Get an `~astropy.coordinates.AltAz` frame or coordinate.
If ``target`` is None, generates an altitude/azimuth frame. Otherwise,
calculates the transformation to that frame for the requested ``target``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
The time at which the observation is taking place. Will be used as
the ``obstime`` attribute in the resulting frame or coordinate. This
will be passed in as the first argument to the `~astropy.time.Time`
initializer, so it can be anything that `~astropy.time.Time` will
accept (including a `~astropy.time.Time` object)
target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord`, or list (optional)
Celestial object(s) of interest. If ``target`` is `None`, returns
the `~astropy.coordinates.AltAz` frame without coordinates.
obswl : `~astropy.units.Quantity` (optional)
Wavelength of the observation used in the calculation.
grid_times_targets: bool (optional)
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy
rules. Useful for grid searches for rise/set times etc.
Returns
-------
`~astropy.coordinates.AltAz`
If ``target`` is `None`, returns `~astropy.coordinates.AltAz` frame.
If ``target`` is not `None`, returns the ``target`` transformed to
the `~astropy.coordinates.AltAz` frame.
Examples
--------
Create an instance of the `~astropy.coordinates.AltAz` frame for an
observer at Apache Point Observatory at a particular time:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> from astropy.coordinates import SkyCoord
>>> apo = Observer.at_site("APO")
>>> time = Time('2001-02-03 04:05:06')
>>> target = SkyCoord(0*u.deg, 0*u.deg)
>>> altaz_frame = apo.altaz(time)
Now transform the target's coordinates to the alt/az frame:
>>> target_altaz = target.transform_to(altaz_frame) # doctest: +SKIP
Alternatively, construct an alt/az frame and transform the target to
that frame all in one step:
>>> target_altaz = apo.altaz(time, target) # doctest: +SKIP
"""
if target is not None:
time, target = self._preprocess_inputs(time, target, grid_times_targets)
altaz_frame = AltAz(location=self.location, obstime=time,
pressure=self.pressure, obswl=obswl,
temperature=self.temperature,
relative_humidity=self.relative_humidity)
if target is None:
# Return just the frame
return altaz_frame
else:
return target.transform_to(altaz_frame)
def parallactic_angle(self, time, target, grid_times_targets=False):
"""
Calculate the parallactic angle.
Parameters
----------
time : `~astropy.time.Time`
Observation time.
target : `~astroplan.FixedTarget` or `~astropy.coordinates.SkyCoord` or list
Target celestial object(s).
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules.
Returns
-------
`~astropy.coordinates.Angle`
Parallactic angle.
Notes
-----
The parallactic angle is the angle between the great circle that
intersects a celestial object and the zenith, and the object's hour
circle [1]_.
.. [1] https://en.wikipedia.org/wiki/Parallactic_angle
"""
time, coordinate = self._preprocess_inputs(time, target, grid_times_targets)
# Eqn (14.1) of Meeus' Astronomical Algorithms
LST = time.sidereal_time('mean', longitude=self.location.lon)
H = (LST - coordinate.ra).radian
q = np.arctan(np.sin(H) /
(np.tan(self.location.lat.radian) *
np.cos(coordinate.dec.radian) -
np.sin(coordinate.dec.radian)*np.cos(H)))*u.rad
return Angle(q)
# Sun-related methods.
@u.quantity_input(horizon=u.deg)
def _horiz_cross(self, t, alt, rise_set, horizon=0*u.degree):
"""
Find time ``t`` when values in array ``a`` go from
negative to positive or positive to negative (exclude endpoints)
``return_limits`` will return nearest times to zero-crossing.
Parameters
----------
t : `~astropy.time.Time`
Grid of N times, any shape. Search grid along first axis, e.g (N, ...)
alt : `~astropy.units.Quantity`
Grid of altitudes
Depending on broadcasting we either have ndim >=3 and
M targets along first axis, e.g (M, N, ...), or
ndim = 2 and targets/times in last axis
rise_set : {"rising", "setting"}
Calculate either rising or setting across the horizon
horizon : float
Number of degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
Returns
-------
Returns the lower and upper limits on the time and altitudes
of the horizon crossing. The altitude limits have shape (M, ...) and the
time limits have shape (...). These arrays aresuitable for interpolation
to find the horizon crossing time.
"""
# handle different cases by enforcing standard shapes on
# the altitude grid
finesse_time_indexes = False
if alt.ndim == 1:
raise ValueError('Must supply more at least a 2D grid of altitudes')
elif alt.ndim == 2:
# TODO: this test for ndim=2 doesn't work. if times is e.g (2,5)
# then alt will have ndim=3, but shape (100, 2, 5) so grid
# is in first index...
ntargets = alt.shape[1]
ngrid = alt.shape[0]
unit = alt.unit
alt = np.broadcast_to(alt, (ntargets, ngrid, ntargets)).T
alt = alt*unit
extra_dimension_added = True
if t.shape[1] == 1:
finesse_time_indexes = True
else:
extra_dimension_added = False
output_shape = (alt.shape[0],) + alt.shape[2:]
if rise_set == 'rising':
# Find index where altitude goes from below to above horizon
condition = (alt[:, :-1, ...] < horizon) * (alt[:, 1:, ...] > horizon)
elif rise_set == 'setting':
# Find index where altitude goes from above to below horizon
condition = (alt[:, :-1, ...] > horizon) * (alt[:, 1:, ...] < horizon)
noncrossing_indices = np.sum(condition, axis=1, dtype=np.intp) < 1
alt_lims1 = u.Quantity(np.zeros(output_shape), unit=u.deg)
alt_lims2 = u.Quantity(np.zeros(output_shape), unit=u.deg)
jd_lims1 = np.zeros(output_shape)
jd_lims2 = np.zeros(output_shape)
if np.any(noncrossing_indices):
for target_index in set(np.where(noncrossing_indices)[0]):
warnmsg = ('Target with index {} does not cross horizon={} within '
'24 hours'.format(target_index, horizon))
if (alt[target_index, ...] > horizon).all():
warnings.warn(warnmsg, TargetAlwaysUpWarning)
else:
warnings.warn(warnmsg, TargetNeverUpWarning)
alt_lims1[np.nonzero(noncrossing_indices)] = np.nan
alt_lims2[np.nonzero(noncrossing_indices)] = np.nan
jd_lims1[np.nonzero(noncrossing_indices)] = np.nan
jd_lims2[np.nonzero(noncrossing_indices)] = np.nan
before_indices = np.array(np.nonzero(condition))
# we want to add an vector like (0, 1, ...) to get after indices
after_indices = before_indices.copy()
after_indices[1, :] += 1
al1 = alt[tuple(before_indices)]
al2 = alt[tuple(after_indices)]
# slice the time in the same way, but delete the object index
before_time_index_tuple = np.delete(before_indices, 0, 0)
after_time_index_tuple = np.delete(after_indices, 0, 0)
if finesse_time_indexes:
before_time_index_tuple[1:] = 0
after_time_index_tuple[1:] = 0
tl1 = t[tuple(before_time_index_tuple)]
tl2 = t[tuple(after_time_index_tuple)]
alt_lims1[tuple(np.delete(before_indices, 1, 0))] = al1
alt_lims2[tuple(np.delete(before_indices, 1, 0))] = al2
jd_lims1[tuple(np.delete(before_indices, 1, 0))] = tl1.utc.jd
jd_lims2[tuple(np.delete(before_indices, 1, 0))] = tl2.utc.jd
if extra_dimension_added:
return (alt_lims1.diagonal(), alt_lims2.diagonal(),
jd_lims1.diagonal(), jd_lims2.diagonal())
else:
return alt_lims1, alt_lims2, jd_lims1, jd_lims2
@u.quantity_input(horizon=u.deg)
def _two_point_interp(self, jd_before, jd_after,
alt_before, alt_after, horizon=0*u.deg):
"""
Do linear interpolation between two ``altitudes`` at
two ``times`` to determine the time where the altitude
goes through zero.
Parameters
----------
jd_before : `float`
JD(UTC) before crossing event
jd_after : `float`
JD(UTC) after crossing event
alt_before : `~astropy.units.Quantity`
altitude before crossing event
alt_after : `~astropy.units.Quantity`
altitude after crossing event
horizon : `~astropy.units.Quantity`
Solve for the time when the altitude is equal to
reference_alt.
Returns
-------
t : `~astropy.time.Time`
Time when target crosses the horizon
"""
slope = (alt_after-alt_before)/((jd_after - jd_before)*u.d)
crossing_jd = (jd_after*u.d - ((alt_after - horizon)/slope))
crossing_jd[np.isnan(crossing_jd)] = u.d*MAGIC_TIME.jd
return np.squeeze(Time(crossing_jd, format='jd'))
def _altitude_trig(self, LST, target, grid_times_targets=False):
"""
Calculate the altitude of ``target`` at local sidereal times ``LST``.
This method provides a factor of ~3 speed up over calling `altaz`, and
inherently does *not* take the atmosphere into account.
Parameters
----------
LST : `~astropy.time.Time`
Local sidereal times (array)
target : {`~astropy.coordinates.SkyCoord`, `FixedTarget`} or similar
Target celestial object's coordinates.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules. Useful for grid searches for rise/set times etc.
Returns
-------
alt : `~astropy.unit.Quantity`
Array of altitudes
"""
LST, target = self._preprocess_inputs(LST, target, grid_times_targets)
alt = np.arcsin(np.sin(self.location.lat.radian) *
np.sin(target.dec) +
np.cos(self.location.lat.radian) *
np.cos(target.dec) *
np.cos(LST.radian - target.ra.radian))
return alt
def _calc_riseset(self, time, target, prev_next, rise_set, horizon,
N=150, grid_times_targets=False):
"""
Time at next rise/set of ``target``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`
Position of target or multiple positions of that target
at multiple times (if target moves, like the Sun)
prev_next : str - either 'previous' or 'next'
Test next rise/set or previous rise/set
rise_set : str - either 'rising' or 'setting'
Compute prev/next rise or prev/next set
horizon : `~astropy.units.Quantity`
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
N : int
Number of altitudes to compute when searching for
rise or set.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules.
Returns
-------
ret1 : `~astropy.time.Time`
Time of rise/set
"""
if not isinstance(time, Time):
time = Time(time)
if prev_next == 'next':
start = 0
end = (1 + (target.approx_sidereal_drift.to(u.day).value
if hasattr(target, 'approx_sidereal_drift') else 0))
else:
start = (-1 - (target.approx_sidereal_drift.to(u.day).value
if hasattr(target, 'approx_sidereal_drift') else 0))
end = 0
times = _generate_24hr_grid(time, start, end, N)
if target is MoonFlag:
altaz = self.altaz(times, get_moon(times, location=self.location),
grid_times_targets=grid_times_targets)
elif target is SunFlag:
altaz = self.altaz(times, get_sun(times),
grid_times_targets=grid_times_targets)
else:
altaz = self.altaz(times, target,
grid_times_targets=grid_times_targets)
altitudes = altaz.alt
al1, al2, jd1, jd2 = self._horiz_cross(times, altitudes, rise_set,
horizon)
return self._two_point_interp(jd1, jd2, al1, al2,
horizon=horizon)
def _calc_transit(self, time, target, prev_next, antitransit=False,
N=150, grid_times_targets=False):
"""
Time at next transit of the meridian of `target`.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`
Position of target or multiple positions of that target
at multiple times (if target moves, like the Sun)
prev_next : str - either 'previous' or 'next'
Test next rise/set or previous rise/set
antitransit : bool
Toggle compute antitransit (below horizon, equivalent to midnight
for the Sun)
N : int
Number of altitudes to compute when searching for
rise or set.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules.
Returns
-------
ret1 : `~astropy.time.Time`
Time of transit/antitransit
"""
# TODO FIX BROADCASTING HERE
if not isinstance(time, Time):
time = Time(time)
if prev_next == 'next':
times = _generate_24hr_grid(time, 0, 1, N, for_deriv=True)
else:
times = _generate_24hr_grid(time, -1, 0, N, for_deriv=True)
# The derivative of the altitude with respect to time is increasing
# from negative to positive values at the anti-transit of the meridian
if antitransit:
rise_set = 'rising'
else:
rise_set = 'setting'
altaz = self.altaz(times, target, grid_times_targets=grid_times_targets)
altitudes = altaz.alt
if altitudes.ndim > 2:
# shape is (M, N, ...) where M is targets and N is grid
d_altitudes = altitudes.diff(axis=1)
else:
# shape is (N, M) where M is targets and N is grid
d_altitudes = altitudes.diff(axis=0)
dt = Time((times.jd[1:] + times.jd[:-1])/2, format='jd')
horizon = 0*u.degree # Find when derivative passes through zero
al1, al2, jd1, jd2 = self._horiz_cross(dt, d_altitudes,
rise_set, horizon)
return self._two_point_interp(jd1, jd2, al1, al2,
horizon=horizon)
def _determine_which_event(self, function, args_dict):
"""
Run through the next/previous/nearest permutations of the solutions
to `function(time, ...)`, and return the previous/next/nearest one
specified by the args stored in args_dict.
"""
time = args_dict.pop('time', None)
target = args_dict.pop('target', None)
which = args_dict.pop('which', None)
horizon = args_dict.pop('horizon', None)
rise_set = args_dict.pop('rise_set', None)
antitransit = args_dict.pop('antitransit', None)
grid_times_targets = args_dict.pop('grid_times_targets', False)
# Assemble arguments for function, depending on the function.
if function == self._calc_riseset:
def event_function(w):
return function(time, target, w, rise_set, horizon,
grid_times_targets=grid_times_targets)
elif function == self._calc_transit:
def event_function(w):
return function(time, target, w, antitransit=antitransit,
grid_times_targets=grid_times_targets)
else:
raise ValueError('Function {} not supported in '
'_determine_which_event.'.format(function))
if not isinstance(time, Time):
time = Time(time)
if which == 'next' or which == 'nearest':
next_event = event_function('next')
if which == 'next':
return next_event
if which == 'previous' or which == 'nearest':
previous_event = event_function('previous')
if which == 'previous':
return previous_event
if which == 'nearest':
mask = abs(time - previous_event) < abs(time - next_event)
return Time(np.where(mask, previous_event.utc.jd,
next_event.utc.jd), format='jd')
raise ValueError('"which" kwarg must be "next", "previous" or '
'"nearest".')
@u.quantity_input(horizon=u.deg)
def target_rise_time(self, time, target, which='nearest', horizon=0*u.degree,
grid_times_targets=False):
"""
Calculate rise time.
Compute time of the next/previous/nearest rise of the ``target``
object, where "rise" is defined as the time when the ``target``
transitions from altitudes below the ``horizon`` to above the
``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
which : {'next', 'previous', 'nearest'}
Choose which sunrise relative to the present ``time`` would you
like to calculate
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
grid_times_targets: bool
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy rules.
Returns
-------
`~astropy.time.Time`
Rise time of target
Examples
--------
Calculate the rise time of Rigel at Keck Observatory:
>>> from astroplan import Observer, FixedTarget
>>> from astropy.time import Time
>>> time = Time("2001-02-03 04:05:06")
>>> target = FixedTarget.from_name("Rigel")
>>> keck = Observer.at_site("Keck")
>>> rigel_rise_time = keck.target_rise_time(time, target, which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(rigel_rise_time)) # doctest: +SKIP
ISO: 2001-02-04 00:51:23.330, JD: 2451944.53569
"""
return self._determine_which_event(self._calc_riseset,
dict(time=time, target=target,
which=which, rise_set='rising',
horizon=horizon,
grid_times_targets=grid_times_targets))
@u.quantity_input(horizon=u.deg)
def target_set_time(self, time, target, which='nearest', horizon=0*u.degree,
grid_times_targets=False):
"""
Calculate set time.
Compute time of the next/previous/nearest set of ``target``, where
"set" is defined as when the ``target`` transitions from altitudes
above ``horizon`` to below ``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
which : {'next', 'previous', 'nearest'}
Choose which sunset relative to the present ``time`` would you
like to calculate
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
grid_times_targets: bool
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy rules.
Returns
-------
`~astropy.time.Time`
Set time of target.
Examples
--------
Calculate the set time of Rigel at Keck Observatory:
>>> from astroplan import Observer, FixedTarget
>>> from astropy.time import Time
>>> time = Time("2001-02-03 04:05:06")
>>> target = FixedTarget.from_name("Rigel")
>>> keck = Observer.at_site("Keck")
>>> rigel_set_time = keck.target_set_time(time, target, which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(rigel_set_time)) # doctest: +SKIP
ISO: 2001-02-03 12:29:34.768, JD: 2451944.02054
"""
return self._determine_which_event(self._calc_riseset,
dict(time=time, target=target,
which=which, rise_set='setting',
horizon=horizon,
grid_times_targets=grid_times_targets))
def target_meridian_transit_time(self, time, target, which='nearest', grid_times_targets=False):
"""
Calculate time at the transit of the meridian.
Compute time of the next/previous/nearest transit of the ``target``
object.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
which : {'next', 'previous', 'nearest'}
Choose which sunrise relative to the present ``time`` would you
like to calculate
grid_times_targets: bool
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy rules.
Returns
-------
`~astropy.time.Time`
Transit time of target
Examples
--------
Calculate the meridian transit time of Rigel at Keck Observatory:
>>> from astroplan import Observer, FixedTarget
>>> from astropy.time import Time
>>> time = Time("2001-02-03 04:05:06")
>>> target = FixedTarget.from_name("Rigel")
>>> keck = Observer.at_site("Keck")
>>> rigel_transit_time = keck.target_meridian_transit_time(time, target,
... which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(rigel_transit_time)) # doctest: +SKIP
ISO: 2001-02-03 06:42:26.863, JD: 2451943.77948
"""
return self._determine_which_event(self._calc_transit,
dict(time=time, target=target,
which=which,
rise_set='setting',
grid_times_targets=grid_times_targets))
def target_meridian_antitransit_time(self, time, target, which='nearest',
grid_times_targets=False):
"""
Calculate time at the antitransit of the meridian.
Compute time of the next/previous/nearest antitransit of the ``target``
object.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
which : {'next', 'previous', 'nearest'}
Choose which sunrise relative to the present ``time`` would you
like to calculate
grid_times_targets : bool
If True, the target object will have extra dimensions packed onto the end,
so that calculations with M targets and N times will return an (M, N)
shaped result. Otherwise, we rely on broadcasting the shapes together
using standard numpy rules.
Returns
-------
`~astropy.time.Time`
Antitransit time of target
Examples
--------
Calculate the meridian anti-transit time of Rigel at Keck Observatory:
>>> from astroplan import Observer, FixedTarget
>>> from astropy.time import Time
>>> time = Time("2001-02-03 04:05:06")
>>> target = FixedTarget.from_name("Rigel")
>>> keck = Observer.at_site("Keck")
>>> rigel_antitransit_time = keck.target_meridian_antitransit_time(
... time, target, which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(rigel_antitransit_time)) # doctest: +SKIP
ISO: 2001-02-03 18:40:29.761, JD: 2451944.27812
"""
return self._determine_which_event(self._calc_transit,
dict(time=time, target=target,
which=which, antitransit=True,
rise_set='setting',
grid_times_targets=grid_times_targets))
@u.quantity_input(horizon=u.deg)
def sun_rise_time(self, time, which='nearest', horizon=0*u.degree):
"""
Time of sunrise.
Compute time of the next/previous/nearest sunrise, where
sunrise is defined as when the Sun transitions from altitudes
below ``horizon`` to above ``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which sunrise relative to the present ``time`` would you
like to calculate.
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
Returns
-------
`~astropy.time.Time`
Time of sunrise
Examples
--------
Calculate the time of the previous sunrise at Apache Point Observatory:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time('2001-02-03 04:05:06')
>>> sun_rise = apo.sun_rise_time(time, which="previous") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(sun_rise)) # doctest: +SKIP
ISO: 2001-02-02 14:02:50.554, JD: 2451943.08531
"""
return self.target_rise_time(time, get_sun(time), which, horizon)
@u.quantity_input(horizon=u.deg)
def sun_set_time(self, time, which='nearest', horizon=0*u.degree):
"""
Time of sunset.
Compute time of the next/previous/nearest sunset, where
sunset is defined as when the Sun transitions from altitudes
below ``horizon`` to above ``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which sunset relative to the present ``time`` would you
like to calculate
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
Returns
-------
`~astropy.time.Time`
Time of sunset
Examples
--------
Calculate the time of the next sunset at Apache Point Observatory:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time('2001-02-03 04:05:06')
>>> sun_set = apo.sun_set_time(time, which="next") # doctest: +SKIP
>>> print("ISO: {0.iso}, JD: {0.jd}".format(sun_set)) # doctest: +SKIP
ISO: 2001-02-04 00:35:42.102, JD: 2451944.52479
"""
return self.target_set_time(time, get_sun(time), which, horizon)
def noon(self, time, which='nearest'):
"""
Time at solar noon.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which noon relative to the present ``time`` would you
like to calculate
Returns
-------
`~astropy.time.Time`
Time at solar noon
"""
return self.target_meridian_transit_time(time, get_sun(time), which)
def midnight(self, time, which='nearest'):
"""
Time at solar midnight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which noon relative to the present ``time`` would you
like to calculate
Returns
-------
`~astropy.time.Time`
Time at solar midnight
"""
return self.target_meridian_antitransit_time(time, get_sun(time), which)
# Twilight convenience functions
def twilight_evening_astronomical(self, time, which='nearest'):
"""
Time at evening astronomical (-18 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate. Default is nearest.
Returns
-------
`~astropy.time.Time`
Time of twilight
"""
return self.sun_set_time(time, which, horizon=-18*u.degree)
def twilight_evening_nautical(self, time, which='nearest'):
"""
Time at evening nautical (-12 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate. Default is nearest.
Returns
-------
`~astropy.time.Time`
Time of twilight
"""
return self.sun_set_time(time, which, horizon=-12*u.degree)
def twilight_evening_civil(self, time, which='nearest'):
"""
Time at evening civil (-6 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate. Default is nearest.
Returns
-------
`~astropy.time.Time`
Time of twilight
"""
return self.sun_set_time(time, which, horizon=-6*u.degree)
def twilight_morning_astronomical(self, time, which='nearest'):
"""
Time at morning astronomical (-18 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate
Returns
-------
`~astropy.time.Time`
Time of twilight
"""
return self.sun_rise_time(time, which, horizon=-18*u.degree)
def twilight_morning_nautical(self, time, which='nearest'):
"""
Time at morning nautical (-12 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate. Default is nearest.
Returns
-------
`~astropy.time.Time`
Time of twilight
"""
return self.sun_rise_time(time, which, horizon=-12*u.degree)
def twilight_morning_civil(self, time, which='nearest'):
"""
Time at morning civil (-6 degree) twilight.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observations. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which twilight relative to the present ``time`` would you
like to calculate. Default is nearest.
Returns
-------
`~astropy.time.Time`
Time of sunset
"""
return self.sun_rise_time(time, which, horizon=-6*u.degree)
# Moon-related methods.
def moon_rise_time(self, time, which='nearest', horizon=0*u.deg):
"""
Returns the local moon rise time.
Compute time of the next/previous/nearest moon rise, where
moon rise is defined as the time when the moon transitions from
altitudes below ``horizon`` to above ``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which moon rise relative to the present ``time`` would you
like to calculate.
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
"""
return self.target_rise_time(time, MoonFlag, which, horizon)
def moon_set_time(self, time, which='nearest', horizon=0*u.deg):
"""
Returns the local moon set time.
Compute time of the next/previous/nearest moon set, where
moon set is defined as the time when the moon transitions from
altitudes below ``horizon`` to above ``horizon``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
which : {'next', 'previous', 'nearest'}
Choose which moon set relative to the present ``time`` would you
like to calculate.
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating set/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
"""
return self.target_set_time(time, MoonFlag, which, horizon)
def moon_illumination(self, time):
"""
Calculate the illuminated fraction of the moon.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
Returns
-------
float
Fraction of lunar surface illuminated
Examples
--------
How much of the lunar surface is illuminated at 2015-08-29 18:35 UTC,
which we happen to know is the time of a full moon?
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time("2015-08-29 18:35")
>>> apo.moon_illumination(time) # doctest: +SKIP
array([ 0.99972487])
"""
if not isinstance(time, Time):
time = Time(time)
return moon_illumination(time)
def moon_phase(self, time=None):
"""
Calculate lunar orbital phase.
For example, phase=2*pi is "new", phase=0 is "full".
Parameters
----------
time : `~astropy.time.Time` or other (see below)
This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
Returns
-------
moon_phase_angle : float
Orbital phase angle of the moon where 2*pi corresponds to new moon,
zero corresponds to full moon.
Examples
--------
Calculate the phase of the moon at 2015-08-29 18:35 UTC. Near zero
radians corresponds to a nearly full moon.
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site('APO')
>>> time = Time('2015-08-29 18:35')
>>> apo.moon_phase(time) # doctest: +SKIP
<Quantity [ 0.03317537] rad>
"""
if time is not None and not isinstance(time, Time):
time = Time(time)
return moon_phase_angle(time)
def moon_altaz(self, time, ephemeris=None):
"""
Returns the position of the moon in alt/az.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
ephemeris : str, optional
Ephemeris to use. If not given, use the one set with
``astropy.coordinates.solar_system_ephemeris.set`` (which is
set to 'builtin' by default).
Returns
-------
altaz : `~astropy.coordinates.SkyCoord`
Position of the moon transformed to altitude and azimuth
Examples
--------
Calculate the altitude and azimuth of the moon at Apache Point
Observatory:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time("2015-08-29 18:35")
>>> altaz_moon = apo.moon_altaz(time) # doctest: +SKIP
>>> print("alt: {0.alt}, az: {0.az}".format(altaz_moon)) # doctest: +SKIP
alt: -63.72706397691421 deg, az: 345.3640380598265 deg
"""
if not isinstance(time, Time):
time = Time(time)
moon = get_moon(time, location=self.location, ephemeris=ephemeris)
return self.altaz(time, moon)
def sun_altaz(self, time):
"""
Returns the position of the Sun in alt/az.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object).
ephemeris : str, optional
Ephemeris to use. If not given, use the one set with
``astropy.coordinates.solar_system_ephemeris.set`` (which is
set to 'builtin' by default).
Returns
-------
altaz : `~astropy.coordinates.SkyCoord`
Position of the moon transformed to altitude and azimuth
"""
if not isinstance(time, Time):
time = Time(time)
sun = get_sun(time)
return self.altaz(time, sun)
@u.quantity_input(horizon=u.deg)
def target_is_up(self, time, target, horizon=0*u.degree,
return_altaz=False, grid_times_targets=False):
"""
Is ``target`` above ``horizon`` at this ``time``?
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
return_altaz : bool (optional)
Also return the '~astropy.coordinates.AltAz' coordinate.
grid_times_targets: bool
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy rules.
Returns
-------
observable : boolean or np.ndarray(bool)
True if ``target`` is above ``horizon`` at ``time``, else False.
Examples
--------
Are Aldebaran and Vega above the horizon at Apache Point Observatory
at 2015-08-29 18:35 UTC?
>>> from astroplan import Observer, FixedTarget
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time("2015-08-29 18:35")
>>> aldebaran = FixedTarget.from_name("Aldebaran")
>>> vega = FixedTarget.from_name("Vega")
>>> apo.target_is_up(time, aldebaran) # doctest: +SKIP
True
>>> apo.target_is_up(time, [aldebaran, vega]) # doctest: +SKIP
array([ True, False], dtype=bool)
"""
if not isinstance(time, Time):
time = Time(time)
altaz = self.altaz(time, target, grid_times_targets=grid_times_targets)
observable = altaz.alt > horizon
if altaz.isscalar:
observable = bool(observable)
if not return_altaz:
return observable
else:
return observable, altaz
@u.quantity_input(horizon=u.deg)
def is_night(self, time, horizon=0*u.deg, obswl=None):
"""
Is the Sun below ``horizon`` at ``time``?
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use
for calculating day/night (i.e.,
-6 deg horizon = civil twilight, etc.)
obswl : `~astropy.units.Quantity` (optional)
Wavelength of the observation used in the calculation
Returns
-------
sun_below_horizon : bool or np.ndarray(bool)
`True` if sun is below ``horizon`` at ``time``, else `False`.
Examples
--------
Is it "nighttime" (i.e. is the Sun below ``horizon``) at Apache Point
Observatory at 2015-08-29 18:35 UTC?
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> apo = Observer.at_site("APO")
>>> time = Time("2015-08-29 18:35")
>>> apo.is_night(time) # doctest: +SKIP
False
"""
if not isinstance(time, Time):
time = Time(time)
solar_altitude = self.altaz(time, target=get_sun(time), obswl=obswl).alt
if solar_altitude.isscalar:
return bool(solar_altitude < horizon)
else:
return solar_altitude < horizon
def local_sidereal_time(self, time, kind='apparent', model=None):
"""
Convert ``time`` to local sidereal time for observer.
This is a thin wrapper around the `~astropy.time.Time.sidereal_time`
method.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
kind : {'mean', 'apparent'} (optional)
Passed to the ``kind`` argument of
`~astropy.time.Time.sidereal_time`
model : str or `None`; optional
The precession/nutation model to assume - see
`~astropy.time.Time.sidereal_time` for more details.
Returns
-------
`~astropy.coordinates.Longitude`
Local sidereal time.
"""
if not isinstance(time, Time):
time = Time(time)
return time.sidereal_time(kind, longitude=self.location.lon,
model=model)
def target_hour_angle(self, time, target, grid_times_targets=False):
"""
Calculate the local hour angle of ``target`` at ``time``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
Time of observation. This will be passed in as the first argument to
the `~astropy.time.Time` initializer, so it can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astropy.coordinates.SkyCoord`, `~astroplan.FixedTarget`, or list
Target celestial object(s)
grid_times_targets: bool
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy rules.
Returns
-------
hour_angle : `~astropy.coordinates.Angle`
The hour angle(s) of the target(s) at ``time``
"""
time, target = self._preprocess_inputs(time, target, grid_times_targets)
return Longitude(self.local_sidereal_time(time) - target.ra)
@u.quantity_input(horizon=u.degree)
def tonight(self, time=None, horizon=0 * u.degree, obswl=None):
"""
Return a time range corresponding to the nearest night
This will return a range of `~astropy.time.Time` corresponding to the
beginning and ending of the night. If in the middle of a given night,
return times from `~astropy.time.Time.now` until the nearest
`~astroplan.Observer.sun_rise_time`
Parameters
----------
time : `~astropy.time.Time` (optional), default = `~astropy.time.Time.now`
The start time for tonight, which is allowed to be arbitrary. See description
above for behavior
horizon : `~astropy.units.Quantity` (optional), default = zero degrees
Degrees above/below actual horizon to use for calculating rise/set times
(e.g., -6 deg horizon = civil twilight, etc.)
obswl : `~astropy.units.Quantity` (optional)
Wavelength of the observation used in the calculation
Returns
-------
times : `~astropy.time.Time`
A tuple of times corresponding to the start and end of current night
"""
current_time = Time.now() if time is None else time
night_mask = self.is_night(current_time, horizon=horizon, obswl=obswl)
sun_set_time = self.sun_set_time(current_time, which='next', horizon=horizon)
start_time = np.where(night_mask, current_time, sun_set_time)
# np.where gives us a list of start Times - convert to Time object
if not isinstance(start_time, Time):
start_time = Time(start_time)
end_time = self.sun_rise_time(start_time, which='next', horizon=horizon)
return start_time, end_time
|