-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare_library.py
1908 lines (1491 loc) · 93.1 KB
/
prepare_library.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 python
# coding: utf-8
'''
python libaray for producing the training dataset
@author: Hui Yang huiyang@gwmail.gwu.edu
Created on Tue Oct 12 2021
version 1.0 the minimum version of library for preparation of TD
'''
import numpy as np, pandas as pd, astropy.units as u, pickle
from os import path
from pathlib import Path
from astropy.coordinates import SkyCoord, Angle
from astropy.table import Table
import os
import scipy.special as sc
from astroquery.vizier import Vizier
import sys
from collections import Counter
import math
from astropy import coordinates
#from math import *
from astropy.io import fits
from astroML.crossmatch import crossmatch_angular
from astroquery.gaia import Gaia
from uncertainties import unumpy
from astropy.time import Time
exnum = 975318642
def atnf_pos(coord, e_coord, coord_format='hms', out='pos'):
'''
calculate the coordinates and their uncertainties from ATNF catalog
'''
if coord[0] == "-":
sign = -1.
else:
sign = 1.
colon_count = coord.count(':')
if out == 'pos':
if colon_count == 2:
h,m,s = pd.to_numeric(coord.split(':'))
deg = ((s/60. + m)/60. + np.abs(h))
elif colon_count == 1:
h,m = pd.to_numeric(coord.split(':'))
deg = (m/60. + np.abs(h))
elif colon_count == 0:
deg = np.abs(pd.to_numeric(coord))
if coord_format == 'hms':
return float(sign*deg*15.)
elif coord_format == 'dms':
return float(sign*deg)
elif out == 'err':
if colon_count == 2:
e_deg = float(e_coord)
elif colon_count == 1:
e_deg = float(e_coord)*60.
elif colon_count == 0:
e_deg = float(e_coord)*60.**2
if coord_format == 'hms':
return float(e_deg)*15.
elif coord_format == 'dms':
return float(e_deg)
def create_perobs_data(data, query_dir, data_dir, name_type='CSCview', name_col='name', ra_col='ra',dec_col='dec',coord_format='hms'):
'''
description:
extract the per-observation CSC 2.0 data using ADQL from http://cda.cfa.harvard.edu/csccli/getProperties URL
input:
data: the DataFrame containing the master-level information of CSC 2.0 sources, including names, coordinates
query_dir: the directory to store the per-obs data
data_dir:
name_type: 'CSCview' has prefix 'CXO' while 'VizierCSC' does not for their CSC 2.0 names
name_col & ra_col & dec_col: column name of CSC 2.0 names, right ascension and declination
coord_format: hms or deg format for the coordinates
output:
no output
each individual per-obs data is saved as a txt file in query_dir
the combined per-obs data is saved as a csv file
'''
Path(query_dir).mkdir(parents=True, exist_ok=True)
data['_q'] = data.index + 1
if coord_format == 'hms':
ras = Angle(data[ra_col], 'hourangle').degree
decs = Angle(data[dec_col], 'deg').degree
elif coord_format =='deg':
ras = data[ra_col].values
decs = data[dec_col].values
pu = 0.1
for source, ra, dec, usrid in zip(data[name_col], ras, decs, range(len(ras))):
#print(source, ra, dec)
if name_type == 'CSCview':
src = source[5:].strip()
elif name_type == 'VizierCSC':
src = source[2:-1]#.decode('utf-8')
if not (path.exists(f'{query_dir}/{src}.txt')):
print(src)
ra_low = ra - pu/3600
ra_upp = ra + pu/3600
dec_low = dec - pu/3600
dec_upp = dec + pu/3600
rad_cone = pu/60
f = open(f'{query_dir}/csc_query_cnt_template.adql', "r")
adql = f.readline()
ra_temp = '266.599396'
dec_temp = '-28.87594'
ra_low_temp = '266.5898794490786'
ra_upp_temp = '266.60891255092145'
dec_low_temp = '-28.884273333333333'
dec_upp_temp = '-28.867606666666667'
rad_cone_temp = '0.543215'
for [str1, str2] in [[rad_cone, rad_cone_temp], [ra, ra_temp], [dec, dec_temp], [ra_low, ra_low_temp], [ra_upp, ra_upp_temp], [dec_low, dec_low_temp], [dec_upp, dec_upp_temp]]:
adql = adql.replace(str2, str(str1))
text_file = open(f'{query_dir}/{src}.adql', "w")
text_file.write(adql)
text_file.close()
os.system("curl -o "+query_dir+'/'+src+".txt \
--form query=@"+query_dir+'/'+src+".adql \
http://cda.cfa.harvard.edu/csccli/getProperties")
df_pers = pd.DataFrame()
for source, usrid in zip(data[name_col], range(len(ras))):
#print(usrid,source)
if name_type == 'CSCview':
src = source[5:].strip()
elif name_type == 'VizierCSC':
src = source[2:-1]#.decode('utf-8')
df = pd.read_csv(f'{query_dir}/{src}.txt', header=154, sep='\t')
df['usrid'] = usrid+1
df_pers = df_pers.append(df, ignore_index=True)
#'''
#df_pers.to_csv(query_dir+'../'+field_name+'_per.csv', index=False)
return df_pers
def stats(df, flx='flux_aper90_mean_', end='.1', drop=False):
print("Run stats......")
df = df.fillna(exnum)
s0 = np.where( (df[flx+'h'+end]!=0) & (df[flx+'h'+end]!=exnum) & (df[flx+'m'+end]!=0) & (df[flx+'m'+end]!=exnum) & (df[flx+'s'+end]!=0) & (df[flx+'s'+end]!=exnum) )[0]
s1 = np.where( (df[flx+'h'+end]!=exnum) & (df['e_'+flx+'h'+end]!=exnum) & (df[flx+'m'+end]!=exnum) & (df['e_'+flx+'m'+end]!=exnum) & (df[flx+'s'+end]!=exnum) & (df['e_'+flx+'s'+end]!=exnum) )[0]
s2 = np.where(((df[flx+'h'+end]!=exnum) & (df['e_'+flx+'h'+end]!=exnum) )&((df[flx+'m'+end]!=exnum) & (df['e_'+flx+'m'+end]!=exnum) )&((df[flx+'s'+end]==exnum) | (df['e_'+flx+'s'+end]==exnum) ))[0]
s3 = np.where(((df[flx+'h'+end]==exnum) | (df['e_'+flx+'h'+end]==exnum) )&((df[flx+'m'+end]!=exnum) & (df['e_'+flx+'m'+end]!=exnum) )&((df[flx+'s'+end]!=exnum) & (df['e_'+flx+'s'+end]!=exnum) ))[0]
s4 = np.where(((df[flx+'h'+end]!=exnum) & (df['e_'+flx+'h'+end]!=exnum) )&((df[flx+'m'+end]==exnum) | (df['e_'+flx+'m'+end]==exnum) )&((df[flx+'s'+end]!=exnum) & (df['e_'+flx+'s'+end]!=exnum) ))[0]
s5 = np.where(((df[flx+'h'+end]==exnum) | (df['e_'+flx+'h'+end]==exnum) )&((df[flx+'m'+end]!=exnum) & (df['e_'+flx+'m'+end]!=exnum) )&((df[flx+'s'+end]==exnum) | (df['e_'+flx+'s'+end]==exnum) ))[0]
s6 = np.where(((df[flx+'h'+end]!=exnum) & (df['e_'+flx+'h'+end]!=exnum) )&((df[flx+'m'+end]==exnum) | (df['e_'+flx+'m'+end]==exnum) )&((df[flx+'s'+end]==exnum) | (df['e_'+flx+'s'+end]==exnum) ))[0]
s7 = np.where(((df[flx+'h'+end]==exnum) | (df['e_'+flx+'h'+end]==exnum) )&((df[flx+'m'+end]==exnum) | (df['e_'+flx+'m'+end]==exnum) )&((df[flx+'s'+end]!=exnum) & (df['e_'+flx+'s'+end]!=exnum) ))[0]
s8 = np.where(((df[flx+'h'+end]==exnum) | (df['e_'+flx+'h'+end]==exnum) )&((df[flx+'m'+end]==exnum) | (df['e_'+flx+'m'+end]==exnum) )&((df[flx+'s'+end]==exnum) | (df['e_'+flx+'s'+end]==exnum)))[0]
s9 = np.where( (df[flx+'h'+end]==exnum) | (df['e_'+flx+'h'+end]==exnum) | (df[flx+'m'+end]==exnum) | (df['e_'+flx+'m'+end]==exnum) | (df[flx+'s'+end]==exnum) | (df['e_'+flx+'s'+end]==exnum) )[0]
df = df.replace(exnum, np.nan)
tot = len(df)
df_rows = [('Y','Y','Y',len(s1),int(len(s1)/tot*1000)/10.),
('Y','Y','N',len(s2),int(len(s2)/tot*1000)/10.),
('N','Y','Y',len(s3),int(len(s3)/tot*1000)/10.),
('Y','N','Y',len(s4),int(len(s4)/tot*1000)/10.),
('N','Y','N',len(s5),int(len(s5)/tot*1000)/10.),
('Y','N','N',len(s6),int(len(s6)/tot*1000)/10.),
('N','N','Y',len(s7),int(len(s7)/tot*1000)/10.),
('N','N','N',len(s8),int(len(s8)/tot*1000)/10.),
('~Y','Y','Y',len(s9),int(len(s9)/tot*1000)/10.)]
tt = Table(rows=df_rows, names=('H', 'M', 'S','#','%'))
print(tt)
print('-----------------')
print('total: ',tot)
print("Only ", len(s1), " detections have valid fluxes at all bands.")
if drop==True:
#print("Only ", len(s1), " detections have valid fluxes at all bands.")
df.loc[s9, 'per_remove_code'] = df.loc[s9, 'per_remove_code']+64
print('After dropping', str(len(s9)),'detections with NaNs,', len(df[df['per_remove_code']==0]),'remain.')
return df
elif drop == False:
return df
def flux2symmetric(df, flx='flux_aper90_',bands=['s', 'm','h'],end='.1'):
# calculate the left & right uncertainties, the mean, the variance of the Fechner distribution for band fluxes
# print("Run flux2symmetric......")
for band in bands:
df['e_'+flx+'hilim_'+band+end] = df[flx+'hilim_'+band+end] - df[flx+''+band+end]
df['e_'+flx+'lolim_'+band+end] = df[flx+''+band+end] - df[flx+'lolim_'+band+end]
df[flx+'mean_'+band+end] = df[flx+''+band+end] + np.sqrt(2/np.pi) * (df['e_'+flx+'hilim_'+band+end] - df['e_'+flx+'lolim_'+band+end])
df['e_'+flx+'mean_'+band+end] = np.sqrt((1.- 2./np.pi)* (df['e_'+flx+'hilim_'+band+end] - df['e_'+flx+'lolim_'+band+end])**2 + df['e_'+flx+'hilim_'+band+end]*df['e_'+flx+'lolim_'+band+end])
df = df.drop(['e_'+flx+'hilim_'+band+end, 'e_'+flx+'lolim_'+band+end], axis=1)
return df
def cal_bflux(df, flx='flux_aper90_',end='.1'):
# calculate the mean and the variance of the broad band flux
df[flx+'b'+end] = df[flx+'s'+end]+df[flx+'m'+end]+df[flx+'h'+end]
df['e_'+flx+'b'+end] = np.sqrt(df['e_'+flx+'s'+end]**2+df['e_'+flx+'m'+end]**2+df['e_'+flx+'h'+end]**2)
return df
def powlaw2symmetric(df, cols=['flux_powlaw','powlaw_gamma','powlaw_nh','powlaw_ampl'],end='.1'):
# calculate the left & right uncertainties, the mean, the variance of the Fechner distribution for band fluxes
# print("Run powlaw2symmetric......")
for col in cols:
df['e_'+col+'_hilim'+end] = df[col+'_hilim'+end] - df[col+end]
df['e_'+col+'_lolim'+end] = df[col+end] - df[col+'_lolim'+end]
df[col+'_mean'+end] = df[col+end] + np.sqrt(2/np.pi) * (df['e_'+col+'_hilim'+end] - df['e_'+col+'_lolim'+end])
df['e_'+col+'_mean'+end] = np.sqrt((1.- 2./np.pi)* (df['e_'+col+'_hilim'+end] - df['e_'+col+'_lolim'+end])**2 + df['e_'+col+'_hilim'+end]*df['e_'+col+'_lolim'+end])
df = df.drop(['e_'+col+'_hilim'+end, 'e_'+col+'_lolim'+end], axis=1)
return df
def add_newdata(data, data_dir):
print("Run add_newdata......")
# Adding new data
data['obs_reg'] = data['obsid']*10000+data['region_id']
print('Before adding new data:')
stats(data)
#stats(data[data['per_remove_code']==0])
bands = ['s', 'm', 'h']
files = [f'{data_dir}/newdata/output_gwu_snull.txt_May_29_2020_15_32_39_clean.csv', f'{data_dir}/newdata/output_gwu_mnull.txt_Jun_01_2020_09_36_59_clean.csv', f'{data_dir}/newdata/gwu_hnull_output.txt_May_01_2020_13_16_39_clean.csv']
for band, fil in zip(bands, files):
data_new = pd.read_csv(fil)
data_new['obs'] = data_new['#current_obsid'].str[:5].astype(int)
data_new['obs_reg'] = data_new['obs']*10000+data_new['reg']
data_new = data_new.rename(columns={'mode':'flux_aper90_'+band+'.1', 'lolim':'flux_aper90_lolim_'+band+'.1','hilim':'flux_aper90_hilim_'+band+'.1'})
data_new = flux2symmetric(data_new, flx='flux_aper90_',bands=[band],end='.1')
data_new = data_new.set_index('obs_reg')
data = data.set_index('obs_reg')
#df = data.copy()
data.update(data_new)
#print(np.count_nonzero(data!=df)/3)
data.reset_index(inplace=True)
print('After adding new ',str(len(data_new)), band, 'band data:')
data = stats(data)
#stats(data[data['per_remove_code']==0])
return data
def apply_flags_filter(data, instrument=True,sig=False,theta_flag=True, dup=True, sat_flag=True, pileup_warning=True, streak_flag=True,pu_signa_fil=False,verb=False):
#print("Run apply_flags_filter......")
data= data.fillna(exnum)
if verb:
stats(data[data['per_remove_code']==0])
if instrument:
s = np.where(data['instrument']==' HRC')[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+1
#print('After dropping', str(len(s)),'detections with HRC instrument,', len(data[data['per_remove_code']==0]),'remain.')
if theta_flag:
s = np.where(data['theta']> 10)[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+2
#print('After dropping', str(len(s)),'detections with theta larger than 10\',', len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if sat_flag:
s = np.where(data['sat_src_flag.1'] == True)[0]
#print(str(sorted(Counter(data['Class'].iloc[s]).items())))
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+4
#print("After dropping", len(s), " detections with sat_src_flag = TRUE,", len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if pileup_warning:
s = np.where((data['pileup_warning'] > 0.3) & (data['pileup_warning'] != exnum))[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+8
#print("After dropping", len(s), " detections with pile_warning>0.3,", len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if streak_flag:
s = np.where(data['streak_src_flag.1'] == True)[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+16
#print("After dropping", len(s), " detections with streak_src_flag = TRUE,", len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if dup:
#print(data.groupby(['obsid','region_id','obi']).filter(lambda g: len(g['name'].unique()) > 1) )
s = np.where(data.set_index(['obsid','region_id','obi']).index.isin(data.groupby(['obsid','region_id','obi']).filter(lambda g: len(g['name'].unique()) > 1 ).set_index(['obsid','region_id','obi']).index))[0]
#data.iloc[s].to_csv('dup.csv',index=False)
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+32
#print("After dropping", len(s), " detections assigned to different sources,", len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if pu_signa_fil:
#s = np.where( (data['flux_significance_b']==exnum) | (data['flux_significance_b']==0) | (np.isinf(data['PU'])) | (data['PU']==exnum))[0]
s = np.where( (np.isinf(data['PU'])) | (data['PU']==exnum))[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+64
#print("After dropping", len(s), " detections having nan sig or inf PU,", len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
if sig:
s = np.where(data['flux_significance_b']< sig)[0]
data.loc[s, 'per_remove_code'] = data.loc[s, 'per_remove_code']+1
#print('After dropping', str(len(s)),'detections with flux_significance_b less than', sig, len(data[data['per_remove_code']==0]),'remain.')
if verb:
stats(data[data['per_remove_code']==0])
data = data.replace(exnum, np.nan)
return data
def cal_theta_counts(df, df_ave, theta, net_count, err_count):
#print("Run cal_theta_counts......")
for col in [theta+'_mean', theta+'_median', 'e_'+theta, net_count, err_count]:
df_ave[col] = np.nan
for src in df.usrid.unique():
idx = np.where( (df.usrid == src))[0] # & (df.per_remove_code==0) )[0]
idx2 = np.where(df_ave.usrid == src)[0]
theta_mean = np.nanmean(df.loc[idx, theta].values)
theta_median = np.nanmedian(df.loc[idx, theta].values)
theta_std = np.nanstd(df.loc[idx, theta].values)
counts = np.nansum(df.loc[idx, net_count].values)
e_counts = np.sqrt(np.nansum( [ e**2 for e in df.loc[idx, err_count].values] ))
df_ave.loc[idx2, theta+'_mean'] = theta_mean
df_ave.loc[idx2, theta+'_median'] = theta_median
df_ave.loc[idx2, 'e_'+theta] = theta_std
df_ave.loc[idx2, net_count] = counts
df_ave.loc[idx2, err_count] = e_counts
df_ave.loc[idx2, theta+'_median'] = theta_median
return df, df_ave
def cal_sig(df, df_ave, sig):
#print("Run cal_sig......")
df_ave[sig+'_max'] = np.nan
for src in df.usrid.unique():
idx = np.where( (df.usrid == src) & (df.per_remove_code==0) )[0]
idx2 = np.where(df_ave.usrid == src)[0]
if len(idx)==0:
continue
elif len(idx)==1:
sig_max = df.loc[idx,sig].values
else:
sig_max = np.nanmax(df.loc[idx,sig])
df_ave.loc[idx2, sig+'_max'] = sig_max
return df, df_ave
def cal_cnt(df, df_ave, cnt, cnt_hi, cnt_lo):
df_ave[cnt+'_max'] = np.nan
for src in df.usrid.unique():
idx = np.where( (df.usrid == src) & (df.per_remove_code==0) )[0]
idx2 = np.where(df_ave.usrid == src)[0]
if len(idx)==0:
continue
elif len(idx)==1:
cnt_max = df.loc[idx,cnt].values
cnt_max_hi = df.loc[idx,cnt_hi].values
cnt_max_lo = df.loc[idx,cnt_lo].values
else:
max_ind = np.nanargmax(df.loc[idx,cnt])
cnt_max = df.loc[max_ind, cnt]
cnt_max_hi = df.loc[max_idx, cnt_hi]
cnt_max_lo = df.loc[max_idx, cnt_lo]
#print(cnt_max, np.nanmax(df.loc[idx,cnt]))
df_ave.loc[idx2, cnt+'_max'] = cnt_max
df_ave.loc[idx2, cnt+'_max_hi'] = cnt_max_hi
df_ave.loc[idx2, cnt+'_max_lo'] = cnt_max_lo
return df, df_ave
def cal_aveflux(df, df_ave, bands, flux_name, per_flux_name, fil = False, add2df=False):
#print("Run cal_aveflux......")
for band in bands:
col = flux_name+band
p_col = per_flux_name+band+'.1'
df_ave[col] = np.nan
df_ave['e_'+col] = np.nan
if add2df:
df[col] = np.nan
df['e_'+col] = np.nan
for uid in df.usrid.unique():
if fil==True:
idx = np.where( (~df[p_col].isna()) & (~df['e_'+p_col].isna()) & (df.per_remove_code==0) & (df.usrid==uid) & (df.theta<=10) & (df['sat_src_flag.1']!=True) & (df.pileup_warning<=0.3))[0]
elif fil=='strict':
idx = np.where( (~df[p_col].isna()) & (~df['e_'+p_col].isna()) & (df.per_remove_code==0) & (df.usird==uid) & (df.theta<=10) & (df['sat_src_flag.1']==False) & (df.conf_code<=7) & (df.pileup_warning<=0.1) & (df.edge_code<=1) & (df.extent_code<=0) & (df['streak_src_flag.1']==False) )[0]
else:
idx = np.where( (~df[p_col].isna()) & (~df['e_'+p_col].isna()) & (df.per_remove_code==0) & (df.usrid==uid) )[0]
idx2 = np.where(df_ave.usrid==uid)[0]
if len(idx)==0:
#df_ave.loc[idx2, 'remove_code'] = 1
continue
elif len(idx) ==1:
ave = df.loc[idx, p_col].values
err = df.loc[idx, 'e_'+p_col].values
#df_ave.loc[idx2, col] = ave
#df_ave.loc[idx2, 'e_'+col] = err
else:
ave = np.average(df.loc[idx, p_col].values, weights=1./(df.loc[idx, 'e_'+p_col].values)**2)
err = np.sqrt(1./sum(1./(df.loc[idx, 'e_'+p_col].values)**2))
df_ave.loc[idx2, col] = ave
df_ave.loc[idx2, 'e_'+col] = err
if add2df:
df.loc[idx, col] = ave
df.loc[idx, 'e_'+col] = err
return df, df_ave
def cal_var(df, df_ave, b_ave,b_per):
#print("Run cal_var......")
new_cols = ['chisqr', 'dof', 'kp_prob_b_max','var_inter_prob','significance_max']
for col in new_cols:
df_ave[col] = np.nan
#b_per = 'flux_aper90_mean_b.1'
for uid in sorted(df.usrid.unique()):
idx = np.where( (~df[b_per].isna()) & (~df['e_'+b_per].isna()) & (df.per_remove_code==0) & (df.usrid==uid) )[0]
dof = len(idx)-1.
idx2 = np.where(df_ave.usrid==uid)[0]
df_ave.loc[idx2, 'dof'] = dof
if dof >-1:
df_ave.loc[idx2, 'kp_prob_b_max'] = np.nanmax(df.loc[idx,'kp_prob_b'].values)
df_ave.loc[idx2, 'significance_max'] = np.nanmax(df.loc[idx,'flux_significance_b'].values)
if (dof == 0) or (dof == -1):
continue
chisqr = np.sum((df.loc[idx,b_per].values-df.loc[idx,b_ave].values)**2/(df.loc[idx,'e_'+b_per].values)**2)
df_ave.loc[idx2, 'chisqr']= chisqr
df_ave['var_inter_prob'] = df_ave.apply(lambda row: sc.chdtr(row.dof, row.chisqr), axis=1)
df_ave = df_ave.round({'var_inter_prob': 3})
return df, df_ave
def combine_master(df_ave, bands=['s','m','h']):
print("run combine_master......")
# one revision can be considered is that to change the "remove_code" if some master data replaced are good
for band in bands:
s = np.where((df_ave['flux_aper90_ave_'+band].isna()) & (df_ave['e_flux_aper90_ave_'+band].isna()) & (~df_ave['flux_aper90_mean_'+band].isna()) & (~df_ave['e_flux_aper90_mean_'+band].isna()) & (df_ave['sat_src_flag']!=True) & (df_ave['streak_src_flag']!=True) )[0]#
df_ave.loc[s, 'flux_aper90_ave_'+band] = df_ave.loc[s, 'flux_aper90_mean_'+band]
df_ave.loc[s, 'e_flux_aper90_ave_'+band] = df_ave.loc[s, 'e_flux_aper90_mean_'+band]
print(len(s), "sources at ", band, " band are saved by combing master data.")
df_ave = stats(df_ave, flx='flux_aper90_ave_', end='')
stats(df_ave[df_ave['remove_code']==0], flx='flux_aper90_ave_', end='')
return df_ave
def nan_flux(df_ave, flux_name):
#print("Run nan_flux......")
df_ave['flux_flag'] = 0
for band, code, flux_hilim in zip(['s', 'm', 'h'], [1, 2, 4], [1e-17, 1e-17, 1e-17]):
col = flux_name+band
idx = np.where( (df_ave[col].isna()) | (df_ave['e_'+col].isna()) )[0]
df_ave.loc[idx, col] = np.sqrt(2/np.pi) * flux_hilim
df_ave.loc[idx, 'e_'+col] = np.sqrt((1.- 2./np.pi))* flux_hilim
df_ave.loc[idx, 'flux_flag'] = df_ave.loc[idx, 'flux_flag'] + code
return df_ave
def cal_ave(df, data_dir, dtype='TD', Chandratype='CSC',PU=False,cnt=False,plot=False, verb=False):
'''
description:
calculate the averaged data from per-observation CSC data
input:
df: the DataFrame of per-observation data
dtype: 'TD' for training dataset and 'field' for field (testing) dataset
plot: plot mode
output:
df_ave: the DataFrame of averaged data from per-observation CSC data
df: the per-observation data used to calculate the averaged data
'''
#print("Run cal_ave......")
print('There are',str(len(df)),'per-obs data.')
df = df.fillna(exnum)
df = df.replace(r'^\s*$', exnum, regex=True)
df = df.apply(pd.to_numeric, errors='ignore')
df = df.replace({' TRUE': True, 'False': False, 'FALSE':False})
df = df.replace(exnum, np.nan)
# convert asymmetric fluxes to symmetric fluxes
df = flux2symmetric(df, end='.1')
if Chandratype == 'CSC' or Chandratype=='CSC-CXO':
df = flux2symmetric(df, end='')
df = cal_bflux(df, flx='flux_aper90_mean_',end='')
df = powlaw2symmetric(df, end='')
if dtype == 'TD' and Chandratype=='CSC':
# Adding new data
df = add_newdata(df, data_dir)
df = cal_bflux(df, flx='flux_aper90_mean_',end='.1')
# Apply with some filters on sat_src_flag and pile_warning at per-obs level
if Chandratype=='CSC' or Chandratype=='CSC-CXO':
df = apply_flags_filter(df, verb=verb)# theta_flag=True,dup=True,sat_flag=True,pileup_warning=True,streak_flag=True
elif Chandratype=='CXO':
df = apply_flags_filter(df,theta_flag=True,dup=False,sat_flag=False,pileup_warning=False,streak_flag=False,pu_signa_fil=False,verb=verb)
#'''
#df.to_csv('TD_test.csv',index=False)
if Chandratype=='CSC':
cols_copy = ['name', 'usrid', 'ra', 'dec', 'err_ellipse_r0', 'err_ellipse_r1', 'err_ellipse_ang', 'significance',
'extent_flag', 'pileup_flag','sat_src_flag', 'streak_src_flag','conf_flag',
'flux_aper90_mean_b', 'e_flux_aper90_mean_b', 'flux_aper90_mean_h', 'e_flux_aper90_mean_h',
'flux_aper90_mean_m', 'e_flux_aper90_mean_m', 'flux_aper90_mean_s', 'e_flux_aper90_mean_s',
'kp_intra_prob_b','ks_intra_prob_b','var_inter_prob_b',
'nh_gal','flux_powlaw_mean','e_flux_powlaw_mean','powlaw_gamma_mean','e_powlaw_gamma_mean',
'powlaw_nh_mean','e_powlaw_nh_mean','powlaw_ampl_mean','e_powlaw_ampl_mean','powlaw_stat']
elif Chandratype=='CXO':
cols_copy = ['usrid']
elif Chandratype=='CSC-CXO':
cols_copy = ['COMPONENT','name', 'usrid', 'ra', 'dec', 'err_ellipse_r0', 'err_ellipse_r1', 'err_ellipse_ang', 'significance',
'extent_flag', 'pileup_flag','sat_src_flag', 'streak_src_flag','conf_flag',
'flux_aper90_mean_b', 'e_flux_aper90_mean_b', 'flux_aper90_mean_h', 'e_flux_aper90_mean_h',
'flux_aper90_mean_m', 'e_flux_aper90_mean_m', 'flux_aper90_mean_s', 'e_flux_aper90_mean_s',
'kp_intra_prob_b','ks_intra_prob_b','var_inter_prob_b',
'nh_gal','flux_powlaw_mean','e_flux_powlaw_mean','powlaw_gamma_mean','e_powlaw_gamma_mean',
'powlaw_nh_mean','e_powlaw_nh_mean','powlaw_ampl_mean','e_powlaw_ampl_mean','powlaw_stat']
df = df[df['per_remove_code']==0].reset_index(drop=True)
#df.to_csv('TD_test.csv',index=False)
if PU:
df_ave = df[cols_copy+[PU]].copy()
else:
df_ave = df[cols_copy].copy()
df_ave['prod_per_remove_code'] = 0
for uid in df_ave.usrid.unique():
idx = np.where(df.usrid==uid)[0]
idx2 = np.where(df_ave.usrid==uid)[0]
df_ave.loc[idx2, 'prod_per_remove_code'] = np.prod(df.loc[idx, 'per_remove_code'].values)
df_ave = df_ave.drop_duplicates(subset =['usrid'], keep = 'first')
df_ave = df_ave.reset_index(drop=True)
df_ave['remove_code'] = 0
df_ave.loc[df_ave.prod_per_remove_code>0, 'remove_code'] = 1
df_ave = df_ave.drop('prod_per_remove_code', axis=1)
df, df_ave = cal_sig(df, df_ave, 'flux_significance_b')
if Chandratype=='CXO' or Chandratype=='CSC-CXO':
df, df_ave = cal_theta_counts(df, df_ave, 'theta', 'NET_COUNTS_broad','NET_ERR_broad')
# Calculating average fluxes
df, df_ave = cal_aveflux(df, df_ave,['s','m','h'],'flux_aper90_ave_','flux_aper90_mean_')#fil =False)
df, df_ave = cal_aveflux(df, df_ave,['b'],'flux_aper90_ave2_','flux_aper90_mean_',add2df=True)
# Calculating inter-variability
df, df_ave = cal_var(df, df_ave, 'flux_aper90_ave2_b','flux_aper90_mean_b.1')
df_ave = df_ave.drop(['flux_aper90_ave2_b','e_flux_aper90_ave2_b'],axis=1)
if Chandratype=='CSC' or Chandratype=='CSC-CXO':
# combine additional useful master flux
#df_ave = combine_master(df_ave)
df_ave['ra']= Angle(df_ave['ra'], 'hourangle').degree
df_ave['dec'] = Angle(df_ave['dec'], 'deg').degree
df_ave = nan_flux(df_ave, 'flux_aper90_ave_')
df_ave = cal_bflux(df_ave, 'flux_aper90_ave_',end='')
if cnt:
df, df_ave = cal_cnt(df, df_ave, 'src_cnts_aper90_b','src_cnts_aper90_hilim_b','src_cnts_aper90_lolim_b')
#df_ave.to_csv('ave_test.csv',index=False)
#'''
return df_ave, df
def MW_counterpart_confusion(ras, decs, R, Es=[], N=10, catalog='wise',ref_mjd=5.e4, pm_cor=False, confusion=True, second_nearest=False):
'''
input:
radec: [[Ra1, Dec1], [Ra2, Dec2], ..., [Ran, Decn]] or [Ra, Dec] (degrees)
R: searching radius for estimating density (arcs)
E: source position uncertainties [E1, E2, ..., En] (arcs, optional)
N: multiple of the nearest source outside of error circle defined as the outer boundary of the area to estimate field density
catalog: '2mass' or 'gaiadr2' or 'wise'
output: a DataFrame table containing
d_nr: distance to the nearest source outside error circle
d_out: outer boundary of the circle to estimate field density
num: number of sources within the circle to estimate density
rho: field density
_q: index of the source
prob: chance coincidence probability
prob_log: logarithmic of chance coincidence probability
'''
cats = {
'gaia': 'I/350/gaiaedr3',
'gaiadist': 'I/352/gedr3dis',
'2mass': 'II/246/out',
'catwise': 'II/365/catwise',
'unwise': 'II/363/unwise',
'allwise': 'II/328/allwise',
'vphas': 'II/341'
}
cols = {
'gaia': ['RAJ2000', 'DEJ2000', 'Gmag', 'e_Gmag', 'BPmag', 'e_BPmag', 'RPmag', 'e_RPmag','Plx', 'e_Plx', 'PM', 'pmRA', 'e_pmRA', 'pmDE'],#, 'e_pmDE'],
'gaiadist': ['RAJ2000', 'DEJ2000', 'rgeo', 'rpgeo'],
'2mass': ['RAJ2000', 'DEJ2000', 'Jmag', 'e_Jmag', 'Hmag', 'e_Hmag', 'Kmag', 'e_Kmag'],
'catwise': ['RAJ2000', 'DEJ2000','W1mproPM','e_W1mproPM','W2mproPM','e_W2mproPM','pmRA','e_pmRA','pmDE','e_pmDE'],
'unwise': ['RAJ2000', 'DEJ2000','FW1','e_FW1','FW2','e_FW2'],
'allwise': ['RAJ2000', 'DEJ2000', 'W1mag', 'e_W1mag', 'W2mag', 'e_W2mag', 'W3mag', 'e_W3mag', 'W4mag', 'e_W4mag']
}
# astroquery match
# gaia: RA_ICRS DE_ICRS at Ep=2016.0; gaiadist: RA_ICRS DE_ICRS at Ep=2016.0
# 2mass: RAJ2000 DEJ2000 at Ep=2000.0; catwise: RA_ICRS DE_ICRS at unknown epoch, change to RAPMdeg DEPMdeg at Ep=2015.4
# unwise: RAJ2000 DEJ2000 at Ep=2000.0; allwise: RAJ2000 DEJ2000 at Ep=2000.0
# vphas: RAJ2000 DEJ2000 at Ep=2000.0
pu_cols = {
'gaia':'e_DE_ICRS', # in mas
'2mass':'errMaj', # in arcsec
'catwise': 'e_DE_ICRS', # in arcsec
'allwise': 'eeMaj' }# in arcsec
if catalog not in cats:
sys.exit(f"wrong catalog name, should be {' or '.join(cats)}")
viz = Vizier(row_limit=-1, timeout=5000, columns=["**", "+_r"], catalog=cats[catalog])
df_rho = pd.DataFrame(columns=['_rs'])#'d_nr','d_out','num','rho','prob','_q','_rs'])
df_MW = pd.DataFrame(columns=['_q'])#+cols[catalog])
if len(Es)==1:
Es = Es*len(ras)
radec = [[ras[i], decs[i]] for i in range(len(ras))]
rd = Table(Angle(radec, 'deg'), names=('_RAJ2000', '_DEJ2000'))
#print(rd)
print('cross-matching to',catalog)
if confusion:
query_res = viz.query_region(rd, radius=R*u.arcsec)[0]
else:
query_radius = 10.
query = viz.query_region(rd, radius=query_radius*u.arcsec)
while len(query)==0:
query_radius +=10
print('updating query radius to',query_radius)
query = viz.query_region(rd, radius=query_radius*u.arcsec)
query_res = query[0]
df = query_res.to_pandas()
if catalog == 'gaia':
df['ra_X'] = df.apply(lambda row: ras[row._q-1],axis=1)
df['dec_X'] = df.apply(lambda row: decs[row._q-1],axis=1)
print('cross-matching to gaiadist')
viz = Vizier(row_limit=-1, timeout=5000, columns=["**", "+_r"], catalog=cats['gaiadist'])
query_radius = 10.
query = viz.query_region(rd, radius=query_radius*u.arcsec)
while len(query)==0:
query_radius +=10
print('updating query radius to',query_radius)
query = viz.query_region(rd, radius=query_radius*u.arcsec)
query_res = query[0]
df_gaiadist = query_res.to_pandas()
#'''
if pm_cor == True and catalog == 'gaia':
gaia_ref_mjd = 57388.
delta_yr = (ref_mjd - gaia_ref_mjd)/365.
df['RA_pmcor'] = df.apply(lambda row:row.RA_ICRS+delta_yr*row.pmRA/(np.cos(row.DE_ICRS*np.pi/180.)*3.6e6),axis=1)
df['DEC_pmcor'] = df.apply(lambda row:row.DE_ICRS+delta_yr*row.pmDE/3.6e6,axis=1)
df.loc[df['RA_pmcor'].isnull(),'RA_pmcor'] = df['RA_ICRS']
df.loc[df['DEC_pmcor'].isnull(),'DEC_pmcor'] = df['DE_ICRS']
df.loc[:, '_r_nopmcor'] = df['_r']
df['_r'] = df.apply(lambda row: SkyCoord(row.RA_pmcor*u.deg, row.DEC_pmcor*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
if pm_cor ==False and catalog == 'gaia':
df['_r'] = df.apply(lambda row: SkyCoord(row.RA_ICRS*u.deg, row.DE_ICRS*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
#if catalog == 'catwise':
#df['_r'] = df.apply(lambda row: SkyCoord(row.RAPMdeg*u.deg, row.DEPMdeg*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
'''
if pm_cor == True and catalog == 'catwise':
catwise_ref_mjd = 57170.
delta_yr = (ref_mjd - catwise_ref_mjd)/365.
df['RA_pmcor'] = df.apply(lambda row:row.RAPMdeg+delta_yr*row.pmRA/(np.cos(row.DEPMdeg*np.pi/180.)*3.6e3),axis=1)
df['DEC_pmcor'] = df.apply(lambda row:row.DEPMdeg+delta_yr*row.pmDE/3.6e3,axis=1)
df['_r'] = df.apply(lambda row: SkyCoord(row.RA_pmcor*u.deg, row.DEC_pmcor*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
df.loc[:, '_r_nopmcor'] = df['_r']
df['_r'] = df.apply(lambda row: SkyCoord(row.RA_pmcor*u.deg, row.DEC_pmcor*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
if pm_cor == True and catalog == 'allwise':
allwise_ref_mjd = 55400.
delta_yr = (ref_mjd - allwise_ref_mjd)/365.
df['RA_pmcor'] = df.apply(lambda row:row.RA_pm+delta_yr*row.pmRA/(np.cos(row.DE_pm*np.pi/180.)*3.6e6),axis=1)
df['DEC_pmcor'] = df.apply(lambda row:row.DE_pm+delta_yr*row.pmDE/3.6e6,axis=1)
df.loc[:, '_r_nopmcor'] = df['_r']
df['_r'] = df.apply(lambda row: SkyCoord(row.RA_pmcor*u.deg, row.DEC_pmcor*u.deg, frame='icrs').separation(SkyCoord(row.ra_X*u.deg, row.dec_X*u.deg, frame='icrs')).arcsecond,axis=1)
'''
for i, e in zip(range(len(ras)), Es):
#print(i,e)
df_sub = df.loc[df['_q']==i+1].reset_index(drop=True)
df_sub = df_sub.sort_values(by=['_r']).reset_index(drop=True)
#nr_bk = min(df_sub.loc[df_sub['_r']> e, '_r'])
if confusion:
try:
nr_bk = min(df_sub.loc[df_sub['_r']> e, '_r'])
except ValueError:
#df_sub.to_csv('MW_test.csv')
#print(i,e)
continue
bk_out = max(min(R, nr_bk*N), 30)
#bk_out = min(R, nr_bk*N)
num_bk = len(df_sub.loc[df_sub['_r']< bk_out])
rho_bk = num_bk/(np.pi*(bk_out**2))
chance_prob = 1. - np.exp(-rho_bk*(np.pi*e**2))
'''
if catalog in pu_cols:
cat_pu_median = 2.*np.median(df_sub[pu_cols[catalog]].values)
if catalog == 'gaia':
cat_pu_median = cat_pu_median/1.e3
df_sub['pu_median'] = cat_pu_median
e = np.sqrt(e**2+cat_pu_median**2)
else:
print(catalog, ' does not count PU in X-ray PUs.')
'''
rs = df_sub.loc[df_sub['_r']<10.,'_r'].tolist()
new_row = {'d_nr':nr_bk,'d_out':bk_out,'num':num_bk,'rho':rho_bk,'prob':chance_prob,'_q':i+1,'_rs':rs}
#if len(df_sub.loc[df_sub['_r']<=2.*e]) >0:
else:
rs = df_sub.loc[df_sub['_r']<10.,'_r'].tolist()
new_row = {'_q':i+1,'_rs':rs}
df_rho = df_rho.append(new_row, ignore_index=True)
if second_nearest:
try:
df_cp = df_sub.loc[df_sub['_r']==sorted(df_sub['_r'].values)[1]]
except IndexError:
continue
else:
try:
df_cp = df_sub.loc[df_sub['_r']==min(df_sub['_r'].values)]
except ValueError:
#print(i,e)
continue
if catalog == 'gaia':
df_cp = df_cp.drop(columns=['ra_X','dec_X'])
#print(df_cp)
#df_MW.append(df_counter, ignore_index=True)
df_MW = pd.concat([df_MW, df_cp])
df_MW = df_MW.drop_duplicates(subset=['_q'])
if confusion:
df_rho['prob_log'] = np.log10(df_rho['prob'])
df_MWs = pd.merge(df_rho, df_MW, how='outer', on=['_q', '_q'])
df_MWs = df_MWs.add_suffix('_'+catalog)
df_MWs = df_MWs.rename(columns= {'_q_'+catalog: '_q'} )
if catalog == 'gaia':
df_gaiadist = df_gaiadist.add_suffix('_gaiadist')
df_gaiadist = df_gaiadist.rename(columns= {'Source_gaiadist':'Source_gaia','_q_gaiadist':'_q'})
df_MWs = df_MWs[df_MWs['EDR3Name_gaia'].notna()]
df_MWs['Source_gaia'] = df_MWs.apply(lambda row: np.int64(row.EDR3Name_gaia[10:]), axis=1)
#print(df_MWs[['Source_gaia','_q']], df_gaiadist[['Source_gaia','_q']])
df_MWs = pd.merge(df_MWs, df_gaiadist, how="left", on=["Source_gaia","_q"])
#print(df_MWs)
#df_MWs = df_MWs.rename(columns= {'RAJ2000':'RAJ2000_'+catalog, 'DEJ2000':'DEJ2000_'+catalog, '_r': '_r_'+catalog} )
return df_MWs
def add_MW(df, file_dir, field_name, Chandratype='CSC',ref_mjd=5.e4,pm_cor=False,confusion=False):
#data = data[0:3]
if path.exists(f'{file_dir}/{field_name}_MW.csv') == True:
data_MW_old = pd.read_csv(f'{file_dir}/{field_name}_MW.csv')
data = df.loc[~df.name.isin(data_MW_old.name)].reset_index(drop=True)
idx_old = data_MW_old.index[data_MW_old.name.isin(df.name)]
data_old = data_MW_old.loc[idx_old].reset_index(drop=True)
else:
data = df
#print(len(data))
#print(data)
if (len(data) == 0) and (len(data_MW_old) > len(idx_old)):
print(len(data), len(data_MW_old), len(idx_old))
for cat in ['gaia','2mass','catwise','unwise','allwise']:
df_MW_old = pd.read_csv(f'{file_dir}/{field_name}_{cat}.csv')
print(len(df_MW_old))
df_MW_old = df_MW_old.loc[df_MW_old._q.isin(data_old._q)].reset_index(drop=True)
#df_MW.to_csv(file_dir+'/'+field_name+'_'+cat+'_new.csv', index=False)
df_MW_old.to_csv(f'{file_dir}/{field_name}_{cat}.csv', index=False)
data_old.to_csv(file_dir+'/'+field_name+'_MW.csv', index=False)
if len(data) > 0:
if Chandratype == 'CSC':
ras = data['ra'].values
decs = data['dec'].values
Es = data['err_ellipse_r0'].values
elif Chandratype == 'CXO' or Chandratype=='CSC-CXO':
ras = data['RA'].values
decs = data['DEC'].values
Es = data['PU'].values
data = data.reset_index(drop=True)
if path.exists(f'{file_dir}/{field_name}_MW.csv') == True:
data['_q'] = data.index + 1 + len(data_MW_old)
else:
data['_q'] = data.index + 1
search_radius = 300 # arcsec
sig_nr = 10
#print(ras,decs)
#for cat, confusion,second_nearest in zip(['gaia','gaiadist','2mass','catwise','unwise','allwise'], [False]*6,[True]+5*[False]):
for cat, conf in zip(['gaia','2mass','catwise','unwise','allwise'], [confusion]*5):#,True,True,True,True,True,False]):
# For field data NGC 3532, we should not match to gaiadist so that we don't have to remove those match to gaiadist but no gaia matched later.
#print(cat, confusion)
df_MW = MW_counterpart_confusion(ras, decs, search_radius, Es=Es, N=sig_nr, catalog=cat,ref_mjd=ref_mjd,pm_cor=pm_cor,confusion=conf)
if path.exists(f'{file_dir}/{field_name}_{cat}.csv') == False:
#df_MW = MW_counterpart_confusion(ras, decs, search_radius, Es=Es, N=sig_nr, catalog=cat,ref_mjd=ref_mjd,pm_cor=pm_cor,confusion=confusion)
df_MW.to_csv(file_dir+'/'+field_name+'_'+cat+'.csv', index=False)
else:
#if len(ras)
df_MW_old = pd.read_csv(f'{file_dir}/{field_name}_{cat}.csv')
df_MW_old = df_MW_old.loc[df_MW_old._q.isin(data_old._q)].reset_index(drop=True)
#df_MW_old = df_MW_old.loc[idx_old].reset_index(drop=True)
df_MW = df_MW.drop_duplicates(subset=['_q'])
df_MW['_q'] = df_MW['_q']+len(data_MW_old)
#df_MW.to_csv(file_dir+'/'+field_name+'_'+cat+'_new.csv', index=False)
df_MW_all = df_MW_old.append(df_MW, ignore_index=True)
#df_MW_all['_q'] = df_MW_all.index+1
df_MW_all.to_csv(f'{file_dir}/{field_name}_{cat}.csv', index=False)
data = pd.merge(data, df_MW, how='outer', on=['_q', '_q'])
if path.exists(f'{file_dir}/{field_name}_MW.csv') == True:
#data.to_csv(file_dir+'/'+field_name+'_MW_new.csv', index=False)
data_all = data_old.append(data,ignore_index=True)
#data_all['_q'] = data_all.index+1
data_all.to_csv(f'{file_dir}/{field_name}_MW.csv', index=False)
else:
data.to_csv(f'{file_dir}/{field_name}_MW.csv', index=False)
def counterpart_clean(df, X_PU='PU',catalog='gaia',X_mjd=57388.,pu_factor=1.5,pm_cor=True,r2=False):
'''
description
drop counterparts outside pu_factor * X-ray PUs in 95% confidence level where X-ray PUs are taking into account of MU PUs, proper motion uncertainties, parallaxes (and their uncertainties), astrometric noises, if any of those are available; flag suspicious counterparts if they are outside 95% PUs or other counterparts are also near the X-ray sources
'''
# astroquery match
# gaia: RA_ICRS DE_ICRS at Ep=2016.0 (MJD 57388); gaiadist: RA_ICRS DE_ICRS at Ep=2016.0
# 2mass: RAJ2000 DEJ2000 between 1997 June (MJD 50600) and 2001 Feb 15 (MJD 51955); catwise: RA_ICRS DE_ICRS at unknown epoch, change to RAPMdeg DEPMdeg at Ep=2015.4 (MJD 57170)
# unwise: RAJ2000 DEJ2000 between 2009 Dec (MJD 55166) and 2011 Feb (MJD 55593), 2013 Dec (MJD 56627) and 2017 Dec (58088); allwise: RAJ2000 DEJ2000 between 2010 Jan 7 (MJD 55203) and 2010 Aug 6 (MJD 55414), and 2010 Sep 29 (MJD 55468) and 2011 Feb 1 (MJD 55593)
# vphas: RAJ2000 DEJ2000 between 2011 Dec 28 (MJD 55923) and 2013 Sep (MJD 56536).
mjd_difs = {'gaia':X_mjd-57388.,'gaiadist':X_mjd-57388.,'2mass':max(abs(X_mjd-50600),(X_mjd-51955)),'catwise':X_mjd-57170.0,
'unwise':max(abs(X_mjd-55203.),abs(X_mjd-55593.),abs(X_mjd-56627),abs(X_mjd-58088)),
'allwise':max(abs(X_mjd-55203.),abs(X_mjd-55414.),abs(X_mjd-55468),abs(X_mjd-55593)),
'vphas':max(abs(X_mjd-55923),abs(X_mjd-56536))
}
df['PU_'+catalog] = 0.
# CU: Coordinate uncertainty
if catalog == 'gaia':
df['PU_CU_'+catalog] = df.apply(lambda row: max(row.e_RA_ICRS_gaia, row.e_DE_ICRS_gaia)*2./1.e3, axis=1)
elif catalog == 'gaiadist':
df['PU_CU_'+catalog] = df['PU_CU_gaia']
elif catalog == '2mass':
df['PU_CU_'+catalog] = df['errMaj_2mass']*2.
elif catalog == 'catwise':
df['PU_CU_'+catalog] = df.apply(lambda row: max(row.e_RA_ICRS_catwise, row.e_DE_ICRS_catwise)*2., axis=1)
elif catalog == 'unwise':
df['PU_CU_'+catalog] = df.apply(lambda row: max(row.e_XposW1_unwise,row.e_XposW2_unwise,row.e_YposW1_unwise,row.e_YposW2_unwise)*2.75*2., axis=1)
elif catalog =='allwise':
df['PU_CU_'+catalog] = df['eeMaj_allwise']*2.
elif catalog =='vphas':
df['PU_CU_'+catalog] = 0.1
df['PU_'+catalog] = df['PU_'+catalog] + df['PU_CU_'+catalog].fillna(0.)**2
# Proper motion uncertainty:
df['e_PM_gaia'] = np.sqrt(df['e_pmRA_gaia']**2+df['e_pmDE_gaia']**2)
if catalog == '2mass':
df['MJD_2mass'] = df.apply(lambda row: Time(row.Date_2mass, format='isot').to_value('mjd', 'long') if pd.notnull(row.Date_2mass) else row, axis=1)
df['MJD_2mass'] = pd.to_numeric(df['MJD_2mass'], errors='coerce')
df['PU_PM_'+catalog] = df.apply(lambda row: row.PM_gaia*(row.MJD_2mass-X_mjd)/(365.*1e3),axis=1)
df['PU_e_PM_'+catalog] = df.apply(lambda row: row.e_PM_gaia*(row.MJD_2mass-X_mjd)*2/(365.*1e3),axis=1)
elif catalog=='catwise':
df['PU_PM_'+catalog] = df.apply(lambda row: row.PM_gaia*(float(row.MJD_catwise)-X_mjd)/(365.*1e3),axis=1)
df['PU_e_PM_'+catalog] = df.apply(lambda row: row.e_PM_gaia*(row.MJD_catwise-X_mjd)*2/(365.*1e3),axis=1)
elif catalog=='vphas':
df['PU_PM_'+catalog] = df.apply(lambda row: row.PM_gaia*(float(row.MJDu_vphas)-X_mjd)/(365.*1e3),axis=1)
df['PU_e_PM_'+catalog] = df.apply(lambda row: row.e_PM_gaia*(row.MJDu_vphas-X_mjd)*2/(365.*1e3),axis=1)
else:
#if catalog != 'gaia':
df['PU_PM_'+catalog] = df['PM_gaia']*mjd_difs[catalog]/(365.*1e3)
df['PU_e_PM_'+catalog] = df['e_PM_gaia']*2.*mjd_difs[catalog]/(365.*1e3)
if catalog != 'gaia':
df['PU_'+catalog] = df['PU_'+catalog] + df['PU_PM_'+catalog].fillna(0.)**2
if catalog == 'gaia' and pm_cor==False:
df['PU_'+catalog] = df['PU_'+catalog] + df['PU_PM_'+catalog].fillna(0.)**2
df['PU_'+catalog] = df['PU_'+catalog] + df['PU_e_PM_'+catalog].fillna(0.)**2