-
Notifications
You must be signed in to change notification settings - Fork 0
/
runaway_functionsv3.py
2361 lines (2088 loc) · 123 KB
/
runaway_functionsv3.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
import os
import astropy
import numpy as np
from astropy import units as u
from astroquery.vizier import Vizier
from astropy.table import Table, join,vstack, Column, Row
from astropy.coordinates import SkyCoord, Angle, match_coordinates_sky
from astropy.time import Time
import warnings
from astropy.utils.metadata import MergeConflictWarning
from astropy.utils.exceptions import ErfaWarning
import time
from typing import List
import yaml
from astropy.stats import sigma_clip
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from matplotlib import pyplot as plt
plt.rcParams["font.family"] = "Palatino"
plt.rcParams["font.size"] = 44
plt.rcParams['figure.subplot.top'] = 1
plt.rcParams['figure.subplot.bottom'] = 0.12
plt.rcParams['figure.subplot.left'] = 0.14
plt.rcParams['figure.subplot.right'] = 1
plt.rcParams['figure.subplot.hspace'] = 0.2
plt.rcParams['figure.subplot.wspace'] = 0.2
# plt.rcParams["font.size"] = 44
# plt.rcParams['figure.subplot.top'] = 1
# plt.rcParams['figure.subplot.bottom'] = 0.1
# plt.rcParams['figure.subplot.left'] = 0.12
# plt.rcParams['figure.subplot.right'] = 1
# plt.rcParams['figure.subplot.hspace'] = 0.2
# plt.rcParams['figure.subplot.wspace'] = 0.2
from astroquery.skyview import SkyView
from regions import CircleSkyRegion, PointSkyRegion, LineSkyRegion
from astropy.wcs import WCS
from astropy.visualization.wcsaxes import add_scalebar
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
from astropy.io import fits
from astroquery.simbad import Simbad
import matplotlib.patches as patches
import matplotlib.cm as cm
import matplotlib.colors as mcolors
from adjustText import adjust_text
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import simpledialog, colorchooser
from astropy.io import ascii
import io
from uncertainties import ufloat, unumpy
workclusters = ['ASCC_107', 'ASCC_114', 'ASCC_127', 'ASCC_13', 'ASCC_16', 'ASCC_19', 'ASCC_21', 'ASCC_32', 'ASCC_67', 'ASCC_9', 'Alessi_20', 'Alessi_43', 'Alessi_Teutsch_5', 'Antalova_2', 'Archinal_1', 'Aveni_Hunter_1', 'BDSB91', 'BDSB93', 'BDSB96', 'BH_121', 'BH_200', 'BH_205', 'BH_217', 'BH_221', 'BH_245', 'BH_54', 'BH_56', 'BH_87', 'BH_92', 'Barkhatova_1', 'Basel_18', 'Basel_8', 'Berkeley_11', 'Berkeley_15', 'Berkeley_47', 'Berkeley_62', 'Berkeley_65', 'Berkeley_7', 'Berkeley_79', 'Berkeley_86', 'Berkeley_87', 'Berkeley_97', 'Bica_2', 'Biurakan_2', 'Bochum_10', 'Bochum_11', 'Bochum_13', 'COIN-Gaia_16', 'COIN-Gaia_21', 'COIN-Gaia_35', 'COIN-Gaia_41', 'Collinder_104', 'Collinder_106', 'Collinder_107', 'Collinder_132', 'Collinder_197', 'Collinder_205', 'Collinder_272', 'Collinder_419', 'Collinder_421', 'Collinder_69', 'Collinder_95', 'Czernik_1', 'Czernik_31', 'Czernik_41', 'Czernik_6', 'Czernik_8', 'Dias_1', 'Dias_5', 'Dolidze_16', 'Dolidze_3', 'Dolidze_32', 'Dolidze_5', 'Dolidze_53', 'Dolidze_8', 'ESO_134_12', 'ESO_332_08', 'ESO_332_13', 'FSR_0165', 'FSR_0198', 'FSR_0224', 'FSR_0236', 'FSR_0284', 'FSR_0306', 'FSR_0336', 'FSR_0398', 'FSR_0451', 'FSR_0498', 'FSR_0551', 'FSR_0686', 'FSR_0852', 'FSR_0904', 'FSR_0968', 'Gulliver_10', 'Gulliver_15', 'Gulliver_19', 'Gulliver_2', 'Gulliver_26', 'Gulliver_31', 'Gulliver_40', 'Gulliver_43', 'Gulliver_5', 'Gulliver_6', 'Gulliver_8', 'Haffner_13', 'Harvard_16', 'Hogg_10', 'Hogg_16', 'Hogg_18', 'Hogg_19', 'Hogg_22', 'IC_1396', 'IC_1590', 'IC_1805', 'IC_1848', 'IC_2157', 'IC_2395', 'IC_2581', 'IC_2948', 'IC_348', 'IC_4996', 'IC_5146', 'Juchert_20', 'King_14', 'King_21', 'King_26', 'Kronberger_1', 'Kronberger_69', 'LP_0288', 'LP_0503', 'LP_0506', 'LP_0733', 'LP_1049', 'LP_1209', 'LP_1211', 'LP_1218', 'LP_1329', 'LP_1342', 'LP_1355', 'LP_1487', 'LP_1490', 'LP_1614', 'LP_1641', 'LP_1768', 'LP_1771', 'LP_1775', 'LP_1780', 'LP_1807', 'LP_1821', 'LP_1864', 'LP_1888', 'LP_2106', 'LP_2113', 'LP_2172', 'LP_2219', 'LP_2221', 'LP_2249', 'Lynga_4', 'Markarian_38', 'Markarian_50', 'Mayer_1', 'Moffat_1', 'NGC_1220', 'NGC_1348', 'NGC_1444', 'NGC_146', 'NGC_1502', 'NGC_1579', 'NGC_1960', 'NGC_1977', 'NGC_1980', 'NGC_2129', 'NGC_2169', 'NGC_2183', 'NGC_2232', 'NGC_2244', 'NGC_2264', 'NGC_2362', 'NGC_2367', 'NGC_2384', 'NGC_2451B', 'NGC_2547', 'NGC_2571', 'NGC_2645', 'NGC_2659', 'NGC_3228', 'NGC_3293', 'NGC_3324', 'NGC_3572', 'NGC_3590', 'NGC_366', 'NGC_3766', 'NGC_4103', 'NGC_433', 'NGC_4463', 'NGC_457', 'NGC_4755', 'NGC_5606', 'NGC_581', 'NGC_6178', 'NGC_6193', 'NGC_6200', 'NGC_6216', 'NGC_6231', 'NGC_6249', 'NGC_6250', 'NGC_6318', 'NGC_6322', 'NGC_637', 'NGC_6383', 'NGC_6396', 'NGC_6404', 'NGC_6451', 'NGC_6520', 'NGC_6530', 'NGC_6531', 'NGC_654', 'NGC_6561', 'NGC_6604', 'NGC_6611', 'NGC_6613', 'NGC_663', 'NGC_6649', 'NGC_6664', 'NGC_6823', 'NGC_6871', 'NGC_6910', 'NGC_6913', 'NGC_7039', 'NGC_7129', 'NGC_7160', 'NGC_7281', 'NGC_7380', 'NGC_869', 'NGC_884', 'NGC_957', 'Pismis_11', 'Pismis_27', 'Pismis_5', 'Pismis_8', 'Pismis_Moreno_1', 'Pozzo_1', 'RSG_8', 'Riddle_4', 'Roslund_2', 'Ruprecht_120', 'Ruprecht_127', 'Ruprecht_138', 'Ruprecht_144', 'Ruprecht_170', 'Ruprecht_26', 'Ruprecht_65', 'Ruprecht_71', 'Ruprecht_94', 'SAI_118', 'SAI_24', 'SAI_4', 'Stephenson_1', 'Stock_14', 'Stock_20', 'Stock_8', 'Teutsch_30', 'Teutsch_38', 'Teutsch_8', 'Trapezium-FG', 'Trumpler_1', 'Trumpler_14', 'Trumpler_15', 'Trumpler_16', 'Trumpler_17', 'Trumpler_28', 'Trumpler_3', 'Trumpler_33', 'UBC_121', 'UBC_133', 'UBC_134', 'UBC_148', 'UBC_155', 'UBC_156', 'UBC_166', 'UBC_177', 'UBC_178', 'UBC_17a', 'UBC_182', 'UBC_188', 'UBC_191', 'UBC_192', 'UBC_198', 'UBC_245', 'UBC_249', 'UBC_258', 'UBC_267', 'UBC_270', 'UBC_272', 'UBC_280', 'UBC_281', 'UBC_296', 'UBC_31', 'UBC_322', 'UBC_337', 'UBC_338', 'UBC_341', 'UBC_342', 'UBC_345', 'UBC_354', 'UBC_361', 'UBC_373', 'UBC_377', 'UBC_379', 'UBC_386', 'UBC_389', 'UBC_391', 'UBC_396', 'UBC_410', 'UBC_413', 'UBC_415', 'UBC_417', 'UBC_422', 'UBC_423', 'UBC_432', 'UBC_46', 'UBC_479', 'UBC_482', 'UBC_483', 'UBC_487', 'UBC_499', 'UBC_51', 'UBC_521', 'UBC_531', 'UBC_532', 'UBC_534', 'UBC_535', 'UBC_536', 'UBC_541', 'UBC_542', 'UBC_545', 'UBC_548', 'UBC_549', 'UBC_550', 'UBC_552', 'UBC_559', 'UBC_562', 'UBC_576', 'UBC_582', 'UBC_588', 'UBC_606', 'UBC_620', 'UBC_63', 'UBC_652', 'UBC_653', 'UBC_663', 'UBC_665', 'UBC_668', 'UFMG_22', 'UFMG_3', 'UFMG_45', 'UFMG_53', 'UPK_150', 'UPK_166', 'UPK_169', 'UPK_194', 'UPK_220', 'UPK_23', 'UPK_265', 'UPK_28', 'UPK_38', 'UPK_385', 'UPK_398', 'UPK_422', 'UPK_445', 'UPK_457', 'UPK_526', 'UPK_540', 'UPK_604', 'UPK_62', 'UPK_621', 'vdBergh_130', 'vdBergh_80', 'vdBergh_85', 'vdBergh_92']
workclusters3d = ['ASCC_107', 'ASCC_114', 'ASCC_127', 'ASCC_13', 'ASCC_16', 'ASCC_19', 'ASCC_21', 'ASCC_32', 'Alessi_20', 'Alessi_43', 'Alessi_Teutsch_5', 'Archinal_1', 'Aveni_Hunter_1', 'BDSB91', 'BDSB93', 'BDSB96', 'BH_121', 'BH_200', 'BH_205', 'BH_221', 'BH_54', 'BH_56', 'BH_87', 'Basel_8', 'Berkeley_86', 'Berkeley_87', 'Bica_2', 'Biurakan_2', 'Bochum_10', 'Bochum_11', 'Bochum_13', 'COIN-Gaia_21', 'COIN-Gaia_41', 'Collinder_104', 'Collinder_106', 'Collinder_107', 'Collinder_132', 'Collinder_197', 'Collinder_272', 'Collinder_419', 'Collinder_421', 'Collinder_69', 'Collinder_95', 'Czernik_41', 'Dias_5', 'Dolidze_16', 'Dolidze_32', 'Dolidze_5', 'Dolidze_53', 'Dolidze_8', 'ESO_332_08', 'ESO_332_13', 'FSR_0165', 'FSR_0236', 'FSR_0306', 'FSR_0336', 'FSR_0398', 'FSR_0551', 'FSR_0686', 'FSR_0904', 'Gulliver_10', 'Gulliver_19', 'Gulliver_2', 'Gulliver_26', 'Gulliver_31', 'Gulliver_6', 'Gulliver_8', 'Haffner_13', 'Harvard_16', 'Hogg_10', 'Hogg_18', 'Hogg_19', 'Hogg_22', 'IC_1396', 'IC_1590', 'IC_1805', 'IC_1848', 'IC_2395', 'IC_2948', 'IC_348', 'IC_4996', 'IC_5146', 'Juchert_20', 'LP_0288', 'LP_0503', 'LP_0506', 'LP_0733', 'LP_1049', 'LP_1209', 'LP_1211', 'LP_1218', 'LP_1329', 'LP_1342', 'LP_1355', 'LP_1490', 'LP_1614', 'LP_1641', 'LP_1768', 'LP_1775', 'LP_1780', 'LP_1807', 'LP_1821', 'LP_2106', 'LP_2113', 'LP_2172', 'LP_2219', 'LP_2221', 'LP_2249', 'Lynga_4', 'Markarian_38', 'NGC_1348', 'NGC_1502', 'NGC_1579', 'NGC_1960', 'NGC_1977', 'NGC_1980', 'NGC_2129', 'NGC_2169', 'NGC_2183', 'NGC_2232', 'NGC_2244', 'NGC_2264', 'NGC_2362', 'NGC_2451B', 'NGC_2547', 'NGC_2571', 'NGC_2659', 'NGC_3228', 'NGC_3293', 'NGC_3324', 'NGC_3572', 'NGC_366', 'NGC_3766', 'NGC_4103', 'NGC_457', 'NGC_4755', 'NGC_581', 'NGC_6178', 'NGC_6193', 'NGC_6200', 'NGC_6216', 'NGC_6231', 'NGC_6249', 'NGC_6250', 'NGC_6318', 'NGC_6322', 'NGC_6383', 'NGC_6396', 'NGC_6404', 'NGC_6520', 'NGC_6530', 'NGC_6531', 'NGC_6561', 'NGC_6611', 'NGC_6613', 'NGC_663', 'NGC_6649', 'NGC_6664', 'NGC_6823', 'NGC_6871', 'NGC_6910', 'NGC_6913', 'NGC_7039', 'NGC_7129', 'NGC_7160', 'NGC_7281', 'NGC_7380', 'NGC_869', 'NGC_957', 'Pismis_27', 'Pismis_5', 'Pismis_Moreno_1', 'Pozzo_1', 'RSG_8', 'Riddle_4', 'Roslund_2', 'Ruprecht_26', 'Ruprecht_94', 'SAI_24', 'Stephenson_1', 'Stock_8', 'Teutsch_38', 'Trapezium-FG', 'Trumpler_14', 'Trumpler_15', 'Trumpler_16', 'Trumpler_17', 'Trumpler_28', 'Trumpler_3', 'UBC_133', 'UBC_148', 'UBC_155', 'UBC_156', 'UBC_178', 'UBC_17a', 'UBC_182', 'UBC_188', 'UBC_191', 'UBC_192', 'UBC_198', 'UBC_249', 'UBC_258', 'UBC_267', 'UBC_272', 'UBC_280', 'UBC_296', 'UBC_31', 'UBC_322', 'UBC_337', 'UBC_338', 'UBC_341', 'UBC_342', 'UBC_345', 'UBC_354', 'UBC_373', 'UBC_377', 'UBC_386', 'UBC_391', 'UBC_396', 'UBC_415', 'UBC_482', 'UBC_51', 'UBC_521', 'UBC_531', 'UBC_532', 'UBC_534', 'UBC_535', 'UBC_536', 'UBC_541', 'UBC_542', 'UBC_548', 'UBC_550', 'UBC_552', 'UBC_559', 'UBC_562', 'UBC_582', 'UBC_588', 'UBC_63', 'UBC_668', 'UFMG_22', 'UFMG_3', 'UFMG_53', 'UPK_150', 'UPK_166', 'UPK_169', 'UPK_194', 'UPK_220', 'UPK_23', 'UPK_265', 'UPK_28', 'UPK_38', 'UPK_385', 'UPK_398', 'UPK_422', 'UPK_445', 'UPK_457', 'UPK_526', 'UPK_540', 'UPK_604', 'UPK_62', 'UPK_621', 'vdBergh_130', 'vdBergh_80', 'vdBergh_85', 'vdBergh_92']
dias2021 = Table.read("dias2021.tsv", format="ascii.ecsv")
maskplx = dias2021['Plx'] > 0.3
maskage = dias2021['logage'] < 7.7
# workclusters = []
# for clustername in dias2021[maskplx & maskage][:]['Cluster']:
# if clustername not in ['ASCC_79','BH_164','BH_23','Collinder_135','Collinder_140','Gulliver_9','IC_2391','IC_2602','Mamajek_1','Platais_8','UPK_535','UPK_606','UPK_640','Berkeley_59','COIN-Gaia_37','Ivanov_4','LP_1937','Sigma_Ori','UBC_632']:
# workclusters.append(clustername)
def read_yaml_file(file_path):
'''
Read the configuration file for the rest of the code.
This contains the various parameters for the code to run.
'''
with open(file_path, 'r') as yaml_file:
config = yaml.safe_load(yaml_file)
return config
config = read_yaml_file('config2.yaml')
class ClusterDias:
def __init__(self, name:str) -> None:
#download the catalog if not already in the cwds
if os.path.exists('./dias2021.tsv'):
dias2021 = Table.read('dias2021.tsv', format='ascii.ecsv')
else:
Vizier.ROW_LIMIT = -1
dias2021 = Vizier.get_catalogs(catalog="J/MNRAS/504/356/table12")[0]
mask_logage = dias2021['logage'] < 7.7
mask_plx = dias2021['Plx'] > 0.3
dias2021 = dias2021[mask_logage & mask_plx]
#select the row from Dias catalog
cluster_row = dias2021[dias2021['Cluster'] == name][0]
#cluster parameters from the row
self.name = name
self.all = cluster_row
self.r50 = cluster_row['r50']*u.deg
self.N = cluster_row['N']
self.skycoord = SkyCoord(ra=cluster_row['RA_ICRS']*u.deg,
dec=cluster_row['DE_ICRS']*u.deg,
distance=cluster_row['Dist']*u.pc,
pm_ra_cosdec=cluster_row['pmRA']*u.mas/u.yr,
pm_dec=cluster_row['pmDE']*u.mas/u.yr,
obstime=(Time('J2000')+1*u.Myr))
self.ra = self.skycoord.ra
self.dec = self.skycoord.dec
self.distance,self.e_distance = self.skycoord.distance,cluster_row['e_Dist']*u.pc
self.pm_ra_cosdec, self.e_pm_ra_cosdec = self.skycoord.pm_ra_cosdec,cluster_row['e_pmRA']*u.mas/u.yr
self.pm_dec, self.e_pm_dec = self.skycoord.pm_dec, cluster_row['e_pmDE']*u.mas/u.yr
self.Av, self.e_Av = round(cluster_row['Av'], 2), round(cluster_row['e_Av'], 2)
self.logage, self.e_logage = round(cluster_row['logage'], 2), round(cluster_row['e_logage'], 2)
self.FeH, self.e_FeH = round(cluster_row['__Fe_H_'], 2), round(cluster_row['e__Fe_H_'], 2)
self.RV, self.e_RV = cluster_row['RV'],cluster_row['e_RV']
self.NRV = cluster_row['NRV']
self.mymembers = self.members()
def members(self) -> None:
members = (Table.read(f'./Clusters_Dias/{self.name}.dat', format='ascii.tab'))[2:] #first two rows removed
mask_BPRP_exists = members['BP-RP'] != " --- "
members = members[mask_BPRP_exists]
members['Source'] = members['Source'].astype(np.int64)
members['Pmemb'] = members['Pmemb'].astype(float)
members['Plx'] = members['Plx'].astype(float)*u.mas
members['e_Plx'] = members['e_Plx'].astype(float)*u.mas
members['RAdeg'] = members['RAdeg'].astype(float)*u.deg
members['DEdeg'] = members['DEdeg'].astype(float)*u.deg
members['pmRA'] = members['pmRA'].astype(float)*u.mas/u.yr
members['pmDE'] = members['pmDE'].astype(float)*u.mas/u.yr
members['e_pmRA'] = members['e_pmRA'].astype(float)*u.mas/u.yr
members['e_pmDE'] = members['e_pmDE'].astype(float)*u.mas/u.yr
members['Gmag'] = members['Gmag'].astype(float)*u.mag
members['e_Gmag'] = members['e_Gmag'].astype(float)*u.mag
members['BPmag'] = members['BPmag'].astype(float)*u.mag
members['e_BPmag'] = members['e_BPmag'].astype(float)*u.mag
members['RPmag'] = members['RPmag'].astype(float)*u.mag
members['e_RPmag'] = members['e_RPmag'].astype(float)*u.mag
members['BP-RP'] = members['BP-RP'].astype(float)*u.mag
members['e_BP-RP'] = members['e_BPmag']+members['e_RPmag']
members = members["RAdeg","DEdeg", "Source","Pmemb","Plx","e_Plx","pmRA","e_pmRA","pmDE","e_pmDE","Gmag","e_Gmag","BP-RP","e_BP-RP"]
return members
def get_full_catalog() -> Table:
dias2021 = Vizier.get_catalogs(catalog="J/MNRAS/504/356/table12")[0]
dias2021.write('dias2021.tsv',format='ascii.ecsv', overwrite=True)
return dias2021
def theoretical_isochrone(self, params=None, returnparams=False, parsec_version=2):
# self.members()
params = params or {}
Av = float(params.get('Av', None)) if params.get('Av') is not None else self.Av
logage = float(params.get('logage', None)) if params.get('logage') is not None else self.logage
FeH = float(params.get('FeH', None)) if params.get('FeH') is not None else self.FeH
Av, logage, FeH = round(Av,2), round(logage,2), round(FeH,2)
theo_iso_path = f"./Clusters/{self.name}/{self.name}_compare_data_out_Av{str(Av)}_logage{str(logage)}_FeH{str(FeH)}.isochrone{parsec_version}"
# print("this", Av, logage, FeH)
if os.path.exists(theo_iso_path):
theo_iso = Table.read(theo_iso_path, format="ascii")
theo_iso["Gmag0"] = theo_iso["Gmag"] #saving the absolute magnitude of the stars
theo_iso['Gmag'] = theo_iso['Gmag'] + 5 * np.log10(self.distance.value) - 5
theo_iso['G_BP'] = theo_iso["G_BP"]+ 5 * np.log10(self.distance.value) - 5
theo_iso['G_RP'] = theo_iso["G_RP"]+ 5 * np.log10(self.distance.value) - 5
else:
theo_iso = get_theoretical_isochrone(Av=Av, logage=logage, FeH=FeH, parsec_version=parsec_version)
theo_iso["Gmag0"] = theo_iso["Gmag"] #saving the absolute magnitude of the stars
if parsec_version==1.2:
theo_iso['Teff0'] = 10**theo_iso['logTe']
theo_iso = theo_iso["Mass", "Teff0", "BP-RP", "Gmag","Gmag0", "G_BP", "G_RP", "logg", "logAge", "logL", "logTe", "Mini"]
theo_iso.write(theo_iso_path, format="ascii", overwrite=True)
#adjust absolute magnitudes to apparent magnitudes using the distance modulus after writing so that this cahnge is not stored in the isochrones written.
theo_iso['Gmag'] = theo_iso['Gmag'] + 5 * np.log10(self.distance.value) - 5
theo_iso['G_BP'] = theo_iso["G_BP"]+ 5 * np.log10(self.distance.value) - 5
theo_iso['G_RP'] = theo_iso["G_RP"]+ 5 * np.log10(self.distance.value) - 5
if returnparams:
return theo_iso, (Av, logage, FeH)
else:
return theo_iso
class ClusterCG:
def __init__(self, name:str) -> None:
self.name = name
#download the catalog if not already in the cwds
if os.path.exists('./CG2020.tsv'):
CG2020 = Table.read('CG2020.tsv', format='ascii.ecsv')
else:
Vizier.ROW_LIMIT = -1
CG2020 = Vizier.get_catalogs(catalog="J/A+A/633/A99/table1")[0]
cluster_row = CG2020[CG2020['Cluster'] == name][0]
self.r50 = cluster_row['r50']*u.deg
def get_full_catalog() -> Table:
CG2020 = Vizier.get_catalogs(catalog="J/A+A/633/A99/table1")[0]
CG2020.write('CG2020.tsv',format='ascii.ecsv')
return CG2020
class Cluster:
def __init__(self, name:str) -> None:
if not os.path.exists(f'Clusters/{name}'):
os.mkdir(f'Clusters/{name}')
clusterDias = ClusterDias(name=name)
try:
clusterCG = ClusterCG(name=name)
self.r50 = clusterCG.r50
except:
self.r50 = clusterDias.r50
self.name = name
self.ra = clusterDias.skycoord.ra
self.dec = clusterDias.skycoord.dec
self.distance = clusterDias.skycoord.distance #don't delete, need for calculating and searching stars in the region
self.rPhy = np.tan(self.r50) * self.distance
self.search_arcmin = search_arcmin(self.distance, self.r50)
# self.r50_phy = np.tan(self.r50) * self.distance #to be changed DR3
suro2024 = Table.read('suro2024.tsv', format='ascii.ecsv')
cluster_row = suro2024[suro2024['Cluster'] == name][0]
self.skycoord = SkyCoord(ra=cluster_row['RA_ICRS']*u.deg,
dec=cluster_row['DE_ICRS']*u.deg,
distance=cluster_row['Dist']*u.pc,
pm_ra_cosdec=cluster_row['pmRA']*u.mas/u.yr,
pm_dec=cluster_row['pmDE']*u.mas/u.yr,
obstime=(Time('J2000')+1*u.Myr))
self.all = cluster_row
self.distance,self.e_distance = cluster_row['Dist']*u.pc,cluster_row['e_Dist']*u.pc
self.pm_ra_cosdec, self.e_pm_ra_cosdec = cluster_row['pmRA']*u.mas/u.yr,cluster_row['e_pmRA']*u.mas/u.yr
self.pm_dec, self.e_pm_dec = cluster_row['pmDE']*u.mas/u.yr, cluster_row['e_pmDE']*u.mas/u.yr
self.Av, self.e_Av = round(cluster_row['Av'], 2), round(cluster_row['e_Av'], 2)
self.logage, self.e_logage = round(cluster_row['logage'], 2), round(cluster_row['e_logage'], 2)
self.FeH, self.e_FeH = round(cluster_row['__Fe_H_'], 2), round(cluster_row['e__Fe_H_'], 2)
self.RV, self.e_RV = cluster_row['RV'],cluster_row['e_RV']
self.NRV = cluster_row['NRV']
if os.path.exists(f"Clusters/{self.name}/{self.name}_members.tsv"):
self.mymembers = Table.read(f"Clusters/{self.name}/{self.name}_members.tsv", format="ascii.ecsv")
self.distance = self.mymembers['rgeo'].mean()*u.pc
self.N = len(self.mymembers)
else:
self.mymembers = self.members()
self.distance = self.mymembers['rgeo'].mean()*u.pc
self.N = len(self.mymembers)
self.kinematic_cluster = find_cluster(self.stars_in_region())
self.all_dias_members = Table.read(f"Clusters/{self.name}/{self.name}_all_dias_members.tsv", format="ascii.ecsv")
#functions
# self.members = (Table.read(f'./Clusters_Dias/{self.name}.dat', format='ascii.tab'))[2:]
# self.members_list = list(self.members['Source'].astype(np.int64))
def members(self, pmemb:float = config['Cluster']['pmemb'], plxquality:float = config['Cluster']['plxquality'], add_members:List = []):
sr = self.stars_in_region()
diasmembers = (ClusterDias(name=self.name).members())['Source','Pmemb']
#add the add_members in this with Pmemb=1
configmembers = config.get('added_members',{}).get(self.name)
print(f"{configmembers} found from config file") if configmembers is not None else None
add_members = add_members + configmembers if configmembers is not None else []
#add_members += configmembers if configmembers is not None else []
#print(add_members)
for mem_source in add_members:
#print(1)
diasmembers.add_row([mem_source,1])
#display(diasmembers)
members = join(sr, diasmembers, keys='Source', join_type='inner') #select the ones that dias says is a member
members.write(f"Clusters/{self.name}/{self.name}_all_dias_members.tsv", format="ascii.ecsv", overwrite=True)
print(f'{len(members)} out of {len(diasmembers)-len(add_members)} dias members found in search region')
mask_pmemb = members['Pmemb'] >= pmemb
mask_plxquality = members['Plx']/members['e_Plx'] >= plxquality
members = members[mask_pmemb & mask_plxquality]
members.sort("Gmag")
members.write(f"Clusters/{self.name}/{self.name}_members.tsv", format="ascii.ecsv", overwrite=True)
#update kinematic parameters
self.changeParam(("N", len(members)))
self.changeParam(("Plx", members['Plx'].mean()))
self.changeParam(("e_Plx", members['Plx'].std()))
self.changeParam(("Dist", members['rgeo'].mean()))
self.changeParam(("e_Dist", members['rgeo'].std()))
self.changeParam(("pmRA", members['pmRA'].mean()))
self.changeParam(("e_pmRA", members['pmRA'].std()))
self.changeParam(("pmDE", members['pmDE'].mean()))
self.changeParam(("e_pmDE", members['pmRA'].std()))
# finding RV from the RV mean of the cluster found
# kinematic_cluster = self.kinematic_cluster
kinematic_cluster = self.mymembers
# if (np.count_nonzero(~(kinematic_cluster['RV'].mask)))>5:
# self.changeParam(("RV", np.mean(kinematic_cluster['RV'])))
# self.changeParam(("e_RV", np.sqrt(np.sum(kinematic_cluster['e_RV'])**2/((np.count_nonzero(~(kinematic_cluster['RV'].mask))))**2)))
# self.changeParam(("NRV", np.count_nonzero(~(kinematic_cluster['RV'].mask))))
# return members
if (np.count_nonzero(~(kinematic_cluster['RV'].mask)))>1:
RV = unumpy.uarray(kinematic_cluster['RV'].value, kinematic_cluster['e_RV'].value)
self.changeParam(("RV", RV.mean().nominal_value))
self.changeParam(("e_RV", RV.mean().std_dev))
self.changeParam(("NRV", np.count_nonzero(~(kinematic_cluster['RV'].mask))))
return members
# elif (np.count_nonzero(~(members['RV'].mask)))>1:
# # self.restoreParam("RV")
# # self.restoreParam("e_RV")
# # self.restoreParam("NRV")
# self.changeParam(("RV", members['RV'].mean()))
# self.changeParam(("e_RV", np.sqrt(np.sum(members['e_RV'])**2/(np.count_nonzero(~(members['RV'].mask)))**2)))
# self.changeParam(("NRV", (np.count_nonzero(~(members['RV'].mask)))))
else:
self.restoreParam("RV")
self.restoreParam("e_RV")
self.restoreParam("NRV")
return members
def Star(self,source, get_similar=False, SkyCoord=True,returnName=False):
warnings.filterwarnings("ignore", category=UserWarning)
star = self.stars_in_region(source)
if len(star)==0:
print("Star not in the region")
return None
star = estimate_temperature(star, self.theoretical_isochrone(params={'Av': self.Av,
'logage': self.logage,
'FeH': self.FeH}))
if SkyCoord:
star = star[
"RA_ICRS_1", "DE_ICRS_1", "rgeo", "b_rgeo", "B_rgeo", "Teff", "Temp. Est","v_pec","e_v_pec","v_pec3d", "HIP", "TYC2", "Source", "Plx", "e_Plx", "pmRA", "pmDE", "e_pmRA", "e_pmDE", "RUWE",
"Gmag", "BP-RP", "BPmag", "RPmag", "e_Gmag", "e_BPmag", "e_RPmag", "e_BP-RP", "SkyCoord",
"rmRA","e_rmRA", "rmDE", "e_rmDE", "logg", "RV", "e_RV","rRV", "e_rRV", "FG", "e_FG", "FBP", "e_FBP", "FRP", "e_FRP", "RAVE5", "RAVE6"
]
else:
star = star[
"RA_ICRS_1", "DE_ICRS_1", "rgeo", "b_rgeo", "B_rgeo", "Teff", "Temp. Est","v_pec","e_v_pec","v_pec3d", "HIP", "TYC2", "Source", "Plx", "e_Plx", "pmRA", "pmDE", "e_pmRA", "e_pmDE", "RUWE",
"Gmag", "BP-RP", "BPmag", "RPmag", "e_Gmag", "e_BPmag", "e_RPmag", "e_BP-RP",
"rmRA","e_rmRA", "rmDE", "e_rmDE", "logg", "RV", "e_RV","rRV", "e_rRV", "FG", "e_FG", "FBP", "e_FBP", "FRP", "e_FRP", "RAVE5", "RAVE6"
]
object = f"Gaia DR3 {source}"
try:
bestname = Simbad.query_object(object)['MAIN_ID'][0]
except:
bestname = object
# print(bestname)
if returnName:
return bestname
star.add_column([bestname],name='Name', index=0)
if get_similar:
theoretical_isochrone = self.theoretical_isochrone()
bprptheo = theoretical_isochrone['BP-RP']
gmagtheo = theoretical_isochrone['Gmag']
differences_bprp = abs(bprptheo - star['BP-RP'])
differences_gmag = abs(gmagtheo - star['Gmag'])
# differences = differences_bprp**2+differences_gmag**2 #method 1
differences = differences_bprp #method 2 main star
closest_star_index = np.argmin(differences)
closest_star = theoretical_isochrone[closest_star_index]
display(closest_star)
return star
def stars_in_region(self, star=None):
stars_in_region_path = f'Clusters/{self.name}/{self.name}_stars_in_region.tsv'
def pm(pmRA,pmDE):
µ = (pmRA**2+pmDE**2)**0.5
return µ
def v(µ,dist):
#dist should be in pc
v = (µ*4.74*dist/1000)
return v
if os.path.exists(stars_in_region_path):
stars_in_region = Table.read(stars_in_region_path, format='ascii.ecsv')
rgeo = stars_in_region['rgeo'].value
b_rgeo = stars_in_region['b_rgeo'].value
B_rgeo = stars_in_region['B_rgeo'].value
rmRA = unumpy.uarray(stars_in_region['rmRA'].value,stars_in_region['e_rmRA'].value)
rmDE = unumpy.uarray(stars_in_region['rmDE'].value,stars_in_region['e_rmDE'].value)
rm = pm(rmRA,rmDE)
v_trans = unumpy.nominal_values(v(rm,rgeo))*u.km/u.s
v_trans_std = unumpy.std_devs(v(rm,rgeo))*u.km/u.s
v_trans_upper = unumpy.nominal_values(v(rm,B_rgeo))*u.km/u.s
v_trans_lower = unumpy.nominal_values(v(rm,b_rgeo))*u.km/u.s
e_v_trans = abs((v_trans_lower-v_trans_upper)/2)
stars_in_region['v_pec'] = v_trans
stars_in_region['v_trans_upper'] = v_trans_upper
stars_in_region['v_trans_lower'] = v_trans_lower
stars_in_region['e_v_pec'] = e_v_trans + v_trans_std
stars_in_region.write(stars_in_region_path, format='ascii.ecsv', overwrite=True)
# stars_in_region['rmRA'] = stars_in_region['pmRA']-self.pm_ra_cosdec
# stars_in_region['rmDE'] = stars_in_region['pmDE']-self.pm_dec
# stars_in_region['e_rmRA'] = stars_in_region['e_pmRA']+self.e_pm_ra_cosdec
# stars_in_region['e_rmDE'] = stars_in_region['e_pmDE']+self.e_pm_dec
# stars_in_region['rRV'] = stars_in_region['RV']-self.RV
# stars_in_region['e_rRV'] = stars_in_region['e_RV']+self.e_RV
# #include members with high rRV as fast stars
# stars_in_region['v_pec'] = 4.74*stars_in_region['rgeo'].value/1000*np.sqrt(((stars_in_region['rmRA'].value)**2+(stars_in_region['rmDE'].value)**2))*u.km/u.s
# stars_in_region['v_pec3d'] = np.sqrt(stars_in_region['v_pec']**2+stars_in_region['rRV']**2)
# #check
# stars_in_region['e_vpec'] = 4.74 * stars_in_region['rgeo'].value/1000 * np.sqrt(((stars_in_region['rmRA'].value * stars_in_region['e_rmRA'].value)**2 + (stars_in_region['rmDE'].value * stars_in_region['e_rmDE'].value)**2)) * u.km/u.s
# stars_in_region['e_vpec3d'] = np.sqrt((stars_in_region['v_pec'] / stars_in_region['v_pec3d'] * stars_in_region['e_vpec'])**2 + (stars_in_region['rRV'] / stars_in_region['v_pec3d'] * stars_in_region['e_rRV'])**2)
# stars_in_region.write(stars_in_region_path, format='ascii.ecsv', overwrite=True)
else:
print("downloading sir")
stars_in_region = self.get_stars_in_region()
stars_in_region['rmRA'] = stars_in_region['pmRA']-self.pm_ra_cosdec
stars_in_region['rmDE'] = stars_in_region['pmDE']-self.pm_dec
stars_in_region['e_rmRA'] = stars_in_region['e_pmRA']+self.e_pm_ra_cosdec
stars_in_region['e_rmDE'] = stars_in_region['e_pmDE']+self.e_pm_dec
stars_in_region['rRV'] = stars_in_region['RV']-self.RV
stars_in_region['e_rRV'] = stars_in_region['e_RV']+self.e_RV
#include members with high rRV as fast stars
stars_in_region['v_pec'] = 4.74*((stars_in_region['rgeo'].value)/1000)*np.sqrt(
(stars_in_region['rmRA'].value)**2
+(stars_in_region['rmDE'].value)**2
)*u.km/u.s
stars_in_region['v_pec3d'] = np.sqrt(stars_in_region['v_pec']**2+stars_in_region['rRV']**2)
#check
stars_in_region['e_v_pec'] = 4.74 * stars_in_region['rgeo'].value/1000 * np.sqrt(((stars_in_region['rmRA'].value * stars_in_region['e_rmRA'].value)**2 + (stars_in_region['rmDE'].value * stars_in_region['e_rmDE'].value)**2)) * u.km/u.s
stars_in_region['e_v_pec3d'] = np.sqrt((stars_in_region['v_pec'] / stars_in_region['v_pec3d'] * stars_in_region['e_v_pec'])**2 + (stars_in_region['rRV'] / stars_in_region['v_pec3d'] * stars_in_region['e_rRV'])**2)
stars_in_region.write(stars_in_region_path, format='ascii.ecsv')
stars_in_region = Table.read(stars_in_region_path, format='ascii.ecsv')
if star is None:
return stars_in_region
else:
return stars_in_region[stars_in_region['Source']==star]
def fast_stars_in_region(self):
sir = self.stars_in_region()
mask_fast2d = sir['v_pec'] > 17.6*u.km/u.s
mask_vpec3ddosentexist = sir['v_pec3d'].mask
mask_fast3d = sir['v_pec3d'] > 25*u.km/u.s
return sir[(mask_fast2d & mask_vpec3ddosentexist) | mask_fast3d]
def fs4giesler(self,outlocation=None):
table = self.fast_stars_in_region()
g = Table()
g['TypeInput'] = np.ones_like(table['e_Plx'].value).astype(int)
g['RA'] = table['SkyCoord'].ra.to_string(unit='hourangle', sep=' ', precision=3, pad=True)
g['DE'] = table['SkyCoord'].dec.to_string(unit='degree', sep=' ', precision=3, pad=True)
g['Plx'] = table['rgeo'].to(u.mas, u.parallax())
g['e_Plx'] = table['e_Plx']
g['RV'] = np.zeros_like(table['e_Plx'].value).astype(int)
# g['RV'] = table['RV']
g['e_RV'] = np.zeros_like(table['e_Plx'].value).astype(int)
# g['e_RV'] = table['e_RV']
g['RVdist'] = np.zeros_like(table['e_Plx'].value).astype(int)
g['pmRA'] = table['pmRA']
g['e_pmRA'] = table['e_pmRA']
g['pmDE'] = table['pmDE']
g['e_pmDE'] = table['e_pmDE']
g['Source'] = table['Source'].astype(str)
# g['RV'] = g['RV'].filled(0) #fill masked values with 0
# g['e_RV'] = g['e_RV'].filled(0) #fill masked values with 0
#this is the first row for the cluster's motion
new_row = [1,
self.ra.to_string(unit='hourangle', sep=' ', precision=3, pad=True), #ra
self.dec.to_string(unit='degree', sep=' ', precision=3, pad=True), #dec
((self.all['Dist']*u.pc).to(u.mas, u.parallax())).value, #plx
self.all['e_Plx'], #e_plx
# self.all['RV'], #RV
0, #RV
# self.all['e_RV'], #e_RV
0, #e_RV
0, #RV_distribution
self.all['pmRA'], #pmRA
self.all['e_pmRA'], #e_pmRA
self.all['pmDE'], #pmDE
self.all['e_pmDE'], #e_pmDE
self.name #ID
]
new_table = Table(names=g.colnames, dtype=[col.dtype for col in g.columns.values()])
new_table.add_row(new_row)
g = vstack([new_table,g])
if outlocation=='local':
g.write(f'Clusters/{self.name}/{self.name}_fs4giesler.tsv', format='csv', delimiter='\t', overwrite=True)
elif outlocation=='remote':
g.write(f"/home/surodeep/suro_aiu/traceback/cluster_runaway/{self.name}/{self.name}_fs4giesler.tsv", format='csv', delimiter='\t', overwrite=True)
return g
def fs4giesler3d(self,outlocation=None):
table = self.fast_stars_in_region()
mask_vpec3dexists = ~table['v_pec3d'].mask
table = table[mask_vpec3dexists]
try:
for star in config['observed_stars'][self.name]:
table.add_row(self.stars_in_region(star)[0])
except:
pass
g = Table()
g['TypeInput'] = np.ones_like(table['e_Plx'].value).astype(int)
g['RA'] = table['SkyCoord'].ra.to_string(unit='hourangle', sep=' ', precision=3, pad=True)
g['DE'] = table['SkyCoord'].dec.to_string(unit='degree', sep=' ', precision=3, pad=True)
g['Plx'] = table['rgeo'].to(u.mas, u.parallax())
g['e_Plx'] = table['e_Plx']
# g['RV'] = np.zeros_like(table['e_Plx'].value).astype(int)
g['RV'] = table['RV']
# g['e_RV'] = np.zeros_like(table['e_Plx'].value).astype(int)
g['e_RV'] = table['e_RV']
g['RVdist'] = np.zeros_like(table['e_Plx'].value).astype(int)
g['pmRA'] = table['pmRA']
g['e_pmRA'] = table['e_pmRA']
g['pmDE'] = table['pmDE']
g['e_pmDE'] = table['e_pmDE']
g['Source'] = table['Source'].astype(str)
#this is the first row for the cluster's motion
new_row = [1,
self.ra.to_string(unit='hourangle', sep=' ', precision=3, pad=True), #ra
self.dec.to_string(unit='degree', sep=' ', precision=3, pad=True), #dec
((self.all['Dist']*u.pc).to(u.mas, u.parallax())).value, #plx
self.all['e_Plx'], #e_plx
self.all['RV'], #RV
# 0, #RV
self.all['e_RV'], #e_RV
# 0, #e_RV
0, #RV_distribution
self.all['pmRA'], #pmRA
self.all['e_pmRA'], #e_pmRA
self.all['pmDE'], #pmDE
self.all['e_pmDE'], #e_pmDE
self.name #ID
]
new_table = Table(names=g.colnames, dtype=[col.dtype for col in g.columns.values()])
new_table.add_row(new_row)
g = vstack([new_table,g])
if outlocation=='local':
g.write(f'Clusters/{self.name}/{self.name}_fs4giesler.tsv', format='csv', delimiter='\t', overwrite=True)
elif outlocation=='remote':
g.write(f"/home/surodeep/suro_aiu/traceback/cluster_runaway3d/{self.name}/{self.name}_fs4giesler.tsv", format='csv', delimiter='\t', overwrite=True)
return g
def get_stars_in_region(self) -> Table:
c = ClusterDias(self.name).skycoord
t1 = searchDR3(c,self.search_arcmin)
t2 = searchDR3_dist(c,self.search_arcmin)
t3 = merge_gaia_tables(t1,t2)
t3.sort('Gmag')
return t3
def changeParam(self,change: tuple):
param,new_value = change
cluster_list = Table.read('dias2021.tsv', format='ascii.ecsv')
cluster_list_mod = Table.read('suro2024.tsv', format='ascii.ecsv')
_old_value = cluster_list[cluster_list['Cluster'] == self.name][0][param]
cluster_list_mod[param][cluster_list_mod['Cluster'] == self.name] = new_value
cluster_list_mod.write('suro2024.tsv', format='ascii.ecsv', overwrite=True)
warnings.simplefilter('ignore', FutureWarning)
print(f'Changed {param:10} {_old_value:.2f} --> {new_value:.2f}')
def restoreParam(self, param: str):
# Read the original and modified tables
cluster_list_original = Table.read('dias2021.tsv', format='ascii.ecsv')
cluster_list_modified = Table.read('suro2024.tsv', format='ascii.ecsv')
# Get the name of the cluster
cluster_name = self.name
if param == 'all':
# Iterate over all columns in the original table
for column in cluster_list_original.colnames:
# Get the original value for the current column
original_value = cluster_list_original[cluster_list_original['Cluster'] == cluster_name][0][column]
# Get the current value for the current column in the modified table (for logging)
current_value = cluster_list_modified[cluster_list_modified['Cluster'] == cluster_name][0][column]
# Restore the original value in the modified table
cluster_list_modified[column][cluster_list_modified['Cluster'] == cluster_name] = original_value
if current_value != original_value:
print(f'Restored {column}: current {current_value} --> {original_value}')
else:
# Handle the case for a single parameter as before
original_value = cluster_list_original[cluster_list_original['Cluster'] == cluster_name][0][param]
current_value = cluster_list_modified[cluster_list_modified['Cluster'] == cluster_name][0][param]
cluster_list_modified[param][cluster_list_modified['Cluster'] == cluster_name] = original_value
print(f'Restored {param}: current {current_value} --> {original_value}')
# Save the modified table
cluster_list_modified.write('suro2024.tsv', format='ascii.ecsv', overwrite=True)
def prepare_trace(self):
mainfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway/{self.name}"
runawayfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway/{self.name}/runaways"
trajfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway/{self.name}/runaway_trajectories"
os.mkdir(mainfolder) if not os.path.exists(mainfolder) else None
os.mkdir(runawayfolder) if not os.path.exists(runawayfolder) else None
os.mkdir(trajfolder) if not os.path.exists(trajfolder) else None
def update_config_template(config_file_path, output_file_path, **kwargs):
# Read the template config file
with open(config_file_path, 'r') as file:
config_content = file.read()
# Replace placeholders with actual values
for key, value in kwargs.items():
placeholder = f"val_{key}"
config_content = config_content.replace(placeholder, str(value))
# Write the updated content to the output file
with open(output_file_path, 'w') as file:
file.write(config_content)
fs4giesler = self.fs4giesler(outlocation='remote')
lastline = len(fs4giesler)+1
# Example usage:
#starno=5
#template config
config_file_path = "/home/surodeep/suro_aiu/traceback/cluster_runaway/template_config_trace.conf"
#output the modified config
output_file_path = f"/home/surodeep/suro_aiu/traceback/cluster_runaway/{self.name}/{self.name}_trace.conf"
params = {
"Threads": 0,
"Orbits": 1000,
"Steps": 1000,
"Width": 100,
"StepSize": -100,
"TimeLimit": 100,
"Criterion": "Hoogerwerf",
"Limit": round(self.rPhy.value,3),
#cluster line
"Star1": f'"/astro/surodeep/traceback/cluster_runaway/{self.name}/{self.name}_fs4giesler.tsv#2"',
#rest of the stars
"Star2": f'"/astro/surodeep/traceback/cluster_runaway/{self.name}/{self.name}_fs4giesler.tsv#3..{lastline}"',
"Assoc": 0,
"OutFile": f'"/astro/surodeep/traceback/cluster_runaway/{self.name}/runaways/run"'
}
update_config_template(config_file_path, output_file_path, **params)
print(f'./traceback ../../cluster_runaway/{self.name}/{self.name}_trace.conf')
def prepare_trace3d(self):
mainfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway3d/{self.name}"
runawayfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway3d/{self.name}/runaways"
trajfolder = f"/home/surodeep/suro_aiu/traceback/cluster_runaway3d/{self.name}/runaway_trajectories"
os.mkdir(mainfolder) if not os.path.exists(mainfolder) else None
os.mkdir(runawayfolder) if not os.path.exists(runawayfolder) else None
os.mkdir(trajfolder) if not os.path.exists(trajfolder) else None
def update_config_template(config_file_path, output_file_path, **kwargs):
# Read the template config file
with open(config_file_path, 'r') as file:
config_content = file.read()
# Replace placeholders with actual values
for key, value in kwargs.items():
placeholder = f"val_{key}"
config_content = config_content.replace(placeholder, str(value))
# Write the updated content to the output file
with open(output_file_path, 'w') as file:
file.write(config_content)
fs4giesler = self.fs4giesler3d(outlocation='remote')
lastline = len(fs4giesler)+1
# Example usage:
#starno=5
#template config
config_file_path = "/home/surodeep/suro_aiu/traceback/cluster_runaway3d/template_config_trace.conf"
#output the modified config
output_file_path = f"/home/surodeep/suro_aiu/traceback/cluster_runaway3d/{self.name}/{self.name}_trace.conf"
params = {
"Threads": 0,
"Orbits": 1000,
"Steps": 1000,
"Width": 100,
"StepSize": -100,
"TimeLimit": 100,
"Criterion": "Hoogerwerf",
"Limit": round(self.rPhy.value,3),
#cluster line
"Star1": f'"/astro/surodeep/traceback/cluster_runaway3d/{self.name}/{self.name}_fs4giesler.tsv#2"',
#rest of the stars
"Star2": f'"/astro/surodeep/traceback/cluster_runaway3d/{self.name}/{self.name}_fs4giesler.tsv#3..{lastline}"',
"Assoc": 0,
"OutFile": f'"/astro/surodeep/traceback/cluster_runaway3d/{self.name}/runaways/run"'
}
update_config_template(config_file_path, output_file_path, **params)
print(f'./traceback ../../cluster_runaway3d/{self.name}/{self.name}_trace.conf')
def runaways_all(self):
#runaways from giesler traceback
outputs = os.listdir(f"{config['runaways_path']}{self.name}/runaways/")
# print("getting from",config['runaways_path'] )
linenos = []
for output in outputs:
#print(output)
if 'run' in output:
linenos.append(int(output.split("+")[1].replace(".out","")))
linenos.sort()
# print(linenos)
fs4giesler = Table.read(f"{config['runaways_path']}{self.name}/{self.name}_fs4giesler.tsv", format='ascii.tab')
fs4 = fs4giesler[np.array(linenos)-2]
fs4['Source'] = fs4['Source'].astype(np.int64)
fs4['RV'] = fs4['RV'].astype(np.float64)
fs4['e_RV'] = fs4['e_RV'].astype(np.float64)
sir = self.stars_in_region()
runaways_all = sir[[source in set(fs4['Source']) for source in sir['Source']]]
# Create a mapping from 'Source' to indices in gr
source_to_index = {source: idx for idx, source in enumerate(fs4['Source'])}
# Replace the RV and e_RV values in the filtered_fs table with the values from the gr table
if "runaway3d" in config['runaways_path']:
for row in runaways_all:
if row['Source'] in source_to_index:
idx = source_to_index[row['Source']]
row['RV'] = fs4['RV'][idx] # Assigning with units
row['e_RV'] = fs4['e_RV'][idx] # Assigning with units
return runaways_all
def runaways(self,params=None,temp_threshold=10000):
params = params or {}
runaways = estimate_temperature(self.runaways_all(), self.theoretical_isochrone(params=params))
runaways = runaways[
"RA_ICRS_1", "DE_ICRS_1", "rgeo", "Teff", "Temp. Est","v_pec","e_v_pec","v_pec3d","e_v_pec3d", "HIP", "TYC2", "Source", "Plx", "e_Plx", "pmRA", "pmDE", "e_pmRA", "e_pmDE", "RUWE",
"Gmag", "BP-RP", "BPmag", "RPmag", "b_rgeo", "B_rgeo", "e_Gmag", "e_BPmag", "e_RPmag", "e_BP-RP", "SkyCoord",
"rmRA","e_rmRA", "rmDE", "e_rmDE", "logg", "RV", "e_RV","rRV", "e_rRV", "FG", "e_FG", "FBP", "e_FBP", "FRP", "e_FRP", "RAVE5", "RAVE6"
]
# runaways['v_pec3d'] = np.sqrt(runaways['v_pec']**2+runaways['RV']**2)
mask_fast2d = runaways['v_pec'] > 17.6*u.km/u.s
mask_vpec3ddosentexist = runaways['v_pec3d'].mask
mask_fast3d = runaways['v_pec3d'] > 25*u.km/u.s
runaways = runaways[(mask_fast2d & mask_vpec3ddosentexist) | mask_fast3d]
mask_temp = runaways['Temp. Est'] >= temp_threshold*u.K
runaways = runaways[mask_temp]
runaways.sort('Temp. Est', reverse=True)
simbad_names = []
for source in runaways['Source']:
simbad_names.append(self.Star(source, returnName=1))
runaways.add_column(simbad_names, name='Name', index=0)
return runaways
def theoretical_isochrone(self, params=None, returnparams=False, parsec_version=2):
# self.members()
params = params or {}
Av = float(params.get('Av', None)) if params.get('Av') is not None else self.Av
logage = float(params.get('logage', None)) if params.get('logage') is not None else self.logage
FeH = float(params.get('FeH', None)) if params.get('FeH') is not None else self.FeH
Av, logage, FeH = round(Av,2), round(logage,2), round(FeH,2)
theo_iso_path = f"./Clusters/{self.name}/{self.name}_compare_data_out_Av{str(Av)}_logage{str(logage)}_FeH{str(FeH)}.isochrone{parsec_version}"
# print("this", Av, logage, FeH)
if os.path.exists(theo_iso_path):
theo_iso = Table.read(theo_iso_path, format="ascii")
theo_iso["Gmag0"] = theo_iso["Gmag"] #saving the absolute magnitude of the stars
theo_iso['Gmag'] = theo_iso['Gmag'] + 5 * np.log10(self.distance.value) - 5
theo_iso['G_BP'] = theo_iso["G_BP"]+ 5 * np.log10(self.distance.value) - 5
theo_iso['G_RP'] = theo_iso["G_RP"]+ 5 * np.log10(self.distance.value) - 5
else:
theo_iso = get_theoretical_isochrone(Av=Av, logage=logage, FeH=FeH, parsec_version=parsec_version)
if parsec_version==1.2:
theo_iso['Teff0'] = 10**theo_iso['logTe']
theo_iso = theo_iso["Mass", "Teff0", "BP-RP", "Gmag", "G_BP", "G_RP", "logg", "logAge", "logL", "logTe", "Mini"]
theo_iso.write(theo_iso_path, format="ascii", overwrite=True)
#adjust absolute magnitudes to apparent magnitudes using the distance modulus after writing so that this cahnge is not stored in the isochrones written.
theo_iso["Gmag0"] = theo_iso["Gmag"] #saving the absolute magnitude of the stars
theo_iso['Gmag'] = theo_iso['Gmag'] + 5 * np.log10(self.distance.value) - 5
theo_iso['G_BP'] = theo_iso["G_BP"]+ 5 * np.log10(self.distance.value) - 5
theo_iso['G_RP'] = theo_iso["G_RP"]+ 5 * np.log10(self.distance.value) - 5
if returnparams:
return theo_iso, (Av, logage, FeH)
else:
return theo_iso
def plot_cluster(self, extra=5 , pixels=1000):
# Open the FITS file and extract the image and WCS
cluster_5pc_fits_path = f'./Clusters/{self.name}/{self.name}_extra{extra}pc.fits'
if not os.path.exists(cluster_5pc_fits_path):
get_search_region(self, extra=extra, pixels=pixels)
with fits.open(cluster_5pc_fits_path) as fits_file:
image = fits_file[0]
wcs = WCS(image.header)
fig, ax = plt.subplots(subplot_kw={'projection': wcs}, figsize=(15, 15))
ax.imshow(image.data, cmap='gray', alpha=0.7, interpolation='gaussian')
lon = ax.coords[0]
lat = ax.coords[1]
lon.set_axislabel('Right Ascension (hms)', minpad=0.4)
latlabel = lat.set_axislabel('Declination (deg)', minpad=0.5)
lon.tick_params(pad=15)
# Set the background color to black
# fig.patch.set_facecolor('black')
ax.set_facecolor('black')
# Set text colors to white
ax.title.set_color('white')
# ax.tick_params(axis='both', colors='black', length=10)
ax.tick_params(axis='none')
ax.grid(color='lightgrey', ls='dotted')
# Plot the cluster region
c = self.skycoord
#circle for the cluster r50
radius = (self.r50).to(u.arcmin)
region = CircleSkyRegion(c, radius)
region_pix = region.to_pixel(wcs)
region_pix.plot(ax=ax, color='orange',
lw=3,
ls='dotted',
label=f"Cluster (r50) = {radius.value:.1f}'"
)
#main members
members = self.mymembers
member_px, member_py = wcs.world_to_pixel_values(members['SkyCoord'].ra, members['SkyCoord'].dec)
ax.scatter(member_px, member_py,
label=f'{len(members)} Cluster members',
c='none', # This can be omitted since facecolors='none' does the job
lw=3,
s=300,
facecolors='none', # Makes the markers hollow
edgecolors='yellow', # Edge color of the markers
alpha=1)
#dias cluster
members = self.all_dias_members
member_px, member_py = wcs.world_to_pixel_values(members['SkyCoord'].ra, members['SkyCoord'].dec)
ax.scatter(member_px, member_py,
label=f'{len(members)} Dias members',
c='red', # This can be omitted since facecolors='none' does the job
s=200,
marker="x",
alpha=1)
# #kinematic cluster
# members = self.kinematic_cluster
# member_px, member_py = wcs.world_to_pixel_values(members['SkyCoord'].ra, members['SkyCoord'].dec)
# ax.scatter(member_px, member_py,
# label=f'{len(members)} kinematic members',
# c='none', # This can be omitted since facecolors='none' does the job
# lw=2,
# s=200,
# facecolors='none', # Makes the markers hollow
# edgecolors='cyan', # Edge color of the markers
# alpha=1)
scalebar_angle = ((((self.search_arcmin.value/4)//5)+1)*5)*u.arcmin
add_scalebar(ax, length=scalebar_angle,
label='',
pad=0.5,
borderpad=0.2,
color='yellow',
size_vertical=2,
fill_bar = True)
from astropy.wcs.utils import proj_plane_pixel_scales
if ax.wcs.is_celestial:
pix_scale = proj_plane_pixel_scales(ax.wcs)
sx = pix_scale[0]
sy = pix_scale[1]
degrees_per_pixel = np.sqrt(sx * sy)
scalebar = AnchoredSizeBar(
ax.transData,
size=0,
loc='lower right',
label=f"{scalebar_angle.value:.0f}'",
color='yellow',
pad=0.6,
borderpad=0.4,
size_vertical=0,
label_top=True,
frameon=False,
sep=30,
)
sep = ((scalebar_angle.value*np.pi)/(60*180))*self.distance.value*u.pc
scalebar2 = AnchoredSizeBar(
ax.transData,
size=0,
loc='lower right',
label=f'{sep:.2f}',
color='yellow',
pad=0.3,
borderpad=0.4,
size_vertical=0,
label_top=False,
frameon=False,
sep=30,
)
ax.add_artist(scalebar)
ax.add_artist(scalebar2)
legend = plt.legend()
legend.get_frame().set_alpha(0.2)
legend.set_draggable(True)
for text in legend.get_texts():
text.set_color("white")
# plt.tight_layout()
plt.show()
fig.canvas.manager.set_window_title(f'{self.name}_cluster')
return ax
def plot_traceback_clean(self, star_tables=[]):
warnings.simplefilter('ignore', ErfaWarning)
if len(star_tables) == 0:
star_tables.append(self.runaways())
# Open the FITS file and extract the image and WCS
cluster_10pc_fits_path = f'./Clusters/{self.name}/{self.name}_extra10pc.fits'
if not os.path.exists(cluster_10pc_fits_path):
get_search_region(self, pixels=800)
with fits.open(cluster_10pc_fits_path) as fits_file:
image = fits_file[0]
wcs = WCS(image.header)
fig, ax = plt.subplots(subplot_kw={'projection': wcs}, figsize=(15, 15))
ax.imshow(image.data, cmap='gray', alpha=0.7, interpolation='gaussian')
# ax.set_xlabel('Right Ascension (hms)', color="black")
# ax.set_ylabel('Declination (degrees)', color="black")
lon = ax.coords[0]
lat = ax.coords[1]
lon.set_axislabel('Right Ascension (hms)', minpad=0.4)
latlabel = lat.set_axislabel('Declination (deg)', minpad=0.3)
# latlabel.set_draggable(True)
lon.tick_params(pad=15)
# Set the background color to black
# fig.patch.set_facecolor('black')
ax.set_facecolor('black')
# Set text colors to white
ax.title.set_color('white')
# ax.tick_params(axis='both', colors='black', length=10)
ax.tick_params(axis='none')
ax.grid(color='lightgrey', ls='dotted')
# Plot the cluster region
c = self.skycoord
#circle for the cluster r50
radius = (self.r50).to(u.arcmin)
region = CircleSkyRegion(c, radius)
region_pix = region.to_pixel(wcs)
region_pix.plot(ax=ax, color='orange',
lw=3,
ls='dotted',
label=f"Cluster (r50) = {radius.value:.1f}'"
)
#circle for the search region
radius_search_arcmin = self.search_arcmin.to(u.arcmin)
region_search_arcmin = CircleSkyRegion(c, radius_search_arcmin)
region_pix_search_arcmin = region_search_arcmin.to_pixel(wcs)
region_pix_search_arcmin.plot(ax=ax, color='green',
lw=4,
ls='dotted',
label=f"Search region = {radius_search_arcmin.value:.1f}'"
)
def plot_traces(ax, allrun, alpha=0.5):
allrun_coord_now = SkyCoord(ra=allrun['RA_ICRS_1'],
dec=allrun['DE_ICRS_1'],
distance=allrun['rgeo'],
pm_ra_cosdec=allrun['rmRA'],
pm_dec=allrun['rmDE'],
obstime=Time('J2000')+500*u.kyr)
allrun_coord_earlier = allrun_coord_now.apply_space_motion(dt=-100*u.kyr)
# Calculate the pixel coordinates of the runaway stars
allrun_pixels_now = wcs.world_to_pixel(allrun_coord_now)
allrun_pixels_earlier = wcs.world_to_pixel(allrun_coord_earlier)
# Plot the current positions as scatter points
scatter_main = ax.scatter(allrun_pixels_now[0], allrun_pixels_now[1],
c=allrun['Temp. Est'], cmap='RdYlBu', edgecolor='red',linewidth=1,
zorder=5,alpha=1,
label='Runaway(s)',
s=150,norm=plt.Normalize(3000, 15000))
# Plot the lines showing motion errors
if len(allrun)>0:
runaway_00, runaway_apdp,runaway_apdm,runaway_amdp,runaway_amdm = [SkyCoord(ra=allrun['RA_ICRS_1'],dec=allrun['DE_ICRS_1'], pm_ra_cosdec=allrun['rmRA'],pm_dec=allrun['rmDE'], frame='icrs',obstime=(Time('J2000')+1*u.Myr)),
SkyCoord(ra=allrun['RA_ICRS_1'],dec=allrun['DE_ICRS_1'], pm_ra_cosdec=(allrun['rmRA']+allrun['e_rmRA']),pm_dec=allrun['rmDE']+allrun['e_rmDE'], frame='icrs',obstime=(Time('J2000')+1*u.Myr)),
SkyCoord(ra=allrun['RA_ICRS_1'],dec=allrun['DE_ICRS_1'], pm_ra_cosdec=(allrun['rmRA']+allrun['e_rmRA']),pm_dec=allrun['rmDE']-allrun['e_rmDE'], frame='icrs',obstime=(Time('J2000')+1*u.Myr)),
SkyCoord(ra=allrun['RA_ICRS_1'],dec=allrun['DE_ICRS_1'], pm_ra_cosdec=(allrun['rmRA']-allrun['e_rmRA']),pm_dec=allrun['rmDE']+allrun['e_rmDE'], frame='icrs',obstime=(Time('J2000')+1*u.Myr)),
SkyCoord(ra=allrun['RA_ICRS_1'],dec=allrun['DE_ICRS_1'], pm_ra_cosdec=(allrun['rmRA']-allrun['e_rmRA']),pm_dec=allrun['rmDE']-allrun['e_rmDE'], frame='icrs',obstime=(Time('J2000')+1*u.Myr))]
earlier_runaway_00 = runaway_00.apply_space_motion(dt = -100_000*u.year)
earlier_runaway_apdp = runaway_apdp.apply_space_motion(dt = -100_000*u.year)
earlier_runaway_apdm = runaway_apdm.apply_space_motion(dt = -100_000*u.year)
earlier_runaway_amdp = runaway_amdp.apply_space_motion(dt = -100_000*u.year)
earlier_runaway_amdm = runaway_amdm.apply_space_motion(dt = -100_000*u.year)
earlier_runaway_00_px = wcs.world_to_pixel_values(earlier_runaway_00.ra, earlier_runaway_00.dec)
earlier_runaway_apdp_px = wcs.world_to_pixel_values(earlier_runaway_apdp.ra, earlier_runaway_apdp.dec)
earlier_runaway_apdm_px = wcs.world_to_pixel_values(earlier_runaway_apdm.ra, earlier_runaway_apdm.dec)
earlier_runaway_amdp_px = wcs.world_to_pixel_values(earlier_runaway_amdp.ra, earlier_runaway_amdp.dec)
earlier_runaway_amdm_px = wcs.world_to_pixel_values(earlier_runaway_amdm.ra, earlier_runaway_amdm.dec)
runaway_00_px = wcs.world_to_pixel_values(runaway_00.ra, runaway_00.dec)
# Calculate the displacement vectors
delta_x = earlier_runaway_apdp_px[0]-earlier_runaway_amdp_px[0]
delta_y = earlier_runaway_apdp_px[1]-earlier_runaway_apdm_px[1]
for pxx, pxy, dx, dy in zip(earlier_runaway_00_px[0], earlier_runaway_00_px[1], delta_x, delta_y):
ellipse = patches.Ellipse(
(pxx, pxy),
width=1.5*dx,
height=1.5*dy,
fill=True,
color='g',
alpha=0.2
)
ax.add_patch(ellipse)
for c in [earlier_runaway_apdp_px,earlier_runaway_apdm_px,earlier_runaway_amdp_px,earlier_runaway_amdm_px]:
delta_x = c[0] - runaway_00_px[0]