stare.py 34.9 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
"""
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
Andrea Bignamini's avatar
Andrea Bignamini committed
33
from drslib import metadata
Monica Rainer's avatar
Monica Rainer committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

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
50
    def __init__(self, stare, group, dbconn, dbnight):
Monica Rainer's avatar
Monica Rainer committed
51
52
53
        self.stare = stare
        self.group = group
        self.dbconn = dbconn
Monica Rainer's avatar
Monica Rainer committed
54
        self.dbnight = dbnight
Monica Rainer's avatar
Monica Rainer committed
55
56
57
58
59
60
61
62
63
64
65
        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
66
67
        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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        """

        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
Monica Rainer's avatar
Monica Rainer committed
89
            if nod.header[CONFIG['KEYS']['STARE']].lower() == CONFIG['OBJ'].lower() or nod.header[CONFIG['KEYS']['STARE']].lower() == CONFIG['UNKNOWN'].lower():
Monica Rainer's avatar
Monica Rainer committed
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
                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))

117
118
        #print name_obj
        #print name_sky
Monica Rainer's avatar
Monica Rainer committed
119

Monica Rainer's avatar
Monica Rainer committed
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
# 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
150
        self.mjd = np.average(np.asarray(mjd_obj)) + (exp_common/(2.0*86400.0))
Monica Rainer's avatar
Monica Rainer committed
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
        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
265
                mdark_mjd = mdark.header[CONFIG['KEYS']['MJD']]
Monica Rainer's avatar
Monica Rainer committed
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
                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'))

298
299
300
            #value_keyA = self.skylist[n].header[CONFIG['KEYS']['FILENAME']]
            value_keyA = self.skylist[n].header[CONFIG['KEYS']['IMANAME']]
            value_mjdA = self.skylist[n].header[CONFIG['KEYS']['MJD']]
Monica Rainer's avatar
Monica Rainer committed
301
302
303
304

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

305
306
307
308
309
310
311
312
313
314
315
316
317
318
        try:
            if use_dark:
                keyA = ''.join((CONFIG['SPEC_USED'][0],'0','SKY'))
                mjdA = ''.join((CONFIG['SPEC_MJD'][0],'0','SKY'))

                value_keyA = os.path.basename(masterdark)
                value_mjdA = mdark_mjd

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


Monica Rainer's avatar
Monica Rainer committed
319
320
321
322
        #Cnome = self.starelist[0].header[CONFIG['KEYS']['FILENAME']]
        Cnome = self.starelist[0].header[CONFIG['KEYS']['IMANAME']]
        #print Cnome
        #qui = Cnome.rindex('.')
Monica Rainer's avatar
Monica Rainer committed
323
324
325
        #nomebase = os.path.splitext(Cnome)[0]
        nomebase = '_'.join((os.path.splitext(Cnome)[0],corrected.header[CONFIG['KEYS']['SLIT']].strip()))

Monica Rainer's avatar
Monica Rainer committed
326
        if grp:
Monica Rainer's avatar
Monica Rainer committed
327
328
            #Cnome = '_'.join((nomebase,'Cgrp.fits'))
            Cnome = '_'.join((nomebase,'grp.fits'))
Monica Rainer's avatar
Monica Rainer committed
329
        else:
Monica Rainer's avatar
Monica Rainer committed
330
331
            #Cnome = '_'.join((nomebase,'C.fits'))
            Cnome = ''.join((nomebase,'.fits'))
Monica Rainer's avatar
Monica Rainer committed
332
333
334
335
336
337
338
339
340
        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
341
    def reduce(self,fitsfile):
Monica Rainer's avatar
Monica Rainer committed
342
343
344
        """
        Straighten, divide by the masterflat, optimal extraction
        """
Monica Rainer's avatar
Monica Rainer committed
345
346

        dbreduced = {}
Monica Rainer's avatar
Monica Rainer committed
347
348
349
        # straighten

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

351
352
353
354
355
        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']:
356
            try:
357
358
359
360
                dy = opt.rindex('DY=')
                ypos = int(opt[dy-2:])
                shift = CONFIG['SHIFT_Y'] + ypos
                dy = False
