-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyt_IM04b_photometric_calibration_file_list.py
1908 lines (1779 loc) · 137 KB
/
pyt_IM04b_photometric_calibration_file_list.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, sys
import datetime
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.colors as mcolors
import scipy
from scipy.stats import norm
import glob, bz2, subprocess
import os.path
from astropy.io import fits
from astropy.io.fits import getheader
from astropy.wcs import WCS
from astropy.time import Time, TimeDelta
from astropy.io.votable import parse_single_table, VOTableSpecWarning, VOWarning
from astropy.table import Table
from astropy import units as u
from astropy.coordinates import SkyCoord
from decimal import *
import sqlite3
from sqlite3 import Error
import jdcal
from jdcal import gcal2jd,jd2gcal
import statistics
from uncertainties import unumpy,ufloat
from uncertainties.umath import *
from uncertainties.unumpy import *
import smtplib, ssl
import macadamia_functions as mcd
### Edit History ###
# 2021-06-30: Added new logging functionality; made separate function for multiap photometry for each aperture
# 2021-06-30: Removed per-function notification emails for individual image processing failures
##### FUNCTION DEFINITIONS -- DATABASE -- RETRIEVE DATA #####
def retrieve_instrument_id(sqlite_file,instrument_name,thread_idx,keep_going,path_logfile,path_errorfile):
# Retrieve instrument_id corresponding to a given instrument name
instrument_id = -1
if keep_going:
mcd.output_log_entry(path_logfile,'Retrieving instrument ID for {:s} from database...'.format(instrument_name))
try:
conn = mcd.create_connection(sqlite_file) # Open connection to database file
cursor = conn.cursor()
query = "SELECT instrument_id FROM instruments WHERE instrument_name='{:s}'".format(instrument_name)
cursor.execute(query)
mcd.output_log_entry(path_logfile,query)
row = cursor.fetchone()
if row != None:
instrument_id = int(row[0])
mcd.output_log_entry(path_logfile,'instrument_id={:d}'.format(instrument_id))
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Instrument {:s} not found.'.format(instrument_name))
keep_going = False
conn.close() # Close connection to database file
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: retrieve_instrument_id()'.format(instrument_name))
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: retrieve_instrument_id()')
return instrument_id,keep_going
def retrieve_mosaic_element_id(sqlite_file,instrument_id,instrument_name,mosaic_element_num,thread_idx,keep_going,path_logfile,path_errorfile):
# Retrieve mosaic_element_id corresponding to a given mosaic element for a given instrument
mosaic_element_id = -1
if keep_going:
mcd.output_log_entry(path_logfile,'Retrieving mosaic element ID from database...')
try:
conn = mcd.create_connection(sqlite_file) # Open connection to database file
cursor = conn.cursor()
query = "SELECT mosaic_element_id FROM mosaic_elements WHERE instrument_id={:d} AND mosaic_element_num={:d}".format(instrument_id,mosaic_element_num)
cursor.execute(query)
mcd.output_log_entry(path_logfile,query)
row = cursor.fetchone()
if row != None:
mosaic_element_id = int(row[0])
mcd.output_log_entry(path_logfile,'Mosaic element {:d} (mosaic_element_id={:d}) found for {:s}.'.format(mosaic_element_num,mosaic_element_id,instrument_name))
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Mosaic element {:d} for {:s} not found.'.format(mosaic_element_num,instrument_name))
keep_going = False
conn.close() # Close connection to database file
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}, Ext {:d}: retrieve_mosaic_element_id()'.format(instrument_name,mosaic_element_num))
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: retrieve_mosaic_element_id()')
return mosaic_element_id,keep_going
##### FUNCTION DEFINITIONS -- EXTRACT IMAGE METADATA #####
def process_date_tai_sdss(date_tai):
date_tai_formatted = date_tai
if date_tai[0:2].isnumeric() and date_tai[2] == '/' and date_tai[3:5].isnumeric() and date_tai[5] == '/' and date_tai[6:8].isnumeric:
if int(date_tai[6:8]) > 20: year = '19' + date_tai[6:8]
else: year = '20' + date_tai[6:8]
date_tai_formatted = year + '-' + date_tai[3:5] + '-' + date_tai[0:2]
return date_tai_formatted
def extract_header_info_sdss(fits_filename,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Extract header information from SDSS image file
headerinfo = ['',0,'',0,'',0,0,0,0,0,1,1,0,0,0,0]
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Extracting header info from {:s}...'.format(fits_filename))
hdulist = fits.open(fits_filename)
hdr = hdulist[0].header
data = hdulist[0].data
date_tai = hdr['DATE-OBS']
exposure_end_tai = hdr['TAIHMS']
exposure_time = float(hdr['EXPTIME'])
pointing_center_ra = float(hdr['RA'])
pointing_center_dec = float(hdr['DEC'])
date_tai = process_date_tai_sdss(date_tai)
t_end = Time('{:s} {:s}'.format(date_tai,exposure_end_tai),scale='tai',format='iso')
dt = TimeDelta(exposure_time,format='sec')
t_start = t_end - dt
exposure_start_tai = t_start.iso[11:]
exposure_start_jd = float(t_start.jd)
filter_name = fits_filename[6:7]
airmass = 1 / np.sin(float(hdr['ALT'])/180*math.pi)
tracking_rate_ra = float(0)
tracking_rate_dec = float(0)
binning_x = int(hdr['COLBIN'])
binning_y = int(hdr['ROWBIN'])
ra_deg = float(hdr['CRVAL1'])
dec_deg = float(hdr['CRVAL2'])
exp_npix_y,exp_npix_x = data.shape
mcd.output_log_entry(path_logfile,'Extracting header info done.')
headerinfo = [date_tai,exposure_start_jd,exposure_start_tai,exposure_time,filter_name,airmass,pointing_center_ra, \
pointing_center_dec,tracking_rate_ra,tracking_rate_dec,binning_x,binning_y,exp_npix_x,exp_npix_y,ra_deg,dec_deg]
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: extract_header_info_sdss()'.format(fits_filename))
print(e)
if os.path.exists(fits_filename[:-5]+'.photfailed'):
with open(fits_filename[:-5]+'.photfailed','a') as f:
f.write('{:s} - SDSS header info extraction using extract_header_info_sdss() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename[:-5]+'.photfailed','w') as f:
f.write('{:s} - SDSS header info extraction using extract_header_info_sdss() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'SDSS header info extraction using extract_header_info_sdss() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: extract_header_info_sdss()')
return headerinfo,proc_status,keep_going
##### FUNCTION DEFINITIONS -- ASTROMETRIC FUNCTIONS #####
def compute_wcs_pixel_scale(fits_file):
wcs_pixscale_x,wcs_pixscale_y = -1,-1
try:
ra1,dec1 = mcd.get_radec_from_pixel_coords(fits_file,1,1)
ra2,dec2 = mcd.get_radec_from_pixel_coords(fits_file,1001,1)
ra3,dec3 = mcd.get_radec_from_pixel_coords(fits_file,1,1001)
wcs_pixscale_x = mcd.compute_angular_dist_radec(ra1,dec1,ra2,dec2)/1000*3600
wcs_pixscale_y = mcd.compute_angular_dist_radec(ra1,dec1,ra3,dec3)/1000*3600
except:
print('{:s} - Function failed: compute_wcs_pixel_scale()'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
return wcs_pixscale_x,wcs_pixscale_y
def get_radec_from_pixel_coords_array(fits_filename_wcs,field_source_table,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Convert pixel coordinates to RA/Dec using WCS information
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Converting pixel coordinates to RA/Dec using WCS information for {:s}...'.format(fits_filename_wcs))
header = fits.getheader(fits_filename_wcs)
w = WCS(header)
ra_array,dec_array = w.wcs_pix2world(field_source_table['x_t'],field_source_table['y_t'],1)
field_source_table['RA'] = ra_array
field_source_table['Dec'] = dec_array
field_source_table['ps1_RA'] = -999.0
field_source_table['ps1_Dec'] = -999.0
field_source_table['gp1_mag'] = -999.0
field_source_table['gp1_err'] = -999.0
field_source_table['rp1_mag'] = -999.0
field_source_table['rp1_err'] = -999.0
field_source_table['ip1_mag'] = -999.0
field_source_table['ip1_err'] = -999.0
field_source_table['zp1_mag'] = -999.0
field_source_table['zp1_err'] = -999.0
field_source_table['g_sdss_mag'] = -999.0
field_source_table['g_sdss_err'] = -999.0
field_source_table['r_sdss_mag'] = -999.0
field_source_table['r_sdss_err'] = -999.0
field_source_table['i_sdss_mag'] = -999.0
field_source_table['i_sdss_err'] = -999.0
field_source_table['z_sdss_mag'] = -999.0
field_source_table['z_sdss_err'] = -999.0
field_source_table['B_mag'] = -999.0
field_source_table['B_err'] = -999.0
field_source_table['V_mag'] = -999.0
field_source_table['V_err'] = -999.0
field_source_table['Rc_mag'] = -999.0
field_source_table['Rc_err'] = -999.0
field_source_table['Ic_mag'] = -999.0
field_source_table['Ic_err'] = -999.0
field_source_table['target_dist'] = -999.0
field_source_table['zero_point'] = -999.0
field_source_table['zpoint_err'] = -999.0
mcd.output_log_entry(path_logfile,'Converting pixel coordinates done.')
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: get_radec_from_pixel_coords_array()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - RA/Dec computation from pixel coordinate array using get_radec_from_pixel_coords_array() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - RA/Dec computation from pixel coordinate array using get_radec_from_pixel_coords_array() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'RA/Dec computation from pixel coordinate array failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: get_radec_from_pixel_coords_array()')
return field_source_table,proc_status,keep_going
##### FUNCTION DEFINITIONS -- SOURCE EXTRACTION #####
def measure_skylevel_stddev(fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
sky_mean,sky_stddev = 0.0,0.0
if keep_going:
try:
image_data = fits.getdata(fits_filename_wcs)
data_min = np.min(image_data)
data_median = np.median(image_data)
data_max = data_median + (data_median - data_min)
data_array = image_data.flatten()
data_array.sort(axis=0)
num_pixels = len(data_array)
idx,max_pix_value = 0,0
while idx < num_pixels and max_pix_value < data_max:
max_pix_value = data_array[idx]
idx += 1
num_pix_clipped = idx-1
data_clipped = [0 for idx in range(num_pix_clipped)]
for idx in range(0,num_pix_clipped):
data_clipped[idx] = data_array[idx]
sky_mean = np.mean(data_clipped)
sky_stddev = np.std(data_clipped)
mcd.output_log_entry(path_logfile,'Sky level measured: mean={:.10f}, stddev={:.10f}'.format(sky_mean,sky_stddev))
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: measure_skylevel_stddev()'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Sky level measurement using measure_skylevel_stddev() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Sky level measurement using measure_skylevel_stddev() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Sky level measurement using measure_skylevel_stddev() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: measure_skylevel_stddev()')
return sky_mean,sky_stddev,proc_status,keep_going
def extract_sources_sdss(sky_stddev,fits_filename_wcs,fits_filestem,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Run tphot to extract sources using both 2D Waussian fits and trailed Waussian fits
output_path_stars,output_path_trails,output_path_moments,output_path_source_list = '','','',''
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Running tphot to extract sources from {:s} ...'.format(fits_filename_wcs))
output_path_stars = fits_filestem + '_wcs.stars'
output_path_trails = fits_filestem + '_wcs.trails'
output_path_moments = fits_filestem + '_wcs.moments'
output_path_source_list = fits_filestem + '_wcs.srclist'
tphot_cmd = ''
if os.path.isfile('/Users/hhsieh/Astro/tools/tphot/tphot'):
tphot_cmd = '/Users/hhsieh/Astro/tools/tphot/tphot'
elif os.path.isfile('/home/hhsieh/tools/tphot/tphot'):
tphot_cmd = '/home/hhsieh/tools/tphot/tphot' # on pohaku
elif os.path.isfile('/atlas/bin/tphot'):
tphot_cmd = '/atlas/bin/tphot' # on atlas
cmd_bias = '-1000' # needed for SDSS because skymean ~ 0
cmd_border = '25'
cmd_net = '{:.3f}'.format(sky_stddev)
cmd_min = '{:.3f}'.format(sky_stddev)
cmd_snr = '3'
cmd_move = '10'
cmd_okfit = '0'
# extract sources using two-dimensional Waussian fits
cmd = [tphot_cmd,fits_filename_wcs,'-snr',cmd_snr,'-bias',cmd_bias,'-border',cmd_border,'-net',cmd_net,'-min',cmd_min,'-move',cmd_move,'-okfit',cmd_okfit,'-out','temp.out']
mcd.output_log_entry(path_logfile,'{:s} {:s} -snr {:s} -bias {:s} -border {:s} -net {:s} -min {:s} -move {:s} -okfit {:s} -out temp.out'.format(tphot_cmd,fits_filename_wcs,cmd_snr,cmd_bias,cmd_border,cmd_net,cmd_min,cmd_move,cmd_okfit))
process = subprocess.call(cmd)
cmd = ['sort','-g','-r','-k','3','temp.out']
mcd.output_log_entry(path_logfile,'sort -g -r -k 3 temp.out')
with open('temp.srt','w') as of:
process = subprocess.call(cmd,stdout=of)
cmd = [tphot_cmd,fits_filename_wcs,'-obj','temp.srt','-out',output_path_stars,'-moment',output_path_moments,'-subtract','-snr',cmd_snr,'-bias',cmd_bias,'-border',cmd_border,'-net',cmd_net,'-min',cmd_min,'-move',cmd_move,'-okfit',cmd_okfit]
mcd.output_log_entry(path_logfile,'{:s} {:s} -obj temp.srt -out {:s} -moment {:s} -subtract -snr {:s} -bias {:s} -border {:s} -net {:s} -min {:s} -move {:s} -okfit {:s}'.format(tphot_cmd,fits_filename_wcs,output_path_stars,output_path_moments,cmd_snr,cmd_bias,cmd_border,cmd_net,cmd_min,cmd_move,cmd_okfit))
process = subprocess.call(cmd)
os.remove('temp.out')
os.remove('temp.srt')
source_count = len(open(output_path_stars).readlines()) # count number of lines in file
if source_count > 0:
mcd.output_log_entry(path_logfile,'{:d} extracted sources using 2D Waussian fits written to {:s}'.format(source_count,output_path_stars))
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'No sources extracted from {:s} using 2D Waussian fits.'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Source extraction using 2D Waussian fits using extract_sources_sdss() failed (no sources extracted).\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Source extraction using 2D Waussian fits using extract_sources_sdss() failed (no sources extracted).\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'No sources extracted using 2D Waussian fits'
keep_going = False
# extract source list
x = np.genfromtxt(output_path_stars,skip_header=1,usecols=(0))
y = np.genfromtxt(output_path_stars,skip_header=1,usecols=(1))
with open(output_path_source_list,'w') as of:
num_sources = len(x)
for idx in range(0,num_sources):
of.write('{:7.2f} {:7.2f}\n'.format(x[idx],y[idx]))
# extract sources using trailed Waussian fits
cmd = [tphot_cmd,fits_filename_wcs,'-trail','-obj',output_path_source_list,'-out',output_path_trails,'-subtract','-snr',cmd_snr,'-bias',cmd_bias,'-border',cmd_border,'-net',cmd_net,'-min',cmd_min,'-move',cmd_move,'-okfit',cmd_okfit,'-chin','10000']
mcd.output_log_entry(path_logfile,'{:s} {:s} -trail -obj {:s} -out {:s} -subtract -snr {:s} -bias {:s} -border {:s} -net {:s} -min {:s} -move {:s} -okfit {:s} -chin 10000'.format(tphot_cmd,fits_filename_wcs,output_path_source_list,output_path_trails,cmd_snr,cmd_bias,cmd_border,cmd_net,cmd_min,cmd_move,cmd_okfit))
process = subprocess.call(cmd)
source_count = len(open(output_path_trails).readlines()) - 1 # count number of lines in file
if source_count > 0:
mcd.output_log_entry(path_logfile,'{:d} extracted sources using trailed Waussian fits written to {:s}'.format(source_count,output_path_trails))
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'No sources extracted from {:s} using trailed Waussian fits.'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Source extraction using trailed Waussian fits using extract_sources_sdss() failed (no sources extracted).\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Source extraction using trailed Waussian fits using extract_sources_sdss() failed (no sources extracted).\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'No sources extracted using trailed Waussian fits'
keep_going = False
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: extract_sources_sdss()'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Source extraction using extract_sources_sdss() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Source extraction using extract_sources_sdss() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Source extraction using extract_sources_sdss() failed'
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: extract_sources_sdss()')
return output_path_stars,output_path_trails,output_path_moments,output_path_source_list,proc_status,keep_going
def create_field_source_table(output_path_stars,output_path_trails,output_path_moments,fits_filename_wcs,match_threshold_pix,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Create calibration star tables
field_source_table = Table()
calib_source_table = Table()
if keep_going:
try:
# Create field source table with trailed Waussian fits
mcd.output_log_entry(path_logfile,'Creating field source table from {:s}...'.format(output_path_trails))
x_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(0))
y_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(1))
flux_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(7))
dflux_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(8))
trail_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(9))
fwhm_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(10))
phi_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(11))
chiN_t = np.genfromtxt(output_path_trails,skip_header=1,usecols=(13))
field_source_table = Table([x_t,y_t,flux_t,dflux_t,trail_t,fwhm_t,phi_t,chiN_t], \
names=('x_t','y_t','flux_t','dflux_t','trail_t','fwhm_t','phi_t','chiN_t'), \
dtype=('f8','f8','f8','f8','f8','f8','f8','f8'))
field_source_table['SNR_t'] = -999.0
field_source_table['x_s'] = -999.0
field_source_table['y_s'] = -999.0
field_source_table['flux_s'] = -999.0
field_source_table['dflux_s'] = -999.0
field_source_table['major_s'] = -999.0
field_source_table['minor_s'] = -999.0
field_source_table['fwhm_s'] = -999.0
field_source_table['phi_s'] = -999.0
field_source_table['chiN_s'] = -999.0
field_source_table['SNR_s'] = -999.0
field_source_table['rKron_s'] = -999.0
num_sources_trails = len(field_source_table)
for idx in range(0,num_sources_trails):
field_source_table[idx]['SNR_t'] = field_source_table[idx]['flux_t'] / field_source_table[idx]['dflux_t']
mcd.output_log_entry(path_logfile,'Creating field source table done.')
# Read in data for 2D Waussian fit results
mcd.output_log_entry(path_logfile,'Reading in data from {:s} and {:s}...'.format(output_path_stars,output_path_moments))
x_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(0))
y_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(1))
flux_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(7))
dflux_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(8))
major_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(9))
minor_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(10))
phi_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(11))
chiN_s = np.genfromtxt(output_path_stars,skip_header=1,usecols=(13))
rKron_s = np.genfromtxt(output_path_moments,skip_header=1,usecols=(6))
num_sources_stars = len(x_s)
SNR_s = [0 for idx in range(num_sources_stars)]
for idx in range(0,num_sources_stars):
SNR_s[idx] = flux_s[idx] / dflux_s[idx]
mcd.output_log_entry(path_logfile,'Reading in data done.')
# Add 2D Waussian fit data to field source table
mcd.output_log_entry(path_logfile,'Adding data from 2D Waussian fit files to field source table...')
for idx_t in range(num_sources_trails):
idx_s = 0
x_star,y_star,flux_star,dflux_star,major_star,minor_star,fwhm_star,phi_star,chiN_star,rKron_star,SNR_star = 0,0,0,0,0,0,0,0,0,0,0
star_source_found = False
while not star_source_found and idx_s < num_sources_stars:
if abs(x_s[idx_s]-field_source_table[idx_t]['x_t']) < match_threshold_pix and abs(y_s[idx_s]-field_source_table[idx_t]['y_t']) < match_threshold_pix:
x_star = x_s[idx_s]
y_star = y_s[idx_s]
flux_star = flux_s[idx_s]
dflux_star = dflux_s[idx_s]
major_star = major_s[idx_s]
minor_star = minor_s[idx_s]
fwhm_star = ((major_star**2 + minor_star**2)/2)**0.5
phi_star = phi_s[idx_s]
chiN_star = chiN_s[idx_s]
rKron_star = rKron_s[idx_s]
SNR_star = SNR_s[idx_s]
star_source_found = True
else:
idx_s += 1
field_source_table[idx_t]['x_s'] = x_star
field_source_table[idx_t]['y_s'] = y_star
field_source_table[idx_t]['flux_s'] = flux_star
field_source_table[idx_t]['dflux_s'] = dflux_star
field_source_table[idx_t]['major_s'] = major_star
field_source_table[idx_t]['minor_s'] = minor_star
field_source_table[idx_t]['fwhm_s'] = fwhm_star
field_source_table[idx_t]['phi_s'] = phi_star
field_source_table[idx_t]['chiN_s'] = chiN_star
field_source_table[idx_t]['rKron_s'] = rKron_star
field_source_table[idx_t]['SNR_s'] = SNR_star
mcd.output_log_entry(path_logfile,'Adding data to field source table done.')
# Create calibration source table
calib_source_table = Table(names=('x_t','y_t','flux_t','dflux_t','trail_t','fwhm_t','phi_t','chiN_t','SNR_t', \
'x_s','y_s','flux_s','dflux_s','major_s','minor_s','fwhm_s','phi_s','chiN_s','SNR_s','rKron_s'))
for idx in range(len(field_source_table)):
calib_source_table.add_row((field_source_table[idx]['x_t'],field_source_table[idx]['y_t'], \
field_source_table[idx]['flux_t'],field_source_table[idx]['dflux_t'], \
field_source_table[idx]['trail_t'],field_source_table[idx]['fwhm_t'], \
field_source_table[idx]['phi_t'],field_source_table[idx]['chiN_t'],field_source_table[idx]['SNR_t'], \
field_source_table[idx]['x_s'],field_source_table[idx]['y_s'], \
field_source_table[idx]['flux_s'],field_source_table[idx]['dflux_s'], \
field_source_table[idx]['major_s'],field_source_table[idx]['minor_s'],field_source_table[idx]['fwhm_s'], \
field_source_table[idx]['phi_s'],field_source_table[idx]['chiN_s'],field_source_table[idx]['SNR_s'], \
field_source_table[idx]['rKron_s']))
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: create_field_source_table'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Field source table creation using create_field_source_table() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Field source table creation using create_field_source_table() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Field source table creation using create_field_source_table() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: create_field_source_table')
return field_source_table,calib_source_table,proc_status,keep_going
def remove_bad_sources(field_source_table,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Remove bad sources from tphot source list (e.g., flux < 0 or SNR < 3)
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Removing flux<0 and SNR<3 sources from tphot source list...')
idx,sources_removed = 0,0
num_field_sources = len(field_source_table)
while idx < len(field_source_table):
if field_source_table[idx]['flux_s'] < 0 or field_source_table[idx]['flux_t'] < 0 or field_source_table[idx]['SNR_s'] < 3:
field_source_table.remove_row(idx)
sources_removed += 1
else:
idx += 1
mcd.output_log_entry(path_logfile,'{:d} negative-flux or SNR < 3 sources removed ({:d} remaining).'.format(sources_removed,(num_field_sources - sources_removed)))
if (num_field_sources - sources_removed) < 3:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Processing stopped for {:s}: remove_bad_sources() - < 3 field sources remaining'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Bad source removal using remove_bad_sources() stopped - < 3 field sources remaining.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Bad source removal using remove_bad_sources() stopped - < 3 field sources remaining.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Fewer than 3 field sources remaining after bad source removal'
keep_going = False
else:
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: remove_bad_sources()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Bad source removal using remove_bad_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Bad source removal using remove_bad_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Bad source removal using remove_bad_sources() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: remove_bad_sources()')
return field_source_table,proc_status,keep_going
def remove_lowsnr_sources(calib_star_table,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Remove low-SNR detections from calibration star table
if keep_going:
mcd.output_log_entry(path_logfile,'Removing low-SNR detections from calibration star table...')
try:
idx,sources_removed = 0,0
num_calib_stars = len(calib_star_table)
while idx < len(calib_star_table):
if calib_star_table[idx]['SNR_s'] < 5:
calib_star_table.remove_row(idx)
sources_removed += 1
else:
idx += 1
mcd.output_log_entry(path_logfile,'Removing low-SNR detections done.')
mcd.output_log_entry(path_logfile,'{:d} calibration sources with SNR < 5 removed ({:d} remaining).'.format(sources_removed,(num_calib_stars - sources_removed)))
if (num_calib_stars - sources_removed) < 3:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Processing stopped for {:s}: remove_lowsnr_sources() - < 3 calibration sources remaining'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Low SNR source removal using remove_lowsnr_sources() stopped - < 3 calibration sources remaining.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Low SNR source removal using remove_lowsnr_sources() stopped - < 3 calibration sources remaining.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Fewer than 3 calibration sources remaining after low SNR source removal'
keep_going = False
else:
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: remove_lowsnr_sources()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Low SNR source removal using remove_lowsnr_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Low SNR source removal using remove_lowsnr_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Low SNR source removal using remove_lowsnr_sources() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: remove_lowsnr_sources()')
return calib_star_table,proc_status,keep_going
def compute_exp_source_density(exp_npix_x,exp_npix_y,wcs_pixscale_x,wcs_pixscale_y,field_source_table,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Compute average source density per square arcminute for entire exposure
source_density = 0
if keep_going:
try:
num_sources = len(field_source_table)
image_size_sqarcmin = exp_npix_x*wcs_pixscale_x/60 * exp_npix_y*wcs_pixscale_y/60
source_density = num_sources / image_size_sqarcmin
mcd.output_log_entry(path_logfile,'Exposure source density: {:.3f}'.format(source_density))
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: compute_exp_source_density()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Source density computation using compute_exp_source_density() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Source density computation using compute_exp_source_density() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Source density computation using compute_exp_source_density() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: compute_exp_source_density()')
return source_density,proc_status,keep_going
##### FUNCTION DEFINITIONS -- PHOTOMETRIC CALIBRATION #####
def retrieve_refcat_sources(ra_deg,dec_deg,radius_arcmin,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Retrieve refcat sources
refcat_table = 0
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Retrieving refcat sources within {:.1f} arcmin of RA={:.6f},Dec={:.6f}'.format(radius_arcmin,ra_deg,dec_deg))
filename = fits_filename_wcs[:-9]+'_refcat_sources.dat'
outf = open(filename,'w')
with open(filename,'w') as outf:
outf.write(' objRA objDec gmag gerr rmag rerr imag ierr zmag zerr\n')
radius_deg = radius_arcmin / 60
cmd_ra = '{:f}'.format(ra_deg)
cmd_dec = '{:f}'.format(dec_deg)
cmd_radius = '{:f}'.format(radius_deg)
cmd_refcat = ''
if os.path.exists('/users/hhsieh/astro/tools/refcat'):
cmd_refcat = '/users/hhsieh/astro/tools/refcat'
directories = '/users/hhsieh/astro/tools/refcat_catalog/00_m_16_binary,/users/hhsieh/astro/tools/refcat_catalog/16_m_17_binary,/users/hhsieh/astro/tools/refcat_catalog/17_m_18_binary,/users/hhsieh/astro/tools/refcat_catalog/18_m_19_binary,/users/hhsieh/astro/tools/refcat_catalog/19_m_20_binary'
elif os.path.exists('/home/hhsieh/tools/refcat'):
cmd_refcat = '/home/hhsieh/tools/refcat' # on pohaku
directories = '/data2/refcat_catalog/00_m_16_binary,/data2/refcat_catalog/16_m_17_binary,/data2/refcat_catalog/17_m_18_binary,/data2/refcat_catalog/18_m_19_binary,/data2/refcat_catalog/19_m_20_binary'
elif os.path.exists('/atlas/bin/refcat'):
cmd_refcat = '/atlas/bin/refcat' # on atlas
directories = '/home/hhsieh/tools/refcat_catalog/00_m_16_binary,/home/hhsieh/tools/refcat_catalog/16_m_17_binary,/home/hhsieh/tools/refcat_catalog/17_m_18_binary,/home/hhsieh/tools/refcat_catalog/18_m_19_binary,/home/hhsieh/tools/refcat_catalog/19_m_20_binary'
var_fields = 'RA,Dec,g,dg,r,dr,i,di,z,dz'
cmd_dir,cmd_rad,cmd_var,cmd_nohdr,cmd_bin = '-dir','-rad','-var','-nohdr','-bin'
cmd = [cmd_refcat,cmd_ra,cmd_dec,cmd_dir,directories,cmd_bin,cmd_rad,cmd_radius,cmd_var,var_fields,cmd_nohdr]
subprocess.call(cmd,stdout=outf)
mcd.output_log_entry(path_logfile,'refcat catalog sources written to {:s}.'.format(filename))
# parse local file into astropy.table object
objRA = np.genfromtxt(filename,skip_header=1,usecols=(0))
objDec = np.genfromtxt(filename,skip_header=1,usecols=(1))
gmag = np.genfromtxt(filename,skip_header=1,usecols=(2))
gerr = np.genfromtxt(filename,skip_header=1,usecols=(3))
rmag = np.genfromtxt(filename,skip_header=1,usecols=(4))
rerr = np.genfromtxt(filename,skip_header=1,usecols=(5))
imag = np.genfromtxt(filename,skip_header=1,usecols=(6))
ierr = np.genfromtxt(filename,skip_header=1,usecols=(7))
zmag = np.genfromtxt(filename,skip_header=1,usecols=(8))
zerr = np.genfromtxt(filename,skip_header=1,usecols=(9))
refcat_table = Table([objRA,objDec,gmag,gerr,rmag,rerr,imag,ierr,zmag,zerr], \
names=('right_ascension','declination','gp1_mag','gp1_err','rp1_mag','rp1_err','ip1_mag','ip1_err','zp1_mag','zp1_err'), \
dtype=('f8','f8','f8','f8','f8','f8','f8','f8','f8','f8'))
num_refcat_sources = len(refcat_table)
if num_refcat_sources > 0:
idx = 0
# Remove sources that are likely to be saturated or have dummy values (i.e., -999)
while idx < len(refcat_table):
if refcat_table[idx]['gp1_mag'] < 10 or refcat_table[idx]['rp1_mag'] < 10 or refcat_table[idx]['ip1_mag'] < 10 or refcat_table[idx]['zp1_mag'] < 10:
refcat_table.remove_row(idx)
else:
idx += 1
num_refcat_sources = len(refcat_table)
if num_refcat_sources > 0:
mcd.output_log_entry(path_logfile,'{:d} refcat catalog sources retrieved.'.format(num_refcat_sources))
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'No refcat calibration sources found for {:s}'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - No refcat calibration sources found using retrieve_refcat_sources().\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - No refcat calibration sources found using retrieve_refcat_sources().\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'No refcat calibration sources found using retrieve_refcat_sources()'
keep_going = False
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: retrieve_refcat_sources()'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Refcat source retrieval using retrieve_refcat_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Refcat source retrieval using retrieve_refcat_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Refcat source retrieval using retrieve_refcat_sources() failed'
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: retrieve_refcat_sources()')
return refcat_table,proc_status,keep_going
def match_refcat_sources(field_source_table,refcat_table,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Find matches for sources extracted by tphot in PS1 source catalog
calib_star_table = 0
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Finding matches for sources extracted by tphot in refcat catalog...')
calib_star_table = Table(names=('x_s','y_s','flux_s','dflux_s','SNR_s', \
'RA','Dec','refcat_RA','refcat_Dec','gp1_mag','gp1_err','rp1_mag','rp1_err','ip1_mag', \
'ip1_err','zp1_mag','zp1_err','g_sdss_mag','g_sdss_err','r_sdss_mag','r_sdss_err','i_sdss_mag', \
'i_sdss_err','z_sdss_mag','z_sdss_err','B_mag','B_err','V_mag','V_err','Rc_mag','Rc_err','Ic_mag', \
'Ic_err','target_dist','zero_point','zpoint_err'))
num_field_sources,num_refcat_stars = len(field_source_table),len(refcat_table)
stars_matched = 0
for idx1 in range(0,num_field_sources):
idx2,star_matched = 0,0
while idx2 < num_refcat_stars and star_matched == 0:
distance = ((field_source_table[idx1]['RA'] - refcat_table[idx2]['right_ascension'])**2 +
(field_source_table[idx1]['Dec'] - refcat_table[idx2]['declination'])**2)**0.5
if distance < 0.000417: # If target matches within 1.5 arcsec
star_matched = 1
copy_fieldsource_row_to_calibstar_table(field_source_table,calib_star_table,idx1,fits_filename_wcs,thread_idx,keep_going,path_logfile,path_errorfile)
calib_star_table[stars_matched]['refcat_RA'] = float(refcat_table[idx2]['right_ascension'])
calib_star_table[stars_matched]['refcat_Dec'] = float(refcat_table[idx2]['declination'])
calib_star_table[stars_matched]['gp1_mag'] = refcat_table[idx2]['gp1_mag']
calib_star_table[stars_matched]['gp1_err'] = refcat_table[idx2]['gp1_err']
calib_star_table[stars_matched]['rp1_mag'] = refcat_table[idx2]['rp1_mag']
calib_star_table[stars_matched]['rp1_err'] = refcat_table[idx2]['rp1_err']
calib_star_table[stars_matched]['ip1_mag'] = refcat_table[idx2]['ip1_mag']
calib_star_table[stars_matched]['ip1_err'] = refcat_table[idx2]['ip1_err']
calib_star_table[stars_matched]['zp1_mag'] = refcat_table[idx2]['zp1_mag']
calib_star_table[stars_matched]['zp1_err'] = refcat_table[idx2]['zp1_err']
stars_matched += 1
else:
idx2 += 1
mcd.output_log_entry(path_logfile,'{:d} extracted sources matched to refcat catalog sources for {:s}.'.format(stars_matched,fits_filename_wcs))
if stars_matched == 0:
mcd.output_error_log_entry(path_logfile,path_errorfile,'No refcat sources matched to image sources using match_refcat_sources() for {:s}.'.format(fits_filename_wcs))
with open(fits_filename_wcs[:-9]+'.refcat_source_matching_failed','w') as f:
f.write('{:s} - No refcat sources matched to image sources using match_refcat_sources().\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'No refcat sources matched to image sources using match_refcat_sources()'
keep_going = False
elif stars_matched < 3:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Insufficient refcat sources (n<3) refcat calibration sources matched for {:s}.'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Insufficient refcat sources (n<3) matched to image sources using match_refcat_sources().\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Insufficient refcat sources (n<3) matched to image sources using match_refcat_sources().\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Fewer than 3 refcat sources matched to image sources using match_refcat_sources()'
keep_going = False
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: match_refcat_sources()'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Refcat source matching using match_refcat_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Refcat source matching using match_refcat_sources() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Refcat source matching using match_refcat_sources() failed'
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: match_refcat_sources()')
return calib_star_table,proc_status,keep_going
def copy_fieldsource_row_to_calibstar_table(field_source_table,calib_star_table,target_idx,fits_filename_wcs,thread_idx,keep_going,path_logfile,path_errorfile):
# Copy source from refcat source list to calibration star list
if keep_going:
try:
calib_star_table.add_row((field_source_table[target_idx]['x_s'],field_source_table[target_idx]['y_s'], \
field_source_table[target_idx]['flux_s'],field_source_table[target_idx]['dflux_s'], \
field_source_table[target_idx]['SNR_s'], \
field_source_table[target_idx]['RA'],field_source_table[target_idx]['Dec'], \
field_source_table[target_idx]['ps1_RA'],field_source_table[target_idx]['ps1_Dec'], \
field_source_table[target_idx]['gp1_mag'],field_source_table[target_idx]['gp1_err'], \
field_source_table[target_idx]['rp1_mag'],field_source_table[target_idx]['rp1_err'], \
field_source_table[target_idx]['ip1_mag'],field_source_table[target_idx]['ip1_err'], \
field_source_table[target_idx]['zp1_mag'],field_source_table[target_idx]['zp1_err'], \
field_source_table[target_idx]['g_sdss_mag'],field_source_table[target_idx]['g_sdss_err'], \
field_source_table[target_idx]['r_sdss_mag'],field_source_table[target_idx]['r_sdss_err'], \
field_source_table[target_idx]['i_sdss_mag'],field_source_table[target_idx]['i_sdss_err'], \
field_source_table[target_idx]['z_sdss_mag'],field_source_table[target_idx]['z_sdss_err'], \
field_source_table[target_idx]['B_mag'],field_source_table[target_idx]['B_err'], \
field_source_table[target_idx]['V_mag'],field_source_table[target_idx]['V_err'], \
field_source_table[target_idx]['Rc_mag'],field_source_table[target_idx]['Rc_err'], \
field_source_table[target_idx]['Ic_mag'],field_source_table[target_idx]['Ic_err'], \
field_source_table[target_idx]['target_dist'], \
field_source_table[target_idx]['zero_point'],field_source_table[target_idx]['zpoint_err']))
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: copy_fieldsource_row_to_calibstar_table()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Calibration star table insertion using copy_fieldsource_row_to_calibstar_table() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Calibration star table insertion using copy_fieldsource_row_to_calibstar_table() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: copy_fieldsource_row_to_calibstar_table()')
return calib_star_table,keep_going
def convert_ps1_mags(gp1_mag,gp1_err,rp1_mag,rp1_err,ip1_mag,ip1_err,zp1_mag,zp1_err,fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Convert PS1 magnitudes to SDSS and Johnson-Cousins systems
magnitudes = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
if keep_going:
try:
# Transform magnitudes
g_ps2sdss_a0,g_ps2sdss_a1,g_ps2sdss_a2,g_ps2sdss_b0,g_ps2sdss_b1 = 0.013, 0.145, 0.019, 0.014, 0.162
r_ps2sdss_a0,r_ps2sdss_a1,r_ps2sdss_a2,r_ps2sdss_b0,r_ps2sdss_b1 = -0.001, 0.004, 0.007,-0.001, 0.011
i_ps2sdss_a0,i_ps2sdss_a1,i_ps2sdss_a2,i_ps2sdss_b0,i_ps2sdss_b1 = -0.005, 0.011, 0.010,-0.004, 0.020
z_ps2sdss_a0,z_ps2sdss_a1,z_ps2sdss_a2,z_ps2sdss_b0,z_ps2sdss_b1 = 0.013,-0.039,-0.012, 0.013,-0.050
B_ps2jc_a0, B_ps2jc_a1, B_ps2jc_a2, B_ps2jc_b0, B_ps2jc_b1 = 0.212, 0.556, 0.034, 0.213, 0.587
V_ps2jc_a0, V_ps2jc_a1, V_ps2jc_a2, V_ps2jc_b0, V_ps2jc_b1 = 0.005, 0.462, 0.013, 0.006, 0.474
Rc_ps2jc_a0, Rc_ps2jc_a1, Rc_ps2jc_a2, Rc_ps2jc_b0, Rc_ps2jc_b1 = -0.137,-0.108,-0.029,-0.138,-0.131
Ic_ps2jc_a0, Ic_ps2jc_a1, Ic_ps2jc_a2, Ic_ps2jc_b0, Ic_ps2jc_b1 = -0.366,-0.136,-0.018,-0.367,-0.149
# y = A0 + A1x + A2x^2 = B0+B1x - Tonry et al. (2012, ApJ, 750, 99)
x = gp1_mag - rp1_mag
g_sdss_mag1 = gp1_mag + g_ps2sdss_a0 + g_ps2sdss_a1*x + g_ps2sdss_a2*(x**2)
r_sdss_mag1 = rp1_mag + r_ps2sdss_a0 + r_ps2sdss_a1*x + r_ps2sdss_a2*(x**2)
i_sdss_mag1 = ip1_mag + i_ps2sdss_a0 + i_ps2sdss_a1*x + i_ps2sdss_a2*(x**2)
z_sdss_mag1 = zp1_mag + z_ps2sdss_a0 + z_ps2sdss_a1*x + z_ps2sdss_a2*(x**2)
g_sdss_mag2 = gp1_mag + g_ps2sdss_b0 + g_ps2sdss_b1*x
r_sdss_mag2 = rp1_mag + r_ps2sdss_b0 + r_ps2sdss_b1*x
i_sdss_mag2 = ip1_mag + i_ps2sdss_b0 + i_ps2sdss_b1*x
z_sdss_mag2 = zp1_mag + z_ps2sdss_b0 + z_ps2sdss_b1*x
B_mag1 = gp1_mag + B_ps2jc_a0 + B_ps2jc_a1*x + B_ps2jc_a2*(x**2)
V_mag1 = rp1_mag + V_ps2jc_a0 + V_ps2jc_a1*x + V_ps2jc_a2*(x**2)
Rc_mag1 = rp1_mag + Rc_ps2jc_a0 + Rc_ps2jc_a1*x + Rc_ps2jc_a2*(x**2)
Ic_mag1 = ip1_mag + Ic_ps2jc_a0 + Ic_ps2jc_a1*x + Ic_ps2jc_a2*(x**2)
B_mag2 = gp1_mag + B_ps2jc_b0 + B_ps2jc_b1*x
V_mag2 = rp1_mag + V_ps2jc_b0 + V_ps2jc_b1*x
Rc_mag2 = rp1_mag + Rc_ps2jc_b0 + Rc_ps2jc_b1*x
Ic_mag2 = ip1_mag + Ic_ps2jc_b0 + Ic_ps2jc_b1*x
g_sdss_mag,g_sdss_err = mcd.magavg([g_sdss_mag1,g_sdss_mag2],[gp1_err,gp1_err])
r_sdss_mag,r_sdss_err = mcd.magavg([r_sdss_mag1,r_sdss_mag2],[rp1_err,rp1_err])
i_sdss_mag,i_sdss_err = mcd.magavg([i_sdss_mag1,i_sdss_mag2],[ip1_err,ip1_err])
z_sdss_mag,z_sdss_err = mcd.magavg([z_sdss_mag1,z_sdss_mag2],[zp1_err,zp1_err])
B_mag, B_err = mcd.magavg([B_mag1, B_mag2] ,[gp1_err,gp1_err])
V_mag, V_err = mcd.magavg([V_mag1, V_mag2] ,[rp1_err,rp1_err])
Rc_mag,Rc_err = mcd.magavg([Rc_mag1,Rc_mag2],[rp1_err,rp1_err])
Ic_mag,Ic_err = mcd.magavg([Ic_mag1,Ic_mag2],[ip1_err,ip1_err])
magnitudes = [g_sdss_mag,g_sdss_err,r_sdss_mag,r_sdss_err,i_sdss_mag,i_sdss_err,z_sdss_mag,z_sdss_err, \
B_mag,B_err,V_mag,V_err,Rc_mag,Rc_err,Ic_mag,Ic_err]
keep_going = True
except Exception as e:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Function failed for {:s}: convert_ps1_mags()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - PS1 magnitude conversion using convert_ps1_mags() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - PS1 magnitude conversion using convert_ps1_mags() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'PS1 magnitude conversion using convert_ps1_mags() failed'
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: convert_ps1_mags()')
return magnitudes,proc_status,keep_going
def compute_zero_point(fits_filename_wcs,filter_name,calib_star_table,exptime,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
# Compute zero points
avg_zeropoint_mag,avg_zeropoint_err,num_calib_stars = 0,0,0
if keep_going:
try:
mcd.output_log_entry(path_logfile,'Computing zero points for {:s}...'.format(fits_filename_wcs))
num_calib_stars = len(calib_star_table)
for idx in range(0,num_calib_stars):
magnitudes,proc_status,keep_going = convert_ps1_mags(calib_star_table[idx]['gp1_mag'],calib_star_table[idx]['gp1_err'], \
calib_star_table[idx]['rp1_mag'],calib_star_table[idx]['rp1_err'], \
calib_star_table[idx]['ip1_mag'],calib_star_table[idx]['ip1_err'], \
calib_star_table[idx]['zp1_mag'],calib_star_table[idx]['zp1_err'],fits_filename_wcs,proc_status,thread_idx,keep_going,path_logfile,path_errorfile)
if keep_going:
keep_going = False
if filter_name == 'g':
calib_star_table[idx]['g_sdss_mag'] = magnitudes[0]
calib_star_table[idx]['g_sdss_err'] = magnitudes[1]
targ_magerr = ufloat(calib_star_table[idx]['g_sdss_mag'],calib_star_table[idx]['g_sdss_err'])
elif filter_name == 'r':
calib_star_table[idx]['r_sdss_mag'] = magnitudes[2]
calib_star_table[idx]['r_sdss_err'] = magnitudes[3]
targ_magerr = ufloat(calib_star_table[idx]['r_sdss_mag'],calib_star_table[idx]['r_sdss_err'])
elif filter_name == 'i':
calib_star_table[idx]['i_sdss_mag'] = magnitudes[4]
calib_star_table[idx]['i_sdss_err'] = magnitudes[5]
targ_magerr = ufloat(calib_star_table[idx]['i_sdss_mag'],calib_star_table[idx]['i_sdss_err'])
elif filter_name == 'z':
calib_star_table[idx]['z_sdss_mag'] = magnitudes[6]
calib_star_table[idx]['z_sdss_err'] = magnitudes[7]
targ_magerr = ufloat(calib_star_table[idx]['z_sdss_mag'],calib_star_table[idx]['z_sdss_err'])
elif filter_name == 'B':
calib_star_table[idx]['B_mag'] = magnitudes[8]
calib_star_table[idx]['B_err'] = magnitudes[9]
targ_magerr = ufloat(calib_star_table[idx]['B_mag'], calib_star_table[idx]['B_err'])
elif filter_name == 'V':
calib_star_table[idx]['V_mag'] = magnitudes[10]
calib_star_table[idx]['V_err'] = magnitudes[11]
targ_magerr = ufloat(calib_star_table[idx]['V_mag'], calib_star_table[idx]['V_err'])
elif filter_name == 'Rc':
calib_star_table[idx]['Rc_mag'] = magnitudes[12]
calib_star_table[idx]['Rc_err'] = magnitudes[13]
targ_magerr = ufloat(calib_star_table[idx]['Rc_mag'],calib_star_table[idx]['Rc_err'])
elif filter_name == 'Ic':
calib_star_table[idx]['Ic_mag'] = magnitudes[14]
calib_star_table[idx]['Ic_err'] = magnitudes[15]
targ_magerr = ufloat(calib_star_table[idx]['Ic_mag'],calib_star_table[idx]['Ic_err'])
star_fluxerr = ufloat(calib_star_table[idx]['flux_s'],calib_star_table[idx]['dflux_s'])
zero_point = targ_magerr + 2.5 * unumpy.log10(star_fluxerr/exptime)
calib_star_table[idx]['zero_point'] = zero_point.nominal_value
calib_star_table[idx]['zpoint_err'] = zero_point.std_dev
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Conversion of refcat source magnitudes to other filters failed for {:s}.'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Refcat source magnitude conversion using compute_zero_point() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Refcat source magnitude conversion using compute_zero_point() failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Refcat source magnitude conversion using compute_zero_point() failed'
keep_going = False
if keep_going:
mcd.output_log_entry(path_logfile,'Removing sources with outlier zero point magnitudes...')
zeropoints = calib_star_table['zero_point']
mu,sigma,proc_status,keep_going = generate_zeropoint_histogram(calib_star_table['zero_point'],fits_filename_wcs,'histogram1',proc_status,thread_idx,keep_going,path_logfile,path_errorfile)
zeropoint_median = statistics.median(zeropoints)
idx,zpoints_removed = 0,0
num_calib_stars = len(calib_star_table)
while idx < len(calib_star_table):
# Remove stars with zero points more than 0.3 mag above or below the median
if calib_star_table[idx]['zero_point'] > (zeropoint_median+0.3) or calib_star_table[idx]['zero_point'] < (zeropoint_median-0.3):
calib_star_table.remove_row(idx)
zpoints_removed += 1
else:
idx += 1
mcd.output_log_entry(path_logfile,'{:d} outlier zeropoints removed, {:d} zeropoints remaining.'.format(zpoints_removed,(num_calib_stars-zpoints_removed)))
if (num_calib_stars-zpoints_removed) < 3:
mcd.output_log_error_entry(path_logfile,path_errorfile,'Insufficient zeropoints (n<3) remaining for compute_zero_point() to continue for {:s}'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Insufficient zeropoints (n<3) remaining for compute_zero_point() to continue.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Insufficient zeropoints (n<3) remaining for compute_zero_point() to continue.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Insufficient zeropoints (n<3) remaining for compute_zero_point() to continue'
keep_going = False
else:
mu,sigma,proc_status,keep_going = generate_zeropoint_histogram(calib_star_table['zero_point'],fits_filename_wcs,'histogram2',proc_status,thread_idx,keep_going,path_logfile,path_errorfile)
avg_zeropoint_mag,avg_zeropoint_err = mcd.magavg(calib_star_table['zero_point'],calib_star_table['zpoint_err'])
mcd.output_log_entry(path_logfile,'Number of stars used for photometric solution: {:d}'.format(num_calib_stars))
mcd.output_log_entry(path_logfile,'Zero point median: {:.3f}'.format(zeropoint_median))
mcd.output_log_entry(path_logfile,'Zero point magnitude solution: {:.3f}+/-{:.3f}'.format(avg_zeropoint_mag,avg_zeropoint_err))
with open(fits_filename_wcs[:-9]+'.photsolved','w') as f:
f.write('{:s} - Photometric calibration successful.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Photometric calibration successful'
keep_going = True
else:
mcd.output_error_log_entry(path_logfile,path_errorfile,'Zero point computation failed for {:s}.'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Zero point computation failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Zero point computation failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Zero point computation failed'
keep_going = False
except Exception as e:
mcd.output_log_error_entry(path_logfile,path_errorfile,'Function failed for {:s}: compute_zero_point()'.format(fits_filename_wcs))
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f:
f.write('{:s} - Zero point computation failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
else:
with open(fits_filename_wcs[:-9]+'.photfailed','w') as f:
f.write('{:s} - Zero point computation failed.\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
proc_status = 'Zero point computation failed'
print(e)
keep_going = False
else:
mcd.output_log_entry(path_logfile,'Function skipped: compute_zero_point()')
return calib_star_table,avg_zeropoint_mag,avg_zeropoint_err,num_calib_stars,proc_status,keep_going
def generate_zeropoint_histogram(zeropoints,fits_filename_wcs,filename_suffix,proc_status,thread_idx,keep_going,path_logfile,path_errorfile):
mu,sigma = 0,0
if keep_going:
try:
filename = fits_filename_wcs[:-9]+'_zeropoint_'+filename_suffix
rect_plot_1 = [0.12,0.12,0.40,0.30]
plt.figure(1,figsize=(12,12))
axPlot1 = plt.axes(rect_plot_1)
n_zeropoint_bins = 20
zeropoint_min = np.amin(zeropoints)
zeropoint_max = np.amax(zeropoints)
zeropoint_bins = np.arange(zeropoint_min,zeropoint_max,(zeropoint_max-zeropoint_min)/n_zeropoint_bins)
mu,sigma = norm.fit(zeropoints)
x1,bins1,p1 = axPlot1.hist(zeropoints,bins=zeropoint_bins,histtype='bar',density=1,edgecolor='black',color='#2077b4',zorder=1)
#y = mlab.normpdf(zeropoint_bins,mu,sigma)
y = scipy.stats.norm.pdf(zeropoint_bins,mu,sigma)
axPlot1.plot(zeropoint_bins,y,ls='--',lw=2,color='#880000',zorder=2)
plt.savefig(filename + '.pdf',format='pdf',transparent=True)
plt.clf()
plt.cla()
plt.close()
mcd.output_log_entry(path_logfile,'Zero-point histogram generation and Gaussian fitting (mu={:.2f} mag; sigma={:.2f}) completed successfully.'.format(mu,sigma))
keep_going = True
except Exception as e:
mcd.output_log_error_entry(path_logfile,path_errorfile,'Function failed for {:s}: generate_zeropoint_histogram()'.format(fits_filename_wcs))
print(e)
if os.path.exists(fits_filename_wcs[:-9]+'.photfailed'):
with open(fits_filename_wcs[:-9]+'.photfailed','a') as f: