stare.py 30.4 KB
Newer Older
Monica Rainer's avatar
Monica Rainer committed
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
"""
Reduction of the single Obj-Sky group:
- check the Obj image quality (signal in well defined region)
- check that the exposure times of Obj and Sky are the same
- check that the number of Obj and Sky images are the same
- average the Obj images
- average the Sky images
- create Obj-Sky image
- remove bad pixel using the bad pixel mask
- straigthen the image
- divide by the masterflat (if required)
- perform optimal extraction
- use the optimal profiles with UNe lamp and do wavelength calibration
- save the C image
Reduction of all the Obj-Sky group:
- check the Obj image quality (signal in well defined region)
- check that the exposure times of Obj and Sky are the same
- check that the number of Obj and Sky images are the same
- average the Obj images
- average the Sky images
- create Obj-Sky image
- remove bad pixel using the bad pixel mask
- straigthen the image
- divide by the masterflat (if required)
- perform optimal extraction
- use the optimal profiles with UNe lamp and do wavelength calibration
- save the C image
"""


from drslib.config import CONFIG
from drslib import db, varie

from astropy import units as u
from astropy.io import ascii, fits

import warnings
from astropy.utils.exceptions import AstropyWarning
import ccdproc

import numpy as np
import math, os, subprocess, time, shutil

from collections import OrderedDict, Counter
#import matplotlib.pyplot as plt


class GBStare():
Monica Rainer's avatar
Monica Rainer committed
49
    def __init__(self, stare, group, dbconn, dbnight):
Monica Rainer's avatar
Monica Rainer committed
50
51
52
        self.stare = stare
        self.group = group
        self.dbconn = dbconn
Monica Rainer's avatar
Monica Rainer committed
53
        self.dbnight = dbnight
Monica Rainer's avatar
Monica Rainer committed
54
55
56
57
58
59
60
61
62
63
64
        self.quality = []
        self.messages = []
        self.starelist = []
        self.skylist = []
        self.starecorr = {}
        self.mjd = -99999

    def qualitycheck(self):
        """
        Check image's quality: check the signal in a well-defined region (only Obj).
        After this, check the number of Obj and Sky images and their exposure times.
Monica Rainer's avatar
Monica Rainer committed
65
66
        Discard those with exposure times different, (discard other images as needed
        to have the same number of Obj and Sky --> NOT ANYMORE).
Monica Rainer's avatar
Monica Rainer committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        """

        expt_obj = []
        expt_sky = []
        signal_obj = []
        sky_time = []
        mjd_obj = []
        name_obj = []
        name_sky = []

        for frame in self.stare:

            nod = ccdproc.CCDData.read(frame, unit=u.adu)

            try: nod.header[CONFIG['KEYS']['STARE']]
            except:
                nod.header[CONFIG['KEYS']['STARE']] = raw_input('Define stare observation %s: [obj/sky]: ' % (os.path.basename(frame))).upper()
                if nod.header[CONFIG['KEYS']['STARE']] == '':
                    continue

            # check the signal in a well-defined zone
88
            if nod.header[CONFIG['KEYS']['STARE']] == CONFIG['OBJ'] or nod.header[CONFIG['KEYS']['STARE']] == CONFIG['UNKNOWN']:
Monica Rainer's avatar
Monica Rainer committed
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
                expt_obj.append(nod.header[CONFIG['KEYS']['EXPTIME']])
                zone = nod.data[CONFIG['SCIENCECHECK'][0]:CONFIG['SCIENCECHECK'][1],CONFIG['SCIENCECHECK'][2]:CONFIG['SCIENCECHECK'][3]]
                mean = np.mean(zone)
                #std = np.std(zone)
                signal_obj.append(mean)

                if mean < CONFIG['NODSIGNAL']:
                    self.messages.append('Science frame %s failed quality check: signal too low (%s). It will not be reduced.' % (str(os.path.basename(frame)),str(mean)))

                else:
                    self.starelist.append(nod)
                    mjd_obj.append(nod.header[CONFIG['KEYS']['MJD']])
                    name_obj.append(os.path.basename(frame))

                    try:
                        nod.header[CONFIG['KEYS']['EXTMODE']]
                    except:
                        nod.header[CONFIG['KEYS']['EXTMODE']] = CONFIG['EXTPAIR']

                    ext = nod.header[CONFIG['KEYS']['EXTMODE']]

            else:
                expt_sky.append(nod.header[CONFIG['KEYS']['EXPTIME']])
                sky_time.append(nod.header[CONFIG['KEYS']['MJD']])
                self.skylist.append(nod)
                name_sky.append(os.path.basename(frame))

# Check if there is at least one Obj image.

        if len(self.starelist) == 0:
            print self.starelist
            self.messages.append('No Obj frame has passed the quality test (signal too low), this group will not be reduced.')
            return False

        #elif len(self.skylist) == 0:
        #    self.messages.append('There are no Sky images, this group will not be reduced.')
        #    return False



