initexit.py 28.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
"""CarbonTracker Data Assimilation Shell (CTDAS) Copyright (C) 2017 Wouter Peters. 
Users are recommended to contact the developers (wouter.peters@wur.nl) to receive
updates of the code. See also: http://www.carbontracker.eu. 

This program is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation, 
version 3. This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

You should have received a copy of the GNU General Public License along with this 
program. If not, see <http://www.gnu.org/licenses/>."""
13
14
15
16
#!/usr/bin/env python
# da_initexit.py

"""
Peters, Wouter's avatar
Peters, Wouter committed
17
18
.. module:: initexit
.. moduleauthor:: Wouter Peters 
19
20
21
22

Revision History:
File created on 13 May 2009.

Peters, Wouter's avatar
Peters, Wouter committed
23
The CycleControl class is found in the module :mod:`initexit`. It is derived from the standard python :class:`dictionary` object. It is the only core object of CTDAS that is automatically created in the pipeline, the user (normally) does not need to modify or extend it. The class is created based on options and arguments passes on the command line when submitting your main CTDAS job. 
24
25
26

Valid options are defined in 

27
.. autofunction:: da.tools.initexit.parse_options
28
29
30
31
32
33

With the name of a valid ``rc-file``, the CycleControl object is instantiated and validated. An example rc-file looks
like this:::

    ! Info on the data assimilation cycle

34
35
36
37
38
39
    time.restart        : False                     ! Restart from an existing run T/F
    time.start          : 2000-01-01 00:00:00       ! Start time of first cycle
    time.finish         : 2000-01-08 00:00:00       ! End time of last cycle
    time.cycle          : 7                         ! length of each cycle, 7 means one week
    time.nlag           : 5                         ! number of cycles in one smoother window
    dir.da_run          : ${HOME}/tmp/test_da       ! the run directory for you project
40
41
42

    ! Info on the DA system used

43
44
    da.system           : CarbonTracker             ! an identifier for your inversion system
    da.system.rc        : da/rc/carbontracker.rc    ! the settings needed in your inversion system
45
46
47

    ! Info on the forward model to be used

48
49
50
    da.obsoperator         : TM5                                ! an identifier for your observation operator
    da.obsoperator.rc      : ${HOME}/Modeling/TM5/tm5-ctdas.rc  ! the rc-file needed to run youobservation operator
    da.optimizer.nmembers  : 30                                 ! the number of ensemble members desired in the optimization
51
52
53
54

The most important method of the CycleControl object are listed below:

.. autoclass:: da.tools.initexit.CycleControl 
55
   :members: setup, finalize,  collect_restart_data, move_restart_data, 
56
             submit_next_cycle, setup_file_structure, recover_run, random_seed
57
58
59
60
61
62
63

Two important attributes of the CycleControl object are:
    (1) DaSystem, an instance of a :ref:`dasystem`
    (2) DaPlatForm, an instance of a :ref:`platform`

Other functions in the module initexit that are related to the control of a DA cycle are:

64
65
.. autofunction:: da.tools.initexit.start_logger 
.. autofunction:: da.tools.initexit.validate_opts_args 
66
67


68
"""
karolina's avatar
karolina committed
69
70
71
import logging
import os
import sys
72
import glob
karolina's avatar
karolina committed
73
import shutil
karolina's avatar
karolina committed
74
import copy
75
import getopt
brunner's avatar
brunner committed
76
import pickle
77
import numpy as np
brunner's avatar
brunner committed
78
#from string import join
79

karolina's avatar
karolina committed
80
import da.tools.rc as rc
81
from da.tools.general import create_dirs, to_datetime, advance_time
82

karolina's avatar
karolina committed
83
needed_da_items = [
84
85
86
87
88
    'time.start',
    'time.finish',
    'time.nlag',
    'time.cycle',
    'dir.da_run',
89
90
91
    'da.resources.ncycles_per_job',
    'da.resources.ntasks',
    'da.resources.ntime',
92
93
94
95
96
    'da.system',
    'da.system.rc',
    'da.obsoperator',
    'da.obsoperator.rc',
    'da.optimizer.nmembers']
