initexit.py 22.7 KB
Newer Older
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
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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#!/usr/bin/env python
# da_initexit.py

"""
Author : peters 

Revision History:
File created on 13 May 2009.

"""

needed_da_items=[
    'time.start',
    'time.finish',
    'time.nlag',
    'time.cycle',
    'dir.da_run',
    'forecast.model',
    'forecast.nmembers',
    'forecast.model.rc',
    'da.platform',
    'da.system']

# only needed in an earlier implemented where each substep was a separate job
# validprocesses = ['start','done','samplestate','advance','invert']

import logging
import os
import sys
import shutil
import datetime
import da.tools.rc as rc



class CycleControl(dict):
    """
    Testing
    =======
    """

    def __init__(self,opts,args):
        """
        Initialization occurs from passed options and arguments to the job control script.
        """

        self.LoadRc(args['rc'])
        self.ValidateRC()
        self.opts = opts

        # Add some useful variables to the rc-file dictionary

        self['jobrcfilename']    = self.RcFileName
        self['dir.da_submit']    = os.getcwd()
        self['da.crash.recover'] = '-r' in opts
        self['verbose']          = '-v' in opts
        self.DaSystem            = None # to be filled later


    def __str__(self):
        """
        String representation of a CycleControl object
        """

        msg = "==============================================================="    ; print msg
        msg = "DA Cycle rc-file is %s" % self.RcFileName                                ; print msg
        msg = "DA Cycle run directory is %s" % self['dir.da_run']           ; print msg
        msg = "DA Cycle inverse system is %s" % self['da.system']           ; print msg
        msg = "DA Cycle forecast model is %s" % self['forecast.model']      ; print msg
        msg = "==============================================================="    ; print msg

        return ""


    def LoadRc(self,RcFileName):
        """ 
        This method loads a DA Cycle rc-file with settings for this simulation 
        """

        rcdata = rc.read(RcFileName)
        for k,v in rcdata.iteritems():
            self[k] = v
        self.RcFileName     = RcFileName
        self.DaRcLoaded    = True

        msg                 = 'DA Cycle rc-file (%s) loaded successfully'%self.RcFileName ; logging.info(msg)

        return True


    def ValidateRC(self):
        """ 
        Validate the contents of the rc-file given a dictionary of required keys
        """
        from da.tools.general import ToDatetime

        for k,v in self.iteritems():
            if v == 'True' : self[k] = True
            if v == 'False': self[k] = False
            if 'date' in k : self[k] = ToDatetime(v)
            if 'time.start' in k : 
                self[k] = ToDatetime(v)
            if 'time.end' in k : 
                self[k] = ToDatetime(v)
            if 'time.finish' in k : 
                self[k] = ToDatetime(v)

        for key in needed_da_items:

            if not self.has_key(key):
                status,msg = ( False,'Missing a required value in rc-file : %s' % key)
                logging.error(msg)
                raise IOError,msg

        status,msg = ( True,'DA Cycle settings have been validated succesfully' )  ; logging.debug(msg)

        return None

    def ParseTimes(self):
        """ 
        Parse time related parameters into datetime objects for later use 
        """
        from da.tools.general import AdvanceTime

        startdate = self['time.start']
        finaldate = self['time.finish']                  

        if finaldate <= startdate:
            msg   = 'The start date (%s) is not greater than the end date (%s), please revise'%(startdate.strftime('%Y%m%d'),finaldate.strftime('%Y%m%d')) 
            logging.error(msg)
            raise ValueError
        #
        cyclelength = self['time.cycle']                 # get time step

