gofioDRS.py 14.4 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
    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
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
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()
Monica Rainer's avatar
Monica Rainer committed
88
89
90

# Databases online/offline

Monica Rainer's avatar
Monica Rainer committed
91
92
dbcalib = db.create_db_calib()

Monica Rainer's avatar
Monica Rainer committed
93
94
95
96
97
98
if CONFIG['OFFLINE']:
    try:
        os.remove(CONFIG['DB_NIGHT_PATH'])
    except:
        pass
else:
Monica Rainer's avatar
Monica Rainer committed
99
    dbramps = db.connect_db_ramp()
Monica Rainer's avatar
Monica Rainer committed
100
101

dbnight = db.create_db_night()
Monica Rainer's avatar
Monica Rainer committed
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


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)
Monica Rainer's avatar
Monica Rainer committed
165
166
167
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['DARK']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
168
169
170
171
172
173
174
175
176
177
178
        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)
Monica Rainer's avatar
Monica Rainer committed
179
180
181
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['FLAT']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
182
183
184
185
186
187
188
189
190
191
192
        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)
Monica Rainer's avatar
Monica Rainer committed
193
194
195
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['WCAL_UNE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
196
197
198
199
200
201
202
203
204
205
206
        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)
Monica Rainer's avatar
Monica Rainer committed
207
208
209
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['WCAL_FP']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
210
211
212
213
214
215
216
217
        rawlists[CONFIG['WCAL_FP']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['NODVALUE']] == 'pair':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING PAIR *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
218
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
219
220
221
222
223
        nods.pair_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
224
225
226
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
227
228
229
230
231
232
233
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'pair':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE PAIR *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
234
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
235
236
237
238
239
        stares.pair_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
240
241
242
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
243
244
245
246
247
248
249
250
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')


    elif raw.command[CONFIG['NODVALUE']] == 'group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING GROUP *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
251
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
252
253
254
255
256
        nods.group_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
257
258
259
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
260
261
262
263
264
265
266
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE GROUP *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
267
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
268
269
270
271
272
        stares.group_process()
        for message in stares.messages:
            drslogger.log(message)
        t2 = time.time()
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
273
274
275
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
276
277
278
279
280
281
282
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['NODVALUE']] == 'incomplete_group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** NODDING INCOMPLETE GROUP *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
283
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
284
285
286
287
288
        nods.ingroup_process()
        for message in nods.messages:
            drslogger.log(message)
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
289
290
291
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
292
293
294
295
296
297
298
        rawlists[CONFIG['SCIENCE']][:] = []
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['STAREVALUE']] == 'incomplete_group':
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** STARE INCOMPLETE GROUP *** ')
        t1 = time.time()
Monica Rainer's avatar
Monica Rainer committed
299
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
300
301
302
303
304
        stares.ingroup_process()
        for message in stares.messages:
            drslogger.log(message) 
        t2 = time.time()   
        drslogger.log('  *** Reduction: %s s ***' % (str(round((t2-t1),2)), ))
Monica Rainer's avatar
Monica Rainer committed
305
306
307
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        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']

324
325
326
327
328
329
330
    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()
331
        sys.exit(0)
332

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

    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)
362
363
                    #raws.pop(0)

Monica Rainer's avatar
Monica Rainer committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
                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)

378
379
380
381
382
383
            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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

    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
399
400
        try: os.remove(CONFIG['MASK_C'])
        except: pass
Monica Rainer's avatar
Monica Rainer committed
401
402
403
404
405
        drslogger.log('Pipeline stopped.')
        dbcalib.close()
        if not CONFIG['OFFLINE']:
            dbramps.close()
            dbnight.close()
406
        sys.exit(0)
Monica Rainer's avatar
Monica Rainer committed
407
408
409
410
411
412
413
414
        

    observer.join()