# Check exposure times: if they are different, the pipeline
# will only keep the majority of images with the same exposure time

        exp_common = Counter(expt_obj).most_common(1)[0][0]

        if Counter(expt_obj).most_common(1)[0][1] < len(expt_obj):
            #print len(self.starelist)
            self.messages.append('The Obj images have different exposure times, some of them will be skipped')
            for n in xrange(len(self.starelist)):
                if self.starelist[n].data[CONFIG['KEYS']['EXPTIME']] != exp_common:
                    self.messages.append('%s has %ss of exposure time: skipped.' % (name_obj[n],str(self.starelist[n].data[CONFIG['KEYS']['EXPTIME']]),))
                    signal_obj.pop(n)
                    self.starelist.pop(n)
                    mjd_obj.pop(n)
                    name_obj.pop(n)
            #print len(self.starelist)

Monica Rainer's avatar
Monica Rainer committed
146
        self.mjd = np.average(np.asarray(mjd_obj)) + (exp_common/(2.0*86400.0))
Monica Rainer's avatar
Monica Rainer committed
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
        sky_time = abs(np.asarray(sky_time) - self.mjd) 

# Skip sky images with exposure time different than Obj
        #print len(self.skylist)
        try:
            for n in xrange(len(expt_sky)):
                if expt_sky[n] != exp_common:
                    self.messages.append('The sky image %s has %ss of exposure time: skipped.' % (name_sky[n],str(expt_sky[n]),))
                    np.delete(sky_time,n)
                    self.skylist.pop(n)
                    name_sky.pop(n)
        except:
            pass
        #print len(self.skylist)

        #if len(self.skylist) == 0:
        #    self.messages.append('There are no Sky images with the same exposure time as the Obj images, this group will not be reduced.')
        #    return False

# Check if the number of Obj and Sky is the same, otherwise skip some images
# Obj: skip the images with lowest signal: MODIFIED - keep all the obj images, even if the sky images are fewer
#        if len(self.starelist) > len(self.skylist):
#            while len(self.starelist) > len(self.skylist):
#                worst = np.argmin(np.asarray(signal_obj))
#                self.messages.append('There are more Obj images than Sky. %s has the lowest signal: skipped.' % (name_obj[n],))
#                signal_obj.pop(worst)
#                self.starelist.pop(worst)
#                name_obj.pop(worst)