361
            except:
362
363
364
                pass

        if dy:
Unknown's avatar
Unknown committed
365
366
367
368
369
            try:
                shift = db.extract_dbfile(self.dbconn,'shiftY')
            except:
                try:
                    cal_flat = db.extract_dbfile(self.dbconn,'flat')
370
371
372
                    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
373
                except:
Monica Rainer's avatar
   
Monica Rainer committed
374
375
376
377
378
379
380
381
                    try:
                        db.copy_dbfile(self.dbconn,'shiftY')
                        shift = db.extract_dbfile(self.dbconn,'shiftY')
                    except:
                        shift = CONFIG['SHIFT_Y']
                        self.messages.append('No flat-field or shift value present in the calibration database, no shift will be applied.')
#                    db.copy_dbfile(self.dbconn,'shiftY')
#                    shift = db.extract_dbfile(self.dbconn,'shiftY')
382
383
            if not shift:
                shift = CONFIG['SHIFT_Y']
384

385
386
387
            shiftY = [''.join(('DY=',str(shift - CONFIG['SHIFT_Y'])))]
            #print shiftY
            args.extend(shiftY)
388

Monica Rainer's avatar
Monica Rainer committed
389
        subprocess.call(args)
Andrea Bignamini's avatar
Andrea Bignamini committed
390

Monica Rainer's avatar
   
Monica Rainer committed
391
        #imstr = ccdproc.CCDData.read(straight, unit=u.adu)
Andrea Bignamini's avatar
Andrea Bignamini committed
392
393
394

        # Update FILENAME in header then
        # add metadata to header and save straight file
Monica Rainer's avatar
   
Monica Rainer committed
395
396
397
398
399
400
401
        with fits.open(straight, 'update') as s:
            s[0].header[CONFIG['KEYS']['FILENAME']] = os.path.basename(straight)
            s[0].header = metadata.add_metadata(s[0].header)

        #hdu = fits.PrimaryHDU(data=imstr.data, header=imstr.header)
        #str_fits = fits.HDUList([hdu])
        #str_fits.writeto(straight, overwrite=True)
Andrea Bignamini's avatar
Andrea Bignamini committed
402

Monica Rainer's avatar
   
Monica Rainer committed
403
404
405
406
        # Read straight file
        imstr = ccdproc.CCDData.read(straight, unit=u.adu)
        imflat = imstr.data.copy()
        
Andrea Bignamini's avatar
Andrea Bignamini committed
407

Monica Rainer's avatar
Monica Rainer committed
408
409
410
411
412
413
414
415
416
        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)),)

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

Monica Rainer's avatar
Monica Rainer committed
417
418
419
420
421
422
423
424
425
426
427
428
        # 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
429
430
431
432
433
434
435
        # 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:
Monica Rainer's avatar
Monica Rainer committed
436
437
                masterflat = False
            if not masterflat:
Monica Rainer's avatar
   
Monica Rainer committed
438
439
440
441
442
443
444
445
446
447
448
#                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)))
                try:
                    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)))
                except:
                    self.messages.append('No masterflat found in the calibration database, it is not possible to identify the orders. The spectra will not be reduced.')
                    return

Monica Rainer's avatar
Monica Rainer committed
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
            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:
516
517
518
            masterlamp = False

        if not masterlamp:
Monica Rainer's avatar
   
Monica Rainer committed
519
520
521
522
523
524
            try:
                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)))
            except:
525
526
527
                masterlamp = False

            if not masterlamp:
Monica Rainer's avatar
   
Monica Rainer committed
528
529
                self.messages.append('No calibration lamp found in the calibration database, the spectra will not be reduced.')
                return
Monica Rainer's avatar
Monica Rainer committed
530
531
532
533
534
535
536
537
538
539
540

        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
541
542
543
544
        #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
545

Monica Rainer's avatar
Monica Rainer committed
546
547
548
549
        x0 = np.zeros(CONFIG['N_ORD'])
        x1 = np.zeros(CONFIG['N_ORD'],dtype=int)
        x2 = np.zeros(CONFIG['N_ORD'],dtype=int)