97
98
99
100
101
102
103

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


class CycleControl(dict):
    """
104
    This object controls the CTDAS system flow and functionality.
105
    """
106
        
karolina's avatar
karolina committed
107
    def __init__(self, opts=[], args={}):
108
        """
Peters, Wouter's avatar
Peters, Wouter committed
109
110
        The CycleControl object is instantiated with a set of options and arguments.
        The list of arguments must contain the name of an existing ``rc-file``. 
111
112
        This rc-file is loaded by method :meth:`~da.tools.initexit.CycleControl.load_rc` and validated
        by :meth:`~da.tools.initexit.CycleControl.validate_rc`
113

Peters, Wouter's avatar
Peters, Wouter committed
114
        Options for the CycleControl consist of accepted command line flags or arguments 
115
        in :func:`~da.tools.initexit.CycleControl.parse_options`
116

117
        """
karolina's avatar
karolina committed
118
119
        rcfile = args['rc']
        self.load_rc(rcfile)
120
        self.validate_rc()
121
122
123
124
        self.opts = opts

        # Add some useful variables to the rc-file dictionary

karolina's avatar
karolina committed
125
        self['jobrcfilename'] = rcfile
karolina's avatar
karolina committed
126
        self['dir.da_submit'] = os.getcwd()
127
        self['da.crash.recover'] = '-r' in opts
128
        self['transition'] = '-t' in opts
karolina's avatar
karolina committed
129
        self['verbose'] = '-v' in opts
130
131
132
        self.dasystem = None # to be filled later
        self.restart_filelist = [] # List of files needed for restart, to be extended later
        self.output_filelist = [] # List of files needed for output, to be extended later
133
134


karolina's avatar
karolina committed
135
    def load_rc(self, rcfilename):
136
137
138
139
        """ 
        This method loads a DA Cycle rc-file with settings for this simulation 
        """

karolina's avatar
karolina committed
140
        rcdata = rc.read(rcfilename)
brunner's avatar
brunner committed
141
        for k, v in rcdata.items():
142
143
            self[k] = v

karolina's avatar
karolina committed
144
145
        logging.info('DA Cycle rc-file (%s) loaded successfully' % rcfilename)
        
146

147
    def validate_rc(self):
148
        """ 
Peters, Wouter's avatar
Peters, Wouter committed
149
150
        Validate the contents of the rc-file given a dictionary of required keys. 
        Currently required keys are :attr:`~da.tools.initexit.needed_da_items`
151
152
        """

brunner's avatar
brunner committed
153
        for k, v in self.items():
karolina's avatar
karolina committed
154
155
156
157
            if v in ['True', 'true', 't', 'T', 'y', 'yes']:
                self[k] = True
            if v in ['False', 'false', 'f', 'F', 'n', 'no']:
                self[k] = False
158
            if 'date' in k : 
159
                self[k] = to_datetime(v)
160
            if k in ['time.start', 'time.end', 'time.finish', 'da.restart.tstamp']:
161
                self[k] = to_datetime(v)
162
        for key in needed_da_items:
brunner's avatar
brunner committed
163
            if key not in self:
karolina's avatar
karolina committed
164
165
166
167
168
169
                msg = 'Missing a required value in rc-file : %s' % key
                logging.error(msg)
                logging.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ')
                logging.error('Please note the update on Dec 02 2011 where rc-file names for DaSystem and ')
                logging.error('are from now on specified in the main rc-file (see da/rc/da.rc for example)')
                logging.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ')
brunner's avatar
brunner committed
170
                raise IOError(msg)
karolina's avatar
karolina committed
171
        logging.debug('DA Cycle settings have been validated succesfully')
172

173
    def parse_times(self):
174
175
176
177
178
179
180
181
        """ 
        Parse time related parameters into datetime objects for later use 
        """

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

        if finaldate <= startdate:
