-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacadamia_functions.py
2802 lines (2503 loc) · 157 KB
/
macadamia_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import os.path
import sys
import re
import glob
import subprocess
import datetime
import math
import ssl
import bz2
import matplotlib.pyplot as plt
import matplotlib.figure as fig
import numpy as np
import numpy.ma as ma
import scipy
import statistics
import uncertainties
import urllib
from astropy import units as u
from astropy.io import fits
from astropy.io.fits import getheader
from astropy.coordinates import SkyCoord
from astropy.time import Time, TimeDelta
from astropy.wcs import WCS
from astropy.coordinates import SkyCoord,Angle
from astropy.io import fits
from astropy.io.fits import getheader
from astropy.stats import SigmaClip,sigma_clipped_stats
from astropy.table import Table
from astropy.time import Time, TimeDelta
from astropy.wcs import WCS
from astropy.visualization.mpl_normalize import ImageNormalize
from astropy.visualization import simple_norm
from astroquery.jplhorizons import Horizons
from bz2 import decompress
from matplotlib.ticker import NullFormatter, MaxNLocator, ScalarFormatter, MultipleLocator, FormatStrFormatter
from photutils.background import Background2D, MedianBackground
from photutils.aperture import CircularAperture,CircularAnnulus,aperture_photometry
from photutils.detection import DAOStarFinder
from photutils.psf import PSFPhotometry
from scipy.stats import norm
from uncertainties import unumpy,ufloat
from uncertainties.umath import *
from uncertainties.unumpy import *
########## TOP LEVEL FUNCTION ##########
def search_extract_archival_photometry(param_dict):
os.chdir(param_dict['base_path'])
# Perform setup for processing (making data directories, loading config parameters, etc.)
param_dict = initialize_processing(param_dict)
# Run search for potential detections in archival data using SSOIS
param_dict = run_ssois_search(param_dict)
# Download and perform initial processing of image files identified by SSOIS search
param_dict = download_ssois_query_result_files(param_dict)
# Locate objects in images and perform multi-aperture photometry
param_dict = perform_photometry(param_dict)
# Move final results files into target photometry folder
param_dict = clean_final_photometry_files(param_dict)
return None
########## INITIAL PROCESSING FUNCTIONS ##########
def initialize_processing(param_dict):
param_dict = set_default_photometry_params(param_dict)
param_dict = set_epochs(param_dict)
param_dict = create_ssois_search_directory(param_dict)
param_dict['log_filepath'] = initialize_log_file(param_dict['query_results_dirpath'])
param_dict = write_phot_params_to_log(param_dict)
param_dict = read_config_file(param_dict)
param_dict = get_instrument_params(param_dict)
return param_dict
def set_default_photometry_params(param_dict):
if 'field_source_phot_radius_arcsec' not in param_dict:
param_dict['field_source_phot_radius_arcsec'] = 3.5
if 'sky_inner_r_arcsec' not in param_dict:
param_dict['sky_inner_r_arcsec'] = 15
if 'sky_outer_r_arcsec' not in param_dict:
param_dict['sky_outer_r_arcsec'] = 25
if 'daofind_fwhm' not in param_dict:
param_dict['daofind_fwhm'] = 1.5
if 'daofind_sigma_threshold' not in param_dict:
param_dict['daofind_sigma_threshold'] = 5
if 'daofind_fwhm_target' not in param_dict:
param_dict['daofind_fwhm_target'] = 1.5
if 'daofind_sigma_threshold_target' not in param_dict:
param_dict['daofind_sigma_threshold_target'] = 3
if 'target_sky_inner_r_arcsec' not in param_dict:
param_dict['target_sky_inner_r_arcsec'] = 15
if 'target_sky_outer_r_arcsec' not in param_dict:
param_dict['target_sky_outer_r_arcsec'] = 25
if 'target_phot_radii_arcsec' not in param_dict:
param_dict['target_phot_radii_arcsec'] = np.arange(1,10.5,0.5)
return param_dict
def set_epochs(param_dict):
param_dict['epoch1'] = '1990-01-01'
param_dict['epoch2'] = datetime.datetime.today().strftime('%Y-%m-%d')
if 'start_date' in param_dict:
if param_dict['start_date'] != '':
param_dict['epoch1'] = param_dict['start_date']
if 'end_date' in param_dict:
if param_dict['end_date'] != '':
param_dict['epoch2'] = param_dict['end_date']
return param_dict
def create_ssois_search_directory(param_dict):
target_name = remove_extra_characters(param_dict['target_name'])
telinst = remove_extra_characters(param_dict['telinst'])
epoch1 = remove_extra_characters(param_dict['epoch1'])
epoch2 = remove_extra_characters(param_dict['epoch2'])
obj_results_dirpath = param_dict['base_path'] + 'archival_search_{:s}/'.format(target_name)
query_results_dirpath = obj_results_dirpath + '{:s}_{:s}_{:s}/'.format(telinst,epoch1,epoch2)
if not os.path.exists(obj_results_dirpath):
os.mkdir(obj_results_dirpath)
if not os.path.exists(query_results_dirpath):
os.mkdir(query_results_dirpath)
param_dict['query_results_dirpath'] = query_results_dirpath
return param_dict
def initialize_log_file(base_path):
# Create and open log file
log_filepath = base_path + 'log_archival_photometry_{:s}.txt'.format(datetime.datetime.today().strftime('%Y%m%d_%H%M%S'))
with open(log_filepath,'w') as log_file:
log_file.write('Archival Asteroid Photometry Log: {:s}\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
return log_filepath
def write_phot_params_to_log(param_dict):
output_log_entry(param_dict['log_filepath'],'target: {:s}'.format(param_dict['target_name']))
output_log_entry(param_dict['log_filepath'],'telescope: {:s}'.format(param_dict['telinst']))
output_log_entry(param_dict['log_filepath'],'field_source_phot_radius_arcsec: {:.2f}'.format(param_dict['field_source_phot_radius_arcsec']))
output_log_entry(param_dict['log_filepath'],'sky_inner_r_arcsec: {:.2f}'.format(param_dict['sky_inner_r_arcsec']))
output_log_entry(param_dict['log_filepath'],'sky_outer_r_arcsec: {:.2f}'.format(param_dict['sky_outer_r_arcsec']))
output_log_entry(param_dict['log_filepath'],'daofind_fwhm: {:.2f}'.format(param_dict['daofind_fwhm']))
output_log_entry(param_dict['log_filepath'],'daofind_fwhm_target: {:.2f}'.format(param_dict['daofind_fwhm_target']))
output_log_entry(param_dict['log_filepath'],'daofind_sigma_threshold: {:.2f}'.format(param_dict['daofind_sigma_threshold']))
for idx in range(len(param_dict['target_phot_radii_arcsec'])):
output_log_entry(param_dict['log_filepath'],'target_phot_radius_arcsec: {:.2f}'.format(param_dict['target_phot_radii_arcsec'][idx]))
output_log_entry(param_dict['log_filepath'],'target_sky_inner_r_arcsec: {:.2f}'.format(param_dict['target_sky_inner_r_arcsec']))
output_log_entry(param_dict['log_filepath'],'target_sky_outer_r_arcsec: {:.2f}'.format(param_dict['target_sky_outer_r_arcsec']))
return param_dict
def read_config_file(param_dict):
config = {}
config_filepath = param_dict['base_path'] + 'macadamia.cfg'
with open(config_filepath,'r') as config_file:
for line in config_file:
line_data = line.split(',')
config[line_data[0]] = line_data[1].strip()
param_dict['config'] = config
return param_dict
def get_instrument_params(param_dict):
instrument_found = False
instrument_params = {}
instrument = param_dict['telinst']
if instrument == 'SDSS':
instrument_params['pixscale'] = 0.396
instrument_params['first_element'] = 0
instrument_params['num_elements'] = 1
instrument_params['obs_code'] = '645'
instrument_found = True
if instrument == 'CTIO-4m/DECam':
instrument_params['pixscale'] = 0.2637
instrument_params['first_element'] = 1
instrument_params['num_elements'] = 60
instrument_params['obs_code'] = '807'
instrument_found = True
if instrument == 'CFHT/MegaCam':
instrument_params['pixscale'] = 0.187
instrument_params['first_element'] = 1
instrument_params['num_elements'] = 40
instrument_params['obs_code'] = '568'
instrument_found = True
if instrument_found:
output_log_entry(param_dict['log_filepath'],'{:s} found:'.format(instrument))
output_log_entry(param_dict['log_filepath'],' - Pixel scale: {:f}'.format(instrument_params['pixscale']))
output_log_entry(param_dict['log_filepath'],' - Index of first element: {:d}'.format(instrument_params['first_element']))
output_log_entry(param_dict['log_filepath'],' - Number of elements: {:d}'.format(instrument_params['num_elements']))
else:
output_log_entry(param_dict['log_filepath'],'{:s} not found:'.format(instrument))
param_dict['instrument_params'] = instrument_params
return param_dict
########## SSOIS SEARCH FUNCTIONS ##########
def run_ssois_search(param_dict):
# Run search for potential detections in archival data using SSOIS
param_dict = generate_ssois_search_url_results_file(param_dict)
param_dict = execute_ssois_search(param_dict)
if param_dict['telinst'] == 'CTIO-4m/DECam':
param_dict = parse_ssois_query_results_decam(param_dict)
else:
param_dict = parse_ssois_query_results(param_dict)
param_dict = run_horizons_queries_prelim(param_dict)
return param_dict
def generate_ssois_search_url_results_file(param_dict):
target_name = param_dict['target_name'].replace(' ','+')
target_name = target_name.replace('/','%2F')
telinst = param_dict['telinst']
epoch1 = param_dict['epoch1']
epoch2 = param_dict['epoch2']
param_dict['ssois_search_url'] = 'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/cadcbin/ssos/ssosclf.pl?lang=en;object={:s};search=bynameall;epoch1={:s};epoch2={:s};eellipse=;eunits=arcseconds;extres=no;xyres=no;telinst={:s};format=tsv'.format(target_name,epoch1,epoch2,telinst)
output_log_entry(param_dict['log_filepath'],'SSOIS search URL: {:s}'.format(param_dict['ssois_search_url']))
query_results_filename = 'ssois_results_{:s}_{:s}_{:s}_{:s}.txt'.format(remove_extra_characters(param_dict['target_name']),
remove_extra_characters(param_dict['telinst']),remove_extra_characters(param_dict['epoch1']),remove_extra_characters(param_dict['epoch2']))
param_dict['query_results_filepath'] = param_dict['query_results_dirpath'] + query_results_filename
output_log_entry(param_dict['log_filepath'],'SSOIS query results filepath: {:s}'.format(param_dict['query_results_filepath']))
return param_dict
def execute_ssois_search(param_dict):
url = param_dict['ssois_search_url']
result_filepath = param_dict['query_results_filepath']
if not os.path.exists(result_filepath):
output_log_entry(param_dict['log_filepath'],'Starting SSOIS query...')
query_successful = True
max_retries = 50
for _ in range(max_retries):
try:
urllib.request.urlretrieve(url.strip(),result_filepath)
except Exception:
output_log_entry(param_dict['log_filepath'],'SSOIS query failed. Retrying...'.format(url))
else:
break
else:
output_log_entry(param_dict['log_filepath'],'SSOIS query failed ({:s}). Maximum retries reached'.format(url))
query_successful = False
if query_successful:
output_log_entry(param_dict['log_filepath'],'Saving SSOIS query results to {:s}'.format(result_filepath))
else:
output_log_entry(param_dict['log_filepath'],'SSOIS query results file already found.')
return param_dict
def parse_ssois_query_results(param_dict):
query_results_filepath = param_dict['query_results_filepath']
query_results = {}
with open(query_results_filepath,'r') as query_results_file:
for _ in range(1): #skip first header line
next(query_results_file)
for line in query_results_file:
line_data = re.split(r'\t+',line.rstrip('\t'))
image_name = line_data[0]
query_results[image_name] = {}
query_results[image_name]['mjd'] = float(str(line_data[1]))
query_results[image_name]['filter_name'] = line_data[2]
query_results[image_name]['exptime'] = float(str(line_data[3]))
query_results[image_name]['obj_ra'] = float(str(line_data[4]))
query_results[image_name]['obj_dec'] = float(str(line_data[5]))
query_results[image_name]['img_target'] = line_data[6]
query_results[image_name]['datalink'] = line_data[8].strip()
param_dict['query_results'] = query_results
output_log_entry(param_dict['log_filepath'],'Query results read in from {:s}'.format(query_results_filepath))
return param_dict
def parse_ssois_query_results_decam(param_dict):
query_results_filepath = param_dict['query_results_filepath']
query_results = {}
prev_image_name,prev_image_prefix,prev_image_suffix = '','',''
with open(query_results_filepath,'r') as query_results_file:
for _ in range(1): #skip first header line
next(query_results_file)
for line in query_results_file:
line_data = re.split(r'\t+',line.rstrip('\t'))
image_name = line_data[0].split()[0].strip()
if '_ooi_' in image_name:
image_prefix = image_name[:17]
image_suffix = image_name[24:-8]
if image_prefix == prev_image_prefix:
if prev_image_suffix != 'v1':
if image_suffix == 'v1' or ('v' in image_suffix and 'v' not in prev_image_suffix) or ('ls' in image_suffix and 'a' in prev_image_suffix):
del query_results[prev_image_name]
query_results[image_name] = {}
query_results[image_name]['mjd'] = line_data[1]
query_results[image_name]['filter_name'] = line_data[2]
query_results[image_name]['exptime'] = line_data[3]
query_results[image_name]['obj_ra'] = line_data[4]
query_results[image_name]['obj_dec'] = line_data[5]
query_results[image_name]['img_target'] = line_data[6]
query_results[image_name]['datalink'] = line_data[8].strip()
prev_image_name = image_name
prev_image_prefix = image_prefix
prev_image_suffix = image_suffix
else:
query_results[image_name] = {}
query_results[image_name]['mjd'] = line_data[1]
query_results[image_name]['filter_name'] = line_data[2]
query_results[image_name]['exptime'] = line_data[3]
query_results[image_name]['obj_ra'] = line_data[4]
query_results[image_name]['obj_dec'] = line_data[5]
query_results[image_name]['img_target'] = line_data[6]
query_results[image_name]['datalink'] = line_data[8].strip()
prev_image_name = image_name
prev_image_prefix = image_prefix
prev_image_suffix = image_suffix
param_dict['query_results'] = query_results
output_log_entry(param_dict['log_filepath'],'Query results read in from {:s}'.format(query_results_filepath))
return param_dict
########## DATA DOWNLOADING AND INITIAL PROCESSING FUNCTIONS ##########
def download_ssois_query_result_files(param_dict):
output_log_entry(param_dict['log_filepath'],'Downloading {:s} data for {:s} from {:s} to {:s}...'.format(param_dict['telinst'],param_dict['target_name'],param_dict['epoch1'].replace('+','-'),param_dict['epoch2'].replace('+','-')))
query_results = param_dict['query_results']
images_to_delete = []
for image_name in query_results:
download_filename = ''
if param_dict['telinst'] == 'CTIO-4m/DECam':
if float(str(param_dict['query_results'][image_name]['exptime'])) >= 30 and param_dict['query_results'][image_name]['filter_name'] not in ['u','Y']:
download_filename = param_dict['query_results_dirpath'] + image_name
else:
images_to_delete.append(image_name)
elif param_dict['telinst'] == 'CFHT/MegaCam':
if float(str(param_dict['query_results'][image_name]['exptime'])) >= 30 and param_dict['query_results'][image_name]['filter_name'] not in ['u','Y']:
download_filename = param_dict['query_results_dirpath'] + os.path.basename(query_results[image_name]['datalink'])
else:
images_to_delete.append(image_name)
else:
download_filename = param_dict['query_results_dirpath'] + os.path.basename(query_results[image_name]['datalink'])
if download_filename != '' and not os.path.exists(download_filename) and not os.path.exists(download_filename[:-3]) and not os.path.exists(download_filename[:-4]):
try:
output_log_entry(param_dict['log_filepath'],'Downloading {:s} to {:s}'.format(query_results[image_name]['datalink'],download_filename))
urllib.request.urlretrieve(query_results[image_name]['datalink'],download_filename)
except:
output_log_entry(param_dict['log_filepath'],'{:s} could not be downloaded ({:s})'.format(download_filename,query_results[image_name]['datalink']))
images_to_delete.append(image_name)
for image_name in images_to_delete:
del param_dict['query_results'][image_name]
param_dict = decompress_data_get_metadata(param_dict)
return param_dict
def decompress_data_get_metadata(param_dict):
if param_dict['telinst'] == 'SDSS':
param_dict = decompress_data_bz2(param_dict)
param_dict = extract_metadata_sdss(param_dict)
if param_dict['telinst'] == 'CTIO-4m/DECam':
param_dict = decompress_data_fz(param_dict)
param_dict = extract_metadata_decam(param_dict)
if param_dict['telinst'] == 'CFHT/MegaCam':
param_dict = decompress_data_fz(param_dict)
param_dict = extract_metadata_megacam(param_dict)
return param_dict
def extract_metadata_sdss(param_dict):
for fits_filename in param_dict['fits_filenames']:
with fits.open(fits_filename) as hdulist:
hdr = hdulist[0].header
date_utc = hdr['DATE-OBS']
time_start_utc = hdr['TAIHMS']
exposure_time = float(hdr['EXPTIME'])
time_start = Time('{:s} {:s}'.format(date_utc,time_start_utc),scale='utc',format='iso')
time_start_jd = float(time_start.jd)
mid_dt = TimeDelta(exposure_time,format='sec') / 2
time_mid = time_start + mid_dt
time_mid_jd = float(time_mid.jd)
filter_name = hdr['FILTER'].strip()
print('filter_name for {:s}: {:s} --> '.format(fits_filename,filter_name),end='')
if filter_name == 'u': filter_name = 'u_sdss'
if filter_name == 'g': filter_name = 'g_sdss'
if filter_name == 'r': filter_name = 'r_sdss'
if filter_name == 'i': filter_name = 'i_sdss'
if filter_name == 'z': filter_name = 'z_sdss'
print('{:s}'.format(filter_name))
param_dict['fits_filenames'][fits_filename]['date_utc'] = date_utc
param_dict['fits_filenames'][fits_filename]['time_start_utc'] = time_start_utc
param_dict['fits_filenames'][fits_filename]['exposure_time'] = exposure_time
param_dict['fits_filenames'][fits_filename]['time_start'] = time_start
param_dict['fits_filenames'][fits_filename]['time_start_jd'] = time_start_jd
param_dict['fits_filenames'][fits_filename]['time_mid'] = time_mid
param_dict['fits_filenames'][fits_filename]['time_mid_jd'] = time_mid_jd
param_dict['fits_filenames'][fits_filename]['filter'] = filter_name
return param_dict
def extract_metadata_decam(param_dict):
images_to_delete = []
for fits_filename in param_dict['fits_filenames']:
try:
with fits.open(fits_filename) as hdulist:
hdr = hdulist[0].header
date_utc = hdr['DATE-OBS'][:10]
time_start_utc = hdr['DATE-OBS'][11:]
exposure_time = float(hdr['EXPTIME'])
time_start = Time('{:s} {:s}'.format(date_utc,time_start_utc),scale='utc',format='iso')
time_start_jd = float(time_start.jd)
mid_dt = TimeDelta(exposure_time,format='sec') / 2
time_mid = time_start + mid_dt
time_mid_jd = float(time_mid.jd)
filter_name = hdr['FILTER'].strip()
print('filter_name for {:s}: {:s} --> '.format(fits_filename,filter_name),end='')
if filter_name == 'g DECam SDSS c0001 4720.0 1520.0': filter_name = 'g_sdss'
if filter_name == 'r DECam SDSS c0002 6415.0 1480.0': filter_name = 'r_sdss'
if filter_name == 'i DECam SDSS c0003 7835.0 1470.0': filter_name = 'i_sdss'
if filter_name == 'z DECam SDSS c0004 9260.0 1520.0': filter_name = 'z_sdss'
if filter_name == 'Y DECam c0005 10095.0 1130.0': filter_name = 'Y'
if filter_name == 'VR DECam c0007 6300.0 2600.0': filter_name = 'VR'
print('{:s}'.format(filter_name))
param_dict['fits_filenames'][fits_filename]['date_utc'] = date_utc
param_dict['fits_filenames'][fits_filename]['time_start_utc'] = time_start_utc
param_dict['fits_filenames'][fits_filename]['exposure_time'] = exposure_time
param_dict['fits_filenames'][fits_filename]['time_start'] = time_start
param_dict['fits_filenames'][fits_filename]['time_start_jd'] = time_start_jd
param_dict['fits_filenames'][fits_filename]['time_mid'] = time_mid
param_dict['fits_filenames'][fits_filename]['time_mid_jd'] = time_mid_jd
param_dict['fits_filenames'][fits_filename]['filter'] = filter_name
except:
output_log_entry(param_dict['log_filepath'],'Extraction of metadata from {:s} failed.'.format(fits_filename))
images_to_delete.append(fits_filename)
for fits_filename in images_to_delete:
if fits_filename in param_dict['fits_filenames']:
del param_dict['fits_filenames'][fits_filename]
return param_dict
def extract_metadata_megacam(param_dict):
images_to_delete = []
for fits_filename in param_dict['fits_filenames']:
try:
with fits.open(fits_filename) as hdulist:
hdr = hdulist[0].header
date_utc = hdr['DATE-OBS']
time_start_utc = hdr['UTC-OBS']
exposure_time = float(hdr['EXPTIME'])
time_start = Time('{:s} {:s}'.format(date_utc,time_start_utc),scale='utc',format='iso')
time_start_jd = float(time_start.jd)
mid_dt = TimeDelta(exposure_time,format='sec') / 2
time_mid = time_start + mid_dt
time_mid_jd = float(time_mid.jd)
filter_name = hdr['FILTER'].strip()
print('filter_name for {:s}: {:s} --> '.format(fits_filename,filter_name),end='')
if filter_name == 'u.MP9301': filter_name = 'u_sdss'
if filter_name == 'g.MP9401': filter_name = 'g_sdss'
if filter_name == 'g.MP9402': filter_name = 'g_sdss'
if filter_name == 'r.MP9601': filter_name = 'r_sdss'
if filter_name == 'r.MP9602': filter_name = 'r_sdss'
if filter_name == 'i.MP9701': filter_name = 'i_sdss'
if filter_name == 'i.MP9702': filter_name = 'i_sdss'
if filter_name == 'i.MP9703': filter_name = 'i_sdss'
if filter_name == 'z.MP9801': filter_name = 'z_sdss'
if filter_name == 'z.MP9901': filter_name = 'z_sdss'
if filter_name == 'gri.MP9605': filter_name = 'gri'
print('{:s}'.format(filter_name))
param_dict['fits_filenames'][fits_filename]['date_utc'] = date_utc
param_dict['fits_filenames'][fits_filename]['time_start_utc'] = time_start_utc
param_dict['fits_filenames'][fits_filename]['exposure_time'] = exposure_time
param_dict['fits_filenames'][fits_filename]['time_start'] = time_start
param_dict['fits_filenames'][fits_filename]['time_start_jd'] = time_start_jd
param_dict['fits_filenames'][fits_filename]['time_mid'] = time_mid
param_dict['fits_filenames'][fits_filename]['time_mid_jd'] = time_mid_jd
param_dict['fits_filenames'][fits_filename]['filter'] = filter_name
except:
output_log_entry(param_dict['log_filepath'],'Extraction of metadata from {:s} failed.'.format(fits_filename))
images_to_delete.append(fits_filename)
for fits_filename in images_to_delete:
if fits_filename in param_dict['fits_filenames']:
del param_dict['fits_filenames'][fits_filename]
return param_dict
########## COMPRESSION/DECOMPRESSION FUNCTIONS ##########
def decompress_data_bz2(param_dict):
output_log_entry(param_dict['log_filepath'],'Decompressing .bz2 data...')
os.chdir(param_dict['query_results_dirpath'])
param_dict['fits_filenames'] = {}
for image_name in param_dict['query_results']:
filename_bz2 = os.path.basename(param_dict['query_results'][image_name]['datalink'])
filename = filename_bz2[:-4]
param_dict['fits_filenames'][filename] = {}
if os.path.exists(filename_bz2) and not os.path.exists(filename):
with bz2.open(filename_bz2,'rb') as f, open(filename,'wb') as of:
data = f.read()
of.write(data)
os.remove(filename_bz2)
output_log_entry(param_dict['log_filepath'],'Decompressing .bz2 data complete.')
return param_dict
def decompress_data_fz(param_dict):
output_log_entry(param_dict['log_filepath'],'Decompressing .fz data...')
os.chdir(param_dict['query_results_dirpath'])
param_dict['fits_filenames'] = {}
images_to_delete = []
for image_name in param_dict['query_results']:
if param_dict['telinst'] == 'CTIO-4m/DECam':
filename_fz = image_name
else:
filename_fz = os.path.basename(param_dict['query_results'][image_name]['datalink'])
filename = filename_fz[:-3]
param_dict['fits_filenames'][filename] = {}
try:
if os.path.exists(filename_fz) and not os.path.exists(filename):
funpack(filename_fz,param_dict['config'])
except:
del param_dict['fits_filenames'][filename]
output_log_entry(param_dict['log_filepath'],'Decompressing .fz data complete.')
return param_dict
########## GENERAL PHOTOMETRY FUNCTIONS ##########
def perform_photometry(param_dict):
filters = ['g_sdss','r_sdss','i_sdss','z_sdss','B','V','R','I']
param_dict = convert_field_source_apert_params_to_pixels(param_dict)
param_dict = convert_target_apert_params_to_pixels(param_dict)
param_dict = run_horizons_queries(param_dict)
param_dict = initialize_target_photometry_output_file(param_dict)
for fits_filename in param_dict['fits_filenames']:
param_dict = search_for_detection_in_extensions(param_dict,fits_filename)
if param_dict['fits_filenames'][fits_filename]['target_ext_id'] != -1:
if param_dict['fits_filenames'][fits_filename]['filter'] in filters:
param_dict = perform_field_source_photometry(param_dict,fits_filename)
param_dict = perform_target_source_photometry(param_dict,fits_filename)
param_dict = write_target_photometry_to_file(param_dict,fits_filename)
else:
output_log_entry(param_dict['log_filepath'],'Skipping photometry of {:s} (non-standard filter).'.format(fits_filename))
else:
output_log_entry(param_dict['log_filepath'],'Skipping photometry of {:s} (object not in FOV).'.format(fits_filename))
clean_output_files(param_dict,fits_filename)
return param_dict
def convert_field_source_apert_params_to_pixels(param_dict):
pixscale = param_dict['instrument_params']['pixscale']
field_source_phot_radius_pix = param_dict['field_source_phot_radius_arcsec'] / pixscale
sky_inner_r_pix = param_dict['sky_inner_r_arcsec'] / pixscale
sky_outer_r_pix = param_dict['sky_outer_r_arcsec'] / pixscale
param_dict['field_source_phot_radius_pix'] = field_source_phot_radius_pix
param_dict['sky_inner_r_pix'] = sky_inner_r_pix
param_dict['sky_outer_r_pix'] = sky_outer_r_pix
return param_dict
def convert_target_apert_params_to_pixels(param_dict):
output_log_entry(param_dict['log_filepath'],'Converting target apertures from arcsec to pixels...')
pixscale = param_dict['instrument_params']['pixscale']
target_phot_radii_arcsec = param_dict['target_phot_radii_arcsec']
target_phot_radii_pix = [0 for idx in range(len(target_phot_radii_arcsec))]
for idx in range(len(target_phot_radii_pix)):
target_phot_radii_pix[idx] = target_phot_radii_arcsec[idx] / pixscale
target_sky_inner_r_pix = param_dict['target_sky_inner_r_arcsec'] / pixscale
target_sky_outer_r_pix = param_dict['target_sky_outer_r_arcsec'] / pixscale
param_dict['target_phot_radii_pix'] = target_phot_radii_pix
param_dict['target_sky_inner_r_pix'] = target_sky_inner_r_pix
param_dict['target_sky_outer_r_pix'] = target_sky_outer_r_pix
return param_dict
def search_for_detection_in_extensions(param_dict,fits_filename):
pixscale = param_dict['instrument_params']['pixscale']
num_elements = param_dict['instrument_params']['num_elements']
first_element = param_dict['instrument_params']['first_element']
output_log_entry(param_dict['log_filepath'],'Searching for target in {:s}...'.format(fits_filename))
target_ext_id = -1
obj_ra = param_dict['fits_filenames'][fits_filename]['ephem']['ra_deg']
obj_dec = param_dict['fits_filenames'][fits_filename]['ephem']['dec_deg']
for idx in range(0,num_elements):
ext_id = first_element + idx
ext_filename = fits_filename[:-5] + '_{:02d}.fits'.format(ext_id)
if not os.path.exists(ext_filename):
extract_extension_data(param_dict,fits_filename,ext_filename,ext_id)
#with fits.open(fits_filename) as hdulist:
# hdr = getheader(fits_filename,0)
# data = hdulist[0].data
# fits.writeto(ext_filename,data,hdr)
ext_filename_wcs = compute_astrometric_solution(param_dict,ext_filename)
if ext_filename_wcs != '':
header = fits.getheader(ext_filename_wcs)
w = WCS(header)
with fits.open(ext_filename_wcs) as hdulist:
data = hdulist[0].data
npix_y,npix_x = data.shape
obj_x,obj_y = w.wcs_world2pix(obj_ra,obj_dec,1)
if obj_x >= 1 and obj_x <= npix_x and obj_y >= 1 and obj_y <= npix_y:
output_log_entry(param_dict['log_filepath'],'Target in FOV of {:s} ({:.1f},{:.1f}).'.format(ext_filename_wcs,obj_x,obj_y))
target_ext_id = ext_id
break
else:
output_log_entry(param_dict['log_filepath'],'Target not in FOV of {:s} ({:.1f},{:.1f}).'.format(ext_filename_wcs,obj_x,obj_y))
os.remove(ext_filename_wcs)
obj_x,obj_y = 0,0
if target_ext_id == -1:
output_log_entry(param_dict['log_filepath'],'Target not found in {:s}.'.format(fits_filename))
param_dict['fits_filenames'][fits_filename]['target_ext_id'] = target_ext_id
param_dict['fits_filenames'][fits_filename]['ext_filename_wcs'] = ext_filename_wcs
param_dict['fits_filenames'][fits_filename]['npix_x'] = npix_x
param_dict['fits_filenames'][fits_filename]['npix_y'] = npix_y
param_dict['fits_filenames'][fits_filename]['obj_x'] = obj_x
param_dict['fits_filenames'][fits_filename]['obj_y'] = obj_y
return param_dict
########## FIELD SOURCE PHOTOMETRY FUNCTIONS ##########
def perform_field_source_photometry(param_dict,fits_filename):
output_log_entry(param_dict['log_filepath'],'Performing field source aperture photometry for {:s}...'.format(fits_filename))
param_dict = find_field_sources(param_dict,fits_filename)
param_dict = plot_field_source_apertures(param_dict,fits_filename)
param_dict = measure_field_source_photometry(param_dict,fits_filename)
param_dict = write_field_source_photometry_to_file(param_dict,fits_filename)
param_dict = write_calibration_stars_to_file(param_dict,fits_filename)
output_log_entry(param_dict['log_filepath'],'Field source aperture photometry for {:s} complete.'.format(fits_filename))
return param_dict
def find_field_sources(param_dict,fits_filename):
# Extracts field sources from image using DAOStarFinder
# Based on code in https://photutils.readthedocs.io/en/stable/detection.html
ext_filename_wcs = param_dict['fits_filenames'][fits_filename]['ext_filename_wcs']
ext_filename_wcs_bgsub = ext_filename_wcs[:-5] + '_bgsub.fits'
param_dict['fits_filenames'][fits_filename]['ext_filename_wcs_bgsub'] = ext_filename_wcs_bgsub
with fits.open(ext_filename_wcs) as hdu_data:
data = hdu_data[0].data
hdr = hdu_data[0].header
sigma_clip = SigmaClip(sigma=3.0)
bkg_estimator = MedianBackground()
bkg = Background2D(data,(50,50),filter_size=(3,3),sigma_clip=sigma_clip,bkg_estimator=bkg_estimator)
data_bgsub = data - bkg.background
mean,median,std = sigma_clipped_stats(data_bgsub,sigma=3.0)
fits.writeto(ext_filename_wcs_bgsub,data_bgsub,hdr,overwrite=True,checksum=True)
#param_dict['fits_filenames'][fits_filename]['nx'] = nx
#param_dict['fits_filenames'][fits_filename]['ny'] = ny
#param_dict['fits_filenames'][fits_filename]['mean'] = mean
#param_dict['fits_filenames'][fits_filename]['median'] = median
#param_dict['fits_filenames'][fits_filename]['std'] = std
daofind = DAOStarFinder(fwhm=param_dict['daofind_fwhm'],threshold=param_dict['daofind_sigma_threshold']*std)
field_sources = daofind(data_bgsub)
if field_sources is not None:
num_field_sources = len(field_sources['xcentroid'])
else:
num_field_sources = 0
if num_field_sources != 0:
header = fits.getheader(ext_filename_wcs)
w = WCS(header)
field_sources['ra'],field_sources['dec'] = w.wcs_pix2world(field_sources['xcentroid'],field_sources['ycentroid'],1)
field_sources['radec'] = SkyCoord(field_sources['ra'],field_sources['dec'],unit='deg')
field_sources['positions'] = np.transpose((field_sources['xcentroid'],field_sources['ycentroid']))
output_filename = ext_filename_wcs[:-5]+'.field_sources.txt'
with open(output_filename,'w') as of:
of.write('star_id RA (deg) Dec (deg) xcoord ycoord\n')
for idx in range(len(field_sources['ra'])):
of.write(' {:03d} {:11.7f} {:11.7f} {:9.3f} {:9.3f}\n'.format(idx+1,field_sources['ra'][idx],field_sources['dec'][idx],field_sources['xcentroid'][idx],field_sources['ycentroid'][idx]))
#print(field_sources.colnames)
output_log_entry(param_dict['log_filepath'],'{:d} sources found'.format(num_field_sources))
param_dict['fits_filenames'][fits_filename]['field_sources'] = field_sources
return param_dict
#############################################################
## Define functions to plot source positions and apertures ##
#############################################################
def plot_field_source_apertures(param_dict,fits_filename):
# Plots all source positions and apertures identified by DAOStarFinder
output_log_entry(param_dict['log_filepath'],'Plotting field source photometry apertures for {:s}...'.format(fits_filename))
ext_filename_wcs = param_dict['fits_filenames'][fits_filename]['ext_filename_wcs']
data,error,imwcs = extract_image_file_data(ext_filename_wcs)
ny,nx = data.shape
field_source_phot_radius_pix = param_dict['field_source_phot_radius_pix']
sky_inner_r_pix = param_dict['sky_inner_r_pix']
sky_outer_r_pix = param_dict['sky_outer_r_pix']
field_sources = param_dict['fits_filenames'][fits_filename]['field_sources']
positions = np.transpose((field_sources['xcentroid'],field_sources['ycentroid']))
aperture = CircularAperture(positions,r=field_source_phot_radius_pix)
annulus_aperture = CircularAnnulus(positions,r_in=sky_inner_r_pix,r_out=sky_outer_r_pix)
norm = simple_norm(data,'sqrt',percent=99)
plt.imshow(data,norm=norm,interpolation='nearest')
plt.xlim(0,nx)
plt.ylim(0,ny)
ap_patches = aperture.plot(color='white',lw=1,label='Photometry aperture')
ann_patches = annulus_aperture.plot(color='red',lw=1,label='Background annulus')
handles = (ap_patches[0],ann_patches[0])
plt.legend(loc=(0.17,0.05),facecolor='#458989',labelcolor='white',handles=handles,prop={'weight':'bold','size':11})
# Save to a File
plot_filepath = ext_filename_wcs[:-5]+'.field_source_apertures.pdf'
plt.savefig(plot_filepath,format = 'pdf', transparent=True)
plt.clf()
plt.cla()
plt.close()
output_log_entry(param_dict['log_filepath'],'Field source photometry apertures plotted ({:s}).'.format(plot_filepath))
return param_dict
#####################################################
## Define functions to perform aperture photometry ##
#####################################################
def measure_field_source_photometry(param_dict,fits_filename):
# photometry stored as Astropy tables in photometry dictionary indexed by image filename
# aperture positions stored in param_dict['fits_filenames'][fits_filename]['field_sources']['positions']
# photometry table columns: aperture_sum,aperture_sum_err,aperture_area,annulus_median,aperture_bkg,aperture_sum_bkgsub
# "print(field_source_phot_table.colnames)" to access column names of astropy table
field_source_phot_table = Table()
ext_filename_wcs = param_dict['fits_filenames'][fits_filename]['ext_filename_wcs']
# Set photometry aperture positions and sizes
positions = param_dict['fits_filenames'][fits_filename]['field_sources']['positions']
field_source_phot_radius_arcsec = param_dict['field_source_phot_radius_arcsec']
field_source_phot_radius_pix = param_dict['field_source_phot_radius_pix']
aperture = CircularAperture(positions,r=field_source_phot_radius_pix)
output_log_entry(param_dict['log_filepath'],'Photometry radius r = {:.2f} arcsec ({:.6f} px)'.format(field_source_phot_radius_arcsec,field_source_phot_radius_pix))
# Read in image data
data,error,imwcs = extract_image_file_data(ext_filename_wcs)
# Compute image background properties from sky annuli
sky_inner_r_pix = param_dict['sky_inner_r_pix']
sky_outer_r_pix = param_dict['sky_outer_r_pix']
annulus_aperture = CircularAnnulus(positions,r_in=sky_inner_r_pix,r_out=sky_outer_r_pix)
annulus_mask = annulus_aperture.to_mask(method='center')
bkg_median,bkg_stdev = [],[]
for mask in annulus_mask:
annulus_data = mask.multiply(data)
annulus_data_1d = annulus_data[mask.data > 0]
_,median_sigclip,stdev_sigclip = sigma_clipped_stats(annulus_data_1d)
bkg_median.append(median_sigclip)
bkg_stdev.append(stdev_sigclip)
bkg_median = np.array(bkg_median)
bkg_stdev = np.array(bkg_stdev)
# Run aperture photometry function
phot = aperture_photometry(data,aperture,method='exact',error=error)
phot['aperture_bkg'] = bkg_median*aperture.area
phot['aperture_sum_bkgsub'] = phot['aperture_sum'] - phot['aperture_bkg']
# Compute zeropoint from field sources if image uses a standard broadband filter
if param_dict['fits_filenames'][fits_filename]['filter'] in ['g_sdss','r_sdss','i_sdss','z_sdss','B','V','R','I']:
param_dict = create_field_source_table(param_dict,fits_filename,phot)
param_dict = compute_zero_point(param_dict,fits_filename)
zeropoint = ufloat(param_dict['fits_filenames'][fits_filename]['median_zeropoint_mag'],param_dict['fits_filenames'][fits_filename]['median_zeropoint_err'])
# Compute magnitudes of field sources from measured fluxes
exptime = param_dict['fits_filenames'][fits_filename]['exposure_time']
phot['mag'],phot['magerr'] = fluxes2mags(phot['aperture_sum_bkgsub'],phot['aperture_sum_err'],zeropoint,exptime)
#phot['target_mag'] = [0.0 for idx in range(0,len(phot['mag']))]
#phot['target_magerr'] = [0.0 for idx in range(0,len(phot['mag']))]
#phot['mag_corr'] = [0.0 for idx in range(0,len(phot['mag']))]
#phot['magerr_corr'] = [0.0 for idx in range(0,len(phot['mag']))]
# Transfer data from aperture photometry output table to phot_table and convert to mag
field_source_phot_table.add_column(phot['aperture_sum'],name='aperture_sum')
field_source_phot_table.add_column(phot['aperture_sum_err'],name='aperture_sum_err')
field_source_phot_table.add_column(aperture.area,name='aperture_area')
field_source_phot_table.add_column(bkg_median,name='annulus_median')
field_source_phot_table.add_column(bkg_stdev,name='annulus_stdev')
field_source_phot_table.add_column(phot['aperture_bkg'],name='aperture_bkg')
field_source_phot_table.add_column((phot['aperture_sum_bkgsub']),name='aperture_sum_bkgsub')
field_source_phot_table.add_column((phot['mag']),name='mag')
field_source_phot_table.add_column((phot['magerr']),name='magerr')
#field_source_phot_table.add_column((phot['target_mag']),name='target_mag')
#field_source_phot_table.add_column((phot['target_magerr']),name='target_magerr')
#field_source_phot_table.add_column((phot['mag_corr']),name='mag_corr')
#field_source_phot_table.add_column((phot['magerr_corr']),name='magerr_corr')
param_dict['fits_filenames'][fits_filename]['field_source_phot_table'] = field_source_phot_table
return param_dict
def create_field_source_table(param_dict,fits_filename,phot):
# Create field source table with aperture photometry
field_source_table = Table()
output_log_entry(param_dict['log_filepath'],'Creating field source table from param_dict...')
x = param_dict['fits_filenames'][fits_filename]['field_sources']['xcentroid']
y = param_dict['fits_filenames'][fits_filename]['field_sources']['ycentroid']
ra = param_dict['fits_filenames'][fits_filename]['field_sources']['ra']
dec = param_dict['fits_filenames'][fits_filename]['field_sources']['dec']
flux = phot['aperture_sum_bkgsub']
dflux = phot['aperture_sum_err']
field_source_table = Table([x,y,ra,dec,flux,dflux], names=('x','y','ra','dec','flux','dflux'), dtype=('f8','f8','f8','f8','f8','f8'))
#num_field_sources = len(field_source_table)
idx,field_sources_removed = 0,0
while idx < len(field_source_table):
# Remove stars with negative or zero fluxes or dflux > flux
if field_source_table[idx]['flux'] <= 0 or field_source_table[idx]['flux'] < field_source_table[idx]['dflux']:
field_source_table.remove_row(idx)
field_sources_removed += 1
else:
idx += 1
output_log_entry(param_dict['log_filepath'],'Removed {:d} bad sources (negative flux or large fluxerr) from field source table.'.format(field_sources_removed))
field_source_table['SNR'] = -999.0
num_sources = len(field_source_table)
for idx in range(0,num_sources):
field_source_table[idx]['SNR'] = field_source_table[idx]['flux'] / field_source_table[idx]['dflux']
field_source_table['refcat_ra'] = -999.0
field_source_table['refcat_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['R_mag'] = -999.0
field_source_table['R_err'] = -999.0
field_source_table['I_mag'] = -999.0
field_source_table['I_err'] = -999.0
field_source_table['target_dist'] = -999.0
field_source_table['zero_point'] = -999.0
field_source_table['zpoint_err'] = -999.0
param_dict['fits_filenames'][fits_filename]['field_source_table'] = field_source_table
output_log_entry(param_dict['log_filepath'],'Field source table created.')
return param_dict
########## TARGET PHOTOMETRY FUNCTIONS ##########
def perform_target_source_photometry(param_dict,fits_filename):
param_dict = find_target_candidate_sources(param_dict,fits_filename)
param_dict = find_target_source(param_dict,fits_filename)
param_dict = plot_target_apertures(param_dict,fits_filename)
param_dict = measure_target_photometry(param_dict,fits_filename)
return param_dict
def initialize_target_photometry_output_file(param_dict):
target_phot_radii_arcsec = param_dict['target_phot_radii_arcsec']
for target_phot_radius_arcsec in target_phot_radii_arcsec:
output_filename = 'target_phot_results.ap{:04.1f}arcsec.txt'.format(target_phot_radius_arcsec)
target = param_dict['target_name']
telescope = param_dict['telinst']
with open(output_filename,'w') as of:
of.write('target telescope filename jdmid ')
of.write('UTdate UTtimemid UTtimemidHr exptime ')
of.write('filter airmass EphemRA EphemDec ')
of.write(' RA_rate Dec_rate tot_rate expt_trail_pa expt_trail_len heliodist geodist ')
of.write('phsang PA_AS PA_NHV orbplang ')
of.write('trueanom Vmag Nmag Tmag RA_3sigma Dec_3sigma ')
of.write(' xcoord ycoord flux dflux ')
of.write(' SNR RA Dec zeropt zpterr ')
of.write('nrefstars apert mag magerr limit_ps limit_sb')
of.write('\n')
return param_dict
##### FILE COMPRESSION FUNCTIONS #####
def fpack(filepath,config):
filepath_fz = ''
if 'cmd_fpack' in config:
try:
cmd = [config['cmd_fpack'],filepath]
process = subprocess.call(cmd)
os.remove(filepath)
filepath_fz = filepath + '.fz'
except:
print('Function failed: fpack() (check if file is a FITS file)')
else:
print('Function failed: fpack() (local command not found)')
return filepath_fz
def funpack(filepath_fz,config):
filepath = ''
if 'cmd_funpack' in config:
try:
cmd = [config['cmd_funpack'],filepath_fz]
process = subprocess.call(cmd)
os.remove(filepath_fz)
filepath = filepath_fz[:-3]
except:
print('Function failed: funpack() (check if file is a fpacked FITS file)')
else:
print('Function failed: funpack() (local command not found)')
return filepath
##### UTILITY FUNCTIONS #####
def file_len(fname):
p = subprocess.Popen(['wc','-l',fname],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result,err = p.communicate()
if p.returncode != 0:
raise IOError(err)
return int(result.strip().split()[0])
def remove_extra_characters(string):
new_string = string.replace('-','')
new_string = new_string.replace('/','')
new_string = new_string.replace('+','')
new_string = new_string.replace(' ','')
return new_string
##### SETUP FUNCTIONS #####
##### LOGGING FUNCTIONS #####
def output_log_entry(log_filepath,log_entry):
with open(log_filepath,'a') as log_file:
print('{:s} - {:s}'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),log_entry))
log_file.write('{:s} - {:s}\n'.format(datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),log_entry))
return None
##### SSOIS SEARCH FUNCTIONS #####
##### ASTROMETRY FUNCTIONS #####
def compute_astrometric_solution(param_dict,fits_filename):
wcs_filename = fits_filename[:-5] + '_wcs.fits'
if not os.path.exists(wcs_filename):
output_log_entry(param_dict['log_filepath'],'Computing astrometric solution for {:s}...'.format(fits_filename))
pixscale = param_dict['instrument_params']['pixscale']
if pixscale != 0:
cmd1,cmd2,cmd3,cmd4,cmd5,cmd6,cmd7 = 'solve-field','--scale-units','arcsecperpix','--scale-low','{:.3f}'.format(pixscale-0.1),'--scale-high','{:.3f}'.format(pixscale+0.1)
cmd = [cmd1,cmd2,cmd3,cmd4,cmd5,cmd6,cmd7,fits_filename]
process = subprocess.call(cmd)
else:
cmd1,cmd2,cmd3 = 'solve-field','--scale-low','1'
cmd = [cmd1,cmd2,cmd3,fits_filename]
process = subprocess.call(cmd)
if os.path.isfile(fits_filename[:-5] + '.solved'):
wcs_filename = fits_filename[:-5] + '_wcs.fits'
os.rename(fits_filename[:-5]+'.new',wcs_filename)
output_log_entry(param_dict['log_filepath'],'Astrometric solution successfully completed.')
clean_wcs_output(fits_filename,param_dict)
os.remove(fits_filename)
else:
wcs_filename = ''
output_log_entry(param_dict['log_filepath'],'Astrometric solution failed.')
else:
output_log_entry(param_dict['log_filepath'],'Astrometric solution for {:s} already computed.'.format(fits_filename))
return wcs_filename
def clean_wcs_output(fits_filename,param_dict):
output_log_entry(param_dict['log_filepath'],'Cleaning up astrometry.net output...')
if os.path.exists(fits_filename[:-5]+'-indx.png'): os.remove(fits_filename[:-5]+'-indx.png')
if os.path.exists(fits_filename[:-5]+'-ngc.png'): os.remove(fits_filename[:-5]+'-ngc.png')
if os.path.exists(fits_filename[:-5]+'-objs.png'): os.remove(fits_filename[:-5]+'-objs.png')
if os.path.exists(fits_filename[:-5]+'-indx.xyls'): os.remove(fits_filename[:-5]+'-indx.xyls')
if os.path.exists(fits_filename[:-5]+'.axy'): os.remove(fits_filename[:-5]+'.axy')
if os.path.exists(fits_filename[:-5]+'.corr'): os.remove(fits_filename[:-5]+'.corr')
if os.path.exists(fits_filename[:-5]+'.match'): os.remove(fits_filename[:-5]+'.match')
if os.path.exists(fits_filename[:-5]+'.rdls'): os.remove(fits_filename[:-5]+'.rdls')
if os.path.exists(fits_filename[:-5]+'.solved'): os.remove(fits_filename[:-5]+'.solved')
if os.path.exists(fits_filename[:-5]+'.wcs'): os.remove(fits_filename[:-5]+'.wcs')
return None
def extract_image_file_data(fits_filename):
with fits.open(fits_filename) as hdu:
data_tmp = hdu[0].data
data = ma.masked_invalid(data_tmp) # mask NaN values
ny,nx = data.shape
imwcs = None
mean,median,std = sigma_clipped_stats(data,sigma=3.0)
error = [[std for idx in range(nx)] for idx in range(ny)]
return data,error,imwcs