Debian Codegraph @

mrcfile/mrcobject.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 mrcobject
5 ---------
6
7 Module which exports the :class:`MrcObject` class.
8
9 Classes:
10 :class:`MrcObject`: An object representing image or volume data in the MRC
11 format.
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 from datetime import datetime
20 import warnings
21
22 import numpy as np
23
24 from . import utils
25 from .dtypes import (HEADER_DTYPE, VOXEL_SIZE_DTYPE, NSTART_DTYPE,
26 get_ext_header_dtype)
27 from .constants import (MAP_ID, IMAGE_STACK_SPACEGROUP, VOLUME_SPACEGROUP,
28 VOLUME_STACK_SPACEGROUP)
29
30
31 class MrcObject(object):
32
33 """An object representing image or volume data in the MRC format.
34
35 The header, extended header and data are stored as numpy arrays and
36 exposed as read-only attributes. To replace the data or extended header,
37 call :meth:`set_data` or :meth:`set_extended_header`. The header cannot be
38 replaced but can be modified in place.
39
40 Voxel size is exposed as a writeable attribute, but is calculated
41 on-the-fly from the header's ``cella`` and ``mx``/``my``/``mz`` fields.
42
43 Three-dimensional data can represent either a stack of 2D images, or a 3D
44 volume. This is indicated by the header's ``ispg`` (space group) field,
45 which is set to 0 for image data and >= 1 for volume data. The
46 :meth:`is_single_image`, :meth:`is_image_stack`, :meth:`is_volume` and
47 :meth:`is_volume_stack` methods can be used to identify the type of
48 information stored in the data array. For 3D data, the
49 :meth:`set_image_stack` and :meth:`set_volume` methods can be used to
50 switch between image stack and volume interpretations of the data.
51
52 If the data contents have been changed, you can use the
53 :meth:`update_header_from_data` and :meth:`update_header_stats` methods to
54 make the header consistent with the data. These methods are called
55 automatically if the data array is replaced by calling :meth:`set_data`.
56 :meth:`update_header_from_data` is fast, even with very large data arrays,
57 because it only examines the shape and type of the data array.
58 :meth:`update_header_stats` calculates statistics from all items in the
59 data array and so can be slow for very large arrays. If necessary, the
60 :meth:`reset_header_stats` method can be called to set the header fields to
61 indicate that the statistics are undetermined.
62
63 Attributes:
64
65 * :attr:`header`
66 * :attr:`extended_header`
67 * :attr:`indexed_extended_header`
68 * :attr:`data`
69 * :attr:`voxel_size`
70 * :attr:`nstart`
71
72 Methods:
73
74 * :meth:`set_extended_header`
75 * :meth:`set_data`
76 * :meth:`is_single_image`
77 * :meth:`is_image_stack`
78 * :meth:`is_volume`
79 * :meth:`is_volume_stack`
80 * :meth:`set_image_stack`
81 * :meth:`set_volume`
82 * :meth:`update_header_from_data`
83 * :meth:`update_header_stats`
84 * :meth:`reset_header_stats`
85 * :meth:`print_header`
86 * :meth:`get_labels`
87 * :meth:`add_label`
88
89 Attributes and methods relevant to subclasses:
90
91 * ``_read_only``
92 * :meth:`_check_writeable`
93 * :meth:`_create_default_attributes`
94 * :meth:`_close_data`
95 * :meth:`_set_new_data`
96
97 """
98
99 def __init__(self, **kwargs):
100 """Initialise a new :class:`MrcObject`.
101
102 This initialiser deliberately avoids creating any arrays and simply
103 sets the header, extended header and data attributes to :data:`None`.
104 This allows subclasses to call :meth:`__init__` at the start of their
105 initialisers and then set the attributes themselves, probably by
106 reading from a file, or by calling :meth:`_create_default_attributes`
107 for a new empty object.
108
109 Note that this behaviour might change in future: this initialiser could
110 take optional arguments to allow the header and data to be provided
111 by the caller, or might create the standard empty defaults rather than
112 setting the attributes to :data:`None`.
113 """
114 super(MrcObject, self).__init__(**kwargs)
115
116 # Set empty default attributes
117 self._header = None
118 self._extended_header = None
119 self._data = None
120 self._read_only = False
121
122 def _check_writeable(self):
123 """Check that this MRC object is writeable.
124
125 Raises:
126 :exc:`ValueError`: If this object is read-only.
127 """
128 if self._read_only:
129 raise ValueError('MRC object is read-only')
130
131 def _create_default_attributes(self):
132 """Set valid default values for the header and data attributes."""
133 self._create_default_header()
134 self._extended_header = np.empty(0, dtype='V1')
135 self._set_new_data(np.empty(0, dtype=np.int8))
136
137 def _create_default_header(self):
138 """Create a default MRC file header.
139
140 The header is initialised with standard file type and version
141 information, default values for some essential fields, and zeros
142 elsewhere. The first text label is also set to indicate the file was
143 created by this module.
144 """
145 self._header = np.zeros(shape=(), dtype=HEADER_DTYPE).view(np.recarray)
146 header = self._header
147 header.map = MAP_ID
148 header.nversion = 20141 # current MRC 2014 format version
149 header.machst = utils.machine_stamp_from_byte_order(header.mode.dtype.byteorder)
150
151 # Default space group is P1
152 header.ispg = VOLUME_SPACEGROUP
153
154 # Standard cell angles all 90.0 degrees
155 default_cell_angle = 90.0
156 header.cellb.alpha = default_cell_angle
157 header.cellb.beta = default_cell_angle
158 header.cellb.gamma = default_cell_angle
159 # (this can also be achieved by assigning a 3-tuple to header.cellb
160 # directly but using the sub-fields individually is easier to read and
161 # understand)
162
163 # Standard axes: columns = X, rows = Y, sections = Z
164 header.mapc = 1
165 header.mapr = 2
166 header.maps = 3
167
168 time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
169 header.label[0] = '{0:40s}{1:>39s} '.format('Created by mrcfile.py',
170 time)
171 header.nlabl = 1
172
173 self.reset_header_stats()
174
175 @property
176 def header(self):
177 """Get the header as a :class:`numpy record array <numpy.recarray>`."""
178 return self._header
179
180 @property
181 def extended_header(self):
182 """Get the extended header as a :class:`numpy array <numpy.ndarray>`.
183
184 The dtype will be void (raw data, dtype ``V'``). If the actual data type
185 of the extended header is known, the dtype of the array can be changed
186 to match. For supported types (e.g. ``'FEI1'`` and ``'FEI2'``), the
187 indexed part of the extended header (excluding any zero padding) can be
188 accessed using :meth:`indexed_extended_header`.
189
190 The extended header may be modified in place. To replace it completely,
191 call :meth:`set_extended_header`.
192 """
193 return self._extended_header
194
195 @property
196 def indexed_extended_header(self):
197 """Get the indexed part of the extended header as a
198 :class:`numpy array <numpy.ndarray>` with the appropriate dtype set.
199
200 Currently only ``'FEI1'`` and ``'FEI2'`` extended headers are supported.
201 Modifications to the indexed extended header will not change the
202 extended header data recorded in this :class:`MrcObject`. If the
203 extended header type is unrecognised or extended header data is not of
204 sufficient length a warning will be produced and the indexed extended
205 header will be None.
206 """
207 # Use the header's byte order for the extended header
208 dtype = get_ext_header_dtype(self.header.exttyp,
209 self.header.mode.dtype.byteorder)
210
211 # Interpret one element
212 try:
213 if self.extended_header.nbytes < dtype.itemsize:
214 raise ValueError
215 first = self.extended_header[0:dtype.itemsize]
216 first.dtype = dtype
217 if first["Metadata size"][0] != dtype.itemsize:
218 raise ValueError
219 except ValueError:
220 warnings.warn("The header has exttyp '{}' but the extended header "
221 "cannot be interpreted as that type"
222 .format(self.header.exttyp), RuntimeWarning)
223 return None
224
225 nbytes = int(self.header["nz"]) * dtype.itemsize
226 try:
227 if self.extended_header.nbytes < nbytes:
228 raise ValueError
229 full = self.extended_header[0:nbytes]
230 full.dtype = dtype
231 except ValueError:
232 warnings.warn("The header has exttyp '{}' but the extended header "
233 "cannot be interpreted as that type"
234 .format(self.header.exttyp), RuntimeWarning)
235 return None
236
237 return full
238
239 def set_extended_header(self, extended_header):
240 """Replace the extended header.
241
242 If you set the extended header you should also set the
243 ``header.exttyp`` field to indicate the type of extended header.
244
245 Raises:
246 :exc:`ValueError`: If the new extended header has more than
247 2,147,483,647 bytes (and therefore its size cannot be stored
248 in the header).
249 """
250 self._check_writeable()
251 if extended_header.nbytes > np.iinfo(np.int32).max:
252 raise ValueError("New extended header is too large! It has {} "
253 "bytes. The maximum allowed is {}."
254 .format(extended_header.nbytes,
255 np.iinfo(np.int32).max))
256 self._extended_header = extended_header
257 self.header.nsymbt = extended_header.nbytes
258
259 @property
260 def data(self):
261 """Get the data as a :class:`numpy array <numpy.ndarray>`."""
262 return self._data
263
264 def set_data(self, data):
265 """Replace the data array.
266
267 This replaces the current data with the given array (or a copy of it),
268 and updates the header to match the new data dimensions. The data
269 statistics (min, max, mean and rms) stored in the header will also be
270 updated.
271
272 Raises:
273 :exc:`ValueError`: if the new data has a dimension larger than
274 2,147,483,647 (and therefore its size cannot be stored in the
275 header).
276
277 Warns:
278 RuntimeWarning: If the data array contains Inf or NaN values.
279 """
280 self._check_writeable()
281
282 # Check if the new data's dtype is valid without changes
283 mode = utils.mode_from_dtype(data.dtype)
284 new_dtype = (utils.dtype_from_mode(mode)
285 .newbyteorder(data.dtype.byteorder))
286
287 for dim in data.shape:
288 if dim > np.iinfo(np.int32).max:
289 raise ValueError("New data array is too large! Found a "
290 "dimension of size {}. The maximum allowed "
291 "is {}."
292 .format(dim, np.iinfo(np.int32).max))
293
294 # Set new_dtype to None if it is the same type as the original array,
295 # to avoid numpy >= 1.24 copying the array unnecessarily
296 if new_dtype == data.dtype:
297 new_dtype = None
298
299 # Copy the data if necessary to ensure correct dtype and C ordering
300 new_data = np.ascontiguousarray(data, dtype=new_dtype)
301
302 # Replace the old data array with the new one, and update the header
303 self._close_data()
304 self._set_new_data(new_data)
305 self.update_header_from_data()
306 self.update_header_stats()
307
308 def _close_data(self):
309 """Close the data array."""
310 self._data = None
311
312 def _set_new_data(self, data):
313 """Replace the data array with a new one.
314
315 The new data array is not checked - it must already be valid for use in
316 an MRC file.
317 """
318 self._data = data
319
320 @property
321 def voxel_size(self):
322 """Get or set the voxel size in angstroms.
323
324 The voxel size is returned as a structured NumPy :class:`record array
325 <numpy.recarray>` with three fields (x, y and z). For example:
326
327 >>> mrc.voxel_size
328 rec.array((0.44825, 0.3925, 0.45874998),
329 dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4')])
330 >>> mrc.voxel_size.x
331 array(0.44825, dtype=float32)
332
333 Note that changing the voxel_size array in-place will *not* change the
334 voxel size in the file -- to prevent this being overlooked
335 accidentally, the writeable flag is set to :data:`False` on the
336 voxel_size array.
337
338 To set the voxel size, assign a new value to the voxel_size attribute.
339 You may give a single number, a 3-tuple ``(x, y ,z)`` or a modified
340 version of the voxel_size array. The following examples are all
341 equivalent:
342
343 >>> mrc.voxel_size = 1.0
344
345 >>> mrc.voxel_size = (1.0, 1.0, 1.0)
346
347 >>> vox_sizes = mrc.voxel_size
348 >>> vox_sizes.flags.writeable = True
349 >>> vox_sizes.x = 1.0
350 >>> vox_sizes.y = 1.0
351 >>> vox_sizes.z = 1.0
352 >>> mrc.voxel_size = vox_sizes
353 """
354 x = self.header.cella.x / self.header.mx
355 y = self.header.cella.y / self.header.my
356 z = self.header.cella.z / self.header.mz
357 sizes = np.rec.array((x, y, z), VOXEL_SIZE_DTYPE)
358 sizes.flags.writeable = False
359 return sizes
360
361 @voxel_size.setter
362 def voxel_size(self, voxel_size):
363 self._check_writeable()
364 try:
365 # First, assume we have a single numeric value
366 sizes = (float(voxel_size),) * 3
367 except TypeError:
368 try:
369 # Not a single value. Next, if voxel_size is an array (as
370 # produced by the voxel_size getter), item() gives a 3-tuple
371 sizes = voxel_size.item()
372 except AttributeError:
373 # If the item() method doesn't exist, assume we have a 3-tuple
374 sizes = voxel_size
375 self._set_voxel_size(*sizes)
376
377 def _set_voxel_size(self, x_size, y_size, z_size):
378 """Set the voxel size.
379
380 Args:
381 x_size: The voxel size in the X direction, in angstroms
382 y_size: The voxel size in the Y direction, in angstroms
383 z_size: The voxel size in the Z direction, in angstroms
384 """
385 self.header.cella.x = x_size * self.header.mx
386 self.header.cella.y = y_size * self.header.my
387 self.header.cella.z = z_size * self.header.mz
388
389 @property
390 def nstart(self):
391 """Get or set the grid start locations.
392
393 This provides a convenient way to get and set the values of the
394 header's ``nxstart``, ``nystart`` and ``nzstart`` fields. Note that
395 these fields are integers and are measured in voxels, not angstroms.
396 The start locations are returned as a structured NumPy :class:`record
397 array <numpy.recarray>` with three fields (x, y and z). For example:
398
399 >>> mrc.header.nxstart
400 array(0, dtype=int32)
401 >>> mrc.header.nystart
402 array(-21, dtype=int32)
403 >>> mrc.header.nzstart
404 array(-12, dtype=int32)
405 >>> mrc.nstart
406 rec.array((0, -21, -12),
407 dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])
408 >>> mrc.nstart.y
409 array(-21, dtype=int32)
410
411 Note that changing the nstart array in-place will *not* change the
412 values in the file -- to prevent this being overlooked accidentally,
413 the writeable flag is set to :data:`False` on the nstart array.
414
415 To set the start locations, assign a new value to the nstart
416 attribute. You may give a single number, a 3-tuple ``(x, y ,z)`` or a
417 modified version of the nstart array. The following examples are all
418 equivalent:
419
420 >>> mrc.nstart = -150
421
422 >>> mrc.nstart = (-150, -150, -150)
423
424 >>> starts = mrc.nstart
425 >>> starts.flags.writeable = True
426 >>> starts.x = -150
427 >>> starts.y = -150
428 >>> starts.z = -150
429 >>> mrc.nstart = starts
430 """
431 x = self.header.nxstart
432 y = self.header.nystart
433 z = self.header.nzstart
434 nstart = np.rec.array((x, y, z), NSTART_DTYPE)
435 nstart.flags.writeable = False
436 return nstart
437
438 @nstart.setter
439 def nstart(self, nstart):
440 self._check_writeable()
441 try:
442 # First, assume we have a single numeric value
443 starts = (int(nstart),) * 3
444 except TypeError:
445 try:
446 # Not a single value. Next, if nstart is an array (as
447 # produced by the nstart getter), item() gives a 3-tuple
448 starts = nstart.item()
449 except AttributeError:
450 # If the item() method doesn't exist, assume we have a 3-tuple
451 starts = nstart
452 self._set_nstart(*starts)
453
454 def _set_nstart(self, nxstart, nystart, nzstart):
455 """Set the grid start locations.
456
457 Args:
458 nxstart: The location of the first column in the unit cell
459 nystart: The location of the first row in the unit cell
460 nzstart: The location of the first section in the unit cell
461 """
462 self.header.nxstart = nxstart
463 self.header.nystart = nystart
464 self.header.nzstart = nzstart
465
466 def is_single_image(self):
467 """Identify whether the file represents a single image.
468
469 Returns:
470 :data:`True` if the data array is two-dimensional.
471 """
472 return self.data.ndim == 2
473
474 def is_image_stack(self):
475 """Identify whether the file represents a stack of images.
476
477 Returns:
478 :data:`True` if the data array is three-dimensional and the space group
479 is zero.
480 """
481 return (self.data.ndim == 3
482 and self.header.ispg == IMAGE_STACK_SPACEGROUP)
483
484 def is_volume(self):
485 """Identify whether the file represents a volume.
486
487 Returns:
488 :data:`True` if the data array is three-dimensional and the space
489 group is not zero.
490 """
491 return (self.data.ndim == 3
492 and self.header.ispg != IMAGE_STACK_SPACEGROUP)
493
494 def is_volume_stack(self):
495 """Identify whether the file represents a stack of volumes.
496
497 Returns:
498 :data:`True` if the data array is four-dimensional.
499 """
500 return self.data.ndim == 4
501
502 def set_image_stack(self):
503 """Change three-dimensional data to represent an image stack.
504
505 This method changes the space group number (``header.ispg``) to zero.
506
507 Raises:
508 :exc:`ValueError`: If the data array is not three-dimensional.
509 """
510 self._check_writeable()
511 if self.data.ndim != 3:
512 raise ValueError('Only 3D data can be changed into an image stack')
513 self.header.ispg = IMAGE_STACK_SPACEGROUP
514 self.header.mz = 1
515
516 def set_volume(self):
517 """Change three-dimensional data to represent a volume.
518
519 If the space group was previously zero (representing an image stack),
520 this method sets it to one. Otherwise the space group is not changed.
521
522 Raises:
523 :exc:`ValueError`: If the data array is not three-dimensional.
524 """
525 self._check_writeable()
526 if self.data.ndim != 3:
527 raise ValueError('Only 3D data can be changed into a volume')
528 if self.is_image_stack():
529 self.header.ispg = VOLUME_SPACEGROUP
530 self.header.mz = self.header.nz
531
532 def update_header_from_data(self):
533 """Update the header from the data array.
534
535 This function updates the header byte order and machine stamp to match
536 the byte order of the data. It also updates the file mode, space group
537 and the dimension fields ``nx``, ``ny``, ``nz``, ``mx``, ``my`` and
538 ``mz``.
539
540 If the data is 2D, the space group is set to 0 (image stack). For 3D
541 data the space group is not changed, and for 4D data the space group is
542 set to 401 (simple P1 volume stack) unless it is already in the volume
543 stack range (401--630).
544
545 This means that new 3D data will be treated as an image stack if the
546 previous data was a single image or image stack, or as a volume if the
547 previous data was a volume or volume stack.
548
549 Note that this function does *not* update the data statistics fields in
550 the header (``dmin``, ``dmax``, ``dmean`` and ``rms``). Use the
551 :meth:`update_header_stats` function to update the statistics.
552 (This is for performance reasons -- updating the statistics can take a
553 long time for large data sets, but updating the other header
554 information is always fast because only the type and shape of the data
555 array need to be inspected.)
556 """
557 self._check_writeable()
558
559 # Check the dtype is one we can handle and update mode to match
560 header = self.header
561 header.mode = utils.mode_from_dtype(self.data.dtype)
562
563 # Ensure header byte order and machine stamp match the data's byte order
564 data_byte_order = self.data.dtype.byteorder
565 header_byte_order = header.mode.dtype.byteorder
566 if (data_byte_order != '|'
567 and not utils.byte_orders_equal(data_byte_order, header_byte_order)):
568 header.byteswap(True)
569 header.dtype = header.dtype.newbyteorder(data_byte_order)
570 header.machst = utils.machine_stamp_from_byte_order(header.mode.dtype
571 .byteorder)
572
573 shape = self.data.shape
574 axes = len(shape)
575 if axes == 2:
576 # Single image. Space group 0, nz = mz = 1
577 header.ispg = IMAGE_STACK_SPACEGROUP
578 header.nx = header.mx = shape[1]
579 header.ny = header.my = shape[0]
580 header.nz = header.mz = 1
581 elif axes == 3:
582 header.nx = header.mx = shape[2]
583 header.ny = header.my = shape[1]
584 if header.ispg == IMAGE_STACK_SPACEGROUP:
585 # Image stack. mz = 1, nz = sections in the volume
586 header.mz = 1
587 header.nz = shape[0]
588 else:
589 # Volume. nz = mz = sections in the volume
590 header.nz = header.mz = shape[0]
591 elif axes == 4:
592 # Volume stack. Space group 401, mz = secs per vol, nz = total sections
593 if not utils.spacegroup_is_volume_stack(header.ispg):
594 header.ispg = VOLUME_STACK_SPACEGROUP
595 header.nx = header.mx = shape[3]
596 header.ny = header.my = shape[2]
597 header.mz = shape[1]
598 header.nz = shape[0] * shape[1]
599 else:
600 raise ValueError('Data must be 2-, 3- or 4-dimensional')
601
602 def update_header_stats(self):
603 """Update the header's ``dmin``, ``dmax``, ``dmean`` and ``rms`` fields
604 from the data.
605
606 Note that this can take some time with large files, particularly with
607 files larger than the currently available memory.
608
609 Warns:
610 RuntimeWarning: If the data array contains Inf or NaN values.
611 """
612 self._check_writeable()
613
614 if self.data.size > 0:
615 # Header stats are always in float32. If we have complex data, this doesn't
616 # make sense so just set rms and leave min, max and mean at their default
617 # un-set values
618 if np.iscomplexobj(self.data):
619 # Avoid ComplexWarning by explicitly taking the real part
620 self.header.rms = np.float32(self.data.std().real)
621 else:
622 min = self.data.min()
623 max = self.data.max()
624
625 if np.isnan(min):
626 warnings.warn("Data array contains NaN values", RuntimeWarning)
627 if np.isinf(min) or np.isinf(max):
628 warnings.warn("Data array contains infinite values", RuntimeWarning)
629
630 self.header.dmin = np.float32(min)
631 self.header.dmax = np.float32(max)
632 self.header.dmean = self.data.mean(dtype=np.float32)
633 self.header.rms = self.data.std(dtype=np.float32)
634 else:
635 self.reset_header_stats()
636
637 def reset_header_stats(self):
638 """Set the header statistics to indicate that the values are unknown."""
639 self._check_writeable()
640
641 self.header.dmin = 0
642 self.header.dmax = -1
643 self.header.dmean = -2
644 self.header.rms = -1
645
646 def print_header(self, print_file=None):
647 """Print the contents of all header fields.
648
649 Args:
650 print_file: The output text stream to use for printing the header.
651 This is passed directly to the ``file`` argument of Python's
652 :func:`print` function. The default is :data:`None`, which
653 means output will be printed to :data:`sys.stdout`.
654 """
655 for item in self.header.dtype.names:
656 print('{0:15s} : {1}'.format(item, self.header[item]),
657 file=print_file)
658
659 def get_labels(self):
660 """Get the labels from the MRC header.
661
662 Up to ten labels are stored in the header as arrays of 80 bytes. This method
663 returns the labels as Python strings, filtered to remove non-printable
664 characters. To access the raw bytes (including any non-printable characters) use
665 the ``header.label`` attribute (and note that ``header.nlabl`` stores the number
666 of labels currently set).
667
668 Returns:
669 The labels, as a list of strings. The list will contain between 0 and 10
670 items, each containing up to 80 characters.
671 """
672 return [
673 utils.printable_string_from_bytes(label)
674 for label in self.header.label[:self.header.nlabl]
675 ]
676
677 def add_label(self, label):
678 """Add a label to the MRC header.
679
680 The new label will be stored after any labels already in the header. If all ten
681 labels are already in use, an exception will be raised.
682
683 Future versions of this method might add checks to ensure that labels containing
684 valid text are not overwritten even if the ``nlabl`` value is incorrect.
685
686 Args:
687 label: The label value to store, as a string containing only printable
688 ASCII characters.
689
690 Raises:
691 :exc:`ValueError`: If the label is longer than 80 bytes or contains
692 non-printable or non-ASCII characters.
693 :exc:`IndexError`: If the file already contains 10 labels and so an
694 additional label cannot be stored.
695 """
696 if not utils.is_printable_ascii(label):
697 raise ValueError("Label contains non-printable or non-ASCII characters")
698 label_bytes = utils.bytes_from_string(label)
699 if len(label_bytes) > 80:
700 raise ValueError("Label value has more than 80 bytes")
701 self.header.label[self.header.nlabl] = label
702 self.header.nlabl += 1
703
704 def validate(self, print_file=None):
705 """Validate this MrcObject.
706
707 This method runs a series of tests to check whether this object
708 complies strictly with the MRC2014 format specification:
709
710 #. MRC format ID string: The header's ``map`` field must contain
711 "MAP ".
712 #. Machine stamp: The machine stamp should contain one of
713 ``0x44 0x44 0x00 0x00``, ``0x44 0x41 0x00 0x00`` or
714 ``0x11 0x11 0x00 0x00``.
715 #. MRC mode: the ``mode`` field should be one of the supported mode
716 numbers: 0, 1, 2, 4, 6 or 12. (Note that MRC modes 3 and 101 are
717 also valid according to the MRC 2014 specification but are not
718 supported by mrcfile.)
719 #. Map and cell dimensions: The header fields ``nx``, ``ny``, ``nz``,
720 ``mx``, ``my``, ``mz``, ``cella.x``, ``cella.y`` and ``cella.z``
721 must all be positive numbers.
722 #. Axis mapping: Header fields ``mapc``, ``mapr`` and ``maps`` must
723 contain the values 1, 2, and 3 (in any order).
724 #. Volume stack dimensions: If the spacegroup is in the range 401--630,
725 representing a volume stack, the ``nz`` field should be exactly
726 divisible by ``mz`` to represent the number of volumes in the stack.
727 #. Header labels: The ``nlabl`` field should be set to indicate the
728 number of labels in use, and the labels in use should appear first
729 in the label array (that is, there should be no blank labels between
730 text-filled ones).
731 #. MRC format version: The ``nversion`` field should be 20140 or 20141
732 for compliance with the MRC2014 standard.
733 #. Extended header type: If an extended header is present, the
734 ``exttyp`` field should be set to indicate the type of extended
735 header.
736 #. Data statistics: The statistics in the header should be correct for
737 the actual data, or marked as undetermined.
738
739 Args:
740 print_file: The output text stream to use for printing messages
741 about the validation. This is passed directly to the ``file``
742 argument of Python's :func:`print` function. The default is
743 :data:`None`, which means output will be printed to
744 :data:`sys.stdout`.
745
746 Returns:
747 :data:`True` if this MrcObject is valid, or :data:`False` if it
748 does not meet the MRC format specification in any way.
749 """
750 valid = True
751
752 def log(message):
753 print(message, file=print_file)
754
755 # Check map ID string
756 if self.header.map != MAP_ID:
757 log("Map ID string is incorrect: found {0}, should be {1}"
758 .format(self.header.map, MAP_ID))
759 valid = False
760
761 # Check machine stamp
762 try:
763 utils.byte_order_from_machine_stamp(self.header.machst)
764 except ValueError:
765 pretty_bytes = utils.pretty_machine_stamp(self.header.machst)
766 log("Invalid machine stamp: " + pretty_bytes)
767 valid = False
768
769 # Check mode is valid
770 try:
771 utils.dtype_from_mode(self.header.mode)
772 except ValueError:
773 log("Invalid mode: {0}".format(self.header.mode))
774 valid = False
775
776 # Check map dimensions and other fields are non-negative
777 for field in ['nx', 'ny', 'nz', 'mx', 'my', 'mz', 'ispg', 'nlabl']:
778 if self.header[field] < 0:
779 log("Header field '{0}' is negative".format(field))
780 valid = False
781
782 # Check cell dimensions are non-negative
783 for field in ['x', 'y', 'z']:
784 if self.header.cella[field] < 0:
785 log("Cell dimension '{0}' is negative".format(field))
786 valid = False
787
788 # Check axis mapping is valid
789 axes = set()
790 for field in ['mapc', 'mapr', 'maps']:
791 axes.add(int(self.header[field]))
792 if axes != {1, 2, 3}:
793 log("Invalid axis mapping: found {0}, should be [1, 2, 3]"
794 .format(sorted(list(axes))))
795 valid = False
796
797 # Check mz value for volume stacks
798 if utils.spacegroup_is_volume_stack(self.header.ispg):
799 if self.header.nz % self.header.mz != 0:
800 log("Error in dimensions for volume stack: nz should be "
801 "divisible by mz. Found nz = {0}, mz = {1})"
802 .format(self.header.nz, self.header.mz))
803 valid = False
804
805 # Check nlabl is correct
806 count = 0
807 seen_empty_label = False
808 for label in self.header.label:
809 if len(label.strip()) > 0:
810 count += 1
811 if seen_empty_label:
812 log("Error in header labels: empty labels appear between "
813 "text-containing labels")
814 valid = False
815 else:
816 seen_empty_label = True
817 if count != self.header.nlabl:
818 log("Error in header labels: nlabl is {0} "
819 "but {1} labels contain text".format(self.header.nlabl, count))
820 valid = False
821
822 # Check MRC format version
823 if self.header.nversion not in (20140, 20141):
824 log("File does not declare MRC format version 20140 or 20141: nversion ="
825 " {0}".format(self.header.nversion))
826 valid = False
827
828 # Check extended header type is set to a known value
829 valid_exttypes = [b'CCP4', b'MRCO', b'SERI', b'AGAR', b'FEI1', b'FEI2', b'HDF5']
830 if self.header.nsymbt > 0 and self.header.exttyp not in valid_exttypes:
831 log("Extended header type is undefined or unrecognised: exttyp = "
832 "'{0}'".format(self.header.exttyp.item().decode('ascii')))
833 valid = False
834
835 # Check data statistics
836 real_rms = real_min = real_max = real_mean = 0
837 if self.header.rms >= 0:
838 if self.data is not None and len(self.data > 0):
839 real_rms = self.data.std()
840 if not np.isclose(real_rms, self.header.rms, rtol=0.01):
841 log("Data statistics appear to be inaccurate: RMS deviation is {0} but"
842 " the value in the header is {1}".format(real_rms, self.header.rms))
843 valid = False
844 if self.header.dmin < self.header.dmax:
845 if self.data is not None and len(self.data > 0):
846 real_min = self.data.min()
847 real_max = self.data.max()
848 if self.header.dmin != real_min:
849 log("Data statistics appear to be inaccurate: minimum is {0} but the"
850 " value in the header is {1}".format(real_min, self.header.dmin))
851 valid = False
852 if self.header.dmax != real_max:
853 log("Data statistics appear to be inaccurate: maximum is {0} but the"
854 " value in the header is {1}".format(real_max, self.header.dmax))
855 valid = False
856 if self.header.dmean > min(self.header.dmin, self.header.dmax):
857 if self.data is not None and len(self.data > 0):
858 real_mean = self.data.mean(dtype=np.float64)
859 if not np.isclose(real_mean, self.header.dmean, rtol=0.01):
860 log("Data statistics appear to be inaccurate: mean is {0} but the"
861 " value in the header is {1}".format(real_mean, self.header.dmean))
862 valid = False
863
864 return valid