gofio.py 13.8 KB
Newer Older
Monica Rainer's avatar
Monica Rainer committed
1
2
import os, sys, time

3
from drslib.config import CONFIG, USRCONFIG, read_usr_config
Monica Rainer's avatar
Monica Rainer committed
4
5
6
7
8
9
10
from drslib.logger import DrsLogger

from drslib import db, rawfiles, darkframes, flatframes, wlframes, nodding, stare


def gofio_init(docopt_args):

11

Monica Rainer's avatar
Monica Rainer committed
12
13
    if docopt_args['--cfg']:
        try:
14
            USRCFG = read_usr_config(docopt_args['-g'])
Monica Rainer's avatar
Monica Rainer committed
15
16
        except:
            try:
17
                USRCFG = read_usr_config(docopt_args['--cfg'])
Monica Rainer's avatar
Monica Rainer committed
18
            except:
19
20
21
22
23
24
25
26
27
                USRCFG = {}
                USRCFG['OFFLINE'] = False
        for key in USRCFG.keys():
            USRCONFIG[key] = USRCFG[key]


    if USRCONFIG['OFFLINE']:
        for key in USRCONFIG.keys():
            CONFIG[key] = USRCONFIG[key]
Monica Rainer's avatar
Monica Rainer committed
28

29
30
        if docopt_args['<date>']:
            CONFIG['DATE'] = docopt_args['<date>']
Monica Rainer's avatar
Monica Rainer committed
31

32
33
34
35
36
37
38
39
        CONFIG['RAW_DIR'] = os.path.join(CONFIG['BASE_RAW'],CONFIG['DATE'])
        CONFIG['OFFLINE_DIR'] = os.path.join(CONFIG['BASE_RED_DIR'],CONFIG['DATE'])
        CONFIG['RED_DIR'] = os.path.join(CONFIG['OFFLINE_DIR'],'offline')
        CONFIG['RED_CALIB'] = os.path.join(CONFIG['RED_DIR'],'CALIB')
        CONFIG['RED_STR'] = os.path.join(CONFIG['RED_DIR'],'STR')
        CONFIG['LOG_FILE'] = os.path.join(CONFIG['RED_DIR'], 'drs.log')
        CONFIG['RAMP_NAME'] = 'ramps' + CONFIG['DATE'] + '.db'
        CONFIG['DB_RAMP'] = os.path.join(CONFIG['BASE_RAMP'],CONFIG['RAMP_NAME'])
Monica Rainer's avatar
Monica Rainer committed
40

41
42
43
44
        CONFIG['DB_OFFLINE'] = ''.join(('db_',CONFIG['DATE'],'_offline.db'))
        CONFIG['DB_OFFLINE_PATH'] = os.path.join(CONFIG['WEBUI_DB_DIR'], CONFIG['DB_OFFLINE'])
        CONFIG['DB_NIGHT'] = CONFIG['DB_OFFLINE']
        CONFIG['DB_NIGHT_PATH'] = CONFIG['DB_OFFLINE_PATH']
Monica Rainer's avatar
Monica Rainer committed
45

46
47
        maskc = ''.join(('GIANOB_MASKC_',CONFIG['DATE'],'.fits'))
        CONFIG['MASK_C'] = os.path.join(CONFIG['RES_DIR'], maskc)
Monica Rainer's avatar
Monica Rainer committed
48
49


50
    elif docopt_args['<date>']:
Monica Rainer's avatar
Monica Rainer committed
51
52
53
54
55
56
        if docopt_args['--all_calib']:
            docopt_args['--dark'] = True
            docopt_args['--flat'] = True
            docopt_args['--une'] = True
            docopt_args['--fp'] = True