karolina's avatar
karolina committed
182
            logging.error('The start date (%s) is not greater than the end date (%s), please revise' % (startdate.strftime('%Y%m%d'), finaldate.strftime('%Y%m%d'))) 
183
184
185
186
187
188
189
190
            raise ValueError
        cyclelength = self['time.cycle']                 # get time step

# Determine end date

        if cyclelength == 'infinite':
            enddate = finaldate
        else:
191
            enddate = advance_time(startdate, cyclelength)
192

karolina's avatar
karolina committed
193
        dt = enddate - startdate
194

karolina's avatar
karolina committed
195
        if enddate > finaldate:  # do not run beyond finaldate
196
197
            enddate = finaldate

karolina's avatar
karolina committed
198
199
200
201
        self['time.start'] = startdate
        self['time.end'] = enddate
        self['time.finish'] = finaldate
        self['cyclelength'] = dt
202

karolina's avatar
karolina committed
203
204
        logging.info("===============================================================")
        logging.info("DA Cycle start date is %s" % startdate.strftime('%Y-%m-%d %H:%M'))
205
        logging.info("DA Cycle end date is %s" % enddate.strftime('%Y-%m-%d %H:%M'))
karolina's avatar
karolina committed
206
207
208
209
        logging.info("DA Cycle final date is %s" % finaldate.strftime('%Y-%m-%d %H:%M'))  
        logging.info("DA Cycle cycle length is %s" % cyclelength)
        logging.info("DA Cycle restart is %s" % str(self['time.restart']))
        logging.info("===============================================================")
210
211


212
    def set_sample_times(self, lag):
213
214
215
216
217
218
        """
        Set the times over which a sampling interval will loop, depending on 
        the lag. Note that lag falls in the interval [0,nlag-1]
        """

        # Start from cycle times 
karolina's avatar
karolina committed
219
220
        self['time.sample.start'] = copy.deepcopy(self['time.start'])
        self['time.sample.end'] = copy.deepcopy(self['time.end'])
221
222
223
224

        # Now advance depending on lag

        for l in range(lag):
225
            self.advance_sample_times()
226
227


228
    def advance_sample_times(self):
229
230
231
232
        """ 
        Advance sampling start and end time by one cycle interval
        """

233
        days = self['cyclelength'].days                
234

235
236
        self['time.sample.start'] = advance_time(self['time.sample.start'], days)
        self['time.sample.end'] = advance_time(self['time.sample.end'], days)
237
238
    

239
    def advance_cycle_times(self):
240
241
242
        """ 
        Advance cycle start and end time by one cycle interval
        """
243
244
              
        days = self['cyclelength'].days                  
Peters, Wouter's avatar
Peters, Wouter committed
245

246
247
        startdate = advance_time(self['time.start'], days)
        enddate = advance_time(self['time.end'], days)
248

karolina's avatar
karolina committed
249
250
        filtertime = startdate.strftime('%Y%m%d')
        self['dir.output'] = os.path.join(self['dir.da_run'], 'output', filtertime)
251

karolina's avatar
karolina committed
252
253
        self['time.start'] = startdate
        self['time.end'] = enddate
254
255


256
257
258
259
    def write_random_seed(self):
        filename = os.path.join(self['dir.restart'], 'randomseed_%s.pickle' % self['time.start'].strftime('%Y%m%d'))
        f = open(filename, 'wb')
        seed = np.random.get_state()
brunner's avatar
brunner committed
260
        pickle.dump(seed, f, -1)
261
        f.close()
262

263
        logging.info("Saved the random seed generator values to file")
264
265


266
267
    def read_random_seed(self, first=False):
        if first:
268
            filename = self.dasystem['random.seed.init']
269
270
271
272
            logging.info("Initialised random seed from: %s"%filename)
        else: 
            filename = os.path.join(self['dir.restart'], 'randomseed_%s.pickle' % self['da.restart.tstamp'].strftime('%Y%m%d'))
            logging.info("Retrieved the random seed generator values of last cycle from file")
