-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmp_nautical.py
1280 lines (1117 loc) · 52.8 KB
/
mp_nautical.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 MODULE IS OPTIMIZED SPECIFICALLY FOR MULTIPROCESSING (DATA BASED PARALELLISM)
# Note: 6 worker processes are sufficient
# Note: read/write to a global variable will occur randomly and give false
# results, e.g. if 'moonvisible[]' is declared here.
# Note: incrementing elapsed time in config.stopwatch fails: result is 0.0
# Shared memory: It is NOT possible to share arbitrary Python objects.
# Multiprocessing can create shared memory blocks containing C
# variables and C arrays. A NumPy extension adds shared NumPy arrays.
# ----------------------------------------------------------------------------------
###### Standard library imports ######
from datetime import datetime, timedelta, timezone
from time import time # 00000 - stopwatch elements
from math import degrees, atan, tan, pi, copysign
#import sys # sys.exit() does not work here
###### Third party imports ######
from skyfield import VERSION
from skyfield.api import load
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
###### Local application imports ######
import config
#----------------------
# initialization
#----------------------
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}'
#----------------------
# internal methods
#----------------------
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 GHAcolong(gha):
# return the colongitude, e.g. 270° returns 90°
coGHA = gha + 180
while coGHA > 360:
coGHA = coGHA - 360
return coGHA
def gha2deg(gst, ra):
# convert GHA (hours) to degrees of arc
sha = (gst - ra) * 15
while sha < 0:
sha = 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 fmtgha(gst, ra):
# formats angle (hours) to that used in the nautical almanac. (ddd°mm.m)
sha = (gst - ra) * 15
if sha < 0:
sha = sha + 360
return fmtdeg(sha)
def time2text(t, with_seconds):
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
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 = not pickRISE # flip RISE to SET & vice-versa
else:
t = sett[ndxS]
if yS[ndxS]: currentstate = True; break
ndxS += 1
pickRISE = not pickRISE # flip RISE to SET & vice-versa
dt = t.utc_datetime()
if prev_dt > dt: print("Event time sequence ERROR on {} in mp_nautical.next_rise_set".format(dt.strftime("%d-%m-%Y")))
prev_dt = dt
return currentstate
def fmt_rise_set(rise, sett, yR, yS, txt, with_seconds=False):
# note: yR and yS must be 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 = None # True if above horizon; False if below horizon; None if unknown
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 = not pickRISE # 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 = not pickRISE # flip RISE to SET & vice-versa
dt = t.utc_datetime()
if prev_dt > dt: print("Event time sequence ERROR on {} in mp_nautical.fmt_rise_set".format(dt.strftime("%d-%m-%Y")))
prev_dt = dt
return Rtxt[0], Stxt[0], Rtxt[1], Stxt[1], finalstate
def fmt_transits(t, lats, 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,lats,t[0])
return transit1, transit2
def rise_set(t, y, lats, with_seconds = False): # 'ts' removed (Aug 2024 simplification)
# 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
# dt0 = t[0].utc_datetime()
# sec0 = dt0.second + int(dt0.microsecond)/1000000.
# t0 = ts.ut1(dt0.year, dt0.month, dt0.day, dt0.hour, dt0.minute, sec0)
# dt1 = t[1].utc_datetime()
# sec1 = dt1.second + int(dt1.microsecond)/1000000.
# t1 = ts.ut1(dt1.year, dt1.month, dt1.day, dt1.hour, dt1.minute, sec1)
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,lats,t[0]) # Aug 2024 simplification
else:
if len(t) == 1: # this happens ocassionally
t0 = t[0] # Aug 2024 simplification
# dt0 = t[0].utc_datetime()
# sec0 = dt0.second + int(dt0.microsecond)/1000000.
# t0 = ts.ut1(dt0.year, dt0.month, dt0.day, dt0.hour, dt0.minute, sec0)
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
# dt0 = t[0].utc_datetime()
# sec0 = dt0.second + int(dt0.microsecond)/1000000.
# t0 = ts.ut1(dt0.year, dt0.month, dt0.day, dt0.hour, dt0.minute, sec0)
# dt1 = t[1].utc_datetime()
# sec1 = dt1.second + int(dt1.microsecond)/1000000.
# t1 = ts.ut1(dt1.year, dt1.month, dt1.day, dt1.hour, dt1.minute, sec1)
# dt2 = t[2].utc_datetime()
# sec2 = dt2.second + int(dt2.microsecond)/1000000.
# t2 = ts.ut1(dt2.year, dt2.month, dt2.day, dt2.hour, dt2.minute, sec2)
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,lats,t[0]) # Aug 2024 simplification
else:
if len(t) > 3:
# this should never get here!
rise_set_error(y,lats,t[0]) # Aug 2024 simplification
return rise, sett, ris2, set2, finalstate
def rise_set_error(y, lats, t0):
# unexpected rise/set values - format message line
msg = "rise_set {} values for {}: {}".format(len(y),lats, 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
#-------------------------------------------------------
# Aries, Venus, Mars, Jupiter & Saturn calculations
#-------------------------------------------------------
def mp_ariesGHA(d, ts): # 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 mp_venusGHA(d, ts, earth, venus): # 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]
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 mp_marsGHA(d, ts, earth, mars): # 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]
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 mp_jupiterGHA(d, ts, earth, jupiter): # 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]
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 mp_saturnGHA(d, ts, earth, saturn): # 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]
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
#---------------------------------------
# Planet SHA & transit calculations
#---------------------------------------
# > > > > > > > > > > MULTIPROCESSING ENTRY POINT < < < < < < < < < <
def mp_planetGHA(d, ts, obj): # used in nautical.planetstab
out = [None, None, None] # return [planet_sha, planet_transit] + processing time
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
if obj == 'venus': venus = eph['venus']
if obj == 'jupiter': jupiter = eph['jupiter barycenter']
if obj == 'saturn': saturn = eph['saturn barycenter']
if obj == 'mars':
if config.ephndx >= 3:
mars = eph['mars barycenter']
else:
mars = eph['mars']
# calculate planet GHA
DEC = None
DEG = None
if obj == 'aries': GHA = mp_ariesGHA(d, ts)
elif obj == 'venus': GHA, DEC, DEG = mp_venusGHA(d, ts, earth, venus)
elif obj == 'mars': GHA, DEC, DEG = mp_marsGHA(d, ts, earth, mars)
elif obj == 'jupiter': GHA, DEC, DEG = mp_jupiterGHA(d, ts, earth, jupiter)
elif obj == 'saturn': GHA, DEC, DEG = mp_saturnGHA(d, ts, earth, saturn)
out[0] = GHA
out[1] = DEC
out[2] = DEG
return out
# > > > > > > > > > > MULTIPROCESSING ENTRY POINT < < < < < < < < < <
# used in nautical.starstab & eventtables.mp_planets_worker
def mp_planetstransit(d, ts, obj, with_seconds = False):
# returns SHA and Meridian Passage for the navigational planets
out = [None, None, None] # return [planet_sha, planet_transit] + processing time
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
if obj == 'venus': planet = eph['venus']
if obj == 'jupiter': planet = eph['jupiter barycenter']
if obj == 'saturn': planet = eph['saturn barycenter']
if obj == 'mars':
if config.ephndx >= 3:
planet = eph['mars barycenter']
else:
planet = eph['mars']
lattxt = u'{} 0{} E transit'.format(obj, degree_sign)
if SkyfieldVersion("1.35") >= 0:
lats = 0.0 # default latitude (any will do)
topos = wgs84.latlon(lats, 0.0 * E, elevation_m=0.0)
observer = earth + topos
else:
topos = Topos(latNS, "0.0 E") # Topos is deprecated in Skyfield v1.35!
# calculate planet SHA
tfr = ts.ut1(d.year, d.month, d.day, 0, 0, 0) # search from
position = earth.at(tfr).observe(planet)
ra = position.apparent().radec(epoch='date')[0] # RA
out[0] = fmtgha(0, ra.hours) # planet_sha
# calculate planet transit
d1 = d + timedelta(days=1)
tto = ts.ut1(d1.year, d1.month, d1.day, 0, 0, 0) # search to
start00 = time() # 00000
if SkyfieldVersion("1.47") < 0:
transit_time, y = almanac.find_discrete(tfr, tto, planet_transit(earth, planet))
time00 = time()-start00 # 00000
out[1] = rise_set(transit_time,y,lattxt,with_seconds = False)[0] # planet_transit
else:
transit_time = almanac.find_transits(observer, planet, tfr, tto)
time00 = time()-start00 # 00000
out[1] = fmt_transits(transit_time,lattxt,with_seconds)[0] # planet_transit
out[2] = time00 # append processing time to list
return out
def planet_transit(earth, planet_name):
# Build a function of time that returns a planet's upper transit time.
def is_planet_transit_at(t):
"""The function that this returns will expect a single argument that is a
:class:`~skyfield.timelib.Time` and will return ``True`` if the moon is up
or twilight has started, else ``False``."""
t._nutation_angles = iau2000b(t.tt)
# Return `True` if the meridian is crossed by time `t`.
position = earth.at(t).observe(planet_name)
ra = position.apparent().radec(epoch='date')[0]
#return t.gast > ra.hours # incorrect
return (t.gast - ra.hours + 12) % 24 - 12 > 0
is_planet_transit_at.rough_period = 0.1 # search increment hint
return is_planet_transit_at
def hor_parallax(d, ts): # used in nautical.starstab
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
venus = eph['venus']
if config.ephndx >= 3:
mars = eph['mars barycenter']
else:
mars = eph['mars']
# Venus
t0 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)
position0 = earth.at(t0).observe(venus)
vau = position0.apparent().radec(epoch='date')[2] # distance
hpvenus = "{:0.1f}".format((tan(6371/(vau.au*149597870.7)))*60*180/pi)
# Mars
position0 = earth.at(t0).observe(mars)
mau = position0.apparent().radec(epoch='date')[2] # distance
hpmars = "{:0.1f}".format((tan(6371/(mau.au*149597870.7)))*60*180/pi)
return [hpmars,hpvenus]
#-------------------------------
# Sun and Moon calculations
#-------------------------------
def mp_sunGHA(d, ts, earth, sun): # 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]
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]
# degs has been added for the suntab function
return ghas,decs,degs
# used in nautical.sunmoontab(m) & eventtables.equationtab
def mp_moonGHA(d, ts, earth, moon, with_seconds = False):
# 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]
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 mp_moonVD(d00, d, d_valNA, ts, earth, moon): # 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 from 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]
V0 = gha2deg(t0.gast, ra0.hours)
D0 = dec0.degrees * 60.0 # convert to minutes of arc
if 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]
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 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
# > > > > > > > > > > MULTIPROCESSING ENTRY POINT < < < < < < < < < <
def mp_sunmoon(date, d_valNA, ts, n):
# !! WE *MUST* PASS config.d_valNA AS ITS VALUE CAN BE CHANGED PROGRAMMATICALLY !!
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
sun = eph['sun']
moon = eph['moon']
d = date + timedelta(days=n)
d0 = d - timedelta(days=1)
ghas, decs, degs = mp_sunGHA(d, ts, earth, sun)
gham, decm, degm, HPm, GHAupper, GHAlower, ghaSoD, ghaEoD = mp_moonGHA(d, ts, earth, moon)
vmin, dmin = mp_moonVD(d0,d,d_valNA,ts,earth,moon)
#buildUPlists(n, ghaSoD, GHAupper, ghaEoD)
#buildLOWlists(n, ghaSoD, GHAupper, ghaEoD)
out = (ghas, decs, degs, gham, decm, degm, HPm, GHAupper, GHAlower, ghaSoD, ghaEoD, vmin, dmin)
return out
#-----------------------
# star calculations
#-----------------------
# > > > > > > > > > > MULTIPROCESSING ENTRY POINT < < < < < < < < < <
def mp_stellar_info(d, ts, df, n): # used in nautical.starstab
# returns a list of lists with name, SHA and Dec all navigational stars for epoch of date.
# 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)
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
t00 = ts.ut1(d.year, d.month, d.day, 0, 0, 0) #calculate at midnight
#t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0) #calculate at noon
out = []
if n == 0: db = db1
elif n == 1: db = db2
elif n == 2: db = db3
elif n == 3: db = db4
elif n == 4: db = db5
else: db = db6
for line in db.strip().split('\n'):
x1 = line.index(',')
name = line[0:x1]
HIPnum = line[x1+1:]
star = Star.from_dataframe(df.loc[int(HIPnum)])
astrometric = earth.at(t00).observe(star).apparent()
ra, dec, distance = astrometric.radec(epoch='date')
sha = fmtgha(0, ra.hours)
decl = fmtdeg(dec.degrees)
out.append([name,sha,decl])
return out
# List of navigational stars with Hipparcos Catalog Number
db1 = """
Alpheratz,677
Ankaa,2081
Schedar,3179
Diphda,3419
Achernar,7588
Hamal,9884
Polaris,11767
Acamar,13847
Menkar,14135
Mirfak,15863
"""
db2 = """
Aldebaran,21421
Rigel,24436
Capella,24608
Bellatrix,25336
Elnath,25428
Alnilam,26311
Betelgeuse,27989
Canopus,30438
Sirius,32349
Adhara,33579
"""
db3 = """
Procyon,37279
Pollux,37826
Avior,41037
Suhail,44816
Miaplacidus,45238
Alphard,46390
Regulus,49669
Dubhe,54061
Denebola,57632
Gienah,59803
"""
db4 = """
Acrux,60718
Gacrux,61084
Alioth,62956
Spica,65474
Alkaid,67301
Hadar,68702
Menkent,68933
Arcturus,69673
Rigil Kent.,71683
Kochab,72607
"""
db5 = """
Zuben'ubi,72622
Alphecca,76267
Antares,80763
Atria,82273
Sabik,84012
Shaula,85927
Rasalhague,86032
Eltanin,87833
Kaus Aust.,90185
Vega,91262
"""
db6 = """
Nunki,92855
Altair,97649
Peacock,100751
Deneb,102098
Enif,107315
Al Na'ir,109268
Fomalhaut,113368
Scheat,113881
Markab,113963
"""
#------------------------
# SUN TWILIGHT table
#------------------------
# > > > > > > > > > > MULTIPROCESSING ENTRY POINT < < < < < < < < < <
def mp_twilight(d, lat, ts, with_seconds = False): # used in nautical.twilighttab (section 1)
# Returns for given date and latitude(in full degrees):
# naut. and civil twilight (before sunrise), sunrise, meridian passage, sunset, civil and nautical twilight (after sunset).
# NOTE: 'twilight' is only called for every third day in the Nautical Almanac...
# ...therefore daily tracking of the sun state is not possible.
time00 = 0.0 # 00000
eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris
earth = eph['earth']
sun = eph['sun']
out = [None,None,None,None,None,None,None] # 6 data items + processing time
hemisph = 'N' if lat >= 0 else 'S'
latNS = "{:3.1f} {}".format(abs(lat), hemisph)
if SkyfieldVersion("1.35") >= 0:
topos = wgs84.latlon(lat, 0.0 * E, elevation_m=0.0)
observer = earth + topos
else:
topos = Topos(latNS, "0.0 E") # Topos is deprecated in Skyfield v1.35!
dt = datetime(d.year, d.month, d.day, 0, 0, 0)
if with_seconds:
dt -= timedelta(seconds=0.5) # search from 0.5 seconds before midnight
else:
dt -= timedelta(seconds=30) # search from 30 seconds before midnight
t0 = ts.ut1(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
t1 = ts.ut1(dt.year, dt.month, dt.day+1, dt.hour, dt.minute, dt.second)
abhd = False # above/below horizon display NOT enabled
# Sunrise/Sunset...
start00 = time() # 00000
horizon = 0.8333 # degrees below horizon
if SkyfieldVersion("1.48") < 0:
actual, y = almanac.find_discrete(t0, t1, f_sun(earth, sun, topos, horizon))
time00 += time()-start00 # 00000
out[2], out[3], r2, s2, fs = rise_set(actual,y,latNS,with_seconds)
else:
sunrise, yR = almanac.find_risings(observer, sun, t0, t1, -horizon)
sunset, yS = almanac.find_settings(observer, sun, t0, t1, -horizon)
time00 += time()-start00 # 00000
out[2], out[3], r2, s2, fs = fmt_rise_set(sunrise,sunset,yR,yS,latNS,with_seconds)
if out[2] == '--:--' and out[3] == '--:--': # if neither sunrise nor sunset...
abhd = True # enable above/below horizon display
yn = midnightsun(d, hemisph)
out[2] = yn
out[3] = yn
# Civil Twilight...
horizon = 6.0 # degrees below horizon
start00 = time() # 00000
if SkyfieldVersion("1.48") < 0:
civil, y = almanac.find_discrete(t0, t1, f_sun(earth, sun, topos, horizon))
time00 += time()-start00 # 00000
out[1], out[4], r2, s2, fs = rise_set(civil,y,latNS,with_seconds)
else:
sunrise, yR = almanac.find_risings(observer, sun, t0, t1, -horizon)
sunset, yS = almanac.find_settings(observer, sun, t0, t1, -horizon)
time00 += time()-start00 # 00000
out[1], out[4], r2, s2, fs = fmt_rise_set(sunrise,sunset,yR,yS,latNS,with_seconds)
if abhd and out[1] == '--:--' and out[4] == '--:--': # if neither begin nor end...
yn = midnightsun(d, hemisph)
out[1] = yn
out[4] = yn
# Nautical Twilight...
horizon = 12.0 # degrees below horizon
start00 = time() # 00000
if SkyfieldVersion("1.48") < 0:
naut, y = almanac.find_discrete(t0, t1, f_sun(earth, sun, topos, horizon))
time00 += time()-start00 # 00000
out[0], out[5], r2, s2, fs = rise_set(naut,y,latNS,with_seconds)
else:
sunrise, yR = almanac.find_risings(observer, sun, t0, t1, -horizon)
sunset, yS = almanac.find_settings(observer, sun, t0, t1, -horizon)
time00 += time()-start00 # 00000
out[0], out[5], r2, s2, fs = fmt_rise_set(sunrise,sunset,yR,yS,latNS,with_seconds)
if abhd and out[0] == '--:--' and out[5] == '--:--': # if neither begin nor end...
yn = midnightsun(d, hemisph)
out[0] = yn
out[5] = yn
out[6] = time00 # append processing time to list
return out
def midnightsun(d, hemisph):
# simple way to fudge whether the sun is up or down when there's no
# sunrise or sunset on date 'dt' depending on the hemisphere only.
sunup = False
n = d.month
if n > 3 and n < 10: # if April to September inclusive
sunup = True
if hemisph == 'S':
sunup = not(sunup)
if sunup == True:
out = r'''\begin{tikzpicture}\draw (0,0) rectangle (12pt,4pt);\end{tikzpicture}'''
else:
out = r'''\rule{12Pt}{4Pt}'''
return out
def f_sun(earth, sun, topos, degBelowHorizon):
# Build a function of time that returns the sun above/below horizon state.
topos_at = (earth + topos).at
def is_sun_up_at(t):
"""The function that this returns will expect a single argument that is a
:class:`~skyfield.timelib.Time` and will return ``True`` if the sun is up
or twilight has started, else ``False``."""
t._nutation_angles = iau2000b(t.tt)
# Return `True` if the sun has risen by time `t`.
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -degBelowHorizon
#is_sun_up_at.rough_period = 0.5 # 24 samples per day (deprecated)
is_sun_up_at.step_days = 0.041666667 # = 1.0 / 24.0 (24 samples per day)
return is_sun_up_at
#-------------------------
# MOONRISE/-SET table
#-------------------------
def getmoonstate(dt, lat, horizon, ts, earth, moon):
# populate the moon state (visible or not) for the specified date & latitude
# note: the first parameter 'dt' is already a datetime 30 seconds before midnight
# note: getmoonstate is called when there is neither a moonrise nor a moonset on 'dt'
time00 = 0.0 # 00000
Hseeks = 0
hemisph = 'N' if lat >= 0 else 'S'
latNS = '{:3.1f} {}'.format(abs(lat), hemisph)
if SkyfieldVersion("1.35") >= 0:
topos = wgs84.latlon(lat, 0.0 * E, elevation_m=0.0)
observer = earth + topos
else:
topos = Topos(latNS, "0.0 E") # Topos is deprecated in Skyfield v1.35!
t0 = ts.ut1(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
#horizon = 0.8333
# search for the next moonrise or moonset (returned in moonrise[0] and y[0])
mstate = None
while mstate == None:
Hseeks += 1
t0 = ts.ut1(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
dt += timedelta(days=1)
t9 = ts.ut1(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
start00 = time() # 00000
if True or SkyfieldVersion("1.48") < 0:
moonrise, y = almanac.find_discrete(t0, t9, f_moon(earth, moon, topos, horizon))
time00 += time()-start00 # 00000
if len(moonrise) > 0:
mstate = False if y[0] else True
else: # !!! DO NOT USE WITH Skyfield 1.48 !!! (see Skyfield Issue #998)
moonrise, yR = almanac.find_risings(observer, moon, t0, t9, -horizon)
moonset, yS = almanac.find_settings(observer, moon, t0, t9, -horizon)
time00 = time()-start00 # 00000
mstate = next_rise_set(moonrise,moonset,yR,yS)
return mstate, time00, Hseeks
def getHorizon(t, earth, moon):
# calculate the angle of the moon below the horizon at moonrise/set
position = earth.at(t).observe(moon) # at noontime (for daily average distance)
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
horizon = sdm + 0.5666667 # moon's equatorial radius + 34' (atmospheric refraction)
return horizon
def moonstate(mstate):
# return the current moonstate (if known)
out = '--:--'
if mstate == True: # above horizon
out = r'''\begin{tikzpicture}\draw (0,0) rectangle (12pt,4pt);\end{tikzpicture}'''
if mstate == False: # below horizon
out = r'''\rule{12Pt}{4Pt}'''
return out
def seek_moonset(t9, t9noon, t0, t1, t1noon, t2, lat, ts, earth, moon):
# for the specified date & latitude ...
# return -1 if there is NO MOONSET yesterday
# return +1 if there is NO MOONSET tomorrow
# return 0 if there was a moonset yesterday and will be a moonset tomorrow
# note: this is called when there is only a moonrise on the specified date+latitude
time00 = 0.0 # 00000
Hseeks = 1
m_set_t = 0 # normal case: assume moonsets yesterday & tomorrow
hemisph = 'N' if lat >= 0 else 'S'
latNS = "{:3.1f} {}".format(abs(lat), hemisph)
if SkyfieldVersion("1.35") >= 0:
topos = wgs84.latlon(lat, 0.0 * E, elevation_m=0.0)
observer = earth + topos
else:
topos = Topos(latNS, "0.0 E") # Topos is deprecated in Skyfield v1.35!
horizon = getHorizon(t1noon, earth, moon)
start00 = time() # 00000
if True or SkyfieldVersion("1.48") < 0:
moonrise, y = almanac.find_discrete(t1, t2, f_moon(earth, moon, topos, horizon))
time00 += time()-start00 # 00000
rise, sett, ris2, set2, fs = rise_set(moonrise,y,latNS)
else: # !!! DO NOT USE WITH Skyfield 1.48 !!! (see Skyfield Issue #998)
moonset, yS = almanac.find_settings(observer, moon, t1, t2, -horizon)
time00 = time()-start00 # 00000
rise, sett, ris2, set2, fs = fmt_rise_set([],moonset[:1],[],yS,latNS)
if sett == '--:--':
m_set_t = +1 # if no moonset detected - it is after tomorrow
else:
Hseeks += 1
horizon = getHorizon(t9noon, earth, moon)
start00 = time() # 00000
if True or SkyfieldVersion("1.48") < 0:
moonrise, y = almanac.find_discrete(t9, t0, f_moon(earth, moon, topos, horizon))