Monica Rainer's avatar
Monica Rainer committed
550
551
        all_cosmics = 0
        for x in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
552

Monica Rainer's avatar
Monica Rainer committed
553
554
            start = x*CONFIG['W_ORD']
            end = min(start+CONFIG['W_ORD'],CONFIG['YCCD'])
Monica Rainer's avatar
Monica Rainer committed
555
556
557
558
559

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

            omask = gmask[start:end]

Monica Rainer's avatar
Monica Rainer committed
560
561
            #order = imstr.data[start:end]
            order = imflat[start:end]
Monica Rainer's avatar
Monica Rainer committed
562
563
564
565
566
567
568
569
570
571
572
573
574

            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
575
            optSpectrum[x],varOptFlux,profile,x0[x],x1[x],x2[x],cosmics = varie.optExtract(goodorder,gaineff,roneff,slit_pos,x)
Monica Rainer's avatar
Monica Rainer committed
576
            all_cosmics = all_cosmics + cosmics
Monica Rainer's avatar
Monica Rainer committed
577
578
579
580
581

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

Monica Rainer's avatar
Monica Rainer committed
582
            extlamp = varie.extract(goodlamp, optSpectrum[x], x1[x], x2[x], profile, lgaineff, lroneff)
Monica Rainer's avatar
Monica Rainer committed
583
584

            if any(CONFIG['USE_FLAT'].values()) is True:
Monica Rainer's avatar
Monica Rainer committed
585
                extflat = varie.extract(norflat, optSpectrum[x], x1[x], x2[x], profile, fgaineff, froneff)
Monica Rainer's avatar
Monica Rainer committed
586
587
                #print extflat
                with np.errstate(divide='ignore', invalid='ignore'):
Monica Rainer's avatar
Monica Rainer committed
588
589
                    #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
590
591
592
                    fsnr[fsnr==np.inf] = 0
                    fsnr[fsnr==-np.inf] = 0
                    fsnr = np.nan_to_num(fsnr)
Monica Rainer's avatar
Monica Rainer committed
593
594
595
596
597
598

                osnr = imstr.data[start:end]
                if slit_pos == CONFIG['B_POS']:
                    osnr = -osnr
                ordersnr = np.ma.MaskedArray(osnr,mask=omask)
                goodsnr = np.ma.compress_rows(ordersnr)
Monica Rainer's avatar
Monica Rainer committed
599
                snrSpectrum = varie.extract(goodsnr, optSpectrum[x], x1[x], x2[x], profile, gaineff, roneff)
Monica Rainer's avatar
Monica Rainer committed
600
601
602
603
604
605
606
607
608


                with np.errstate(divide='ignore', invalid='ignore'):
                    #ssnr = (np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])))/(gaineff*nspec*optSpectrum[x])
                    #ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*nspec*snrSpectrum)),gaineff*nspec*snrSpectrum)
                    ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*snrSpectrum)),gaineff*snrSpectrum)
                    snr[x] = 1.0/(np.sqrt(ssnr**2 + fsnr[x]**2))


Monica Rainer's avatar
Monica Rainer committed
609
            else:
Monica Rainer's avatar
Monica Rainer committed
610
611
612
613
614
                #fsnr[x] = np.zeros(len(optSpectrum[x]))
                with np.errstate(divide='ignore', invalid='ignore'):
                    #ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])),gaineff*nspec*optSpectrum[x])
                    ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*optSpectrum[x])),gaineff*optSpectrum[x])
                    snr[x] = 1.0/(np.sqrt(ssnr**2 + fsnr[x]**2))
Monica Rainer's avatar
Monica Rainer committed
615

Monica Rainer's avatar
Monica Rainer committed
616
617
618
            #with np.errstate(divide='ignore', invalid='ignore'):
            #    ssnr = np.true_divide(np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])),gaineff*nspec*optSpectrum[x])
            #    snr[x] = 1.0/(np.sqrt(ssnr**2 + fsnr[x]**2))
Monica Rainer's avatar
Monica Rainer committed
619
620
621
622
623
624
625


            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
626
627
            keyfail = ''.join((CONFIG['CAL_FAILED'][0],str(x+32)))

