-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathastronomy.py
10574 lines (9085 loc) · 424 KB
/
astronomy.py
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
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2019-2025 Don Cross <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""Astronomy Engine by Don Cross
See the GitHub project page for full documentation, examples,
and other information:
https://github.com/cosinekitty/astronomy
"""
import math
import datetime
import enum
import re
import abc
from typing import Any, List, Tuple, Optional, Union, Callable, Dict
def _cbrt(x: float) -> float:
'''Returns the cube root of x.'''
y = (x ** (1.0 / 3.0)) if (x >= 0.0) else -((-x) ** (1.0 / 3.0))
# mypy knows that the exponentiation operator '**' can return
# complex values in some cases. It doesn't realize that can't
# happen here. To prevent type errors, explicitly check the type.
if isinstance(y, float):
return y
raise InternalError()
def _cdiv(numer: int, denom: int) -> int:
'''Divide negative numbers the same way C does: rounding toward zero, not down.'''
sign = -1 if (numer * denom) < 0 else +1
return sign * (abs(numer) // abs(denom))
KM_PER_AU = 1.4959787069098932e+8 #<const> The number of kilometers per astronomical unit.
C_AUDAY = 173.1446326846693 #<const> The speed of light expressed in astronomical units per day.
AU_PER_LY = 63241.07708807546 #<const> The number of astronomical units in one light-year.
# Jupiter radius data are nominal values obtained from:
# https://www.iau.org/static/resolutions/IAU2015_English.pdf
# https://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html
JUPITER_EQUATORIAL_RADIUS_KM = 71492.0 #<const> The equatorial radius of Jupiter, expressed in kilometers.
JUPITER_POLAR_RADIUS_KM = 66854.0 #<const> The polar radius of Jupiter, expressed in kilometers.
JUPITER_MEAN_RADIUS_KM = 69911.0 #<const> The volumetric mean radius of Jupiter, expressed in kilometers.
# The radii of Jupiter's 4 largest moons were obtained from:
# https://ssd.jpl.nasa.gov/?sat_phys_par
IO_RADIUS_KM = 1821.6 #<const> The mean radius of Jupiter's moon Io, expressed in kilometers.
EUROPA_RADIUS_KM = 1560.8 #<const> The mean radius of Jupiter's moon Europa, expressed in kilometers.
GANYMEDE_RADIUS_KM = 2631.2 #<const> The mean radius of Jupiter's moon Ganymede, expressed in kilometers.
CALLISTO_RADIUS_KM = 2410.3 #<const> The mean radius of Jupiter's moon Callisto, expressed in kilometers.
_RAD2HOUR = 3.819718634205488 # 12/pi = factor to convert radians to sidereal hours
_HOUR2RAD = 0.2617993877991494365 # pi/12 = factor to convert sidereal hours to radians
_DAYS_PER_TROPICAL_YEAR = 365.24217
_PI2 = 2.0 * math.pi
_EPOCH = datetime.datetime(2000, 1, 1, 12, tzinfo = datetime.timezone.utc)
_ASEC360 = 1296000.0
_ASEC2RAD = 4.848136811095359935899141e-6
_ARC = 3600.0 * 180.0 / math.pi # arcseconds per radian
_ANGVEL = 7.2921150e-5
_SECONDS_PER_DAY = 24.0 * 3600.0
_SOLAR_DAYS_PER_SIDEREAL_DAY = 0.9972695717592592
_MEAN_SYNODIC_MONTH = 29.530588
_EARTH_ORBITAL_PERIOD = 365.256
_NEPTUNE_ORBITAL_PERIOD = 60189.0
_REFRACTION_NEAR_HORIZON = 34.0 / 60.0
_SUN_RADIUS_KM = 695700.0
_SUN_RADIUS_AU = _SUN_RADIUS_KM / KM_PER_AU
_EARTH_FLATTENING = 0.996647180302104
_EARTH_FLATTENING_SQUARED = _EARTH_FLATTENING ** 2
_EARTH_EQUATORIAL_RADIUS_KM = 6378.1366
_EARTH_POLAR_RADIUS_KM = _EARTH_EQUATORIAL_RADIUS_KM * _EARTH_FLATTENING
_EARTH_EQUATORIAL_RADIUS_AU = _EARTH_EQUATORIAL_RADIUS_KM / KM_PER_AU
_EARTH_MEAN_RADIUS_KM = 6371.0 # mean radius of the Earth's geoid, without atmosphere
_EARTH_ATMOSPHERE_KM = 88.0 # effective atmosphere thickness for lunar eclipses
_EARTH_ECLIPSE_RADIUS_KM = _EARTH_MEAN_RADIUS_KM + _EARTH_ATMOSPHERE_KM
_MOON_EQUATORIAL_RADIUS_KM = 1738.1
_MOON_EQUATORIAL_RADIUS_AU = (_MOON_EQUATORIAL_RADIUS_KM / KM_PER_AU)
_MOON_MEAN_RADIUS_KM = 1737.4
_MOON_POLAR_RADIUS_KM = 1736.0
_MOON_POLAR_RADIUS_AU = (_MOON_POLAR_RADIUS_KM / KM_PER_AU)
_ASEC180 = 180.0 * 60.0 * 60.0
_AU_PER_PARSEC = _ASEC180 / math.pi
_EARTH_MOON_MASS_RATIO = 81.30056
#
# Masses of the Sun and outer planets, used for:
# (1) Calculating the Solar System Barycenter
# (2) Integrating the movement of Pluto
#
# https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf
#
# Page 10 in the above document describes the constants used in the DE405 ephemeris.
# The following are G*M values (gravity constant * mass) in [au^3 / day^2].
# This side-steps issues of not knowing the exact values of G and masses M[i];
# the products GM[i] are known extremely accurately.
#
_SUN_GM = 0.2959122082855911e-03
_MERCURY_GM = 0.4912547451450812e-10
_VENUS_GM = 0.7243452486162703e-09
_EARTH_GM = 0.8887692390113509e-09
_MARS_GM = 0.9549535105779258e-10
_JUPITER_GM = 0.2825345909524226e-06
_SATURN_GM = 0.8459715185680659e-07
_URANUS_GM = 0.1292024916781969e-07
_NEPTUNE_GM = 0.1524358900784276e-07
_PLUTO_GM = 0.2188699765425970e-11
_MOON_GM = _EARTH_GM / _EARTH_MOON_MASS_RATIO
@enum.unique
class _PrecessDir(enum.Enum):
From2000 = 0
Into2000 = 1
def _LongitudeOffset(diff: float) -> float:
offset: float = diff
while offset <= -180.0:
offset += 360.0
while offset > 180.0:
offset -= 360.0
return offset
def _NormalizeLongitude(lon: float) -> float:
while lon < 0.0:
lon += 360.0
while lon >= 360.0:
lon -= 360.0
return lon
def DeltaT_EspenakMeeus(ut: float) -> float:
"""The default Delta T function used by Astronomy Engine.
Espenak and Meeus use a series of piecewise polynomials to
approximate DeltaT of the Earth in their "Five Millennium Canon of Solar Eclipses".
See: https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html
This is the default Delta T function used by Astronomy Engine.
Parameters
----------
ut: float
The floating point number of days since noon UTC on January 1, 2000.
Returns
-------
float
The estimated difference TT-UT on the given date, expressed in seconds.
"""
# Fred Espenak writes about Delta-T generically here:
# https://eclipse.gsfc.nasa.gov/SEhelp/deltaT.html
# https://eclipse.gsfc.nasa.gov/SEhelp/deltat2004.html
# He provides polynomial approximations for distant years here:
# https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html
# They start with a year value 'y' such that y=2000 corresponds
# to the UTC Date 15-January-2000. Convert difference in days
# to mean tropical years.
y = 2000 + ((ut - 14) / _DAYS_PER_TROPICAL_YEAR)
if y < -500:
u = (y - 1820) / 100
return -20 + (32 * u*u)
if y < 500:
u = y / 100
u2 = u*u; u3 = u*u2; u4 = u2*u2; u5 = u2*u3; u6 = u3*u3
return 10583.6 - 1014.41*u + 33.78311*u2 - 5.952053*u3 - 0.1798452*u4 + 0.022174192*u5 + 0.0090316521*u6
if y < 1600:
u = (y - 1000) / 100
u2 = u*u; u3 = u*u2; u4 = u2*u2; u5 = u2*u3; u6 = u3*u3
return 1574.2 - 556.01*u + 71.23472*u2 + 0.319781*u3 - 0.8503463*u4 - 0.005050998*u5 + 0.0083572073*u6
if y < 1700:
u = y - 1600
u2 = u*u; u3 = u*u2
return 120 - 0.9808*u - 0.01532*u2 + u3/7129.0
if y < 1800:
u = y - 1700
u2 = u*u; u3 = u*u2; u4 = u2*u2
return 8.83 + 0.1603*u - 0.0059285*u2 + 0.00013336*u3 - u4/1174000
if y < 1860:
u = y - 1800
u2 = u*u; u3 = u*u2; u4 = u2*u2; u5 = u2*u3; u6 = u3*u3; u7 = u3*u4
return 13.72 - 0.332447*u + 0.0068612*u2 + 0.0041116*u3 - 0.00037436*u4 + 0.0000121272*u5 - 0.0000001699*u6 + 0.000000000875*u7
if y < 1900:
u = y - 1860
u2 = u*u; u3 = u*u2; u4 = u2*u2; u5 = u2*u3
return 7.62 + 0.5737*u - 0.251754*u2 + 0.01680668*u3 - 0.0004473624*u4 + u5/233174
if y < 1920:
u = y - 1900
u2 = u*u; u3 = u*u2; u4 = u2*u2
return -2.79 + 1.494119*u - 0.0598939*u2 + 0.0061966*u3 - 0.000197*u4
if y < 1941:
u = y - 1920
u2 = u*u; u3 = u*u2
return 21.20 + 0.84493*u - 0.076100*u2 + 0.0020936*u3
if y < 1961:
u = y - 1950
u2 = u*u; u3 = u*u2
return 29.07 + 0.407*u - u2/233 + u3/2547
if y < 1986:
u = y - 1975
u2 = u*u; u3 = u*u2
return 45.45 + 1.067*u - u2/260 - u3/718
if y < 2005:
u = y - 2000
u2 = u*u; u3 = u*u2; u4 = u2*u2; u5 = u2*u3
return 63.86 + 0.3345*u - 0.060374*u2 + 0.0017275*u3 + 0.000651814*u4 + 0.00002373599*u5
if y < 2050:
u = y - 2000
return 62.92 + 0.32217*u + 0.005589*u*u
if y < 2150:
u = (y-1820)/100
return -20 + 32*u*u - 0.5628*(2150 - y)
# all years after 2150
u = (y - 1820) / 100
return -20 + (32 * u*u)
_DeltaT = DeltaT_EspenakMeeus
def _TerrestrialTime(ut: float) -> float:
return ut + _DeltaT(ut) / 86400.0
def _UniversalTime(tt: float) -> float:
# This is the inverse function of _TerrestrialTime.
# This is an iterative numerical solver, but because
# the relationship between UT and TT is almost perfectly linear,
# it converges extremely fast (never more than 3 iterations).
dt = _TerrestrialTime(tt) - tt # first approximation of dt = tt - ut
while True:
ut = tt - dt
tt_check = _TerrestrialTime(ut)
err = tt_check - tt
if abs(err) < 1.0e-12:
return ut
dt += err
_TimeRegex = re.compile(r'^([\+\-]?[0-9]+)-([0-9]{2})-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2}(\.[0-9]+)?))?Z)?$')
class Time:
"""Represents a date and time used for performing astronomy calculations.
All calculations performed by Astronomy Engine are based on
dates and times represented by `Time` objects.
Parameters
----------
ut : float
UT1/UTC number of days since noon on January 1, 2000.
See the `ut` attribute of this class for more details.
Attributes
----------
ut : float
The floating point number of days of Universal Time since noon UTC January 1, 2000.
Astronomy Engine approximates UTC and UT1 as being the same thing, although they are
not exactly equivalent; UTC and UT1 can disagree by up to 0.9 seconds.
This approximation is sufficient for the accuracy requirements of Astronomy Engine.
Universal Time Coordinate (UTC) is the international standard for legal and civil
timekeeping and replaces the older Greenwich Mean Time (GMT) standard.
UTC is kept in sync with unpredictable observed changes in the Earth's rotation
by occasionally adding leap seconds as needed.
UT1 is an idealized time scale based on observed rotation of the Earth, which
gradually slows down in an unpredictable way over time, due to tidal drag by the Moon and Sun,
large scale weather events like hurricanes, and internal seismic and convection effects.
Conceptually, UT1 drifts from atomic time continuously and erratically, whereas UTC
is adjusted by a scheduled whole number of leap seconds as needed.
The value in `ut` is appropriate for any calculation involving the Earth's rotation,
such as calculating rise/set times, culumination, and anything involving apparent
sidereal time.
Before the era of atomic timekeeping, days based on the Earth's rotation
were often known as *mean solar days*.
tt : float
Terrestrial Time days since noon on January 1, 2000.
Terrestrial Time is an atomic time scale defined as a number of days since noon on January 1, 2000.
In this system, days are not based on Earth rotations, but instead by
the number of elapsed [SI seconds](https://physics.nist.gov/cuu/Units/second.html)
divided by 86400. Unlike `ut`, `tt` increases uniformly without adjustments
for changes in the Earth's rotation.
The value in `tt` is used for calculations of movements not involving the Earth's rotation,
such as the orbits of planets around the Sun, or the Moon around the Earth.
Historically, Terrestrial Time has also been known by the term *Ephemeris Time* (ET).
"""
def __init__(self, ut : Union[float, str], tt: Optional[float] = None):
if isinstance(ut, str):
# Undocumented hack, to make repr(time) reversible.
other = Time.Parse(ut)
self.ut: float = other.ut
self.tt: float = other.tt
else:
self.ut = ut
if tt is None:
self.tt = _TerrestrialTime(ut)
else:
self.tt = tt
self._et: Optional[_e_tilt] = None # lazy-cache for earth tilt
self._st: Optional[float] = None # lazy-cache for sidereal time
@staticmethod
def FromTerrestrialTime(tt: float) -> "Time":
"""Creates a #Time object from a Terrestrial Time day value.
Parameters
----------
tt : float
The number of days after the J2000 epoch.
Returns
-------
Time
"""
return Time(_UniversalTime(tt), tt)
@staticmethod
def Parse(text: str) -> "Time":
"""Creates a #Time object from a string of the form 'yyyy-mm-ddThh:mm:ss.sssZ'
Parses a UTC date and time from a string and returns a #Time object.
Permits a subset of ISO 8601 format.
The year, month, and day are required.
Hours, minutes, seconds, and fractions of a second are optional.
If time is specified, there must be a 'T' between the date and the time
and a 'Z' at the end of the time.
Parameters
----------
text : string
A string of the following formats:
`yyyy-mm-dd`
`yyyy-mm-ddThh:mmZ`
`yyyy-mm-ddThh:mm:ssZ`
`yyyy-mm-ddThh:mm:ss.sssZ`
Returns
-------
Time
"""
m = _TimeRegex.match(text)
if m is None:
raise DateTimeFormatError(text)
year = int(m.group(1))
month = int(m.group(2))
if not (1 <= month <= 12):
raise DateTimeFormatError(text)
day = int(m.group(3))
if not (1 <= day <= 31):
raise DateTimeFormatError(text)
hour = int(m.group(5) or '0')
if not (0 <= hour <= 23):
raise DateTimeFormatError(text)
minute = int(m.group(6) or '0')
if not (0 <= minute <= 59):
raise DateTimeFormatError(text)
second = float(m.group(8) or '0')
if not (0.0 <= second < 60.0):
raise DateTimeFormatError(text)
return Time.Make(year, month, day, hour, minute, second)
@staticmethod
def Make(year: int, month: int, day: int, hour: int, minute: int, second: float) -> "Time":
"""Creates a #Time object from a UTC calendar date and time.
Parameters
----------
year : int
The UTC year value, e.g. 2019.
month : int
The UTC month in the range 1..12.
day : int
The UTC day of the month, in the range 1..31.
hour : int
The UTC hour, in the range 0..23.
minute : int
The UTC minute, in the range 0..59.
second : float
The real-valued UTC second, in the range [0, 60).
Returns
-------
Time
"""
# This formula is adapted from NOVAS C 3.1 function julian_date().
y = int(year)
m = int(month)
d = int(day)
f = (14 - m) // 12
y2000 = (
(d - 365972956)
+ _cdiv(1461 * (y + 1000000 - f), 4)
+ _cdiv(367 * (m - 2 + f*12), 12)
- _cdiv(3 * _cdiv(y + 1000100 - f, 100), 4)
)
ut = (y2000 - 0.5) + (hour / 24.0) + (minute / 1440.0) + (second / 86400.0)
return Time(ut)
@staticmethod
def Now() -> "Time":
"""Returns the computer's current date and time in the form of a #Time object.
Uses the computer's system clock to find the current UTC date and time.
Converts that date and time to a #Time value and returns the result.
Callers can pass this value to other Astronomy Engine functions to
calculate current observational conditions.
Returns
-------
Time
"""
ut = (datetime.datetime.now(datetime.timezone.utc) - _EPOCH).total_seconds() / 86400.0
return Time(ut)
def AddDays(self, days: float) -> "Time":
"""Calculates the sum or difference of a #Time with a specified real-valued number of days.
Sometimes we need to adjust a given #Time value by a certain amount of time.
This function adds the given real number of days in `days` to the date and time
in the calling object.
More precisely, the result's Universal Time field `ut` is exactly adjusted by `days`
and the Terrestrial Time field `tt` is adjusted for the resulting UTC date and time,
using a best-fit piecewise polynomial model devised by
[Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html).
The value of the calling object is not modified. This function creates a brand new
#Time object and returns it.
Parameters
----------
days : float
A floating point number of days by which to adjust `time`.
May be negative, 0, or positive.
Returns
-------
Time
"""
return Time(self.ut + days)
def __repr__(self) -> str:
return 'Time(\'' + str(self) + '\')'
def __str__(self) -> str:
(year, month, day, hour, minute, second) = self.Calendar()
millis = max(0, min(59999, int(math.floor(1000.0 * second))))
if year < 0:
text = '-{:06d}'.format(-year)
elif year <= 9999:
text = '{:04d}'.format(year)
else:
text = '+{:06d}'.format(year)
text += '-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}.{:03d}Z'.format(month, day, hour, minute, millis // 1000, millis % 1000)
return text
def Calendar(self) -> Tuple[int, int, int, int, int, float]:
"""Returns a tuple of the form (year, month, day, hour, minute, second).
This is a convenience method for converting a `Time` value into
its Gregorian calendar date/time representation.
Unlike the built-in `datetime` class, this method can represent
dates over a nearly 2 million year range: the years -999999 to +999999.
"""
# Adapted from the NOVAS C 3.1 function cal_date().
# [Don Cross - 2023-02-25] Fixed to handle a much wider range of years.
djd = self.ut + 2451545.5
jd = int(math.floor(djd))
x = 24.0 * math.fmod(djd, 1.0)
if x < 0.0:
x += 24.0
hour = int(x)
x = 60.0 * math.fmod(x, 1.0)
minute = int(x)
second = 60.0 * math.fmod(x, 1.0)
c = 2500
k = jd + (68569 + c*146097)
n = _cdiv(4*k, 146097)
k = k - _cdiv(146097*n + 3, 4)
m = _cdiv(4000*(k+1), 1461001)
k = k - _cdiv(1461 * m, 4) + 31
month = _cdiv(80 * k, 2447)
day = k - _cdiv(2447 * month, 80)
k = _cdiv(month, 11)
month = month + 2 - 12 * k
year = 100 * (n - 49) + m + k - c*400
return (year, month, day, hour, minute, second)
def Utc(self) -> datetime.datetime:
"""Returns the UTC date and time as a `datetime` object.
Uses the standard [`datetime`](https://docs.python.org/3/library/datetime.html) class
to represent the date and time in this Time object.
Returns
-------
datetime
"""
return _EPOCH + datetime.timedelta(days=self.ut)
def _etilt(self) -> "_e_tilt":
# Calculates precession and nutation of the Earth's axis.
# The calculations are very expensive, so lazy-evaluate and cache
# the result inside this Time object.
if self._et is None:
self._et = _e_tilt(self)
return self._et
def __lt__(self, other: "Time") -> bool:
return self.tt < other.tt
def __eq__(self, other: object) -> bool:
if not isinstance(other, Time):
return NotImplemented
return self.tt == other.tt
def __le__(self, other: "Time") -> bool:
return self.tt <= other.tt
def __ne__(self, other: object) -> bool:
if not isinstance(other, Time):
return NotImplemented
return self.tt != other.tt
def __gt__(self, other: "Time") -> bool:
return self.tt > other.tt
def __ge__(self, other: "Time") -> bool:
return self.tt >= other.tt
class Vector:
"""A Cartesian vector with 3 space coordinates and 1 time coordinate.
The vector's space coordinates are measured in astronomical units (AU).
The coordinate system varies and depends on context.
The vector also includes a time stamp.
Attributes
----------
x : float
The x-coordinate of the vector, measured in AU.
y : float
The y-coordinate of the vector, measured in AU.
z : float
The z-coordinate of the vector, measured in AU.
t : Time
The date and time at which the coordinate is valid.
"""
def __init__(self, x: float, y: float, z: float, t: Time) -> None:
self.x = x
self.y = y
self.z = z
self.t = t
def __repr__(self) -> str:
return 'Vector({}, {}, {}, {})'.format(self.x, self.y, self.z, repr(self.t))
def Length(self) -> float:
"""Returns the length of the vector in AU."""
# It would be nice to use math.hypot() here,
# but before Python 3.8, it only accepts 2 arguments.
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
def __add__(self, other: "Vector") -> "Vector":
return Vector(self.x + other.x, self.y + other.y, self.z + other.z, self.t)
def __sub__(self, other: "Vector") -> "Vector":
return Vector(self.x - other.x, self.y - other.y, self.z - other.z, self.t)
def __neg__(self) -> "Vector":
return Vector(-self.x, -self.y, -self.z, self.t)
def __truediv__(self, scalar: float) -> "Vector":
return Vector(self.x/scalar, self.y/scalar, self.z/scalar, self.t)
def format(self, coord_format: str) -> str:
"""Returns a custom format string representation of the vector."""
layout = '({:' + coord_format + '}, {:' + coord_format + '}, {:' + coord_format + '}, {})'
return layout.format(self.x, self.y, self.z, str(self.t))
class StateVector:
"""A combination of a position vector, a velocity vector, and a time.
The position (x, y, z) is measured in astronomical units (AU).
The velocity (vx, vy, vz) is measured in AU/day.
The coordinate system varies and depends on context.
The state vector also includes a time stamp.
Attributes
----------
x : float
The x-coordinate of the position, measured in AU.
y : float
The y-coordinate of the position, measured in AU.
z : float
The z-coordinate of the position, measured in AU.
vx : float
The x-component of the velocity, measured in AU/day.
vy : float
The y-component of the velocity, measured in AU/day.
vz : float
The z-component of the velocity, measured in AU/day.
t : Time
The date and time at which the position and velocity vectors are valid.
"""
def __init__(self, x: float, y: float, z: float, vx: float, vy: float, vz: float, t: Time) -> None:
self.x = x
self.y = y
self.z = z
self.vx = vx
self.vy = vy
self.vz = vz
self.t = t
def __repr__(self) -> str:
return 'StateVector(x={}, y={}, z={}, vx={}, vy={}, vz={}, t={})'.format(
self.x, self.y, self.z,
self.vx, self.vy, self.vz,
repr(self.t))
def __add__(self, other: "StateVector") -> "StateVector":
return StateVector(
self.x + other.x,
self.y + other.y,
self.z + other.z,
self.vx + other.vx,
self.vy + other.vy,
self.vz + other.vz,
self.t
)
def __sub__(self, other: "StateVector") -> "StateVector":
return StateVector(
self.x - other.x,
self.y - other.y,
self.z - other.z,
self.vx - other.vx,
self.vy - other.vy,
self.vz - other.vz,
self.t
)
def Position(self) -> Vector:
"""Extracts a position vector from this state vector."""
return Vector(self.x, self.y, self.z, self.t)
def Velocity(self) -> Vector:
"""Extracts a velocity vector from this state vector."""
return Vector(self.vx, self.vy, self.vz, self.t)
@enum.unique
class Body(enum.Enum):
"""The celestial bodies supported by Astronomy Engine calculations.
Values
------
Invalid: An unknown, invalid, or undefined celestial body.
Mercury: The planet Mercury.
Venus: The planet Venus.
Earth: The planet Earth.
Mars: The planet Mars.
Jupiter: The planet Jupiter.
Saturn: The planet Saturn.
Uranus: The planet Uranus.
Neptune: The planet Neptune.
Pluto: The planet Pluto.
Sun: The Sun.
Moon: The Earth's moon.
EMB: The Earth/Moon Barycenter.
SSB: The Solar System Barycenter.
Star1: User-defined star 1.
Star2: User-defined star 2.
Star3: User-defined star 3.
Star4: User-defined star 4.
Star5: User-defined star 5.
Star6: User-defined star 6.
Star7: User-defined star 7.
Star8: User-defined star 8.
"""
Invalid = -1
Mercury = 0
Venus = 1
Earth = 2
Mars = 3
Jupiter = 4
Saturn = 5
Uranus = 6
Neptune = 7
Pluto = 8
Sun = 9
Moon = 10
EMB = 11
SSB = 12
Star1 = 101
Star2 = 102
Star3 = 103
Star4 = 104
Star5 = 105
Star6 = 106
Star7 = 107
Star8 = 108
def MassProduct(body: Body) -> float:
"""Returns the product of mass and universal gravitational constant of a Solar System body.
For problems involving the gravitational interactions of Solar System bodies,
it is helpful to know the product GM, where G = the universal gravitational constant
and M = the mass of the body. In practice, GM is known to a higher precision than
either G or M alone, and thus using the product results in the most accurate results.
This function returns the product GM in the units au^3/day^2.
The values come from page 10 of a
[JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf).
Parameters
----------
body : Body
The body for which to find the GM product.
Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet.
Any other value will cause an exception to be thrown.
Returns
-------
float
The mass product of the given body in au^3/day^2.
"""
if body == Body.Sun: return _SUN_GM
if body == Body.Mercury: return _MERCURY_GM
if body == Body.Venus: return _VENUS_GM
if body == Body.Earth: return _EARTH_GM
if body == Body.Moon: return _MOON_GM
if body == Body.EMB: return _EARTH_GM + _MOON_GM
if body == Body.Mars: return _MARS_GM
if body == Body.Jupiter: return _JUPITER_GM
if body == Body.Saturn: return _SATURN_GM
if body == Body.Uranus: return _URANUS_GM
if body == Body.Neptune: return _NEPTUNE_GM
if body == Body.Pluto: return _PLUTO_GM
raise InvalidBodyError(body)
class _StarDef:
def __init__(self) -> None:
self.ra = 0.0
self.dec = 0.0
self.dist = 0.0 # signals that the star has not yet been defined
_StarTable:List[_StarDef] = [_StarDef() for _ in range(8)]
def _GetStar(body: Body) -> Optional[_StarDef]:
if Body.Star1.value <= body.value <= Body.Star8.value:
return _StarTable[int(body.value - Body.Star1.value)]
return None
def _UserDefinedStar(body: Body) -> Optional[_StarDef]:
star = _GetStar(body)
if star and (star.dist > 0.0):
return star
return None
def DefineStar(body: Body, ra: float, dec: float, distanceLightYears: float) -> None:
"""Assign equatorial coordinates to a user-defined star.
Some Astronomy Engine functions allow their `body` parameter to
be a user-defined fixed point in the sky, loosely called a "star".
This function assigns a right ascension, declination, and distance
to one of the eight user-defined stars `Body.Star1`..`Body.Star8`.
Stars are not valid until defined. Once defined, they retain their
definition until re-defined by another call to `DefineStar`.
Parameters
----------
body: Body
One of the eight user-defined star identifiers: `Body.Star1`, `Body.Star2`, ..., `Body.Star8`.
ra: float
The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ).
The value is in units of sidereal hours, and must be within the half-open range [0, 24).
dec: float
The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ).
The value is in units of degrees north (positive) or south (negative) of the J2000 equator,
and must be within the closed range [-90, +90].
distanceLightYears: float
The distance between the star and the Sun, expressed in light-years.
This value is used to calculate the tiny parallax shift as seen by an observer on Earth.
If you don't know the distance to the star, using a large value like 1000 will generally work well.
The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations.
"""
star = _GetStar(body)
if star is None:
raise InvalidBodyError(body)
if not (0.0 <= ra < 24.0):
raise Error('Invalid right ascension: {}'.format(ra))
if not (-90.0 <= dec <= +90.0):
raise Error('Invalid declination: {}'.format(dec))
star.ra = ra
star.dec = dec
star.dist = distanceLightYears * AU_PER_LY
def BodyCode(name: str) -> Body:
"""Finds the Body enumeration value, given the name of a body.
Parameters
----------
name: str
The common English name of a supported celestial body.
Returns
-------
Body
If `name` is a valid body name, returns the enumeration
value associated with that body.
Otherwise, returns `Body.Invalid`.
Example
-------
>>> astronomy.BodyCode('Mars')
<Body.Mars: 3>
"""
if name not in Body.__members__:
return Body.Invalid
return Body[name]
def _IsSuperiorPlanet(body: Body) -> bool:
return body in [Body.Mars, Body.Jupiter, Body.Saturn, Body.Uranus, Body.Neptune, Body.Pluto]
_PlanetOrbitalPeriod:List[float] = [
87.969,
224.701,
_EARTH_ORBITAL_PERIOD,
686.980,
4332.589,
10759.22,
30685.4,
_NEPTUNE_ORBITAL_PERIOD,
90560.0
]
class Error(Exception):
"""Indicates an error in an astronomical calculation."""
def __init__(self, message: str) -> None:
Exception.__init__(self, message)
class DateTimeFormatError(Error):
"""The syntax of a UTC date/time string was not valid, or it contains invalid values."""
def __init__(self, text: str) -> None:
Error.__init__(self, 'The date/time string is not valid: "{}"'.format(text))
class EarthNotAllowedError(Error):
"""The Earth is not allowed as the celestial body in this calculation."""
def __init__(self) -> None:
Error.__init__(self, 'The Earth is not allowed as the body.')
class InvalidBodyError(Error):
"""The celestial body is not allowed for this calculation."""
def __init__(self, body: Body) -> None:
Error.__init__(self, 'This body is not valid, or is not supported for this calculation: {}'.format(body))
class BadVectorError(Error):
"""A vector magnitude is too small to have a direction in space."""
def __init__(self) -> None:
Error.__init__(self, 'Vector is too small to have a direction.')
class InternalError(Error):
"""An internal error occured that should be reported as a bug.
Indicates an unexpected and unrecoverable condition occurred.
If you encounter this error using Astronomy Engine, it would be very
helpful to report it at the [Issues](https://github.com/cosinekitty/astronomy/issues)
page on GitHub. Please include a copy of the stack trace, along with a description
of how to reproduce the error. This will help improve the quality of
Astronomy Engine for everyone! (Thank you in advance from the author.)
"""
def __init__(self) -> None:
Error.__init__(self, 'Internal error - please report issue, including stack trace, at https://github.com/cosinekitty/astronomy/issues')
class NoConvergeError(Error):
"""A numeric solver did not converge.
Indicates that there was a failure of a numeric solver to converge.
If you encounter this error using Astronomy Engine, it would be very
helpful to report it at the [Issues](https://github.com/cosinekitty/astronomy/issues)
page on GitHub. Please include a copy of the stack trace, along with a description
of how to reproduce the error. This will help improve the quality of
Astronomy Engine for everyone! (Thank you in advance from the author.)
"""
def __init__(self) -> None:
Error.__init__(self, 'Numeric solver did not converge - please report issue at https://github.com/cosinekitty/astronomy/issues')
def PlanetOrbitalPeriod(body: Body) -> float:
"""Returns the average number of days it takes for a planet to orbit the Sun.
Parameters
----------
body : Body
One of the planets: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto.
Returns
-------
float
The mean orbital period of the body in days.
"""
if isinstance(body, Body) and (0 <= body.value < len(_PlanetOrbitalPeriod)):
return _PlanetOrbitalPeriod[int(body.value)]
raise InvalidBodyError(body)
def _SynodicPeriod(body: Body) -> float:
if body == Body.Earth:
raise EarthNotAllowedError()
if body.value < 0 or body.value >= len(_PlanetOrbitalPeriod):
raise InvalidBodyError(body)
if body == Body.Moon:
return _MEAN_SYNODIC_MONTH
return abs(_EARTH_ORBITAL_PERIOD / (_EARTH_ORBITAL_PERIOD/_PlanetOrbitalPeriod[int(body.value)] - 1.0))
def AngleBetween(a: Vector, b: Vector) -> float:
"""Calculates the angle in degrees between two vectors.
Given a pair of vectors, this function returns the angle in degrees
between the two vectors in 3D space.
The angle is measured in the plane that contains both vectors.
Parameters
----------
a : Vector
The first of a pair of vectors between which to measure an angle.
b : Vector
The second of a pair of vectors between which to measure an angle.
Returns
-------
float
The angle between the two vectors expressed in degrees.
The value is in the range [0, 180].
"""
r: float = a.Length() * b.Length()
if r < 1.0e-8:
raise BadVectorError()
dot: float = (a.x*b.x + a.y*b.y + a.z*b.z) / r
if dot <= -1.0:
return 180.0
if dot >= +1.0:
return 0.0
return math.degrees(math.acos(dot))
class Observer:
"""Represents the geographic location of an observer on the surface of the Earth.
Parameters
----------
latitude : float
Geographic latitude in degrees north of the equator.
longitude : float
Geographic longitude in degrees east of the prime meridian at Greenwich, England.
height : float
Elevation above sea level in meters.