# Sky: skip the images farther temporally from the Obj: MODIFIED - keep all the obj images, even if the sky images are fewer
#        elif len(self.starelist) < len(self.skylist):
#        if len(self.starelist) < len(self.skylist):
#            while len(self.starelist) < len(self.skylist):
#                farther = np.argmax(sky_time)
#                self.messages.append('There are more Sky images than Obj. %s was observed farthest from the Obj sequence: skipped.' % (name_sky[n],))
#                np.delete(sky_time,farther)
#                self.skylist.pop(farther)
#                name_sky.pop(farther)

        if ext == CONFIG['EXTAVG']:
            self.group['stares'].extend(self.stare)

        return True


    def createObj(self,grp):
        """
        Average the Obj and the Sky images, subtract Sky from Obj.
        Bad pixel removal.
        """

        badpix = ccdproc.CCDData.read(CONFIG['BADPIX_MASK'], unit=u.adu)
        bad_mask=badpix.data
        inverse_mask=np.logical_not(bad_mask)

        #t1 = time.time()

        obj = ccdproc.Combiner(self.starelist)
        med_obj = obj.average_combine()
        med_obj.header = self.starelist[0].header
        med_obj.header[CONFIG['GAIN_EFF'][0]] = (len(self.starelist)*CONFIG['GAIN'],CONFIG['GAIN_EFF'][1])
        #print med_obj.header[CONFIG['GAIN_EFF'][0]]

        med_obj.header[CONFIG['RON_EFF'][0]] = (math.sqrt(len(self.starelist))*CONFIG['RON'],CONFIG['RON_EFF'][1])

        am = []
        for n in self.starelist:
            am.append(n.header[CONFIG['KEYS']['AM']])
        am = np.average(np.asarray(am))

        med_obj.header[CONFIG['AIRMASS'][0]] = (am,CONFIG['AIRMASS'][1])


        try:
            sky = ccdproc.Combiner(self.skylist)
            med_sky = sky.average_combine()
            med_sky.header = self.skylist[0].header
            med_sky.header[CONFIG['GAIN_EFF'][0]] = (len(self.skylist)*CONFIG['GAIN'],CONFIG['GAIN_EFF'][1])
            med_sky.header[CONFIG['RON_EFF'][0]] = (math.sqrt(len(self.skylist))*CONFIG['RON'],CONFIG['RON_EFF'][1])

            sky_corrected = med_obj.data - med_sky.data
            self.messages.append('Sky subtracted.')

        except:
            exptime = med_obj.header[CONFIG['KEYS']['EXPTIME']]
            darkname = 'dark' + str(int(exptime))
            use_dark = True

            try:
                masterdark = db.extract_dbfile(self.dbconn,darkname)
            except:
                masterdark = False

            if not masterdark:
                self.messages.append('No masterdark found for this night, it will be taken from the calibration database.')
                try:
                    db.copy_dbfile(self.dbconn,darkname)
                    masterdark = db.extract_dbfile(self.dbconn,darkname)
                except:
                    for key in CONFIG['DARKLIST']:
                        try:
                            darkname = 'dark' + str(int(key))
                            db.copy_dbfile(self.dbconn,darkname)
                            masterdark = db.extract_dbfile(self.dbconn,darkname)
                            self.messages.append('No masterdark in the calibration database with the same exposure time as the flat-field. The %s sec masterdark will be used instead' % (str(int(key))))
                            break
                        except:
                            self.messages.append('There are no masterdark in the calibration database. The masterdark will not be used.')
                            use_dark = False

            if use_dark:
                mdark = ccdproc.CCDData.read(masterdark, unit=u.adu)
                sky_corrected = ccdproc.subtract_dark(med_obj,mdark,exposure_time=CONFIG['KEYS']['EXPTIME'],exposure_unit=u.second)
                sky_corrected = sky_corrected.data
                self.messages.append('There is no sky image, the masterdark has been subtracted.')
            else:
                sky_corrected = med_obj.data
                self.messages.append('There is no sky image, the object will be reduced anyway.')

        bp_corrected = varie.badpix(sky_corrected,bad_mask,inverse_mask)
        bp_corrected = np.asarray(bp_corrected,dtype='float32')
        self.messages.append('Bad pixel correction done.')

        corrected = ccdproc.CCDData(bp_corrected,unit=u.adu)
        #corrected = ccdproc.CCDData(bp_corrected)
        corrected.header = self.starelist[0].header
        corrected.header[CONFIG['RON_EFF'][0]] = (math.sqrt(2)*med_obj.header[CONFIG['RON_EFF'][0]],CONFIG['RON_EFF'][1])

        corrected.header[CONFIG['DRS_MJD'][0]] = (self.mjd,CONFIG['DRS_MJD'][1])

        corrected.header[CONFIG['KEYS']['NCOMBINE']] = len(self.starelist) + len(self.skylist)
        for n in xrange(len(self.starelist)):
            keyA = ''.join((CONFIG['SPEC_USED'][0],str(n),'OBJ'))
            mjdA = ''.join((CONFIG['SPEC_MJD'][0],str(n),'OBJ'))

            #value_keyA = self.starelist[n].header[CONFIG['KEYS']['FILENAME']]
            value_keyA = self.starelist[n].header[CONFIG['KEYS']['IMANAME']]
            value_mjdA = self.starelist[n].header[CONFIG['KEYS']['MJD']]

            corrected.header[keyA] = (value_keyA,CONFIG['SPEC_USED'][1])
            corrected.header[mjdA] = (value_mjdA,CONFIG['SPEC_MJD'][1])

        for n in xrange(len(self.skylist)):
            keyA = ''.join((CONFIG['SPEC_USED'][0],str(n),'SKY'))
            mjdA = ''.join((CONFIG['SPEC_MJD'][0],str(n),'SKY'))

            #value_keyA = self.starelist[n].header[CONFIG['KEYS']['FILENAME']]
            value_keyA = self.starelist[n].header[CONFIG['KEYS']['IMANAME']]
            value_mjdA = self.starelist[n].header[CONFIG['KEYS']['MJD']]

            corrected.header[keyA] = (value_keyA,CONFIG['SPEC_USED'][1])
            corrected.header[mjdA] = (value_mjdA,CONFIG['SPEC_MJD'][1])

        #Cnome = self.starelist[0].header[CONFIG['KEYS']['FILENAME']]
        Cnome = self.starelist[0].header[CONFIG['KEYS']['IMANAME']]
        #print Cnome
        #qui = Cnome.rindex('.')
        nomebase = os.path.splitext(Cnome)[0]
        if grp:
            #Cnome = '_'.join((Cnome[0:qui],'Cgrp.fits'))
            Cnome = '_'.join((nomebase,'Cgrp.fits'))
        else:
            Cnome = '_'.join((nomebase,'C.fits'))
        Cnome = os.path.join(CONFIG['TMP_DIR'],Cnome)

        #cor_fits = corrected.to_hdu()
        hdu = fits.PrimaryHDU(data=corrected.data,header=corrected.header)
        cor_fits = fits.HDUList([hdu])
        cor_fits.writeto(Cnome,clobber=True)

        return Cnome