273
        f = open(filename, 'rb')
brunner's avatar
brunner committed
274
        seed = pickle.load(f)
275
276
        np.random.set_state(seed)
        f.close()
277

278

279
    def setup(self):
280
281
282
        """ 
        This method determines how to proceed with the cycle. Three options are implemented:

Peters, Wouter's avatar
Peters, Wouter committed
283
284
285
            1. *Fresh start*  : set up the required file structure for this simulation and start
            2. *Restart*      : use latest da_runtime variables from the exec dir and restart
            3. *Recover*      : restart after crash by getting data from restart/one-ago folder
286
287
288

        The choice that gets executed depends on the presence of 

Peters, Wouter's avatar
Peters, Wouter committed
289
290
            # the ``-r`` option on the command line, this triggers a recover
            # the ``time.restart : True`` option in the da.rc file
291
292

        The latter is automatically set if the filter submits the next cycle at the end of the current one, 
293
        through method :meth:`~da.tools.initexit.CycleControl.submit_next_cycle`.
Peters, Wouter's avatar
Peters, Wouter committed
294

Peters, Wouter's avatar
Peters, Wouter committed
295
        The specific call tree under each scenario is: 
Peters, Wouter's avatar
Peters, Wouter committed
296

Peters, Wouter's avatar
Peters, Wouter committed
297
            1. *Fresh Start*
298
                *  :meth:`~da.tools.initexit.CycleControl.setup_file_structure()`  <- Create directory tree
Peters, Wouter's avatar
Peters, Wouter committed
299
            2. *Restart*
300
301
                *  :meth:`~da.tools.initexit.CycleControl.setup_file_structure()`
                *  :meth:`~da.tools.initexit.CycleControl.random_seed`    <- Read the random seed from file
Peters, Wouter's avatar
Peters, Wouter committed
302
            3. *Recover*
303
304
305
                *  :meth:`~da.tools.initexit.CycleControl.setup_file_structure()`
                *  :meth:`~da.tools.initexit.CycleControl.recover_run()`          <- Recover files from restart/one-ago dir, reset ``time.start``
                *  :meth:`~da.tools.initexit.CycleControl.random_seed` 
Peters, Wouter's avatar
Peters, Wouter committed
306
307
308

        And is always followed by a call to

309
            * parse_times()
Peters, Wouter's avatar
Peters, Wouter committed
310
            * WriteRc('jobfilename')
311
        """        
312
313
314
315
316
317
318
319
        if self['transition']:
            logging.info("Transition of filter from previous step with od meteo from 25 to 34 levels")
            self.setup_file_structure()
            strippedname = os.path.split(self['jobrcfilename'])[-1]
            self['jobrcfilename'] = os.path.join(self['dir.exec'], strippedname)
            self.read_random_seed(False)

        elif self['time.restart']:
karolina's avatar
karolina committed
320
            logging.info("Restarting filter from previous step")
321
            self.setup_file_structure()
322
            strippedname = os.path.split(self['jobrcfilename'])[-1]
karolina's avatar
karolina committed
323
            self['jobrcfilename'] = os.path.join(self['dir.exec'], strippedname)
324
325
            self.read_random_seed(False)

326
        else: #assume that it is a fresh start, change this condition to more specific if crash recover added
karolina's avatar
karolina committed
327
            logging.info("First time step in filter sequence")
328
            self.setup_file_structure()
329
330

            # expand jobrcfilename to include exec dir from now on.
331
332
333
            # First strip current leading path from filename

            strippedname = os.path.split(self['jobrcfilename'])[-1]
karolina's avatar
karolina committed
334
            self['jobrcfilename'] = os.path.join(self['dir.exec'], strippedname)
335

brunner's avatar
brunner committed
336
            if 'extendedregionsfile' in self.dasystem:
brunner's avatar
brunner committed
337
#                shutil.copy(os.path.join(self.dasystem['extendedregionsfile']),os.path.join(self['dir.exec'],'da','analysis','copied_regions_extended.nc')) 
Ingrid Luijkx's avatar
Ingrid Luijkx committed
338
                logging.info('Copied extended regions file to the analysis directory: %s'%os.path.join(self.dasystem['extendedregionsfile'])) 
