| 1 |
# Copyright (c) 2016, Science and Technology Facilities Council |
| 2 |
# This software is distributed under a BSD licence. See LICENSE.txt. |
| 3 |
""" |
| 4 |
mrcmemmap |
| 5 |
--------- |
| 6 |
|
| 7 |
Module which exports the :class:`MrcMemmap` class. |
| 8 |
|
| 9 |
Classes: |
| 10 |
:class:`MrcMemmap`: An MrcFile subclass that uses a memory-mapped data |
| 11 |
array. |
| 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 mmap |
| 20 |
import os |
| 21 |
import warnings |
| 22 |
|
| 23 |
import numpy as np |
| 24 |
|
| 25 |
import mrcfile.utils as utils |
| 26 |
from .mrcfile import MrcFile |
| 27 |
|
| 28 |
|
| 29 |
class MrcMemmap(MrcFile): |
| 30 |
|
| 31 |
"""MrcFile subclass that uses a :class:`numpy memmap array <numpy.memmap>` |
| 32 |
for the data. |
| 33 |
|
| 34 |
Using a memmap means that the disk access is done lazily: the data array |
| 35 |
will only be read or written in small chunks when required. To access the |
| 36 |
contents of the array, use the array slice operator. |
| 37 |
|
| 38 |
Usage is the same as for :class:`~mrcfile.mrcfile.MrcFile`. |
| 39 |
|
| 40 |
Note that memmap arrays use a fairly small chunk size and so performance |
| 41 |
could be poor on file systems that are optimised for infrequent large I/O |
| 42 |
operations. |
| 43 |
|
| 44 |
If required, it is possible to create a very large empty file by creating a |
| 45 |
new MrcMemmap and then calling :meth:`_open_memmap` to create the memmap |
| 46 |
array, which can then be filled slice-by-slice. Be aware that the contents |
| 47 |
of a new, empty memmap array depend on your platform: the data values |
| 48 |
could be garbage or zeros. |
| 49 |
|
| 50 |
""" |
| 51 |
|
| 52 |
def __repr__(self): |
| 53 |
return "MrcMemmap('{0}', mode='{1}')".format(self._iostream.name, |
| 54 |
self._mode) |
| 55 |
|
| 56 |
def set_extended_header(self, extended_header): |
| 57 |
"""Replace the file's extended header. |
| 58 |
|
| 59 |
Note that the file's entire data block must be moved if the extended |
| 60 |
header size changes. Setting a new extended header can therefore be |
| 61 |
very time consuming with large files, if the new extended header |
| 62 |
occupies a different number of bytes than the previous one. |
| 63 |
""" |
| 64 |
old_ext_header_size = self._extended_header.nbytes |
| 65 |
super(MrcMemmap, self).set_extended_header(extended_header) |
| 66 |
if extended_header.nbytes != old_ext_header_size: |
| 67 |
data_copy = self._data.copy() |
| 68 |
self._close_data() |
| 69 |
self._extended_header = extended_header |
| 70 |
self.header.nsymbt = extended_header.nbytes |
| 71 |
header_nbytes = self.header.nbytes + extended_header.nbytes |
| 72 |
total_nbytes = header_nbytes + data_copy.nbytes |
| 73 |
|
| 74 |
# Workaround for https://github.com/ccpem/mrcfile/issues/65 |
| 75 |
if data_copy.nbytes == 0 and total_nbytes % mmap.ALLOCATIONGRANULARITY == 0: |
| 76 |
# Add one extra byte here to avoid triggering mmap error |
| 77 |
total_nbytes += 1 |
| 78 |
|
| 79 |
self._iostream.truncate(total_nbytes) |
| 80 |
self._open_memmap(data_copy.dtype, data_copy.shape) |
| 81 |
np.copyto(self._data, data_copy) |
| 82 |
|
| 83 |
def flush(self): |
| 84 |
"""Flush the header and data arrays to the file buffer.""" |
| 85 |
if not self._read_only: |
| 86 |
self._iostream.seek(0) |
| 87 |
self._iostream.write(self.header) |
| 88 |
self._iostream.write(self.extended_header) |
| 89 |
|
| 90 |
# Flushing the file before the mmap makes the mmap flush faster |
| 91 |
self._iostream.flush() |
| 92 |
self._data.flush() |
| 93 |
self._iostream.flush() |
| 94 |
|
| 95 |
# Seek to end of data block so stream is left in the same position |
| 96 |
# as normal |
| 97 |
self._iostream.seek(self._data.nbytes, os.SEEK_CUR) |
| 98 |
|
| 99 |
def _read_data(self): |
| 100 |
"""Read the data block from the file. |
| 101 |
|
| 102 |
This method first calculates the parameters needed to read the data |
| 103 |
(block start position, endian-ness, file mode, array shape) and then |
| 104 |
opens the data as a numpy memmap array. |
| 105 |
""" |
| 106 |
try: |
| 107 |
dtype = utils.data_dtype_from_header(self.header) |
| 108 |
except ValueError as err: |
| 109 |
if self._permissive: |
| 110 |
warnings.warn("{0} - data block not read".format(err), |
| 111 |
RuntimeWarning) |
| 112 |
self._data = None |
| 113 |
return |
| 114 |
else: |
| 115 |
raise |
| 116 |
|
| 117 |
shape = utils.data_shape_from_header(self.header) |
| 118 |
|
| 119 |
self._open_memmap(dtype, shape) |
| 120 |
|
| 121 |
def _open_memmap(self, dtype, shape): |
| 122 |
"""Open a new memmap array pointing at the file's data block.""" |
| 123 |
acc_mode = 'r' if self._read_only else 'r+' |
| 124 |
# Need to use self.header.nsymbt rather than self.extended_header.nbytes because |
| 125 |
# self.extended_header might be None in permissive read mode. Need to convert to |
| 126 |
# Python int (rather than numpy int32) to avoid possible overflow. |
| 127 |
header_nbytes = self.header.nbytes + int(self.header.nsymbt) |
| 128 |
|
| 129 |
self._iostream.flush() |
| 130 |
try: |
| 131 |
self._data = np.memmap(self._iostream, |
| 132 |
dtype=dtype, |
| 133 |
mode=acc_mode, |
| 134 |
offset=header_nbytes, |
| 135 |
shape=shape) |
| 136 |
except Exception as ex: |
| 137 |
if self._permissive: |
| 138 |
warnings.warn("Error opening memmap", RuntimeWarning) |
| 139 |
self._data = None |
| 140 |
else: |
| 141 |
raise ex |
| 142 |
|
| 143 |
# Check if the file is the expected size. |
| 144 |
if self.data is not None: |
| 145 |
file_size = self._get_file_size() |
| 146 |
remaining_file_size = file_size - header_nbytes |
| 147 |
data_size = self.data.nbytes |
| 148 |
|
| 149 |
# Workaround for https://github.com/ccpem/mrcfile/issues/65 |
| 150 |
if data_size == 0 and header_nbytes % mmap.ALLOCATIONGRANULARITY == 0: |
| 151 |
# Expect a file one byte larger here to avoid triggering mmap error |
| 152 |
data_size = 1 |
| 153 |
|
| 154 |
if data_size < remaining_file_size: |
| 155 |
msg = ("MRC file is {0} bytes larger than expected" |
| 156 |
.format(remaining_file_size - data_size)) |
| 157 |
warnings.warn(msg, RuntimeWarning) |
| 158 |
|
| 159 |
def _close_data(self): |
| 160 |
"""Delete the existing memmap array, if it exists. |
| 161 |
|
| 162 |
The array is flagged as read-only before deletion, so if a reference to |
| 163 |
it has been kept elsewhere, changes to it should no longer be able to |
| 164 |
change the file contents. |
| 165 |
""" |
| 166 |
if self._data is not None: |
| 167 |
self._data.flush() |
| 168 |
self._data.flags.writeable = False |
| 169 |
self._data = None |
| 170 |
|
| 171 |
def _set_new_data(self, data): |
| 172 |
"""Override of :meth:`_set_new_data` to handle opening a new memmap and |
| 173 |
copying data into it.""" |
| 174 |
# Need to use self.header.nsymbt rather than self.extended_header.nbytes because |
| 175 |
# self.extended_header might be None in permissive read mode. Need to convert to |
| 176 |
# Python int (rather than numpy int32) to avoid possible overflow. |
| 177 |
file_size = self.header.nbytes + int(self.header.nsymbt) + data.nbytes |
| 178 |
self._iostream.truncate(file_size) |
| 179 |
self._open_memmap(data.dtype, data.shape) |
| 180 |
np.copyto(self._data, data, casting='no') |