Monica Rainer's avatar
Monica Rainer committed
319
    def reduce(self,fitsfile):
Monica Rainer's avatar
Monica Rainer committed
320
321
322
        """
        Straighten, divide by the masterflat, optimal extraction
        """
Monica Rainer's avatar
Monica Rainer committed
323
324

        dbreduced = {}
Monica Rainer's avatar
Monica Rainer committed
325
326
327
        # straighten

        straight = fitsfile.replace('.fits','_str.fits')
328

329
330
331
332
333
        args = [CONFIG['STRAIGHT'],fitsfile,straight]
        args.extend(CONFIG['STRAIGHT_OPT'])
        # search for shift defined in the straighten options in config.py
        dy = True
        for opt in CONFIG['STRAIGHT_OPT']:
334
            try:
335
336
337
338
                dy = opt.rindex('DY=')
                ypos = int(opt[dy-2:])
                shift = CONFIG['SHIFT_Y'] + ypos
                dy = False
339
            except:
340
341
342
                pass

        if dy:
Unknown's avatar
Unknown committed
343
344
345
346
347
            try:
                shift = db.extract_dbfile(self.dbconn,'shiftY')
            except:
                try:
                    cal_flat = db.extract_dbfile(self.dbconn,'flat')
348
349
350
                    mflat = ccdproc.CCDData.read(cal_flat, unit=u.adu)
                    shift = varie.shiftY(mflat.data)
                    db.insert_dbfile(self.dbconn,'shiftY',shift)
Unknown's avatar
Unknown committed
351
                except:
352
353
                    db.copy_dbfile(self.dbconn,'shiftY')
                    shift = db.extract_dbfile(self.dbconn,'shiftY')
354
355
            if not shift:
                shift = CONFIG['SHIFT_Y']
356

357
358
359
            shiftY = [''.join(('DY=',str(shift - CONFIG['SHIFT_Y'])))]
            #print shiftY
            args.extend(shiftY)
360

Monica Rainer's avatar
Monica Rainer committed
361
362
363
364
365
366
367
368
369
370
371
372
        subprocess.call(args)
        str_file = os.path.join(CONFIG['RED_STR'],os.path.basename(straight))
        try: shutil.copyfile(straight,str_file)
        except: pass

        self.messages.append('%s: orders straightened.' % str(os.path.basename(fitsfile)),)

        imstr = ccdproc.CCDData.read(straight, unit=u.adu)

        try: nspec = imstr.header[CONFIG['KEYS']['NCOMBINE']]
        except: nspec = 1

Monica Rainer's avatar
Monica Rainer committed
373
374
375
376
377
378
379
380
381
382
383
384
        # search for slit position
        try:
            slit_value = imstr.header[CONFIG['KEYS']['SLIT']]
            if slit_value == CONFIG['A']:
                slit_pos = CONFIG['A_POS']
            elif slit_value == CONFIG['B']:
                slit_pos = CONFIG['B_POS']
            else:
                slit_pos = CONFIG['C_POS']
        except: slit_pos = CONFIG['C_POS']


