OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
get_output_name.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 """
4 Program to return the name of the next level file that would be created from
5 the input file name.
6 """
7 
8 import optparse
9 import os
10 import re
11 import sys
12 import traceback
13 
14 import datetime
17 import seadasutils.ProcUtils as ProcUtils
18 #import namer_constants
22 import mlp.obpg_data_file
24 
25 __version__ = '1.0.6-2021-08-01'
26 __author__ = 'byang'
27 
28 #2345678901234567890123456789012345678901234567890123456789012345678901234567890
29 
30 
31 
32 FILE_TYPES_CONVERTER = {'Level 0': 'Level 0',
33  'Level 1A': 'Level 1A',
34  'l1agen' : 'Level 1A',
35  'Level 1B': 'Level 1B',
36  'Level 2': 'Level 2',
37  'L3bin': 'L3bin',
38  'Level 3 Binned': 'L3bin'}
39 
40 #def get_1_file_name(input_name, file_typer, file_type, sensor,
41 # target_program, clopts):
42 # def convert_str_to_int(short_str):
43 # """
44 # Returns an integer taken from the passed in string.
45 # """
46 # try:
47 # int_value = int(short_str)
48 # except ValueError:
49 # err_msg = "Error! Unable to convert {0} to integer.".format(short_str)
50 # sys.exit(err_msg)
51 # return int_value
52 
53 # def find_extension(format_data_list, search_term):
54 # """
55 # Returns the extension from format_data_list that is indicated by
56 # search_term.
57 # """
58 # extension = None
59 # try:
60 # # Are we searching for a matching index number ...
61 # int(search_term)
62 # tuple_index = 0
63 # except ValueError:
64 # # ... or a matching format name?
65 # tuple_index = 1
66 # # Use a generator to find the match.
67 # format_index = next((i for i, t in enumerate(format_data_list) if format_data_list[i][tuple_index].lower() == search_term.lower()), None)
68 # if (format_index != None) and (format_index < len(format_data_list)):
69 # extension = format_data_list[format_index][2]
70 # else:
71 # for ext_candidate in format_data_list:
72 # if search_term.lower() == ext_candidate[2].lower():
73 # extension = ext_candidate[2]
74 # break
75 # return extension
76 
77 # def get_1_file_name(data_file, target_program, clopts):
78 # """
79 # Return the next level name for a single file.
80 # """
81 # level_finder = mlp.name_finder_utils.get_level_finder([data_file],
82 # target_program,
83 # clopts)
84 # next_level_name = level_finder.get_next_level_name()
85 # return next_level_name
86 
87 def get_multifile_next_level_name(data_files_list_info, target_program, clopts):
88  """
89  Return the next level name for a set of files.
90  """
91  for file_info in data_files_list_info:
92  if file_info.file_type == 'unknown':
93  err_msg = 'Error! File {0} is of unknown type.'.format(
94  file_info.name)
95  sys.exit(err_msg)
96  next_level_name = get_multifile_output_name(data_files_list_info,
97  target_program, clopts)
98  return next_level_name
99 
100 def get_multifile_output_name(data_files_list_info, target_program, clopts):
101  """
102  Returns the file name derived from a group of files names.
103  """
104  list_file_type = data_files_list_info[0].file_type
105  for data_file in data_files_list_info[1:]:
106  if data_file.file_type != list_file_type:
107  err_msg = 'Error! File types do not match for {0} and {1}'.\
108  format(data_files_list_info[0].name, data_file.name)
109  sys.exit(err_msg)
110  output_name = mlp.get_output_name_utils.get_output_name(data_files_list_info, target_program, clopts)
111  return output_name
112 
113 # def read_fileformats():
114 # """
115 # Returns a tuple containing the file formats.
116 # """
117 
118 # format_file_path = os.path.join(os.getenv('OCDATAROOT'), 'common',
119 # 'file_formats.txt')
120 # if os.path.exists(format_file_path):
121 # file_formats = []
122 # format_file_hndl = open(format_file_path)
123 # inp_lines = format_file_hndl.readlines()
124 # format_file_hndl.close()
125 # for line in inp_lines:
126 # cleaned_line = line.strip()
127 # if cleaned_line[0] != '#':
128 # #format = get_format(cleaned_line)
129 # file_format = tuple(cleaned_line.split(':'))
130 
131 # file_formats.append(file_format)
132 
133 # return file_formats
134 # else:
135 # err_msg = 'Error! Cannot find file {0}.'.format(format_file_path)
136 # sys.exit(err_msg)
137 
138 
139 
141  """
142  Returns the options and arguments from a command line call.
143  """
144  ver_msg = ' '.join(['%prog', __version__])
145  use_msg = 'usage: %prog INPUT_FILE TARGET_PROGRAM'
146  cl_parser = optparse.OptionParser(usage=use_msg, version=ver_msg)
147  cl_parser.add_option('--oformat', dest='oformat', action='store',
148  type='string', help='output format')
149  cl_parser.add_option('--odir', dest='odir', action='store',
150  type='string', help='output directory')
151  cl_parser.add_option('--resolution', dest='resolution', action='store',
152  type='string',
153  help='resolution for l3mapgen')
154  cl_parser.add_option('--suite', dest='suite', action='store',
155  type='string', help='data type suite')
156  # cl_parser.add_option('--product', dest='product', action='store',
157  # type='string', help='product type (for smigen)')
158  (clopts, clargs) = cl_parser.parse_args()
159  if len(clargs) == 0:
160  print ("\nError! No input file or target program specified.\n")
161  cl_parser.print_help()
162  sys.exit(0)
163  elif len(clargs) == 1:
164  print ("\nError! No target program specified.\n")
165  cl_parser.print_help()
166  sys.exit(0)
167  elif len(clargs) > 2:
168  print ('\nError! Too many arguments specified on the command line.')
169  cl_parser.print_help()
170  sys.exit(0)
171  else:
172  return clopts, clargs[0], clargs[1]
173 
174 def get_data_files_info(file_list_file):
175  """
176  Returns a list of of data files.
177  """
178  file_info = []
179  with open(file_list_file, 'rt') as file_list_file:
180  inp_lines = file_list_file.readlines()
181  for line in inp_lines:
182  filename = line.strip()
183  if os.path.exists(filename):
184  file_typer = mlp.get_obpg_file_type.ObpgFileTyper(filename)
185  file_type, sensor = file_typer.get_file_type()
186  if file_type != 'unknown':
187  stime, etime = file_typer.get_file_times()
188  file_metadata = file_typer.attributes
189  data_file = mlp.obpg_data_file.ObpgDataFile(filename, file_type,
190  sensor, stime, etime, file_metadata)
191  file_info.append(data_file)
192  else:
193  err_msg = 'Error! {0} is not an OBPG file.'.\
194  format(filename)
195  sys.exit(err_msg)
196  else:
197  err_msg = 'Error! File {0} could not be found.'.format(filename)
198  sys.exit(err_msg)
199  file_info.sort(key=myfunc)
200  return file_info
201 
202 def myfunc(n):
203  return n.start_time
204 
206  """
207  Builds and prints an error message from the exception information,
208  then exits.
209  """
210  exc_parts = exc_info
211  err_type = str(exc_parts[0]).split('.')[1][0:-2]
212  err_msg = 'Error! Encountered {0}:'.format(str(err_type))
213  print (err_msg)
214  if DEBUG:
215  traceback.print_exc()
216  sys.exit(1)
217 
218 def main():
219  """
220  Main function for when this module is called as a program.
221  """
222  ret_status = 0
223  clopts, inp_name, targ_prog = get_command_line_data()
224 
225  #if not targ_prog in namer_constants.PROCESSABLE_PROGRAMS:
226  if not targ_prog in PROCESSABLE_PROGRAMS:
227  err_msg = 'Error! The target program, "{0}", is not known.'.\
228  format(targ_prog)
229  sys.exit(err_msg)
230  if os.path.exists(inp_name):
231  try:
232  file_typer = mlp.get_obpg_file_type.ObpgFileTyper(inp_name)
233  ftype, sensor = file_typer.get_file_type()
234  if ftype == 'unknown':
236  # Try treating the input file as a file list file.
237  data_files_info = get_data_files_info(inp_name)
238  if len(data_files_info) > 0:
239  next_level_name = get_multifile_next_level_name(
240  data_files_info, targ_prog, clopts)
241  else:
242  err_msg = "Error! No OBPG files found in {0}".\
243  format(inp_name)
244  sys.exit(err_msg)
245  else:
246  # The input file wasn't a file list file.
247  err_msg = "File {0} is not an OBPG file.".format(inp_name)
248  sys.exit(err_msg)
249  else:
250  # The file is an OBPG file
251  stime, etime = file_typer.get_file_times()
252  file_metadata = file_typer.attributes
253  data_file = mlp.obpg_data_file.ObpgDataFile(inp_name, ftype, sensor,
254  stime, etime,
255  file_metadata)
256  next_level_name = mlp.get_output_name_utils.get_output_name([data_file], targ_prog, clopts)
257  print ('Output Name: ' + next_level_name)
258  except SystemExit as sys_ex:
259  # The intention here is to catch exit exceptions we throw in other
260  # parts of the program and continue with the exit, outputting
261  # whatever error message was created for the exit.
262  sys.exit(sys_ex)
263  except:
264  handle_unexpected_exception(sys.exc_info())
265  else:
266  err_msg = "Error! File {0} was not found.".format(inp_name)
267  sys.exit(err_msg)
268  return ret_status
269 
270 
271 
272 #global DEBUG
273 DEBUG = False
274 DEBUG = True # Comment out for production use
275 PROCESSABLE_PROGRAMS = \
276  set(list(mlp.next_level_name_finder.NextLevelNameFinder.PROCESSING_LEVELS.keys()) +\
277  list(mlp.next_level_name_finder.HawkeyeNextLevelNameFinder.PROCESSING_LEVELS.keys()) +\
278  list(mlp.next_level_name_finder.ModisNextLevelNameFinder.PROCESSING_LEVELS.keys()) +\
279  list(mlp.next_level_name_finder.SeawifsNextLevelNameFinder.PROCESSING_LEVELS.keys()) +\
280  list(mlp.viirs_next_level_name_finder.ViirsNextLevelNameFinder.PROCESSING_LEVELS.keys()))
281 
282 if __name__ == '__main__':
283  sys.exit(main())
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 is_ascii_file(filename)
Definition: MetaUtils.py:78
def get_data_files_info(file_list_file)
def handle_unexpected_exception(exc_info)
const char * str
Definition: l1c_msi.cpp:35
def get_output_name(data_files, target_program, clopts)
def get_multifile_output_name(data_files_list_info, target_program, clopts)
def get_multifile_next_level_name(data_files_list_info, target_program, clopts)