Debian Codegraph @

mrcfile/mrcfile.py

raw
1 # Copyright (c) 2016, Science and Technology Facilities Council
2 # This software is distributed under a BSD licence. See LICENSE.txt.
3 """
4 mrcfile
5 -------
6
7 Module which exports the :class:`MrcFile` class.
8
9 Classes:
10 :class:`MrcFile`: An object which represents an MRC file.
11
12 """
13
14 # Import Python 3 features for future-proofing
15 from __future__ import (absolute_import, division, print_function,
16 unicode_literals)
17
18
19 import os
20 import warnings
21
22 from .mrcinterpreter import MrcInterpreter
23
24
25 class MrcFile(MrcInterpreter):
26
27 """An object which represents an MRC file.
28
29 The header and data are handled as numpy arrays - see
30 :class:`~mrcfile.mrcobject.MrcObject` for details.
31
32 :class:`MrcFile` supports a permissive read mode for attempting to open
33 corrupt or invalid files. See
34 :class:`mrcfile.mrcinterpreter.MrcInterpreter` or the :doc:`usage guide
35 <../usage_guide>` for more information.
36
37 Usage:
38 To create a new MrcFile object, pass a file name and optional mode. To
39 ensure the file is written to disk and closed correctly, it's best to
40 use the :keyword:`with` statement:
41
42 >>> with MrcFile('tmp.mrc', 'w+') as mrc:
43 ... mrc.set_data(np.zeros((10, 10), dtype=np.int8))
44
45 In mode ``r`` or ``r+``, the named file is opened from disk and read.
46 In mode ``w+`` a new empty file is created and will be written to disk
47 at the end of the :keyword:`with` block (or when
48 :meth:`~.MrcInterpreter.flush` or :meth:`close` is called).
49
50 """
51
52 def __init__(self, name, mode='r', overwrite=False, permissive=False,
53 header_only=False, **kwargs):
54 """Initialise a new :class:`MrcFile` object.
55
56 The given file name is opened in the given mode. For mode ``r`` or
57 ``r+`` the header, extended header and data are read from the file. For
58 mode ``w+`` a new file is created with a default header and empty
59 extended header and data arrays.
60
61 Args:
62 name: The file name to open, as a string or pathlib Path.
63 mode: The file mode to use. This should be one of the following:
64 ``r`` for read-only, ``r+`` for read and write, or ``w+`` for a
65 new empty file. The default is ``r``.
66 overwrite: Flag to force overwriting of an existing file if the
67 mode is ``w+``. If :data:`False` and a file of the same name
68 already exists, the file is not overwritten and an exception is
69 raised. The default is :data:`False`.
70 permissive: Read the file in permissive mode. (See
71 :class:`mrcfile.mrcinterpreter.MrcInterpreter` for details.)
72 The default is :data:`False`.
73 header_only: Only read the header (and extended header) from the
74 file. The default is :data:`False`.
75
76 Raises:
77 :exc:`ValueError`: If the mode is not one of ``r``, ``r+`` or
78 ``w+``.
79 :exc:`ValueError`: If the file is not a valid MRC file and
80 ``permissive`` is :data:`False`.
81 :exc:`ValueError`: If the mode is ``w+``, the file already exists
82 and overwrite is :data:`False`.
83 :exc:`OSError`: If the mode is ``r`` or ``r+`` and the file does
84 not exist.
85
86 Warns:
87 RuntimeWarning: If the file appears to be a valid MRC file but the
88 data block is longer than expected from the dimensions in the
89 header.
90 RuntimeWarning: If the file is not a valid MRC file and
91 ``permissive`` is :data:`True`.
92 RuntimeWarning: If the header's ``exttyp`` field is set to a known
93 value but the extended header's size is not a multiple of the
94 number of bytes in the corresponding dtype.
95 """
96 super(MrcFile, self).__init__(permissive=permissive, **kwargs)
97
98 if mode not in ['r', 'r+', 'w+']:
99 raise ValueError("Mode '{0}' not supported".format(mode))
100
101 name = str(name) # in case name is a pathlib Path
102 if ('w' in mode and os.path.exists(name) and not overwrite):
103 raise ValueError("File '{0}' already exists; set overwrite=True "
104 "to overwrite it".format(name))
105
106 self._mode = mode
107 self._read_only = (self._mode == 'r')
108
109 self._open_file(name)
110
111 try:
112 if 'w' in mode:
113 self._create_default_attributes()
114 else:
115 self._read(header_only)
116 except Exception:
117 self._close_file()
118 raise
119
120 def __repr__(self):
121 return "MrcFile('{0}', mode='{1}')".format(self._iostream.name,
122 self._mode)
123
124 def _open_file(self, name):
125 """Open a file object to use as the I/O stream."""
126 self._iostream = open(name, self._mode + 'b')
127
128 def _read(self, header_only=False):
129 """Override _read() to move back to start of file first."""
130 self._iostream.seek(0)
131 super(MrcFile, self)._read(header_only)
132
133 def _read_data(self):
134 """Override _read_data() to check file size matches data block size."""
135 file_size = self._get_file_size()
136 # Need to use self.header.nsymbt rather than self.extended_header.nbytes because
137 # self.extended_header might be None in permissive read mode. Need to convert to
138 # Python int (rather than numpy int32) to avoid possible overflow.
139 header_size = self.header.nbytes + int(self.header.nsymbt)
140 remaining_file_size = file_size - header_size
141
142 super(MrcFile, self)._read_data(max_bytes=remaining_file_size)
143
144 # Check if the file is the expected size.
145 if self.data is not None:
146 data_size = self.data.nbytes
147 if data_size < remaining_file_size:
148 msg = ("MRC file is {0} bytes larger than expected"
149 .format(remaining_file_size - data_size))
150 warnings.warn(msg, RuntimeWarning)
151
152 def _get_file_size(self):
153 """Return the size of the underlying file object, in bytes."""
154 pos = self._iostream.tell()
155 self._iostream.seek(0, os.SEEK_END)
156 size = self._iostream.tell()
157 self._iostream.seek(pos, os.SEEK_SET)
158 return size
159
160 def close(self):
161 """Flush any changes to disk and close the file.
162
163 This override calls :meth:`.MrcInterpreter.close` to ensure the stream
164 is flushed and closed, then closes the file object.
165 """
166 super(MrcFile, self).close()
167 self._close_file()
168
169 def _close_file(self):
170 """Close the file object."""
171 self._iostream.close()
172
173 def validate(self, print_file=None):
174 """Validate this MRC file.
175
176 The tests are:
177
178 #. MRC format ID string: The ``map`` field in the header should
179 contain "MAP ".
180 #. Machine stamp: The machine stamp should contain one of
181 ``0x44 0x44 0x00 0x00``, ``0x44 0x41 0x00 0x00`` or
182 ``0x11 0x11 0x00 0x00``.
183 #. MRC mode: the ``mode`` field should be one of the supported mode
184 numbers: 0, 1, 2, 4, 6 or 12. (Note that MRC modes 3 and 101 are
185 also valid according to the MRC 2014 specification but are not
186 supported by mrcfile.)
187 #. Map and cell dimensions: The header fields ``nx``, ``ny``, ``nz``,
188 ``mx``, ``my``, ``mz``, ``cella.x``, ``cella.y`` and ``cella.z``
189 must all be positive numbers.
190 #. Axis mapping: Header fields ``mapc``, ``mapr`` and ``maps`` must
191 contain the values 1, 2, and 3 (in any order).
192 #. Volume stack dimensions: If the spacegroup is in the range 401--630,
193 representing a volume stack, the ``nz`` field should be exactly
194 divisible by ``mz`` to represent the number of volumes in the stack.
195 #. Header labels: The ``nlabl`` field should be set to indicate the
196 number of labels in use, and the labels in use should appear first
197 in the label array.
198 #. MRC format version: The ``nversion`` field should be 20140 or 20141
199 for compliance with the MRC2014 standard.
200 #. Extended header type: If an extended header is present, the
201 ``exttyp`` field should be set to indicate the type of extended
202 header.
203 #. Data statistics: The statistics in the header should be correct for
204 the actual data in the file, or marked as undetermined.
205 #. File size: The size of the file on disk should match the expected
206 size calculated from the MRC header.
207
208 Args:
209 print_file: The output text stream to use for printing messages
210 about the validation. This is passed directly to the ``file``
211 argument of Python's :func:`print` function. The default is
212 :data:`None`, which means output will be printed to
213 :data:`sys.stdout`.
214
215 Returns:
216 :data:`True` if the file is valid, or :data:`False` if the file
217 does not meet the MRC format specification in any way.
218 """
219 valid = super(MrcFile, self).validate(print_file=print_file)
220
221 if self.data is not None:
222 # Check file size
223 file_size = self._get_file_size()
224 mrc_size = (self.header.nbytes
225 + self.extended_header.nbytes
226 + self.data.nbytes)
227 if (file_size != mrc_size):
228 print("File is larger than expected. Actual size: {0} bytes; "
229 "expected size: {1} bytes (calculated from header)"
230 .format(file_size, mrc_size),
231 file=print_file)
232 valid = False
233 else:
234 print("Data block could not be read - file size not checked",
235 file=print_file)
236 valid = False
237
238 return valid