Monica Rainer's avatar
Monica Rainer committed
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
        # use only the regions of the orders
        try:
            goodmask = ccdproc.CCDData.read(CONFIG['MASK_C'], unit=u.adu)
        except:
            try:
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
            except:
                masterflat = False
            if not masterflat:
                db.copy_dbfile(self.dbconn,'flatstr')
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
                self.messages.append('No masterflat found for this night, it will be taken from the calibration database: %s' % (os.path.basename(masterflat)))
            mflat = ccdproc.CCDData.read(masterflat, unit=u.adu)
            varie.buildMaskC(mflat.data)
            self.messages.append('The extraction mask was created.')
            goodmask = ccdproc.CCDData.read(CONFIG['MASK_C'], unit=u.adu)

        gmask = goodmask.data

        roneff = imstr.header[CONFIG['RON_EFF'][0]]
        gaineff = imstr.header[CONFIG['GAIN_EFF'][0]]

        if CONFIG['USE_FLAT']['global']:
            try:
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
            except:
                masterflat = False

            if not masterflat:
                db.copy_dbfile(self.dbconn,'flatstr')
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
                self.messages.append('No masterflat found for this night, it will be taken from the calibration database: %s' % (os.path.basename(masterflat)))

            flat = ccdproc.CCDData.read(masterflat, unit=u.adu)
            froneff = flat.header[CONFIG['RON_EFF'][0]]
            fgaineff = flat.header[CONFIG['GAIN_EFF'][0]]
            meanflat = np.mean(flat.data)
            norflat = np.true_divide(flat.data,meanflat)
            with np.errstate(divide='ignore', invalid='ignore'):
                imflat = np.true_divide(imflat,norflat)

        elif CONFIG['USE_FLAT']['order']:
            try:
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
            except:
                masterflat = False

            if not masterflat:
                db.copy_dbfile(self.dbconn,'flatstr')
                masterflat = db.extract_dbfile(self.dbconn,'flatstr')
                self.messages.append('No masterflat found for this night, it will be taken from the calibration database: %s' % (os.path.basename(masterflat)))
            flat = ccdproc.CCDData.read(masterflat, unit=u.adu)
            froneff = flat.header[CONFIG['RON_EFF'][0]]
            fgaineff = flat.header[CONFIG['GAIN_EFF'][0]]


        elif CONFIG['USE_FLAT']['nor']:
            try:
                masterflat = db.extract_dbfile(self.dbconn,'flatnor')
            except:
                masterflat = False

            if not masterflat:
                db.copy_dbfile(self.dbconn,'flatnor')
                masterflat = db.extract_dbfile(self.dbconn,'flatnor')
                self.messages.append('No masterflat found for this night, it will be taken from the calibration database: %s' % (os.path.basename(masterflat)))

            flat = ccdproc.CCDData.read(masterflat, unit=u.adu)
            froneff = flat.header[CONFIG['RON_EFF'][0]]
            fgaineff = flat.header[CONFIG['GAIN_EFF'][0]]
            meanflat = 1.0
            norflat = flat.data
            with np.errstate(divide='ignore', invalid='ignore'):
                imflat = np.true_divide(imflat,norflat)


        try:
            masterlamp = db.extract_dbfile(self.dbconn,'une_str')
        except:
            masterlamp = False

        if not masterlamp:
            db.copy_dbfile(self.dbconn,'une_str')
            masterlamp = db.extract_dbfile(self.dbconn,'une_str')
            db.copy_dbfile(self.dbconn,'une_calib')
            self.messages.append('No calibration lamp found for this night, it will be taken from the calibration database: %s' % (os.path.basename(masterlamp)))

        mlamp = ccdproc.CCDData.read(masterlamp, unit=u.adu)

        lroneff = mlamp.header[CONFIG['RON_EFF'][0]]
        lgaineff = mlamp.header[CONFIG['GAIN_EFF'][0]]

        # read the lines to use in the wavelength calibration
        select_lines, all_lines = varie.UNe_linelist()

        # prepare the structure for the calibrated results
        heacal = OrderedDict() # header for the calibration table
Monica Rainer's avatar
Monica Rainer committed
482
483
484
485
        #stdSpectrum = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        optSpectrum = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        fsnr = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        snr = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
Monica Rainer's avatar
Monica Rainer committed
486

Monica Rainer's avatar
Monica Rainer committed
487
488
        all_cosmics = 0
        for x in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
489

Monica Rainer's avatar
Monica Rainer committed
490
491
            start = x*CONFIG['W_ORD']
            end = min(start+CONFIG['W_ORD'],CONFIG['YCCD'])
Monica Rainer's avatar
Monica Rainer committed
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

            # select only the rows wit the signal using the appropriate mask

            omask = gmask[start:end]

            order = imstr.data[start:end]

            if CONFIG['USE_FLAT']['order']:
                ordflat = flat.data[start:end]
                # divide by masterflat normalized by its average value
                meanflat = np.mean(ordflat)
                norflat = np.true_divide(ordflat,meanflat)
                with np.errstate(divide='ignore', invalid='ignore'):
                    order = np.true_divide(order,norflat)

            ordermasked = np.ma.MaskedArray(order,mask=omask)
            goodorder = np.ma.compress_rows(ordermasked)

            # call optimal extraction
Monica Rainer's avatar
Monica Rainer committed
511
512
            optSpectrum[x],varOptFlux,profile,x1,x2,cosmics = varie.optExtract(goodorder,gaineff,roneff,slit_pos,x)
            all_cosmics = all_cosmics + cosmics
Monica Rainer's avatar
Monica Rainer committed
513
514
515
516
517
518
519
520
521
522
523

            olamp = mlamp.data[start:end]
            orderlamp = np.ma.MaskedArray(olamp,mask=omask)
            goodlamp = np.ma.compress_rows(orderlamp)

            extlamp = varie.extract(goodlamp, optSpectrum[x], x1, x2, profile, lgaineff, lroneff)

            if any(CONFIG['USE_FLAT'].values()) is True:
                extflat = varie.extract(norflat, optSpectrum[x], x1, x2, profile, fgaineff, froneff)
                #print extflat
                with np.errstate(divide='ignore', invalid='ignore'):
Monica Rainer's avatar
Monica Rainer committed
524
525
                    #fsnr[x] = (np.sqrt(froneff**2 + (fgaineff*(extflat*meanflat))))/(fgaineff*(extflat*meanflat))
                    fsnr[x] = np.true_divide(np.sqrt(froneff**2 + (fgaineff*(extflat*meanflat))),fgaineff*(extflat*meanflat))