Monica Rainer's avatar
Monica Rainer committed
628
            if calib_failed:
Monica Rainer's avatar
Monica Rainer committed
629
                heacal[keyfail] = (False,CONFIG['CAL_FAILED'][1])
Monica Rainer's avatar
Monica Rainer committed
630
631
632
633
634
635
636
637
638
                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
639
                heacal[keyfail] = (True,CONFIG['CAL_FAILED'][1])
Monica Rainer's avatar
Monica Rainer committed
640
641
642
643
644
645
646
647
648
                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
649
        if all_cosmics == (CONFIG['NCOSMIC']+1)*CONFIG['N_ORD']:
Monica Rainer's avatar
Monica Rainer committed
650
651
652
            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
653

Monica Rainer's avatar
Monica Rainer committed
654
        redname = os.path.join(CONFIG['RED_DIR'],str(os.path.basename(fitsfile)))
655
656
657
658
659
660
        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
661
662

        heaspe = fits.Header(imstr.header)
663
664
        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
665

Monica Rainer's avatar
Monica Rainer committed
666
        try:
667
668
669
            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
670
        try:
671
672
673
            heaspe[CONFIG['MASTERLAMP'][0]] = (os.path.basename(masterlamp),CONFIG['MASTERLAMP'][1])
        except:
            heaspe[CONFIG['MASTERLAMP'][0]] = ('None',CONFIG['MASTERLAMP'][1])
674

Monica Rainer's avatar
Monica Rainer committed
675
676
677
678
        snr[snr==np.inf] = 0
        snr[snr==-np.inf] = 0
        snr = np.nan_to_num(snr)

Monica Rainer's avatar
Monica Rainer committed
679
680
681
682
683
684
685
686
687
688

        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
689

Monica Rainer's avatar
Monica Rainer committed
690
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
691
692
693
694
695
696
697
            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
698
        barycorr, hjd, bjd = varie.berv_corr(heaspe)
Monica Rainer's avatar
Monica Rainer committed
699
700
        heaspe[CONFIG['BERV'][0]] = (barycorr,CONFIG['BERV'][1])
        heaspe[CONFIG['HJD'][0]] = (hjd,CONFIG['HJD'][1])
Monica Rainer's avatar
Monica Rainer committed
701
        heaspe[CONFIG['BJD'][0]] = (bjd,CONFIG['BJD'][1])
Monica Rainer's avatar
Monica Rainer committed
702

Monica Rainer's avatar
Monica Rainer committed
703
704
        waves = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
705
706
            waves[o] = varie.wcalib(heaspe,o)

707
708
709
710
711
712
        #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
713

Monica Rainer's avatar
Monica Rainer committed
714

715
716
717
718
719
        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
720

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

Monica Rainer's avatar
Monica Rainer committed
723
724
725
726
        heaspe[CONFIG['YPOS'][0]] = (round((np.mean(x0)),2), CONFIG['YPOS'][1])
        heaspe[CONFIG['YPOS_LOW'][0]] = (round((np.mean(x1)),2), CONFIG['YPOS_LOW'][1])
        heaspe[CONFIG['YPOS_UP'][0]] = (round((np.mean(x2)),2), CONFIG['YPOS_UP'][1])

Andrea Bignamini's avatar
Andrea Bignamini committed
727
728
729
        # Add metadata to header
        heaspe = metadata.add_metadata(heaspe)

730
731
732
733
        #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
734
735

        calname = os.path.join(CONFIG['RED_DIR'],calname)
736
737
        #tbhdu.writeto(calname,clobber=True)
        hdulist.writeto(calname,clobber=True)
738

Monica Rainer's avatar
Monica Rainer committed
739
740
741
        try: obj_name = heaspe[CONFIG['KEYS']['OBJECT']]
        except: obj_name = 'NONE'

Monica Rainer's avatar
Monica Rainer committed
742

Monica Rainer's avatar
Monica Rainer committed
743
        if CONFIG['S1D']:
744
745
            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
746
            #s1d = varie.create_s1d(optSpectrum,snr,heaspe)
