-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpodi_swarpstack.py
More file actions
executable file
·2546 lines (2131 loc) · 104 KB
/
podi_swarpstack.py
File metadata and controls
executable file
·2546 lines (2131 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright 2012-2013 Ralf Kotulla & WIYN Observatory
# University of Wisconsin - Milwaukee & Madison
# kotulla@uwm.edu
#
# This file is part of the ODI QuickReduce pipeline package.
#
# If you find this program or parts thereof please make sure to
# cite it appropriately (please contact the author for the most
# up-to-date reference to use). Also if you find any problems
# or have suggestions on how to improve the code or its
# functionality please let me know. Comments and questions are
# always welcome.
#
# The code is made publicly available. Feel free to share the link
# with whoever might be interested. However, I do ask you to not
# publish additional copies on your own website or other sources.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
"""
Function
--------------------------------------------------------------------------------
**podi_swarpstack.py** handles most of the most common stacking problems. It
supports a number of use-cases, from simle stacking a bunch of files, adding
more frames to an additional stack, as well as matching a new frame to a
reference stack.
The general procedure is to create a single rectified image for each of the
input frames first. In a second step, swarp combines all these rectified images
into the final step. While this is overkill for stellar fields, this approach
ensures better sky background subtraction across OTAs in the case of large
galaxies or objects.
Before each run, swarpstack determines the final size of the resulting stacked
frame. Each of the input frames is then rectified, distortion corrected and
interpolated onto this final grid, eliminating double-interpolations.
How to run podi_swarpstack
--------------------------------------------------------------------------------
Simple stacking of a bunch of frames
podi_swarpstack.py output_stack.fits file1.fits file2.fits
Adding frames to an already existing stack
podi_swarpstack.py -add output_stack.fits file3.fits
Matching a new frame to a reference frame
podi_swarpstack.py -reference=reference.fits output_stack.fits file*.fits
Additional command line options
--------------------------------------------------------------------------------
* **-bgsub**
Activate background subtraction. Without this frame no background subtraction
is performed. While this is the safest options for some cases it leads to
rather ratty looking stacks if the sky-level was at all variable during the
exposure (e.g. with moon, twilight, scattered light)
* **-reusesingles**
By default, the single recified images are re-created when swarpstack is being
run. With this option swarpstack checks if a recitified image already exists
and uses the existing file instead of re-creating a new one. This is
particularly helpful and in fact the default if adding new frames to an
already existing stack.
* **-dimension=X**
If given without the -bgsub parameter this option has no effect. If -bgsub is
enabled, the background filtering options are adjusted automatically to avoid
over-subtracting objects of the specified dimenson or smaller, hence avoiding
subtracting the galacy continuum as background fluctuation. The value X
specifies the galaxy/source dimension in arc-minutes.
* **-pixelscale=X**
Chooses the specified pixel scale for the output stack, with X given in
arcsec/pixel.
* **-nonsidereal=a,b,c**
Apply a non-sidereal motion correction to all input frames before stacking.
a is the motion in dRA*cos(dec) in arcseconds/hour, b is the motion dDec, also
in arcsec/hour, and c is the MJD reference, either a valid FITS frame or the
MJD as floating point number
"""
from __future__ import print_function
import os
import sys
import astropy.io.fits as pyfits
import subprocess
import math
import shutil
from podi_commandline import *
from podi_definitions import *
#from podi_collectcells import *
import podi_sitesetup as sitesetup
import podi_illumcorr
import multiprocessing
from podi_fitskybackground import sample_background_using_ds9_regions
import podi_associations
import podi_photflat
import podi_logging
import logging
import socket
import tempfile
import shutil
import warnings
import time
import itertools
import bottleneck
import ephem
import ic_background
from podi_focalplanelayout import FocalPlaneLayout
# try:
# # sys.path.append("/work/quickreduce/merge_master_py3/test/")
# # print(sys.path)
# import ephemerides
# import podi_ephemerides
# print("Added the test durectory for ephems")
# except:
# pass
def mp_prepareinput(input_queue, output_queue, swarp_params, options, apf_data=None):
while (True):
cmd = input_queue.get()
if (cmd is None):
input_queue.task_done()
break
(input_file, fileid) = cmd
logger = logging.getLogger("MP-Prep( %s )" % (os.path.basename(input_file)))
ret = {
"master_reduction_files": {},
"corrected_file": None,
'exptime': 0,
'mjd_obs_start': 0,
'mjd_obs_end': 0,
'nonsidereal-dradec': None,
}
try:
hdulist = pyfits.open(input_file)
except IOError:
logger.error("Can't open file %s" % (input_file))
output_queue.put(None)
input_queue.task_done()
continue
mjd_obs_start = hdulist[0].header['MJD-OBS']
exptime = hdulist[0].header['EXPMEAS'] if 'EXPMEAS' in hdulist[0].header else \
hdulist[0].header['EXPTIME']
mjd_obs_end = hdulist[0].header['MJD-OBS'] + (exptime/86400.)
# Save these values for the return queue
ret['exptime'] = exptime
ret['mjd_obs_start'] = mjd_obs_start
ret['mjd_obs_end'] = mjd_obs_end
corrected_filename = None
# Keep track of what files are being used for this stack
master_reduction_files_used = podi_associations.collect_reduction_files_used(
{}, {"calibrated": input_file} ) #ret['corrected_file']})
if (swarp_params['preswarp_only']):
logger.info("No prepping, working towards pre-swarp only")
ret['corrected_file'] = input_file
ret['gain'] = 1.0
ret['skylevel'] = 0.0
ret['weight'] = 1.
ret["master_reduction_files"] = master_reduction_files_used
hdulist.close()
output_queue.put(ret)
input_queue.task_done()
continue
#
# Compute on how to scale the flux values
#
fluxscale_value = numpy.nan
magzero = hdulist[0].header['PHOTZP_X'] if 'PHOTZP_X' in hdulist[0].header else -99.
if (magzero > 0 and not swarp_params['no-fluxscale']):
fluxscale_value = math.pow(10, 0.4*(swarp_params['target_magzero']-magzero))
else:
exptime = hdulist[0].header['EXPMEAS'] if 'EXPMEAS' in hdulist[0].header else (
hdulist[0].header['EXPTIME'] if 'EXPTIME' in hdulist[0].header else 1.0)
fluxscale_value = 1./exptime
# Assemble the temporary filename for the corrected frame
suffix = None
# Now construct the output filename
if (suffix is None and swarp_params['no-fluxscale'] and not numpy.isnan(fluxscale_value)):
suffix = "exptimenorm"
if (suffix is None and not numpy.isnan(swarp_params['target_magzero']) and not numpy.isnan(fluxscale_value)):
suffix = "fluxnorm"
if (suffix is None and swarp_params['use_nonsidereal']):
suffix = "nonsidereal"
if (suffix is None and swarp_params['use_ephemerides']):
suffix = "ephemerides"
if (suffix is None and options['skip_otas'] != []):
suffix = "otaselect"
if (suffix is None and options['illumcorr']):
suffix = "illumcorr"
if (suffix is None and options['bpm_dir'] is not None):
suffix = "bpmfixed"
if (suffix is None and not swarp_params['subtract_back'] == 'swarp'):
suffix = "skysub"
if (suffix is None and options['photflat'] is not None):
suffix = "photflat"
if (suffix is not None):
corrected_filename = "%(single_dir)s/%(obsid)s.%(suffix)s.%(fileid)d.fits" % {
"single_dir": swarp_params['unique_singledir'],
"obsid": hdulist[0].header['OBSID'],
"suffix": suffix,
"fileid": fileid,
}
logger.info("Applying preparations ...")
#
# Check if we need to apply any corrections
#
if (corrected_filename is None or
(os.path.isfile(corrected_filename) and swarp_params['reuse_singles'])
):
# Either we don't need to apply any corrections or we can re-use an
# older file with these corrections already applied
logger.info("No correction needs to be applied!")
ret['corrected_file'] = input_file
else:
gain = hdulist[0].header['GAIN']
if (swarp_params['use_nonsidereal']):
logger.debug("Applying the non-sidereal motion correction")
# First apply the non-sidereal correction to all input frames
# Keep frames that are already modified
from podi_collectcells import apply_nonsidereal_correction
# print options['nonsidereal']
nonsidereal_dradec = apply_nonsidereal_correction(hdulist, options, logger)
ret["nonsidereal-dradec"] = nonsidereal_dradec
try:
if (os.path.isfile(options['nonsidereal']['ref'])):
master_reduction_files_used = podi_associations.collect_reduction_files_used(
master_reduction_files_used,
{"nonsidereal-reference": options['nonsidereal']['ref']})
except:
pass
if (swarp_params['use_ephemerides']):
# get MJD of current frame
mjd_thisframe = hdulist[0].header['MJD-OBS'] + 0.5*hdulist[0].header['EXPTIME']/2./86400
mjd_ref = swarp_params['ephemerides']['ref-mjd']
# print "\n"*10
# print "ref-mjd",mjd_ref
# print "this mjd",mjd_thisframe
# print "min mjd", numpy.min(swarp_params['ephemerides']['data'][:,0])
# print "max mjd", numpy.max(swarp_params['ephemerides']['data'][:,0])
# print "\n"*10
# now compute the Ra/Dec of the target in both the reference
# frame and in this frame
ephem_data = swarp_params['ephemerides']['data']
logger.debug("EPHEM_DATA: %s" % (ephem_data))
ra_from_mjd = scipy.interpolate.interp1d( ephem_data[:,0], ephem_data[:,1], kind='linear' )
dec_from_mjd = scipy.interpolate.interp1d( ephem_data[:,0], ephem_data[:,2], kind='linear' )
ra_ref = ra_from_mjd(mjd_ref)
ra_this = ra_from_mjd(mjd_thisframe)
dec_ref = dec_from_mjd(mjd_ref)
dec_this = dec_from_mjd(mjd_thisframe)
# print "\n"*5, "ra//dec = ", ra_ref, dec_ref, "\n"*5
# The Ra/Dec correction is how much the object has moved
# (as derived from the ephemerides) between the reference MJD
# and the timestamp of this frame
d_ra = ra_ref - ra_this
d_dec = dec_ref - dec_this
# print d_ra, d_dec
d_days = mjd_thisframe - mjd_ref
logger.debug("Applying ephemerid correction (%+.6f deg, %+.6f deg, dT=%.3f days)" % (
d_ra, d_dec, d_days))
# Now apply these corrections to all extensions with an
# apparently valid WCS system
orig_ra, orig_dec = None, None
for ext in hdulist:
if ('CRVAL1' in ext.header and
'CRVAL2' in ext.header):
# print ext.header['CRVAL1'], ext.header['CRVAL2'], (ext.header['EXTNAME'] if 'EXTNAME' in ext.header else "??")
orig_ra = ext.header['CRVAL1'] if orig_ra is None else orig_ra
orig_dec = ext.header['CRVAL2'] if orig_dec is None else orig_dec
ext.header['CRVAL1'] += d_ra
ext.header['CRVAL2'] += d_dec
# print ext.header['CRVAL1'], ext.header['CRVAL2'], (ext.header['EXTNAME'] if 'EXTNAME' in ext.header else "??")
logger.debug("Pre-correction Ra/Dec was: %12.7f %+12.7f" % (orig_ra, orig_dec))
logger.debug("Post-corrected Ra/Dec is: %12.7f %+12.7f" % (orig_ra + d_ra, orig_dec + d_dec))
ret["nonsidereal-dradec"] = numpy.array([numpy.nan, -d_dec, -d_ra])
if (options['skip_otas'] != []):
logger.debug("Skipping some OTAs")
ota_list = []
for ext in hdulist:
ota = -1
try:
ota = int(ext.header['EXTNAME'][3:5])
except:
pass
if (ota in options['skip_otas']):
logger.debug("skipping ota %s as requested" % (ext.header['EXTNAME']))
continue
ota_list.append(ext)
# Save the modified OTA list for later
hdulist = pyfits.HDUList(ota_list)
#
# Delete the dead OTA 2,1 for data taken past Feb 1st, 2019 (MJD ~ 58515)
# TODO: Add command line option to override this function
#
if (hdulist[0].header['MJD-OBS'] > 58515):
# this data has a dead OTA 2,1
ota_list = []
for ext in hdulist:
if (ext.name == "OTA21.SCI"):
continue
ota_list.append(ext)
hdulist = pyfits.HDUList(ota_list)
if (options['bpm_dir'] is not None):
logger.debug("Applying bad-pixel masks")
for ext in range(len(hdulist)):
if (not is_image_extension(hdulist[ext])):
continue
fppos = None
if ('FPPOS' in hdulist[ext].header):
fppos = hdulist[ext].header['FPPOS']
if (fppos is not None):
region_file = "%s/bpm_%s.reg" % (options['bpm_dir'], fppos)
if (os.path.isfile(region_file)):
mask_broken_regions(hdulist[ext].data, region_file)
master_reduction_files_used = podi_associations.collect_reduction_files_used(
master_reduction_files_used, {"bpm": region_file})
# Loop over all extensions and only select those that are not marked as guide chips
if (True): #options['skip_otas'] != []):
logger.debug("Sorting out guide-OTAs")
ota_list = []
for ext in hdulist:
if ('CELLMODE' in ext.header and
ext.header['CELLMODE'].find("V") >= 0):
logger.debug("skipping ota %s as requested" % (ext.header['EXTNAME']))
continue
if (swarp_params['skip_guide_otas']):
if (is_guide_ota(hdulist[0], ext)):
logger.info("OTA %s is likely guide-OTA, skipping" % (ext.name))
continue
ota_list.append(ext)
# Save the modified OTA list for later
hdulist = pyfits.HDUList(ota_list)
# Mask out saturated pixels
if (swarp_params['mask_saturated'] is not None):
for ext in hdulist:
if (not is_image_extension(ext)):
continue
ext.data[ext.data > swarp_params['mask_saturated']] = numpy.nan
if (options['illumcorr_dir'] is not None):
illum_file = podi_illumcorr.get_illumination_filename(
options['illumcorr_dir'], hdulist[0].header['FILTER'], hdulist[0].header['BINNING'])
logger.debug("Applying illumination correction (%s)" % (illum_file))
master_reduction_files_used = podi_associations.collect_reduction_files_used(
master_reduction_files_used, {"illumination": illum_file})
podi_illumcorr.apply_illumination_correction(hdulist, illum_file)
if (swarp_params['wipe_cells'] is not None):
binning = hdulist[0].header['BINNING']
# XXX ADD SUPPORT FOR SOFTWARE BINNING AS WELL HERE !!!
logger.info("Wiping out specified cells")
for ext in hdulist:
if (not is_image_extension(ext)):
continue
wipecells(ext, swarp_params['wipe_cells'], binning=binning)
# clear out the bottom few rows in each OTA cell to account for the fat-zero problem
if (swarp_params['cheese_grate'] is not None):
if (swarp_params['cheese_grate'] == 'auto'):
# TODO: change the equation for the auto scaling
_skylevel = hdulist[0].header['SKYLEVEL']
n_lines = int((120 - _skylevel) / 10 * 1.5)
if (n_lines <= 0):
n_lines = 0
logger.info("Apply de-cheese-grating [auto-mode]: %d lines", n_lines)
else:
n_lines = swarp_params['cheese_grate']
logger.info("Apply de-cheese-grating [manual mode]: %d lines", n_lines)
fpl = FocalPlaneLayout(hdulist)
for ext in hdulist:
if (not is_image_extension(ext)):
continue
if (fpl.get_detector_generation(ext.header) >= 7):
# this is a lot-7 detector, nothing to do
logger.info("Skipping de-cheese-grate for lot-7 OTA %s" % (ext.name))
continue
for _x in range(8):
for _y in range(8):
x1,x2,y1,y2 = cell2ota__get_target_region(_x, _y, trimcell=0)
ext.data[y1:y1+n_lines+1, x1:x2+1] = numpy.nan
skylevel = 0.
if (not swarp_params['subtract_back'] == False and
not swarp_params['subtract_back'] in ['swarp', "_REGIONS_"] and
not swarp_params['subtract_back'].startswith("IC,")):
skylevel = numpy.nan
if (swarp_params['subtract_back'] in hdulist[0].header):
skylevel = hdulist[0].header[swarp_params['subtract_back']]
else:
try:
skylevel = float(swarp_params['subtract_back'])
except ValueError:
logger.warning("Could not determine sky-level (%s), skipping sky-subtraction" % (
swarp_params['subtract_back']))
except:
raise
if (not numpy.isnan(skylevel)):
for ext in hdulist:
if (not is_image_extension(ext)):
continue
ext.data -= skylevel
logger.debug("Subtracting skylevel (%f) from extension %s" % (skylevel, ext.name))
elif (swarp_params['subtract_back'].startswith("IC,")):
logger.info("Using scale & subtract model for BG subtraction")
ic_file = swarp_params['subtract_back'][3:]
if (not os.path.isfile(ic_file)):
logger.critical("Unable to open IC file for sky-subtraction: %s" % (ic_file))
skylevel = 0
else:
# Now we do have an illumination correction template for sky-subtraction
hdulist, skyframe = ic_background.scale_subtract_background_model(
in_filename=hdulist,
ic_file=ic_file,
out_filename=None, per_ota=True,
twod_model=True,
logger=logger,
)
skylevel = hdulist[0].header['SKYLEVEL']
skyframe.writeto(corrected_filename[:-5]+".skybg.fits", overwrite=True)
elif (swarp_params['subtract_back'] == 'swarp'):
skylevel = hdulist[0].header['SKYLEVEL']
elif (swarp_params['subtract_back'] == "_REGIONS_"):
#
# Get measurements for each of the sky-regions in the current OTA
#
all_sky_samples = None
for ext in hdulist:
if (not is_image_extension(ext)):
continue
sky_samples = sample_background_using_ds9_regions(ext, swarp_params['sky_regions'])
if (type(sky_samples) == type(None)):
continue
#print sky_samples.shape
#print all_sky_samples.shape if all_sky_samples != None else "XXX"
all_sky_samples = sky_samples if type(all_sky_samples) == type(None) else \
numpy.append(all_sky_samples, sky_samples, axis=0)
try:
numpy.savetxt(os.path.basename(input_file)+".sky", all_sky_samples)
logger.info("Found %d sky-samples in user-defined regions" % (all_sky_samples.shape[0]))
except:
pass
#
# Now we have all sky-samples across the entire focal plane
#
if (all_sky_samples is not None and
all_sky_samples.size > 0):
cleaned = three_sigma_clip(all_sky_samples[:,2])
skylevel = numpy.median(cleaned)
skynoise = numpy.std(cleaned)
logger.info("custom: %f vs %f (+/- %f)" % (skylevel, hdulist[0].header['SKYLEVEL'], skynoise))
else:
skylevel = hdulist[0].header['SKYLEVEL']
logger.warning("Not enough sky-samples from ds9 regions, using default skylevel (%f)" % (
skylevel))
for ext in hdulist:
if (not is_image_extension(ext)):
continue
ext.data -= skylevel
logger.debug("Subtracting ds9/user skylevel (%f) from extension %s" % (skylevel, ext.name))
else:
skylevel = hdulist[0].header['SKYLEVEL']
if (options['photflat'] is not None):
photflat_filename = options['photflat']
if (os.path.isfile(photflat_filename)):
# apply correction
photflat_hdu = pyfits.open(photflat_filename)
master_reduction_files_used = podi_associations.collect_reduction_files_used(
master_reduction_files_used, {"photflat": photflat_filename})
for ext in hdulist:
try:
photflat_ext = photflat_hdu[ext.name]
ext.data /= photflat_ext.data
logger.debug("Successfully applied photometric flatfield for %s" % (ext.name))
except (KeyError, ValueError, TypeError):
continue
if (swarp_params['autophotflat'] and apf_data is not None):
# determine which frames to use for the auto-photflat
this_mjd = hdulist[0].header['MJD-OBS']
use_apf_data = apf_data.copy()
use_apf_mjds = numpy.array([float(f) for f in use_apf_data[:,0]])
logger.info("MJD for %s is %f" % (input_file, this_mjd))
this_index = numpy.arange(use_apf_data.shape[0])[(use_apf_data[:,1] == input_file)]
# print this_index
# print "timeframe:", swarp_params['apf_timeframe']
# print "nframes:", swarp_params['apf_nframes']
if (swarp_params['apf_timeframe'] is not None):
_mjd = use_apf_mjds
# print _mjd
select = numpy.fabs(_mjd-this_mjd) <= swarp_params['apf_timeframe']
# print select
logger.info("Found %d frames within %.2f days of mjd=%.6f" % (
numpy.sum(select), swarp_params['apf_timeframe'], this_mjd
))
elif (swarp_params['apf_nframes'] is not None):
idx = numpy.arange(use_apf_data.shape[0])
select = numpy.fabs(idx-this_index) <= swarp_params['apf_nframes']
else:
select = numpy.ones((use_apf_data.shape[0]), dtype=numpy.bool)
if (swarp_params['apf_noauto']):
select[this_index] = False
files_for_apf = [str(f) for f in use_apf_data[select, 1]]
logger.info("Using these files to compute phot.flat for %s:\n%s" % (input_file, "\n".join(list(files_for_apf))))
# Now that we have a list of files, create the photometric
# flatfield
custom_photflat, apf_extras = podi_photflat.create_photometric_flatfield(
filelist = files_for_apf,
smoothing=swarp_params['apf_resolution'],
strict_ota=False,
return_interpolator=True,
parallel=True,
n_processes=1,
)
# save the photflat
output_bn = os.path.splitext(outputfile)[0]
custom_photflat.writeto(
"custom_apf_for_%s_in_%s.fits" % (hdulist[0].header['OBSID'], output_bn),
overwrite=True
)
# XXX
if (options['illumcorr_dir'] is not None and
swarp_params['un_illumcorr']):
logger.info("Un-doing illumination correction (%s)" % (illum_file))
master_reduction_files_used = podi_associations.collect_reduction_files_used(
master_reduction_files_used, {"un_illumination": illum_file})
podi_illumcorr.apply_illumination_correction(hdulist, illum_file, invert=False)
if (not numpy.isnan(fluxscale_value)):
logger.debug("Applying flux-scaling (%.10e)" % (fluxscale_value))
for ext in hdulist:
if (not is_image_extension(ext)):
continue
ext.data *= fluxscale_value
logger.debug("Applying flux-scaling (%.10e) to extension %s" % (fluxscale_value, ext.name))
# Apply fluxscaling to GAIN and SKYLEVLE as well
gain /= fluxscale_value
skylevel *= fluxscale_value
# Check if the corrected file already exists - if not create it
#if (not os.path.isfile(corrected_filename)):
logger.debug("Writing correctly prepared file--> %s" % (corrected_filename))
clobberfile(corrected_filename)
hdulist.writeto(corrected_filename, overwrite=True)
# Now change the filename of the input list to reflect
# the corrected file
ret['corrected_file'] = corrected_filename
ret['gain'] = gain
ret['skylevel'] = skylevel
#
# Now also create a relative weight map for this frame
# scaling factor is the exposure time of each frame
#
weight_hdulist = [hdulist[0]] # copy the primary header
for ext in hdulist[1:]:
if (not is_image_extension(ext)):
continue
weight_data = numpy.ones(ext.data.shape, dtype=numpy.float32) #* 100.
ret['weight'] = 1.
if (not numpy.isnan(fluxscale_value)):
weight_data /= fluxscale_value
ret['weight'] = 1./fluxscale_value
weight_data[numpy.isnan(ext.data)] = 0.
weight_img = pyfits.ImageHDU(header=ext.header, data=weight_data)
weight_hdulist.append(weight_img)
# convert extension list to proper HDUList ...
weight_hdulist = pyfits.HDUList(weight_hdulist)
# ... and write extension to file
weight_filename = ret['corrected_file'][:-5]+".weight.fits"
clobberfile(weight_filename)
weight_hdulist.writeto(weight_filename, overwrite=True)
logger.info("Wrote input weight map to %s" % (weight_filename))
# Finally, close the input file
hdulist.close()
#
# Now we have the filename of the file to be used for the swarp-input
#
ret["master_reduction_files"] = master_reduction_files_used
logger.debug("Sending return value to master process")
output_queue.put(ret)
input_queue.task_done()
# print input_file, "\n", ret["master_reduction_files"]
# end of routine
def prepare_input(inputlist, swarp_params, options,
apf_data=None):
logger = logging.getLogger("PrepFiles")
#
# initialize queues for commands and return-values
#
in_queue = multiprocessing.JoinableQueue()
out_queue = multiprocessing.Queue()
#
# fill queue with files to be processed
#
n_jobs = 0
existing_inputlist = []
for fn in inputlist: #i in range(len(inputlist)):
if (not os.path.isfile(fn)):
continue
try:
hdulist = pyfits.open(fn)
except IOError:
logger.error("Can't open file %s" % (fn))
continue
hdulist.close()
existing_inputlist.append(fn)
if (len(existing_inputlist) <= 0):
logger.error("No valid files found")
return
wcs_inputlist = []
photcal_inputlist = []
for idx, fn in enumerate(existing_inputlist):
hdulist = pyfits.open(fn)
#
# Perform some checks to only include valid frames in the stack
#
# Frame needs to have valid WCS solution
if ('WCSCAL' in hdulist[0].header and
not hdulist[0].header['WCSCAL'] and
not swarp_params['ignore_quality_checks']):
logger.info("Excluding frame (%s) due to faulty WCS calibration" % (fn))
#good_inputlist[idx] = None
continue
wcs_inputlist.append(fn)
# and proper photometric calibration
if ('MAGZERO' in hdulist[0].header and
hdulist[0].header['MAGZERO'] <= 0 and
not swarp_params['no-fluxscale'] and
not swarp_params['ignore_quality_checks']):
logger.info("Excluding frame (%s) due to missing photometric calibration" % (fn))
#good_inputlist[idx] = None
continue
photcal_inputlist.append(fn)
if (len(photcal_inputlist) > 0):
logger.debug("Restricting input file list to files with valid photoemtric calibration")
inputlist = photcal_inputlist
elif (len(wcs_inputlist) > 0):
logger.warning("No files with photometric calibration found, reverting to list of WCS-calibrated files")
inputlist = wcs_inputlist
else:
logger.warning("No files with WCS and/or photometry found, reverting to unfiltered inputlist")
inputlist = existing_inputlist
for idx, fn in enumerate(inputlist):
in_queue.put((fn, idx+1))
n_jobs += 1
logger.info("Queued %d jobs ..." % (n_jobs))
#
# Start worker processes
#
worker_args = (in_queue, out_queue, swarp_params, options, apf_data)
processes = []
for i in range(sitesetup.number_cpus):
p = multiprocessing.Process(target=mp_prepareinput, args=worker_args)
p.start()
processes.append(p)
# also add a quit-command for each process
in_queue.put(None)
#
# wait until all work is done
#
in_queue.join()
#
# return the list of corrected files.
#
# Keep track of what files are being used for this stack
master_reduction_files_used = {}
corrected_file_list = []
nonsidereal_offsets = []
stack_start_time = 1e9
stack_end_time = -1e9
stack_total_exptime = 0
stack_framecount = 0
gain_list = numpy.zeros((n_jobs))
skylevel_list = numpy.zeros((n_jobs))
weight_list = numpy.zeros((n_jobs))
for i in range(n_jobs):
ret = out_queue.get()
logger.debug("Received results from job %d" % (i+1))
gain_list[i] = ret['gain']
skylevel_list[i] = ret['skylevel']
weight_list[i] = ret['weight']
# Also set some global stack-related parameters that we will add to the
# final stack at the end
# mjd_obs_start = hdulist[0].header['MJD-OBS']
# exptime = hdulist[0].header['EXPMEAS'] if 'EXPMEAS' in hdulist[0].header else \
# hdulist[0].header['EXPTIME']
# mjd_obs_end = hdulist[0].header['MJD-OBS'] + (exptime/86400.)
# logger.debug("Exposure time: %f, MJD=%f" % (exptime, mjd_obs_start))
stack_total_exptime += ret['exptime']
stack_framecount += 1
stack_start_time = numpy.min([stack_start_time, ret['mjd_obs_start']])
stack_end_time = numpy.max([stack_end_time, ret['mjd_obs_end']])
master_reduction_files_used = podi_associations.collect_reduction_files_used(master_reduction_files_used,
ret['master_reduction_files'])
corrected_file_list.append(ret['corrected_file'])
nonsidereal_offsets.append(ret['nonsidereal-dradec'])
photom_list = (gain_list, skylevel_list, weight_list)
#
# By now all frames have all corrections applied,
# so we can go ahead and stack them as usual
#
# Make sure to join/terminate all processes
for p in processes:
p.join()
logger.info("All files prepared!")
return (corrected_file_list,
stack_total_exptime,
stack_framecount,
stack_start_time,
stack_end_time,
master_reduction_files_used,
nonsidereal_offsets,
photom_list)
def cleanup_singles(unique_singledir, logger):
try:
shutil.rmtree(unique_singledir)
except:
logger.error("There was a problem with recursively deleting the temp directory")
podi_logging.log_exception()
pass
return
def mp_swarp_single(sgl_queue, dum):
while(True):
cmd = sgl_queue.get()
if (cmd is None):
sgl_queue.task_done()
break
swarp_cmd, prepared_file, single_file, swarp_params, nonsidereal_dradec, create_mask = cmd
logger = logging.getLogger("MPSwarpSgl(%s)" % (os.path.basename(single_file)))
hdulist = pyfits.open(prepared_file)
obsid = hdulist[0].header['OBSID']
logger.info("Starting work on focal-plane frame ...")
single_created_ok = False
try:
logger.debug(" ".join(swarp_cmd.split()))
ret = subprocess.Popen(swarp_cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(swarp_stdout, swarp_stderr) = ret.communicate()
if (sitesetup.log_shell_output):
logger.debug("\nCommand:\n%s\n--> Returncode: %d\n---\nStd.Out:\n%s\n---\nStd.Err:\n%s\n---",
swarp_cmd, ret.returncode, swarp_stdout, swarp_stderr)
# logger.debug("swarp stdout:\n"+swarp_stdout)
# if (len(swarp_stderr) > 0 and ret.returncode != 0):
# logger.warning("swarp stderr:\n"+swarp_stderr)
# elif (sitesetup.log_shell_output):
# logger.debug("swarp stderr:\n"+swarp_stderr)
# Add some basic headers from input file to the single file
# this is important for the differencing etc.
logger.info("adding header to single file (%s)" % (single_file))
hdu_single = pyfits.open(single_file, mode='update')
for hdrkey in [
'TARGRA', 'TARGDEC',
'FILTER', 'FILTERID', 'FILTDSCR',
'OBSID', 'OBJECT',
'EXPTIME',
'DATE-OBS', 'TIME-OBS', 'MJD-OBS']:
if (hdrkey in hdulist[0].header):
key, val, com = hdulist[0].header.cards[hdrkey]
hdu_single[0].header[key] = (val, com)
# hdu_single.writeto(single_file, clobber=True)
hdu_single.flush()
hdu_single.close()
single_created_ok = True
#print "\n".join(swarp_stderr)
# single_prepared_files.append(single_file)
except OSError as e:
podi_logging.log_exception()
# print("Execution failed: %s" % (e), file=sys.stderr)
#
# Apply the mask if requested
#
if (single_created_ok and create_mask and swarp_params['mask-list']):
# not swarp_params['mask'] is None and
#
# Based on the MJD of this frame, determine the best mask-frame
#
try:
frame_mjd = hdulist[0].header['MJD-OBS']
except:
frame_mjd = 0
diff_mjd = numpy.fabs(swarp_params['mask-mjds'] - frame_mjd)
# Find the frame with the smallest delta_mjd
idx = numpy.argmin(diff_mjd)
mask_file = swarp_params['mask-list'][idx]
logger.info("Using mask %s for frame %s" % (mask_file, prepared_file))
#
# Apply the non-sidereal correction to the mask
# (only in non-sidereal mode)
#
this_mask = single_file[:-5]+".maskraw.fits"
logger.info("This mask: %s" % (this_mask))
mask_hdu = pyfits.open(mask_file) #swarp_params['mask'])
logger.info("Applying non-sid corr: %s" % (str(nonsidereal_dradec)))
if (nonsidereal_dradec is not None):
d_radec = numpy.array(nonsidereal_dradec)
# Correct the declination
mask_hdu[0].header['CRVAL2'] -= d_radec[1]
# correct RA, compensating for cos(declination)
if (d_radec.shape[0] == 3):
mask_hdu[0].header['CRVAL1'] -= d_radec[2]
else:
cos_dec = math.cos(math.radians(mask_hdu[0].header['CRVAL2']))
mask_hdu[0].header['CRVAL1'] -= d_radec[0] / cos_dec
clobberfile(this_mask)
mask_hdu.writeto(this_mask, overwrite=True)
mask_hdu.close()
logger.info("wrote raw mask with fudged WCS: %s" % (this_mask))
#
# Swarp the mask to the identical pixelgrid as the single frame
#
hdu_single = pyfits.open(single_file, mode='update')
out_crval1 = hdu_single[0].header['CRVAL1']
out_crval2 = hdu_single[0].header['CRVAL2']
out_naxis1 = hdu_single[0].header['NAXIS1']
out_naxis2 = hdu_single[0].header['NAXIS2']
hdu_single.close()
mask_aligned = single_file[:-5]+".mask.fits"
swarp_mask = """
%(swarp)s -c %(swarp_default)s
-IMAGEOUT_NAME %(mask_aligned)s
-WEIGHTOUT_NAME /dev/null
-CENTER_TYPE MANUAL
-CENTER %(center_ra)f,%(center_dec)f
-IMAGE_SIZE %(imgsizex)d,%(imgsizey)d
-RESAMPLE_DIR %(resample_dir)s
-RESAMPLING_TYPE BILINEAR
-PIXEL_SCALE %(pixelscale)f \
-PIXELSCALE_TYPE %(pixelscale_type)s \
-COMBINE Y \
-COMBINE_TYPE AVERAGE \
-SUBTRACT_BACK N \
%(mask_raw)s
""" % {
'swarp': sitesetup.swarp_exec,
'swarp_default': "%s/config/swarp.default" % (sitesetup.exec_dir),
'mask_raw': this_mask,
'mask_aligned': mask_aligned,
'center_ra': out_crval1,
'center_dec': out_crval2,
'imgsizex': out_naxis1,
'imgsizey': out_naxis2,
'resample_dir': swarp_params['unique_singledir'],
'pixelscale': swarp_params['pixelscale'],
'pixelscale_type': "MANUAL",
}
# print "\n"*3," ".join(swarp_mask.split()),"\n"*3
logger.info("Matching global mask to frame ...")