Monica Rainer's avatar
Monica Rainer committed
526
527
528
529
530
531
532
533
                    fsnr[fsnr==np.inf] = 0
                    fsnr[fsnr==-np.inf] = 0
                    fsnr = np.nan_to_num(fsnr)
                #print fsnr
            else:
                fsnr[x] = np.zeros(len(optSpectrum[x]))

            with np.errstate(divide='ignore', invalid='ignore'):
Monica Rainer's avatar
Monica Rainer committed
534
535
                #ssnr = (np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])))/(gaineff*nspec*optSpectrum[x])
                ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])),gaineff*nspec*optSpectrum[x])
Monica Rainer's avatar
Monica Rainer committed
536
537
538
539
540
541
542
543
                snr[x] = 1.0/(np.sqrt(ssnr**2 + fsnr[x]**2))


            calib_failed, coeffs, comments = varie.UNe_calibrate(extlamp,x+32,select_lines[x+32],all_lines[x+32])

            for comment in comments:
                self.messages.append(comment)

Monica Rainer's avatar
Monica Rainer committed
544
545
            keyfail = ''.join((CONFIG['CAL_FAILED'][0],str(x+32)))

Monica Rainer's avatar
Monica Rainer committed
546
            if calib_failed:
Monica Rainer's avatar
Monica Rainer committed
547
                heacal[keyfail] = (False,CONFIG['CAL_FAILED'][1])
Monica Rainer's avatar
Monica Rainer committed
548
549
550
551
552
553
554
555
556
                self.messages.append(' *** WARNING ***')
                self.messages.append('The default wavelength calibration for the order %s will be taken from the database and as such it will not be optimal for the night.' % (str(x+32),))
                wcalib = db.extract_dbfile(self.dbconn,'une_calib')
                wlc = ccdproc.CCDData.read(wcalib, unit=u.adu)
                for key in coeffs:
                    keyword = ''.join((CONFIG['WLCOEFFS'][key][0],str(x+32)))
                    heacal[keyword] = wlc.header[keyword]

            else:
Monica Rainer's avatar
Monica Rainer committed
557
                heacal[keyfail] = (True,CONFIG['CAL_FAILED'][1])
Monica Rainer's avatar
Monica Rainer committed
558
559
560
561
562
563
564
565
566
                for key in coeffs:
                    keyword = ''.join((CONFIG['WLCOEFFS'][key][0],str(x+32)))
                    heacal[keyword] = (coeffs[key],CONFIG['WLCOEFFS'][key][1])


        optSpectrum = np.asarray(optSpectrum, dtype='float32')


        self.messages.append('The spectrum %s was extracted.' % str(os.path.basename(straight)),)
Monica Rainer's avatar
Monica Rainer committed
567
568
569
570
        if all_cosmics == 1050:
            self.messages.append('%s cosmics were removed (maximum iteration reached).' % str(all_cosmics),)
        else:
            self.messages.append('%s cosmics were removed.' % str(all_cosmics),)
Monica Rainer's avatar
Monica Rainer committed
571

Monica Rainer's avatar
Monica Rainer committed
572
        redname = os.path.join(CONFIG['RED_DIR'],str(os.path.basename(fitsfile)))
573
574
575
576
577
578
        sfx = ''.join(('_',CONFIG['MERGED'],'.fits'))
        msfx = ''.join(('_',CONFIG['UNMERGED'],'.fits'))
        calname = redname.replace('.fits',msfx)
        calname1d = redname.replace('.fits',sfx)
        #calname = redname.replace('.fits','_e2ds.fits')
        #calname1d = redname.replace('.fits','_s1d.fits')
Monica Rainer's avatar
Monica Rainer committed
579
580

        heaspe = fits.Header(imstr.header)
581
582
        heaspe[CONFIG['KEYS']['FILENAME']] = str(os.path.basename(calname))
        heaspe[CONFIG['KEYS']['IMANAME']] = str(os.path.basename(calname))
Monica Rainer's avatar
Monica Rainer committed
583

Monica Rainer's avatar
Monica Rainer committed
584
        try:
585
586
587
            heaspe[CONFIG['MASTERFLAT'][0]] = (os.path.basename(masterflat),CONFIG['MASTERFLAT'][1])
        except:
            heaspe[CONFIG['MASTERFLAT'][0]] = ('None',CONFIG['MASTERFLAT'][1])
Monica Rainer's avatar
Monica Rainer committed
588
        try:
589
590
591
            heaspe[CONFIG['MASTERLAMP'][0]] = (os.path.basename(masterlamp),CONFIG['MASTERLAMP'][1])
        except:
            heaspe[CONFIG['MASTERLAMP'][0]] = ('None',CONFIG['MASTERLAMP'][1])
592

