-
Notifications
You must be signed in to change notification settings - Fork 3
/
alma_skyfield.py
2253 lines (1938 loc) · 90.6 KB
/
alma_skyfield.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
# -*- coding: utf-8 -*-
# Copyright (C) 2024 Andrew Bauer
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
# This contains the majority of functions that calculate values for the Nautical Almanac
###### Standard library imports ######
# don't confuse the 'date' method with the 'Date' variable!
# the following line includes 'datetime.combine' class method:
from datetime import date, time, datetime, timedelta, timezone
# don't confuse the 'time' instance method in the 'datetime' object with the 'Time' module:
import time as Time # 00000 - stopwatch elements
from math import pi, cos, tan, atan, degrees, copysign
import os
import errno
import socket
import sys # required for .stdout.write()
import urllib.error # used in 'download_EOP' function
from urllib.request import urlopen
from collections import deque
###### Third party imports ######
from skyfield import VERSION
from skyfield.api import Loader
from skyfield.api import Topos, Star, wgs84, N, S, E, W # Topos is deprecated in Skyfield v1.35!
from skyfield import almanac
from skyfield.nutationlib import iau2000b
from skyfield.data import hipparcos
from skyfield.magnitudelib import planetary_magnitude
import numpy as np
###### Local application imports ######
import config
#---------------------------
# Module initialization
#---------------------------
urlIERS = "ftp://ftp.iers.org/products/eop/rapid/standard/"
urlUSNO = "https://maia.usno.navy.mil/ser7/" # alternate location
urlDCIERS = "https://datacenter.iers.org/data/9/" # alternate location
hour_of_day = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
next_hour_of_day = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
degree_sign= u'\N{DEGREE SIGN}'
def SkyfieldVersion(version2): # compare Skyfield version to version2
versions2 = [int(v) for v in version2.split(".")]
for i in range(max(len(VERSION),len(versions2))):
v1 = VERSION[i] if i < len(VERSION) else 0
v2 = versions2[i] if i < len(versions2) else 0
if v1 > v2: return 1
elif v1 < v2: return -1
return 0
def compareVersion(version1, version2):
versions1 = [int(v) for v in version1.split(".")]
versions2 = [int(v) for v in version2.split(".")]
for i in range(max(len(versions1),len(versions2))):
v1 = versions1[i] if i < len(versions1) else 0
v2 = versions2[i] if i < len(versions2) else 0
if v1 > v2: return 1
elif v1 < v2: return -1
return 0
def isConnected():
try:
# connect to the host -- tells us if the host is actually reachable
sock = socket.create_connection(("www.iers.org", 80))
if sock is not None: sock.close
return True
except OSError:
pass
# try alternate source if above server is down ...
try:
# connect to the host -- tells us if the host is actually reachable
sock = socket.create_connection(("maia.usno.navy.mil", 80))
if sock is not None: sock.close
return True
except OSError:
pass
return False # if neither is reachable
# NOTE: the IERS server is unavailable (due to maintenance work in the first 3 weeks, at least, of April 2022)
# however, although the USNO server currently works, it was previously down for 2.5 years!
# So it is still best to try using the IERS server as first oprion, and USNO as second.
def testServer(filename, url):
url += filename
try:
connection2 = urlopen(url)
except Exception as e:
e2 = IOError('cannot download {0} because {1}'.format(url, e))
e2.__cause__ = None
# raise e2
return False
return True # server works
def download_EOP(path, filename, url, loc):
# NOTE: the following 'print' statement does not print immediately in Linux!
#print("Downloading EOP data from USNO...", end ="")
sys.stdout.write("Downloading EOP data from {}...".format(loc))
sys.stdout.flush()
filepath = os.path.join(path, filename)
url += filename
try:
connection = urlopen(url)
except urllib.error.URLError as e:
#raise IOError('error getting {0} - {1}'.format(url, e))
print('\nError getting {0} - {1}'.format(url, e))
sys.exit(0)
blocksize = 128*1024
# Claim our own unique download filename.
tempbase = tempname = path + filename + '.download'
flags = getattr(os, 'O_BINARY', 0) | os.O_CREAT | os.O_EXCL | os.O_RDWR
i = 1
while True:
try:
fd = os.open(tempname, flags, 0o666)
except OSError as e: # "FileExistsError" is not supported by Python 2
if e.errno != errno.EEXIST:
raise
i += 1
tempname = '{0}{1}'.format(tempbase, i)
else:
break
# Download to the temporary filename.
with os.fdopen(fd, 'wb') as w:
try:
length = 0
while True:
data = connection.read(blocksize)
if not data:
break
w.write(data)
length += len(data)
w.flush()
except Exception as e:
raise IOError('error getting {0} - {1}'.format(url, e))
# Rename the temporary file to the destination name.
if os.path.exists(filepath):
os.remove(filepath)
try:
os.rename(tempname, filepath)
except Exception as e:
raise IOError('error renaming {0} to {1} - {2}'.format(tempname, filepath, e))
sys.stdout.write("done.\n")
sys.stdout.flush()
def init_sf(spad):
global ts, eph, earth, moon, sun, venus, mars, jupiter, saturn, df
load = Loader(spad) # spad = folder to store the downloaded files
EOPdf = "finals2000A.all" # Earth Orientation Parameters data file
dfIERS = spad + EOPdf
config.useIERSEOP = False
config.txtIERSEOP = ""
if config.useIERS:
if SkyfieldVersion("1.31") >= 0:
if os.path.isfile(dfIERS):
if load.days_old(EOPdf) > float(config.ageIERS):
if isConnected():
if testServer(EOPdf, urlIERS): # first try downloading via FTP
load.download(EOPdf)
elif testServer(EOPdf, urlUSNO):# then try the USNO server
download_EOP(spad,EOPdf,urlUSNO,"USNO")
else: # finally try the IERS datacenter (available in more countries)
download_EOP(spad,EOPdf,urlDCIERS,"IERS datacenter")
else: print("NOTE: no Internet connection... using existing '{}'".format(EOPdf))
ts = load.timescale(builtin=False) # timescale object
config.useIERSEOP = True
else:
if isConnected():
if testServer(EOPdf, urlIERS): # first try downloading via FTP
load.download(EOPdf)
elif testServer(EOPdf, urlUSNO):# then try the USNO server
download_EOP(spad,EOPdf,urlUSNO,"USNO")
else: # finally try the IERS datacenter (available in more countries)
download_EOP(spad,EOPdf,urlDCIERS,"IERS datacenter")
ts = load.timescale(builtin=False) # timescale object
config.useIERSEOP = True
else:
print("NOTE: no Internet connection... using built-in UT1-tables")
ts = load.timescale() # timescale object with built-in UT1-tables
else:
ts = load.timescale() # timescale object with built-in UT1-tables
else:
ts = load.timescale() # timescale object with built-in UT1-tables
if config.useIERSEOP and os.path.isfile(dfIERS):
# get the IERS EOP data "release date" according to these rules:
# - begin searching within this millenium (ignoring data from 02 Jan 1973 to 31 Dec 1999)
# - halt when the following value is "P", i.e. predicted as opposed to measured:
# - flag for Bull. A UT1-UTC values
# - step back one day to the record that has "I", i.e. measured data.
#
# the date of this record is the last date with IERS measured data.
# [the more recent the date, the more accurate/reliable are both the past IERS
# Earth Orientation Parameters as well as the future (predicted) EOP data values.]
# IERS EOP data format definition:
# https://maia.usno.navy.mil/ser7/readme.finals2000A
queue = deque(["a", "b", "c", "d"])
PredData = False # True when Prediction data flagged
PredEnd = False # True when Prediction data no longer flagged
iers = ""
with open(dfIERS) as file:
for line in file:
mjd = int(line[7:12])
if not PredData and mjd >= 51544: # skip data in previous millenium
queue.append(line)
queue.popleft()
c1 = line[16:17] # IERS (I) or Prediction (P) flag for Bull. A polar motion values
c2 = line[57:58] # IERS (I) or Prediction (P) flag for Bull. A UT1-UTC values
c3 = line[95:96] # IERS (I) or Prediction (P) flag for Bull. A nutation values
if not PredData and c2 == "P":
PredData = True
iers = ""
while queue:
iersdata = queue.pop()
if iersdata[57:58] == "I":
iers = iersdata
break
if iers == "": iers = iersdata
year = int(iers[0:2]) + 2000
mth = int(iers[2:4])
day = int(iers[4:6])
dt = date(year, mth, day)
config.txtIERSEOP = "IERS Earth Orientation data as of " + dt.strftime("%d-%b-%Y")
elif PredData: # search for end of Prediction data
c2 = line[57:58] # IERS (I) or Prediction (P) flag for Bull. A UT1-UTC values
if c2 == "P":
iers = line
else:
PredEnd = True
break
if iers == "":
print("Error: IERS Earth Orientation Parameters data file is incomplete...")
print(" most likely the download did not finish properly.")
print(" Please delete the 'finals2000A.all' data file and")
print(" rerun this program - it will be downloaded anew.")
sys.exit(0)
# detect end of Prediction data even if file ends with c2 == "P" ...
year = int(iers[0:2]) + 2000
mth = int(iers[2:4])
day = int(iers[4:6])
dt2 = date(year, mth, day)
config.endIERSEOP = "IERS Earth Orientation predictions end " + dt2.strftime("%d-%b-%Y")
config.dt_IERSEOP = dt2
if config.ephndx in set([0, 1, 2, 3, 4]):
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
moon = eph['moon']
sun = eph['sun']
venus = eph['venus']
jupiter = eph['jupiter barycenter']
saturn = eph['saturn barycenter']
if config.ephndx >= 3:
mars = eph['mars barycenter']
else:
mars = eph['mars']
# load the Hipparcos catalog as a 118,218 row Pandas dataframe.
with load.open(hipparcos.URL) as f:
#hipparcos_epoch = ts.tt(1991.25)
df = hipparcos.load_dataframe(f)
return ts
#------------------------
# internal functions
#------------------------
def norm(delta):
# normalize the angle between 0° and 360°
# (usually delta is roughly 15 degrees)
while delta < 0:
delta += 360.0
while delta >= 360.0:
delta -= 360.0
return delta
def GHAcolong(gha):
# return the colongitude, e.g. 270° returns 90°
coGHA = gha + 180
while coGHA > 360:
coGHA -= 360
return coGHA
def fmtgha(gst, ra):
# formats angle (hours) to that used in the nautical almanac. (ddd°mm.m)
sha = (gst - ra) * 15
if sha < 0:
sha += 360
return fmtdeg(sha)
def gha2deg(gst, ra):
# convert GHA (hours) to degrees of arc
sha = (gst - ra) * 15
while sha < 0:
sha += 360
return sha
def fmtdeg(deg, fixedwidth=1):
# formats the angle (deg) to that used in the nautical almanac (ddd°mm.m)
# the optional argument specifies the minimum width for the degrees
theminus = ""
if deg < 0:
theminus = '-'
df = abs(deg)
di = int(df)
mf = round((df-di)*60, 1) # minutes (float), rounded to 1 decimal place
mi = int(mf) # minutes (integer)
if mi == 60:
mf -= 60
di += 1
if di == 360:
di = 0
if fixedwidth == 2:
gm = "{}{:02d}$^\circ${:04.1f}".format(theminus,di,mf)
else:
if fixedwidth == 3:
gm = "{}{:03d}$^\circ${:04.1f}".format(theminus,di,mf)
else:
gm = "{}{}$^\circ${:04.1f}".format(theminus,di,mf)
return gm
def time2text(t, with_seconds, debug=False):
# note: times printed are ROUNDED appropriately to the minute or second - for proof, enable 'debug'
if debug:
dt = t.utc_datetime() # convert to python datetime in UTC
ut1 = dt + timedelta(seconds=t.dut1) # convert to datetime in UT1
print(" ",ut1.isoformat(' ')," ",t.ut1_strftime('%H:%M:%S')," ",t.ut1_strftime('%H:%M'))
# Note: ..._strftime functionality:
# If the smallest time unit in your format is minutes or seconds, then the time is rounded
# to the nearest minute or second. Otherwise the value is truncated rather than rounded.
if with_seconds:
return t.ut1_strftime('%H:%M:%S')
else:
return t.ut1_strftime('%H:%M')
def next_rise_set(rise, sett, yR, yS):
ndxR = 0 if len(rise) > 0 else 10
ndxS = 0 if len(sett) > 0 else 10
pickRISE = None # no idea if RISE or SET comes first and is valid
prev_dt = datetime.min.replace(tzinfo=timezone.utc) # closest to datetime zero
currentstate = None # current state at start of selected time period
while ndxR < len(rise) or ndxS < len(sett):
if pickRISE is None: # establish if RISE or SET to be chosen (initialize pickRISE)
RISEok = SETTok = False
if ndxR < len(rise): RISEok = True
if ndxS < len(sett): SETTok = True
if RISEok and not SETTok: pickRISE = True
if SETTok and not RISEok: pickRISE = False
if RISEok and SETTok:
pickRISE = True if rise[ndxR] < sett[ndxS] else False # Skyfield >= 1.48 rqrd
if not RISEok and not SETTok: ndxR += 1; ndxS += 1
continue # avoid 't.utc_datetime()' below as 't' unknown
elif pickRISE:
t = rise[ndxR]
if yR[ndxR]: currentstate = False; break
ndxR += 1
pickRISE = False # flip RISE to SET & vice-versa
else:
t = sett[ndxS]
if yS[ndxS]: currentstate = True; break
ndxS += 1
pickRISE = True # flip RISE to SET & vice-versa
dt = t.utc_datetime()
if prev_dt > dt:
print("Event time sequence ERROR in alma_skyfield.next_rise_set:".format(dt.strftime("%d-%m-%Y")))
print(" {} is followed by {}".format(prev_dt.strftime("%d-%m-%Y %H:%M"),dt.strftime("%d-%m-%Y %H:%M")))
sys.exit(0)
prev_dt = dt
return currentstate
def fmt_rise_set(rise, sett, yR, yS, txt, with_seconds=False):
# note: yR and yS are passed here as it is not possible to .pop() a False time from the Time object.
# note: if yR or yS returns [], it is interpreted as False. However the time would also be [].
ndxR = 0 if len(rise) > 0 else 10
ndxS = 0 if len(sett) > 0 else 10
pickRISE = None # no idea if RISE or SET comes first and is valid
prev_dt = datetime.min.replace(tzinfo=timezone.utc) # closest to datetime zero
r = s = 0
Rtxt = ['--:--', '--:--'] #if not with_seconds else ['--:--:--', '--:--:--']
Stxt = ['--:--', '--:--'] #if not with_seconds else ['--:--:--', '--:--:--']
# 'finalstate' is True if above horizon; False if below horizon; None if unknown
finalstate = None
while ndxR < len(rise) or ndxS < len(sett):
if pickRISE is None: # establish if RISE or SET to be chosen (initialize pickRISE)
RISEok = SETTok = False
if ndxR < len(rise): RISEok = True
if ndxS < len(sett): SETTok = True
if RISEok and not SETTok: pickRISE = True
if SETTok and not RISEok: pickRISE = False
if RISEok and SETTok:
pickRISE = True if rise[ndxR] < sett[ndxS] else False # Skyfield >= 1.48 rqrd
if not RISEok and not SETTok: ndxR += 1; ndxS += 1
continue # avoid 't.utc_datetime()' below as 't' unknown
elif pickRISE:
if ndxR < len(rise):
t = rise[ndxR]
if yR[ndxR]:
Rtxt[r] = time2text(t, with_seconds)
r += 1; finalstate = True
ndxR += 1
pickRISE = False # flip RISE to SET & vice-versa
else:
if ndxS < len(sett):
t = sett[ndxS]
if yS[ndxS]:
Stxt[s] = time2text(t, with_seconds)
s += 1; finalstate = False
ndxS += 1
pickRISE = True # flip RISE to SET & vice-versa
dt = t.utc_datetime()
if prev_dt > dt:
print("Event time sequence ERROR in alma_skyfield.fmt_rise_set:")
print(" latitude {}: {} is followed by {}".format(txt, prev_dt.strftime("%d-%m-%Y %H:%M"),dt.strftime("%d-%m-%Y %H:%M")))
sys.exit(0)
prev_dt = dt
return Rtxt[0], Stxt[0], Rtxt[1], Stxt[1], finalstate
def fmt_transits(t, txt, with_seconds=False):
# analyse the return values from the 'find_transits' method...
# get planet transit times (if any) rounded to nearest minute
transit1 = '--:--'
transit2 = '--:--'
if len(t) == 1: # this happens most often
t0 = t[0]
# get the UT1 time rounded to minutes OR seconds ...
transit1 = time2text(t0, with_seconds)
else:
if len(t) == 2: # this happens very rarely
t0 = t[0]; t1 = t[1]
# get the UT1 time rounded to minutes OR seconds ...
transit1 = time2text(t0, with_seconds)
transit2 = time2text(t1, with_seconds)
elif len(t) > 2:
# this should never get here!
rise_set_error(0,txt,t[0])
return transit1, transit2
def rise_set(t, y, txt, with_seconds=False):
# analyse the return values from the 'find_discrete' method...
# get sun/moon rise/set values (if any) rounded to nearest minute
rise = '--:--'
sett = '--:--'
ris2 = '--:--'
set2 = '--:--'
# 'finalstate' is True if above horizon; False if below horizon; None if unknown
finalstate = None
if len(t) == 2: # this happens most often
t0 = t[0]; t1 = t[1] # Aug 2024 simplification
if y[0] and not(y[1]):
# get the UT1 time rounded to minutes OR seconds ...
rise = time2text(t0, with_seconds)
sett = time2text(t1, with_seconds)
finalstate = False
else:
if not(y[0]) and y[1]:
# get the UT1 time rounded to minutes OR seconds ...
sett = time2text(t0, with_seconds)
rise = time2text(t1, with_seconds)
finalstate = True
else:
# this should never get here!
rise_set_error(y,txt,t[0]) # Aug 2024 simplification
else:
if len(t) == 1: # this happens ocassionally
t0 = t[0] # Aug 2024 simplification
if y[0]:
# get the UT1 time rounded to minutes OR seconds ...
rise = time2text(t0, with_seconds)
finalstate = True
else:
# get the UT1 time rounded to minutes OR seconds ...
sett = time2text(t0, with_seconds)
finalstate = False
else:
if len(t) == 3: # this happens rarely (in high latitudes mid-year)
t0 = t[0]; t1 = t[1]; t2 = t[2] # Aug 2024 simplification
if y[0] and not(y[1]) and y[2]:
# get the UT1 time rounded to minutes OR seconds ...
rise = time2text(t0, with_seconds)
sett = time2text(t1, with_seconds)
ris2 = time2text(t2, with_seconds)
finalstate = True
else:
if not(y[0]) and y[1] and not(y[2]):
# get the UT1 time rounded to minutes OR seconds ...
sett = time2text(t0, with_seconds)
rise = time2text(t1, with_seconds)
set2 = time2text(t2, with_seconds)
finalstate = False
else:
# this should never get here!
rise_set_error(y,txt,t[0]) # Aug 2024 simplification
else:
if len(t) > 3:
# this should never get here!
rise_set_error(y,txt,t[0]) # Aug 2024 simplification
return rise, sett, ris2, set2, finalstate
def rise_set_error(y, txt, t0):
# unexpected rise/set values - format message line
msg = "rise_set {} values for {}: {}".format(len(y),txt, y[0])
if len(y) > 1:
msg = msg + " {}".format(y[1])
if len(y) > 2:
msg = msg + " {}".format(y[2])
if len(y) > 3:
msg = msg + " {}".format(y[3])
dt = t0.utc_datetime() + timedelta(seconds = t0.dut1)
if config.logfileopen:
# write to log file
config.writeLOG("\n{}".format(dt.isoformat()))
config.writeLOG(" " + msg)
else:
# print to console
print("{} {}".format(dt.isoformat(), msg))
return
#-------------------------------
# Miscellaneous
#-------------------------------
def getDUT1(d): # used in nautical.doublepage
# obtain calculation parameters
t = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
return t.dut1, t.delta_t
#-------------------------------
# Sun and Moon calculations
#-------------------------------
def sunGHA(d): # used in nautical.sunmoontab(m)
# compute sun's GHA and DEC per hour of day
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(sun)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
ghas = ['' for x in range(24)]
decs = ['' for x in range(24)]
degs = ['' for x in range(24)]
for i in range(len(dec.degrees)):
ghas[i] = fmtgha(t[i].gast, ra.hours[i])
decs[i] = fmtdeg(dec.degrees[i],2)
degs[i] = dec.degrees[i]
#for i in range(len(dec.degrees)):
# print(i, ghas[i])
# degs has been added for the suntab function
return ghas,decs,degs
def sunSD(d): # used in nautical.sunmoontab(m)
# compute semi-diameter of sun and sun's declination change per hour (in minutes)
t00 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
#t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0)
position = earth.at(t00).observe(sun)
distance = position.apparent().radec(epoch='date')[2]
dist_km = distance.km
# OLD: sds = degrees(atan(695500.0 / dist_km)) # radius of sun = 695500 km
svmr = degrees(atan(695700.0 / dist_km)) # volumetric mean radius of sun = 695700 km
sunVMRm = "{:0.1f}".format(svmr * 60) # convert to minutes of arc
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(sun)
dec0 = position0.apparent().radec(epoch='date')[1]
D0 = dec0.degrees * 60.0 # convert to minutes of arc
t1= ts.ut1(d.year, d.month, d.day, 1, 0, 0)
position1 = earth.at(t1).observe(sun)
dec1 = position1.apparent().radec(epoch='date')[1]
D1 = dec1.degrees * 60.0 # convert to minutes of arc
if config.d_valNA:
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
sunDm = "{:0.1f}".format(Dvalue)
return sunVMRm, sunDm
def moonSD(d): # used in nautical.sunmoontab(m)
# compute semi-diameter of moon (in minutes)
t00 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
#t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0)
position = earth.at(t00).observe(moon)
distance = position.apparent().radec(epoch='date')[2]
dist_km = distance.km
# OLD: sdm = degrees(atan(1738.1/dist_km)) # equatorial radius of moon = 1738.1 km
sdm = degrees(atan(1737.4/dist_km)) # volumetric mean radius of moon = 1737.4 km
sdmm = "{:0.1f}".format(sdm * 60) # convert to minutes of arc
return sdmm
def moonGHA(d, with_seconds = False): # used in nautical.sunmoontab(m) & eventtables.equationtab
# compute moon's GHA, DEC and HP per hour of day
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(moon)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
#distance = position.apparent().radec(epoch='date')[2]
ra, dec, distance = position.apparent().radec(epoch='date')
if with_seconds:
# also compute moon's GHA at End of Day (23:59:59.5) and Start of Day (24 hours earlier)
tSoD = ts.ut1(d.year, d.month, d.day-1, 23, 59, 59.5)
tEoD = ts.ut1(d.year, d.month, d.day, 23, 59, 59.5)
else: # round to minutes of time
# also compute moon's GHA at End of Day (23:59:30) and Start of Day (24 hours earlier)
tSoD = ts.ut1(d.year, d.month, d.day-1, 23, 59, 30)
tEoD = ts.ut1(d.year, d.month, d.day, 23, 59, 30)
posSoD = earth.at(tSoD).observe(moon)
raSoD = posSoD.apparent().radec(epoch='date')[0]
ghaSoD = gha2deg(tSoD.gast, raSoD.hours) # GHA as float
posEoD = earth.at(tEoD).observe(moon)
raEoD = posEoD.apparent().radec(epoch='date')[0]
ghaEoD = gha2deg(tEoD.gast, raEoD.hours) # GHA as float
GHAupper = [-1.0 for x in range(24)]
GHAlower = [-1.0 for x in range(24)]
gham = ['' for x in range(24)]
decm = ['' for x in range(24)]
degm = ['' for x in range(24)]
HPm = ['' for x in range(24)]
for i in range(len(dec.degrees)):
## raIDL = ra.hours[i] + 12 # at International Date Line
## if raIDL > 24: raIDL = raIDL - 24
GHAupper[i] = gha2deg(t[i].gast, ra.hours[i]) # GHA as float
GHAlower[i] = GHAcolong(GHAupper[i])
gham[i] = fmtgha(t[i].gast, ra.hours[i])
decm[i] = fmtdeg(dec.degrees[i],2)
degm[i] = dec.degrees[i]
dist_km = distance.km[i]
# OLD: HP = degrees(atan(6378.0/dist_km)) # radius of earth = 6378.0 km
HP = degrees(atan(6371.0/dist_km)) # volumetric mean radius of earth = 6371.0 km
HPm[i] = "{:0.1f}'".format(HP * 60) # convert to minutes of arc
# degm has been added for the sunmoontab function
# GHAupper is an array of GHA per hour as float
# ghaSoD, ghaEoD = GHA at Start/End of Day as time is rounded to hh:mm (or hh:mm:ss)
return gham, decm, degm, HPm, GHAupper, GHAlower, ghaSoD, ghaEoD
def moonVD(d00, d): # used in nautical.sunmoontab(m)
# OLD: # first value required is from 23:30 on the previous day...
# OLD: t0 = ts.ut1(d00.year, d00.month, d00.day, 23, 30, 0)
# first value required is at 00:00 on the current day...
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
pos0 = earth.at(t0).observe(moon)
#ra0 = pos0.apparent().radec(epoch='date')[0]
#dec0 = pos0.apparent().radec(epoch='date')[1]
ra0, dec0, _ = pos0.apparent().radec(epoch='date')
V0 = gha2deg(t0.gast, ra0.hours)
D0 = dec0.degrees * 60.0 # convert to minutes of arc
if config.d_valNA:
D0 = round(D0, 1)
# OLD: # ...then 24 values at hourly intervals from 23:30 onwards
# OLD: t = ts.ut1(d.year, d.month, d.day, hour_of_day, 30, 0)
# ...then 24 values at hourly intervals from 00:00 onwards
t = ts.ut1(d.year, d.month, d.day, next_hour_of_day, 0, 0)
position = earth.at(t).observe(moon)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
moonVm = ['' for x in range(24)]
moonDm = ['' for x in range(24)]
for i in range(len(dec.degrees)):
V1 = gha2deg(t[i].gast, ra.hours[i])
Vdelta = V1 - V0
if Vdelta < 0: Vdelta += 360
Vdm = (Vdelta-(14.0+(19.0/60.0))) * 60 # subtract 14:19:00
moonVm[i] = "{:0.1f}'".format(Vdm)
D1 = dec.degrees[i] * 60.0 # convert to minutes of arc
if config.d_valNA:
D1 = round(D1, 1)
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
moonDm[i] = "{:0.1f}'".format(Dvalue)
V0 = V1 # store current value as next previous value
D0 = D1 # store current value as next previous value
return moonVm, moonDm
#------------------------------------------------
# Venus, Mars, Jupiter & Saturn calculations
#------------------------------------------------
def venusGHA(d): # used in nautical.planetstab(m)
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(venus)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
ghas = ['' for x in range(24)]
decs = ['' for x in range(24)]
degs = ['' for x in range(24)]
for i in range(len(dec.degrees)):
ghas[i] = fmtgha(t[i].gast, ra.hours[i])
decs[i] = fmtdeg(dec.degrees[i],2)
degs[i] = dec.degrees[i]
#for i in range(len(dec.degrees)):
# print(i, ghas[i])
return ghas, decs, degs
def marsGHA(d): # used in nautical.planetstab(m)
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(mars)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
ghas = ['' for x in range(24)]
decs = ['' for x in range(24)]
degs = ['' for x in range(24)]
for i in range(len(dec.degrees)):
ghas[i] = fmtgha(t[i].gast, ra.hours[i])
decs[i] = fmtdeg(dec.degrees[i],2)
degs[i] = dec.degrees[i]
#for i in range(len(dec.degrees)):
# print(i, ghas[i])
return ghas, decs, degs
def jupiterGHA(d): # used in nautical.planetstab(m)
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(jupiter)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
ghas = ['' for x in range(24)]
decs = ['' for x in range(24)]
degs = ['' for x in range(24)]
for i in range(len(dec.degrees)):
ghas[i] = fmtgha(t[i].gast, ra.hours[i])
decs[i] = fmtdeg(dec.degrees[i],2)
degs[i] = dec.degrees[i]
#for i in range(len(dec.degrees)):
# print(i, ghas[i])
return ghas, decs, degs
def saturnGHA(d): # used in nautical.planetstab(m)
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
position = earth.at(t).observe(saturn)
#ra = position.apparent().radec(epoch='date')[0]
#dec = position.apparent().radec(epoch='date')[1]
ra, dec, _ = position.apparent().radec(epoch='date')
ghas = ['' for x in range(24)]
decs = ['' for x in range(24)]
degs = ['' for x in range(24)]
for i in range(len(dec.degrees)):
ghas[i] = fmtgha(t[i].gast, ra.hours[i])
decs[i] = fmtdeg(dec.degrees[i],2)
degs[i] = dec.degrees[i]
#for i in range(len(dec.degrees)):
# print(i, ghas[i])
return ghas, decs, degs
def vdm_Venus(d): # used in nautical.planetstab(m)
# compute v (GHA correction), d (Declination correction), m (magnitude of planet)
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(venus)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#dec0 = position0.apparent().radec(epoch='date')[1] # declination
ra0, dec0, _ = position0.apparent().radec(epoch='date')
D0 = dec0.degrees * 60.0 # convert to minutes of arc
mag = "{:0.2f}".format(planetary_magnitude(position0)) # planetary magnitude
t1 = ts.ut1(d.year, d.month, d.day, 1, 0, 0)
position1 = earth.at(t1).observe(venus)
#ra1 = position1.apparent().radec(epoch='date')[0] # RA
#dec1 = position1.apparent().radec(epoch='date')[1] # declination
ra1, dec1, _ = position1.apparent().radec(epoch='date')
D1 = dec1.degrees * 60.0 # convert to minutes of arc
sha0 = (t0.gast - ra0.hours) * 15
sha1 = (t1.gast - ra1.hours) * 15
sha = norm(sha1 - sha0) - 15
RAcorrm = "{:0.1f}".format(sha * 60) # convert to minutes of arc
if config.d_valNA:
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
venusDm = "{:0.1f}".format(Dvalue)
return RAcorrm, venusDm, mag
def vdm_Mars(d): # used in nautical.planetstab(m)
# compute v (GHA correction), d (Declination correction)
# NOTE: m (magnitude of planet) comes from alma_ephem.py
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(mars)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#dec0 = position0.apparent().radec(epoch='date')[1] # declination
ra0, dec0, _ = position0.apparent().radec(epoch='date')
D0 = dec0.degrees * 60.0 # convert to minutes of arc
mag = "{:0.2f}".format(planetary_magnitude(position0)) # planetary magnitude
t1 = ts.ut1(d.year, d.month, d.day, 1, 0, 0)
position1 = earth.at(t1).observe(mars)
#ra1 = position1.apparent().radec(epoch='date')[0] # RA
#dec1 = position1.apparent().radec(epoch='date')[1] # declination
ra1, dec1, _ = position1.apparent().radec(epoch='date')
D1 = dec1.degrees * 60.0 # convert to minutes of arc
sha0 = (t0.gast - ra0.hours) * 15
sha1 = (t1.gast - ra1.hours) * 15
sha = norm(sha1 - sha0) - 15
RAcorrm = "{:0.1f}".format(sha * 60) # convert to minutes of arc
if config.d_valNA:
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
marsDm = "{:0.1f}".format(Dvalue)
return RAcorrm, marsDm, mag
def vdm_Jupiter(d): # used in nautical.planetstab(m)
# compute v (GHA correction), d (Declination correction), m (magnitude of planet)
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(jupiter)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#dec0 = position0.apparent().radec(epoch='date')[1] # declination
ra0, dec0, _ = position0.apparent().radec(epoch='date')
D0 = dec0.degrees * 60.0 # convert to minutes of arc
mag = "{:0.2f}".format(planetary_magnitude(position0)) # planetary magnitude
t1 = ts.ut1(d.year, d.month, d.day, 1, 0, 0)
position1 = earth.at(t1).observe(jupiter)
#ra1 = position1.apparent().radec(epoch='date')[0] # RA
#dec1 = position1.apparent().radec(epoch='date')[1] # declination
ra1, dec1, _ = position1.apparent().radec(epoch='date')
D1 = dec1.degrees * 60.0 # convert to minutes of arc
sha0 = (t0.gast - ra0.hours) * 15
sha1 = (t1.gast - ra1.hours) * 15
sha = norm(sha1 - sha0) - 15
RAcorrm = "{:0.1f}".format(sha * 60) # convert to minutes of arc
if config.d_valNA:
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
jupDm = "{:0.1f}".format(Dvalue)
return RAcorrm, jupDm, mag
def vdm_Saturn(d): # used in nautical.planetstab(m)
# compute v (GHA correction), d (Declination correction)
# NOTE: m (magnitude of planet) comes from alma_ephem.py
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(saturn)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#dec0 = position0.apparent().radec(epoch='date')[1] # declination
ra0, dec0, _ = position0.apparent().radec(epoch='date')
D0 = dec0.degrees * 60.0 # convert to minutes of arc
mag = "{:0.2f}".format(planetary_magnitude(position0)) # planetary magnitude
t1 = ts.ut1(d.year, d.month, d.day, 1, 0, 0)
position1 = earth.at(t1).observe(saturn)
#ra1 = position1.apparent().radec(epoch='date')[0] # RA
#dec1 = position1.apparent().radec(epoch='date')[1] # declination
ra1, dec1, _ = position1.apparent().radec(epoch='date')
D1 = dec1.degrees * 60.0 # convert to minutes of arc
sha0 = (t0.gast - ra0.hours) * 15
sha1 = (t1.gast - ra1.hours) * 15
sha = norm(sha1 - sha0) - 15
RAcorrm = "{:0.1f}".format(sha * 60) # convert to minutes of arc
if config.d_valNA:
Dvalue = abs(D1 - D0)
elif copysign(1.0,D1) == copysign(1.0,D0):
Dvalue = abs(D1) - abs(D0)
else:
Dvalue = -abs(D1 - D0)
satDm = "{:0.1f}".format(Dvalue)
return RAcorrm, satDm, mag
#-----------------------------------------
# Aries & planet transit calculations
#-----------------------------------------
def ariesGHA(d): # used in nautical.planetstab(m)
t = ts.ut1(d.year, d.month, d.day, hour_of_day, 0, 0)
ghas = ['' for x in range(24)]
for i in range(24):
ghas[i] = fmtgha(t[i].gast, 0)
return ghas
def ariestransit(d): # used in nautical.planetstab(m)
# returns transit time of aries for the *PREVIOUS* date
t = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
trans = 24 - (t.gast / 1.00273790935)
hr = int(trans)
# round >=30 seconds to next minute
#min = tup[-2] + int(round(tup[-1]/60+0.00001))
min = int(round((trans - hr) * 60))
if min == 60:
min = 0
hr += 1
if hr == 24:
hr = 0
ttime = '{:02d}:{:02d}'.format(hr,min)
return ttime
def planetstransit(d, with_seconds = False): # used in nautical.starstab & eventtables.meridiantab
# returns SHA and Meridian Passage for the navigational planets
d1 = d + timedelta(days=1)
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
t1 = ts.ut1(d1.year, d1.month, d1.day, 0, 0, 0)
if SkyfieldVersion("1.48") >= 0:
topos = wgs84.latlon(0.0 * N, 0.0 * E, elevation_m=0.0) # default latitude 0°N (any will do)
observer = earth + topos
# Venus
position0 = earth.at(t0).observe(venus)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#vau = position0.apparent().radec(epoch='date')[2] # distance
ra0, _, vau = position0.apparent().radec(epoch='date')
vsha = fmtgha(0, ra0.hours)
hpvenus = "{:0.1f}".format((tan(6371/(vau.au*149597870.7)))*60*180/pi)
#position = earth.at(t0).observe(venus)
#ra = position.apparent().radec(epoch='date')[0]
#print('Venus transit: ', t0.gast, ra.hours)
# calculate planet transit
start00 = Time.time() # 00000
if SkyfieldVersion("1.48") < 0:
transit_time, y = almanac.find_discrete(t0, t1, planet_transit(venus))
config.stopwatch += Time.time()-start00 # 00000
vtrans = rise_set(transit_time,y,u'Venus 0{} E transit'.format(degree_sign),with_seconds)[0]
else:
transit_time = almanac.find_transits(observer, venus, t0, t1)
config.stopwatch += Time.time()-start00 # 00000
vtrans = fmt_transits(transit_time,u'Venus 0{} E transit'.format(degree_sign),with_seconds)[0]
#if len(transit_time) != 1:
# print('Venus returned %s transit values' %len(transit_time))
# Mars
position0 = earth.at(t0).observe(mars)
#ra0 = position0.apparent().radec(epoch='date')[0] # RA
#mau = position0.apparent().radec(epoch='date')[2] # distance
ra0, _, mau = position0.apparent().radec(epoch='date')