| 1 |
# Copyright (c) 2016, Science and Technology Facilities Council |
| 2 |
# This software is distributed under a BSD licence. See LICENSE.txt. |
| 3 |
""" |
| 4 |
mrcinterpreter |
| 5 |
-------------- |
| 6 |
|
| 7 |
Module which exports the :class:`MrcInterpreter` class. |
| 8 |
|
| 9 |
Classes: |
| 10 |
:class:`MrcInterpreter`: An object which can interpret an I/O stream as MRC |
| 11 |
data. |
| 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 warnings |
| 20 |
|
| 21 |
import numpy as np |
| 22 |
|
| 23 |
from . import utils |
| 24 |
from .dtypes import HEADER_DTYPE |
| 25 |
from .mrcobject import MrcObject |
| 26 |
from .constants import MAP_ID |
| 27 |
|
| 28 |
|
| 29 |
class MrcInterpreter(MrcObject): |
| 30 |
|
| 31 |
"""An object which interprets an I/O stream as MRC / CCP4 map data. |
| 32 |
|
| 33 |
The header and data are handled as numpy arrays - see |
| 34 |
:class:`~mrcfile.mrcobject.MrcObject` for details. |
| 35 |
|
| 36 |
:class:`MrcInterpreter` can be used directly, but it is mostly intended as |
| 37 |
a superclass to provide common stream-handling functionality. This can be |
| 38 |
used by subclasses which will handle opening and closing the stream. |
| 39 |
|
| 40 |
This class implements the :meth:`~object.__enter__` and |
| 41 |
:meth:`~object.__exit__` special methods which allow it to be used by the |
| 42 |
Python context manager in a :keyword:`with` block. This ensures that |
| 43 |
:meth:`close` is called after the object is finished with. |
| 44 |
|
| 45 |
When reading the I/O stream, a :exc:`ValueError` is raised if the data is |
| 46 |
invalid in one of the following ways: |
| 47 |
|
| 48 |
#. The header's ``map`` field is not set correctly to confirm the file |
| 49 |
type. |
| 50 |
#. The machine stamp is invalid and so the data's byte order cannot be |
| 51 |
determined. |
| 52 |
#. The mode number is not recognised. Currently accepted modes are 0, 1, 2, |
| 53 |
4 and 6. |
| 54 |
#. The file is not large enough for the specified extended header size. |
| 55 |
#. The data block is not large enough for the specified data type and |
| 56 |
dimensions. |
| 57 |
|
| 58 |
:class:`MrcInterpreter` offers a permissive read mode for handling |
| 59 |
problematic files. If ``permissive`` is set to :data:`True` and any of the |
| 60 |
validity checks fails, a :mod:`warning <warnings>` is issued instead of an |
| 61 |
exception, and file interpretation continues. If the mode number is invalid |
| 62 |
or the data block is too small, the |
| 63 |
:attr:`~mrcfile.mrcobject.MrcObject.data` attribute will be set to |
| 64 |
:data:`None`. In this case, it might be possible to inspect and correct the |
| 65 |
header, and then call :meth:`_read` again to read the data correctly. See |
| 66 |
the :doc:`usage guide <../usage_guide>` for more details. |
| 67 |
|
| 68 |
Methods: |
| 69 |
|
| 70 |
* :meth:`flush` |
| 71 |
* :meth:`close` |
| 72 |
|
| 73 |
Methods relevant to subclasses: |
| 74 |
|
| 75 |
* :meth:`_read` |
| 76 |
* :meth:`_read_data` |
| 77 |
* :meth:`_read_bytearray_from_stream` |
| 78 |
|
| 79 |
""" |
| 80 |
|
| 81 |
def __init__(self, iostream=None, permissive=False, header_only=False, |
| 82 |
**kwargs): |
| 83 |
"""Initialise a new MrcInterpreter object. |
| 84 |
|
| 85 |
This initialiser reads the stream if it is given. In general, |
| 86 |
subclasses should call :meth:`__init__` without giving an ``iostream`` |
| 87 |
argument, then set the ``_iostream`` attribute themselves and call |
| 88 |
:meth:`_read` when ready. |
| 89 |
|
| 90 |
To use the MrcInterpreter class directly, pass a stream when creating |
| 91 |
the object (or for a write-only stream, create an MrcInterpreter with |
| 92 |
no stream, call :meth:`._create_default_attributes` and set the |
| 93 |
``_iostream`` attribute directly). |
| 94 |
|
| 95 |
Args: |
| 96 |
iostream: The I/O stream to use to read and write MRC data. The |
| 97 |
default is :data:`None`. |
| 98 |
permissive: Read the stream in permissive mode. The default is |
| 99 |
:data:`False`. |
| 100 |
header_only: Only read the header (and extended header) from the |
| 101 |
file. The default is :data:`False`. |
| 102 |
|
| 103 |
Raises: |
| 104 |
:exc:`ValueError`: If ``iostream`` is given, the data it contains |
| 105 |
cannot be interpreted as a valid MRC file and ``permissive`` |
| 106 |
is :data:`False`. |
| 107 |
|
| 108 |
Warns: |
| 109 |
RuntimeWarning: If ``iostream`` is given, the data it contains |
| 110 |
cannot be interpreted as a valid MRC file and ``permissive`` |
| 111 |
is :data:`True`. |
| 112 |
""" |
| 113 |
super(MrcInterpreter, self).__init__(**kwargs) |
| 114 |
|
| 115 |
self._iostream = iostream |
| 116 |
self._permissive = permissive |
| 117 |
|
| 118 |
# If iostream is given, initialise by reading it |
| 119 |
if self._iostream is not None: |
| 120 |
self._read(header_only) |
| 121 |
|
| 122 |
def __enter__(self): |
| 123 |
"""Called by the context manager at the start of a :keyword:`with` |
| 124 |
block. |
| 125 |
|
| 126 |
Returns: |
| 127 |
This object (``self``). |
| 128 |
""" |
| 129 |
return self |
| 130 |
|
| 131 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 132 |
"""Called by the context manager at the end of a :keyword:`with` |
| 133 |
block. |
| 134 |
|
| 135 |
This ensures that the :meth:`close` method is called. |
| 136 |
""" |
| 137 |
self.close() |
| 138 |
|
| 139 |
def __del__(self): |
| 140 |
"""Attempt to flush the stream when this object is garbage collected. |
| 141 |
|
| 142 |
It's better not to rely on this - instead, use a :keyword:`with` |
| 143 |
block or explicitly call the :meth:`close` method. |
| 144 |
""" |
| 145 |
try: |
| 146 |
self.close() |
| 147 |
except Exception: |
| 148 |
pass |
| 149 |
|
| 150 |
def _read(self, header_only=False): |
| 151 |
"""Read the header, extended header and data from the I/O stream. |
| 152 |
|
| 153 |
Before calling this method, the stream should be open and positioned at |
| 154 |
the start of the header. This method will advance the stream to the end |
| 155 |
of the data block (or the end of the extended header if ``header_only`` |
| 156 |
is :data:`True`. |
| 157 |
|
| 158 |
Args: |
| 159 |
header_only: Only read the header and extended header from the |
| 160 |
stream. The default is :data:`False`. |
| 161 |
|
| 162 |
Raises: |
| 163 |
:exc:`ValueError`: If the data in the stream cannot be interpreted |
| 164 |
as a valid MRC file and ``permissive`` is :data:`False`. |
| 165 |
|
| 166 |
Warns: |
| 167 |
RuntimeWarning: If the data in the stream cannot be interpreted |
| 168 |
as a valid MRC file and ``permissive`` is :data:`True`. |
| 169 |
""" |
| 170 |
self._read_header() |
| 171 |
self._read_extended_header() |
| 172 |
if not header_only: |
| 173 |
self._read_data() |
| 174 |
|
| 175 |
def _read_header(self): |
| 176 |
"""Read the MRC header from the I/O stream. |
| 177 |
|
| 178 |
The header will be read from the current stream position, and the |
| 179 |
stream will be advanced by 1024 bytes. |
| 180 |
|
| 181 |
Raises: |
| 182 |
:exc:`ValueError`: If the data in the stream cannot be interpreted |
| 183 |
as a valid MRC file and ``permissive`` is :data:`False`. |
| 184 |
|
| 185 |
Warns: |
| 186 |
RuntimeWarning: If the data in the stream cannot be interpreted |
| 187 |
as a valid MRC file and ``permissive`` is :data:`True`. |
| 188 |
""" |
| 189 |
# Read 1024 bytes from the stream |
| 190 |
header_arr, bytes_read = self._read_bytearray_from_stream(HEADER_DTYPE.itemsize) |
| 191 |
if bytes_read < HEADER_DTYPE.itemsize: |
| 192 |
raise ValueError("Couldn't read enough bytes for MRC header") |
| 193 |
|
| 194 |
# Use a recarray to allow access to fields as attributes |
| 195 |
# (e.g. header.mode instead of header['mode']) |
| 196 |
header = np.frombuffer(header_arr, dtype=HEADER_DTYPE).reshape(()).view(np.recarray) |
| 197 |
|
| 198 |
# Check the map ID to make sure this is an MRC file. The full map ID |
| 199 |
# should be 'MAP ', but we check only the first three bytes because |
| 200 |
# this is the form specified in the MRC2014 paper and is used by some |
| 201 |
# other software. |
| 202 |
if bytes(header.map)[:3] != MAP_ID[:3]: |
| 203 |
msg = ("Map ID string not found - " |
| 204 |
"not an MRC file, or file is corrupt") |
| 205 |
if self._permissive: |
| 206 |
warnings.warn(msg, RuntimeWarning) |
| 207 |
else: |
| 208 |
raise ValueError(msg) |
| 209 |
|
| 210 |
# Read the machine stamp to get the file's byte order |
| 211 |
try: |
| 212 |
byte_order = utils.byte_order_from_machine_stamp(header.machst) |
| 213 |
except ValueError as err: |
| 214 |
if self._permissive: |
| 215 |
byte_order = '<' # try little-endian as a sensible default |
| 216 |
warnings.warn(str(err), RuntimeWarning) |
| 217 |
else: |
| 218 |
raise |
| 219 |
|
| 220 |
# Create a new dtype with the correct byte order and update the header |
| 221 |
header.dtype = header.dtype.newbyteorder(byte_order) |
| 222 |
|
| 223 |
# Check mode is valid; if not, try the opposite byte order |
| 224 |
# (Some MRC files have been seen 'in the wild' that are correct except |
| 225 |
# that the machine stamp indicates the wrong byte order.) |
| 226 |
if self._permissive: |
| 227 |
try: |
| 228 |
utils.dtype_from_mode(header.mode) |
| 229 |
except ValueError: |
| 230 |
try: |
| 231 |
opp_mode = header.mode.view(header.mode.dtype.newbyteorder()) |
| 232 |
utils.dtype_from_mode(opp_mode) |
| 233 |
# If we get here the new byte order is probably correct |
| 234 |
# Use it and issue a warning |
| 235 |
header.dtype = header.dtype.newbyteorder() |
| 236 |
pretty_machst = utils.pretty_machine_stamp(header.machst) |
| 237 |
msg = "Machine stamp '{0}' does not match the apparent byte order '{1}'" |
| 238 |
warnings.warn(msg.format(pretty_machst, header.mode.dtype.byteorder), |
| 239 |
RuntimeWarning) |
| 240 |
except ValueError: |
| 241 |
# Neither byte order gives a valid mode. Ignore for now, |
| 242 |
# and a warning will be issued by _read_data() |
| 243 |
pass |
| 244 |
|
| 245 |
header.flags.writeable = not self._read_only |
| 246 |
self._header = header |
| 247 |
|
| 248 |
def _read_extended_header(self): |
| 249 |
"""Read the extended header from the stream. |
| 250 |
|
| 251 |
If there is no extended header, a zero-length array is assigned to the |
| 252 |
extended_header attribute. |
| 253 |
|
| 254 |
The dtype is set as void (``'V1'``). |
| 255 |
|
| 256 |
Raises: |
| 257 |
:exc:`ValueError`: If the stream is not long enough to contain the |
| 258 |
extended header indicated by the header and ``permissive`` |
| 259 |
is :data:`False`. |
| 260 |
|
| 261 |
Warns: |
| 262 |
RuntimeWarning: If the stream is not long enough to contain the |
| 263 |
extended header indicated by the header and ``permissive`` |
| 264 |
is :data:`True`. |
| 265 |
""" |
| 266 |
ext_header_arr, bytes_read = self._read_bytearray_from_stream(int(self.header.nsymbt)) |
| 267 |
|
| 268 |
if bytes_read < self.header.nsymbt: |
| 269 |
msg = ("Expected {0} bytes in extended header but could only read {1}" |
| 270 |
.format(self.header.nsymbt, bytes_read)) |
| 271 |
if self._permissive: |
| 272 |
warnings.warn(msg, RuntimeWarning) |
| 273 |
self._extended_header = None |
| 274 |
return |
| 275 |
else: |
| 276 |
raise ValueError(msg) |
| 277 |
|
| 278 |
self._extended_header = np.frombuffer(ext_header_arr, dtype='V1') |
| 279 |
|
| 280 |
self._extended_header.flags.writeable = not self._read_only |
| 281 |
|
| 282 |
def _read_data(self, max_bytes=0): |
| 283 |
"""Read the data array from the stream. |
| 284 |
|
| 285 |
This method uses information from the header to set the data array's |
| 286 |
shape and dtype. |
| 287 |
|
| 288 |
Args: |
| 289 |
max_bytes: Read at most this many bytes from the stream. If zero or |
| 290 |
negative, the full size of the data block as defined in the header |
| 291 |
will be read, even if this is very large. |
| 292 |
|
| 293 |
Raises: |
| 294 |
:exc:`ValueError`: If the stream is not long enough to contain the |
| 295 |
data indicated by the header and ``permissive`` is |
| 296 |
:data:`False`. |
| 297 |
|
| 298 |
Warns: |
| 299 |
RuntimeWarning: If the stream is not long enough to contain the |
| 300 |
data indicated by the header and ``permissive`` is |
| 301 |
:data:`True`. |
| 302 |
""" |
| 303 |
try: |
| 304 |
dtype = utils.data_dtype_from_header(self.header) |
| 305 |
except ValueError as err: |
| 306 |
if self._permissive: |
| 307 |
warnings.warn("{0} - data block cannot be read".format(err), |
| 308 |
RuntimeWarning) |
| 309 |
self._data = None |
| 310 |
return |
| 311 |
else: |
| 312 |
raise |
| 313 |
|
| 314 |
shape = utils.data_shape_from_header(self.header) |
| 315 |
|
| 316 |
nbytes = dtype.itemsize |
| 317 |
for axis_length in shape: |
| 318 |
nbytes *= axis_length |
| 319 |
|
| 320 |
if max_bytes > 0 and nbytes > max_bytes: |
| 321 |
msg = ("Expected {0} bytes in data block but limit is {1}" |
| 322 |
.format(nbytes, max_bytes)) |
| 323 |
if self._permissive: |
| 324 |
warnings.warn(msg, RuntimeWarning) |
| 325 |
self._data = None |
| 326 |
return |
| 327 |
else: |
| 328 |
raise ValueError(msg) |
| 329 |
|
| 330 |
data_arr, bytes_read = self._read_bytearray_from_stream(nbytes) |
| 331 |
|
| 332 |
if bytes_read < nbytes: |
| 333 |
msg = ("Expected {0} bytes in data block but could only read {1}" |
| 334 |
.format(nbytes, bytes_read)) |
| 335 |
if self._permissive: |
| 336 |
warnings.warn(msg, RuntimeWarning) |
| 337 |
self._data = None |
| 338 |
return |
| 339 |
else: |
| 340 |
raise ValueError(msg) |
| 341 |
|
| 342 |
self._data = np.frombuffer(data_arr, dtype=dtype).reshape(shape) |
| 343 |
self._data.flags.writeable = not self._read_only |
| 344 |
|
| 345 |
def _read_bytearray_from_stream(self, number_of_bytes): |
| 346 |
"""Read a :class:`bytearray` from the stream. |
| 347 |
|
| 348 |
This default implementation relies on the stream implementing the |
| 349 |
:meth:`~io.BufferedIOBase.readinto` method to avoid copying the new |
| 350 |
array while creating the mutable :class:`bytearray`. Subclasses |
| 351 |
should override this if their stream does not support |
| 352 |
:meth:`~io.BufferedIOBase.readinto`. |
| 353 |
|
| 354 |
Returns: |
| 355 |
A 2-tuple of the :class:`bytearray` and the number of bytes that |
| 356 |
were read from the stream. |
| 357 |
""" |
| 358 |
result_array = bytearray(number_of_bytes) |
| 359 |
bytes_read = self._iostream.readinto(result_array) |
| 360 |
return result_array, bytes_read |
| 361 |
|
| 362 |
def close(self): |
| 363 |
"""Flush to the stream and clear the header and data attributes.""" |
| 364 |
if self._header is not None and not self._iostream.closed: |
| 365 |
self.flush() |
| 366 |
self._header = None |
| 367 |
self._extended_header = None |
| 368 |
self._close_data() |
| 369 |
|
| 370 |
def flush(self): |
| 371 |
"""Flush the header and data arrays to the I/O stream. |
| 372 |
|
| 373 |
This implementation seeks to the start of the stream, writes the |
| 374 |
header, extended header and data arrays, and then truncates the stream. |
| 375 |
|
| 376 |
Subclasses should override this implementation for streams which do not |
| 377 |
support :meth:`~io.IOBase.seek` or :meth:`~io.IOBase.truncate`. |
| 378 |
""" |
| 379 |
if not self._read_only: |
| 380 |
self._iostream.seek(0) |
| 381 |
self._iostream.write(self.header) |
| 382 |
self._iostream.write(self.extended_header) |
| 383 |
self._iostream.write(np.ascontiguousarray(self.data)) |
| 384 |
self._iostream.truncate() |
| 385 |
self._iostream.flush() |