339
340
341
342
343
344
            #for filename in glob.glob(os.path.join(self['dir.exec'],'da','analysis','*.pickle')):
            #    logging.info('Deleting pickle file %s to make sure the correct regions are used'%os.path.split(filename)[1])
            #    os.remove(filename) 
            #for filename in glob.glob(os.path.join(self['dir.exec'],'*.pickle')):
            #    logging.info('Deleting pickle file %s to make sure the correct regions are used'%os.path.split(filename)[1])
            #    os.remove(filename) 
brunner's avatar
brunner committed
345
            if 'random.seed.init' in self.dasystem:
346
                self.read_random_seed(True)
347

348
        self.parse_times()
349

350
    def setup_file_structure(self):
351
352
        """ 
        Create file structure needed for data assimilation system.
Peters, Wouter's avatar
Peters, Wouter committed
353
354
355
356
357
358
359
360
        In principle this looks like:

            * ``${da_rundir}``
            * ``${da_rundir}/input``
            * ``${da_rundir}/output``
            * ``${da_rundir}/exec``
            * ``${da_rundir}/analysis``
            * ``${da_rundir}/jobs``
361
362
            * ``${da_rundir}/restart/current``
            * ``${da_rundir}/restart/one-ago``
Peters, Wouter's avatar
Peters, Wouter committed
363

364
        .. note:: The exec dir will actually be a simlink to the directory where
365
366
367
                 the observation operator executable lives. This directory is passed through
                 the ``da.rc`` file. 

368
        .. note:: The observation input files will be placed in the exec dir,
369
                 and the resulting simulated values will be retrieved from there as well.
Peters, Wouter's avatar
Peters, Wouter committed
370

371
372
373
374
        """

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

karolina's avatar
karolina committed
375
        filtertime = self['time.start'].strftime('%Y%m%d')
376

karolina's avatar
karolina committed
377
378
379
380
381
382
        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.analysis'] = os.path.join(self['dir.da_run'], 'analysis')
        self['dir.jobs'] = os.path.join(self['dir.da_run'], 'jobs')
        self['dir.restart'] = os.path.join(self['dir.da_run'], 'restart')
383

384
385
386
387
388
389
390
        create_dirs(self['dir.da_run'])
        create_dirs(os.path.join(self['dir.exec']))
        create_dirs(os.path.join(self['dir.input']))
        create_dirs(os.path.join(self['dir.output']))
        create_dirs(os.path.join(self['dir.analysis']))
        create_dirs(os.path.join(self['dir.jobs']))
        create_dirs(os.path.join(self['dir.restart']))
391

karolina's avatar
karolina committed
392
        logging.info('Succesfully created the file structure for the assimilation job')
393

394

395
    def finalize(self):
396
        """
397
        finalize the da cycle, this means writing the save data and rc-files for the next run. 
398
399
400
        The following sequence of actions occur:

            * Write the randomseed to file for reuse in next cycle
Peters, Wouter's avatar
Peters, Wouter committed
401
            * Write a new ``rc-file`` with ``time.restart : True``, and new ``time.start`` and ``time.end``
402
403
404
405
            * Collect all needed data needed for check-pointing (restart from current system state)
            * Move the previous check pointing data out of the way, and replace with current
            * Submit the next cycle

406
        """
407
408
        self.write_random_seed()                              
        self.write_new_rc_file()                              
409
        
410
411
412
        self.collect_restart_data()  # Collect restart data for next cycle into a clean restart/current folder
        self.collect_output()  # Collect restart data for next cycle into a clean restart/current folder
        self.submit_next_cycle()
413

414
    def collect_output(self):
415
        """ Collect files that are part of the requested output for this cycle. This function allows users to add files 
416
417
            to a list, and then the system will copy these to the current cycle's output directory.
            The list of files included is read from the 
418
            attribute "output_filelist" which is a simple list of files that can be appended by other objects/methods that
419
420
421
422
            require output data to be saved.


        """