Monica Rainer's avatar
Monica Rainer committed
593
594
595
596
        snr[snr==np.inf] = 0
        snr[snr==-np.inf] = 0
        snr = np.nan_to_num(snr)

Monica Rainer's avatar
Monica Rainer committed
597
598
599
600
601
602
603
604
605
606

        snry = round(np.mean(snr[41]),2)
        snrj = round(np.mean(snr[29]),2)
        snrh = round(np.mean(snr[14]),2)
        snrk = round(np.mean(snr[3]),2)

        self.messages.append('Stare image: SNR[Y band, order=73, wl=1050 nm] = %s' % (str(snry)),)
        self.messages.append('Stare image: SNR[J band, order=61, wl=1250 nm] = %s' % (str(snrj)),)
        self.messages.append('Stare image: SNR[H band, order=46, wl=1650 nm] = %s' % (str(snrh)),)
        self.messages.append('Stare image: SNR[K band, order=35, wl=2200 nm] = %s' % (str(snrk)),)
Monica Rainer's avatar
Monica Rainer committed
607

Monica Rainer's avatar
Monica Rainer committed
608
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
609
610
611
612
613
614
615
            key_snr = ''.join((CONFIG['SNR'][0],str(o+32)))
            heaspe[key_snr] = (round(np.mean(snr[o]),2),CONFIG['SNR'][1])

        heaspe[CONFIG['WLFIT'][0]] = (CONFIG['WLFIT_FUNC'],CONFIG['WLFIT'][1])
        for hea in heacal:
            heaspe[hea] = heacal[hea]

Monica Rainer's avatar
Monica Rainer committed
616
        barycorr, hjd, bjd = varie.berv_corr(heaspe)
Monica Rainer's avatar
Monica Rainer committed
617
618
        heaspe[CONFIG['BERV'][0]] = (barycorr,CONFIG['BERV'][1])
        heaspe[CONFIG['HJD'][0]] = (hjd,CONFIG['HJD'][1])
Monica Rainer's avatar
Monica Rainer committed
619
        heaspe[CONFIG['BJD'][0]] = (bjd,CONFIG['BJD'][1])
Monica Rainer's avatar
Monica Rainer committed
620

Monica Rainer's avatar
Monica Rainer committed
621
622
        waves = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
623
624
            waves[o] = varie.wcalib(heaspe,o)

625
626
627
628
629
630
        #spefits = fits.PrimaryHDU(optSpectrum,header=heaspe)
        #wavefits = fits.ImageHDU(waves,name='WAVE')
        #snrfits = fits.ImageHDU(snr,name='SNR')
        #results = fits.HDUList([spefits,wavefits,snrfits])
        #calname = os.path.join(CONFIG['RED_DIR'],calname)
        #results.writeto(calname,clobber=True)
Monica Rainer's avatar
Monica Rainer committed
631

Monica Rainer's avatar
Monica Rainer committed
632

633
634
635
636
637
        orders=np.arange(CONFIG['N_ORD'])+32
        c1 = fits.Column(name='ORDER', format='I', array=orders)
        c2 = fits.Column(name='WAVE', format=''.join((str(CONFIG['YCCD']),'D')), unit='nm', array=waves)
        c3 = fits.Column(name='FLUX', format=''.join((str(CONFIG['YCCD']),'D')), array=optSpectrum)
        c4 = fits.Column(name='SNR', format=''.join((str(CONFIG['YCCD']),'D')), array=snr)
Monica Rainer's avatar
Monica Rainer committed
638

Monica Rainer's avatar
Monica Rainer committed
639
640
        heaspe[CONFIG['DRS_VERSION'][0]] = (CONFIG['VERSION'], CONFIG['DRS_VERSION'][1])

641
642
643
644
        #tbhdu = fits.BinTableHDU.from_columns([c1, c2, c3, c4],header=heaspe)
        tbhdu = fits.BinTableHDU.from_columns([c1, c2, c3, c4])
        prihdu = fits.PrimaryHDU(data=None, header=heaspe)
        hdulist = fits.HDUList([prihdu, tbhdu])
Monica Rainer's avatar
Monica Rainer committed
645
646

        calname = os.path.join(CONFIG['RED_DIR'],calname)
647
648
        #tbhdu.writeto(calname,clobber=True)
        hdulist.writeto(calname,clobber=True)
649

Monica Rainer's avatar
Monica Rainer committed
650
651
652
        try: obj_name = heaspe[CONFIG['KEYS']['OBJECT']]
        except: obj_name = 'NONE'

Monica Rainer's avatar
Monica Rainer committed
653

Monica Rainer's avatar
Monica Rainer committed
654
        if CONFIG['S1D']:
655
656
            heaspe[CONFIG['KEYS']['FILENAME']] = str(os.path.basename(calname1d))
            heaspe[CONFIG['KEYS']['IMANAME']] = str(os.path.basename(calname1d))
