-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexospective.py
More file actions
1963 lines (1649 loc) · 75.9 KB
/
exospective.py
File metadata and controls
1963 lines (1649 loc) · 75.9 KB
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
"""
exospective
Generates star charts showing the night sky from arbitrary positions in 3D space.
"""
import numpy as np
import pandas as pd
from skyfield.api import Star, load
from skyfield.data import hipparcos
from skyfield.positionlib import Barycentric
import matplotlib.pyplot as plt
from typing import Tuple, Optional, List
import argparse
import json
import os
import sys
from astroquery.simbad import Simbad
# Manual collision detection (adjustText removed for v1)
# Star name cache file
STAR_NAME_CACHE_FILE = '.star_name_cache.json'
# Load or initialize star name cache
def load_star_name_cache():
"""Load cached star names from disk."""
if os.path.exists(STAR_NAME_CACHE_FILE):
try:
with open(STAR_NAME_CACHE_FILE, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return {}
return {}
def save_star_name_cache(cache):
"""Save star name cache to disk."""
try:
with open(STAR_NAME_CACHE_FILE, 'w') as f:
json.dump(cache, f, indent=2)
except Exception as e:
print(f"Warning: Could not save star name cache: {e}", file=sys.stderr)
def query_star_info_from_simbad(hip_id):
"""
Query SIMBAD for the best name, spectral type, and temperature for a star.
Parameters:
-----------
hip_id : int
Hipparcos catalog number
Returns:
--------
tuple : (name, spectral_type, teff) - spectral_type and teff may be None
"""
try:
custom_simbad = Simbad()
custom_simbad.add_votable_fields('ids', 'sp_type', 'mesfe_h')
result = custom_simbad.query_object(f"HIP {hip_id}")
if result is None or len(result) == 0:
return f"HIP {hip_id}", None, None
# Get spectral type and temperature
sp_type = result['sp_type'][0] if result['sp_type'][0] else None
teff = None
if 'mesfe_h.teff' in result.colnames:
teff_val = result['mesfe_h.teff'][0]
if teff_val and not np.ma.is_masked(teff_val):
teff = float(teff_val)
# Get all identifiers
ids_str = result['ids'][0]
if isinstance(ids_str, bytes):
ids_str = ids_str.decode('utf-8')
identifiers = [id.strip() for id in ids_str.split('|')]
# Name priority hierarchy
# 1. Check for NAME prefix first (proper names like "NAME Sirius")
for id in identifiers:
if id.startswith('NAME '):
return id.replace('NAME ', ''), sp_type, teff
# 2. Look for simple proper names (single word, capitalized, not a catalog designation)
for id in identifiers:
if id.startswith(('HIP ', 'HD ', 'HR ', 'SAO ', 'TYC ', 'BD', 'CD', 'CPD', 'GJ ', '2MASS', 'GCRV', 'GEN#', 'GSC', 'AG', 'PPM')) or '*' in id:
continue
if len(id.split()) == 1 and id[0].isupper():
return id, sp_type, teff
# 3. Look for Bayer designations (Greek letters)
greek_letters = ['alf', 'bet', 'gam', 'del', 'eps', 'zet', 'eta', 'tet', 'iot', 'kap', 'lam', 'mu', 'nu', 'xi', 'omi', 'pi', 'rho', 'sig', 'tau', 'ups', 'phi', 'chi', 'psi', 'ome']
for id in identifiers:
for greek in greek_letters:
if greek in id.lower() and len(id.split()) <= 3:
return id.replace('* ', '').strip(), sp_type, teff
# 4. Look for Flamsteed designations (number + constellation)
for id in identifiers:
parts = id.split()
if len(parts) == 2 and parts[0].isdigit():
return id.replace('* ', '').strip(), sp_type, teff
# 5. Look for HD catalog
for id in identifiers:
if id.startswith('HD '):
return id, sp_type, teff
# 6. Fallback to HIP
return f"HIP {hip_id}", sp_type, teff
except Exception as e:
print(f"Warning: Could not query SIMBAD for HIP {hip_id}: {e}", file=sys.stderr)
return f"HIP {hip_id}", None, None
def get_star_info(hip_id, cache):
"""
Get star name, spectral type, and temperature using cache or SIMBAD.
Parameters:
-----------
hip_id : int
Hipparcos catalog number
cache : dict
Star info cache
Returns:
--------
tuple : (name, spectral_type, teff)
"""
hip_str = str(hip_id)
if hip_str in cache:
cached = cache[hip_str]
# Handle old cache formats
if isinstance(cached, str):
return cached, None, None
return cached.get('name', f"HIP {hip_id}"), cached.get('sp_type'), cached.get('teff')
# Query SIMBAD
name, sp_type, teff = query_star_info_from_simbad(hip_id)
# Cache successful queries
if not name.startswith('HIP '):
cache[hip_str] = {'name': name, 'sp_type': sp_type, 'teff': teff}
return name, sp_type, teff
# Common star names mapped to Hipparcos IDs
# Includes brightest stars and well-known named stars
def teff_to_rgb(teff):
"""
Convert effective temperature to RGB color.
Uses blackbody approximation for star colors.
Parameters:
-----------
teff : float
Effective temperature in Kelvin
Returns:
--------
tuple : (r, g, b) values 0-1
"""
# Approximate RGB from temperature (simplified blackbody)
# Based on typical star color temperatures
t = teff / 100.0
# Red channel
if t <= 66:
r = 1.0
else:
r = 1.29293618 * ((t - 60) ** -0.1332047592)
r = max(0, min(1, r))
# Green channel
if t <= 66:
g = 0.390081579 * np.log(t) - 0.631841444
else:
g = 1.12989086 * ((t - 60) ** -0.0755148492)
g = max(0, min(1, g))
# Blue channel
if t >= 66:
b = 1.0
elif t <= 19:
b = 0.0
else:
b = 0.543206789 * np.log(t - 10) - 1.19625408
b = max(0, min(1, b))
return (r, g, b)
def spectral_to_teff(sp_type):
"""
Estimate effective temperature from spectral type.
Parameters:
-----------
sp_type : str
Spectral type string (e.g., 'G2V', 'K1.5III', 'M3.5V')
Returns:
--------
float : Estimated temperature in Kelvin, or None if unparseable
"""
if not sp_type:
return None
# Base temperatures for each spectral class (main sequence)
base_temps = {
'O': 35000, 'B': 20000, 'A': 9000, 'F': 7000,
'G': 5500, 'K': 4500, 'M': 3200, 'L': 1800, 'T': 1000
}
# Temperature range within each class (early to late subtype)
temp_ranges = {
'O': 15000, 'B': 10000, 'A': 2000, 'F': 1500,
'G': 1000, 'K': 1000, 'M': 1400, 'L': 800, 'T': 700
}
# Parse spectral class (first letter)
sp_class = sp_type[0].upper()
if sp_class not in base_temps:
return None
base = base_temps[sp_class]
range_t = temp_ranges[sp_class]
# Try to parse subtype (0-9)
subtype = 5.0 # default to middle
try:
# Find digits after the class letter
i = 1
num_str = ''
while i < len(sp_type) and (sp_type[i].isdigit() or sp_type[i] == '.'):
num_str += sp_type[i]
i += 1
if num_str:
subtype = float(num_str)
subtype = min(9.9, max(0, subtype))
except:
pass
# Calculate temperature (higher subtype = cooler)
teff = base - (subtype / 10.0) * range_t
return teff
def get_star_color(sp_type, teff=None):
"""
Get RGB color for a star based on temperature or spectral type.
Parameters:
-----------
sp_type : str
Spectral type string
teff : float, optional
Effective temperature in Kelvin (preferred if available)
Returns:
--------
tuple : (r, g, b) values 0-1, or None for white default
"""
# Use teff if available
if teff and teff > 0:
return teff_to_rgb(teff)
# Fall back to spectral type
estimated_teff = spectral_to_teff(sp_type)
if estimated_teff:
return teff_to_rgb(estimated_teff)
return None # Will use white
STAR_NAMES = {
# Brightest stars (magnitude < 1.5)
32349: 'Sirius', # α CMa, mag -1.46
30438: 'Canopus', # α Car, mag -0.72
71683: 'Rigil Kentaurus', # α Cen A, mag -0.27
69673: 'Arcturus', # α Boo, mag -0.05
91262: 'Vega', # α Lyr, mag 0.03
24608: 'Capella', # α Aur, mag 0.08
24436: 'Rigel', # β Ori, mag 0.13
37279: 'Procyon', # α CMi, mag 0.34
9884: 'Achernar', # α Eri, mag 0.46
21421: 'Betelgeuse', # α Ori, mag 0.50 (variable)
25336: 'Hadar', # β Cen, mag 0.61
80763: 'Altair', # α Aql, mag 0.77
68702: 'Acrux', # α Cru, mag 0.77
21589: 'Aldebaran', # α Tau, mag 0.85
113368: 'Antares', # α Sco, mag 1.09
7588: 'Pollux', # β Gem, mag 1.14
49669: 'Spica', # α Vir, mag 1.04
86032: 'Deneb', # α Cyg, mag 1.25
62434: 'Mimosa', # β Cru, mag 1.30
# Other well-known stars
677: 'Alpheratz', # α And
3179: 'Schedar', # α Cas
5447: 'Mirach', # β And
8728: 'Diphda', # β Cet
11767: 'Polaris', # α UMi, North Star
15863: 'Menkar', # α Cet
25428: 'Bellatrix', # γ Ori
25930: 'Elnath', # β Tau
26311: 'Alnilam', # ε Ori (Orion's Belt center)
26727: 'Alnitak', # ζ Ori (Orion's Belt)
27989: 'Saiph', # κ Ori
30324: 'Miaplacidus', # β Car
31681: 'Adhara', # ε CMa
33579: 'Castor', # α Gem
34444: 'Shaula', # λ Sco
36850: 'Alhena', # γ Gem
41037: 'Mizar', # ζ UMa
44816: 'Dubhe', # α UMa
46390: 'Merak', # β UMa
49583: 'Alioth', # ε UMa
53910: 'Alkaid', # η UMa
54061: 'Menkent', # θ Cen
57632: 'Alphecca', # α CrB
59774: 'Antares', # α Sco
61084: 'Kochab', # β UMi
65474: 'Rasalhague', # α Oph
67301: 'Shaula', # λ Sco
72607: 'Eltanin', # γ Dra
76267: 'Rasalgethi', # α Her
77070: 'Vega', # α Lyr
84012: 'Sheliak', # β Lyr
85927: 'Albireo', # β Cyg
97649: 'Fomalhaut', # α PsA
102098: 'Deneb Kaitos', # β Cet
109268: 'Peacock', # α Pav
113881: 'Alnair', # α Gru
}
# Constellation center positions (RA in degrees, Dec in degrees)
# Approximate centers for orientation purposes
CONSTELLATION_POSITIONS = {
# Zodiac constellations
'Aries': (32.0, 20.0),
'Taurus': (65.0, 15.0),
'Gemini': (105.0, 22.0),
'Cancer': (130.0, 20.0),
'Leo': (155.0, 15.0),
'Virgo': (195.0, 0.0),
'Libra': (230.0, -15.0),
'Scorpius': (247.0, -25.0),
'Sagittarius': (285.0, -25.0),
'Capricornus': (315.0, -18.0),
'Aquarius': (330.0, -10.0),
'Pisces': (15.0, 10.0),
# Major northern constellations
'Ursa Major': (165.0, 55.0),
'Ursa Minor': (225.0, 75.0),
'Cassiopeia': (15.0, 62.0),
'Cepheus': (315.0, 70.0),
'Draco': (225.0, 65.0),
'Cygnus': (305.0, 42.0),
'Lyra': (280.0, 38.0),
'Aquila': (295.0, 8.0),
'Hercules': (258.0, 30.0),
'Boötes': (210.0, 30.0),
'Corona Borealis': (233.0, 30.0),
'Andromeda': (20.0, 37.0),
'Perseus': (50.0, 43.0),
'Auriga': (80.0, 42.0),
'Pegasus': (340.0, 20.0),
# Orion region
'Orion': (85.0, 0.0),
'Canis Major': (105.0, -20.0),
'Canis Minor': (115.0, 5.0),
# Southern constellations
'Centaurus': (200.0, -45.0),
'Crux': (187.0, -60.0),
'Carina': (140.0, -64.0),
'Vela': (135.0, -47.0),
'Puppis': (120.0, -30.0),
'Hydra': (170.0, -15.0),
'Corvus': (185.0, -18.0),
'Crater': (175.0, -15.0),
'Lupus': (225.0, -42.0),
'Ara': (260.0, -55.0),
'Triangulum Australe': (245.0, -65.0),
'Pavo': (305.0, -65.0),
'Grus': (335.0, -47.0),
'Phoenix': (20.0, -48.0),
'Eridanus': (55.0, -30.0),
'Fornax': (45.0, -32.0),
'Sculptor': (350.0, -32.0),
'Tucana': (340.0, -65.0),
'Indus': (315.0, -55.0),
'Octans': (210.0, -85.0),
'Columba': (85.0, -35.0),
'Dorado': (75.0, -60.0),
'Pictor': (85.0, -55.0),
}
def adjust_label_positions(ax, texts: List, constellation_texts: List = None,
text_magnitudes: List = None):
"""
Manually adjust label positions to avoid overlaps.
Star labels prefer to be above the star (initial offset already applied).
Brighter stars (lower magnitude) are processed first and get priority for positions.
Uses multiple position alternatives and collision detection.
Parameters:
-----------
ax : matplotlib axis
The axis containing the labels
texts : list
List of matplotlib Text objects (star labels and Sol)
constellation_texts : list, optional
List of matplotlib Text objects for constellation labels
text_magnitudes : list, optional
List of magnitudes corresponding to texts (for priority sorting)
"""
if not texts and not constellation_texts:
return
# Combine texts and magnitudes for sorting
# Brighter stars (lower magnitude) get processed first
star_labels = []
if texts and text_magnitudes:
# Pair each text with its magnitude for sorting
for text, mag in zip(texts, text_magnitudes):
star_labels.append((text, mag))
# Sort by magnitude (brighter/lower magnitude first)
star_labels.sort(key=lambda x: x[1])
elif texts:
# No magnitude data, just use texts as-is
star_labels = [(text, 999) for text in texts]
# Add constellation labels (processed after stars)
const_labels = []
if constellation_texts:
const_labels = [(text, 1000) for text in constellation_texts]
# Combine: stars (sorted by brightness) then constellations
all_labels = star_labels + const_labels
if not all_labels:
return
# Get axis limits for calculating label dimensions
xlim = ax.get_xlim()
ylim = ax.get_ylim()
x_range = xlim[1] - xlim[0]
y_range = ylim[1] - ylim[0]
# Base label dimensions (as fraction of axis range)
base_label_width = x_range * 0.015
base_label_height = y_range * 0.01
# Store label positions and dimensions
label_data = []
# Position alternatives (prefer above, then other positions)
# Order matters: above is first (preferred for stars)
position_offsets = [
(0, 1), # Above (preferred)
(1, 0), # Right
(0, -1), # Below
(-1, 0), # Left
(0.7, 0.7), # Upper right
(-0.7, 0.7), # Upper left
(0.7, -0.7), # Lower right
(-0.7, -0.7),# Lower left
(0, 1.5), # Far above
(1.5, 0), # Far right
(0, -1.5), # Far below
(-1.5, 0), # Far left
]
def labels_collide(x1, y1, w1, h1, x2, y2, w2, h2):
"""Check if two labels overlap."""
return not (x1 + w1/2 < x2 - w2/2 or
x1 - w1/2 > x2 + w2/2 or
y1 + h1/2 < y2 - h2/2 or
y1 - h1/2 > y2 + h2/2)
# Process each label (in brightness order for stars, then constellations)
for text, magnitude in all_labels:
# Get font size and calculate scaled dimensions
fontsize = text.get_fontsize()
size_scale = fontsize / 8.0 # Scale relative to base fontsize
label_width = base_label_width * size_scale
label_height = base_label_height * size_scale
# Star position (labels start here)
star_x = text.get_position()[0]
star_y = text.get_position()[1]
# Direction-aware offset multiplier
# Constellation labels need more space
offset_multiplier = 1.3 if fontsize <= 7 else 1.0
# Try each position alternative
# Always offset labels from stars (start with "above" preference)
best_position = None
for dx, dy in position_offsets:
# Use direction-aware offsets: width for horizontal, height for vertical
# This prevents labels from being pushed too far in one direction
offset_x = abs(dx) * label_width * offset_multiplier if dx != 0 else 0
offset_y = abs(dy) * label_height * offset_multiplier if dy != 0 else 0
# For diagonal moves, use both components
test_x = star_x + (dx * label_width * offset_multiplier if dx != 0 else 0)
test_y = star_y + (dy * label_height * offset_multiplier if dy != 0 else 0)
# Check collision with all stored labels
collides = False
for stored in label_data:
if labels_collide(test_x, test_y, label_width, label_height,
stored['x'], stored['y'], stored['w'], stored['h']):
collides = True
break
if not collides:
best_position = (test_x, test_y)
break
# If all positions collide, use the first alternative anyway
if best_position is None:
dx, dy = position_offsets[0]
fallback_x = star_x + (dx * label_width * offset_multiplier if dx != 0 else 0)
fallback_y = star_y + (dy * label_height * offset_multiplier if dy != 0 else 0)
best_position = (fallback_x, fallback_y)
# Update text position
text.set_position(best_position)
# Store this label's position and dimensions
label_data.append({
'x': best_position[0],
'y': best_position[1],
'w': label_width,
'h': label_height
})
class StarChartGenerator:
"""Main class for generating star charts from arbitrary observer positions."""
def __init__(self, ra: float, dec: float, distance: float,
system_name: Optional[str] = None,
magnitude_cutoff: float = 6.0,
label_magnitude_threshold: float = 1.0,
show_constellations: bool = False,
label_constellations: bool = None,
grid_spacing: int = 15,
output_dir: str = ".",
show_grid: bool = True,
show_star_labels: bool = True,
show_constellation_labels: bool = True,
show_sol_label: bool = True,
highlight_sol: bool = True):
"""
Initialize the star chart generator.
Parameters:
-----------
ra : float
Right Ascension in decimal degrees (0-360)
dec : float
Declination in decimal degrees (-90 to +90)
distance : float
Distance from Sol in parsecs
system_name : str, optional
Name for the system (default: coordinates string)
magnitude_cutoff : float
Faintest magnitude to display (default: 6.0)
label_magnitude_threshold : float
Brightest magnitude to label (default: 1.0)
show_constellations : bool
Whether to show constellation lines (default: False)
label_constellations : bool, optional
Whether to label constellations (auto-decides based on distance if None)
grid_spacing : int
Grid line spacing in degrees (default: 15)
output_dir : str
Output directory path (default: current directory)
"""
self.ra = self._validate_ra(ra)
self.dec = self._validate_dec(dec)
self.distance = self._validate_distance(distance)
self.system_name = system_name or f"RA {ra}° Dec {dec}° Distance {distance} pc"
self.magnitude_cutoff = magnitude_cutoff
self.label_magnitude_threshold = label_magnitude_threshold
self.show_constellations = show_constellations
# Auto-decide constellation labels based on distance (if enabled)
if label_constellations is None:
self.label_constellations = show_constellation_labels and (distance * 3.26156 < 40)
else:
self.label_constellations = label_constellations and show_constellation_labels
self.grid_spacing = grid_spacing
self.output_dir = output_dir
self.show_grid = show_grid
self.show_star_labels = show_star_labels
self.show_sol_label = show_sol_label
self.highlight_sol = highlight_sol
# Will be populated during processing
self.observer_position = None
self.stars_data = None
# Load star name cache
self.star_name_cache = load_star_name_cache()
@staticmethod
def _validate_ra(ra: float) -> float:
"""Validate and normalize RA to 0-360 degrees."""
if ra < 0 or ra > 360:
raise ValueError(f"RA must be between 0 and 360 degrees, got {ra}")
return ra
@staticmethod
def _validate_dec(dec: float) -> float:
"""Validate declination range."""
if dec < -90 or dec > 90:
raise ValueError(f"Dec must be between -90 and +90 degrees, got {dec}")
return dec
@staticmethod
def _validate_distance(distance: float) -> float:
"""Validate distance is positive."""
if distance <= 0:
raise ValueError(f"Distance must be positive, got {distance}")
return distance
def ra_dec_distance_to_cartesian(self) -> np.ndarray:
"""
Convert observer's RA/Dec/distance (spherical) to Cartesian coordinates.
Returns:
--------
np.ndarray : [x, y, z] position in AU from Solar System barycenter
"""
# Convert RA, Dec to radians
ra_rad = np.radians(self.ra)
dec_rad = np.radians(self.dec)
# Convert parsecs to AU (1 parsec = 206265 AU)
distance_au = self.distance * 206265.0
# Spherical to Cartesian conversion
# In equatorial coordinates:
# x points to RA=0, Dec=0 (vernal equinox)
# y points to RA=90, Dec=0
# z points to Dec=90 (north celestial pole)
x = distance_au * np.cos(dec_rad) * np.cos(ra_rad)
y = distance_au * np.cos(dec_rad) * np.sin(ra_rad)
z = distance_au * np.sin(dec_rad)
return np.array([x, y, z])
def load_hipparcos_catalog(self):
"""Load the Hipparcos star catalog using Skyfield."""
print("Loading Hipparcos catalog...", file=sys.stderr)
# Note: de421.bsp (JPL planetary ephemeris) was intentionally removed here.
# It would be needed for time-dependent astrometric corrections (stellar
# aberration, barycentric parallax refinement, date-specific sky rendering),
# but exospective's current calculations work directly from catalog
# RA/Dec/parallax and don't require ephemeris data. Re-add if adding
# time-dependent or high-precision features in the future.
# Load Hipparcos catalog
with load.open(hipparcos.URL) as f:
df = hipparcos.load_dataframe(f)
print(f"Loaded {len(df)} stars from Hipparcos catalog", file=sys.stderr)
return df
def calculate_star_positions_from_observer(self, hipparcos_df: pd.DataFrame) -> pd.DataFrame:
"""
Calculate positions and apparent magnitudes of stars as seen from observer position.
Parameters:
-----------
hipparcos_df : pd.DataFrame
Hipparcos catalog data
Returns:
--------
pd.DataFrame : Processed star data with observer-relative positions and magnitudes
"""
# Get observer position in Cartesian AU
self.observer_position = self.ra_dec_distance_to_cartesian()
print(f"Observer position: {self.observer_position / 206265.0} pc", file=sys.stderr)
print(f"Processing {len(hipparcos_df)} stars...", file=sys.stderr)
# Filter out stars without parallax data
stars_with_parallax = hipparcos_df[hipparcos_df['parallax_mas'] > 0].copy()
print(f"Stars with valid parallax: {len(stars_with_parallax)}", file=sys.stderr)
# Calculate distance to each star from Earth (in parsecs)
# parallax_mas is in milliarcseconds, so we use 1000.0 / parallax_mas to get parsecs
stars_with_parallax['distance_from_earth_pc'] = 1000.0 / stars_with_parallax['parallax_mas']
# Convert star positions to Cartesian coordinates (in AU)
# Using the same coordinate system as observer position
ra_rad = np.radians(stars_with_parallax['ra_degrees'])
dec_rad = np.radians(stars_with_parallax['dec_degrees'])
distance_au = stars_with_parallax['distance_from_earth_pc'] * 206265.0
stars_with_parallax['x_earth'] = distance_au * np.cos(dec_rad) * np.cos(ra_rad)
stars_with_parallax['y_earth'] = distance_au * np.cos(dec_rad) * np.sin(ra_rad)
stars_with_parallax['z_earth'] = distance_au * np.sin(dec_rad)
# Calculate position relative to observer
stars_with_parallax['x_rel'] = stars_with_parallax['x_earth'] - self.observer_position[0]
stars_with_parallax['y_rel'] = stars_with_parallax['y_earth'] - self.observer_position[1]
stars_with_parallax['z_rel'] = stars_with_parallax['z_earth'] - self.observer_position[2]
# Calculate distance from observer (in AU, then convert to parsecs)
distance_from_observer_au = np.sqrt(
stars_with_parallax['x_rel']**2 +
stars_with_parallax['y_rel']**2 +
stars_with_parallax['z_rel']**2
)
stars_with_parallax['distance_from_observer_pc'] = distance_from_observer_au / 206265.0
# Recalculate apparent magnitude from observer position
# Formula: m_new = m_earth + 5 * log10(d_new / d_earth)
distance_ratio = (stars_with_parallax['distance_from_observer_pc'] /
stars_with_parallax['distance_from_earth_pc'])
stars_with_parallax['magnitude_from_observer'] = (
stars_with_parallax['magnitude'] + 5 * np.log10(distance_ratio)
)
# Filter out stars within 0.5 light-years (to exclude parent star system)
# 0.5 ly = 0.1533 pc
min_distance_pc = 0.5 / 3.26156
stars_with_parallax = stars_with_parallax[
stars_with_parallax['distance_from_observer_pc'] >= min_distance_pc
].copy()
# Filter by magnitude cutoff
visible_stars = stars_with_parallax[
stars_with_parallax['magnitude_from_observer'] <= self.magnitude_cutoff
].copy()
print(f"Stars visible from observer (mag <= {self.magnitude_cutoff}): {len(visible_stars)}", file=sys.stderr)
# Add star names from STAR_NAMES dictionary
visible_stars['name'] = visible_stars.index.map(STAR_NAMES)
return visible_stars
def add_sol(self, stars_df: pd.DataFrame) -> pd.DataFrame:
"""
Add Sol (the Sun) to the star data.
Parameters:
-----------
stars_df : pd.DataFrame
Existing star data
Returns:
--------
pd.DataFrame : Star data with Sol added
"""
# Sol is at the origin in Earth-centered coordinates
# Position relative to observer
sol_x_rel = -self.observer_position[0]
sol_y_rel = -self.observer_position[1]
sol_z_rel = -self.observer_position[2]
# Distance to Sol from observer
distance_to_sol_au = np.sqrt(sol_x_rel**2 + sol_y_rel**2 + sol_z_rel**2)
distance_to_sol_pc = distance_to_sol_au / 206265.0
# Calculate Sol's apparent magnitude from observer
# Absolute magnitude of Sol: M = 4.83
# m = M + 5 * log10(d) - 5, where d is in parsecs
if distance_to_sol_pc > 0:
sol_magnitude = 4.83 + 5 * np.log10(distance_to_sol_pc) - 5
else:
sol_magnitude = -26.74 # As seen from Earth (observer at Sol)
print(f"Sol distance: {distance_to_sol_pc:.2f} pc, magnitude: {sol_magnitude:.2f}", file=sys.stderr)
# Create Sol entry
sol_data = {
'hip': 0, # Special ID for Sol
'magnitude': -26.74, # From Earth
'ra_degrees': 0.0,
'dec_degrees': 0.0,
'parallax': 1000000.0, # Dummy value
'distance_from_earth_pc': 0.0,
'x_earth': 0.0,
'y_earth': 0.0,
'z_earth': 0.0,
'x_rel': sol_x_rel,
'y_rel': sol_y_rel,
'z_rel': sol_z_rel,
'distance_from_observer_pc': distance_to_sol_pc,
'magnitude_from_observer': sol_magnitude,
'name': 'Sol'
}
# Add to dataframe
sol_df = pd.DataFrame([sol_data], index=[0])
combined_df = pd.concat([stars_df, sol_df])
return combined_df
def transform_to_galactic_coordinates(self, stars_df: pd.DataFrame) -> pd.DataFrame:
"""
Transform star positions from observer to galactic coordinates.
Parameters:
-----------
stars_df : pd.DataFrame
Star data with relative positions
Returns:
--------
pd.DataFrame : Star data with galactic longitude and latitude
"""
print("Transforming to galactic coordinates...", file=sys.stderr)
# Calculate spherical coordinates from observer-relative Cartesian
x = stars_df['x_rel'].values
y = stars_df['y_rel'].values
z = stars_df['z_rel'].values
# Convert to spherical coordinates (RA, Dec from observer)
r = np.sqrt(x**2 + y**2 + z**2)
ra_from_obs = np.degrees(np.arctan2(y, x))
ra_from_obs = np.where(ra_from_obs < 0, ra_from_obs + 360, ra_from_obs)
dec_from_obs = np.degrees(np.arcsin(z / r))
# Now convert from equatorial to galactic coordinates
# Using standard transformation
# Galactic north pole: RA = 192.859508°, Dec = 27.128336°
# Galactic center: RA = 266.405°, Dec = -28.936°
# Standard rotation matrices for equatorial to galactic conversion
ra_rad = np.radians(ra_from_obs)
dec_rad = np.radians(dec_from_obs)
# Galactic pole in equatorial coordinates
ra_gp = np.radians(192.859508)
dec_gp = np.radians(27.128336)
l_cp = np.radians(122.932) # Galactic longitude of celestial pole
# Conversion formulas
sin_b = (np.sin(dec_rad) * np.sin(dec_gp) +
np.cos(dec_rad) * np.cos(dec_gp) * np.cos(ra_rad - ra_gp))
galactic_lat = np.degrees(np.arcsin(sin_b))
y_gal = np.cos(dec_rad) * np.sin(ra_rad - ra_gp)
x_gal = (np.sin(dec_rad) * np.cos(dec_gp) -
np.cos(dec_rad) * np.sin(dec_gp) * np.cos(ra_rad - ra_gp))
galactic_lon = np.degrees(np.arctan2(y_gal, x_gal)) + np.degrees(l_cp)
galactic_lon = np.where(galactic_lon < 0, galactic_lon + 360, galactic_lon)
galactic_lon = np.where(galactic_lon >= 360, galactic_lon - 360, galactic_lon)
stars_df['galactic_lon'] = galactic_lon
stars_df['galactic_lat'] = galactic_lat
return stars_df
def get_constellation_positions_from_observer(self):
"""
Calculate where constellation region centers appear from observer's viewpoint.
Returns:
--------
list of tuples: (constellation_name, galactic_lon, galactic_lat)
"""
constellation_positions = []
for const_name, (ra_earth, dec_earth) in CONSTELLATION_POSITIONS.items():
# Convert constellation center position (as seen from Earth) to Cartesian
# Treat it as a point at a large distance (arbitrary, just for direction)
distance_au = 1e10 # Arbitrary large distance for direction
ra_rad = np.radians(ra_earth)
dec_rad = np.radians(dec_earth)
# Position in Earth-centered coordinates
x_earth = distance_au * np.cos(dec_rad) * np.cos(ra_rad)
y_earth = distance_au * np.cos(dec_rad) * np.sin(ra_rad)
z_earth = distance_au * np.sin(dec_rad)
# Position relative to observer
x_rel = x_earth - self.observer_position[0]
y_rel = y_earth - self.observer_position[1]
z_rel = z_earth - self.observer_position[2]
# Convert to spherical (RA, Dec from observer)
r = np.sqrt(x_rel**2 + y_rel**2 + z_rel**2)
ra_from_obs = np.degrees(np.arctan2(y_rel, x_rel))
if ra_from_obs < 0:
ra_from_obs += 360
dec_from_obs = np.degrees(np.arcsin(z_rel / r))
# Convert to galactic coordinates
ra_rad = np.radians(ra_from_obs)
dec_rad = np.radians(dec_from_obs)
ra_gp = np.radians(192.859508)
dec_gp = np.radians(27.128336)
l_cp = np.radians(122.932)
sin_b = (np.sin(dec_rad) * np.sin(dec_gp) +
np.cos(dec_rad) * np.cos(dec_gp) * np.cos(ra_rad - ra_gp))
galactic_lat = np.degrees(np.arcsin(sin_b))
y_gal = np.cos(dec_rad) * np.sin(ra_rad - ra_gp)
x_gal = (np.sin(dec_rad) * np.cos(dec_gp) -
np.cos(dec_rad) * np.sin(dec_gp) * np.cos(ra_rad - ra_gp))
galactic_lon = np.degrees(np.arctan2(y_gal, x_gal)) + np.degrees(l_cp)
if galactic_lon < 0:
galactic_lon += 360
if galactic_lon >= 360:
galactic_lon -= 360
constellation_positions.append((const_name, galactic_lon, galactic_lat))
return constellation_positions
def get_stars_to_label(self, stars_df, top_n=20):
"""
Determine which stars should be labeled based on brightness from observer's perspective.
Queries SIMBAD for proper names.
Parameters:
-----------
stars_df : pd.DataFrame
Star data with magnitude_from_observer
top_n : int
Number of brightest stars to label (default: 20)
Returns:
--------
pd.DataFrame : Stars to label with display names and colors
"""
# Exclude Sol from this logic (handled separately)
non_sol_stars = stars_df[stars_df.get('name', pd.Series()) != 'Sol'].copy()
# Get top N brightest stars from observer
stars_to_label = non_sol_stars.nsmallest(top_n, 'magnitude_from_observer').copy()
print(f"Querying SIMBAD for names of {len(stars_to_label)} bright stars...", file=sys.stderr)
# Query SIMBAD for display names and colors
display_names = []
colors = []
for hip_id in stars_to_label.index:
name, sp_type, teff = get_star_info(hip_id, self.star_name_cache)
display_names.append(name)
color = get_star_color(sp_type, teff)
colors.append(color if color else (1.0, 1.0, 1.0))
stars_to_label['display_name'] = display_names
stars_to_label['color'] = colors
# Save cache after queries
save_star_name_cache(self.star_name_cache)
return stars_to_label
def calculate_star_size(self, magnitudes):
"""
Calculate star marker sizes based on apparent magnitude.
Larger sizes for brighter (smaller magnitude) stars.
Parameters:
-----------
magnitudes : array-like
Apparent magnitudes
Returns:
--------
array : Marker sizes in points
"""
# Scale from magnitude to size
# Magnitude 6 (faintest visible) -> smallest size
# Magnitude -1.5 (brightest) -> largest size