-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathld_charts.py
2774 lines (2388 loc) · 113 KB
/
ld_charts.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) 2023 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/>.
# NOTE: the new format statement requires a literal '{' to be entered as '{{',
# and a literal '}' to be entered as '}}'. The old '%' format specifier
# will be removed from Python at some later time. See:
# https://docs.python.org/3/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting
###### Standard library imports ######
import sys
from datetime import datetime, timedelta
import math
###### Local application imports ######
import config
import ld_stardata
from ld_skyfield import sunGHA, moonGHA, venusGHA, marsGHA, jupiterGHA, saturnGHA, ld_planets, ld_stars, getHipparcos, getCustomStar
# My apologies to those who read this . . .
# Although use of global variables is frowned upon by the Python community,
# I have chosen to employ global variables in this module to reduce the
# number of arguments passed to some functions, so that the function
# arguments focus on the frequently changing parameters.
# A comment before a function describes which global variables are used.
# . . . and Murphy whispered in his sleep "If it works, don't touch it"
LDtargets = ['sun','ven','mar','jup','sat','Ache','Acru','Adha','Alde','Alta','Anta','Arct','Bete','Cano','Cape','Dene','Foma','Hada','Pola','Poll','Proc','Regu','Rige','Rigi','Siri','Spic','Vega']
# reserve memory for 41 stars in a constellation
#global csize
csize = 0
#global cstars
cstars = [[None]*4 for i in range(41)] # cstars[0][0] up to cstars[40][3]
planet_x = [] # empty list of planets added (to check if they partially overlap)
stars_LD = [] # empty list of LD stars (to print at bottom of page)
degree_sign= u'\N{DEGREE SIGN}'
# globals required in: getc, showLD, buildchart, printcname, addstar, addtext ...
shamin = shamax = sharng = None
decmin = decmax = None
PREVobjects = [] # list of LD objects from previous day
PREVobjColour = [] # list of LD object-colour tuples from previous day
#---------------------------
# Module initialization
#---------------------------
def init_A4(ts, d0=None):
# initialize variables for this module
global sf
if config.pgsz == "A4":
sf = 1.39 # scale factor (1.39cm to 10 degrees SHA/DEC)
else:
sf = 1.31 # scale factor (1.31cm to 10 degrees SHA/DEC)
## A4/Letter LANDSCAPE ##
global const_fs
const_fs = "large" # constellation name fontsize (12pt)
global navstar_fs
navstar_fs = "normalsize" # navigational star fontsize (10pt)
#navstar_fs = "fontsize{6pt}" # navigational star fontsize (6pt)
global navnum_fs
navnum_fs = "Large" # navigational starnum fontsize (14.4pt)
global star_fs
star_fs = "footnotesize" # star fontsize (8pt)
global title_fs
title_fs ="Large" # title, SHA, DEC fontsize (14.4pt)
global ns_fs
ns_fs = "large" # North, South fontsize (12pt)
if d0 != None:
global t00 # getc() requires 't00'; makeLDcharts updates 't00'
t00 = ts.utc(d0.year, d0.month, d0.day, 0, 0, 0)
return
#----------------------------
# astronomical functions
#----------------------------
# global variables >>>> shamin, sharng
def SHAleftofzero(sha):
# return True if SHA 0° is within plot borders; and if 'sha' is left of SHA 0° and within plot borders
# return False otherwise
if 360 - shamin <= sharng:
# SHA 0° is within plot and not first SHA, i.e. SHAs < 360° are plotted
return (sha >= shamin)
else: return False
# global variables >>>> sharng
def ext_sha(sha0):
# calculate a fake "extended sha" value that will
# transform to a correct X-axis coordinate whether
# within plot left/right borders or not. It can be
# < 0 or >= 360 based upon where SHA 0° lies on the
# X-axis (which depends on 'x_o', the X-axis plot offset).
# This is to facilitate computation of coordinates that
# are beyond the LEFT or RIGHT plot borders but are
# required to draw constellation or Lunar Distance lines.
sha = sha0 % 360.0 # 0 <= sha < 360 (just in case!)
v = outsideplot(sha)
if v == 0:
if SHAleftofzero(sha): return sha - 360.0
return sha # unchanged
if v == +1:
if sha < sharng - x_o: return sha + 360.0
return sha # unchanged
if v == -1:
if sha > -x_o: return sha - 360.0
return sha # unchanged
# global variables >>>> shamin, shamax
def outsideplot(sha0):
# As constellations have a limited size, if some points
# are within the plot area (i.e. ignore constellations
# completely outside the plot area!!!), detect points
# just beyond the left or right plot borders...
# ... in order to complete the constellation lines
# 'mid_sha' is the center SHA of the unplotted range
# return -1 if 'sha' left of left plot border (up to 'mid_sha')
# return +1 if 'sha' right of right plot border (up to 'mid_sha')
# return 0 otherwise
# (lines will be correctly clipped if -1 or +1 is returned)
sha = sha0 % 360.0 # 0 <= sha < 360
if shamax > shamin:
edge_sha = (shamax - shamin) / 2
else:
edge_sha = (shamin - shamax) / 2
mid_sha = shamax + edge_sha
if mid_sha > 360:
mid_sha -= 360
# check if within left edge_sha
if mid_sha < shamin:
v = -1 if mid_sha < sha < shamin else 0
else:
v = 0 if shamin <= sha <= mid_sha else -1
if v != 0: return v
# check if within right edge_sha
if mid_sha > shamax:
v = 1 if mid_sha > sha > shamax else 0
else:
v = 0 if shamax >= sha >= mid_sha else 1
return v
# global variables >>>> decmin, decmax
def outofbounds_dec(dec):
# As constellations have a limited size, if some points
# are within the plot area (i.e. ignore constellations
# completely above or below the plot area!!!), detect points
# just beyond the lower or upper plot borders...
# ... in order to complete the constellation lines
# return -1 if 'dec' below lower plot border
# return +1 if 'dec' above upper plot border
# return 0 otherwise
# (lines will be correctly clipped if -1 or +1 is returned)
if dec > decmax: return +1
if dec < decmin: return -1
return 0
def shaadd(sha, inc):
ang = sha + inc
ang = ang % 360 # DO NOT CHANGE TO FLOAT with "ang = ang % 360.0"
#if ang >= 360: ang = ang - 360
return ang
# global variables >>>> shamin, shamax
def outofbounds_sha(sha):
if sha < 0 or sha >= 360:
raise Exception("SHA not in range 0 <= SHA < 360")
sys.exit(0)
# check if object within plot range (x-axis)
if shamax > shamin:
v = False if shamin <= sha <= shamax else True
else:
v = True if shamax < sha < shamin else False
return v
def validSHA(FROMsha, sha, TOsha):
# check if the SHA lies between FROMsha and TO sha
if FROMsha < TOsha:
return True if FROMsha < sha < TOsha else False
else:
x = False
if sha > FROMsha or sha < TOsha: x = True
return x
# all local variables below!
def sha_inc(shamin, shamax):
# increment shamin & shamax by 5 degrees
shamin += 5
if shamin >= 360: shamin -= 360
shamax += 5
if shamax >= 360: shamax -= 360
return shamin, shamax
def ra_sha(ra):
# convert angle (hours) to sha (degrees)
sha = (- ra) * 15
if sha < 0:
sha = sha + 360
return sha
def group_width(csha):
# get the constellation width, and min and max SHA
# find the largest gap in sorted SHA values: this is not in the constellation!
cwth = c_min = c_max = 0.0
if len(csha) < 2: return cwth, c_min, c_max
maxdiff = 0.0
#csha.sort() # CAUTION: this modifies the list in-place
new_csha = sorted(csha) # this creates a new list
for i in range(len(new_csha)):
if i == 0:
diff = 360 - (new_csha[-1] - new_csha[0])
else:
diff = new_csha[i] - new_csha[i-1]
if diff > maxdiff:
maxdiff = diff
c_max = new_csha[i-1] if i > 0 else new_csha[-1]
k = i
c_min = new_csha[k]
cwth = c_max - c_min
if cwth < 0: cwth += 360
return cwth, c_min, c_max
def group_range(cdec):
# get the min and max DEC from a list; also the mid DEC
d_mid = d_min = d_max = 0.0
if len(cdec) == 0: return d_mid, d_min, d_max
cdec.sort()
d_min = cdec[0]
d_max = cdec[-1]
d_mid = (d_max + d_min) / 2.0
return d_mid, d_min, d_max
#-----------------------------------------------
# graphical functions for chart constructon
#-----------------------------------------------
# global variables >>>> decmin, decmax, sharng, t00
def getc(cname, skipstars=[], c='consGrey'):
# get constellation parameters and plot it
# cname = constellation name
# skipstars = skip 'plotstar' for these (instead they are plotted using 'addstar')
# c = colour of constellation pattern lines
## global d
## print("d = {}; type = {}".format(d,type(d)))
global csize
global cstars
csha = [] # build list of SHA values of stars in constellation
out = ""
cpattern = ""
fnd = False
ndx = 0
starstoplot = 0
cnameSHA = 999.0 #invalid value
cnameDEC = 100.0 #invalid value
cname2SHA = 999.0 #invalid value
cname2DEC = 100.0 #invalid value
for line in ld_stardata.constellations.strip().split('\n'):
if not(fnd):
x1 = line.find(':')
if x1 != -1:
if cname == line[0:x1]:
fnd = True
x2 = cname.find('_')
if x2 == -1:
x3 = line.find(',')
if x3 != -1:
cname1 = cname
cnameSHA = float(line[x1+1:x3])
cnameDEC = float(line[x3+1:])
else:
cname1 = cname[0:x2]
cname2 = cname[x2+1:]
x4 = line.find(';')
part1 = line[x1+1:x4]
part2 = line[x4+1:]
x3 = part1.find(',')
if x3 != -1:
cnameSHA = float(part1[0:x3])
cnameDEC = float(part1[x3+1:])
x4 = part2.find(',')
if x4 != -1:
cname2SHA = float(part2[0:x4])
cname2DEC = float(part2[x4+1:])
continue
else:
if line[3:4] == ' ':
# save all stars in constellation
bayercode = line[0:3]
HIPnum = line[4:]
##t00 = ts.utc(d.year, d.month, d.day, 0, 0, 0)
ra, dec, mag = getHipparcos(HIPnum, t00)
sha = ra_sha(ra.hours)
csha.append(sha)
v = outsideplot(sha)
if v == 0 and outofbounds_dec(dec.degrees) == 0: starstoplot += 1
if cname == "CraterXXX": # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
print("{} {}, sha = {:.3f} v = {} w = {}".format(cname,bayercode,sha,v,SHAleftofzero(sha)))
if v == 0 and SHAleftofzero(sha): sha -= 360 # NEW
if v == -1: sha -= 360
x = (x_o + sha) * sf / 10.0
y = dec.degrees * sf / 10.0
##### print("cstars = {} {} {} {}".format(bayercode,x,y,mag))
#out += plotstar(x,y) # don't plot here!
cstars[ndx][0] = bayercode
cstars[ndx][1] = x
cstars[ndx][2] = y
cstars[ndx][3] = mag
ndx += 1
csize = ndx
else:
if line[0:1] == "#": # comment line
continue
cpattern = line
break
if not fnd: return ""
cwth, c_min, c_max = group_width(csha)
#print(" {:5.2f} {} extends from {:.2f} to {:.2f}".format(cwth,cname,c_min,c_max))
if cwth > 85:
# maximum permitted constellation width is (360 - plot width)/2 = 85°
# Constellations that are wider must be split into smaller units
# because the mid-point of the unplotted region (e.g. 275° for a
# plot from 0° to 190°) determines if a connecting line should
# extend to the right or the left plot border.
print("ERROR: {} width {:.2f}, extends from {:.2f} to {:.2f}".format(cname,cwth,c_min,c_max))
if starstoplot == 0: return ""
# clip area is the plot boundary
x1 = 0.0
y1 = decmin * sf / 10.0
x2 = sharng * sf / 10.0
y2 = decmax * sf / 10.0
out += r"""
% constellation: {}
\begin{{scope}}
\clip ({:.3f},{:.3f}) rectangle ({:.3f},{:.3f});""".format(cname, x1, y1, x2, y2)
# draw constellation shape pattern
while len(cpattern) > 4:
starfr = cpattern[0:3]
join = False
cp = cpattern[3:4]
if cp == "-":
join = True
dp = "" # default is 'thin' 0.4pt
if cp == "=":
join = True
dp = "very thick," # 0.8pt
starto = cpattern[4:7]
cpattern = cpattern[4:]
if join:
x1, y1 = findstar(starfr)
x2, y2 = findstar(starto)
# draw constellation shape in colour 'c'
out += r"""
\draw[%s%s] (%0.3f,%0.3f) -- (%0.3f,%0.3f);""" %(dp,c,x1,y1,x2,y2)
# plot stars in constellation (*after* drawing the shape pattern)
for ndx in range(csize):
bayercode = cstars[ndx][0]
# don't overlay a black circle with another colour ... it leaves a thin black rim
if bayercode not in skipstars:
x = cstars[ndx][1]
y = cstars[ndx][2]
mag = cstars[ndx][3]
out += plotstar(x,y,mag)
out += r"""
\end{scope}"""
# print constellation name at locn in degrees
out1 = ""
if cnameDEC != 100.0:
out1 = printcname(cname1,cnameSHA,cnameDEC)
if cname2DEC != 100.0:
out2 = printcname(cname2,cname2SHA,cname2DEC)
# second word exists - was the first word printed?
if out1 != "" and out2 != "":
out += out1 + out2 # print both or none
else:
out += out1
return out
# global variables >>>> decmin, decmax, sharng
def printcname(cname, sha, dec, p='right', c='gray'):
# print constellation name
v = outsideplot(sha)
if v != 0: return ""
if outofbounds_dec(dec) != 0: return ""
# skip constellation names that are within 1.5° of upper or lower plot border...
if abs(dec - decmin) < 1.5 or abs(dec - decmax) < 1.5: return ""
if v == 0 and SHAleftofzero(sha): sha = sha - 360 # NEW
x = (x_o + sha) * sf / 10.0
y = dec * sf / 10.0
if cname == 'Draco2': cname = 'Draco' # patch (Draco is wide - print twice)
if cname == 'Hydra2': cname = 'Hydra' # patch (Hydra is split into two constellations)
if cname == 'ScorpiusXXX':
# first declare a new variable and store the length of 'cname' text in it
# within tikz, it's necessary to surround this in \pgfinterruptpicture ... \endpgfinterruptpicture
# use tcolorbox to apply a background color (colback), text color (colupper) and opacity (opacityfill) - this requires 'standard jigsaw'
out = r"""
\settowidth{\myl}{\pgfinterruptpicture\%s{%s}\endpgfinterruptpicture}
\draw (%0.2f,%0.2f) node[%s] {\begin{tcolorbox}[standard jigsaw,size=minimal,colupper=%s,colback=white,opacityfill=0.7,width=\myl]{\%s{%s}}\end{tcolorbox}};
""" %(const_fs,cname,x,y,p,c,const_fs,cname)
else:
if cname == "GeminiXX":
print("{}: x/sf= {:.2f} y= {} {}".format(cname,x/sf,y,p))
# prevent constellation names crossing the right plot border...
deltaX = 0.0
x_max = sharng / 10.0
## if x/sf > x_max - 0.3 and p == 'right': p = 'left' # don't switch sides
if x/sf > x_max - 0.4 and p == 'right': return "" # e.g. remove Leo
elif x/sf > x_max - 0.7 and p == 'right' and len(cname) >= 5: return "" # e.g. remove Indus
elif x/sf > x_max - 1.2 and p == 'right' and len(cname) >= 8: return "" # e.g. remove Aquarius
elif x/sf > x_max - 1.6 and p == 'right' and len(cname) >= 10: return "" # e.g. for Camelopardalis
#elif x/sf > x_max - 0.7 and p == 'right' and len(cname) <= 5: deltaX = 0.7
#elif x/sf > x_max - 1.0 and p == 'right' and len(cname) >= 6: deltaX = 1.0
x -= deltaX
out = r"""
\draw[color=%s] (%0.2f,%0.2f) node[%s] {\%s{%s}};""" %(c,x,y,p,const_fs,cname)
return out
def findstar(bayercode):
x = 1.0
y = 1.0
global csize
global cstars
for ndx in range(csize):
if cstars[ndx][0] == bayercode:
x = cstars[ndx][1]
y = cstars[ndx][2]
break
return x, y
def getstar(fname):
# return SHA and Dec for epoch of date.
if fname[:3] == "HIP":
ra, dec, mag = getCustomStar(fname, t00)
sha = ra_sha(ra.hours)
return fname,sha,dec.degrees,mag
for line in ld_stardata.popstars.split('\n'):
if line[7:] == fname:
HIPnum = line[:6].lstrip(' ')
ra, dec, mag = getHipparcos(HIPnum, t00)
#if math.isnan(ra) or math.isnan(dec): # e.g. HIP78727, HIP55203
sha = ra_sha(ra.hours)
return fname,sha,dec.degrees,mag
print("getstar error: {} not found in Hipparcos catalogue".format(fname))
sys.exit(0)
def plotstar(x, y, mag=5.0, c='black', op=1.0, c2='black'):
if mag == 5.0:
m = 0.5
else: # A4 Landscape
m = ((5.0 - mag) / 2.3) + 0.6
pct = ",opacity=%s" %(op) if op != 1.0 else ''
if c == 'white':
# c2 is the circle colour
m2 = m - 0.18 # subtract just less than half the line thickness (in pt)
out = r"""
\fill[color=%s%s] (%0.3f,%0.3f) circle[radius=%0.2f pt];
\draw [color=%s] (%0.3f,%0.3f) circle[radius=%0.2f pt];""" %(c, pct, x, y, m, c2, x, y, m2)
else:
out = r"""
\fill[color=%s%s] (%0.3f,%0.3f) circle[radius=%0.2f pt];""" %(c, pct, x, y, m)
return out
def numpos(p, rn, n):
# improve the x, y coordinates for the navigational star number
# find the opposite side (of the star name) to place the number of the navigational star
updown = False
p2 = p
# switch left <=> right
if p.find('right') != -1:
p2 = p.replace("right", "left")
if p.find('left') != -1:
p2 = p.replace("left", "right")
# switch above <=> below
if p.find('above') != -1:
p2 = p.replace("above", "below")
updown = True
if p.find('below') != -1:
p2 = p.replace("below", "above")
updown = True
# swap X +ve <=> -ve
if p2.find('xshift=-') != -1:
p2 = p2.replace("xshift=-", "xshift=")
else:
if p2.find('xshift=') != -1:
p2 = p2.replace("xshift=", "xshift=-")
# if above or below: swap Y +ve <=> -ve
if updown:
if p2.find('yshift=-') != -1:
p2 = p2.replace("yshift=-", "yshift=")
else:
if p2.find('yshift=') != -1:
p2 = p2.replace("yshift=", "yshift=-")
# rn can only contain 1 comma
i1 = rn.find(',')
if i1 == -1:
s1 = rn
s2 = ''
else:
s1 = rn[:i1]
s2 = rn[i1+1:]
if s2.find(',') != -1:
print("ERROR: incorrect parameters for star {}: '{}'".format(n,rn))
sys.exit()
if s1.startswith('xshift='):
i2 = p2.find('xshift=')
if i2 != -1:
i3 = p2.find('ex', i2)
p2 = p2.replace(p2[i2:i3+2], s1, 1)
else: p2 = p2 + ',' + s1
if s1.startswith('yshift='):
i2 = p2.find('yshift=')
if i2 != -1:
i3 = p2.find('ex', i2)
p2 = p2.replace(p2[i2:i3+2], s1, 1)
else: p2 = p2 + ',' + s1
if s2 == '':
#print("{}: '{}' => '{}'".format(n,p,p2))
return p2
if s2.startswith('xshift='):
i2 = p2.find('xshift=')
if i2 != -1:
i3 = p2.find('ex', i2)
p2 = p2.replace(p2[i2:i3+2], s2, 1)
else: p2 = p2 + ',' + s2
if s2.startswith('yshift='):
i2 = p2.find('yshift=')
if i2 != -1:
i3 = p2.find('ex', i2)
p2 = p2.replace(p2[i2:i3+2], s2, 1)
else: p2 = p2 + ',' + s2
#print("{}: '{}' => '{}'".format(n,p,p2))
return p2
# global variables >>> d00, sharng, stars_LD
def addstar(starname, n=0, c='black', p='right', rn=''):
global stars_LD
# plot the star as a filled circle ...
name, sha, dec, mag = getstar(starname)
if outofbounds_sha(sha): return ""
if outofbounds_dec(dec) != 0: return ""
if SHAleftofzero(sha): sha = sha - 360 # NEW
x = (x_o + sha) * sf / 10.0
y = dec * sf / 10.0
c2 = c
if c == 'blue': c = 'airforceBlue'
fsize = star_fs
if c2 == 'blue':
c2 = 'orange'
c2 = 'airforceBlue'
fsize = navstar_fs
out = plotstar(x,y,mag,c2)
# print the star name ...
x_max = sharng / 10.0
if starname == 'XXX':
# first declare a new variable and store the length of 'starname' text in it
# within tikz, it's necessary to surround this in \pgfinterruptpicture ... \endpgfinterruptpicture
# use tcolorbox to apply a background color (colback), text color (colupper) and opacity (opacityfill) - this requires 'standard jigsaw'
out += r"""
\settowidth{\myl}{\pgfinterruptpicture\%s{%s}\endpgfinterruptpicture}
\draw (%0.2f,%0.2f) node[%s] {\begin{tcolorbox}[standard jigsaw,size=minimal,colupper=%s,colback=white,opacityfill=0.7,width=\myl]{\%s{%s}}\end{tcolorbox}};""" %(fsize,name,x,y,p,c,fsize,name)
else:
if n == 0:
# prevent starname crossing the right or left plot border...
if not (x/sf > x_max - 1.0 and p.startswith('right') and len(name) >= 5) and not (x/sf < 1.2 and p.startswith('left')):
p2 = "opacity=0.4," + p
out += r"""
\draw[color=%s] (%0.2f,%0.2f) node[%s,font=\%s] {%s};""" %(c, x, y, p2, fsize, name)
else:
nsf = ''
p2 = "opacity=0.5," + numpos(p,rn,n)
# prevent starname crossing the left or right plot border...
if not (x/sf > x_max - 1.0 and p.startswith('right')) and not (x/sf < 1.2 and p.startswith('left')):
# print star name AND navigational star number from the Nautical Almanac
out += r"""
\draw[color=%s] (%0.2f,%0.2f) node[%s,font=\%s%s] {%s};
\draw[color=airforceBlue] (%0.2f,%0.2f) node[%s] {\fontfamily{phv}\%s\textbf{%s}};""" %(c, x, y, p, fsize, nsf, name, x, y, p2, navnum_fs, n)
else:
# print only the navigational star number from the Nautical Almanac
stars_LD.append([starname, n, False]) # append star name, nav number, 'True' if used for LD
out += r"""
\draw[color=airforceBlue] (%0.2f,%0.2f) node[%s] {\fontfamily{phv}\%s\textbf{%s}};""" %(x, y, p2, navnum_fs, n)
return out
# global variables >>> d00, sharng
def addtext(starname, txt, c='black', p='right'):
# add text without plotting a star
name, sha, dec, mag = getstar(starname)
if outofbounds_sha(sha): return ""
if outofbounds_dec(dec) != 0: return ""
if SHAleftofzero(sha): sha = sha - 360 # NEW
x = (x_o + sha) * sf / 10.0
y = dec * 9 * sf / 90.0
# prevent starname crossing the right or left plot border...
out = ""
x_max = sharng / 10.0
if not (x/sf > x_max - 1.0 and p.startswith('right') and len(name) >= 5) and not (x/sf < 1.2 and p.startswith('left')):
p2 = "opacity=0.4," + p
out = r"""
\draw[color=%s] (%0.2f,%0.2f) node[%s,font=\%s] {%s};""" %(c, x, y, p2, star_fs, txt)
return out
# global variables >>> d00
def adddot(starname):
name, sha, dec, mag = getstar(starname)
if outofbounds_sha(sha): return ""
if outofbounds_dec(dec) != 0: return ""
if SHAleftofzero(sha): sha = sha - 360 # NEW
x = (x_o + sha) * sf / 10.0
y = dec * 9 * sf / 90.0
#print("{} x = {:.3f} y = {:.3f} mag = {} sha = {:.3f} dec = {:.3f}".format(starname,x,y,mag,sha,dec))
out = plotstar(x,y,mag)
return out
def getMOON(date):
# get the X coordinate of the Moon at 00h
sha, dec = moonGHA(date)
if outofbounds_sha(sha[0]): return None
Xsha = ext_sha(sha[0])
xObj = (x_o + Xsha) * sf / 10.0
return xObj
def XaxisLD(xMoon, sha, just):
if xMoon == None: return 0.0
Xsha = ext_sha(sha)
xObj = (x_o + Xsha) * sf / 10.0
if just == 'right':
if xObj > xMoon: return xObj - xMoon
else: return 0.0
elif just == 'left':
if xObj < xMoon: return xMoon - xObj
else: return 0.0
else: return 0.0
def addMOON(newMoon, checkpos = False):
out = ""
xyMoon00 = [None, None]
xyMoon24 = [None, None]
s = [None] * 3
d = [None] * 3
s, d = moonGHA(d00)
t = ["0h", "12h", "24h"]
# first check all coordinates
outofrange = False
for i in range(3):
sha = s[i]
dec = d[i]
if outofbounds_sha(sha): outofrange = True
if outofbounds_dec(dec) != 0: outofrange = True
#print(i, sha, dec, outofbounds_sha(sha), outofbounds_dec(dec))
if not checkpos and outofrange: return out, xyMoon00, xyMoon24
if not outofrange:
for i in range(3):
sha = s[i]
dec = d[i]
if outofbounds_sha(sha): continue
if outofbounds_dec(dec) != 0: continue
if SHAleftofzero(sha):
sha = sha - 360 # NEW
s[i] = sha # IMPORTANT
# chart coordinates of Moon...
x = (x_o + sha) * sf / 10.0
y = dec * sf / 10.0
out += plotstar(x,y,1.0,'amaranth',0.6)
if i == 0:
xyMoon00[0] = x
xyMoon00[1] = y
if i == 2:
xyMoon24[0] = x
xyMoon24[1] = y
# chart coordinates of associated time of day (0h 12h 24h)...
x = (x_o + sha -0.4) * sf / 10.0
y = (dec + 1.5) * sf / 10.0
out += r"""
\draw[color=%s] (%0.2f,%0.2f) node[font=\%s] {%s};""" %('black', x, y, star_fs, t[i])
txt = "New Moon" if newMoon else "Moon"
dx = s[0] - s[2]
dy = d[0] - d[2]
#print("dx",dx)
ang = math.atan(dy/dx)
rot = "%0.3f" %(ang*todegrees)
txtsep = 4.5
# chart coordinates of 'Moon' text...
x = (x_o + s[1] - (txtsep*math.sin(ang))) * sf / 10.0
y = (d[1] + (txtsep*math.cos(ang))) * sf / 10.0
out += r"""
\draw[color=%s] (%0.3f,%0.3f) node[opacity=0.6,rotate=%s] {\fontfamily{phv}\%s\textbf{%s}};""" %('amaranth', x, y, rot, navnum_fs, txt)
if checkpos: return x, y # only return the coordinates of "Moon" text
# also return the coordinates of the moon at 0h
return out, xyMoon00, xyMoon24
def addSUN():
return addPLANET("Sun")
# global variables >>> planet_x
def addPLANET(planet):
out = ""
s = [None] * 5
d = [None] * 5
if planet == "Venus":
s, d = venusGHA(d00)
elif planet == "Mars":
s, d = marsGHA(d00)
elif planet == "Jupiter":
s, d = jupiterGHA(d00)
elif planet == "Saturn":
s, d = saturnGHA(d00)
elif planet == "Sun":
s, d = sunGHA(d00)
# first check all coordinates (print as long as one is in range)
outofrange = True
oneoutofrange = False
for i in range(5):
sha = s[i]
dec = d[i]
if not outofbounds_sha(sha): outofrange = False
else: oneoutofrange = True
if outofrange: return out
for i in [4,3,2,1,0]:
sha = s[i]
dec = d[i]
if outofbounds_sha(sha):
if x_o >= 0 and outsideplot(sha) == -1: sha -= 360
#if x_o < 0 and outsideplot(sha) == +1: sha += 360
s[i] = sha # IMPORTANT
else:
if SHAleftofzero(sha):
sha = sha - 360 # NEW
s[i] = sha # IMPORTANT
x = (x_o + sha) * sf / 10.0
y = dec * sf / 10.0
# DO NOT USE OPACITY < 1.0 BECAUSE THEY OVERLAP
#print(" {:13} x={:7.3f} y={:7.3f} {}".format(planet+":",x/sf,y/sf,i))
if i == 0:
out += plotstar(x,y,1,'white',1.0,'blue2')
else:
out += plotstar(x,y,1,'blue2',1.0)
if oneoutofrange: return out # don't print label or arrow
# direction of movement
dx = s[0] - s[4]
dy = d[0] - d[4]
#print("dx",dx)
ang = math.atan(dy/dx)
rot = "%0.3f" %(ang*todegrees)
txtsep = 3.0 if dx > 0 else -3.0
midX = (x_o + s[2]) * sf / 10.0
# check if existing planets already in this vicinity
global planet_x
for item in planet_x:
if abs(item[0] - midX) < 1.0:
xx = item[1]
yy = item[2]
x = (x_o + s[2] + (txtsep*math.sin(ang))) * sf / 10.0
y = (d[2] - (txtsep*math.cos(ang))) * sf / 10.0
sep1 = math.sqrt((xx-x)**2 + (yy-y)**2)
x = (x_o + s[2] + (-txtsep*math.sin(ang))) * sf / 10.0
y = (d[2] - (-txtsep*math.cos(ang))) * sf / 10.0
sep2 = math.sqrt((xx-x)**2 + (yy-y)**2)
if sep2 > sep1: txtsep = - txtsep
break
# check if moon is very close
xx, yy = addMOON(False, True) # returns coordinates of "Moon" text
if abs(xx - midX) < 0.7:
x = (x_o + s[2] + (txtsep*math.sin(ang))) * sf / 10.0
y = (d[2] - (txtsep*math.cos(ang))) * sf / 10.0
sep1 = math.sqrt((xx-x)**2 + (yy-y)**2)
x = (x_o + s[2] + (-txtsep*math.sin(ang))) * sf / 10.0
y = (d[2] - (-txtsep*math.cos(ang))) * sf / 10.0
sep2 = math.sqrt((xx-x)**2 + (yy-y)**2)
if sep2 > sep1: txtsep = - txtsep
x = (x_o + s[2] + (txtsep*math.sin(ang))) * sf / 10.0
y = (d[2] - (txtsep*math.cos(ang))) * sf / 10.0
planet_x.append([midX, x, y]) # append list: planet X-position at 12h and text position
lnsep = 5.0 if txtsep > 0 else -5.0
lnlng = 3.6 / 2 # half line length
arlng = 1.0
arang = 30/todegrees
# NOTE: direction-of-movement arrows are separated (above or below object) to
# minimize collision of RIGHT-moving objects with LEFT-moving objects.
if dx > 0: # print name with LEFT arrow (direction of movement) below object
c2 = 'blue2'
x0 = (x_o + s[2] + lnsep*math.sin(ang) - lnlng*math.cos(ang)) * sf / 10.0
y0 = (d[2] - lnsep*math.cos(ang) - lnlng*math.sin(ang)) * sf / 10.0
x1 = x0 + (lnlng * sf / 5.0)
y1 = y0
x2 = x0 + arlng*math.cos(arang) * sf / 10.0
y2 = y0 + arlng*math.sin(arang) * sf / 10.0
x3 = x2
y3 = y0 - arlng*math.sin(arang) * sf / 10.0
else: # print name with RIGHT arrow (direction of movement) above object
c2 = 'blue2' # was c2 = 'Bronze'
x0 = (x_o + s[2] + lnsep*math.sin(ang) + lnlng*math.cos(ang)) * sf / 10.0
y0 = (d[2] - lnsep*math.cos(ang) + lnlng*math.sin(ang)) * sf / 10.0
x1 = x0 - (lnlng * sf / 5.0)
y1 = y0
x2 = x0 - arlng*math.cos(arang) * sf / 10.0
y2 = y0 + arlng*math.sin(arang) * sf / 10.0
x3 = x2
y3 = y0 - arlng*math.sin(arang) * sf / 10.0
out += r"""
\draw[color=%s] (%0.3f,%0.3f) node[rotate=%s,font=\%s] {%s};""" %(c2, x, y, rot, navstar_fs, planet)
out += r"""
\begin{scope}
\draw [rotate around={%.1f:(%0.3f,%0.3f)},color=%s] (%0.3f,%0.3f) -- (%0.3f,%0.3f)
(%0.3f,%0.3f) -- (%0.3f,%0.3f) -- (%0.3f,%0.3f);
\end{scope}""" %(ang*todegrees, x0, y0, c2, x0, y0, x1, y1, x2, y2, x0, y0, x3, y3)
return out
#---------------------------------
# pick Lunar Distance targets
#---------------------------------
# global variables >>> d00
def LDstrategy(strat):
# generate Lunar Distance targets according to chosen strategy
# arguments for LD graphics ... create a list for the day
LDlist = [] # List of chosen celestial objects
H0list = [] # Lunar Distance angle at 0h per chosen celestial object
SGNlist = [] # left and/or right of Moon 'sign' per chosen celestial object
# >>>>>>>>>>>> Calculate all required data <<<<<<<<<<<<
out2, tup2, NMhours, ra_m = ld_planets(d00) # planets & sun
#print(out2[0][1].hours)
#print("NMhours",NMhours)
out, tup = ld_stars(d00, NMhours, out2[0][1].hours)
#print("\nout =", out)
#print()
tup = tup + tup2
tup.sort(key = lambda x: x[1]) # sort by signed first valid LD
if config.debug_strategy:
print("New Moon hours:\n{}".format(NMhours))
# =================================================================
# Strategy "C"
# =================================================================
# >>>>>>>>>>>> Decide which Lists to print (8 maximum) <<<<<<<<<<<<
if strat == "C":
LDtxt = " (objects with highest brightness)"
# build list of objects sorted by largest hourly LD delta first
tuple_list = [None] * 27
for i in range(len(tup)):
tuple_list[i] = (tup[i][0], tup[i][5], math.copysign(1, tup[i][1]), tup[i][4])
tuple_list.sort(key = lambda x: x[1]) # sort by object magnitude
if config.debug_strategy:
print("--- tuples with highest brightness first ---")
print(tuple_list)
# =================================================================
# Strategy "B"
# =================================================================
# >>>>>>>>>>>> Decide which Lists to print (8 maximum) <<<<<<<<<<<<
if strat == "B":
LDtxt = " (objects with largest hourly LD delta)"
# build list of objects sorted by largest hourly LD delta first
tuple_list = [None] * 27
for i in range(len(tup)):
tuple_list[i] = (tup[i][0], tup[i][3], math.copysign(1, tup[i][1]), tup[i][4])
tuple_list.sort(key = lambda x: -x[1]) # sort by max hourly LD delta
if config.debug_strategy:
print("--- tuples with largest ld_delta_max first ---")
print(tuple_list)
# =================================================================
# Code common to Strategy "C" and "B"
# =================================================================
if strat == "B" or strat == "C":
# split the list into Positive and Negative LD (RA in relation to the Moon)
NEGlist = []
POSlist = []
for i in range(len(tuple_list)):
if tuple_list[i][3] > 0: # ignore objects with no data
if tuple_list[i][2] > 0:
POSlist.append(tuple_list[i][0]) # object index
else:
NEGlist.append(tuple_list[i][0]) # object index
# attempt to pick objects evenly from Positive and Negative lists:
OUTlist = []
i_neg = 0
i_pos = 0
i_out = 0
while i_out < 8:
if i_neg < len(NEGlist):
OUTlist.append(NEGlist[i_neg])
i_neg += 1
i_out += 1
if i_pos < len(POSlist):
OUTlist.append(POSlist[i_pos])
i_pos += 1
i_out += 1
if i_neg == len(NEGlist) and i_pos == len(POSlist): break
iLists = len(OUTlist)
#print(" {} lists".format(iLists))
#print(OUTlist)
# >>>>>>>>>>>> Gather data from Lists <<<<<<<<<<<<
iCols = iLists
if iCols < 5: LDtxt = "" # not wide enough to print full text
#extracols = ""
obj = [None] * iCols
ld = [None] * 24
iC = 0
# output the objects in OUTlist in the sequence within 'tup'
for i in range(len(tup)):
ndx = tup[i][0]
#print("ndx=",ndx)
if ndx in set(OUTlist):
ld_first = tup[i][1] # first valid lunar distance angle in the day