# Determine end date

        if cyclelength == 'infinite':
            enddate = finaldate
        else:
            enddate = AdvanceTime(startdate,cyclelength)

        #
        if enddate > finaldate:  # do not run beyon finaldate
            enddate = finaldate

        self['time.start']   = startdate
        self['time.end']     = enddate
        self['time.finish']  = finaldate
        self['cyclelength']  = cyclelength

        msg = "==============================================================="    ; logging.info(msg)
        msg = "DA Cycle start date is %s"   % startdate.strftime('%Y-%m-%d %H:%M')      ; logging.info(msg)
        msg = "DA Cycle end   date is %s"   % enddate.strftime('%Y-%m-%d %H:%M')        ; logging.info(msg)
        msg = "DA Cycle final date is %s"   % finaldate.strftime('%Y-%m-%d %H:%M')      ; logging.info(msg)
        msg = "DA Cycle cycle length is %s" % cyclelength                               ; logging.info(msg)
        msg = "DA Cycle restart is %s"      % str(self['time.restart'])     ; logging.info(msg)
        msg = "==============================================================="    ; logging.info(msg)

        return None

    def RandomSeed(self,action='read'):
        """ Get the randomseed and save it, or read the random seed and set it"""
        import cPickle
        import numpy as np

        filename = os.path.join(self['dir.save'],'randomseed.pickle')

        if action == 'write':
            f        = open(filename,'wb')
            seed     = np.random.get_state()
            dummy    = cPickle.dump (seed,f,-1)
            dummy    = f.close()

            msg      = "Saved the random seed generator values to file"

        if action == 'read':
            f        = open(filename,'rb')
            seed     = cPickle.load(f)
            dummy    = np.random.set_state(seed)
            dummy    = f.close()

            msg      = "Retrieved the random seed generator values from file"

        logging.info(msg)

        return None

    def Initialize(self):
        """ Determine how to proceed with this cycle: 
        
            (a) recover from crash : get the save data from the one-ago folder and replace the da_runtime variables with those from the save dir
            (b) restart cycle      : use latest da_runtime variables from the exec dir
            (c) fresh start        : set up the required file structure for this simulation
        """        

#
# case 1: A recover from a previous crash, this is signaled by flag "-r"
#
        if self['da.crash.recover']:

            msg   = "Recovering simulation from data in: %s" % self['dir.da_run']  ; logging.info(msg)

            dummy = self.SetupFileStructure()

            dummy = self.RecoverRun()

            dummy = self.RandomSeed('read')
#
# case 2: A continuation, this is signaled by rc-item time.restart = True
#
        elif self['time.restart']:

            msg   = "Restarting filter from previous step"  ; logging.info(msg)

            dummy = self.SetupFileStructure()

            dummy = self.RandomSeed('read')
#
# case 3: A fresh start, this is signaled by rc-item time.restart = False
#
        elif not self['time.restart']:
            msg   = "First time step in filter sequence"   ; logging.info(msg)

            dummy = self.SetupFileStructure()

            # expand jobrcfilename to include exec dir from now on.

            self['jobrcfilename'] = os.path.join(self['dir.exec'],self['jobrcfilename'])


        self.ParseTimes()
        self.WriteRC(self['jobrcfilename'])

        return None


    def SetupFileStructure(self):
        """ 
        Create file structure needed for data assimilation system.
            In principle this looks like:

                ${da_rundir}
                ${da_rundir}/input
                ${da_rundir}/output
                ${da_rundir}/exec
                ${da_rundir}/diagnostics
                ${da_rundir}/analysis
                ${da_rundir}/jobs
                ${da_rundir}/save
                ${da_rundir}/save/one-ago
                ${da_rundir}/save/two-ago

            Note that the exec dir will actually be a simlink to the directory where
            the SIBCASA or model executable lives. This directory is passed through
            the da.rc file. The observation input files will be placed in the exec dir,
            and the resulting simulated values will be retrieved from there as well.
        """
        from da.tools.general import CreateDirs

