stare.py 28 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
49
50
"""
Last modified: 2017-03-07

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
51
    def __init__(self, stare, group, dbconn, dbnight):
Monica Rainer's avatar
Monica Rainer committed
52
53
54
        self.stare = stare
        self.group = group
        self.dbconn = dbconn
Monica Rainer's avatar
Monica Rainer committed
55
        self.dbnight = dbnight
Monica Rainer's avatar
Monica Rainer committed
56
57
58
59
60
61
62
63
64
65
66
        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
67
68
        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
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
        """

        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
            if nod.header[CONFIG['KEYS']['STARE']] == CONFIG['OBJ']:
                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)

        self.mjd = np.average(np.asarray(mjd_obj)) + (exp_common/(2*86400))
        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

    def reduce(self,fitsfile,slit_pos):
        """
        Straighten, divide by the masterflat, optimal extraction
        """
Monica Rainer's avatar
Monica Rainer committed
325
326

        dbreduced = {}
Monica Rainer's avatar
Monica Rainer committed
327
328
329
        # straighten

        straight = fitsfile.replace('.fits','_str.fits')
330
331
332
        #args = [CONFIG['STRAIGHT'],fitsfile,straight,CONFIG['STRAIGHT_OPT']]
        args = [CONFIG['STRAIGHT'],fitsfile,straight]
        args.extend(CONFIG['STRAIGHT_OPT'])
Monica Rainer's avatar
Monica Rainer committed
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
        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

        # 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
442
443
444
445
        #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
446

Monica Rainer's avatar
Monica Rainer committed
447
448
        all_cosmics = 0
        for x in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
449

Monica Rainer's avatar
Monica Rainer committed
450
451
            start = x*CONFIG['W_ORD']
            end = min(start+CONFIG['W_ORD'],CONFIG['YCCD'])
Monica Rainer's avatar
Monica Rainer committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470

            # 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
471
472
            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
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

            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'):
                    fsnr[x] = (np.sqrt(froneff**2 + (fgaineff*(extflat*meanflat))))/(fgaineff*(extflat*meanflat))
                    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'):
                ssnr = (np.sqrt(roneff**2 + (gaineff*nspec*optSpectrum[x])))/(gaineff*nspec*optSpectrum[x])
                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)

            if calib_failed:
                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:
                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
521
522
523
524
        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
525

Monica Rainer's avatar
Monica Rainer committed
526
        redname = os.path.join(CONFIG['RED_DIR'],str(os.path.basename(fitsfile)))
527
528
529
530
531
532
        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
533
534
535

        heaspe = fits.Header(imstr.header)

Monica Rainer's avatar
Monica Rainer committed
536
        try:
537
538
539
            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
540
        try:
541
542
543
            heaspe[CONFIG['MASTERLAMP'][0]] = (os.path.basename(masterlamp),CONFIG['MASTERLAMP'][1])
        except:
            heaspe[CONFIG['MASTERLAMP'][0]] = ('None',CONFIG['MASTERLAMP'][1])
544

Monica Rainer's avatar
Monica Rainer committed
545
546
547
548
        snr[snr==np.inf] = 0
        snr[snr==-np.inf] = 0
        snr = np.nan_to_num(snr)

Monica Rainer's avatar
Monica Rainer committed
549
550
551
552
553
554
555
556
557
558

        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
559

Monica Rainer's avatar
Monica Rainer committed
560
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
561
562
563
564
565
566
567
568
569
570
571
            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]

        barycorr, hjd = varie.berv_corr(heaspe)
        heaspe[CONFIG['BERV'][0]] = (barycorr,CONFIG['BERV'][1])
        heaspe[CONFIG['HJD'][0]] = (hjd,CONFIG['HJD'][1])

Monica Rainer's avatar
Monica Rainer committed
572
573
        waves = np.zeros((CONFIG['N_ORD'],CONFIG['YCCD']))
        for o in xrange(CONFIG['N_ORD']):
Monica Rainer's avatar
Monica Rainer committed
574
575
            waves[o] = varie.wcalib(heaspe,o)

576
577
578
579
580
581
        #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
582

583
584
585
586
587
        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
588

589
        tbhdu = fits.BinTableHDU.from_columns([c1, c2, c3, c4],header=heaspe)
Monica Rainer's avatar
Monica Rainer committed
590
591

        calname = os.path.join(CONFIG['RED_DIR'],calname)
592
593
        tbhdu.writeto(calname,clobber=True)

Monica Rainer's avatar
Monica Rainer committed
594
595
596
        try: obj_name = heaspe[CONFIG['KEYS']['OBJECT']]
        except: obj_name = 'NONE'

Monica Rainer's avatar
Monica Rainer committed
597

Monica Rainer's avatar
Monica Rainer committed
598
599
        if CONFIG['S1D']:
            #s1d = varie.create_s1d(optSpectrum,snr,heaspe)
600
            s1d, startval = varie.create_s1d(optSpectrum,heaspe)
Monica Rainer's avatar
Monica Rainer committed
601
            heaspe['CRPIX1'] = (1.,'Reference pixel')
602
            heaspe['CRVAL1'] = (startval,'Coordinates at reference pixel')
Monica Rainer's avatar
Monica Rainer committed
603
604
605
606
607
            heaspe['CDELT1'] = (CONFIG['S1D_STEP'],'Coordinates increment per pixel')

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

608
            s1dfits = fits.PrimaryHDU(s1d,header=heaspe)
Monica Rainer's avatar
Monica Rainer committed
609
610
            calname1d = os.path.join(CONFIG['RED_DIR'],calname1d)
            s1dfits.writeto(calname1d,clobber=True)
Monica Rainer's avatar
Monica Rainer committed
611
612
613
614
615
616
            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
617

Monica Rainer's avatar
Monica Rainer committed
618
619

        if imstr.header[CONFIG['KEYS']['EXTMODE']] == CONFIG['EXTPAIR']:
Monica Rainer's avatar
Monica Rainer committed
620
            return calname, straight, dbreduced 
Monica Rainer's avatar
Monica Rainer committed
621
622

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

Monica Rainer's avatar
Monica Rainer committed
625
        return calname, False, dbreduced
Monica Rainer's avatar
Monica Rainer committed
626
627

    def pair_process(self):
628
        #reduced = ','.join(map(os.path.basename,self.stare))
Monica Rainer's avatar
Monica Rainer committed
629
        stamp = time.time()
630
631
        #db.insert_dbnight(self.dbnight, reduced, stamp)
        db.insert_dbnight(self.dbnight, self.stare, stamp)
Monica Rainer's avatar
Monica Rainer committed
632

Monica Rainer's avatar
Monica Rainer committed
633
634
635
        warnings.simplefilter('ignore', category=AstropyWarning)
        if self.qualitycheck():
            obj = self.createObj(False)
Monica Rainer's avatar
Monica Rainer committed
636
637
638
639
640
641
642
643
644
            calib, straight, dbreduced = self.reduce(obj,CONFIG['C_POS'])

            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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
            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
662
            calib, straight, dbreduced = self.reduce(obj,CONFIG['C_POS'])
Monica Rainer's avatar
Monica Rainer committed
663
664
665
666
667
668
669
670
671
672
673
674
675
            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
676
            calib, straight, dbreduced = self.reduce(obj,CONFIG['C_POS'])
Monica Rainer's avatar
Monica Rainer committed
677
678
679
680
681
682
683
684
            if straight:
                os.remove(obj)
                os.remove(straight)
        self.group.clear()

        return