gofioDRS.py 13.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
"""
GOFIO DRS
Last modified: 2017-03-07
Written by Monica Rainer
"""

import os, glob, sys, time

from drslib.config import CONFIG
from logger.logger import DrsLogger

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

# use watchdog to monitor file creation
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

# first argument: night to be reduced, using the calibration in the database
# to be used at the end of the night, after the calibration lamp has been
# observed and put in the database
try:
    CONFIG['DATE'] = sys.argv[1]
    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':True,'flat':True,'une':True,'fp':True,'only_calib':True}
    CONFIG['DO_CALIB'] = {'dark':False,'flat':False,'une':False,'fp':False,'only_calib':False}
32
33
34
35

    maskc = ''.join(('GIANOB_MASKC_',CONFIG['DATE'],'.fits'))
    CONFIG['MASK_C'] = os.path.join(CONFIG['RES_DIR'], maskc)

Monica Rainer's avatar
Monica Rainer committed
36
37
38
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
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
except:
    pass


# 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
try:
    CONFIG['DATE'] = sys.argv[2]
except:
    pass

# 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

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
try:
    os.mkdir(CONFIG['CALIB_DIR'])
except OSError:
    pass


drslogger = DrsLogger()
dbcalib = db.create_db_calib()

if not CONFIG['OFFLINE']:
    dbramps = db.connect_db_ramp()
    dbnight = db.create_db_night()


do_calib = CONFIG['DO_CALIB']

# watchdog append fits files to the raw list
class UpdateRawList(PatternMatchingEventHandler):
    def process(self, event):
        raws.append(event.src_path)
        drslogger.log('File %s has arrived.' % (event.src_path))

    def on_created(self, event):
        ext = os.path.splitext(event.src_path)[1]
        if ext == '.fts':
            self.process(event)

# data reduction
def GianoBreduce(rawfits,lists,dbcalib,working,group,do_calib,stop):

    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']:
                    lists[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:
        drslogger.log('Checking the FITS file ' + str(os.path.basename(rawfits)))
        raw = rawfiles.GBCheckRawFiles(rawfits,lists,working,group,do_calib)
        raw.check_raw_file()
        working = raw.working
        group = raw.group
        go = raw.go
        #do_calib = raw.do_calib

    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 *** ')
        darks = darkframes.GBDarks(rawlists[CONFIG['DARK']],dbcalib)
        darks.process()
        for message in darks.messages:
            drslogger.log(message)
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['DARK']]:
                db.insert_dbnight(dbnight, reduced)
        rawlists[CONFIG['DARK']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['FLAT']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FLAT-FIELD FRAMES *** ')
        flats = flatframes.GBFlats(rawlists[CONFIG['FLAT']],dbcalib)
        flats.process()
        for message in flats.messages:
            drslogger.log(message)
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['FLAT']]:
                db.insert_dbnight(dbnight, reduced)
        rawlists[CONFIG['FLAT']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_UNE']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** UNE LAMP FRAMES *** ')
        wls = wlframes.GBWls(rawlists[CONFIG['WCAL_UNE']],dbcalib)
        wls.une_process()
        for message in wls.messages:
            drslogger.log(message)
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['WCAL_UNE']]:
                db.insert_dbnight(dbnight, reduced)
        rawlists[CONFIG['WCAL_UNE']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_FP']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FP LAMP FRAMES *** ')
        fps = wlframes.GBWls(rawlists[CONFIG['WCAL_FP']],dbcalib)
        fps.fp_process()
        for message in fps.messages:
            drslogger.log(message)
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['WCAL_FP']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        nods.pair_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        stares.pair_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        nods.group_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        stares.group_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        nods.ingroup_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        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)
        stares.ingroup_process()
        for message in stares.messages:
            drslogger.log(message) 
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
        if not CONFIG['OFFLINE']:
            for reduced in rawlists[CONFIG['SCIENCE']]:
                db.insert_dbnight(dbnight, reduced)
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')
    else:
        pass

    if stop:
        return

    #print group
    return working, group, go, do_calib



if __name__ == "__main__":
    rawdir = CONFIG['RAW_DIR']

310
311
312
313
314
315
316
    if not os.path.exists(rawdir):
        drslogger.log('The RAW directory %s does not exist. GOFIO will now close down.' % rawdir)
        drslogger.log('Pipeline stopped.')
        dbcalib.close()
        if not CONFIG['OFFLINE']:
            dbramps.close()
            dbnight.close()
317
        sys.exit(0)
318

Monica Rainer's avatar
Monica Rainer committed
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

    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


# check if there are already files in RAW_DIR, create list raws in temporal order
    fits = os.path.join(rawdir,"*.fts")
    raws = glob.glob(fits)
    raws.sort()

# use watchdog to check when new files are created
    observer = Observer()
    observer.schedule(UpdateRawList(),rawdir)
    observer.start()

    try:
        while True:
            time.sleep(1)

# the raw files are processed
            while raws:
                if CONFIG['OFFLINE']:
                    working, group, go, do_calib = GianoBreduce(raws[0], rawlists, dbcalib, working, group, do_calib, stop)
                    if go:
                        raws.pop(0)
348
349
                    #raws.pop(0)

Monica Rainer's avatar
Monica Rainer committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
                else:
                    for n in xrange(len(raws)):
                        if db.check_night(dbnight,raws[n]):
                            raws.pop(n)
                            break
                        elif db.check_raw(dbramps,raws[n]):
                            working, group, go, do_calib = GianoBreduce(raws[n], rawlists, dbcalib, working, group, do_calib, stop)
                            if go:
                                raws.pop(n)
                            break

                        else:
                            time.sleep(1)

364
365
366
367
368
369
            if CONFIG['OFFLINE']:
                drslogger.log('No more files to reduce.')
                dbcalib.close()
                try: os.remove(CONFIG['MASK_C'])
                except: pass
                sys.exit(0)
Monica Rainer's avatar
Monica Rainer committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

    except KeyboardInterrupt:

        observer.stop()
        # reduce any file still pending!
        if working:
            drslogger.log('Processing the last pending files (if any).')
            stop = True
            if CONFIG['OFFLINE']:
                GianoBreduce(raws[0], rawlists, dbcalib, working, group, do_calib, stop)
            else:
                for n in xrange(len(raws)):
                    if db.check_raw(dbramps,raws[n]):
                        GianoBreduce(raws[n], rawlists, dbcalib, working, group, do_calib, stop)
                        break
385
386
        try: os.remove(CONFIG['MASK_C'])
        except: pass
Monica Rainer's avatar
Monica Rainer committed
387
388
389
390
391
        drslogger.log('Pipeline stopped.')
        dbcalib.close()
        if not CONFIG['OFFLINE']:
            dbramps.close()
            dbnight.close()
392
        sys.exit(0)
Monica Rainer's avatar
Monica Rainer committed
393
394
395
396
397
398
399
400
        

    observer.join()