Coverage for python/astro_metadata_translator/bin/translateheader.py : 10%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of astro_metadata_translator.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the LICENSE file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12"""Implementation of the ``translate_header.py`` script.
14Read file metadata from the specified files and report the translated content.
15"""
17__all__ = ("main", "process_files")
19import argparse
20import logging
22import sys
23import traceback
24import importlib
25import yaml
26from astro_metadata_translator import ObservationInfo, fix_header
28from ..file_helpers import find_files, read_basic_metadata_from_file
31# Output mode choices
32OUTPUT_MODES = ("auto", "verbose", "table", "yaml", "fixed", "yamlnative", "fixednative", "none")
34# Definitions for table columns
35TABLE_COLUMNS = ({
36 "format": "32.32s",
37 "attr": "observation_id",
38 "label": "ObsId"
39 },
40 {
41 "format": "8.8s",
42 "attr": "observation_type",
43 "label": "ImgType",
44 },
45 {
46 "format": "16.16s",
47 "attr": "object",
48 "label": "Object",
49 },
50 {
51 "format": "16.16s",
52 "attr": "physical_filter",
53 "label": "Filter",
54 },
55 {
56 "format": "5.1f",
57 "attr": "exposure_time",
58 "label": "ExpTime",
59 },
60 )
63def build_argparser():
64 """Construct an argument parser for the ``translate_header.py`` script.
66 Returns
67 -------
68 argparser : `argparse.ArgumentParser`
69 The argument parser that defines the ``translate_header.py``
70 command-line interface.
71 """
73 parser = argparse.ArgumentParser(description="Summarize headers from astronomical data files")
74 parser.add_argument("files", metavar="file", type=str, nargs="+",
75 help="File(s) from which headers will be parsed."
76 " If a directory is given it will be scanned for files matching the regular"
77 " expression defined in --regex.")
78 parser.add_argument("-q", "--quiet", action="store_true",
79 help="Do not report the translation content from each header. This forces "
80 "output mode 'none'.")
81 parser.add_argument("-d", "--dumphdr", action="store_true",
82 help="Dump the header in YAML format to standard output rather than translating it."
83 " This is the same as using mode=yaml")
84 parser.add_argument("--traceback", action="store_true",
85 help="Give detailed trace back when any errors encountered")
86 parser.add_argument("-n", "--hdrnum", default=1,
87 help="HDU number to read. If the HDU can not be found, a warning is issued but "
88 "translation is attempted using the primary header. "
89 "The primary header is always read and merged with this header.")
90 parser.add_argument("-m", "--mode", default="auto", choices=OUTPUT_MODES,
91 help="Display mode for translated parameters. 'verbose' displays all the information"
92 " available. 'table' displays important information in tabular form."
93 " 'yaml' dumps the header in YAML format (this is equivalent to -d option)."
94 " 'fixed' dumps the header in YAML after it has had corrections applied."
95 " Add 'native' suffix to dump YAML in PropertyList or Astropy native form."
96 " 'none' displays no translated header information and is an alias for the "
97 " '--quiet' option."
98 " 'auto' mode is 'verbose' for a single file and 'table' for multiple files.")
99 parser.add_argument("-l", "--log", default="warn",
100 help="Python logging level to use.")
102 re_default = r"\.fit[s]?\b"
103 parser.add_argument("-r", "--regex", default=re_default,
104 help="When looking in a directory, regular expression to use to determine whether"
105 f" a file should be examined. Default: '{re_default}'")
107 parser.add_argument("-p", "--packages", action="append", type=str,
108 help="Python packages to import to register additional translators")
110 return parser
113def read_file(file, hdrnum, print_trace,
114 outstream=sys.stdout, errstream=sys.stderr, output_mode="verbose",
115 write_heading=False):
116 """Read the specified file and process it.
118 Parameters
119 ----------
120 file : `str`
121 The file from which the header is to be read.
122 hdrnum : `int`
123 The HDU number to read. The primary header is always read and
124 merged with the header from this HDU.
125 print_trace : `bool`
126 If there is an error reading the file and this parameter is `True`,
127 a full traceback of the exception will be reported. If `False` prints
128 a one line summary of the error condition.
129 outstream : `io.StringIO`, optional
130 Output stream to use for standard messages. Defaults to `sys.stdout`.
131 errstream : `io.StringIO`, optional
132 Stream to send messages that would normally be sent to standard
133 error. Defaults to `sys.stderr`.
134 output_mode : `str`, optional
135 Output mode to use. Must be one of "verbose", "none", "table",
136 "yaml", or "fixed". "yaml" and "fixed" can be modified with a
137 "native" suffix to indicate that the output should be a representation
138 of the native object type representing the header (which can be
139 PropertyList or an Astropy header). Without this modify headers
140 will be dumped as simple `dict` form.
141 "auto" is not allowed by this point.
142 write_heading: `bool`, optional
143 If `True` and in table mode, write a table heading out before writing
144 the content.
146 Returns
147 -------
148 success : `bool`
149 `True` if the file was handled successfully, `False` if the file
150 could not be processed.
151 """
152 if output_mode not in OUTPUT_MODES:
153 raise ValueError(f"Output mode of '{output_mode}' is not understood.")
154 if output_mode == "auto":
155 raise ValueError("Output mode can not be 'auto' here.")
157 # This gets in the way in tabular mode
158 if output_mode != "table":
159 print(f"Analyzing {file}...", file=errstream)
161 try:
162 md = read_basic_metadata_from_file(file, hdrnum, errstream=errstream, can_raise=True)
163 if md is None:
164 raise RuntimeError(f"Failed to read file {file} HDU={hdrnum}")
166 if output_mode.endswith("native"):
167 # Strip native and don't change type of md
168 output_mode = output_mode[:-len("native")]
169 else:
170 # Rewrite md as simple dict for output
171 md = {k: v for k, v in md.items()}
173 if output_mode in ("yaml", "fixed"):
175 if output_mode == "fixed":
176 fix_header(md, filename=file)
178 # The header should be written out in the insertion order
179 print(yaml.dump(md, sort_keys=False), file=outstream)
180 return True
181 obs_info = ObservationInfo(md, pedantic=True, filename=file)
182 if output_mode == "table":
183 columns = ["{:{fmt}}".format(getattr(obs_info, c["attr"]), fmt=c["format"])
184 for c in TABLE_COLUMNS]
186 if write_heading:
187 # Construct headings of the same width as the items
188 # we have calculated. Doing this means we don't have to
189 # work out for ourselves how many characters will be used
190 # for non-strings (especially Quantity)
191 headings = []
192 separators = []
193 for thiscol, defn in zip(columns, TABLE_COLUMNS):
194 width = len(thiscol)
195 headings.append("{:{w}.{w}}".format(defn["label"], w=width))
196 separators.append("-"*width)
197 print(" ".join(headings), file=outstream)
198 print(" ".join(separators), file=outstream)
200 row = " ".join(columns)
201 print(row, file=outstream)
202 elif output_mode == "verbose":
203 print(f"{obs_info}", file=outstream)
204 elif output_mode == "none":
205 pass
206 else:
207 raise RuntimeError(f"Output mode of '{output_mode}' not recognized but should be known.")
208 except Exception as e:
209 if print_trace:
210 traceback.print_exc(file=outstream)
211 else:
212 print(f"Failure processing {file}: {e}", file=outstream)
213 return False
214 return True
217def process_files(files, regex, hdrnum, print_trace,
218 outstream=sys.stdout, errstream=sys.stderr,
219 output_mode="auto"):
220 """Read and translate metadata from the specified files.
222 Parameters
223 ----------
224 files : iterable of `str`
225 The files or directories from which the headers are to be read.
226 regex : `str`
227 Regular expression string used to filter files when a directory is
228 scanned.
229 hdrnum : `int`
230 The HDU number to read. The primary header is always read and
231 merged with the header from this HDU.
232 print_trace : `bool`
233 If there is an error reading the file and this parameter is `True`,
234 a full traceback of the exception will be reported. If `False` prints
235 a one line summary of the error condition.
236 outstream : `io.StringIO`, optional
237 Output stream to use for standard messages. Defaults to `sys.stdout`.
238 errstream : `io.StringIO`, optional
239 Stream to send messages that would normally be sent to standard
240 error. Defaults to `sys.stderr`.
241 output_mode : `str`, optional
242 Output mode to use for the translated information.
243 "auto" switches based on how many files are found.
245 Returns
246 -------
247 okay : `list` of `str`
248 All the files that were processed successfully.
249 failed : `list` of `str`
250 All the files that could not be processed.
251 """
252 found_files = find_files(files, regex)
254 # Convert "auto" to correct mode
255 if output_mode == "auto":
256 if len(found_files) > 1:
257 output_mode = "table"
258 else:
259 output_mode = "verbose"
261 # Process each file
262 failed = []
263 okay = []
264 heading = True
265 for path in sorted(found_files):
266 isok = read_file(path, hdrnum, print_trace, outstream, errstream, output_mode,
267 heading)
268 heading = False
269 if isok:
270 okay.append(path)
271 else:
272 failed.append(path)
274 return okay, failed
277def main():
278 """Read metadata from the supplied files and translate the content to
279 standard form.
281 Returns
282 -------
283 status : `int`
284 Exit status to be passed to `sys.exit()`. 0 if any of the files
285 could be translated. 1 otherwise.
286 """
288 logging.warn("This command is deprecated. Please use 'astrometadata translate' "
289 " or 'astrometadata dump' instead. See 'astrometadata -h' for more details.")
291 args = build_argparser().parse_args()
293 # Process import requests
294 if args.packages:
295 for m in args.packages:
296 importlib.import_module(m)
298 output_mode = args.mode
299 if args.quiet:
300 output_mode = "none"
301 elif args.dumphdr:
302 output_mode = "yaml"
304 # Set the log level. Convert to upper case to allow the user to
305 # specify --log=DEBUG or --log=debug
306 numeric_level = getattr(logging, args.log.upper(), None)
307 if not isinstance(numeric_level, int):
308 raise ValueError(f"Invalid log level: {args.log}")
309 logging.basicConfig(level=numeric_level)
311 # Main loop over files
312 okay, failed = process_files(args.files, args.regex, args.hdrnum,
313 args.traceback,
314 output_mode=output_mode)
316 if failed:
317 print("Files with failed translations:", file=sys.stderr)
318 for f in failed:
319 print(f"\t{f}", file=sys.stderr)
321 if okay:
322 # Good status if anything was returned in okay
323 return 0
324 else:
325 return 1