Monica Rainer's avatar
Monica Rainer committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
        CONFIG['DATE'] = docopt_args['<date>']
        CONFIG['OFFLINE'] = True
        CONFIG['RAW_DIR'] = os.path.join(CONFIG['BASE_RAW'],CONFIG['DATE'])
        CONFIG['OFFLINE_DIR'] = os.path.join(CONFIG['BASE_RED_DIR'],CONFIG['DATE'])
        CONFIG['RED_DIR'] = os.path.join(CONFIG['OFFLINE_DIR'],'offline')
        CONFIG['RED_CALIB'] = os.path.join(CONFIG['RED_DIR'],'CALIB')
        CONFIG['RED_STR'] = os.path.join(CONFIG['RED_DIR'],'STR')
        CONFIG['LOG_FILE'] = os.path.join(CONFIG['RED_DIR'], 'drs.log')
        CONFIG['DO_CALIB'] = {'dark': docopt_args['--dark'], 'flat': docopt_args['--flat'], 'une': docopt_args['--une'], 'fp': docopt_args['--fp'], 'only_calib': docopt_args['--only_calib']}
 
        if docopt_args['--use_flat'] == 'global':
            CONFIG['USE_FLAT'] = {'global':True, 'order':False, 'nor':False}
        elif docopt_args['--use_flat'] == 'order':
            CONFIG['USE_FLAT'] = {'global':False, 'order':True, 'nor':False} 
        elif docopt_args['--use_flat'] == 'nor':
            CONFIG['USE_FLAT'] = {'global':False, 'order':False, 'nor':True}
        else:
            CONFIG['USE_FLAT'] = {'global':False, 'order':False, 'nor':False}

76
77
78
79
80
81
82
83
84
85
        if docopt_args['--s1d'] == 'norm':
            CONFIG['S1D'] = True
            CONFIG['S1D_NORM'] = True
        elif docopt_args['--s1d'] == 'no':
            CONFIG['S1D'] = False
            CONFIG['S1D_NORM'] = False
        else:
            CONFIG['S1D'] = True
            CONFIG['S1D_NORM'] = False

Monica Rainer's avatar
Monica Rainer committed
86
87
        if docopt_args['--group']:
            CONFIG['EXTDEFAULT'] = CONFIG['EXTAVG']
88

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
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
        maskc = ''.join(('GIANOB_MASKC_',CONFIG['DATE'],'.fits'))
        CONFIG['MASK_C'] = os.path.join(CONFIG['RES_DIR'], maskc)

        CONFIG['DB_OFFLINE'] = ''.join(('db_',CONFIG['DATE'],'_offline.db'))
        CONFIG['DB_OFFLINE_PATH'] = os.path.join(CONFIG['WEBUI_DB_DIR'], CONFIG['DB_OFFLINE'])
        CONFIG['DB_NIGHT'] = CONFIG['DB_OFFLINE']
        CONFIG['DB_NIGHT_PATH'] = CONFIG['DB_OFFLINE_PATH']


    # second argument: how to query the calibration database
    # to be set if the the user wants to reduce the night using 
    # another night's calibrations
    if docopt_args['<calib_date>']:
        CONFIG['DATE'] = docopt_args['<calib_date>']



    # remove the mask with the order position (if it exists)
    # it will be re-build with the correct flat-field
    try:
        os.remove(CONFIG['MASK_C'])
    except:
        pass

    # Create the reduction directory
    try:
        os.mkdir(CONFIG['BASE_RED_DIR'])
    except OSError:
        pass

    if CONFIG['OFFLINE']:
        try:
            os.mkdir(CONFIG['OFFLINE_DIR'])
        except OSError:
            pass

    try:
        os.mkdir(CONFIG['RED_DIR'])
    except OSError:
        pass

    try:
        os.mkdir(CONFIG['RED_CALIB'])
        os.mkdir(CONFIG['RED_STR'])
    except OSError:
        pass


    # Create the calibration directory tree
    try:
        os.mkdir(CONFIG['BASE_CALIB_DIR'])
    except OSError:
        pass

    try:
        os.mkdir(CONFIG['CALIB_DIR'])
    except OSError:
        pass


    # initialize logger
    drslogger = DrsLogger()

    # Databases online/offline

    dbcalib = db.create_db_calib()

    if CONFIG['OFFLINE']:
        dbramps = False
        try:
            os.remove(CONFIG['DB_NIGHT_PATH'])
        except:
            pass
    else:
        dbramps = db.connect_db_ramp()

    dbnight = db.create_db_night()

    if not os.path.exists(CONFIG['RAW_DIR']):
        drslogger.log('The RAW directory %s does not exist. GOFIO will now close down.' % CONFIG['RAW_DIR'])
        drslogger.log('Pipeline stopped.')
        dbcalib.close()
        if not CONFIG['OFFLINE']:
            dbramps.close()
            dbnight.close()
        sys.exit(0)

    rawlists = {CONFIG['DARK']:[],CONFIG['FLAT']:[],CONFIG['WCAL_UNE']:[],CONFIG['WCAL_FP']:[],CONFIG['SCIENCE']:[]}

    # store the information on what the pipeline is working on (dark, flat, ...) and which science group/pair
    working = 0
    group = {}
    stop = False

    # --------------------------------
    #     End initializing GOFIO
    # --------------------------------

    return CONFIG, rawlists, dbcalib, working, group, stop, drslogger, dbnight, dbramps



