gofioDRS.py 18.7 KB
Newer Older
Monica Rainer's avatar
Monica Rainer committed
1
"""
Monica Rainer's avatar
Monica Rainer committed
2
GOFIO DRS v1.1.0
Monica Rainer's avatar
Monica Rainer committed
3
Written by Monica Rainer
Monica Rainer's avatar
Monica Rainer committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Usage:
    gofioDRS.py -h
    gofioDRS.py [-g=<gofio_config>]
    gofioDRS.py <date> [--dark --flat --une --fp --only_calib --use_flat=<flag>]
    gofioDRS.py <date> <calib_date> [--dark --flat --une --fp --only_calib --use_flat=<flag>]

Options:
    -h,--help           : show this screen
    -g,--cfg            : path of the configuration file (optional)
    date                : date to be reduced, no configuration file possible (always first input)
    calib_date          : calibration date to be used (always second input)
    --dark              : darks are reduced
    --flat              : flats are reduced
    --une               : U-Ne lamps are reduced
    --fp                : FP lamps are reduced
    --only_calib        : only calibration are reduced, no science images
21
    --use_flat=<flag>   : flat-field is removed, options are global/order/nor/none [Default: order]
Monica Rainer's avatar
Monica Rainer committed
22

Monica Rainer's avatar
Monica Rainer committed
23
24
25
26
"""

import os, glob, sys, time

Monica Rainer's avatar
Monica Rainer committed
27
28
29
from docopt import docopt

from drslib.config import CONFIG, read_usr_config
Monica Rainer's avatar
Monica Rainer committed
30
31
from drslib.logger import DrsLogger
#from logger.logger import DrsLogger
Monica Rainer's avatar
Monica Rainer committed
32
33
34
35
36
37
38

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

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
72
73

# read docopt_arg and act accordingly

docopt_args = docopt(__doc__)
#print docopt_args

if docopt_args['--cfg']:
    try:
        USRCONFIG = read_usr_config(docopt_args['-g'])
    except:
        try:
            USRCONFIG = read_usr_config(docopt_args['--cfg'])
        except:
            USRCONFIG = {}
            USRCONFIG['OFFLINE'] = False


    if USRCONFIG['OFFLINE']:
        for key in USRCONFIG.keys():
            CONFIG[key] = USRCONFIG[key]

        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'])

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

Monica Rainer's avatar
Monica Rainer committed
77
78
if docopt_args['<date>']:
    CONFIG['DATE'] = docopt_args['<date>']
Monica Rainer's avatar
Monica Rainer committed
79
80
81
82
83
84
85
    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')
Monica Rainer's avatar
Monica Rainer committed
86
    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']}
Monica Rainer's avatar
Monica Rainer committed
87
    #CONFIG['DO_CALIB'] = {'dark':True,'flat':True,'une':True,'fp':True,'only_calib':True}
Monica Rainer's avatar
Monica Rainer committed
88
    #CONFIG['DO_CALIB'] = {'dark':False,'flat':False,'une':False,'fp':False,'only_calib':False}
89
    #CONFIG['USE_FLAT'] = {'global':False, 'order':False, 'nor':False} 
Monica Rainer's avatar
Monica Rainer committed
90
91
92
93
94
95
96
97
    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}
98
99
100
101

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

Monica Rainer's avatar
Monica Rainer committed
102
103
104
105
106
    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
107
108
109
110

# 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
Monica Rainer's avatar
Monica Rainer committed
111
112
113
114
115
if docopt_args['<calib_date>']:
    CONFIG['DATE'] = docopt_args['<calib_date>']


#print docopt_args
116
117
118
#print CONFIG['DATE']
#print CONFIG['DO_CALIB']
#print CONFIG['USE_FLAT']
Monica Rainer's avatar
Monica Rainer committed
119
120
121
122
123
124
125
126
127

# 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
128
129
130
131
try:
    os.mkdir(CONFIG['BASE_RED_DIR'])
except OSError:
    pass
Monica Rainer's avatar
Monica Rainer committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

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


151
152
153
154
155
156
# Create the calibration directory tree
try:
    os.mkdir(CONFIG['BASE_CALIB_DIR'])
except OSError:
    pass

Monica Rainer's avatar
Monica Rainer committed
157
158
159
160
161
162
try:
    os.mkdir(CONFIG['CALIB_DIR'])
except OSError:
    pass


163

Monica Rainer's avatar
Monica Rainer committed
164
drslogger = DrsLogger()
Monica Rainer's avatar
Monica Rainer committed
165
166
167

# Databases online/offline

Monica Rainer's avatar
Monica Rainer committed
168
169
dbcalib = db.create_db_calib()

Monica Rainer's avatar
Monica Rainer committed
170
171
172
173
174
175
if CONFIG['OFFLINE']:
    try:
        os.remove(CONFIG['DB_NIGHT_PATH'])
    except:
        pass
else:
Monica Rainer's avatar
Monica Rainer committed
176
    dbramps = db.connect_db_ramp()
Monica Rainer's avatar
Monica Rainer committed
177
178

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


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 *** ')
238
        stamp = time.time()
Monica Rainer's avatar
Monica Rainer committed
239
240
241
242
        darks = darkframes.GBDarks(rawlists[CONFIG['DARK']],dbcalib)
        darks.process()
        for message in darks.messages:
            drslogger.log(message)
