OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
getanc_aquarius.py
Go to the documentation of this file.
1 #! /usr/bin/env python3
2 
3 import os
4 import sys
5 import subprocess
6 import tarfile
7 import argparse
8 
9 from seadasutils.ParamUtils import ParamProcessing
10 from seadasutils.ProcUtils import date_convert, addsecs, cat, httpdl
11 from seadasutils.aquarius_utils import aquarius_timestamp
12 import seadasutils.anc_utils as ga
13 from seadasutils.setupenv import env
14 
15 
17  """
18  utilities for Aquarius ancillary data
19  """
20 
21  def __init__(self, filename=None,
22  start=None,
23  stop=None,
24  ancdir=None,
25  ancdb='ancillary_data.db',
26  curdir=False,
27  verbose=False,
28  printlist=True,
29  download=True,
30  refreshDB=False):
31 
32  self.filename = filename
33  self.start = start
34  self.stop = stop
35  self.printlist = printlist
36  self.verbose = verbose
37  self.curdir = curdir
38  self.ancdir = ancdir
39  self.ancdb = ancdb
40  self.dl = download
41  self.refreshDB = refreshDB
42  self.dirs = {}
43  self.ancfiles = {}
44 
45  def parse_anc(self, anc_filelist):
46  anc = ParamProcessing(parfile=anc_filelist)
47  anc.parseParFile()
48  self.ancfiles = anc.params['main']
49 
50  def write_anc(self, anc_filelist):
51  anc = ParamProcessing(parfile=anc_filelist)
52  anc.params['main'] = self.ancfiles
53  anc.buildParameterFile('main')
54 
55  def run_mk_anc(self, count):
56  """
57  Run mk_aquarius_ancillary_data to create the "y" files
58  """
59 
60  # start and end of this 24-hour period in yyyymmdd
61  dt = self.start
62  if count >= 2:
63  dt = self.stop
64  sdt = date_convert(dt, 'j', 'd')
65  edt = date_convert(addsecs(dt, 86400, 'j'), 'j', 'd')
66 
67  callnum = format(count, 'd')
68  hour = os.path.basename(self.ancfiles['met' + callnum])[8:10]
69  yancfilename = ''.join(['y', sdt, hour, '.h5'])
70 
71  # make the yancfile
72  if self.verbose:
73  print("")
74  print("Creating Aquarius yancfile%s %s..." % (count, yancfilename))
75  mk_anc = os.path.join(self.dirs['bin'], 'mk_aquarius_ancillary_data')
76  mk_anc_cmd = [mk_anc,
77  self.ancfiles['sstfile1'],
78  self.ancfiles['sstfile2'],
79  self.ancfiles['atm' + callnum],
80  self.ancfiles['met' + callnum],
81  self.ancfiles['swhfile' + callnum],
82  self.ancfiles['frozenfile' + callnum],
83  self.ancfiles['icefile1'],
84  self.ancfiles['icefile2'],
85  self.ancfiles['sssfile1'],
86  self.ancfiles['sssfile2'],
87  self.ancfiles['argosfile1'],
88  self.ancfiles['argosfile2'],
89  sdt, edt]
90  status = subprocess.call(mk_anc_cmd, shell=False)
91  if status:
92  if self.verbose:
93  print("mk_aquarius_ancillary_data returned with exit status: "
94  + str(status))
95  print('command: ' + mk_anc_cmd)
96  return None
97 
98  # add info from MERRA file
99  geos = os.path.join(self.dirs['bin'], 'geos')
100  geos_cmd = [geos, yancfilename, self.ancfiles['geosfile']]
101  status = subprocess.call(geos_cmd, shell=False)
102  if status:
103  if self.verbose:
104  print('geos returned with exit status: ' + str(status))
105  print('command: ' + geos_cmd)
106  return None
107 
108  # success!
109  if self.verbose:
110  print("yancfile %s created successfully!" % yancfilename)
111  return yancfilename
112 
113 
114 if __name__ == "__main__":
115 
116  version = "1.1"
117 
118  # Read commandline options...
119  usage = '''
120  %(prog)s [OPTIONS] FILE
121 
122  This program does the following:
123 
124  1) executes getanc for Aquarius L1 files. If an input file is
125  specified the start and end times are determined automatically,
126  otherwise a start time must be provided by the user.
127 
128  2) runs the mk_aquarius_ancillary_data program to create the "y-files"
129  required as input to l2gen_aquarius.
130 
131  3) retrieves and un-tars the scatterometer files
132  '''
133 
134  parser = argparse.ArgumentParser(prog="getanc_aquarius",usage=usage)
135  parser.add_argument('--version', action='version', version='%(prog)s ' + version)
136  parser.add_argument("filename", nargs='?',
137  help="Input L1 file", metavar="L1FILE")
138  parser.add_argument("-s", "--start",
139  help="Time of the first scanline (if used, no input file is required)",
140  metavar="START")
141  parser.add_argument("-e", "--stop",
142  help="Time of last scanline", metavar="STOP")
143 
144  ancdb_help_text = "Use a custom filename for ancillary database. If " \
145  "full path not given, ANCDB is assumed to exist "\
146  "(or will be created) under " + \
147  ga.DEFAULT_ANC_DIR_TEXT + "/log/. If " + \
148  ga.DEFAULT_ANC_DIR_TEXT + "/log/ does not " \
149  "exist, ANCDB is assumed (or will be created) " \
150  "under the current working directory"
151  parser.add_argument("--ancdb", default='ancillary_data.db',help=ancdb_help_text, metavar="ANCDB")
152  parser.add_argument("--ancdir",
153  help="Use a custom directory tree for ancillary files", metavar="ANCDIR")
154  parser.add_argument("-c", "--curdir", action="store_true",
155  default=False, help="Download ancillary files directly into current working directory")
156  parser.add_argument("-r", "--refreshDB", action="store_true", default=False,
157  help="Remove existing database records and re-query for ancillary files")
158  parser.add_argument("--disable-download", action="store_false", dest="download",default=True,
159  help="Disable download of ancillary files not found on hard disk")
160  parser.add_argument("--timeout", type=float, default=10.0, metavar="TIMEOUT",
161  help="set the network timeout in seconds")
162  parser.add_argument("-v", "--verbose", action="store_true",
163  default=False, help="print status messages")
164  parser.add_argument("--noprint", action="store_false", default=True,
165  help="Suppress printing the resulting list of files to the screen")
166  parser.add_argument("-f", "--force-download", action="store_true", dest='force', default=False,
167  help="Force download of ancillary files, even if found on hard disk")
168 
169  args = parser.parse_args()
170 
171  if args.filename is None and args.start is None:
172  parser.print_help()
173  sys.exit(1)
174 
175  g = GetAncAquarius(filename=args.filename,
176  start=argssstart,
177  stop=args.stop,
178  curdir=args.curdir,
179  ancdir=args.ancdir,
180  ancdb=args.ancdb,
181  verbose=args.verbose,
182  printlist=args.noprint,
183  download=args.download,
184  refreshDB=args.refreshDB)
185 
186  env(g)
187  if not g.start:
188  (g.start, g.stop, sensor) = aquarius_timestamp(args.filename)
189 
190  # Run getanc
191  getanc = os.path.join(g.dirs['bin'], 'getanc')
192  if args.filename:
193  getanc_cmd = [getanc, '--mission=aquarius --noprint', args.filename]
194  else:
195  getanc_cmd = [getanc, '--mission=aquarius --noprint', '-s', args.start]
196  if args.stop:
197  getanc_cmd.append(args.stop)
198 
199  if args.verbose:
200  getanc_cmd.append(' --verbose')
201  if args.refreshDB:
202  getanc_cmd.appen(' --refreshDB')
203  if args.force:
204  getanc_cmd.append(' --force')
205 
206  # print(getanc_cmd)
207  status = subprocess.call(getanc_cmd, shell=False)
208 
209  if status and args.verbose:
210  print('getanc returned with exit status: ' + str(status))
211  print('command: ' + getanc_cmd)
212 
213  if args.filename is None:
214  anc_filelist = args.start + ".anc"
215  else:
216  anc_filelist = '.'.join([os.path.basename(args.filename), 'anc'])
217 
218  g.parse_anc(anc_filelist)
219  anclist = list(g.ancfiles.keys())
220 
221  # create yancfiles
222  g.ancfiles['yancfile1'] = g.run_mk_anc(1)
223  g.ancfiles['yancfile2'] = g.run_mk_anc(2)
224  if not (g.ancfiles['yancfile1'] and g.ancfiles['yancfile2']):
225  print('ERROR in making yancfiles!')
226  exit(1)
227 
228  # make 3rd yancfile, as needed
229  atm3 = g.ancfiles.get('atm3', None)
230  if atm3 and atm3 not in (g.ancfiles['atm1'], g.ancfiles['atm2']):
231  g.ancfiles['yancfile3'] = g.run_mk_anc(3)
232 
233  # retrieve and extract scatterometer files
234  gran = os.path.basename(args.filename).split('.')[0]
235  scatfile = '.'.join([gran, 'L2_SCAT_V5.0.tar'])
236  scatpath = '/'.join(['/cgi/getfile', scatfile])
237  if verbose:
238  print('\nDownloading ' + scatfile + ' to current directory.')
239  status = httpdl('oceandata.sci.gsfc.nasa.gov',
240  scatpath, uncompress=True, verbose=verbose)
241  if status:
242  print('Error downloading', scatfile)
243  else:
244  tar = tarfile.open(scatfile)
245  tar.extractall()
246  tar.close()
247 
248  # translate anctype to parameter names expected by l2gen_aquarius
249  g.ancfiles['l2_uncertainties_file'] = g.ancfiles.get('pert', '')
250  g.ancfiles['sif_file'] = g.ancfiles.get('sif', '')
251  g.ancfiles['sss_matchup_file'] = g.ancfiles.get('sssmatchup', '')
252 
253  # clean up anc_filelist to remove files contained in the yancfiles
254  for key in anclist:
255  if key not in ('xrayfile1', 'xrayfile2',
256  'l2_uncertainties_file',
257  'sif_file',
258  'sss_matchup_file',
259  'rim_file'):
260  del (g.ancfiles[key])
261 
262  # add hard-coded suite version number
263  g.ancfiles['suite'] = 'V5.0.0'
264 
265  # save original
266  os.rename(anc_filelist, anc_filelist + '.orig')
267 
268  # write out the cleaned .anc file
269  g.write_anc(anc_filelist)
270  if args.verbose or args.printlist:
271  cat(anc_filelist)
272  sys.exit(0)
def parse_anc(self, anc_filelist)
list(APPEND LIBS ${PGSTK_LIBRARIES}) add_executable(atteph_info_modis atteph_info_modis.c) target_link_libraries(atteph_info_modis $
Definition: CMakeLists.txt:7
def cat(file_to_print)
Definition: ProcUtils.py:356
def write_anc(self, anc_filelist)
def __init__(self, filename=None, start=None, stop=None, ancdir=None, ancdb='ancillary_data.db', curdir=False, verbose=False, printlist=True, download=True, refreshDB=False)
def env(self)
Definition: setupenv.py:7
const char * str
Definition: l1c_msi.cpp:35
def httpdl(server, request, localpath='.', outputfilename=None, ntries=5, uncompress=False, timeout=30., verbose=0, force_download=False, chunk_size=DEFAULT_CHUNK_SIZE)
Definition: manifest.py:75
def date_convert(datetime_i, in_datetype=None, out_datetype=None)
Definition: ProcUtils.py:232
def addsecs(datetime_i, dsec, datetype=None)
Definition: ProcUtils.py:268