# data reduction
def GianoBreduce(rawfits,rawlists,dbcalib,working,group,do_calib,stop,drslogger, dbnight):

    if stop:
        try:
            raw = rawfiles.GBCheckRawFiles(None,None,None,None,None)
            group = raw.group
            working = raw.working
            if working == CONFIG['SCIENCE']:
                if group['nodstare'] == CONFIG['NODVALUE'] and group['pair']:
                    rawlists[CONFIG['SCIENCE']].pop()
                if group:
                    drslogger.log('Reducing pending frames.')
                    print 'Press Ctrl-C again to stop the pipeline now.'
                    raw.command[group['nodstare']] = 'incomplete_group'
            elif working:
                drslogger.log('Reducing pending %s frames.' % working)
                print 'Press Ctrl-C again to stop the pipeline now.'
                raw.command[working] = True
            else:
                return

        except KeyboardInterrupt:
            drslogger.log('Pipeline stopped.')
            sys.exit(0)

# check raw file and insert in the correct list

    else:
220
221
222
223
224
225
226
        if rawfits:
            drslogger.log('Checking the FITS file ' + str(os.path.basename(rawfits)))
            raw = rawfiles.GBCheckRawFiles(rawfits,rawlists,working,group,do_calib)
            raw.check_raw_file()
            working = raw.working
            group = raw.group
            go = raw.go
Monica Rainer's avatar
Monica Rainer committed
227
        #do_calib = raw.do_calib
228
229
230
231
        else:
            raw = rawfiles.GBCheckRawFiles(rawfits,rawlists,working,group,do_calib)
            raw.command[CONFIG['STAREVALUE']] = 'incomplete_group'
            go = raw.go
Monica Rainer's avatar
Monica Rainer committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

    for message in raw.messages:
        drslogger.log(message)
    #print group
# see if the previous function passed a command and execute it
    if raw.command[CONFIG['DARK']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** DARK FRAMES *** ')
        stamp = time.time()
        darks = darkframes.GBDarks(rawlists[CONFIG['DARK']],dbcalib)
        darks.process()
        for message in darks.messages:
            drslogger.log(message)

        db.insert_calib(dbnight, 'DARK', darks.darks, darks.quality, stamp)

        rawlists[CONFIG['DARK']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['FLAT']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FLAT-FIELD FRAMES *** ')
        stamp = time.time()
        flats = flatframes.GBFlats(rawlists[CONFIG['FLAT']],dbcalib)
        flats.process()
        for message in flats.messages:
            drslogger.log(message)

        db.insert_calib(dbnight, 'FLAT', flats.flats, flats.quality, stamp)

        rawlists[CONFIG['FLAT']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_UNE']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** UNE LAMP FRAMES *** ')
        stamp = time.time()
        wls = wlframes.GBWls(rawlists[CONFIG['WCAL_UNE']],dbcalib)
        wls.une_process()
        for message in wls.messages:
            drslogger.log(message)

        db.insert_calib(dbnight, 'WCAL_UNE', wls.wls, wls.quality, stamp)

        rawlists[CONFIG['WCAL_UNE']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_FP']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FP LAMP FRAMES *** ')
        stamp = time.time()
        fps = wlframes.GBWls(rawlists[CONFIG['WCAL_FP']],dbcalib)
        fps.fp_process()
        for message in fps.messages:
            drslogger.log(message)

        db.insert_calib(dbnight, 'WCAL_FP', fps.wls, fps.quality, stamp)

        rawlists[CONFIG['WCAL_FP']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['NODVALUE']] == 'pair':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING PAIR *** ')
        t1 = time.time()
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        nods.pair_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'pair':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE PAIR *** ')
        t1 = time.time()
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        stares.pair_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')


    elif raw.command[CONFIG['NODVALUE']] == 'group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING GROUP *** ')
        t1 = time.time()
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        nods.group_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE GROUP *** ')
        t1 = time.time()
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        stares.group_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['NODVALUE']] == 'incomplete_group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING INCOMPLETE GROUP *** ')
        t1 = time.time()
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        nods.ingroup_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'incomplete_group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE INCOMPLETE GROUP *** ')
        t1 = time.time()
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
        stares.ingroup_process()
        for message in stares.messages:
            drslogger.log(message) 
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))

        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')
    else:
        pass

    if stop:
        return

    #print group
    return working, group, go, do_calib, rawlists