# Create the run directory for this DA job, including I/O structure

        filtertime  = self['time.start'].strftime('%Y%m%d')

        self['dir.exec']        = os.path.join(self['dir.da_run'],'exec')
        self['dir.input']       = os.path.join(self['dir.da_run'],'input')
        self['dir.output']      = os.path.join(self['dir.da_run'],'output',filtertime)
        self['dir.diagnostics'] = os.path.join(self['dir.da_run'],'diagnostics')
        self['dir.analysis']    = os.path.join(self['dir.da_run'],'analysis')
        self['dir.jobs']        = os.path.join(self['dir.da_run'],'jobs')
        self['dir.save']        = os.path.join(self['dir.da_run'],'save')

        CreateDirs(self['dir.da_run'])
        CreateDirs(os.path.join(self['dir.exec']))
        CreateDirs(os.path.join(self['dir.input']))
        CreateDirs(os.path.join(self['dir.output']))
        CreateDirs(os.path.join(self['dir.diagnostics']))
        CreateDirs(os.path.join(self['dir.analysis']))
        CreateDirs(os.path.join(self['dir.jobs']))
        CreateDirs(os.path.join(self['dir.save']))
        CreateDirs(os.path.join(self['dir.save'],'one-ago'))
        CreateDirs(os.path.join(self['dir.save'],'two-ago'))

        msg = 'Succesfully created the file structure for the assimilation job'  ; logging.info(msg)


    def RecoverRun(self):
        """Prepare a recovery from a crashed run. This consists of: 
        
                - copying all data from the save/one-ago folder,
                - replacing all rc-file items with those from da_runtime.rc 
                - resetting the seed of the random number generator to the value it had before the crash
                
        """

        # Move all data from the save/one-ago directory to the save/current directory

        dummy = self.MoveSaveData(io_option='restore',save_option='full',filter=[])

        # Replace rc-items with those from the crashed run last rc-file

        file_rc_rec = os.path.join(self['dir.save'],'da_runtime.rc')
        rc_rec      = rc.read(file_rc_rec)

        for k,v in rc_rec.iteritems():
            self[k] = v

        self.ValidateRC()

        msg         = "Replaced rc-items.... "                                        ; logging.debug(msg)
        msg         = "Next cycle start date is %s" % self['time.start']  ; logging.debug(msg)

        return None

    def Finalize(self):
        """
        Finalize the da cycle, this means writing the save data and rc-files for the next run
        """

        dummy = self.RandomSeed('write')
        dummy = self.WriteNewRCfile()
        dummy = self.CollectSaveData()
        dummy = self.MoveSaveData(io_option='store',save_option='full')
        dummy = self.SubmitNextCycle()

    def CollectSaveData(self):
        """ Collect files needed for the restart of this cycle in case of a crash, or for the continuation of the next cycle. 
            All files needded are written to the save/ directory.
            Currently, the following files are included

            -) The randomseed.pickle file, also already in the save directory
            -) The da_runtime.rc file
            -) The savestate.yyyymmdd.nc file
            -) ...

            Note that we assume that the transport model restart files are directly written to the save/ directory and do not need to be collected

        """

        filtertime  = self['time.start'].strftime('%Y%m%d')

        file1       = os.path.join(self['dir.exec'],'da_runtime.rc')
        file2       = os.path.join(self['dir.output'],'savestate.nc')

        FilesToSave = [file1,file2]

        targetdir   = os.path.join(self['dir.save'])

        msg         = "Collecting the required restart/save data"                                 ; logging.info(msg)
        msg         = "           to   directory: %s " % targetdir                                ; logging.debug(msg)

        for file in FilesToSave:

            msg         = "           [copy] .... %s " % file                                     ; logging.debug(msg)
            dummy       = shutil.copy(file,file.replace(os.path.split(file)[0],targetdir) )


    def MoveSaveData(self, io_option='restore', save_option='partial',filter=[]):
        """ Store or restore model state to/from a temporary directory. Two save_option options are available:

            (1) save_option = 'partial'  : Save the background concentration fields only, to use for a later advance of the background
            (2) save_option = 'full'     : Save all restart data, to use for a next cycle

            While also two IO options are available:

            (1) io_option = restore    : Get data from a directory
            (2) io_option = store      : Save data to a directory

            In case of a 'store' command the target folder is re-created so that the contents are empty to begin with.

            There is currently room for the specific sub-models to also add save data to the mix. This is done through a 
            forecast.model dependend import statement, followed by a call to function:

            model.MoveSaveData(**args)

        """
        from da.tools.general import CreateDirs

        if io_option not in ['store','restore']:
            raise ValueError,'Invalid option specified for io_option (%s)' % io_option
        if save_option not in ['partial','full']:
            raise ValueError,'Invalid option specified for save_option (%s)' % save_option


        savedir     = os.path.join(self['dir.save'])
        oneagodir   = os.path.join(self['dir.save'],'one-ago')
        tempdir     = os.path.join(self['dir.save'],'tmp')


        if save_option == 'partial':   # save background data to tmp dir

            if io_option == 'store':

                targetdir = tempdir
                sourcedir = savedir

            elif io_option == 'restore':

                sourcedir = tempdir
                targetdir = savedir

        elif save_option == 'full':   # move all save data to one-ago dir

            if io_option == 'store':

                targetdir = oneagodir
                sourcedir = savedir

            elif io_option == 'restore':

                sourcedir = oneagodir
                targetdir = savedir