Monica Rainer's avatar
Monica Rainer committed
657
            #s1d = varie.create_s1d(optSpectrum,snr,heaspe)
658
            s1d, startval = varie.create_s1d(optSpectrum,heaspe)
Monica Rainer's avatar
Monica Rainer committed
659
            heaspe['CRPIX1'] = (1.,'Reference pixel')
660
            heaspe['CRVAL1'] = (startval,'Coordinates at reference pixel')
Monica Rainer's avatar
Monica Rainer committed
661
662
663
664
665
            heaspe['CDELT1'] = (CONFIG['S1D_STEP'],'Coordinates increment per pixel')

            heaspe['CTYPE1'] = ('Nanometers','Units of coordinates')
            heaspe['BUNIT'] = ('Relative Flux','Units of data values')

666
            s1dfits = fits.PrimaryHDU(s1d,header=heaspe)
Monica Rainer's avatar
Monica Rainer committed
667
668
            calname1d = os.path.join(CONFIG['RED_DIR'],calname1d)
            s1dfits.writeto(calname1d,clobber=True)
Monica Rainer's avatar
Monica Rainer committed
669
670
671
672
673
674
            rid = varie.random_id(12)

            dbreduced['s1d'] = {'slit':slit_pos, 'path':calname1d, 'snry':snry, 'snrj':snrj, 'snrh':snrh, 'snrk':snrk, 'type':'s1d', 'name':obj_name, 'id':rid}

        rid = varie.random_id(12)
        dbreduced['ms1d'] = {'slit':slit_pos, 'path':calname, 'snry':snry, 'snrj':snrj, 'snrh':snrh, 'snrk':snrk, 'type':'ms1d', 'name':obj_name, 'id':rid}
Monica Rainer's avatar
Monica Rainer committed
675

Monica Rainer's avatar
Monica Rainer committed
676
677

        if imstr.header[CONFIG['KEYS']['EXTMODE']] == CONFIG['EXTPAIR']:
Monica Rainer's avatar
Monica Rainer committed
678
            return calname, straight, dbreduced 
Monica Rainer's avatar
Monica Rainer committed
679
680

        elif 'grp' in fitsfile:
Monica Rainer's avatar
Monica Rainer committed
681
            return calname, straight, dbreduced
Monica Rainer's avatar
Monica Rainer committed
682

Monica Rainer's avatar
Monica Rainer committed
683
        return calname, False, dbreduced
Monica Rainer's avatar
Monica Rainer committed
684
685

    def pair_process(self):
686
        #reduced = ','.join(map(os.path.basename,self.stare))
Monica Rainer's avatar
Monica Rainer committed
687
        stamp = time.time()
688
689
        #db.insert_dbnight(self.dbnight, reduced, stamp)
        db.insert_dbnight(self.dbnight, self.stare, stamp)
Monica Rainer's avatar
Monica Rainer committed
690

Monica Rainer's avatar
Monica Rainer committed
691
692
693
        warnings.simplefilter('ignore', category=AstropyWarning)
        if self.qualitycheck():
            obj = self.createObj(False)
Monica Rainer's avatar
Monica Rainer committed
694
            calib, straight, dbreduced = self.reduce(obj)
Monica Rainer's avatar
Monica Rainer committed
695
696
697
698
699
700
701
702

            try:
                db.insert_dbreduced(self.dbnight, dbreduced['s1d'], stamp)
            except:
                pass
            db.insert_dbreduced(self.dbnight, dbreduced['ms1d'], stamp)


Monica Rainer's avatar
Monica Rainer committed
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
            if straight:
                os.remove(obj)
                os.remove(straight)

        #self.stare[:] = []
        self.starelist[:] = []
        self.skylist[:] = []

        return

    def group_process(self):
        warnings.simplefilter('ignore', category=AstropyWarning)
        self.pair_process()
        self.stare = self.group['stares']
        #print self.stare
        if self.qualitycheck():
            obj = self.createObj(True)
Monica Rainer's avatar
Monica Rainer committed
720
            calib, straight, dbreduced = self.reduce(obj)
Monica Rainer's avatar
Monica Rainer committed
721
722
723
724
725
726
727
728
729
730
731
732
733
            if straight:
                os.remove(obj)
                os.remove(straight)
        self.group.clear()

        return

    def ingroup_process(self):
        warnings.simplefilter('ignore', category=AstropyWarning)
        self.pair_process()
        self.stare = self.group['stares']
        if self.qualitycheck():
            obj = self.createObj(True)
Monica Rainer's avatar
Monica Rainer committed
734
            calib, straight, dbreduced = self.reduce(obj)
Monica Rainer's avatar
Monica Rainer committed
735
736
737
738
739
740
741
742
            if straight:
                os.remove(obj)
                os.remove(straight)
        self.group.clear()

        return