747
            s1d, startval = varie.create_s1d(optSpectrum,heaspe)
Monica Rainer's avatar
Monica Rainer committed
748
            heaspe['CRPIX1'] = (1.,'Reference pixel')
749
            heaspe['CRVAL1'] = (startval,'Coordinates at reference pixel')
Monica Rainer's avatar
Monica Rainer committed
750
751
752
753
754
            heaspe['CDELT1'] = (CONFIG['S1D_STEP'],'Coordinates increment per pixel')

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

Andrea Bignamini's avatar
Andrea Bignamini committed
755
756
757
            # Add metadata to header
            heaspe = metadata.add_metadata(heaspe)

758
            s1dfits = fits.PrimaryHDU(s1d,header=heaspe)
Monica Rainer's avatar
Monica Rainer committed
759
760
            calname1d = os.path.join(CONFIG['RED_DIR'],calname1d)
            s1dfits.writeto(calname1d,clobber=True)
Monica Rainer's avatar
Monica Rainer committed
761
762
763
764
765
766
            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
767

Monica Rainer's avatar
Monica Rainer committed
768
769

        if imstr.header[CONFIG['KEYS']['EXTMODE']] == CONFIG['EXTPAIR']:
Monica Rainer's avatar
Monica Rainer committed
770
            return calname, straight, dbreduced 
Monica Rainer's avatar
Monica Rainer committed
771
772

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

Monica Rainer's avatar
Monica Rainer committed
775
        return calname, False, dbreduced
Monica Rainer's avatar
Monica Rainer committed
776
777

    def pair_process(self):
778
        #reduced = ','.join(map(os.path.basename,self.stare))
Monica Rainer's avatar
Monica Rainer committed
779
        stamp = time.time()
780
781
        #db.insert_dbnight(self.dbnight, reduced, stamp)
        db.insert_dbnight(self.dbnight, self.stare, stamp)
Monica Rainer's avatar
Monica Rainer committed
782

Monica Rainer's avatar
Monica Rainer committed
783
784
785
        warnings.simplefilter('ignore', category=AstropyWarning)
        if self.qualitycheck():
            obj = self.createObj(False)
Monica Rainer's avatar
   
Monica Rainer committed
786
787
788
789
790

            try:
                calib, straight, dbreduced = self.reduce(obj)
            except:
                straight = False
Monica Rainer's avatar
Monica Rainer committed
791
792
793
794
795

            try:
                db.insert_dbreduced(self.dbnight, dbreduced['s1d'], stamp)
            except:
                pass
Monica Rainer's avatar
   
Monica Rainer committed
796
797
798
799
            try:
                db.insert_dbreduced(self.dbnight, dbreduced['ms1d'], stamp)
            except:
                pass
Monica Rainer's avatar
Monica Rainer committed
800

Monica Rainer's avatar
Monica Rainer committed
801
802
803
804
805
806
807
            if straight:
                os.remove(obj)
                os.remove(straight)

        #self.stare[:] = []
        self.starelist[:] = []
        self.skylist[:] = []
Monica Rainer's avatar
Monica Rainer committed
808
809
        if not self.group['stares']:
            self.group.clear()
Monica Rainer's avatar
Monica Rainer committed
810
811
812
813
814
815
816
817
818
819

        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
820
            calib, straight, dbreduced = self.reduce(obj)
Monica Rainer's avatar
Monica Rainer committed
821
822
823
824
825
826
827
828
829
830
            if straight:
                os.remove(obj)
                os.remove(straight)
        self.group.clear()

        return

    def ingroup_process(self):
        warnings.simplefilter('ignore', category=AstropyWarning)
        self.pair_process()
Monica Rainer's avatar
Monica Rainer committed
831
832
833
834
835
836
837
838
839
840
841
        try:
            self.stare = self.group['stares']
            if self.qualitycheck():
                obj = self.createObj(True)
                calib, straight, dbreduced = self.reduce(obj)
                if straight:
                    os.remove(obj)
                    os.remove(straight)
            self.group.clear()
        except:
            pass
Monica Rainer's avatar
Monica Rainer committed
842
843
844
845

        return