# If "store" is requested, recreate target dir, cleaning the contents 

        if io_option == 'store':
            CreateDirs(os.path.join(targetdir),forceclean=True)

        msg         = "Performing a %s %s of data" % (save_option,io_option)                      ; logging.debug(msg)
        msg         = "           from directory: %s " % sourcedir                                ; logging.debug(msg)
        msg         = "           to   directory: %s " % targetdir                                ; logging.debug(msg)
        msg         = "           with filter   : %s " % filter                                   ; logging.debug(msg)


        for file in os.listdir(sourcedir):

            file = os.path.join(sourcedir,file)

            if os.path.isdir(file): # skip dirs
                skip = True
            elif filter == []:      # copy all
                skip= False        
            else:                   # check filter
                skip = True         # default skip
                for f in filter:
                    if f in file: 
                        skip = False # unless in filter
                        break
                
            if skip: 
                msg         = "           [skip] .... %s " % file                                     ; logging.debug(msg)
                continue    


            if io_option == 'store' and save_option == 'full':
                #msg         = "           [move] .... %s " % file                                                ; logging.debug(msg)
                #dummy       = shutil.move(file,file.replace(sourcedir,targetdir) )
                msg         = "           [copy] .... %s " % file                                                ; logging.debug(msg)
                dummy       = shutil.copy(file,file.replace(sourcedir,targetdir) )

            else:        
                msg         = "           [copy] .... %s " % file                                                ; logging.debug(msg)
                dummy       = shutil.copy(file,file.replace(sourcedir,targetdir) )

#
    def WriteNewRCfile(self):
        """ Write the rc-file for the next DA cycle. Note that the start time for the next cycle is the end time of this one, while 
            the end time for the next cycle is the current end time + one cycle length. The resulting rc-file is written to:
            
            (1) to the dir.exec so that it can be used when resubmitting the next cycle
            
        """
        from da.tools.general import AdvanceTime

        # These first two lines advance the filter time for the next cycle

        self['time.start']        = self['time.end']
        self['time.end']          = AdvanceTime(self['time.end'],self['cyclelength'])

        # The rest is info needed for a system restart

        self['time.restart']     = True
        #self['time.start']       = self['time.start'].strftime('%Y-%m-%d %H:%M:%S')
        #self['time.finish']      = self['time.finish'].strftime('%Y-%m-%d %H:%M:%S')

        fname                                = os.path.join(self['dir.exec'],'da_runtime.rc')
        self['da.restart.fname'] = fname
        dummy                                = rc.write(fname,self)

        msg = 'Wrote new da_runtime.rc (%s)'%fname ; logging.debug(msg)


    def WriteRC(self,fname):
        """ Write RC file after each process to reflect updated info """

        dummy  = rc.write(fname,self)
        msg    = 'Wrote expanded rc-file (%s)'%(fname) ; logging.debug(msg)
        return None

    def SubmitNextCycle(self):
        """ 
        Submit next job in cycle, if needed. The end date is held against the final date. A subprocess is called that 
        submits the next job, without waiting for its result so this cycle can finish and exit. 
        """
        import subprocess
        import os


        DaPlatForm = self.DaPlatForm

        if self['time.start'] < self['time.finish']:

            jobparams               = {'jobname':'das','jobaccount':'co2','jobnodes':'nserial 1','jobtime':'00:30:00','jobshell':'/bin/sh'}
            template                = DaPlatForm.GetJobTemplate(jobparams)
            template                += 'cd %s\n'%os.getcwd()
            template                += './das.py rc=%s'% self['da.restart.fname']

            cd                      = self['time.end'].strftime('%Y%m%d')
            jobfile                 = DaPlatForm.WriteJob(self,template,'cycle.%s.das'%cd)
            jobid                   = DaPlatForm.SubmitJob(jobfile) 
        else:
            logging.info('Final date reached, no new cycle started')

        return None

    def SubmitSubStep(self,stepname):
        """ submit the next substep of a DA cycle"""
        import subprocess
        import os
        from string import join


        DaPlatForm = self.DaPlatForm

        jobparams               = {'jobname':'das.%s'%stepname}
        template                = DaPlatForm.GetJobTemplate(jobparams)
        template                += 'cd %s\n'%os.getcwd()
        template                += './das.py rc=%s process=%s %s' % (self['jobrcfilename'],stepname,join(self.opts,''),) 
        jobfile                 = DaPlatForm.WriteJob(self,template,stepname)
        jobid                   = DaPlatForm.SubmitJob(jobfile) 

        return None