karolina's avatar
karolina committed
423
        targetdir = os.path.join(self['dir.output'])
424
        create_dirs(targetdir)
425

karolina's avatar
karolina committed
426
427
        logging.info("Collecting the required output data") 
        logging.debug("           to   directory: %s " % targetdir)
428

429
        for file in set(self.output_filelist):
430
431
            if os.path.isdir(file): # skip dirs
                continue
432
            if not os.path.exists(file): # skip dirs
karolina's avatar
karolina committed
433
                logging.warning("           [not found] .... %s " % file)
434
                continue
435

karolina's avatar
karolina committed
436
437
            logging.debug("           [copy] .... %s " % file)
            shutil.copy(file, file.replace(os.path.split(file)[0], targetdir))
438
439
440



441
    def collect_restart_data(self):
442
        """ Collect files needed for the restart of this cycle in case of a crash, or for the continuation of the next cycle. 
443
            All files needed are written to the restart/current directory. The list of files included is read from the 
444
            attribute "restart_filelist" which is a simple list of files that can be appended by other objects/methods that
445
446
            require restart data to be saved.

447
            .. note:: Before collecting the files in the ``restart_filelist``, the restart/current directory will be emptied and
448
                     recreated. This prevents files from accumulating in the restart/current and restart/one-ago folders. It 
449
                     also means that if a file is missing from the ``restart_filelist``, it will not be available for check-pointing
450
451
452
                     if your run crashes or dies!

            Currently, the following files are included:
453

454
                * The ``da_runtime.rc`` file
455
                * The ``randomseed.pickle`` file
456
                * The savestate.nc file
457
                * The files in the ``ObservationOperator.restart_filelist``, i.e., restart data for the transport model
458

459

Peters, Wouter's avatar
Peters, Wouter committed
460
            .. note:: We assume that the restart files for the :ref:`ObservationOperator` 
461
                      reside in a separate folder, i.e, the ObservationOperator does *not* write directly to the CTDAS restart dir!
462
463
464

        """

465
        targetdir = os.path.join(self['dir.restart'])
466

467
        #logging.info("Purging the current restart directory before collecting new data")
468

469
        #create_dirs(targetdir, forceclean=True)
470

karolina's avatar
karolina committed
471
472
        logging.info("Collecting the required restart data")
        logging.debug("           to   directory: %s " % targetdir)
473

474
        for file in set(self.restart_filelist):
475
476
            if os.path.isdir(file): # skip dirs
                continue
477
            if not os.path.exists(file): 
karolina's avatar
karolina committed
478
                logging.warning("           [not found] .... %s " % file)
479
            else:
karolina's avatar
karolina committed
480
481
                logging.debug("           [copy] .... %s " % file)
                shutil.copy(file, file.replace(os.path.split(file)[0], targetdir))
482
483
484
485



#
486
    def write_new_rc_file(self):
487
488
489
490
491
492
        """ Write the rc-file for the next DA cycle. 

            .. note:: 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 the ``dir.exec`` so that it can be used when resubmitting the next cycle
493
494
            
        """
karolina's avatar
karolina committed
495
        
496
        # We make a copy of the current dacycle object, and modify the start + end dates and restart value
497

karolina's avatar
karolina committed
498
499
500
501
        new_dacycle = copy.deepcopy(self)
        new_dacycle['da.restart.tstamp'] = self['time.start']
        new_dacycle.advance_cycle_times()
        new_dacycle['time.restart'] = True
502
        
503
        # Create the name of the rc-file that will hold this new input, and write it
504

505
506
        #fname = os.path.join(self['dir.exec'], 'da_runtime.rc')  # current exec dir holds next rc file
        
karolina's avatar
karolina committed
507
        fname = os.path.join(self['dir.restart'], 'da_runtime_%s.rc' % new_dacycle['time.start'].strftime('%Y%m%d'))#advanced time
