-
Notifications
You must be signed in to change notification settings - Fork 0
/
OGLE_RRLyr.py
executable file
·1878 lines (1644 loc) · 86.1 KB
/
OGLE_RRLyr.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
'''
Add a description of the code later
'''
# Standard library imports
from pathlib import Path
import os
import re
import sys
import warnings
# Third-party imports
from astropy import units as u
from astropy.coordinates import SkyCoord # , Distance
from astropy.io import ascii
from astropy.table import Table, vstack, hstack # , Column
from astroquery.simbad import Simbad
import inquirer as iq
from matplotlib import cm
from matplotlib.colors import ListedColormap # , LinearSegmentedColormap
import matplotlib.colors as colors
import matplotlib.gridspec as gridspec
# import matplotlib.patches as patch
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from sklearn.mixture import GaussianMixture
# from sklearn import mixture, preprocessing
import scipy.stats
from scipy.stats import multivariate_normal
from termcolor import colored # , cprint
# Local application imports
# from local_module import local_class
# from test_emcee_mod import log_prior # testing! (get() functions...)
def main():
# required to import local modules:
path = os.path.dirname(os.path.realpath(__file__))
if path not in sys.path:
sys.path.insert(0, os.path.join(path))
sys.path.insert(0, os.path.dirname(path))
# To-do: Make local imports with clem, ogle, gaia and ir!!
global NGC, c1, memb, tel, reHeader, ncat, p_member
NGC, c1, RA_DEC, new_gc = choose_cluster()
if not os.path.isdir(f'{path}/{NGC}'):
os.mkdir(f'{path}/{NGC}')
os.mkdir(f'{path}/{NGC}/Aux_Cats')
ncat = iq.prompt({iq.Confirm('t', message='Download new catalogues?',
default=False)})['t']
rrls, gaia_full, gaia_filt, rrl_gaia, rrl_gaiac, ir_filt, rrl_irc, \
tel, rr_mag, rad = read_cats_Xmatch(NGC, c1, new_gc)
Jname = 'Jmag3' if tel == 'vvv' else 'Jmag'
Hname = 'Hmag3' if tel == 'vvv' else 'Hmag'
Ksname = 'Ksmag3' if tel == 'vvv' else 'Kmag'
Imag = rrl_gaiac['Imag']
# FROM HERE: do not use read_catalogues with several global variables,
# and retrieve only the useful variables from tables!
# DELETE funct. read_catalogues(), after removing all other calls!!!
# read_catalogues(NGC)
memb = iq.prompt({iq.Confirm('memb', message='Use previous membership' +
' results?', default=False)})['memb']
options = ['King profile (half-light radius)', 'Sigma-clipping (<V>,' +
' <I> & <Ks>)', 'Proper motions (from Gaia EDR3)']
reHeader, head, alpha = not memb, not memb, 2.0
pars = {}
if not memb:
recalc = iq.prompt({iq.Checkbox('rec', message='What do you want to' +
' recalculate? ', choices=options)})['rec']
if options[0] in recalc:
RA_DEC_Plane(memb, head, c1, RA_DEC, rad, gaia_filt, rrl_gaiac)
if options[1] in recalc:
# ARRUMAR PARA OS QUE TEM FILTRO B!::: URGENTE!
rr_mag = 'Ic' if rr_mag == 'I' else rr_mag
list_V = mag_vs_period(memb, rrl_gaiac, rr_mag, 2.5)
if len(Imag) != 0 and Imag[0] != -99.99:
list_I = mag_vs_period(memb, rrl_gaiac, 'I', alpha)
list_Ks = mag_vs_period(memb, rrl_irc, Ksname, alpha)
list_mags = [list_V, list_I, list_Ks]
pars['list_mags'] = [list_V, list_I, list_Ks]
if options[2] in recalc:
plot_CMDs(memb, tel, gaia_filt, rrl_gaiac, ir_filt, rrl_irc)
ans_VPD = VPD_select(memb, gaia_filt, rrl_gaiac, c1, tel)
c_rad, pms_RA_1d, pms_DE_1d, pms_2d, f_pms_2d = ans_VPD
pars['c_rad'] = c_rad
pars['pms_1d_2d'] = [pms_RA_1d, pms_DE_1d, pms_2d, f_pms_2d]
if options[1] not in recalc:
pars = save_read(memb, False, recalc, pars, alpha)
list_mags = pars['list_mags']
pars = membership(gaia_filt, rrl_gaiac, c1, pars, alpha)
else:
pars = save_read(memb, False, recalc, pars, alpha)
pars = membership(gaia_filt, rrl_gaiac, c1, pars, alpha)
pars = save_read(memb, True, recalc, pars, alpha)
memb = True
pars = save_read(memb, False, options, pars, alpha)
p_member, list_mags = pars['memb_bellini'], pars['list_mags']
ans_VPD = VPD_select(memb, gaia_filt, rrl_gaiac, c1, tel, pars)
if not memb:
c_rad, pms_RA_1d, pms_DE_1d, pms_2d, f_pms_2d = ans_VPD
else:
c_rad = ans_VPD
RA_DEC_Plane(memb, head, c1, RA_DEC, rad, gaia_filt, rrl_gaiac)
mag_vs_period(memb, rrl_gaiac, rr_mag, 2.5, list_mags[0])
if len(Imag) != 0 and Imag[0] != -99.99:
mag_vs_period(memb, rrl_gaiac, 'I', alpha, list_mags[1])
# mag_vs_period(memb, Ksmag, Ksname, alpha, list_mags[2]) ### dimension problem!
plot_CMDs(memb, tel, gaia_filt, rrl_gaiac, ir_filt, rrl_irc, p_member)
print()
def sig_clip(mag, filt, alpha, numb, std=False):
'''
Computes the mean/error of <mag> (vs Period), using a sig-clipping method
to avoid the effect of outliers (field RRLs). It's made through a series of
iterations, computing med and removing stars outside med+/-alpha*sig.
'''
m1 = mag != -99.99
stds, med_old = [], round(np.median(mag[m1]), 3)
std_old = round(np.std(mag[m1]), 3) if len(mag[m1]) > 1 else 0.25
stds.append(std_old)
num = 2 if filt in ['V', 'B', 'Ic'] else 3
msg = '\033[1m {0:}) <{1:}> vs. Period:\033[0m {2:.3f} +/- {3:3f}'
print(msg.format(num, filt, med_old, std_old) + ' (with outliers)')
# print(f'\033[1m {%d}) <%S> vs. Period:\033[0m %.3f +/- %.3f (with outliers)'
# % (num, filt, med_old, std_old))
if len(mag[m1]) == 1:
mean, med_new = np.mean(mag[m1]), np.median(mag[m1])
err, std_new = 0.25, 0.25
else:
for j in range(numb+1):
if j > 0:
med_old, std_old = med_new, std_new
m2 = (mag > med_old - alpha*std_old) & (mag < med_old + alpha*std_old)
med_new, std_new = np.median(mag[m2]), np.std(mag[m2])
stds.append(round(std_new, 3))
if j == numb:
if std:
print(np.array(stds))
mean, err = np.mean(mag[m2]), np.std(mag[m2])/(len(mag[m2])**0.5)
if not memb:
print(u' \u25B8 \u03C3-clipping: %.3f +/- %.3f '%(med_new, std_new)+\
'(%.3f +/- %.3f)%s'%(mean, err, colored(u' \033[1m\u2713\033[0m','green')))
return mean, err, med_new, std_new
def auto_ticks(ax):
'''
This aux function places ticks inside the plot in both axis, and sets major/
minor ticks depending on the entries (xmaj,xmin...).
'''
ax.tick_params(direction='in',which='both')
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.yaxis.set_major_locator(ticker.AutoLocator())
ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
def choose_cluster():
'''
This function reads the cats properties and the number of stars in order to
make a summary of these cats, to be printed in the terminal.
'''
warnings.simplefilter(action='ignore', category=FutureWarning)
u_coord = (u.si.hourangle, u.si.deg)
# os.system('printf "\n";python -V')
# print(sys.version_info)
print(f'{sys.version} --> {os.path.basename(__file__)} \n')
new_gc = iq.prompt({iq.Confirm('new', message='New cluster or update' +
' catalogues?', default=False)})['new']
path = os.path.dirname(os.path.realpath(__file__))
harris = Table.read(f'{path}/harris_mwgc.fits', format='fits')
IDs, names = np.array(harris['ID']), np.array(harris['Name'])
RAs, DECs = np.array(harris['RA']), np.array(harris['DEC'])
IDs = np.array([i.decode('utf-8').strip() for i in IDs])
names = np.array([n.decode('utf-8').strip() for n in names])
RAs = np.array([ra.decode('utf-8').strip() for ra in RAs])
DECs = np.array([dec.decode('utf-8').strip() for dec in DECs])
# insert cluster, validating from Harris catalogue
if new_gc:
IDs_case = [i.casefold() for i in IDs]
names_case = [n.casefold() for n in names]
check = list(IDs) + [n.casefold() for n in names if n != ''] + \
IDs_case + [n for n in names if n != '']
NGC = iq.prompt([iq.Text('c', message='Cluster name', validate=
lambda _, x: x.replace(' ', '').casefold() in check)])['c']
NGC = NGC.replace(' ', '').casefold()
if NGC in IDs_case:
NGC = IDs[IDs_case.index(NGC)]
else:
NGC = IDs[names_case.index(NGC)]
# choose previous cluster
elif not new_gc:
fold = ['__pycache__', 'Clement', 'GaiaEDR3', 'L_versus_B', 'OGLE-CVS',
'Paper', 'References', 'testCodes']
GCs = [n for n in os.listdir(path) if '.' not in n and n not in fold]
NGC = iq.prompt([iq.List(name='ngc', message='Choose the cluster',
choices=sorted(GCs), carousel=True)])['ngc']
# get coordinates from Simbad or Harris
t = Simbad.query_object(NGC)
if len(t) >= 1: # Simbad
c = SkyCoord(t['RA'][0], t['DEC'][0], unit=u_coord)
else: # Harris
RA, DEC = RAs[list(IDs).index(NGC)], DECs[list(IDs).index(NGC)]
c = SkyCoord(RA, DEC, unit=u_coord)
RA_DEC = c.to_string('hmsdms')
# print header [name(s), coords] in terminal
if names[list(IDs).index(NGC)] != '':
head = ' {} ({}) '.format(NGC, names[list(IDs).index(NGC)])
else:
head = ' {} '.format(NGC)
l, s = u'\u2500'*(len(head)), ' '*4
r, d = RA_DEC.split()[0], RA_DEC.split()[1]
print(u'\n\033[1m{}\u250C{}\u2510\n{}\u2502{}\u2502'.format(s, l, s, head),
u'{}RA {} ; DEC {}\n{}\u2514{}\u2518\n\33[0m'.format(s, r, d, s, l))
return NGC, c, RA_DEC, new_gc
def get_clement(ngc, center): # 23.mar.21: OK!
'''
Add description later...
ESO 452-SC11 ==> 1636-283 in H10
ESO 455-SC11 ==> HP1 in H10 (HauteProvince)
ESO 333-SC016 ==> Ton2 in H10 (Tonantzintla)
There are 6 lines of diff: 8 only H, 2 only C!!!
'''
path = os.path.dirname(os.path.realpath(__file__))
c_clusters = Table.read(f'{path}/Clement/c1-clusters.fit', format='fits')
c_radec = SkyCoord(ra=c_clusters['RAJ2000'], dec=c_clusters['DEJ2000'])
c_rads = center.separation(c_radec)
c_name = c_clusters['Name'][c_rads.argmin()].split(',')[0].replace(' ', '')
c_name = c_name.replace('Ruprecht', 'Rup').replace('2MASS', '2MS')
c_NED = c_clusters['NEDname'][c_rads.argmin()].replace(' ', '')
c_NED = c_NED.replace('Palomar', 'Pal')
# Correct HP1 for Haute Provence 1!!!
H10_notC = '(Ko1-2, Whiting1, BH176, FSR1735, Bh261, GLIMPSE1-2)'
if ngc == c_NED or ngc == c_name.replace('-', '') or c_name in \
['ESO 452-SC11', 'ESO 455-SC11', 'ESO 333-SC016']:
c_file = c_clusters['File'][c_rads.argmin()].strip()
c_upd = '({})'.format(c_clusters['Update'][c_rads.argmin()].strip())
c_Nv = c_clusters['Nv'][c_rads.argmin()]
c_vars = Table.read(f'{path}/Clement/c2-variables.fit', format='fits')
# 3111 -> 39, 1892, 76 , 4 , 26 , 986 , 50 , 4 , 6 , 28
ts = ['RR','RR0','RR01','RR01?','RR0?','RR1','RR1?','RR2','RR2?','RR?']
t_flag = np.array([typ in ts for typ in c_vars['Type']])
f_flag = np.array([f.strip() == c_file for f in c_vars['File']])
flags = (t_flag & f_flag)
rrl_epochs = list(c_vars['Epoch'][flags])
if not (rrl_epochs and all(rrl == 'R0' for rrl in rrl_epochs)):
print('Not all RRLs have J2000 coordinates! Stop.')
if c_Nv != len(c_vars[f_flag]):
print('Number of variables does not match! Stop.')
rrl_ids = np.array(c_vars['Var'][flags], dtype='str')
rrl_ras = c_vars['RAJ2000'][flags]
rrl_decs = c_vars['DEJ2000'][flags]
rrl_pers = np.array(c_vars['Per'][flags])
rrl_mags = np.array(c_vars['__mag_'][flags])
rrl_amps = np.array(c_vars['Amp'][flags])
rrl_filts = np.array(c_vars['Filt'][flags], dtype='str')
rrl_filts = np.where(rrl_filts == ' ', '', rrl_filts)
rrl_types = np.array(c_vars['Type'][flags], dtype='str')
#..NGC6266: RA-DEC offset
if ngc == 'NGC6266':
rrl_ras = rrl_ras - 2.1e-4
rrl_decs = rrl_decs + 1.12e-3
#..NGC6441 (V36 - V104): ' ' -> 'V' (Layden+1999 & Pritzl+2001)
if ngc == 'NGC6441':
rrl_filts[:47] = 'V'
rrls = (rrl_ids, rrl_ras, rrl_decs, rrl_pers, rrl_mags, rrl_amps,
rrl_filts, rrl_types)
lab = ['ID', 'RA', 'DEC', 'cPeriod', 'mag', 'Ampl', 'Filt', 'cType']
dt = [(np.unicode_, 8), np.float64, np.float64, np.float32, np.float32,
np.float32, (np.unicode_, 8), (np.unicode_, 8)]
fname = f'{path}/{ngc}/{ngc}_clem.fits'
out = Table(rrls, names=lab, dtype=dt)
out.replace_column('RA', np.around(rrl_ras, decimals=6))
out.replace_column('DEC', np.around(rrl_decs, decimals=6))
out.write(fname, format='fits', overwrite=True)
return out, c_upd
print("Cluster is NOT in Clement's catalogue:\n{}.".format(H10_notC))
return Table(), ''
def get_ogle(ngc, center): # 23.mar.21: OK!
'''
Reads the OGLE catalogues, returning the RRLs inside a given radius.
'''
ns = ['Name', 'oType', 'RA', 'DEC']
path = os.path.dirname(os.path.realpath(__file__))
ident = ascii.read(f'{path}/L_versus_B/ident_edit.dat', names=ns,
data_start=0)
ident2 = ascii.read(f'{path}/L_versus_B/ident2_edit.dat', names=ns,
data_start=0)
ogleIV, c_unit = vstack([ident, ident2]), (u.si.hourangle, u.si.deg)
o_coord = SkyCoord(ra=ogleIV['RA'], dec=ogleIV['DEC'], unit=c_unit)
o_rad = center.separation(o_coord)
use_Rt = iq.prompt({iq.Confirm('Rt', message='Use King tidal radius?',
default=False)})['Rt']
if use_Rt:
#..Call King function (Francisco) #!!!
pass
else:
valid, m = r'^[0-9]*(?:\.(\d|\d\d|\d\d\d))?$', 'Insert radius '
lim = iq.prompt([iq.Text('lim', message=m+'(arcmin)', validate=
lambda _, x: re.match(valid, x) and float(x) <= 20)])['lim']
lim = float(lim)
inside = o_rad <= lim*u.si.arcmin
print()
# selecting stars inside the given radius
ogle_in = ogleIV[inside]
fname = '{}_ocvs_{}arcmin.fits'.format(ngc, str(lim).replace('.', 'p'))
# no OGLE stars
if len(ogle_in) == 0:
return Table(), lim
# transforming RA-DEC (hmsdms -> deg, 6 dec-digits)
o_ras_deg = np.array(np.around(o_coord[inside].ra, decimals=6))
o_decs_deg = np.array(np.around(o_coord[inside].dec, decimals=6))
ns, dt = ('RA', 'DEC'), list(np.repeat([np.float64], 2))
coords = Table(np.c_[o_ras_deg, o_decs_deg], names=ns, dtype=dt)
ogle_in.remove_columns(['RA', 'DEC'])
ogle_in.add_columns(list(coords.columns.values())) # corr on 20.fev.2021
# extra columns with photometry and period
abc = ['ID', 'Imag', 'Vmag', 'Period', 'uPeriod', 'Time-max', 'Iamp',
'R_21', 'phi_21', 'R_31', 'phi_31']
d = abc + ['Period2', 'uPeriod2', 'Time-max2', 'Iamp2', 'R_21f',
'phi_21f', 'R_31f', 'phi_31f']
blg_ab = ascii.read(f'{path}/OGLE-CVS/blg/RRab.dat', names=abc, data_start=0)
blg_c = ascii.read(f'{path}/OGLE-CVS/blg/RRc.dat', names=abc, data_start=0)
blg_d = ascii.read(f'{path}/OGLE-CVS/blg/RRd.dat', names=d, data_start=0)
blg_ad = ascii.read(f'{path}/OGLE-CVS/blg/aRRd.dat', names=d, data_start=0)
gd_ab = ascii.read(f'{path}/OGLE-CVS/gd/RRab.dat', names=abc, data_start=0)
gd_c = ascii.read(f'{path}/OGLE-CVS/gd/RRc.dat', names=abc, data_start=0)
gd_d = ascii.read(f'{path}/OGLE-CVS/gd/RRd.dat', names=d, data_start=0)
gd_ad = ascii.read(f'{path}/OGLE-CVS/gd/aRRd.dat', names=d, data_start=0)
# declaring the phot arrays
o_imags = np.zeros(len(ogle_in))
o_vmags, o_pers = np.copy(o_imags), np.copy(o_imags)
o_upers, o_amps = np.copy(o_imags), np.copy(o_imags)
name = {'BLG-RRab': blg_ab, 'BLG-RRc': blg_c, 'BLG-RRd': blg_d,
'BLG-aRRd': blg_ad, 'GD-RRab': gd_ab, 'GD-RRc': gd_c,
'GD-RRd': gd_d, 'GD-aRRd': gd_ad}
# looping to add phot columns
for (idx, rrl) in enumerate(ogle_in):
key = '{}-{}'.format(rrl['Name'].split('-')[1], rrl['oType'])
good = name[key]['ID'] == rrl['Name']
o_imags[idx] = float(name[key]['Imag'][good])
try: # lines with '-' --> NaN
o_vmags[idx] = name[key]['Vmag'][good]
except ValueError:
o_vmags[idx] = np.nan
o_pers[idx] = name[key]['Period'][good]
o_upers[idx] = name[key]['uPeriod'][good]
o_amps[idx] = name[key]['Iamp'][good]
# appending new columns and save
cols = np.c_[o_imags, o_vmags, o_pers, o_upers, o_amps]
ns = ('Imag', 'o_Vmag', 'o_Period', 'o_uPeriod', 'Iamp')
dt = list(np.repeat([np.float32], 5))
phot = Table(cols, names=ns, dtype=dt)
ogle_in.add_columns(list(phot.columns.values()))
ogle_in.write(f'{path}/{ngc}/{fname}', format='fits', overwrite=True)
return ogle_in, lim
def clean_gaia2(ngc, rad, full_t, bulge=True): # 18.mar.21: OK!
'''
WRITE DOCS LATER!!!
It is separated from get_gaia, so we can use it in other codes!!!
Read Arenou+2018. fullt needs to be an AstroPy table!
phot_bp_rp_excess_factor is the ratio of the sum of G_BP and G_RP fluxes
over the G flux and should be around one for normal stars.
'''
#.Defining the main variables
chi2, nu = full_t['chi2AL'], full_t['NgAL'] - 5
u_filt = np.sqrt(chi2/nu)
E_fac = full_t['E_BR_RP_']
#.Defining the flags from Equations 1, 2 and 3
flag1 = np.ones(len(full_t),dtype=bool)
flag2a, flag2b, flag3 = np.copy(flag1), np.copy(flag1), np.copy(flag1)
for (i, star) in enumerate(full_t):
flag1[i] = u_filt[i] < 1.2*max(1, np.exp(-0.2*(star['Gmag']-19.5)))
flag2a[i] = E_fac[i] > 1.0 + 0.015*(star['BPmag']-star['RPmag'])**2
flag2b[i] = E_fac[i] < 1.3 + 0.06*(star['BPmag']-star['RPmag'])**2
flag3[i] = star['Nper'] > 8
#.Normal: Equations 1 and 2
if not bulge: flags = flag1 & flag2a & flag2b
#.Preferable for bulge proper motions
elif bulge: flags = flag1 & flag3
#.Returning the output table
#print (' > Gaia ({}\'): Before {} stars / After {} stars'.format(rad,\
# len(full_t), len(full_t[flags])) + ' (Arenou+2018)')
return full_t[flags]
def get_gaia2(ngc, center, radius): # 18.mar.21: OK!
'''
This (I/345/gaia2) WRITE DOCS LATER!!!
For those with a well-measured parallax, it is possible to convert the
epochs from 2015.5 to J2000 (January 1st, 2020).
There is one line more in astroquery.Vizier?
Method 1 transformed to J2000 is exactly equal the Vizier RAJ2000 !!! OK!
(But since there are some stars without parralax, I will use Vizier)
'''
#print('Entrando em get_gaia2')
path = os.path.dirname(os.path.realpath(__file__))
rad, pm_u = radius*u.si.arcmin, u.si.mas/u.si.yr
## Method 1: astroquery.Gaia (slow, epoch 2015.5 to J2000)
# Links: https://astroquery.readthedocs.io/en/latest/gaia/gaia.html
# https://docs.astropy.org/en/stable/coordinates/apply_space_motion.html
# [Bailer-Jones (2015, 1507.02105); Bailer-Jones+ (2018, 1804.10121)
'''from astroquery.gaia import Gaia
from astropy.time import Time
j = Gaia.cone_search_async(center, radius)
tab = j.get_results()
c0 = SkyCoord(ra=tab['ra'][0]*u.si.deg, dec=tab['dec'][0]*u.si.deg,\
distance=Distance(parallax=tab['parallax'][0] * u.si.mas),\
pm_ra_cosdec=tab['pmra'][0]*pm_u,pm_dec=tab['pmdec'][0]*pm_u,\
obstime=Time(tab['ref_epoch'][0], format='decimalyear'))
epoch_J2000 = Time('2000-01-01')
c_2mass_epoch = c0.apply_space_motion(epoch_J2000) # Checked!'''
## Method 2: Get also RAJ2000 and DEJ2000 (fast, Vizier)
# Link: https://astroquery.readthedocs.io/en/latest/vizier/vizier.html
# I tried to change e-/s, but it's not good (TOPCAT)
from astropy.io.fits.verify import VerifyWarning
warnings.simplefilter(action='ignore', category=u.UnitsWarning)
warnings.simplefilter(action='ignore', category=VerifyWarning)
from astroquery.vizier import Vizier
#rad = 1 * u.si.arcmin ### change later: only testing!!!
std_cols = Vizier(row_limit=1000000).query_region(center, radius=rad,\
catalog='I/345/gaia2')
v1 = Vizier(columns=['RAJ2000','e_RAJ2000','DEJ2000','e_DEJ2000'],\
row_limit=1000000)
v2 = Vizier(columns=['NgAL','chi2AL','Nper','phot_bp_rp_excess_factor'],
row_limit=1000000)
J2000 = v1.query_region(center, radius=rad, catalog='I/345/gaia2')
flags = v2.query_region(center, radius=rad, catalog='I/345/gaia2')
gaia2 = hstack([std_cols[0], J2000[0], flags[0]])
#.Reordering the columns (J2000, flags, std_cols)
order = ['RAJ2000','e_RAJ2000','DEJ2000','e_DEJ2000','Source','NgAL',\
'chi2AL','Nper','E_BR_RP_','Plx','e_Plx','pmRA','e_pmRA','pmDE',\
'e_pmDE','Dup','FG','e_FG','Gmag','e_Gmag','FBP','e_FBP','BPmag',\
'e_BPmag','FRP','e_FRP','RPmag','e_RPmag','BP-RP','RV','e_RV',\
'Teff','AG','E_BP-RP_','Rad','Lum','RA_ICRS','e_RA_ICRS',\
'DE_ICRS','e_DE_ICRS']
gaia2_full = gaia2[order]
#.Changing masked values to np.NaN -> Method 1 (quick!)
def fill_cols(tbl, fill=np.nan, kind='f'):
"""
In-place fill of ``tbl`` columns which have dtype ``kind``
with ``fill`` value.
"""
for col in tbl.itercols():
if col.dtype.kind == kind:
col[...] = col.filled(fill)
fill_cols(gaia2_full, fill=np.nan, kind='f') ### IMPORTANT!!!
fill_cols(gaia2_full, fill=-99, kind='i')
#.Changing masked values to np.NaN -> Method 2 (slower)
# for col in gaia2_full.colnames:
# for (idx,elem) in enumerate(gaia2_full[col]):
# if elem is np.ma.masked or elem == 1.0E20:
# gaia2_full[col][idx] = np.NaN
#.Write full table (before and after Arenou+18 filtering)
fname = '{}_gaia2_{}arcmin.fits'.format(ngc,str(radius).replace('.','p'))
gaia2_full.write(f'{path}/{ngc}/{fname}', format='fits', overwrite=True)
gaia2_filt = clean_gaia2(ngc, radius, gaia2_full)
fname = fname.replace('gaia2','gaia2c')
gaia2_filt.write(f'{path}/{ngc}/{fname}', format='fits', overwrite=True)
return gaia2_full, gaia2_filt
def get_gaia3(ngc, center, radius): # 18.mar.21: OK!
# print('Entrando em get_gaia3')
from astroquery.gaia import Gaia
# from GaiaEDR3 import GaiaEDR3_data as gaiaedr3
from get_gaia_edr3 import GaiaEDR3_data as gaiaedr3
path = os.path.dirname(gaiaedr3.__file__)
# Gaia.login(credentials_file=f'{path}/my_credentials.txt')
Gaia.login(credentials_file=f'{path}/my_credentials-RAPHAEL.txt')
ngc, c, rad, out, outname, lind20 = gaiaedr3.initial_inputs(ngc, radius)
gaia3, gaia3_valid = gaiaedr3.astroquery_adql(ngc, c, rad, outname)
# success = gaiaedr3.upload_to_gaia(gaia3, 'tablename', outname)
gaia3_corr = gaiaedr3.gaia_codes(gaia3, gaia3_valid, lind20, outname)
# print (center == c1)
return gaia3, gaia3_corr
def get_vvv_2mass(ngc, center, radius, full=False): # 23.mar.21: OK!
'''
WRITE DESCRIPTION (DOCS) LATER
Get the IR data from VVV (preferable) or 2MASS (ABDC quality flags)
Don't save/return the unfiltered catalogue, only the filtered one!!!
The 'full' kwarg determines if the ir_full Table will be saved.
'''
from astroquery.vizier import Vizier
path = os.path.dirname(os.path.realpath(__file__))
rad = radius * u.si.arcmin
#.Check if cluster is inside VVV-DR2 covered area
col1 = ['RAJ2000','DEJ2000','iauname','mClass','Z-Y','e_Z-Y','J-H',\
'e_J-H','H-Ks','e_H-Ks','Zmag3','e_Zmag3','Zperrbits','Ymag3',\
'e_Ymag3','Yperrbits']
col2 = ['Jmag3','e_Jmag3','Jperrbits','Hmag3','e_Hmag3','Hperrbits',\
'Ksmag3','e_Ksmag3','Ksperrbits']
v0 = Vizier(row_limit=1000000, columns=col1, catalog='II/348/vvv2')
v1 = Vizier(row_limit=1000000, columns=col2, catalog='II/348/vvv2')
try:
tab0 = v0.query_region(center, radius=rad)['II/348/vvv2']
tab1 = v1.query_region(center, radius=rad)['II/348/vvv2']
ir_full = hstack([tab0, tab1])
tel, f = 'vvv', 'perrbits'
except TypeError:
tel = '2mass'
#.VVV-DR2 photometry tables (with flags)
if tel == 'vvv':
fmag = ['Zmag3', 'Ymag3', 'Jmag3', 'Hmag3', 'Ksmag3']
fcol = ['Z-Y', 'J-H', 'H-Ks']
ir_filt = Table(ir_full)
for star in ir_filt:
for (idx, mag) in enumerate(fmag):
if star[mag[:-4]+f] > 255 or star[mag] is np.ma.masked:
star[mag], star['e_'+mag] = np.nan, np.nan
for (idx, col) in enumerate(fcol):
if star[col] is np.ma.masked:
star[col], star['e_'+col] = np.nan, np.nan
#.2MASS photometry tables (with flags)
elif tel == '2mass':
c = ['RAJ2000','DEJ2000','2MASS','Jmag','e_Jmag','Hmag','e_Hmag',\
'Kmag','e_Kmag','Qflg','Rflg','Bflg','Cflg','Xflg','Aflg']
v2 = Vizier(row_limit=1000000, columns=c, catalog='II/246/out')
ir_full = v2.query_region(center, radius=rad)['II/246/out']
ir_filt, val_Qflg = Table(ir_full), ['A', 'B', 'C', 'D']
fmag = ['Jmag', 'Hmag', 'Kmag']
for star in ir_filt:
for (idx, mag) in enumerate(fmag):
if star['Qflg'][idx] not in val_Qflg:
star[mag], star['e_'+mag] = np.nan, np.nan
ir_filt.meta['description'] = ir_filt.meta['description'][:55]
#.Write/Return ONLY the filtered IR table (VVV or 2MASS)
rad_str = str(radius).replace('.','p')
fname = f'{ngc}_{tel}c_{rad_str}arcmin.fits'
ir_filt.write(f'{path}/{ngc}/{fname}', format='fits', overwrite=True)
if full:
fname = fname.replace(tel+'c', tel)
ir_full.write(f'{path}/{ngc}/{fname}', format='fits', overwrite=True)
return ir_filt, tel
def read_cats_Xmatch(NGC, c, new_gc): # 23.mar.21: OK!
'''
Write a description (and docs) later.
Reads all catalogues and make the cross-matches!!!
Clement, OGLE, Xmatch, Gaia(Xmatch), IR (Xmatch)
Return: Xmatch, gaia_ [...]
'''
from astropy.io.fits.verify import VerifyWarning
warnings.simplefilter(action='ignore', category=u.UnitsWarning)
warnings.simplefilter(action='ignore', category=VerifyWarning)
global n_gaiac # remove!
u_coord = (u.si.deg, u.si.deg)
path = os.path.dirname(os.path.realpath(__file__))
# calling the get_clement() function
if new_gc:
c_rrls, c_upd = get_clement(NGC, c)
elif Path(f'{path}/{NGC}/{NGC}_clem.fits').is_file():
c_rrls = Table.read(f'{path}/{NGC}/{NGC}_clem.fits', format='fits')
else:
c_rrls = Table()
# calling the get_ogle() function
fs = [f for f in os.listdir(f'{path}/{NGC}') if 'ocvs' in f and '.fits' in f]
if new_gc and ncat:
o_rrls, o_lim = get_ogle(NGC, c)
elif len(fs) > 0:
o_rrls = Table.read(f'{path}/{NGC}/{fs[0]}', format='fits')
o_lim = float(fs[0].split('_')[-1].split('arc')[0].replace('p','.'))
else:
o_rrls, o_lim = Table(), 0
# cross-match OGLE (source) vs. Clement
if len(o_rrls) == 0:
print('\n\033[1m * Cluster is not in the OGLE footprint *\033[0m\n')
sys.exit()
c_ogle = SkyCoord(o_rrls['RA'], o_rrls['DEC'], unit=u_coord)
c_clem = SkyCoord(c_rrls['RA'], c_rrls['DEC'], unit=u_coord)
idx, d2d, d3d = c_ogle.match_to_catalog_sky(c_clem)
max_sep = 4.5 if NGC == 'NGC6266' else 1.0 # important!
sep_constraint = d2d < max_sep * u.si.arcsec
clem_matches = c_rrls[idx[sep_constraint]]
# adding OGLE stars without match
c_empty_row = ['', np.nan, np.nan, np.nan, np.nan, np.nan, '', '']
n_new, sort_idxs = 0, np.zeros(len(c_ogle), dtype=int)
for i in range(len(c_ogle)):
if not sep_constraint[i]:
clem_matches.add_row(c_empty_row)
sort_idxs[len(clem_matches)-1] = i
n_new += 1
else:
sort_idxs[i-n_new] = i
c_mixed = clem_matches[np.argsort(sort_idxs)]
# adding Clement stars without match
for (i, item) in enumerate(c_rrls['ID']):
if item not in c_mixed['ID']:
c_mixed.add_row(c_rrls[i])
# OGLE+Clement tables and write output
o_empty_row = ['', ''] + list(np.repeat(np.nan, 7))
n_clem_out = len(c_rrls)-len(c_rrls[idx[sep_constraint]])
for i in range(n_clem_out):
out = [c_mixed['RA'][-n_clem_out+i], c_mixed['DEC'][-n_clem_out+i]]
o_empty_row = ['', ''] + out + list(np.repeat(np.nan, 5))
o_rrls.add_row(o_empty_row)
if o_rrls:
del c_mixed['RA', 'DEC']
rrls = hstack([o_rrls, c_mixed], join_type='exact')
rrls.write(f'{path}/{NGC}/{NGC}_Xmatch.fits', format='fits', overwrite=True)
# organize prints in the terminal
n_ogle, n_tot = len(c_ogle), len(c_rrls)+n_new
if not c_rrls:
print(' > Clement: No RR Lyrae')
if not new_gc:
c_upd = ''
else:
print(f' > Clement: {len(c_rrls)} RR Lyrae {c_upd}')
if o_rrls:
col = colored(f'{n_tot} in total!\033[0m', 'yellow')
print(f' > OGLE ({str(o_lim)}\'): {n_ogle} RR Lyrae\033[1m',
f'({n_new} new) ==> {col}\n')
else:
print(f'There are no OGLE RRLs inside rad={str(o_lim)}.\n')
# calling the get_gaia2() or get_gaia3() function
dr = 'gaia3'
rad_str = str(o_lim).replace('.', 'p') + 'arcmin'
cat = [f for f in os.listdir(f'{path}/{NGC}') if f'{dr}_c{rad_str}' in f]
source = {'gaia2': 'Source', 'gaia3': 'source_id'}
if new_gc and ncat:
if dr == 'gaia3':
gaia3_orig, gaia_full = get_gaia3(NGC, c, o_lim)
else:
gaia_full, gaia_filt = get_gaia2(NGC, c, o_lim) # DR2
elif cat:
filt = cat[0].replace(f'{dr}', f'{dr}c')
full = cat[0] if dr == 'gaia2' else filt
gaia_full = Table.read(f'{path}/{NGC}/{full}', format='fits')
gaia_filt = Table.read(f'{path}/{NGC}/{filt}', format='fits')
else:
gaia_full, gaia_filt = Table(), Table()
if dr == 'gaia3':
# gaia_filt = gaia_full[gaia3_full['all_flags'] == 1]
# gaia_filt = gaia_full[gaia_full['flag_noExcess'] == 1]
flag_noExcess_ruwe2p0 = (gaia_full['flag_ruwe_2p0'] == 1) & \
(gaia_full['flag_gmag'] == 1) & \
(gaia_full['flag_rpmag'] == 1) ### TESTAR SE DEU CERTO!!!
gaia_filt = gaia_full[flag_noExcess_ruwe2p0]
print(f'\n > {dr} ({str(o_lim)}\'): Before {len(gaia_full)} stars',
f'/ After {len(gaia_filt)} stars (cat. validation)')
# breakpoint()
def remove_duplicates(tab1, tab2, source_str):
unique = np.unique(tab2[source_str], return_counts=True)[0]
counts = np.unique(tab2[source_str], return_counts=True)[1]
duplic = []
for i in range(len(counts)): # remove duplicated entries: ok
if counts[i] > 1:
duplic.append(unique[i])
for dup in duplic:
idxs = np.nonzero(tab2[source_str] == dup)[0]
r = 0 if d2d[sep_const][idxs[0]] > d2d[sep_const][idxs[1]] else 1
tab1.remove_row(idxs[r])
tab2.remove_row(idxs[r])
return hstack([tab1, tab2], join_type='exact')
# cross-match OGLE+Clem vs. Gaia cleaned
c_match = SkyCoord(rrls['RA'], rrls['DEC'], unit=u_coord)
c_gaiac = SkyCoord(gaia_filt['RAJ2000'], gaia_filt['DEJ2000'], unit=u_coord)
idx, d2d, d3d = c_match.match_to_catalog_sky(c_gaiac)
sep_const = d2d < 1.0 * u.si.arcsec
rrlc_matches = rrls[sep_const]
gaiac_matches = gaia_filt[idx[sep_const]]
rrl_gaiac = remove_duplicates(rrlc_matches, gaiac_matches, source[dr])
fnamec = f'{path}/{NGC}/{NGC}_Xmatch_wGaiac.fits'
rrl_gaiac.write(fnamec, format='fits', overwrite=True)
# breakpoint()
# cross-match OGLE+Clem vs. Gaia full
c_gaia = SkyCoord(gaia_full['RAJ2000'], gaia_full['DEJ2000'], unit=u_coord)
idx, d2d, d3d = c_match.match_to_catalog_sky(c_gaia)
sep_const = d2d < 1.0 * u.si.arcsec
rrl_matches = rrls[sep_const]
gaia_matches = gaia_full[idx[sep_const]]
rrl_gaia = remove_duplicates(rrl_matches, gaia_matches, source[dr])
fname = f'{path}/{NGC}/{NGC}_Xmatch_wGaia.fits'
rrl_gaia.write(fname, format='fits', overwrite=True)
#.Gaia vs RR Lyrae cross-match: Final prints
n_gaia, n_gaiac = len(rrl_gaia), len(rrl_gaiac)
n_miss = n_tot-len(rrl_gaiac)
final = f'({n_miss} missing)' if n_miss else '(all)'
print (f' > Gaia vs RRLs: {n_gaia} / {n_gaiac} RR Lyrae {final}')
# breakpoint()
#.Calling the get_vvv_2mass() function
filt_f = [f for f in os.listdir(f'{path}/{NGC}') if ('vvvc' in f or \
'2massc' in f) and 'arcmin.fits' in f]
if new_gc and ncat:
ir_filt, tel = get_vvv_2mass(NGC, c, o_lim)
elif len(filt_f) > 0:
ir_filt = Table.read(f'{path}/{NGC}/{filt_f[0]}', format='fits')
tel = filt_f[0].split('_')[1][:-1]
else:
ir_filt, tel = Table() , '2mass'
#.Cross-match OGLE+Clem vs. IR data (clean)
c_match = SkyCoord(rrls['RA'], rrls['DEC'], unit=u_coord)
c_ir = SkyCoord(ir_filt['RAJ2000'], ir_filt['DEJ2000'], unit=u_coord)
idx, d2d, d3d = c_match.match_to_catalog_sky(c_ir)
sep_const = d2d < 1.0 * u.si.arcsec
rrl_matches = rrls[sep_const]
ir_matches = ir_filt[idx[sep_const]]
#.OGLE+Clem + IRc data, write output and print
label = 'iauname' if tel == 'vvv' else '_2MASS'
rrl_irc = remove_duplicates(rrl_matches, ir_matches, label)
fname = f'{path}/{NGC}/{NGC}_Xmatch_w{tel}c.fits'
rrl_irc.write(fname, format='fits', overwrite=True)
Kname = 'Ksmag3' if tel == 'vvv' else 'Kmag'
Kgood = len(ir_filt[~np.isnan(ir_filt[Kname])])
print (f'\n > {tel.upper()} ({str(o_lim)}\'): Before {len(ir_filt)}',
f'stars / After {Kgood} stars (phot-flags)')
n_irc, n_miss = len(rrl_irc), n_tot-len(rrl_irc)
final = f'({n_miss} missing)' if n_miss else '(all)'
print (f' > {tel.upper()} vs RRLs: {n_irc} RR Lyrae {final}')
#.Print missing and returning all the important tables
input(colored('\n%s <<< Press ENTER to start >>> '%(' '*19),'green'))
from collections import Counter
ct = Counter(rrls['Filt'][rrls['Filt'] != ''])
rr_mag, n_mag = ct.most_common()[0][0], ct.most_common()[0][1]
if rr_mag == 'P':
rr_mag, n_mag = ct.most_common()[1][0], ct.most_common()[0][1]
print (f'\n > {n_tot-n_mag} RR Lyr without <{rr_mag}> value (Clement)')
print (f' > {n_tot-n_ogle} RR Lyr without <I> value (OGLE)')
Kmiss = n_tot - len(rrl_irc[Kname][~np.isnan(rrl_irc[Kname])])
print (f' > {Kmiss} RR Lyr without Ks value ({tel.upper()})\n')
return rrls, gaia_full, gaia_filt, rrl_gaia, rrl_gaiac, ir_filt,\
rrl_irc, tel, rr_mag, o_lim
def RA_DEC_Plane(memb, head, cen, RA_DEC, rad, gaia_filt, rrl_gaiac): # 24.mar.21: OK!
'''
Plots a RA-DEC plane with the spatial distribution of the catalogued RRLs.
There are two types: with or without membership colors. The SOAR version has
the extensive computations of the Circle, with SkyCoord.
'''
if head:
print(f"\033[1m 1) RA-DEC plane:\033[0m RR Lyrae (r={rad}')", end='')
print(colored(u' \033[1m\u2713\033[0m','green'))
if not memb: fig = plt.figure(figsize=(6.19,6))
else:
# fig = plt.figure(figsize=(6.19,6.63))
fig = plt.figure(figsize=(6.1,6))
ax = plt.gca()
cen_ra, cen_dec = cen.ra.deg, cen.dec.deg
ra, dec = rrl_gaiac['ra'], rrl_gaiac['dec']
cividisBig = cm.get_cmap('plasma_r', 512)
newcmp = ListedColormap(cividisBig(np.linspace(0.1, 0.95, 256)))
if not memb:
ax.scatter(ra, dec, s=10, color='red', marker='o', zorder=3,\
label='RR Lyrae')
else:
pcm = plt.scatter(ra, dec, s=25, c=p_member, cmap=newcmp, label=\
'RR Lyrae', zorder=3) # norm=colors.PowerNorm(gamma=1/8)
#divider = make_axes_locatable(ax)
#cax = divider.append_axes('top', size='2%', pad=0.3)
#cbar = plt.colorbar(pcm, cax=cax, orientation='horizontal', ticks=\
# [0.0,0.2,0.4,0.6,0.8,1.0])
#plt.clim(0, 1)
#cax.xaxis.set_ticks_position('top')
#cbar.set_label('Membership', fontsize=11)
ax.scatter(cen_ra, cen_dec, s=150, color='black', marker='+', zorder=4, \
label='Center', alpha=0.8)
ax.scatter(gaia_filt['ra'], gaia_filt['dec'], s=0.15, marker='x',\
color='gainsboro', label=r'$Gaia_{\rm filt}$')
# !!! CURIOUS !!! Circle vs. Ellipse
#circ = plt.Circle((cen_ra, cen_DE),rad/60,ls='--',color='k',zorder=5,fill=False)
#ax.add_artist(circ)
u, v = cen_ra, cen_dec # x and y-positions of the center
a = (rad/60)/np.cos(cen_dec*np.pi/180) #radius on the x-axis
b = rad/60 #radius on the y-axis
t = np.linspace(0, 2*np.pi, 200)
ax.plot(u + a*np.cos(t), v + b*np.sin(t), ls='--', color='green', label=\
r'r = $%d\,^{\prime}$'%rad)
# for it in t: plt.plot([u, u + a*np.cos(it)],[v, v + b*np.sin(it)])
# ellipse = patch.Ellipse((u,v), 2*a, 2*b, angle=0, ls='--', fill=False)
# ax.add_artist(ellipse)
# angles = np.linspace(0,360,25)
# for angle in angles:
# l_angle = angle * np.pi/180
# DE_l = DEc + (rad/60)*np.sin(l_angle)
# RA_l = RAc + (rad/60)*np.cos(l_angle)/np.cos(DE_l*np.pi/180)
# plt.plot([RAc,RA_l],[DEc,DE_l],zorder=1000)
# ax.update({'xlabel':'Right ascension (deg)', 'ylabel':'Declination (deg)'})
ax.set_xlabel('Right ascension (deg)', fontsize=15.5)
ax.set_ylabel('Declination (deg)', fontsize=15.5)
ax.tick_params(axis='both', which='major', labelsize=14)
auto_ticks(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.1))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.02))
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.1))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.02))
ax.invert_xaxis()
ax.legend(loc=1, fontsize=14.5)
plt.title(r'%s$\,$%s: %s$^{\rm{h}}$%s$^{\rm{m}}$%s$^{\rm{s}}$ %s'%\
(NGC[:3],NGC[3:],RA_DEC.split()[0][:2],RA_DEC.split()[0][3:5],\
RA_DEC.split()[0][6:-1], RA_DEC.split()[1][:3]) + r'$^{\circ}$'\
r'%s$^{\prime}$%s$^{\prime\prime}$'%(RA_DEC.split()[1][4:6],\
RA_DEC.split()[1][7:-1]),fontsize=17)
plt.tight_layout()
plt.subplots_adjust(bottom=0.098, right=0.967, left=0.158, top=0.927) # bottom=0.073
plt.show()
def mag_vs_period(memb, rrls, filt, alpha, list_med=[]): # 29.mar.21: OK!
'''
This function generates the <mag> vs Period plot, using the sig-clipping
function above, and can be applied to any magnitude.
'''
#tel, Jname, Hname, Ksname = 'VVV','Jmag3','Hmag3','Ksmag3'
#else: tel, Jname, Hname, Ksname = '2mass','Jmag','Hmag','Kmag'
#mag_dict = {'V':'mag', 'B':'mag', 'Ic': 'mag', 'I':'Imag', 'Ksmag3':filt, 'Kmag':filt}
num = 3 if filt == 'I' else 2 # falta aqui tbm
mag_dict = {('V','B','Ic'): 'mag', ('I'):'Imag', ('Ksmag3','Kmag'):filt}
for (i, item) in enumerate([*mag_dict]):
if filt in item: break
mag = rrls[mag_dict[[*mag_dict][i]]]
if filt in ['Ksmag3', 'Kmag']: filt = 'Ks'
period = rrls['o_Period']
ra = rrls['ra'] if filt != 'Ks' else rrls['RA']
dec = rrls['dec'] if filt != 'Ks' else rrls['DEC']
#.Correction if there is more than one Filt
if filt in ('V','B','Ic'):
f = rrls['Filt'] == filt[0]
mag, ra, dec, period = mag[f], ra[f], dec[f], period[f]
if not memb:
list_med = []
mean, err, med, std = sig_clip(mag[~np.isnan(mag)], filt, alpha, 20)
list_med.extend([mean, err, med, std])
#print (list_med)
else:
mean, err = list_med[0], list_med[1]
med, std = list_med[2], list_med[3]
if reHeader:
print(f'\033[1m {num}) <{filt}> vs. Period:\033[0m ', end='')
print(f'{mean:.3f} +/- {err:.3f} ({med:.3f} +/- {std:.3f})', end='')
print(colored(u' \033[1m\u2713\033[0m','green'))
if memb:
f = rrls['Filt'] == filt[0]
pmemb = np.array(p_member)[f] if filt in ('V','B','Ic') else np.array(p_member)
if NGC == 'NGC6717':
err = 0.100 if filt in ('V','B','Ic') else 0.080
if filt == 'Ic': filt = 'I'
flag = abs(mag-med) <= alpha*std
ra.unit, dec.unit = u.si.deg, u.si.deg
c2 = SkyCoord(ra, dec, frame='icrs')
sep = c1.separation(c2).arcmin
size = np.array([15 if s <= 2.8 else 5 for s in sep])
mag_in, period_in, size_in = mag[flag], period[flag], size[flag]
mag_out, period_out, size_out = mag[~flag], period[~flag], size[~flag]
color = ['red' if p >= 0.4 else 'blue' for p in period_in]
plt.figure(figsize=(7.1,2.5)) # x_old = 6, y = 2.65
gs = gridspec.GridSpec(1, 2, width_ratios=[14,1])
ax1, ax2 = plt.subplot(gs[0]), plt.subplot(gs[1])
ax1.tick_params(axis='both', which='major', labelsize=13.5)
ax1.set_xlabel('Period (days)', fontsize=13.5)
if filt == 'Ks': filt = r'K_{\rm{S}}'
ax1.set_ylabel(r'$\langle %s\rangle$'%filt, fontsize=13.5)
auto_ticks(ax1)
# if NGC[0:3] == 'NGC':
# ax1.set_title(r'%s$\,$%s: $\langle %s\rangle$ vs. Period'%(NGC[:3],NGC[3:],filt))
# else: ax1.set_title(r'%s$\,$%s: $\langle %s\rangle$ vs. Period'%(NGC[:-1],NGC[-1],filt))
ax1.text(0.77, mean-2+0.76, r'%s$\,$%s'%(NGC[:3],NGC[3:]), \
color='black',fontsize=17, family='sans-serif') # max(period)+0.05-0.135
#ax1.set_xlim(min(period)-0.05,max(period)+0.05) # normal x-range
ax1.set_xlim(0.21, 0.94) # panels
ax1.set_ylim(mean-2.0, mean+2.0)
if not memb:
for x, y, s, c in zip(period_in, mag_in, size_in, color):
ax1.scatter(x, y, s=s, zorder=5, color=c)
ax1.scatter(period_out, mag_out, s=size_out, zorder=4, color='silver')
else:
cividisBig = cm.get_cmap('plasma_r', 512)
newcmp = ListedColormap(cividisBig(np.linspace(0.1, 0.95, 256)))
print(len(mag), len(mag[flag]))
pcm = ax1.scatter(period[flag], mag[flag], s=28, c=pmemb[flag], cmap=\
newcmp, zorder=4)#, norm=colors.PowerNorm(gamma=1)) # 1/8
if len(mag[~flag]) != 0:
pcm2 = ax1.scatter(period[~flag], mag[~flag], s=28, c=pmemb[~flag], \
cmap=newcmp, zorder=4)#, norm=colors.PowerNorm(gamma=1/4))
pcm2.set_facecolor('none')
#ax1.scatter(period, mag, s=15, c='silver', zorder=5)
print(alpha)
label = r'%.3f$\,\pm\,$%.3f'%(mean,err)
ax1.axhline(mean, color='k', ls='--', lw=1.2, zorder=1, label=label)
ax1.axhline(mean+err, color='gray', ls=':', lw=1, zorder=2)
ax1.axhline(mean-err, color='gray', ls=':', lw=1, zorder=2)
ax1.axhline(med+alpha*std, color='gray', ls=':', lw=1, zorder=2)
ax1.axhline(med-alpha*std, color='gray', ls=':', lw=1, zorder=2)
ax1.legend(loc=2, fontsize=13.5)
ax1.invert_yaxis()