-
Notifications
You must be signed in to change notification settings - Fork 2
/
rk_specred.py
executable file
·2489 lines (2083 loc) · 92.9 KB
/
rk_specred.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
SPECREDUCE
General data reduction script for SALT long slit data.
This includes step that are not yet included in the pipeline
and can be used for extended reductions of SALT data.
It does require the pysalt package to be installed
and up to date.
"""
import os
import sys
import glob
import shutil
import time
import matplotlib
import numpy
# import pyfits
# import astropy.io.fits as pyfits
from astropy.io import fits
from scipy.ndimage.filters import median_filter
import bottleneck
import scipy.interpolate
# Disable nasty and useless RankWarning when spline fitting
import warnings
# sys.path.insert(1, "/work/pysalt/")
# sys.path.insert(1, "/work/pysalt/plugins")
# sys.path.insert(1, "/work/pysalt/proptools")
# sys.path.insert(1, "/work/pysalt/saltfirst")
# sys.path.insert(1, "/work/pysalt/saltfp")
# sys.path.insert(1, "/work/pysalt/salthrs")
# sys.path.insert(1, "/work/pysalt/saltred")
# sys.path.insert(1, "/work/pysalt/saltspec")
# sys.path.insert(1, "/work/pysalt/slottools")
# sys.path.insert(1, "/work/pysalt/lib")
# from pyraf import iraf
# from iraf import pysalt
import pysalt
from pysalt.saltred.saltobslog import obslog
from pysalt.saltred.saltprepare import saltprepare
from pysalt.saltred.saltbias import saltbias
from pysalt.saltred.saltgain import saltgain
from pysalt.saltred.saltxtalk import saltxtalk
from pysalt.saltred.saltcrclean import saltcrclean
from pysalt.saltred.saltcombine import saltcombine
from pysalt.saltred.saltflat import saltflat
from pysalt.saltred.saltmosaic import saltmosaic
from pysalt.saltred.saltillum import saltillum
from pysalt.saltspec.specidentify import specidentify
from pysalt.saltspec.specrectify import specrectify
from pysalt.saltspec.specsky import skysubtract
from pysalt.saltspec.specextract import extract, write_extract
from pysalt.saltspec.specsens import specsens
from pysalt.saltspec.speccal import speccal
from PySpectrograph.Spectra import findobj
# import fits
import pysalt.mp_logging
import logging
import numpy
import pickle
from optparse import OptionParser
#
# Ralf Kotulla modules
#
from helpers import *
import wlcal
import traceline
import skysub2d
import optimal_spline_basepoints as optimalskysub
import skyline_intensity
import prep_science
import podi_cython
import optscale
import fiddle_slitflat2
import wlmodel
# this is just temporary to make debugging easier
import spline_pickle_test
import test_mask_out_obscured as find_obscured_regions
import map_distortions
import model_distortions
import find_sources
import zero_background
import tracespec
import optimal_extraction
import plot_high_res_sky_spec
import findcentersymmetry
import rectify_fullspec
matplotlib.use('Agg')
numpy.seterr(divide='ignore', invalid='ignore')
warnings.simplefilter('ignore', numpy.RankWarning)
# warnings.simplefilter('ignore', fits.fitsDeprecationWarning)
from astropy.utils.exceptions import *
warnings.simplefilter('ignore', AstropyDeprecationWarning)
warnings.simplefilter('ignore', FutureWarning)
warnings.simplefilter('ignore', UserWarning)
wlmap_fitorder = [2, 2]
def find_appropriate_arc(hdulist, arcfilelist, arcinfos=None,
accept_closest=False):
if arcinfos is None:
arcinfos = {}
hdrs_to_match = [
'CCDSUM',
'WP-STATE', # Waveplate State Machine State
'ET-STATE', # Etalon State Machine State
'GR-STATE', # Grating State Machine State
'GR-STA', # Commanded Grating Station
'BS-STATE', # Beamsplitter State Machine State
'FI-STATE', # Filter State Machine State
'AR-STATE', # Articulation State Machine State
'AR-STA', # Commanded Articulation Station
'CAMANG', # Commanded Articulation Station
'POLCONF', # Polarization configuration
'GRATING', # Commanded grating station
]
flexmatch_headers = []
if (not accept_closest):
hdrs_to_match.append(
'GRTILT', # Commanded grating angle
)
else:
flexmatch_headers.append(
'GRTILT', # Commanded grating angle
)
logger = logging.getLogger("FindGoodArc")
logger.debug("Checking the following list of ARCs:\n * %s" % ("\n * ".join(arcfilelist)))
matching_arcs = []
for arcfile in arcfilelist:
if (arcfile in arcinfos):
# use header that we extracted in an earlier run
hdr = arcinfos[arcfile]
else:
# this is a new file we haven't scanned before
arc_hdulist = fits.open(arcfile)
hdr = arc_hdulist[0].header
arcinfos[arcfile] = hdr
arc_hdulist.close()
#
# Now search for files with the identical spectral setup
#
matches = True
for hdrname in hdrs_to_match:
logger.debug("Comparing header key --> %s <--" % (hdrname))
# if we can't compare the headers we'll assume they won't match
if (not hdrname in hdulist[0].header or not hdrname in hdr):
matches = False
logger.debug("(%s) Not found in one of the two files" % (hdrname))
break
if (not hdulist[0].header[hdrname] == hdr[hdrname]):
matches = False
logger.debug("(%s) Found in both, but does not match!" % (hdrname))
break
# if all headers exist in both files and all headers match,
# then this ARC file should be usable to calibrate the OBJECT frame
if (matches):
logger.debug("FOUND GOOD ARC")
matching_arcs.append(arcfile)
#
# If accepting closest matches as well, check for best match
#
flex_matches = []
if (not accept_closest):
return matching_arcs, True
else:
logger.info("Selecting the closest matched ARC from list")
for arcfile in matching_arcs:
if (arcfile in arcinfos):
# use header that we extracted in an earlier run
hdr = arcinfos[arcfile]
else:
# this is a new file we haven't scanned before
arc_hdulist = fits.open(arcfile)
hdr = arc_hdulist[0].header
arcinfos[arcfile] = hdr
arc_hdulist.close()
fm = []
for hdrname in flexmatch_headers:
if (hdrname not in hdr):
fm.append(numpy.NaN)
else:
fm.append(hdr[hdrname])
flex_matches.append(fm)
flex_matches = numpy.array(flex_matches)
# target value
target_fm = []
for hdrname in flexmatch_headers:
if (hdrname not in hdulist[0].header):
target_fm.append(numpy.NaN)
else:
target_fm.append(hdulist[0].header[hdrname])
target_fm = numpy.array(target_fm)
diff = numpy.fabs((flex_matches - target_fm))
closest = numpy.argmin(diff)
#print matching_arcs
#print closest
#print numpy.array(matching_arcs)[closest]
matching_arcs = [numpy.array(matching_arcs)[closest]]
return matching_arcs, diff[closest]==0
# print "***\n" * 3, matching_arcs, "\n***" * 3
def tiledata(hdulist, rssgeom):
logger = logging.getLogger("TileData")
out_hdus = [hdulist[0]]
gap, xshift, yshift, rotation = rssgeom
xshift = numpy.array(xshift)
yshift = numpy.array(yshift)
# Gather information about existing extensions
sci_exts = []
var_exts = []
bpm_exts = []
detsecs = []
exts = {} # 'SCI': [], 'VAR': [], 'BPM': [] }
ext_order = ['SCI', 'BPM', 'VAR']
for e in ext_order:
exts[e] = []
for i in range(1, len(hdulist)):
if (hdulist[i].header['EXTNAME'] == 'SCI'):
# Remember this function for later use
sci_exts.append(i)
exts['SCI'].append(i)
# Also find out the detsec header entry so we can put all chips
# in the right order (blue to red) without having to rely on
# ordering within the file
decsec = hdulist[i].header['DETSEC']
detsec_startx = int(decsec[1:-1].split(":")[0])
detsecs.append(detsec_startx)
var_ext, bpm_ext = -1, -1
if ('VAREXT' in hdulist[i].header):
var_ext = hdulist[i].header['VAREXT']
if ('BPMEXT' in hdulist[i].header):
bpm_ext = hdulist[i].header['BPMEXT']
var_exts.append(var_ext)
bpm_exts.append(bpm_ext)
exts['VAR'].append(var_ext)
exts['BPM'].append(bpm_ext)
# print sci_exts
# print detsecs
#
# Better make sure we have all 6 CCDs
#
# Problem: How to handle different readout windows here???
#
if (len(sci_exts) != 6):
logger.critical("Could not find all 6 CCD sections!")
return
# convert to numpy array
detsecs = numpy.array(detsecs)
sci_exts = numpy.array(sci_exts)
# sort extensions by DETSEC position
detsec_sort = numpy.argsort(detsecs)
sci_exts = sci_exts[detsec_sort]
for name in exts:
exts[name] = numpy.array(exts[name])[detsec_sort]
# print exts
#
# Now we have all extensions in the right order
#
# Compute how big the output array should be
width = 0
height = -1
amp_width = numpy.zeros_like(sci_exts)
amp_height = numpy.zeros_like(sci_exts)
for i, ext in enumerate(sci_exts):
amp_width[i] = hdulist[ext].data.shape[1]
amp_height[i] = hdulist[ext].data.shape[0]
# Add in the widths of all gaps
binx, biny = pysalt.get_binning(hdulist)
logger.debug("Creating tiled image using binning %d x %d" % (binx, biny))
width = numpy.sum(amp_width) + 2 * gap / binx # + numpy.sum(numpy.fabs((xshift/binx).round()))
height = numpy.max(amp_height) # + numpy.sum(numpy.fabs((yshift/biny).round()))
# print width, height
# print xshift
# print yshift
for name in ext_order:
logger.debug("Starting tiling for extension %s !" % (name))
# Now create the mosaics
data = numpy.empty((height, width))
data[:, :] = numpy.NaN
for i, ext in enumerate(exts[name]): # sci_exts):
dx_gaps = int(gap * int(i / 2) / binx)
dx_shift = xshift[int(i / 2)] / binx
startx = numpy.sum(amp_width[0:i])
# Add in gaps if applicable
startx += dx_gaps
# Also factor in the small corrections
# startx -= dx_shift
endx = startx + amp_width[i]
logger.debug("Putting extension %d (%s) at X=%d -- %d (gaps=%d, shift=%d)" % (
i, name, startx, endx, dx_gaps, dx_shift))
# logger.info("input size: %d x %d" % (amp_width[i], amp_height[i]))
# logger.info("output size: %d x %d" % (amp_width[i], height))
data[:, startx:endx] = hdulist[ext].data[:, :amp_width[i]]
imghdu = fits.ImageHDU(data=data)
imghdu.name = name
out_hdus.append(imghdu)
logger.debug("Finished tiling for all %d data products" % (len(ext_order)))
return fits.HDUList(out_hdus)
def salt_prepdata(infile, badpixelimage=None, create_variance=False,
masterbias=None, clean_cosmics=True,
flatfield_frame=None, mosaic=False,
verbose=False, *args):
_, fb = os.path.split(infile)
logger = logging.getLogger("PrepData(%s)" % (fb))
logger.info("Working on file %s" % (infile))
# hdulist = fits.open(infile)
hdulist = fits.open(infile)
# print hdulist, type(hdulist)
pysalt_log = None # 'pysalt.log'
badpixel_hdu = None
if (not badpixelimage is None):
badpixel_hdu = fits.open(badpixelimage)
#
# Do some prepping
#
# hdulist.info()
logger.debug("Prepare'ing")
hdulist = pysalt.saltred.saltprepare.prepare(
hdulist,
createvar=create_variance,
badpixelstruct=badpixel_hdu)
# Add some history headers here
#
# Overscan/bias
#
logger.debug("Subtracting bias & overscan")
# for ext in hdulist:
# if (not ext.data == None): print ext.data.shape
bias_hdu = None
if (not masterbias is None and os.path.isfile(masterbias)):
bias_hdu = fits.open(masterbias)
hdulist = pysalt.saltred.saltbias.bias(
hdulist,
subover=True, trim=True, subbias=False,
bstruct=bias_hdu,
median=False, function='polynomial', order=5, rej_lo=3.0, rej_hi=5.0,
niter=10, plotover=False,
log=pysalt_log, verbose=verbose)
logger.debug("done with bias & overscan")
# print "--------------"
# for ext in hdulist:
# if (not ext.data == None): print ext.data.shape
# Again, add some headers here
#
# Gain
#
logger.debug("Correcting gain")
dblist = [] # saltio.readgaindb(gaindb)
hdulist = pysalt.saltred.saltgain.gain(hdulist,
mult=True,
usedb=False,
dblist=dblist,
log=pysalt_log, verbose=verbose)
logger.debug("done with gain")
#
# Xtalk
#
logger.debug("fixing crosstalk")
usedb = False
if usedb:
xtalkfile = xtalkfile.strip()
xdict = saltio.readxtalkcoeff(xtalkfile)
else:
xdict = None
if usedb:
obsdate = saltkey.get('DATE-OBS', struct[0])
obsdate = int('%s%s%s' % (obsdate[0:4], obsdate[5:7], obsdate[8:]))
xkey = numpy.array(xdict.keys())
date = xkey[abs(xkey - obsdate).argmin()]
xcoeff = xdict[date]
else:
xcoeff = []
hdulist = pysalt.saltred.saltxtalk.xtalk(hdulist, xcoeff, log=pysalt_log, verbose=verbose)
logger.debug("done with crosstalk")
#
# crj-clean
#
# clean the cosmic rays
multithread = True
logger.debug("removing cosmics")
if multithread and len(hdulist) > 1:
crj_function = pysalt.saltred.saltcrclean.multicrclean
else:
crj_function = pysalt.saltred.saltcrclean.crclean
if (clean_cosmics):
# hdulist = crj_function(hdulist,
# crtype='edge', thresh=5, mbox=11, bthresh=5.0,
# flux_ratio=0.2, bbox=25, gain=1.0, rdnoise=5.0, fthresh=5.0, bfactor=2,
# gbox=3, maxiter=5)
sigclip = 5.0
sigfrac = 0.6
objlim = 5.0
saturation_limit = 65000
# This is BEFORE mosaicing, therefore:
# Loop over all SCI extensions
for ext in hdulist:
if (ext.name == 'SCI'):
with open("headers", "a") as h:
print >> h, ext.header
gain = 1.5 if (not 'GAIN' in ext.header) else ext.header['GAIN']
readnoise = 3 if (not 'RDNOISE' in ext.header) else ext.header['RDNOISE']
crj = podi_cython.lacosmics(
ext.data.astype(numpy.float64),
gain=gain,
readnoise=readnoise,
niter=3,
sigclip=sigclip, sigfrac=sigfrac, objlim=objlim,
saturation_limit=saturation_limit,
verbose=False
)
cell_cleaned, cell_mask, cell_saturated = crj
ext.data = cell_cleaned
logger.debug("done with cosmics")
#
# Apply flat-field correction if requested
#
logger.info("FLAT: %s" % (str(flatfield_frame)))
if (not flatfield_frame is None and os.path.isfile(flatfield_frame)):
logger.debug("Applying flatfield")
flathdu = fits.open(flatfield_frame)
pysalt.saltred.saltflat.flat(
struct=hdulist, # input
fstruct=flathdu, # flatfield
)
# saltflat('xgbpP*fits', '', 'f', flatimage, minflat=500, clobber=True, logfile=logfile, verbose=True)
flathdu.close()
logger.debug("done with flatfield")
else:
logger.debug("continuing without flat-field correction!")
if (mosaic):
logger.debug("Mosaicing all chips together")
geomfile = pysalt.get_data_filename("pysalt$data/rss/RSSgeom.dat")
geomfile = pysalt.get_data_filename("data/rss/RSSgeom.dat")
logger.debug("Reading geometry from file %s (%s)" % (geomfile, os.path.isfile(geomfile)))
# does CCD geometry definition file exist
if (not os.path.isfile(geomfile)):
logger.critical("Unable to read geometry file %s!" % (geomfile))
else:
gap = 0
xshift = [0, 0]
yshift = [0, 0]
rotation = [0, 0]
gap, xshift, yshift, rotation, status = pysalt.lib.saltio.readccdgeom(geomfile, logfile=None, status=0)
logger.debug("Using CCD geometry: gap=%d, Xshift=%d,%d, Yshift=%d,%d, rot=%d,%d" % (
gap, xshift[0], xshift[1], yshift[0], yshift[1], rotation[0], rotation[1]))
# print "\n@@"*5, gap, xshift, yshift, rotation, "\n@"*5
logger.debug("mosaicing -- GAP:%f - X-shift:%f/%f y-shift:%f/%f rotation:%f/%f" % (
gap, xshift[0], xshift[1], yshift[0], yshift[1], rotation[0], rotation[1]))
# logger.info("File structure before mosaicing:")
# hdulist.info()
gap = 90
xshift = [0.0, +5.9, -2.1]
yshift = [0.0, -2.6, 0.4]
rotation = [0, 0, 0]
hdulist = tiledata(hdulist, (gap, xshift, yshift, rotation))
# #return
# create the mosaic
# logger.info("Running IRAF geotran to create mosaic, be patient!")
# hdulist = pysalt.saltred.saltmosaic.make_mosaic(
# struct=hdulist,
# gap=gap, xshift=xshift, yshift=yshift, rotation=rotation,
# interp_type='linear',
# boundary='constant', constant=0, geotran=True, fill=False,
# #boundary='constant', constant=0, geotran=False, fill=False,
# cleanup=True, log=None, verbose=verbose)
# hdulist[2].name = 'VAR'
# hdulist[3].name = 'BPM'
# hdulist.info()
# logger.debug("done with mosaic")
return hdulist
def save_sky_spec(wl, sky_spline, hi_res=None):
wl_min = numpy.min(wl)
wl_max = numpy.max(wl)
mean_dwl = (wl_max - wl_min) / wl.shape[1]
if (hi_res is None):
hi_res = 0.1 * mean_dwl
n_points = int((wl_max - wl_min) / hi_res)
sky_wl = numpy.arange(n_points, dtype=numpy.float) * hi_res + wl_min
sky_flux = sky_spline(sky_wl)
imghdu = fits.ImageHDU(
data=sky_flux,
name="SKYSPEC"
)
imghdu.header['WCSNAME'] = "calibrated wavelength"
imghdu.header['CRPIX1'] = 1.
imghdu.header['CRVAL1'] = wl_min
imghdu.header['CD1_1'] = hi_res
imghdu.header['CTYPE1'] = "AWAV"
imghdu.header['CUNIT1'] = "Angstrom"
return imghdu
#################################################################################
#################################################################################
#################################################################################
def specred(rawdir, prodir, options,
imreduce=True, specreduce=True,
calfile=None, lamp='Ar',
automethod='Matchlines', skysection=[800, 1000],
cleanup=True):
#print rawdir
#print prodir
logger = logging.getLogger("SPECRED")
# get the name of the files
# if (type(infile) == list):
# infile_list = infile
# elif (type(infile) == str and os.path.isdir(infile)):
infile_list = glob.glob(os.path.join(rawdir, "*.fits"))
# get the current date for the files
obsdate = os.path.basename(infile_list[0])[1:9]
#print obsdate
# set up some files that will be needed
logfile = 'spec' + obsdate + '.log'
flatimage = 'FLAT%s.fits' % (obsdate)
dbfile = 'spec%s.db' % obsdate
# create the observation log
# obs_dict=obslog(infile_list)
# import pysalt.lib.saltsafeio as saltio
#print infile_list
#
#
# Now reduce all files, one by one
#
#
# work_dir = "working/"
# if (not os.path.isdir(work_dir)):
# os.mkdir(work_dir)
# #
# # Make sure we have all directories
# #
# for rs in reduction_steps:
# dirname = "%s/%s" % (work_dir, rs)
# if (not os.path.isdir(dirname)):
# os.mkdir(dirname)
#
# Go through the list of files, find out what type of file they are
#
logger.info("Identifying frames and sorting by type (object/flat/arc)")
obslog = {
'FLAT': [],
'ARC': [],
'OBJECT': [],
}
for idx, filename in enumerate(infile_list):
hdulist = fits.open(filename)
if (not hdulist[0].header['INSTRUME'] == "RSS"):
logger.info("Frame %s is not a valid RSS frame (instrument: %s)" % (
filename, hdulist[0].header['INSTRUME']))
continue
obstype = None
if ('OBSTYPE' in hdulist[0].header):
obstype = hdulist[0].header['OBSTYPE']
if (obstype not in ['OBJECT', 'ARC', 'FLAT']):
obstype = None
if (obstype is None or (obstype.strip() == "" and 'CCDTYPE' in hdulist[0].header)):
obstype = hdulist[0].header['CCDTYPE']
if (obstype in obslog):
obslog[obstype].append(filename)
logger.debug("Identifying %s as %s" % (filename, obstype))
else:
logger.info("No idea what to do with frame %s --> %s" % (filename, obstype))
for obstype in obslog:
if (len(obslog[obstype]) > 0):
logger.info("Found the following %ss:\n -- %s" % (
obstype, "\n -- ".join(obslog[obstype])))
else:
logger.info("No files of type %s found!" % (obstype))
if (options.check_only):
return
#
# Go through the list of files, find all flat-fields, and create a master flat field
#
logger.info("Creating a master flat-field frame")
flatfield_filenames = []
flatfield_hdus = {}
first_flat = None
flatfield_list = {}
for idx, filename in enumerate(obslog['FLAT']):
hdulist = fits.open(filename)
obstype = None
if ('OBSTYPE' in hdulist[0].header):
obstype = hdulist[0].header['OBSTYPE']
if (obstype is None or (obstype.strip() == "" and 'CCDTYPE' in hdulist[0].header)):
obstype = hdulist[0].header['CCDTYPE']
if (obstype.find("FLAT") >= 0 and
hdulist[0].header['INSTRUME'] == "RSS" and
options.use_flats):
#
# This is a flat-field
#
#
# Get some parameters so we can create flatfields for each specific
# instrument configuration
#
grating = hdulist[0].header['GRATING']
grating_angle = hdulist[0].header['GR-ANGLE']
grating_tilt = hdulist[0].header['GRTILT']
binning = "x".join(hdulist[0].header['CCDSUM'].split())
if (not grating in flatfield_list):
flatfield_list[grating] = {}
if (not binning in flatfield_list[grating]):
flatfield_list[grating][binning] = {}
if (not grating_tilt in flatfield_list[grating][binning]):
flatfield_list[grating][binning][grating_tilt] = {}
if (not grating_angle in flatfield_list[grating][binning][grating_tilt]):
flatfield_list[grating][binning][grating_tilt][grating_angle] = []
flatfield_list[grating][binning][grating_tilt][grating_angle].append(filename)
for grating in flatfield_list:
for binning in flatfield_list[grating]:
for grating_tilt in flatfield_list[grating][binning]:
for grating_angle in flatfield_list[grating][binning][grating_tilt]:
filelist = flatfield_list[grating][binning][grating_tilt][grating_angle]
flatfield_hdus = {}
logger.info("Creating master flatfield for %s (%.3f/%.3f), %s (%d frames)" % (
grating, grating_angle, grating_tilt, binning, len(filelist)))
for filename in filelist:
_, fb = os.path.split(filename)
single_flat = "flat_%s" % (fb)
hdu = salt_prepdata(filename,
badpixelimage=None,
create_variance=True,
clean_cosmics=False,
mosaic=False,
verbose=False)
pysalt.clobberfile(single_flat)
hdu.writeto(single_flat, clobber=True)
logger.info("Wrote single flatfield to %s" % (single_flat))
for extid, ext in enumerate(hdu):
if (ext.name == "SCI"):
# Only use the science extensions, leave everything else
# untouched: Apply a one-dimensional median filter to take
# out spectral slope. We can then divide the raw data by this
# median flat to isolate pixel-by-pixel variations
filtered = scipy.ndimage.filters.median_filter(
input=ext.data,
size=(1, 25),
footprint=None,
output=None,
mode='reflect',
cval=0.0,
origin=0)
ext.data /= filtered
if (not extid in flatfield_hdus):
flatfield_hdus[extid] = []
flatfield_hdus[extid].append(ext.data)
single_flat = "norm" + single_flat
pysalt.clobberfile(single_flat)
hdu.writeto(single_flat, clobber=True)
logger.info("Wrote normalized flatfield to %s" % (single_flat))
if (first_flat is None):
first_flat = hdulist
print first_flat
if (len(filelist) <= 0):
continue
# Combine all flat-fields into a single master-flat
for extid in flatfield_hdus:
flatstack = flatfield_hdus[extid]
# print "EXT",extid,"-->",flatstack
logger.info("Ext %d: %d flats" % (extid, len(flatstack)))
flatstack = numpy.array(flatstack)
print flatstack.shape
avg_flat = numpy.mean(flatstack, axis=0)
print "avg:", avg_flat.shape
first_flat[extid].data = avg_flat
masterflat_filename = "flat__%s_%s_%.3f_%.3f.fits" % (
grating, binning, grating_tilt, grating_angle)
pysalt.clobberfile(masterflat_filename)
first_flat.writeto(masterflat_filename, clobber=True)
# # hdu = salt_prepdata(filename, badpixelimage=None, create_variance=False,
# # verbose=False)
# # flatfield_hdus.append(hdu)
#############################################################################
#
# Determine a wavelength solution from ARC frames, where available
#
#############################################################################
logger.info("Searching for a wavelength calibration from the ARC files")
skip_wavelength_cal_search = False # os.path.isfile(dbfile)
# Keep track of when the ARCs were taken, so we can pick the one closest
# in time to the science observation for data reduction
arc_obstimes = numpy.ones((len(obslog['ARC']))) * -999.9
arc_mosaic_list = [None] * len(obslog['ARC'])
arc_mef_list = [None] * len(obslog['ARC'])
if (not skip_wavelength_cal_search):
for idx, filename in enumerate(obslog['ARC']):
_, fb = os.path.split(filename)
hdulist = fits.open(filename)
# Use Julian Date for simple time indexing
arc_obstimes[idx] = hdulist[0].header['JD']
arc_filename = "ARC_%s" % (fb)
arc_mosaic_filename = "ARC_m_%s" % (fb)
rect_filename = "ARC-RECT_%s" % (fb)
if (os.path.isfile(arc_mosaic_filename) and options.reusearcs):
arc_mosaic_list[idx] = arc_mosaic_filename
logger.info("Re-using ARC %s from previous run" % (arc_mosaic_filename))
continue
logger.info("Creating MEF for frame %s --> %s" % (fb, arc_filename))
hdu = salt_prepdata(filename,
badpixelimage=None,
create_variance=True,
clean_cosmics=False,
mosaic=False,
verbose=False)
pysalt.clobberfile(arc_filename)
hdu.writeto(arc_filename, clobber=True)
arc_mef_list[idx] = arc_filename
logger.info("Creating mosaic for frame %s --> %s" % (fb, arc_mosaic_filename))
hdu_mosaiced = salt_prepdata(filename,
badpixelimage=None,
create_variance=True,
clean_cosmics=False,
mosaic=True,
verbose=False)
#
# Now we have a HDUList of the mosaiced ARC file, so
# we can continue to the wavelength calibration
#
logger.info("Starting wavelength calibration")
binx, biny = pysalt.get_binning(hdulist)
logger.info("Checking symmetry of ARC lines to tune the spectropgraph model")
symmetry_lines, best_midline, linewidth = \
findcentersymmetry.find_curvature_symmetry_line(
hdulist=hdu_mosaiced,
data_ext='SCI',
avg_width=10,
n_lines=10,
)
reference_row = int(best_midline[1])
logger.info("Using row %d as reference row" % (reference_row))
hdu_mosaiced[0].header['WLREFROW'] = (
reference_row, "symmetry row")
hdu_mosaiced[0].header['WLREFCOL'] = (
best_midline[0], "approx line position x")
hdu_mosaiced[0].header['LINEWDTH'] = (
linewidth, "linewidth in pixels")
wls_data = wlcal.find_wavelength_solution(
hdu_mosaiced,
line=reference_row,
#line=(2070/biny)
)
if (wls_data is None):
logger.error("Unable to compute WL map from %s" % (filename))
continue
#
# Write wavelength solution to FITS header so we can access it
# again if we need to at a later point
#
logger.info("Storing wavelength solution in ARC file (%s)" % (arc_mosaic_filename))
hdu_mosaiced[0].header['WLSFIT_N'] = len(wls_data['wl_fit_coeffs'])
for i in range(len(wls_data['wl_fit_coeffs'])):
hdu_mosaiced[0].header['WLSFIT_%d' % (i)] = wls_data['wl_fit_coeffs'][i]
#
# Now add some plotting here just to make sure the user is happy :-)
#
logger.info("Creating calibration plot for user")
plotfile = arc_mosaic_filename[:-5] + ".png"
wlcal.create_wl_calibration_plot(wls_data, hdu_mosaiced, plotfile)
#
# Simulate the ARC spectrum by extracting a 2-D ARC spectrum just
# like we would for the sky-subtraction in OBJECT frames
#
logger.info("Computing a 2-D wavelength solution by tracing arc lines")
arc_region_file = "ARC_m_%s_traces.reg" % (fb[:-5])
wls_2darc = traceline.compute_2d_wavelength_solution(
arc_filename=hdu_mosaiced,
n_lines_to_trace=-15, # -50, # trace all lines with S/N > 50
fit_order=wlmap_fitorder,
output_wavelength_image="wl+image.fits",
debug=True,
arc_region_file=arc_region_file,
trace_every=0.05,
wls_data=wls_data,
)
wl_hdu = fits.ImageHDU(data=wls_2darc)
wl_hdu.name = "WAVELENGTH"
wl_hdu.header['OBJECT'] = ("wavelength map (ARC-trace)", "description")
hdu_mosaiced.append(wl_hdu)
#
# Compute a synthetic 2-D wavelength model
#
logger.info("Computing 2-D wavelength map from RSS spectrograph model")
model_wl = wlmodel.rssmodelwave(
header=hdu_mosaiced[0].header,
img=hdu_mosaiced['SCI'].data,
xbin=binx, ybin=biny,
y_center=reference_row*biny,
)
hdu_mosaiced.append(
fits.ImageHDU(
data=model_wl,
name="WL_MODEL_2D",
header=fits.Header(
{"OBJECT": "wavelength map from RSS model"}
)
)
)
fits.PrimaryHDU(data=model_wl).writeto("arcwl.fits", clobber=True)
hdu_mosaiced[0].header['RSSYCNTR'] = (
reference_row*biny,
"reference line for spectrograph model"
)
#
# Now go ahead and extract the full 2-d sky
#
logger.info("Extracting a ARC-spectrum from the entire frame")
arc_regions = numpy.array([[0, hdu_mosaiced['SCI'].data.shape[0]]])
hdu_mosaiced.writeto("dummy.fits", clobber=True)
arc2d = skysub2d.make_2d_skyspectrum(
hdu_mosaiced,
model_wl, #wls_2darc,
sky_regions=arc_regions,
oversample_factor=1.0,
)
simul_arc_hdu = fits.ImageHDU(data=arc2d)
simul_arc_hdu.name = "SIMULATION"
hdu_mosaiced.append(simul_arc_hdu)
logger.info("Writing calibrated ARC frame to file (%s)" % (arc_mosaic_filename))
pysalt.clobberfile(arc_mosaic_filename)
hdu_mosaiced.writeto(arc_mosaic_filename, clobber=True)
arc_mosaic_list[idx] = arc_mosaic_filename
# lamp=hdu[0].header['LAMPID'].strip().replace(' ', '')
# lampfile=pysalt.get_data_filename("pysalt$data/linelists/%s.txt" % lamp)
# automethod='Matchlines'
# skysection=[800,1000]
# logger.info("Searching for wavelength solution (lamp:%s, arc-image:%s)" % (
# lamp, arc_filename))
# specidentify(arc_filename, lampfile, dbfile, guesstype='rss',
# guessfile='', automethod=automethod, function='legendre', order=5,
# rstep=100, rstart='middlerow', mdiff=10, thresh=3, niter=5,
# inter=False, clobber=True, logfile=logfile, verbose=True)
# logger.debug("Done with specidentify")
# logger.debug("Starting specrectify")
# specrectify(arc_filename, outimages=rect_filename, outpref='',
# solfile=dbfile, caltype='line',
# function='legendre', order=3, inttype='interp',