508
        
karolina's avatar
karolina committed
509
        rc.write(fname, new_dacycle)
510
        logging.debug('Wrote new da_runtime.rc (%s) to restart dir' % fname)
511

512
        # The rest is info needed for a system restart, so it modifies the current dacycle object (self)
513

karolina's avatar
karolina committed
514
        self['da.restart.fname'] = fname    # needed for next job template
515
516
        #self.restart_filelist.append(fname)  # not that needed since it is already written to the restart dir...
        #logging.debug('Added da_runtime.rc to the restart_filelist for later collection')
517
518


519
    def write_rc(self, fname):
520
521
        """ Write RC file after each process to reflect updated info """

karolina's avatar
karolina committed
522
        rc.write(fname, self)
karolina's avatar
karolina committed
523
        logging.debug('Wrote expanded rc-file (%s)' % fname)
karolina's avatar
karolina committed
524
        
525

526
    def submit_next_cycle(self):
527
        """ 
Peters, Wouter's avatar
Peters, Wouter committed
528
        Submit the next job of a DA cycle, this consists of 
529
530
531
            * Changing to the working directory from which the job was started initially
            * create a line to start the master script again with a newly created rc-file
            * Submitting the jobfile 
Peters, Wouter's avatar
Peters, Wouter committed
532
533
534

        If the end of the cycle series is reached, no new job is submitted.

535
        """
karolina's avatar
karolina committed
536
        
537

538
        if self['time.end'] < self['time.finish']:
539

Peters, Wouter's avatar
test    
Peters, Wouter committed
540
            # file ID and names
karolina's avatar
karolina committed
541
542
543
            jobid = self['time.end'].strftime('%Y%m%d') 
            targetdir = os.path.join(self['dir.exec'])
            jobfile = os.path.join(targetdir, 'jb.%s.jb' % jobid)
544
            logfile = os.path.join(targetdir, 'jb.%s.log' % jobid)
Peters, Wouter's avatar
test    
Peters, Wouter committed
545
            # Template and commands for job
546
            jobparams = {'jobname':"j.%s" % jobid, 'jobnodes':self['da.resources.ntasks'], 'jobtime': self['da.resources.ntime'], 'logfile': logfile, 'errfile': logfile}
547
            template = self.daplatform.get_job_template(jobparams)
karolina's avatar
karolina committed
548
            execcommand = os.path.join(self['dir.da_submit'], sys.argv[0]) 
549
550
            if '-t' in self.opts:
                (self.opts).remove('-t') 
551

brunner's avatar
brunner committed
552
            if 'icycle_in_job' not in os.environ:
553
554
555
556
                logging.info('Environment variable icycle_in_job not found, resubmitting after this cycle')
                os.environ['icycle_in_job'] = self['da.resources.ncycles_per_job']  # assume that if no cycle number is set, we should submit the next job by default
            else:
                logging.info('Environment variable icycle_in_job was found, processing cycle %s of %s in this job'%(os.environ['icycle_in_job'],self['da.resources.ncycles_per_job']) )
557

558
            ncycles = int(self['da.resources.ncycles_per_job'])
559
560
561
562
            for cycle in range(ncycles): 
                nextjobid = '%s'% ( (self['time.end']+cycle*self['cyclelength']).strftime('%Y%m%d'),)
                nextrestartfilename = self['da.restart.fname'].replace(jobid,nextjobid)
                nextlogfilename = logfile.replace(jobid,nextjobid)
563
                if self.daplatform.ID == 'WU capegrim':
brunner's avatar
brunner committed
564
                    template += '\nexport icycle_in_job=%d\npython %s rc=%s %s >&%s &\n' % (cycle+1,execcommand, nextrestartfilename, str.join(str(self.opts), ''), nextlogfilename,)
brunner's avatar
brunner committed
565
                else: 
brunner's avatar
brunner committed
566
                    template += '\nexport icycle_in_job=%d\npython %s rc=%s %s >&%s\n' % (cycle+1,execcommand, nextrestartfilename, str.join(str(self.opts), ''), nextlogfilename,) 