243
244
245
246
        #reduced = ','.join(map(os.path.basename,darks.darks))
        #quality = ','.join(map(str,darks.quality))
        #db.insert_calib(dbnight, 'DARK', reduced, quality, stamp)
        db.insert_calib(dbnight, 'DARK', darks.darks, darks.quality, stamp)
Monica Rainer's avatar
Monica Rainer committed
247
248
249
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['DARK']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
250
251
252
253
254
255
256
        rawlists[CONFIG['DARK']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['FLAT']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FLAT-FIELD FRAMES *** ')
257
        stamp = time.time()
Monica Rainer's avatar
Monica Rainer committed
258
259
260
261
        flats = flatframes.GBFlats(rawlists[CONFIG['FLAT']],dbcalib)
        flats.process()
        for message in flats.messages:
            drslogger.log(message)
262
263
264
265
        #reduced = ','.join(map(os.path.basename,flats.flats))
        #quality = ','.join(map(str,flats.quality))
        #db.insert_calib(dbnight, 'FLAT', reduced, quality, stamp)
        db.insert_calib(dbnight, 'FLAT', flats.flats, flats.quality, stamp)
Monica Rainer's avatar
Monica Rainer committed
266
267
268
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['FLAT']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
269
270
271
272
273
274
275
        rawlists[CONFIG['FLAT']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_UNE']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** UNE LAMP FRAMES *** ')
276
        stamp = time.time()
Monica Rainer's avatar
Monica Rainer committed
277
278
279
280
        wls = wlframes.GBWls(rawlists[CONFIG['WCAL_UNE']],dbcalib)
        wls.une_process()
        for message in wls.messages:
            drslogger.log(message)
281
282
283
284
        #reduced = ','.join(map(os.path.basename,wls.wls))
        #quality = ','.join(map(str,wls.quality))
        #db.insert_calib(dbnight, 'WCAL_UNE', reduced, quality, stamp)
        db.insert_calib(dbnight, 'WCAL_UNE', wls.wls, wls.quality, stamp)
Monica Rainer's avatar
Monica Rainer committed
285
286
287
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['WCAL_UNE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
288
289
290
291
292
293
294
        rawlists[CONFIG['WCAL_UNE']][:] = []
        group.clear()
        drslogger.log('----------------------------------------------')

    elif raw.command[CONFIG['WCAL_FP']]:
        drslogger.log('----------------------------------------------')
        drslogger.log(' *** FP LAMP FRAMES *** ')
295
        stamp = time.time()
Monica Rainer's avatar
Monica Rainer committed
296
297
298
299
        fps = wlframes.GBWls(rawlists[CONFIG['WCAL_FP']],dbcalib)
        fps.fp_process()
        for message in fps.messages:
            drslogger.log(message)
300
301
302
303
        #reduced = ','.join(map(os.path.basename,fps.wls))
        #quality = ','.join(map(str,fps.quality))
        #db.insert_calib(dbnight, 'WCAL_FP', reduced, quality, stamp)
        db.insert_calib(dbnight, 'WCAL_FP', fps.wls, fps.quality, stamp)
Monica Rainer's avatar
Monica Rainer committed
304
305
306
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['WCAL_FP']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
307
308
309
310
311
312
313
314
        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
315
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
316
317
318
319
320
        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
321
322
323
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
324
325
326
327
328
329
330
        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
331
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
332
333
334
335
336
        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
337
338
339
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
340
341
342
343
344
345
346
347
        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
348
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
349
350
351
352
353
        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
354
355
356
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
357
358
359
360
361
362
363
        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
364
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
365
366
367
368
369
        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
370
371
372
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
373
374
375
376
377
378
379
        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
380
        nods = nodding.GBNodding(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
381
382
383
384
385
        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
386
387
388
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
389
390
391
392
393
394
395
        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
396
        stares = stare.GBStare(rawlists[CONFIG['SCIENCE']],group,dbcalib,dbnight)
Monica Rainer's avatar
Monica Rainer committed
397
398
399
400
401
        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
402
403
404
        #if not CONFIG['OFFLINE']:
        #    for reduced in rawlists[CONFIG['SCIENCE']]:
        #        db.insert_dbnight(dbnight, reduced)
Monica Rainer's avatar
Monica Rainer committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        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']

421
422
423
424
425
426
427
    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()
428
        sys.exit(0)
429

Monica Rainer's avatar
Monica Rainer committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

    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)
459
460
                    #raws.pop(0)

Monica Rainer's avatar
Monica Rainer committed
461
462
                else:
                    for n in xrange(len(raws)):
463
                        if db.check_night(dbnight,os.path.basename(raws[n])):
Monica Rainer's avatar
Monica Rainer committed
464
465
                            raws.pop(n)
                            break
466
467
                        #elif db.check_raw(dbramps,raws[n]):
                        elif db.check_raw(dbramps,os.path.basename(raws[n])):
Monica Rainer's avatar
Monica Rainer committed
468
469
470
471
472
473
474
475
                            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)

476
477
478
479
480
481
            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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496

    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
497
498
        try: os.remove(CONFIG['MASK_C'])
        except: pass
Monica Rainer's avatar
Monica Rainer committed
499
500
501
502
503
        drslogger.log('Pipeline stopped.')
        dbcalib.close()
        if not CONFIG['OFFLINE']:
            dbramps.close()
            dbnight.close()
504
        sys.exit(0)
Monica Rainer's avatar
Monica Rainer committed
505
506
507
508
509
510
511
512
        

    observer.join()