darkframes.py 5.05 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
"""
Last modified: 2017-03-07

Reduction of the flat-fields:
- check the exposure time
- check the mean flux in the four quadrants
- create the masterdark
"""

from astropy import units as u
from astropy.io import fits
import warnings
from astropy.utils.exceptions import AstropyWarning

from ccdproc import CCDData, Combiner
from drslib.config import CONFIG
from drslib import db
import numpy as np
import os, shutil


class GBDarks():
    def __init__(self, darks, dbconn):
        self.darks = darks
        self.dbconn = dbconn
        self.quality = []
        self.messages = []
        self.darklists = CONFIG['DARKLIST']
        self.masterdarks = {}


    def qualitycheck(self):
        for frame in self.darks:
            dark = CCDData.read(frame, unit=u.adu)
            exptime = int(dark.header[CONFIG['KEYS']['EXPTIME']])
            if exptime not in self.darklists.keys():
                self.messages.append('Dark frame %s has exposure time %s sec: skipped.' % (str(os.path.basename(frame)),str(dark.header[CONFIG['KEYS']['EXPTIME']]),))
38
                self.quality.append('FAILED')
Monica Rainer's avatar
Monica Rainer committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
                continue

# check the four dark quadrants, compute mean and std
            x = CONFIG['XCCD']
            y = CONFIG['YCCD']

            mean = []
            std = []

            quadrant1 = dark.data[0:x/2,0:y/2]
            mean.append(np.mean(quadrant1))
            #std.append(np.std(quadrant1))

            quadrant2 = dark.data[x/2+1:x,0:y/2]
            mean.append(np.mean(quadrant2))
            #std.append(np.std(quadrant2))

            quadrant3 = dark.data[0:x/2,y/2+1:y]
            mean.append(np.mean(quadrant3))
            #std.append(np.std(quadrant3))

            quadrant4 = dark.data[x/2+1:x,y/2+1:y]
            mean.append(np.mean(quadrant4))
            #std.append(np.std(quadrant4))

            if exptime in CONFIG['DARK_MEAN']:
                qcheck = np.asarray(CONFIG['DARK_MEAN'][exptime]) 
            else:
                qcheck = np.asarray(CONFIG['DARK_MEAN'][min(CONFIG['DARK_MEAN'].keys(), key=lambda k: abs(k-exptime))])

            if (np.asarray(mean) > qcheck).any():
                self.messages.append('Dark frame %s failed quality check' % (str(os.path.basename(frame))),)
                dark = None
72
                self.quality.append('FAILED')
Monica Rainer's avatar
Monica Rainer committed
73
74
75

            else:
                self.darklists[exptime].append(dark)
76
                self.quality.append('OK')
Monica Rainer's avatar
Monica Rainer committed
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

            #print frame
            #print 'Quadrant 1: mean ' + str(mean[0])
            #print 'Quadrant 2: mean ' + str(mean[1])
            #print 'Quadrant 3: mean ' + str(mean[2])
            #print 'Quadrant 4: mean ' + str(mean[3])
            #print 'Global: mean ' + str(np.mean(dark.data)) + ' - std ' + str(np.std(dark.data))
        return


    def masterdark(self):
        for exptime in self.darklists:
            calname = 'dark' + str(int(exptime))
            if self.darklists[exptime]:
                hea = self.darklists[exptime][0].header
                darkname = hea[CONFIG['KEYS']['IMANAME']].replace('.fts','_DARK.fits')

                nome = os.path.join(CONFIG['CALIB_DIR'],darkname)
                red_name = os.path.join(CONFIG['RED_CALIB'],darkname)

                combinedark = Combiner(self.darklists[exptime])
                combinedark.sigma_clipping(func=np.ma.mean)

                self.masterdarks[exptime] = combinedark.average_combine()
                self.masterdarks[exptime].data = np.asarray(self.masterdarks[exptime].data, dtype='float32')
                self.masterdarks[exptime].header = hea
                self.masterdarks[exptime].header[CONFIG['KEYS']['FILENAME']] = darkname
                self.masterdarks[exptime].header[CONFIG['KEYS']['NCOMBINE']] = len(self.darklists[exptime])

                hdu = fits.PrimaryHDU(data=self.masterdarks[exptime].data,header=self.masterdarks[exptime].header)
                mdark = fits.HDUList([hdu])

                darkmean = '%.3f' % np.mean(self.masterdarks[exptime].data)

                mdark.writeto(nome,clobber=True)

                shutil.copyfile(nome,red_name)

                self.darklists[exptime][:] = [] # empty the lists
                self.masterdarks[exptime] = None

                self.messages.append('Created masterdark with exposure time = %s seconds.' % (str(exptime)))
                self.messages.append('Mean value of dark current: %s ' % (str(darkmean),))

                db.insert_dbfile(self.dbconn,calname,nome)

            else:
                self.messages.append('Not enough dark frame to create %s sec masterdark. The masterdark will be taken from the calibration database.' % (exptime),)
                if db.check_dbfile(self.dbconn,calname):
                    try:
                        db.copy_dbfile(self.dbconn,calname)
                    except:
                        self.messages.append('There are no masterdarks of %s sec in the database. If needed, observe them now.' % (exptime),)
        return

    def process(self):
        warnings.simplefilter('ignore', category=AstropyWarning)
        self.qualitycheck()
        self.masterdark()
        return