Debian Codegraph @

mrcfile/load_functions.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 load_functions
6 --------------
7
8 Module for top-level functions that open MRC files and form the main API of
9 the package.
10
11 """
12
13 # Import Python 3 features for future-proofing
14 from __future__ import (absolute_import, division, print_function,
15 unicode_literals)
16
17 import io
18 import os
19
20 import numpy as np
21
22 from . import utils
23 from .bzip2mrcfile import Bzip2MrcFile
24 from .constants import MAP_ID, MAP_ID_OFFSET_BYTES
25 from .future_mrcfile import FutureMrcFile
26 from .gzipmrcfile import GzipMrcFile
27 from .mrcfile import MrcFile
28 from .mrcmemmap import MrcMemmap
29
30
31 def new(name, data=None, compression=None, overwrite=False):
32 """Create a new MRC file.
33
34 Args:
35 name: The file name to use, as a string or :class:`~pathlib.Path`.
36 data: Data to put in the file, as a :class:`numpy array
37 <numpy.ndarray>`. The default is :data:`None`, to create an empty
38 file.
39 compression: The compression format to use. Acceptable values are:
40 :data:`None` (the default; for no compression), ``'gzip'`` or
41 ``'bzip2'``.
42 It's good practice to name compressed files with an appropriate
43 extension (for example, ``.mrc.gz`` for gzip) but this is not
44 enforced.
45 overwrite: Flag to force overwriting of an existing file. If
46 :data:`False` and a file of the same name already exists, the file
47 is not overwritten and an exception is raised.
48
49 Returns:
50 An :class:`~mrcfile.mrcfile.MrcFile` object (or a
51 subclass of it if ``compression`` is specified).
52
53 Raises:
54 :exc:`ValueError`: If the file already exists and overwrite is
55 :data:`False`.
56 :exc:`ValueError`: If the compression format is not recognised.
57
58 Warns:
59 RuntimeWarning: If the data array contains Inf or NaN values.
60 """
61 if compression == 'gzip':
62 NewMrc = GzipMrcFile
63 elif compression == 'bzip2':
64 NewMrc = Bzip2MrcFile
65 elif compression is not None:
66 raise ValueError("Unknown compression format '{0}'"
67 .format(compression))
68 else:
69 NewMrc = MrcFile
70 mrc = NewMrc(name, mode='w+', overwrite=overwrite)
71 if data is not None:
72 mrc.set_data(data)
73 return mrc
74
75
76 def open(name, mode='r', permissive=False, header_only=False): # @ReservedAssignment
77 """Open an MRC file.
78
79 This function opens both normal and compressed MRC files. Supported
80 compression formats are: gzip, bzip2.
81
82 It is possible to use this function to create new MRC files (using mode
83 ``w+``) but the :func:`new` function is more flexible.
84
85 This function offers a permissive read mode for attempting to open corrupt
86 or invalid files. In permissive mode, :mod:`warnings` are issued instead of
87 exceptions if problems with the file are encountered. See
88 :class:`~mrcfile.mrcinterpreter.MrcInterpreter` or the
89 :doc:`usage guide <../usage_guide>` for more information.
90
91 Args:
92 name: The file name to open, as a string or :class:`~pathlib.Path`.
93 mode: The file mode to use. This should be one of the following: ``r``
94 for read-only, ``r+`` for read and write, or ``w+`` for a new empty
95 file. The default is ``r``.
96 permissive: Read the file in permissive mode. The default is
97 :data:`False`.
98 header_only: Only read the header (and extended header) from the file.
99 The default is :data:`False`.
100
101 Returns:
102 An :class:`~mrcfile.mrcfile.MrcFile` object (or a
103 :class:`~mrcfile.gzipmrcfile.GzipMrcFile` object if the file is
104 gzipped).
105
106 Raises:
107 :exc:`ValueError`: If the mode is not one of ``r``, ``r+`` or ``w+``.
108 :exc:`ValueError`: If the file is not a valid MRC file and
109 ``permissive`` is :data:`False`.
110 :exc:`ValueError`: If the mode is ``w+`` and the file already exists.
111 (Call :func:`new` with ``overwrite=True`` to deliberately overwrite
112 an existing file.)
113 :exc:`OSError`: If the mode is ``r`` or ``r+`` and the file does not
114 exist.
115
116 Warns:
117 RuntimeWarning: If the file appears to be a valid MRC file but the data
118 block is longer than expected from the dimensions in the header.
119 RuntimeWarning: If the file is not a valid MRC file and ``permissive``
120 is :data:`True`.
121 RuntimeWarning: If the header's ``exttyp`` field is set to a known
122 value but the extended header's size is not a multiple of the
123 number of bytes in the corresponding dtype.
124 """
125 NewMrc = MrcFile
126 name = str(name) # in case name is a pathlib Path
127 if os.path.exists(name):
128 if "w" in mode:
129 raise ValueError("File '{0}' already exists; use a different name, or"
130 " delete it first or call 'mrcfile.new()' with"
131 " 'overwrite=True' to overwrite it".format(name))
132 with io.open(name, 'rb') as f:
133 start = f.read(MAP_ID_OFFSET_BYTES + len(MAP_ID))
134 # Check for map ID string to avoid trying to decompress normal files
135 # where the nx value happens to include the magic number for a
136 # compressed format. (This still risks failing to correctly decompress
137 # compressed files which happen to have 'MAP ' at position 208, but
138 # that is less likely and if it does occur, the CompressedMrcFile
139 # class can always be used directly instead.)
140 if start[-len(MAP_ID):] != MAP_ID:
141 if start[:2] == b'\x1f\x8b':
142 NewMrc = GzipMrcFile
143 elif start[:2] == b'BZ':
144 NewMrc = Bzip2MrcFile
145 return NewMrc(name, mode=mode, permissive=permissive,
146 header_only=header_only)
147
148
149 def read(name):
150 """Read an MRC file's data into a numpy array.
151
152 This is a convenience function to read the data from an MRC file when there is no
153 need for the file's header information. To read the headers as well, or if you need
154 access to an :class:`~mrcfile.mrcfile.MrcFile` object representing the file, use
155 :func:`mrcfile.open` instead.
156
157 Args:
158 name: The file name to read, as a string or :class:`~pathlib.Path`.
159
160 Returns:
161 A :class:`numpy array<numpy.ndarray>` containing the data from the file.
162 """
163 with open(name, mode='r', permissive=True) as mrc:
164 data = mrc.data.copy()
165 return data
166
167
168 def write(name, data=None, overwrite=False, voxel_size=None):
169 """Write a new MRC file.
170
171 This is a convenience function to allow data to be quickly written to a file (with
172 optional compression) using just a single function call. However, there is no
173 control over the file's metadata except for optionally setting the voxel size. For
174 more control, or if you need access to an :class:`~mrcfile.mrcfile.MrcFile` object
175 representing the new file, use :func:`mrcfile.new` instead.
176
177 Args:
178 name: The file name to use, as a string or :class:`~pathlib.Path`. If the name
179 ends with ``.gz`` or ``.bz2``, the file will be compressed using gzip or
180 bzip2 respectively.
181 data: Data to put in the file, as a :class:`numpy array
182 <numpy.ndarray>`. The default is :data:`None`, to create an empty
183 file.
184 overwrite: Flag to force overwriting of an existing file. If
185 :data:`False` and a file of the same name already exists, the file
186 is not overwritten and an exception is raised.
187 voxel_size: float | 3-tuple
188 The voxel size to be written in the file header.
189
190 Raises:
191 :exc:`ValueError`: If the file already exists and overwrite is
192 :data:`False`.
193
194 Warns:
195 RuntimeWarning: If the data array contains Inf or NaN values.
196 """
197 name = str(name) # in case name is a pathlib Path
198 compression = None
199 if name.endswith('.gz'):
200 compression = 'gzip'
201 elif name.endswith('.bz2'):
202 compression = 'bzip2'
203 with new(name, data, compression, overwrite) as mrc:
204 if voxel_size is not None:
205 mrc.voxel_size = voxel_size
206
207
208 def open_async(name, mode='r', permissive=False):
209 """Open an MRC file asynchronously in a separate thread.
210
211 This allows a file to be opened in the background while the main thread
212 continues with other work. This can be a good way to improve performance if
213 the main thread is busy with intensive computation, but will be less
214 effective if the main thread is itself busy with disk I/O.
215
216 Multiple files can be opened in the background simultaneously. However,
217 this implementation is relatively crude; each call to this function will
218 start a new thread and immediately use it to start opening a file. If you
219 try to open many large files at the same time, performance will decrease as
220 all of the threads attempt to access the disk at once. You'll also risk
221 running out of memory to store the data from all the files.
222
223 This function returns a :class:`~mrcfile.future_mrcfile.FutureMrcFile`
224 object, which deliberately mimics the API of the
225 :class:`~concurrent.futures.Future` object from Python 3's
226 :mod:`concurrent.futures` module. (Future versions of this library might
227 return genuine :class:`~concurrent.futures.Future` objects instead.)
228
229 To get the real :class:`~mrcfile.mrcfile.MrcFile` object from a
230 :class:`~mrcfile.future_mrcfile.FutureMrcFile`, call
231 :meth:`~mrcfile.future_mrcfile.FutureMrcFile.result`. This will block until
232 the file has been read and the :class:`~mrcfile.mrcfile.MrcFile` object is
233 ready. To check if the :class:`~mrcfile.mrcfile.MrcFile` is ready without
234 blocking, call :meth:`~mrcfile.future_mrcfile.FutureMrcFile.running` or
235 :meth:`~mrcfile.future_mrcfile.FutureMrcFile.done`.
236
237 Args:
238 name: The file name to open, as a string or :class:`~pathlib.Path`.
239 mode: The file mode (one of ``r``, ``r+`` or ``w+``).
240 permissive: Read the file in permissive mode. The default is
241 :data:`False`.
242
243 Returns:
244 A :class:`~mrcfile.future_mrcfile.FutureMrcFile` object.
245
246 """
247 return FutureMrcFile(open, (name,), dict(mode=mode, permissive=permissive))
248
249
250 def mmap(name, mode='r', permissive=False):
251 """Open a memory-mapped MRC file.
252
253 This allows much faster opening of large files, because the data is only
254 accessed on disk when a slice is read or written from the data array. See
255 the :class:`~mrcfile.mrcmemmap.MrcMemmap` class documentation for more
256 information.
257
258 Because the memory-mapped data array accesses the disk directly, compressed
259 files cannot be opened with this function. In all other ways, :func:`mmap`
260 behaves in exactly the same way as :func:`open`. The
261 :class:`~mrcfile.mrcmemmap.MrcMemmap` object returned by this function can
262 be used in exactly the same way as a normal
263 :class:`~mrcfile.mrcfile.MrcFile` object.
264
265 Args:
266 name: The file name to open, as a string or :class:`~pathlib.Path`.
267 mode: The file mode (one of ``r``, ``r+`` or ``w+``).
268 permissive: Read the file in permissive mode. The default is
269 :data:`False`.
270
271 Returns:
272 An :class:`~mrcfile.mrcmemmap.MrcMemmap` object.
273 """
274 return MrcMemmap(name, mode=mode, permissive=permissive)
275
276
277 def new_mmap(name, shape, mrc_mode=0, fill=None, overwrite=False, extended_header=None, exttyp=None):
278 """Create a new, empty memory-mapped MRC file.
279
280 This function is useful for creating very large files. The initial contents
281 of the data array can be set with the ``fill`` parameter if needed, but be
282 aware that filling a large array can take a long time.
283
284 If ``fill`` is not set, the new data array's contents are unspecified and
285 system-dependent. (Some systems fill a new empty mmap with zeros, others
286 fill it with the bytes from the disk at the newly-mapped location.) If you
287 are definitely going to fill the entire array with new data anyway you can
288 safely leave ``fill`` as :data:`None`, otherwise it is advised to use a
289 sensible fill value (or ensure you are on a system that fills new mmaps
290 with a reasonable default value).
291
292 Args:
293 name: The file name to use, as a string or :class:`~pathlib.Path`.
294 shape: The shape of the data array to open, as a 2-, 3- or 4-tuple of
295 ints. For example, ``(nz, ny, nx)`` for a new 3D volume, or
296 ``(ny, nx)`` for a new 2D image.
297 mrc_mode: The MRC mode to use for the new file. One of 0, 1, 2, 4 or 6,
298 which correspond to numpy dtypes as follows:
299
300 * mode 0 -> int8
301 * mode 1 -> int16
302 * mode 2 -> float32
303 * mode 4 -> complex64
304 * mode 6 -> uint16
305
306 The default is 0.
307 fill: An optional value to use to fill the new data array. If
308 :data:`None`, the data array will not be filled and its contents
309 are unspecified. Numpy's usual rules for rounding or rejecting
310 values apply, according to the dtype of the array.
311 overwrite: Flag to force overwriting of an existing file. If
312 :data:`False` and a file of the same name already exists, the file
313 is not overwritten and an exception is raised.
314 extended_header: The extended header object
315 exttyp: The extended header type
316
317 Returns:
318 A new :class:`~mrcfile.mrcmemmap.MrcMemmap` object.
319
320 Raises:
321 :exc:`ValueError`: If the MRC mode is invalid.
322 :exc:`ValueError`: If the file already exists and overwrite is
323 :data:`False`.
324 :exc:`ValueError`: If the extended header or any of the dimensions of
325 the shape have a size greater than 2,147,483,647 (and
326 therefore the size cannot be stored in the header).
327 """
328 for dim in shape:
329 if dim > np.iinfo(np.int32).max:
330 raise ValueError("New shape is too large! Found a dimension of"
331 " size {}. The maximum allowed is {}."
332 .format(dim, np.iinfo(np.int32).max))
333
334 mrc = MrcMemmap(name, mode='w+', overwrite=overwrite)
335
336 # Add the extended header and type. We need to do this before creating the
337 # memory mapped file to avoid having to copy lots of data
338 if extended_header is not None:
339 mrc.set_extended_header(extended_header)
340 if exttyp is not None:
341 mrc.header.exttyp = exttyp
342
343 dtype = utils.dtype_from_mode(mrc_mode)
344 mrc._open_memmap(dtype, shape)
345 mrc.update_header_from_data()
346 if fill is not None:
347 mrc.data[...] = fill
348 mrc.flush()
349 return mrc