HWRF  trunk@4391
exhwrf_launch.py
1 #! /usr/bin/env python
2 
3 ##@namespace scripts.exhwrf_launch
4 # Creates the initial HWRF directory structure for executing a
5 # single HWRF cycle. This script must be run before any other.
6 #
7 # This script is executed as follows:
8 # @code{.sh}
9 # exhwrf_launch.py YYYYMMDDHH STID CASE_ROOT /path/to/parm [options]
10 # @endcode
11 #
12 # @note When NCEP Central Operations (NCO) runs this job, the $PARAFLAG
13 # environment variable must be set to "NO" to trigger NCO-specific rules
14 #
15 # Command line argument meanings:
16 #
17 # * YYYYMMDDHH --- a ten digit cycle date and hour
18 # * STID --- a three character storm identifier: storm number and one
19 # letter basin. For example, 12L for Katrina.
20 # * CASE_ROOT --- HISTORY for a retrospective run and FORECAST for
21 # a real-time run
22 # * /path/to/parm --- path to the parm/ directory for locating the
23 # standard *.conf files
24 #
25 # The [options] can be:
26 #
27 # * file.conf --- a configuration file to read
28 # * section.Option=VALUE --- after reading all configuration files,
29 # set option "Option" in section "section" to the given value.
30 #
31 # This is the order in which configuration files and options are
32 # processed:
33 #
34 # 1. Internal initial options from the startdata variable (which does almost nothing).
35 # 2. parm/hwrf_input.conf --- input file locations
36 # 3. parm/hwrf.conf --- detailed HWRF configuration settings
37 # 4. parm/hwrf_holdvars.conf --- for generating the com/storm*.holdvars.txt file
38 # 5. parm/hwrf_basic.conf --- basic, high-level HWRF configuration settings
39 # 6. Configuration files listed in the [options] to exhwrf_launch
40 # 7. Configuration section.Option=VALUE settings in exhwrf_launch
41 # 8. The hwrf_expt.prelaunch() function is called to set per-cycle or per-basin settings.
42 #
43 # See the hwrf_expt.prelaunch() function and the hwrf.prelaunch module
44 # for details on the prelaunch functionality.
45 #
46 # After configuration information is determined, the sanity checks are
47 # run. If the sanity checks succeed, the initial directory structure is
48 # created and the com/storm*.conf file is generated. The database is
49 # filled with products and tasks generated by the hwrf_expt module, and
50 # then the script exits.
51 
52 import os, sys, re, logging, collections
53 
54 if 'USHhwrf' in os.environ:
55  sys.path.append(os.environ['USHhwrf'])
56 elif 'HOMEhwrf' in os.environ:
57  sys.path.append(os.path.join(os.environ['HOMEhwrf'],'ush'))
58 else:
59  guess_HOMEhwrf=os.path.dirname(os.path.dirname(
60  os.path.realpath(__file__)))
61  guess_USHhwrf=os.path.join(guess_HOMEhwrf,'ush')
62  sys.path.append(guess_USHhwrf)
63 
65 import hwrf.launcher
66 import hwrf_expt
67 from hwrf.numerics import to_datetime
68 
69 ## The logging.Logger for log messages
70 logger=None
71 
72 ## Initial configuration data to be inserted to the
73 # hwrf.launcher.HWRFLauncher before reading configuration files.
74 startdata='''
75 # Holdvars file with ksh variables:
76 holdvars="{holdvars}"
77 
78 # Main conf file:
79 CONFhwrf="{CONFhwrf}"
80 
81 # Cycle being run:
82 cycle={YMDH}
83 
84 # Three character storm ID -- just number and basin letter:
85 stormid3="{vit[stormid3]}"
86 
87 # Long storm ID:
88 longstormid="{vit[longstormid]}"
89 ''' # Don't forget the end of line before the '''
90 
91 def usage(logger):
92  logger.critical('Invalid arguments to exhwrf_launch.py. Aborting.')
93  print '''
94 Usage: exhwrf_launch.py 2014062400 95E case_root /path/to/parm [options]
95 
96 Mandatory arguments:
97  2014062400 -- the cycle to run
98  95E -- storm id
99  case_root -- FORECAST = real-time mode, HISTORY = retrospective mod
100  /path/to/parm -- location of parm directory where standard conf files
101  reside
102 
103 Optional arguments:
104 section.option=value -- override conf options on the command line
105 /path/to/file.conf -- additional conf files to parse
106 
107 Aborting due to incorrect arguments.'''
108  sys.exit(2)
109 
110 def main():
111  """!Processes configuration information and passes on to the
112  hwrf.launcher module to create the initial directory structure and
113  conf file."""
114  logger=logging.getLogger('exhwrf_launch')
115  PARAFLAG = ( 'YES' == os.environ.get('PARAFLAG','YES') )
116  logger.info('Top of exhwrf_launch.')
117 
118  args=sys.argv[1:]
119 
120  # Check the initial arguments passed in.
121  if len(args)<4: usage(logger)
122 
123  # Find cycle: Same for all storms in a multistorm.
124  cycle=to_datetime(args[0])
125 
126  # Multistorm - jtf
127  fake_stid = None
128  go_since_multistorm_sids = False
129 
130  # Test to see if BASINS and/or MULTISTORM_SIDS is set
131  basins = os.environ.get('BASINS', None)
132  multi_sids_env = os.environ.get('MULTISTORM_SIDS','')
133  multi_sids = list()
134  if multi_sids_env:
135  multi_sids = [s for s in multi_sids_env.split()]
136  if basins is not None:
137  go_since_multistorm_sids = True
138  logger.info('Looks like this is rocoto, running a multistorm with basins: %s'%(basins))
139  # call storm priority
140  bstorms = hwrf.launcher.multistorm_priority(args, basins, logger, usage)
141  logger.info('Priority found the following storms: ' +repr(bstorms))
142  for s in bstorms:
143  if s not in multi_sids:
144  multi_sids.append(s)
145 
146  logger.info('MS LIST: ' +repr(multi_sids))
147 
148  if multi_sids:
149  go_since_multistorm_sids = True
150  fakestorm_conf = None
151 
152  if go_since_multistorm_sids:
153  logger.info('Parsing input arguments for a multistorm with ids: %s.'% (multi_sids))
154  (case_root, parm, infiles, stids, fake_stid, priority_stid, moreopts) = \
155  hwrf.launcher.multistorm_parse_args(multi_sids, args[1:], logger, usage)
156  # Make sure you pass the last elements of the moreopts list, since it is the options
157  # for the fake storm, namely the correct config.startfile.
158  fakestorm_conf=hwrf.launcher.launch(infiles,cycle,fake_stid,moreopts[-1],case_root,
159  prelaunch=hwrf_expt.prelaunch,
160  fakestorm=True)
161  else:
162  (case_root,parm,infiles,stid,moreopt) = \
163  hwrf.launcher.parse_launch_args(args[1:],logger,usage)
164  stids = [stid]
165  moreopts = [moreopt]
166 
167  logger.info('Requested storm %s cycle %s case root %s'
168  %(stid,cycle.strftime('%Y%m%d%H'),case_root))
169 
170  global_storm_num = 2
171  for i,stid in enumerate(stids):
172  if stid != fake_stid:
173  conf=hwrf.launcher.launch(infiles,cycle,stid,moreopts[i],case_root,
174  prelaunch=hwrf_expt.prelaunch,
175  fakestorm_conf=fakestorm_conf,
176  storm_num=global_storm_num)
177  else:
178  conf=fakestorm_conf
179 
180  global_storm_num += 1
181  conf.sanity_check()
182 
183  if 'NO'==os.environ.get('PARAFLAG','YES'):
184  message=conf.strinterp('wcoss_fcst_nco','{messages}/message{storm_num}')
185  if os.path.exists(message):
186  alert=produtil.dbnalert.DBNAlert(['MODEL','HWRF_MESSAGE','{job}',
187  message])
188  alert()
189 
190  holdvars=conf.strinterp('dir','{com}/{stormlabel}.holdvars.txt')
191  logger.info(holdvars+': write holdvars here')
192  with open(holdvars,'wt') as f:
193  f.write(conf.make_holdvars())
194 
195  if conf.has_option('config','startfile'):
196  startfile=conf.getstr('config','startfile')
197  logger.info(startfile+': Write holdvars and conf location here.')
198  startcontents=conf.strinterp('config',startdata,holdvars=holdvars)
199  with open(startfile,'wt') as f:
200  f.write(startcontents)
201 
202 
203 if __name__ == '__main__':
204  try:
206  produtil.log.postmsg('exhwrf_launch is starting')
207  main()
208  produtil.log.postmsg('exhwrf_launch completed')
209  except Exception as e:
210  produtil.log.jlogger.critical(
211  'exhwrf_launch failed: %s'%(str(e),),exc_info=True)
212  sys.exit(2)
Contains setup(), which initializes the produtil package.
Definition: setup.py:1
def multistorm_priority
Definition: launcher.py:136
def postmsg(message)
Sends the message to the jlogfile logging stream at level INFO.
Definition: log.py:46
def setup(ignore_hup=False, dbnalert_logger=None, jobname=None, cluster=None, send_dbn=None, thread_logger=False, thread_stack=2 **24, kwargs)
Initializes the produtil package.
Definition: setup.py:15
def parse_launch_args
Parsed arguments to scripts that launch the HWRF system.
Definition: launcher.py:170
def launch
Initializes the directory structure for a new HWRF workflow.
Definition: launcher.py:404
Time manipulation and other numerical routines.
Definition: numerics.py:1
This module runs the NCO dbn_alert program, or logs dbn_alert messages if run with dbn alerts disable...
Definition: dbnalert.py:1
This class represents a call to dbn_alert, as a callable Python object.
Definition: dbnalert.py:47
Creates the initial HWRF directory structure, loads information into each job.
Definition: launcher.py:1
Configures logging.
Definition: log.py:1
def multistorm_parse_args
Definition: launcher.py:34
def main()
Processes configuration information and passes on to the hwrf.launcher module to create the initial d...