def StartLogger():
    """ start the logging of messages to screen"""

# start the logging basic configuration by setting up a log file

    logging.basicConfig(level    = logging.INFO,
                        format   = ' [%(levelname)-7s] (%(asctime)s) py-%(module)-20s : %(message)s',
                        datefmt  = '%Y-%m-%d %H:%M:%S')

def ParseOptions():
    """ Function parses options from the command line and returns the arguments as a dictionary"""
    import getopt
    import sys

# Parse keywords, the only option accepted so far is the "-h" flag for help

    opts=[]
    args=[]
    try:                                
        opts, args = getopt.gnu_getopt(sys.argv[1:], "-hrv")
    except getopt.GetoptError, msg:           
        logging.error('%s'%msg)
        sys.exit(2)      

    for options in opts:
        options=options[0].lower()
        if options == '-h':
            print ""
            print helptext
            sys.exit(2)      
        if options == '-r':
            logging.info('-r flag specified on command line: recovering from crash')
        if options == '-v':
            logging.info('-v flag specified on command line: extra verbose output')
            dummy  = logging.root.setLevel(logging.DEBUG)

# Parse arguments and return as dictionary

    arguments={}
    for item in args:
        #item=item.lower()

# Catch arguments that are passed not in "key=value" format

        if '=' in item:
            key, arg = item.split('=')
        else:
            logging.error('%s'%'Argument passed without description (%s)' % item)
            raise getopt.GetoptError,arg

        arguments[key]=arg

    if opts: opts=opts[0]

    return opts, arguments

def ValidateOptsArgs(opts,args):
    """ Validate the options and arguments passed from the command line before starting the cycle """

    if not args.has_key("rc"):
        msg = "There is no rc-file specified on the command line. Please use rc=yourfile.rc"   ; logging.error(msg)
        raise IOError,msg
    elif not os.path.exists(args['rc']):
        msg = "The specified rc-file (%s) does not exist " % args['rc'] ;  logging.error(msg)
        raise IOError,msg

    # WP not needed anymore
    #if not args.has_key('process'):
    #    msg = "There is no process specified on the command line, assuming process=Start"   ; logging.info(msg)
    #    args['process'] = 'start'
    #if args['process'].lower() not in validprocesses:
    #    msg = "The specified process (%s) is not valid"%args['process']   ; logging.error(msg)
    #    raise IOError,msg

    return opts,args

def CleanUpCycle(DaCycle):
    """
    Move files, clean up rundir after a cycle has finished
    """

    # move log file to rundir/jobs
    jobdir      = os.path.join(DaCycle['dir.da_run'],"jobs")
    logfile     = 'das.o%s'%DaCycle.DaPlatForm.GetMyID()

    if os.path.exists(logfile):
        joblogfile  = os.path.join(jobdir,'cycle.%s.log'%DaCycle['time.start'].strftime('%Y%m%d')) 
        dummy       = shutil.move(logfile,joblogfile)
        msg         = "....Moved %s to %s"%(logfile,joblogfile)   ; logging.debug(msg)

        msg = "The complete log file is now at: %s"%(joblogfile)   ; logging.info(msg)


if __name__ == "__main__":
    pass