Peters, Wouter's avatar
test    
Peters, Wouter committed
567
568

            # write and submit 
569
            self.daplatform.write_job(jobfile, template, jobid)
brunner's avatar
brunner committed
570
571
572
            if 'da.resources.ncycles_per_job' in self:
                do_submit = (int(os.environ['icycle_in_job']) >= int(self['da.resources.ncycles_per_job']))
            else:
573
                dosubmit = False
574
575
576
577
          
            if do_submit:
                jobid = self.daplatform.submit_job(jobfile, joblog=logfile)

578
579
580
581
        else:
            logging.info('Final date reached, no new cycle started')


582
def start_logger(level=logging.INFO):
583
584
585
586
    """ start the logging of messages to screen"""

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

karolina's avatar
karolina committed
587
588
589
    logging.basicConfig(level=level,
                        format=' [%(levelname)-7s] (%(asctime)s) py-%(module)-20s : %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
590

591
def parse_options():
592
593
594
595
596
597
598
599
600
601
    """ 
    Function parses options from the command line and returns the arguments as a dictionary.
    Accepted command line arguments are:

    ========  =======
    Argument  Meaning
    ========  =======
    -v        verbose output in log files
    -h        display help
    -r        start a simulation by recovering from a previous crash
602
    -t        start a simulation by transitioning from 25 to 34 layers in December 2005 (od meteo)
603
604
605
    ========  =======

    """
606
607
608

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

karolina's avatar
karolina committed
609
610
    opts = []
    args = []
611
    try:                                
612
        opts, args = getopt.gnu_getopt(sys.argv[1:], "-rvt")
brunner's avatar
brunner committed
613
    except getopt.GetoptError as msg:           
karolina's avatar
karolina committed
614
        logging.error('%s' % msg)
615
616
617
        sys.exit(2)      

    for options in opts:
karolina's avatar
karolina committed
618
        options = options[0].lower()
619
620
        if options == '-r':
            logging.info('-r flag specified on command line: recovering from crash')
621
622
        if options == '-t':
            logging.info('-t flag specified on command line: transition with od from December 2005')    
623
624
        if options == '-v':
            logging.info('-v flag specified on command line: extra verbose output')
karolina's avatar
karolina committed
625
            logging.root.setLevel(logging.DEBUG)
626

627
    if opts: 
628
        optslist = [item[0] for item in opts]
629
    else:
karolina's avatar
karolina committed
630
        optslist = []
631

632
633
# Parse arguments and return as dictionary

karolina's avatar
karolina committed
634
    arguments = {}
635
636
637
638
639
640
641
642
    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:
karolina's avatar
karolina committed
643
            logging.error('%s' % 'Argument passed without description (%s)' % item)
brunner's avatar
brunner committed
644
            raise getopt.GetoptError(arg)
645

karolina's avatar
karolina committed
646
        arguments[key] = arg
647
648


649
    return optslist, arguments
650

651
def validate_opts_args(opts, args):
652
653
654
655
656
    """ 
 Validate the options and arguments passed from the command line before starting the cycle. The validation consists of checking for the presence of an argument "rc", and the existence of
 the specified rc-file.  
 
    """
brunner's avatar
brunner committed
657
    if "rc" not in args:
karolina's avatar
karolina committed
658
659
        msg = "There is no rc-file specified on the command line. Please use rc=yourfile.rc"
        logging.error(msg)
brunner's avatar
brunner committed
660
        raise IOError(msg)
661
    elif not os.path.exists(args['rc']):
karolina's avatar
karolina committed
662
663
        msg = "The specified rc-file (%s) does not exist " % args['rc'] 
        logging.error(msg)
brunner's avatar
brunner committed
664
        raise IOError(msg)
665
666
667
668
669
670
671
672
673

    # 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

karolina's avatar
karolina committed
674
    return opts, args
675
676
677


if __name__ == "__main__":
678
    pass
679