Debian Codegraph @

mrcfile/validator.py

raw
1 # Copyright (c) 2018, Science and Technology Facilities Council
2 # This software is distributed under a BSD licence. See LICENSE.txt.
3
4 """
5 validator
6 ---------
7
8 Module for top-level functions that validate MRC files.
9
10 This module is runnable to allow files to be validated easily from the command
11 line.
12
13 """
14
15 # Import Python 3 features for future-proofing
16 from __future__ import (absolute_import, division, print_function,
17 unicode_literals)
18
19 import argparse
20 import sys
21 import traceback
22
23 from . import load_functions
24
25
26 def main(args=None):
27 """
28 Validate a list of MRC files given as command arguments.
29
30 The return value is used as the process exit code when this function is
31 called by running this module or from the corresponding ``console_scripts``
32 entry point.
33
34 Returns:
35 ``0`` if all command arguments are names of valid MRC files. ``1`` if
36 no file names are given or any of the files is not a valid MRC file.
37 """
38 if args is None:
39 args = sys.argv[1:]
40 parser = argparse.ArgumentParser(
41 description="Validate a list of MRC files. Exit status is 0 if all "
42 "input files are valid, or 1 if any input file is "
43 "invalid. Descriptions of the problems with any invalid "
44 "files are written to the standard output."
45 )
46 parser.add_argument("filename", nargs='*', help="Input MRC file")
47 args = parser.parse_args(args)
48 names = args.filename
49 if validate_all(names):
50 return 0
51 return 1
52
53
54 def validate_all(names, print_file=None):
55 """Validate a list of MRC files.
56
57 This function calls :func:`validate` for each file name in the given list.
58
59 Args:
60 names: A sequence of file names to open and validate.
61 print_file: The output text stream to use for printing messages about
62 the validation. This is passed directly to the ``print_file``
63 argument of the :func:`validate` function. The default is
64 :data:`None`, which means output will be printed to
65 :data:`sys.stdout`.
66
67 Returns:
68 :data:`True` if all of the files are valid, or :data:`False` if any of
69 the files do not meet the MRC format specification in any way.
70
71 Raises:
72 :exc:`OSError`: If one of the files does not exist or cannot be opened.
73
74 Warns:
75 RuntimeWarning: If one of the files is seriously invalid because it has
76 no map ID string, an incorrect machine stamp, an unknown mode
77 number, or is not the same size as expected from the header.
78 """
79 result = True
80 for name in names:
81 if not validate(name, print_file):
82 result = False
83 return result
84
85
86 def validate(name, print_file=None):
87 """Validate an MRC file.
88
89 This function first opens the file by calling :func:`~mrcfile.open` (with
90 ``permissive=True``), then calls :meth:`~mrcfile.mrcfile.MrcFile.validate`,
91 which runs a series of tests to check whether the file complies with the
92 MRC2014 format specification.
93
94 If the file is completely valid, this function returns :data:`True`,
95 otherwise it returns :data:`False`. Messages explaining the validation
96 result will be printed to :data:`sys.stdout` by default, but if a text
97 stream is given (using the ``print_file`` argument) output will be printed
98 to that instead.
99
100 Badly invalid files will also cause :mod:`warning <warnings>` messages to
101 be issued, which will be written to :data:`sys.stderr` by default. See the
102 documentation of the :mod:`warnings` module for information on how to
103 suppress or capture warning output.
104
105 Because the file is opened by calling :func:`open`, gzip- and
106 bzip2-compressed MRC files can be validated easily using this function.
107
108 After the file has been opened, it is checked for problems. The tests are:
109
110 #. MRC format ID string: The ``map`` field in the header should contain
111 "MAP ".
112 #. Machine stamp: The machine stamp should contain one of
113 ``0x44 0x44 0x00 0x00``, ``0x44 0x41 0x00 0x00`` or
114 ``0x11 0x11 0x00 0x00``.
115 #. MRC mode: the ``mode`` field should be one of the supported mode
116 numbers: 0, 1, 2, 4, 6 or 12. (Note that MRC modes 3 and 101 are also
117 valid according to the MRC 2014 specification but are not supported by
118 mrcfile.)
119 #. Map and cell dimensions: The header fields ``nx``, ``ny``, ``nz``,
120 ``mx``, ``my``, ``mz``, ``cella.x``, ``cella.y`` and ``cella.z`` must
121 all be positive numbers.
122 #. Axis mapping: Header fields ``mapc``, ``mapr`` and ``maps`` must contain
123 the values 1, 2, and 3 (in any order).
124 #. Volume stack dimensions: If the spacegroup is in the range 401--630,
125 representing a volume stack, the ``nz`` field should be exactly
126 divisible by ``mz`` to represent the number of volumes in the stack.
127 #. Header labels: The ``nlabl`` field should be set to indicate the number
128 of labels in use, and the labels in use should appear first in the label
129 array.
130 #. MRC format version: The ``nversion`` field should be 20140 or 20141 for
131 compliance with the MRC2014 standard.
132 #. Extended header type: If an extended header is present, the ``exttyp``
133 field should be set to indicate the type of extended header.
134 #. Data statistics: The statistics in the header should be correct for the
135 actual data in the file, or marked as undetermined.
136 #. File size: The size of the file on disk should match the expected size
137 calculated from the MRC header.
138
139 Args:
140 name: The file name to open and validate.
141 print_file: The output text stream to use for printing messages about
142 the validation. This is passed directly to the ``file`` argument of
143 Python's :func:`print` function. The default is :data:`None`, which
144 means output will be printed to :data:`sys.stdout`.
145
146 Returns:
147 :data:`True` if the file is valid, or :data:`False` if the file does
148 not meet the MRC format specification in any way.
149
150 Raises:
151 :exc:`OSError`: If the file does not exist or cannot be opened.
152
153 Warns:
154 RuntimeWarning: If the file is seriously invalid because it has no map
155 ID string, an incorrect machine stamp, an unknown mode number, or
156 is not the same size as expected from the header.
157 """
158 print("Checking if {} is a valid MRC2014 file...".format(name), file=print_file)
159 try:
160 with load_functions.open(name, permissive=True) as mrc:
161 result = mrc.validate(print_file=print_file)
162 except Exception:
163 result = False
164 traceback.print_exc(file=print_file)
165 if result:
166 print("File appears to be valid.", file=print_file)
167 return result
168
169
170 if __name__ == '__main__':
171 sys.exit(main())