Debian Codegraph @

mrcz/ioMRC.py

raw ◀ ▶
2 Debian patches touch this file
1 from __future__ import division, print_function, absolute_import, unicode_literals
2 '''
3 Conventional MRC2014 and on-the-fly compressed MRCZ file interface
4
5 CCPEM MRC2014 specification:
6 http://www.ccpem.ac.uk/mrc_format/mrc2014.php
7
8 IMOD specification:
9 http://bio3d.colorado.edu/imod/doc/mrc_format.txt
10
11 Testing:
12 http://emportal.nysbc.org/mrc2014/
13
14 Tested output on: Gatan GMS, IMOD, Chimera, Relion, MotionCorr, UnBlur
15 '''
16
17 import os, os.path, sys
18 import numpy as np
19 import threading
20 import struct
21 from enum import Enum
22
23 try:
24 from concurrent.futures import ThreadPoolExecutor
25 except ImportError as e:
26 if sys.version_info > (3,0):
27 raise ImportError('Get the backport for `concurrent.futures` for Py2.7 as `pip install futures`')
28 raise e
29 from mrcz.__version__ import __version__
30 from distutils.version import StrictVersion
31
32 import logging
33 logger = logging.getLogger('MRCZ')
34 try:
35 import blosc
36 BLOSC_PRESENT = True
37 # For async operations we want to release the GIL in blosc operations and
38 # file IO operations.
39 blosc.set_releasegil(True)
40 DEFAULT_N_THREADS = blosc.detect_number_of_cores()
41 except ImportError:
42 # Can be ImportError or ModuleNotFoundError depending on the Python version,
43 # but ModuleNotFoundError is a child of ImportError and is still caught.
44 BLOSC_PRESENT = False
45 logger.info('`blosc` meta-compression library not found, file compression disabled.')
46 DEFAULT_N_THREADS = 1
47 try:
48 import rapidjson as json
49 except ImportError:
50 import json
51 logger.info('`python-rapidjson` not found, using builtin `json` instead.')
52
53 def _defaultMetaSerialize(value):
54 """
55 Is called by `json.dumps()` whenever it encounters an object it does
56 not know how to serialize. Currently handles:
57
58 1. Any object with a `serialize()` method, which is assumed to be a helper
59 method.
60 1. `numpy` scalars as well as `ndarray`
61 2. Python `Enum` objects which are serialized as strings in the form
62 ``'Enum.{object.__class__.__name__}.{object.name}'``. E.g. ``'Enum.Axis.X'``.
63 """
64 if hasattr(value, 'serialize'):
65 return value.serialize()
66 elif hasattr(value, '__array_interface__'):
67 # Checking for '__array_interface__' also sanitizes numpy scalars
68 # like np.float32 or np.int32
69 return value.tolist()
70 elif isinstance(value, Enum):
71 return 'Enum.{}.{}'.format(value.__class__.__name__, value.name)
72 else:
73 raise TypeError('Unhandled type for JSON serialization: {}'.format(type(value)))
74
75 # Do we also want to convert long lists to np.ndarrays?
76
77 # Buffer for file I/O
78 # Quite arbitrary, in bytes (hand-optimized)
79 BUFFERSIZE = 2**20
80 BLOSC_BLOCK = 2**16
81 DEFAULT_HEADER_LEN = 1024
82
83 # ENUM dicts for our various Python to MRC constant conversions
84 COMPRESSOR_ENUM = {0:None, 1:'blosclz', 2:'lz4', 3:'lz4hc', 4:'snappy', 5:'zlib', 6:'zstd'}
85 REVERSE_COMPRESSOR_ENUM = {None:0, 'blosclz':1, 'lz4':2, 'lz4hc':2, 'snappy':4, 'zlib':5, 'zstd':6}
86
87 MRC_COMP_RATIO = 1000
88 CCPEM_ENUM = {0: 'i1', 1:'i2', 2:'f4', 4:'c8', 6:'u2', 7:'i4', 8:'u4', 101:'u1'}
89 EMAN2_ENUM = {1: 'i1', 2:'u1', 3:'i2', 4:'u2', 5:'i4', 6:'u4', 7:'f4'}
90 REVERSE_CCPEM_ENUM = {'int8':0, 'i1':0,
91 'uint4':101,
92 'int16':1, 'i2':1,
93 'uint16':6, 'u2':6,
94 'int32':7, 'i4':7,
95 'uint32': 8, 'u4':8,
96 'float64':2, 'f8':2, 'float32':2, 'f4':2,
97 'complex128':4, 'c16':4, 'complex64':4, 'c8':4}
98 WARNED_ABOUT_CASTING_F64 = False
99 WARNED_ABOUT_CASTING_C128 = False
100
101 # Executor for writing compressed blocks to disk
102 _asyncWriter = ThreadPoolExecutor(max_workers = 1)
103 # Executor for calls to asyncReadMRC and asyncWriteMRC
104 _asyncExecutor = ThreadPoolExecutor(max_workers = 1)
105 def _setAsyncWorkers(N_workers):
106 '''
107 **This function is protected as there appears to be little value in using more
108 than one worker. It may be subject to removal in the future.**
109
110 Sets the maximum number of background workers that can be used for reading
111 or writing with the functions. Defaults to 1. Generally when writing
112 to hard drives use 1 worker. For random-access drives there may be
113 advantages to using multiple workers.
114
115 Some test results, 30 files, each 10 x 2048 x 2048 x float-32, on a CPU
116 with 4 physical cores:
117
118 HD, 1 worker: 42.0 s
119 HD, 2 workers: 50.0 s
120 HD, 4 workers: 50.4 s
121 SSD, 1 worker: 12.6 s
122 SSD, 2 workers: 11.6 s
123 SSD, 4 workers: 8.9 s
124 SSD, 8 workers: 16.9 s
125
126 Parameters
127 ----------
128 N_workers: int
129 The number of threads for asynchronous reading and writing to disk
130 '''
131 if N_workers <= 0:
132 raise ValueError('N_workers must be greater than 0')
133 if _asyncExecutor._max_workers == N_workers:
134 return
135 _asyncExecutor._max_workers = N_workers
136 _asyncExecutor._adjust_thread_count()
137
138 def setDefaultThreads(n_threads):
139 """
140 Set the default number of threads, if the argument is not provided in
141 calls to `readMRC` and `writeMRC`.
142
143 Generally optimal thread count is the number of physical cores, but
144 blosc defaults to the number of virtual cores. Therefore on machines with
145 hyperthreading it can be more efficient to manually set this value
146 """
147 global DEFAULT_N_THREADS
148 DEFAULT_N_THREADS = int(n_threads)
149
150 def defaultHeader():
151 '''
152 Generator function to create a metadata header dictionary with the relevant
153 fields.
154
155 Returns
156 -------
157 header
158 a default MRC header dictionary with all fields with default values.
159 '''
160 header = {}
161 header['fileConvention'] = 'ccpem'
162 header['endian'] = 'le'
163 header['MRCtype'] = 0
164 header['dimensions'] = np.array( [0,0,0], dtype=int )
165 header['dtype'] = 'u1'
166
167 header['compressor'] = None
168 header['packedBytes'] = 0
169 header['clevel'] = 1
170
171 header['maxImage'] = 1.0
172 header['minImage'] = 0.0
173 header['meanImage'] = 0.0
174
175 header['pixelsize'] = 0.1
176 header['pixelunits'] = u'nm' # Can be '\\AA' for Angstroms
177 header['voltage'] = 300.0 # kV
178 header['C3'] = 2.7 # mm
179 header['gain'] = 1.0 # counts/electron
180
181 if BLOSC_PRESENT:
182 header['n_threads'] = DEFAULT_N_THREADS
183
184 return header
185
186 def _getMRCZVersion(label):
187 """
188 Checks to see if the first label holds the MRCZ version information,
189 in which case it returns a version object. Generally used to recover nicely
190 in case of backward compatibility problems.
191
192 Parameters
193 ----------
194 label: Union[str, bytes]
195
196 Returns
197 -------
198 version: Optional[distutils.version.StrictVersion]
199 areturns ``None`` if `label` cannot be parsed.
200 """
201 if isinstance(label, bytes):
202 label = label.decode()
203
204 label = label.rstrip(' \t\r\n\0')
205 if not label.startswith('MRCZ'):
206 return None
207
208 label = label[4:]
209 try:
210 version = StrictVersion(label)
211 return version
212 except ValueError:
213 return None
214
215
216 def readMRC(MRCfilename, idx=None, endian='le',
217 pixelunits=u'\\AA', fileConvention='ccpem',
218 useMemmap=False, n_threads=None, slices=None):
•219 r'''
220 Imports an MRC/Z file as a NumPy array and a meta-data dict.
221
222 Parameters
223 ----------
224 image: numpy.ndarray
225 a 1-3 dimension ``numpy.ndarray`` with one of the supported data types in
226 ``mrcz.REVERSE_CCPEM_ENUM``
227 meta: dict
228 a ``dict`` with various fields relating to the MRC header information.
229 Can also hold arbitrary meta-data, but the use of large numerical data
230 is not recommended as it is encoded as text via JSON.
231 idx: Tuple[int]
232 Index tuple ``(first, last)`` where first (inclusive) and last (not
233 inclusive) indices of images to be read from the stack. Index of first image
234 is 0. Negative indices can be used to count backwards. A singleton integer
235 can be provided to read only one image. If omitted, will read whole file.
236 Compression is currently not supported with this option.
237 pixelunits: str
238 can be ``'AA' (Angstoms), 'nm', '\mum', or 'pm'``. Internally pixel
239 sizes are always encoded in Angstroms in the MRC file.
240 fileConvention: str
241 can be ``'ccpem'`` (equivalent to IMOD) or ``'eman2'``, which is
242 only partially supported at present.
243 endian: str
244 can be big-endian as ``'be'`` or little-endian as ``'le'``. Defaults
245 to `'le'` as the vast majority of modern computers are little-endian.
246 n_threads: int
247 is the number of threads to use for decompression, defaults to
248 use all virtual cores.
249 useMemmap: bool = True
250 returns a ``numpy.memmap`` instead of a ``numpy.ndarray``. Not recommended
251 as it will not work with compression.
252 slices: Optional[int] = None
253 Reflects the number of slices per frame. For example, in time-series
254 with multi-channel STEM, would be ``4`` for a 4-quadrant detector. Data
255 is always written contiguously in MRC, but will be returned as a list of
256 ``[slices, *shape]``-shaped arrays. The default option ``None`` will
257 check for a ``'slices'`` field in the meta-data and use that, otherwise
258 it defaults to ``0`` which is one 3D array.
259
260
261 Returns
262 -------
263 image: Union[list[numpy.ndarray], numpy.ndarray]
264 If ``slices == 0`` then a monolithic array is returned, else a ``list``
265 of ``[slices, *shape]``-shaped arrays.
266 meta: dict
267 the stored meta-data in a dictionary. Note that arrays are generally
268 returned as lists due to the JSON serialization.
269
270 Example
271 -------
272 [image, meta] = readMRC(MRCfilename, idx=None,
273 pixelunits=u'\\AA', useMemmap=False, n_threads=None)
274 '''
275
276 with open(MRCfilename, 'rb', buffering=BUFFERSIZE) as f:
277 # Read in header as a dict
278
279 header, slices = readMRCHeader(MRCfilename, slices, endian=endian, fileConvention = fileConvention, pixelunits=pixelunits)
280 # Support for compressed data in MRCZ
281
282
283 if ( (header['compressor'] in REVERSE_COMPRESSOR_ENUM)
284 and (REVERSE_COMPRESSOR_ENUM[header['compressor']] > 0)
285 and idx == None ):
286 return __MRCZImport(f, header, slices, endian=endian, fileConvention=fileConvention,
287 n_threads=n_threads)
288 # Else load as uncompressed MRC file
289
290 if idx != None:
291 # If specific images were requested:
292 # TO DO: add support to read all images within a range at once
293
294 if header['compressor'] != None:
295 raise RuntimeError('Reading from arbitrary positions not supported for compressed files. Compressor = %s'%header['compressor'])
296 if np.isscalar( idx ):
297 indices = np.array([idx, idx], dtype='int')
298 else:
299 indices = np.array(idx, dtype='int')
300
301 # Convert to old way:
302 idx = indices[0]
303 n = indices[1] - indices[0] + 1
304
305 if idx < 0:
306 # Convert negative index to equivalent positive index:
307 idx = header['dimensions'][0] + idx
308
309 # Just check if the desired image is within the stack range:
310 if idx < 0 or idx >= header['dimensions'][0]:
311 raise ValueError('Error: image or slice index out of range. idx = %d, z_dimension = %d'%(idx, header['dimensions'][0]))
312 elif idx + n > header['dimensions'][0]:
313 raise ValueError('Error: image or slice index out of range. idx + n = %d, z_dimension = %d'%(idx + n, header['dimensions'][0]))
314 elif n < 1:
315 raise ValueError('Error: n must be >= 1. n = %d'%n)
316 else:
317 # We adjust the dimensions of the returned image in the header:
318 header['dimensions'][0] = n
319
320 # This offset will be applied to f.seek():
321 offset = idx * np.prod(header['dimensions'][1:])*np.dtype(header['dtype']).itemsize
322
323 else:
324 offset = 0
325
326 f.seek(DEFAULT_HEADER_LEN + header['extendedBytes'] + offset)
327 if bool(useMemmap):
328 image = np.memmap(f, dtype=header['dtype'],
329 mode='c',
330 shape=tuple(dim for dim in header['dimensions']))
331 else: # Load entire file into memory
332 dims = header['dimensions']
333 if slices > 0: # List of NumPy 2D-arrays
334 frame_size = slices * np.prod(dims[1:])
335 n_frames = dims[0] // slices
336 dtype = header['dtype']
337
338 # np.fromfile advances the file pointer `f` for us.
339 image = []
340 for I in range(n_frames):
341 buffer = np.fromfile(f, dtype=dtype, count=frame_size)
342 buffer = buffer.reshape((slices, dims[1], dims[2])).squeeze()
343 image.append(buffer)
344
345 else: # monolithic NumPy ndarray
346 image = np.fromfile(f, dtype=header['dtype'], count=np.prod(dims))
347
348 if header['MRCtype'] == 101:
349 # Seems the 4-bit is interlaced ...
350 interlaced_image = image
351 image = np.empty(np.prod(dims), dtype=header['dtype'])
352 image[0::2] = np.left_shift(interlaced_image,4) / 15
353 image[1::2] = np.right_shift(interlaced_image,4)
354
355 image = np.squeeze(image.reshape(dims))
356
357 return image, header
358
359
360 def __MRCZImport(f, header, slices, endian='le', fileConvention='ccpem',
361 returnHeader=False, n_threads=None):
362 '''
363 Equivalent to MRCImport, but for compressed data using the blosc library.
364
365 The following compressors are recommended: [``'zlib'``, ``'zstd'``, ``'lz4'``]
366
367 Memory mapping is not possible in this case at present. Possibly support can
368 be added for memory mapping with `c-blosc2`.
369 '''
370 if not BLOSC_PRESENT:
371 raise ImportError( '`blosc` is not installed, cannot decompress file.' )
372
373 if n_threads == None:
374 blosc.nthreads = DEFAULT_N_THREADS
375 else:
376 blosc.nthreads = n_threads
377
378 dims = header['dimensions']
379 dtype = header['dtype']
380 if slices > 0:
381 image = []
382 n_frames = dims[0] // slices
383 else:
384 image = np.empty(dims, dtype=dtype)
385 n_frames = dims[0]
386
387 if slices > 1:
388 target_shape = (slices, dims[1], dims[2])
389 else:
390 target_shape = (dims[1], dims[2])
391 # target_shape = (dims[1], dims[2])
392 blosc_chunk_pos = DEFAULT_HEADER_LEN + header['extendedBytes']
393
394 # NOTE: each channel of each frame is separately compressed by blosc,
395 # so that if slices is not what was originally input, each slice can
396 # be decompressed individually.
397 if slices == 1: # List of 2D frames
398 for J in range(n_frames):
399 f.seek(blosc_chunk_pos)
400 ((nbytes, blockSize, ctbytes), (ver_info)) = readBloscHeader(f)
401 f.seek(blosc_chunk_pos)
402 image.append(np.frombuffer(
403 blosc.decompress(f.read(ctbytes)), dtype=dtype).reshape(target_shape))
404 blosc_chunk_pos += (ctbytes)
405 elif slices > 1: # List of 3D frames
406 for J in range(n_frames):
407 frame = np.empty(target_shape, dtype=dtype)
408 for I in range(slices):
409 f.seek(blosc_chunk_pos)
410 ((nbytes, blockSize, ctbytes), (ver_info)) = readBloscHeader(f)
411 f.seek(blosc_chunk_pos)
412 frame[I,:,:] = np.frombuffer(
413 blosc.decompress(f.read(ctbytes)), dtype=dtype).reshape(target_shape[1:])
414 blosc_chunk_pos += (ctbytes)
415 image.append(frame)
416 else: # Monolithic frame
417 for J in range(n_frames):
418 f.seek(blosc_chunk_pos)
419 ((nbytes, blockSize, ctbytes), (ver_info)) = readBloscHeader(f)
420 f.seek(blosc_chunk_pos)
421 image[J,:,:] = np.frombuffer(
422 blosc.decompress(f.read(ctbytes)), dtype=dtype).reshape(target_shape)
423 blosc_chunk_pos += (ctbytes)
424
425
426 if header['MRCtype'] == 101:
427 # Seems the 4-bit is interlaced
428 if slices > 0:
429 raise NotImplementedError('MRC type 101 (uint4) not supported with return as `list`')
430 interlaced_image = image
431
432 image = np.empty(np.prod(header['dimensions']), dtype=dtype)
433 # Bit-shift and Bit-and to seperate decimated pixels
434 image[0::2] = np.left_shift(interlaced_image, 4) / 15
435 image[1::2] = np.right_shift(interlaced_image, 4)
436
437 if not slices > 0:
438 image = np.squeeze(image)
439
440 return image, header
441
442
443 def readBloscHeader(filehandle):
444 '''
445 Reads in the 16 byte header file from a blosc chunk. Blosc header format
446 for each chunk is as follows::
447
448 |-0-|-1-|-2-|-3-|-4-|-5-|-6-|-7-|-8-|-9-|-A-|-B-|-C-|-D-|-E-|-F-|
449 ^ ^ ^ ^ | nbytes | blocksize | ctbytes |
450 | | | |
451 | | | +--typesize
452 | | +------flags
453 | +----------versionlz
454 +--------------version
455 '''
456 [version, versionlz, flags, typesize] = np.fromfile(filehandle, dtype='uint8', count=4)
457 [nbytes, blocksize, ctbytes] = np.fromfile(filehandle, dtype='uint32', count=3)
458 return ([nbytes, blocksize, ctbytes], [version, versionlz, flags, typesize])
459
460
461 def readMRCHeader(MRCfilename, slices=None, endian='le', fileConvention = 'ccpem', pixelunits=u'\\AA'):
462 '''
463 Reads in the first 1024 bytes from an MRC file and parses it into a Python
464 dictionary, yielding header information. This function is not intended to be
465 called by the user under typical usage.
466
467 Parameters
468 ----------
469 As per `readMRC`
470
471 Returns
472 -------
473 header: dict
474 All found meta-data in the header and extended header packaged into
475 a dictionary.
476 '''
477 if endian == 'le':
478 endchar = '<'
479 else:
480 endchar = '>'
481 dtype_i4 = np.dtype(endchar + 'i4')
482 dtype_f4 = np.dtype(endchar + 'f4')
483
484 header = {}
485 with open(MRCfilename, 'rb') as f:
486 # Grab version information early
487 f.seek(224)
488 mrcz_version = _getMRCZVersion(f.read(80))
489
490 # diagStr = ''
491 # Get dimensions, in format [nz, ny, nx] (stored as [nx,ny,nz] in the file)
492 f.seek(0)
493 header['dimensions'] = np.flipud(np.fromfile(f, dtype=dtype_i4, count=3))
494
495 header['MRCtype'] = int(np.fromfile(f, dtype=dtype_i4, count=1)[0])
496 # Hack to fix lack of standard endian indication in the file header
497 if header['MRCtype'] > 16000000:
498 # Endianess found to be backward
499 header['MRCtype'] = int(np.asarray(header['MRCtype']).byteswap()[0])
500 header['dimensions'] = header['dimensions'].byteswap()
501 if endchar == '<':
502 endchar = '>'
503 else:
504 endchar = '<'
505 dtype_i4 = np.dtype(endchar + 'i4')
506 dtype_f4 = np.dtype(endchar + 'f4')
507
508 # Extract compressor from dtype > MRC_COMP_RATIO
509 header['compressor'] = COMPRESSOR_ENUM[np.floor_divide(header['MRCtype'], MRC_COMP_RATIO)]
510 header['MRCtype'] = np.mod(header['MRCtype'], MRC_COMP_RATIO)
511 logger.debug('compressor: %s, MRCtype: %s' % (str(header['compressor']),str(header['MRCtype'])))
512
513 fileConvention = fileConvention.lower()
514
515 if fileConvention == 'eman2':
516 try:
517 header['dtype'] = EMAN2_ENUM[header['MRCtype']]
518 except:
519 raise ValueError('Error: unrecognized EMAN2-MRC data type = ' + str(header['MRCtype']))
520
521 elif fileConvention == 'ccpem': # Default is CCPEM
522 try:
523 header['dtype'] = CCPEM_ENUM[header['MRCtype']]
524 except:
525 raise ValueError('Error: unrecognized CCPEM-MRC data type = ' + str(header['MRCtype']))
526 else:
527 raise ValueError('Error: unrecognized MRC file convention: {}'.format(fileConvention))
528
529 # Apply endian-ness to NumPy dtype
530 header['dtype'] = endchar + header['dtype']
531
532 # slices is z-axis per frame for list-of-arrays representation
533
534 if slices is None:
535 # We had a bug in version <= 0.4.1 where we wrote the dimensions
536 # into both (Nx, Ny, Nz) AND (Mx, My, Mz), therefore the slicing
537 # is essentially unknown (and wrong). So we have this version
538 # check where we force slices to be 1 (i.e. we assume it is a
539 # stack of 2D images).
540 if mrcz_version is not None and mrcz_version < StrictVersion('0.5.0'):
541 logger.warning('MRCZ version < 0.5.0 for file {}, assuming slices == 1.'.format(MRCfilename))
542 slices = 1
543 else:
544 f.seek(36)
•545 slices = int(np.fromfile(f, dtype=dtype_i4, count=1)[0])
546
547
548 # Read in pixelsize
549 f.seek(40)
550 cellsize = np.fromfile(f, dtype=dtype_f4, count=3)
551 header['pixelsize'] = np.flipud( cellsize ) / header['dimensions']
552 # MRC is Angstroms by convention
553 header['pixelunits'] = pixelunits
554
555 # '\AA' will eventually be deprecated, please cease using it.
•556 if header['pixelunits'] == r'\\AA' or header['pixelunits'] == r'\AA':
557 pass
•558 elif header['pixelunits'] == r'\mum':
559 header['pixelsize'] *= 1E-5
560 elif header['pixelunits'] == u'pm':
561 header['pixelsize'] *= 100.0
562 else: # Default to nm
563 header['pixelsize'] *= 0.1
564
565 # Read in [X,Y,Z] array ordering
566 # Currently I don't use this
567 # f.seek(64)
568 # axesTranpose = np.fromfile( f, dtype=endchar + 'i4', count=3 ) - 1
569
570 # Read in statistics
571 f.seek(76)
572 header['minImage'], header['maxImage'], header['meanImage'] = np.fromfile(f, dtype=dtype_f4, count=3)
573
574 # Size of meta-data
575 f.seek(92)
•576 header['extendedBytes'] = int(np.fromfile(f, dtype=dtype_i4, count=1)[0])
577 if header['extendedBytes'] > 0:
578 f.seek(104)
579 header['metaId'] = f.read(4)
580
581 # Read in kV, C3, and gain
582 f.seek(132)
583 microscope_state = np.fromfile(f, dtype=dtype_f4, count=3)
584 header['voltage'] = float(microscope_state[0])
585 header['C3'] = float(microscope_state[1])
586 header['gain'] = float(microscope_state[2])
587
588 # Read in size of packed data
589 f.seek(144)
590 # Have to convert to Python int to avoid index warning.
591 header['packedBytes'] = struct.unpack('q', f.read(8))
592
593 # Now read in JSON meta-data if present
594 if 'metaId' in header and header['metaId'] == b'json':
595 f.seek(DEFAULT_HEADER_LEN)
596 meta = json.loads(f.read(header['extendedBytes'] ).decode('utf-8'))
597 for key, value in meta.items():
598 if key not in header:
599 header[key] = value
600 return header, slices
601
602 def writeMRC(input_image, MRCfilename, meta=None, endian='le', dtype=None,
603 pixelsize=[0.1,0.1,0.1], pixelunits=u'\\AA', shape=None,
604 voltage=0.0, C3=0.0, gain=1.0, compressor=None, clevel=1,
605 n_threads=None, quickStats=True, idx=None):
•606 r'''
607 Write a conventional MRC file, or a compressed MRCZ file to disk. If
608 compressor is ``None``, then backwards compatibility with other MRC libraries
609 should be preserved. Other libraries will not, however, recognize
610 the JSON extended meta-data.
611
612 Parameters
613 ----------
614 input_image: Union[numpy.ndarray, list[numpy.ndarray]]
615 The image data to write, should be a 1-3 dimension ``numpy.ndarray``
616 or a list of 2-dimensional ``numpy.ndarray``s.
617 meta: dict
618 will be serialized by JSON and written into the extended header. Note
619 that ``rapidjson`` (the default) or ``json`` (the fallback) cannot
620 serialize all Python objects, so sanitizing ``meta`` to remove non-standard
621 library data structures is advisable, including ``numpy.ndarray`` values.
622 dtype: Union[numpy.dtype, str]
623 will cast the data before writing it.
624 pixelsize: Tuple[x,y,z]
625 is [z,y,x] pixel size (singleton values are ok for square/cubic pixels)
626 pixelunits: str = u'\\AA'
627 one of
628 - ``'\\AA'`` for Angstroms
629 - ``'pm'`` for picometers
630 - ``'\mum'`` for micrometers
631 - ``'nm'`` for nanometers.
632 MRC standard is always Angstroms, so pixelsize is converted internally
633 from nm to Angstroms as needed.
634 shape: Optional[Tuple[int]]
635 is only used if you want to later append to the file, such as
636 merging together Relion particles for Frealign. Not recommended and
637 only present for legacy reasons.
638 voltage: float = 300.0
639 accelerating potential in keV
640 C3: float = 2.7
641 spherical aberration in mm
642 gain: float = 1.0
643 detector gain in units (counts/primary electron)
644 compressor: str = None
645 is a choice of ``None, 'lz4', 'zlib', 'zstd'``, plus ``'blosclz'``, ``'lz4hc'``
646 - ``'lz4'`` is generally the fastest.
647 - ``'zstd'`` generally gives the best compression performance, and is still almost
648 as fast as 'lz4' with ``clevel == 1``.
649 clevel: int = 1
650 the compression level, 1 is fastest, 9 is slowest. The compression ratio
651 will rise slowly with clevel (but not as fast as the write time slows
652 down).
653 n_threads: int = None
654 number of threads to use for blosc compression. Defaults to number of
655 virtual cores if ``== None``.
656 quickStats: bool = True
657 estimates the image mean, min, max from the first frame only, which
658 saves computational time for image stacks. Generally strongly advised to
659 be ``True``.
660 idx
661 can be used to write an image or set of images starting at a specific
662 position in the MRC file (which may already exist). Index of first image
663 is 0. A negative index can be used to count backwards. If omitted, will
664 write whole stack to file. If writing to an existing file, compression
665 or extended MRC2014 headers are currently not supported with this option.
666
667 Returns
668 -------
669 ``None``
670
671 Warning
672 -------
673 MRC definitions are not consistent. Generally we support the CCPEM2014 schema
674 as much as possible.
675 '''
676
677 if not BLOSC_PRESENT and compressor is not None:
678 raise ImportError('`blosc` is not installed, cannot use file compression.')
679
680 # For dask, we don't want to import dask, but we can still work-around how to
681 # check its type without isinstance()
682 image_type = type(input_image)
683 if image_type.__module__ == 'dask.array.core' and image_type.__name__ == 'Array':
684 # Ideally it would be faster to iterate over the chunks and pass each one
685 # to blosc but that likely requires c-blosc2
686 input_image = input_image.__array__()
687 dims = input_image.shape
688
689 slices = 0
690 global WARNED_ABOUT_CASTING_F64, WARNED_ABOUT_CASTING_C128
691
692 if isinstance(input_image, (tuple,list)):
693 shape = input_image[0].shape
694 ndim = input_image[0].ndim
695 if ndim == 3:
696 slices = shape[0]
697 shape = shape[1:]
698 elif ndim == 2:
699 slices = 1
700 else:
701 raise ValueError('For a sequence of arrays, only 2D or 3D arrays are handled.')
702
703 dims = np.array([len(input_image)*slices, shape[0], shape[1]])
704
705 # Verify that each image in the list is the same 2D shape and dtype
706 first_shape = input_image[0].shape
707 first_dtype = input_image[0].dtype
708
709 # Cast float64 -> float32, and complex128 -> complex64
710 for J, z_slice in enumerate(input_image):
711 assert(np.all(z_slice.shape == first_shape))
712
713 if z_slice.dtype == np.float64 or z_slice.dtype == float:
714 if not WARNED_ABOUT_CASTING_F64:
715 logger.warn('Casting {} to `numpy.float32`, further warnings will be suppressed.'.format(MRCfilename))
716 WARNED_ABOUT_CASTING_F64 = True
717 input_image[J] = z_slice.astype(np.float32)
718 elif z_slice.dtype == np.complex128:
719 if not WARNED_ABOUT_CASTING_C128:
720 logger.warn('Casting {} to `numpy.complex64`, further warnings will be suppressed.'.format(MRCfilename))
721 WARNED_ABOUT_CASTING_C128 = True
722 input_image[J] = z_slice.astype(np.complex64)
723 else:
724 assert(z_slice.dtype == input_image[0].dtype)
725
726
727 else: # Array-'like' object
728 dims = input_image.shape
729 if input_image.ndim == 2:
730 # If it's a 2D image we force it to 3D - this makes life easier later:
731 input_image = input_image.reshape((1, input_image.shape[0], input_image.shape[1]))
732
733 # Cast float64 -> float32, and complex128 -> complex64
734 if input_image.dtype == np.float64 or input_image.dtype == float:
735 if not WARNED_ABOUT_CASTING_F64:
736 logger.warn('Casting {} to `numpy.float64`'.format(MRCfilename))
737 WARNED_ABOUT_CASTING_F64 = True
738 input_image = input_image.astype(np.float32)
739 elif input_image.dtype == np.complex128:
740 if not WARNED_ABOUT_CASTING_C128:
741 logger.warn('Casting {} to `numpy.complex64`'.format(MRCfilename))
742 WARNED_ABOUT_CASTING_C128 = True
743 input_image = input_image.astype(np.complex64)
744
745 # We will need this regardless if writing to an existing file or not:
746 if endian == 'le':
747 endchar = '<'
748 else:
749 endchar = '>'
750
751 # We now check if we have to create a new header (i.e. new file) or not. If
752 # the file exists, but idx is 'None', it will be replaced by a new file
753 # with new header anyway:
754 if os.path.isfile(MRCfilename):
755 if idx == None:
756 idxnewfile = True
757 else:
758 idxnewfile = False
759 else:
760 idxnewfile = True
761
762
763 if idxnewfile:
764 if dtype == 'uint4' and compressor != None:
765 raise TypeError('uint4 packing is not compatible with compression, use int8 datatype.')
766
767 header = {'meta': meta}
768 if dtype == None:
769 if slices > 0:
770 header['dtype'] = endchar + input_image[0].dtype.descr[0][1].strip('<>|')
771 else:
772 header['dtype'] = endchar + input_image.dtype.descr[0][1].strip('<>|')
773 else:
774 header['dtype'] = dtype
775
776 # Now we need to filter dtype to make sure it's actually acceptable to MRC
777 if not header['dtype'].strip('<>|') in REVERSE_CCPEM_ENUM:
778 raise TypeError('ioMRC.MRCExport: Unsupported dtype cast for MRC %s' % header['dtype'])
779
780 header['dimensions'] = dims
781
782 header['pixelsize'] = pixelsize
783 header['pixelunits'] = pixelunits
784 header['shape'] = shape
785
786 # This overhead calculation is annoying but many 3rd party tools that use
787 # MRC require these statistical parameters.
788 if bool(quickStats):
789 if slices > 0:
790 first_image = input_image[0]
791 else:
792 first_image = input_image[0,:,:]
793
794 imMin = first_image.real.min(); imMax = first_image.real.max()
795 header['maxImage'] = imMax
796 header['minImage'] = imMin
797 header['meanImage'] = 0.5*(imMax + imMin)
798 else:
799 if slices > 0:
800 header['maxImage'] = np.max( [z_slice.real.max() for z_slice in input_image] )
801 header['minImage'] = np.min( [z_slice.real.min() for z_slice in input_image] )
802 header['meanImage'] = np.mean( [z_slice.real.mean() for z_slice in input_image] )
803 else:
804 header['maxImage'] = input_image.real.max()
805 header['minImage'] = input_image.real.min()
806 header['meanImage'] = input_image.real.mean()
807
808 header['voltage'] = voltage
809 if not bool( header['voltage'] ):
810 header['voltage'] = 0.0
811 header['C3'] = C3
812 if not bool( header['C3'] ):
813 header['C3'] = 0.0
814 header['gain'] = gain
815 if not bool( header['gain'] ):
816 header['gain'] = 1.0
817
818 header['compressor'] = compressor
819 header['clevel'] = clevel
820 if n_threads == None and BLOSC_PRESENT:
821 n_threads = DEFAULT_N_THREADS
822 header['n_threads'] = n_threads
823
824 if dtype == 'uint4':
825 if slices > 0:
826 raise NotImplementedError('Saving of lists of arrays not supported for `dtype=uint4`')
827 # Decimate to packed 4-bit
828 input_image = input_image.astype('uint8')
829 input_image = input_image[:,:,::2] + np.left_shift(input_image[:,:,1::2],4)
830
831 else: # We are going to append to an already existing file:
832 # So we try to figure out its header with 'CCPEM' or 'eman2' file conventions:
833 try:
834 header, slices = readMRCHeader(MRCfilename, slices=None, endian=endian, fileConvention='CCPEM', pixelunits=pixelunits)
835
836 except ValueError:
837 try:
838 header, slices = readMRCHeader(MRCfilename, slices=None, endian=endian, fileConvention='eman2', pixelunits=pixelunits)
839 except ValueError:
840 # If neither 'CCPEM' nor 'eman2' formats satisfy:
841 raise ValueError('Error: unrecognized MRC type for file: %s ' % MRCfilename)
842
843 # If the file already exists, its X,Y dimensions must be consistent with the current image to be written:
844 if np.any( header['dimensions'][1:] != input_image.shape[1:]):
845 raise ValueError('Error: x,y dimensions of image do not match that of MRC file: %s ' % MRCfilename)
846 # TO DO: check also consistency of dtype?
847
848 if 'meta' not in header.keys():
849 header['meta'] = meta
850
851 # Now that we have a proper header, we go into the details of writing to a specific position:
852 if idx != None:
853 if header['compressor'] != None:
854 raise RuntimeError('Writing at arbitrary positions not supported for compressed files. Compressor = %s' % header['compressor'])
855
856 idx = int(idx)
857 # Force 2D to 3D dimensions:
858 if len( header['dimensions'] ) == 2:
859 header['dimensions'] = np.array([1, header['dimensions'][0], header['dimensions'][1]])
860
861 # Convert negative index to equivalent positive index:
862 if idx < 0:
863 idx = header['dimensions'][0] + idx
864
865 # Just check if the desired image is within the stack range:
866 # In principle we could write to a position beyond the limits of the file (missing slots would be filled with zeros), but let's avoid that the user writes a big file with zeros by mistake. So only positions within or immediately consecutive to the stack are allowed:
867 if idx < 0 or idx > header['dimensions'][0]:
868 raise ValueError( 'Error: image or slice index out of range. idx = %d, z_dimension = %d' % (idx, header['dimensions'][0]) )
869
870 # The new Z dimension may be larger than that of the existing file, or even of the new file, if an index larger than the current stack is specified:
871 newZ = idx + input_image.shape[0]
872 if newZ > header['dimensions'][0]:
873 header['dimensions'] = np.array([idx + input_image.shape[0], header['dimensions'][1], header['dimensions'][2]])
874
875 # This offset will be applied to f.seek():
876 offset = idx * np.prod(header['dimensions'][1:]) * np.dtype(header['dtype']).itemsize
877
878 else:
879 offset = 0
880
881
882 __MRCExport(input_image, header, MRCfilename, slices,
883 endchar=endchar, offset=offset, idxnewfile=idxnewfile)
884
885
886 def __MRCExport(input_image, header, MRCfilename, slices,
887 endchar='<', offset=0, idxnewfile=True):
888 '''
889 MRCExport private interface with a dictionary rather than a mess of function
890 arguments.
891 '''
892
893 if idxnewfile: # If forcing a new file we truncate it even if it already exists:
894 fmode = 'wb'
895 else: # Otherwise we'll just update its header and append images as required:
896 fmode = 'rb+'
897
898 with open(MRCfilename, fmode, buffering=BUFFERSIZE) as f:
899 extendedBytes = writeMRCHeader(f, header, slices, endchar=endchar)
900 f.seek(DEFAULT_HEADER_LEN + extendedBytes + offset)
901
902 dtype = header['dtype']
903 if ('compressor' in header) \
904 and (header['compressor'] in REVERSE_COMPRESSOR_ENUM) \
905 and (REVERSE_COMPRESSOR_ENUM[header['compressor']]) > 0:
906 # compressed MRCZ
907 logger.debug('Compressing %s with compressor %s%d' %
908 (MRCfilename, header['compressor'], header['clevel']))
909
910 applyCast = False
911 if slices > 0:
912 chunkSize = input_image[0].size
913 typeSize = input_image[0].dtype.itemsize
914 if dtype != 'uint4' and input_image[0].dtype != dtype:
915 applyCast = True
916 else:
917 chunkSize = input_image[0,:,:].size
918 typeSize = input_image.dtype.itemsize
919 if dtype != 'uint4' and input_image.dtype != dtype:
920 applyCast = True
921
922 blosc.set_nthreads(header['n_threads'])
923 # for small image dimensions we need to scale blocksize appropriately
924 # so we use the available cores
925 block_size = np.minimum(BLOSC_BLOCK, chunkSize//header['n_threads'])
926 blosc.set_blocksize(block_size)
927
928 header['packedBytes'] = 0
929
930 clevel = header['clevel']
931 cname = header['compressor']
932
933 # For 3D frames in lists, we need to further sub-divide each frame
934 # into slices so that each channel is compressed seperately by
935 # blosc.
936 if slices > 1:
937 deep_image = input_image # grab a reference
938 input_image = []
939 for frame in deep_image:
940 for I in range(slices):
941 input_image.append(frame[I,:,:])
942
943 for J, frame in enumerate(input_image):
944 if applyCast:
945 frame = frame.astype(dtype)
946
947 if frame.flags['C_CONTIGUOUS'] and frame.flags['ALIGNED']:
948 # Use pointer
949 compressedData = blosc.compress_ptr(frame.__array_interface__['data'][0],
950 frame.size,
951 typeSize,
952 clevel=header['clevel'],
953 shuffle=blosc.BITSHUFFLE,
954 cname=header['compressor'])
955 else:
956 # Use tobytes, which is slower in benchmarking
957 compressedData = blosc.compress(frame.tobytes(),
958 typeSize,
959 clevel=clevel,
960 shuffle=blosc.BITSHUFFLE,
961 cname=cname)
962
963
964 f.write(compressedData)
965 header['packedBytes'] += len(compressedData)
966
967 # Rewind and write out the total compressed size
968 f.seek(144)
969 np.int64(header['packedBytes']).astype(endchar + 'i8').tofile(f)
970
971 else: # vanilla MRC
972 if slices > 0:
973 if dtype != 'uint4' and dtype != input_image[0].dtype:
974 for z_slice in input_image:
975 z_slice.astype(dtype).tofile(f)
976 else:
977 for z_slice in input_image:
978 z_slice.tofile(f)
979 else:
980 if dtype != 'uint4' and dtype != input_image.dtype:
981 input_image = input_image.astype(dtype)
982 input_image.tofile(f)
983
984
985 return
986
987 def writeMRCHeader(f, header, slices, endchar='<'):
988 '''
989 Parameters
990 ----------
991 Writes a header to the file-like object ``f``, requires a dict
992 called ``header`` to parse the appropriate fields.
993
994 Returns
995 -------
996 ``None``
997
998 Note
999 ----
1000 Use `defaultHeader()` to retrieve an example with all potential fields.
1001 '''
1002 dtype_f4 = endchar + 'f4'
1003 dtype_i4 = endchar + 'i4'
1004
1005 f.seek(0)
1006 # Write dimensions
1007 if len(header['dimensions']) == 2: # force to 3-D
1008 dimensions = np.array([1, header['dimensions'][0], header['dimensions'][1]])
1009 else:
1010 dimensions = np.array(header['dimensions'])
1011
1012 # Flip to Fortran order
1013 dimensions = np.flipud(dimensions)
1014 dimensions.astype(dtype_i4).tofile(f)
1015
1016 # 64-bit floats are automatically down-cast
1017 dtype = header['dtype'].lower().strip( '<>|' )
1018 try:
1019 MRCmode = np.int32(REVERSE_CCPEM_ENUM[dtype]).astype(endchar + 'i4')
1020 except:
1021 raise ValueError('Warning: Unknown dtype for MRC encountered = ' + str(dtype))
1022
1023 # Add 1000 * COMPRESSOR_ENUM to the dtype for compressed data
1024 if ('compressor' in header
1025 and header['compressor'] in REVERSE_COMPRESSOR_ENUM
1026 and REVERSE_COMPRESSOR_ENUM[header['compressor']] > 0):
1027 header['compressor'] = header['compressor'].lower()
1028 MRCmode += MRC_COMP_RATIO * REVERSE_COMPRESSOR_ENUM[header['compressor']]
1029
1030 # How many bytes in an MRCZ file, so that the file can be appended-to.
1031 try:
1032 f.seek(144)
1033 np.int32( header['packedBytes'] ).astype(endchar + 'i8').tofile(f)
1034 except:
1035 # This is written afterward so we don't try to keep the entire compressed file in RAM
1036 pass
1037
1038 f.seek(12)
1039 MRCmode.tofile(f)
1040
1041 # Print NXSTART, NYSTART, NZSTART
1042 np.array([0, 0, 0], dtype=dtype_i4).tofile(f)
1043
1044 # Print MX, MY, MZ, the sampling. We only allow for slicing along the z-axis,
1045 # e.g. for multi-channel STEM.
1046 f.seek(36)
1047 np.int32(slices).astype(dtype_i4).tofile(f)
1048
1049 # Print cellsize = pixelsize * dimensions
1050 # '\AA' will eventually be deprecated (probably in Python 3.7/8), please cease using it.
•1051 if header['pixelunits'] == r'\\AA' or header['pixelunits'] == r'\AA':
1052 AApixelsize = np.array(header['pixelsize'])
•1053 elif header['pixelunits'] == r'\mum':
1054 AApixelsize = np.array(header['pixelsize'])*10000.0
1055 elif header['pixelunits'] == 'pm':
1056 AApixelsize = np.array(header['pixelsize'])/100.0
1057 else: # Default is nm
1058 AApixelsize = np.array(header['pixelsize'])*10.0
1059
1060 # The above AApixelsize insures we cannot have an array of len=1 here
1061 if isinstance( AApixelsize, np.ndarray ) and AApixelsize.size == 1:
1062 cellsize = np.array([AApixelsize,AApixelsize,AApixelsize]) * dimensions
1063 elif not isinstance( AApixelsize, (list,tuple,np.ndarray) ):
1064 cellsize = np.array([AApixelsize,AApixelsize,AApixelsize]) * dimensions
1065 elif len(AApixelsize) == 2:
1066 # Default to z-axis pixelsize of 10.0 Angstroms
1067 cellsize = np.flipud(np.array( [10.0, AApixelsize[0], AApixelsize[1]])) * dimensions
1068 else:
1069 cellsize = np.flipud(np.array( AApixelsize )) * dimensions
1070
1071 f.seek(40)
1072 np.array(cellsize, dtype=dtype_f4).tofile(f)
1073 # Print default cell angles
1074 np.array([90.0,90.0,90.0], dtype=dtype_f4).tofile(f)
1075
1076 # Print axis associations (we use C ordering internally in all Python code)
1077 np.array([1,2,3], dtype=dtype_i4).tofile(f)
1078
1079 # Print statistics (if available)
1080 f.seek(76)
1081 if 'minImage' in header:
1082 np.float32(header['minImage']).astype(dtype_f4).tofile(f)
1083 else:
1084 np.float32(0.0).astype(dtype_f4).tofile(f)
1085 if 'maxImage' in header:
1086 np.float32(header['maxImage']).astype(dtype_f4).tofile(f)
1087 else:
1088 np.float32(1.0).astype(dtype_f4).tofile(f)
1089 if 'meanImage' in header:
1090 np.float32(header['meanImage']).astype(dtype_f4).tofile(f)
1091 else:
1092 np.float32(0.0).astype(dtype_f4).tofile(f)
1093
1094 # We'll put the compressor info and number of compressed bytes in 132-204
1095 # and new metadata
1096 # RESERVED: 132: 136: 140 : 144 for voltage, C3, and gain
1097 f.seek(132)
1098 if 'voltage' in header:
1099 np.float32(header['voltage']).astype(dtype_f4).tofile(f)
1100 if 'C3' in header:
1101 np.float32(header['C3']).astype(dtype_f4).tofile(f)
1102 if 'gain' in header:
1103 np.float32(header['gain']).astype(dtype_f4).tofile(f)
1104
1105
1106 # Magic MAP_ indicator that tells us this is in-fact an MRC file
1107 f.seek(208)
1108 f.write(b'MAP ')
1109 # Write a machine stamp, '17,17' for big-endian or '68,65' for little
1110 # Note that the MRC format doesn't indicate the endianness of the endian
1111 # identifier...
1112 f.seek(212)
1113 if endchar == '<':
1114 f.write(struct.pack(b'BB', 68, 65))
1115 else:
1116 f.write(struct.pack(b'BB', 17, 17))
1117
1118 # Write b'MRCZ<version>' into labels
1119 f.seek(220)
1120 f.write(struct.pack(b'i', 1)) # We have one label
1121 f.write(b'MRCZ' + __version__.encode('ascii'))
1122
1123 # Extended header, if meta is not None
1124 if isinstance(header['meta'], dict):
1125 jsonMeta = json.dumps(header['meta'], default=_defaultMetaSerialize).encode('utf-8')
1126
1127 jsonLen = len(jsonMeta)
1128 # Length of extended header
1129 f.seek(92)
1130 f.write(struct.pack(endchar+'i', jsonLen))
1131
1132 # 4-byte char ID string of extended metadata type
1133 f.seek(104)
1134 f.write(b'json')
1135
1136 # Go to the extended header
1137 f.seek(DEFAULT_HEADER_LEN)
1138 f.write( jsonMeta )
1139 return jsonLen
1140
1141 # No extended header
1142 return 0
1143
1144 def asyncReadMRC(*args, **kwargs):
1145 '''
1146 Calls `readMRC` in a separate thread and executes it in the background.
1147
1148 Parameters
1149 ----------
1150 Valid arguments are as for `readMRC()`.
1151
1152 Returns
1153 -------
1154 future
1155 A ``concurrent.futures.Future()`` object. Calling ``future.result()``
1156 will halt until the read is finished and returns the image and meta-data
1157 as per a normal call to `readMRC`.
1158
1159 Example
1160 -------
1161
1162 worker = asyncReadMRC( 'someones_file.mrc' )
1163 # Do some work
1164 mrcImage, mrcMeta = worker.result()
1165 '''
1166 return _asyncExecutor.submit(readMRC, *args, **kwargs)
1167
1168 def asyncWriteMRC(*args, **kwargs):
1169 '''
1170 Calls `writeMRC` in a seperate thread and executes it in the background.
1171
1172 Parameters
1173 ----------
1174 Valid arguments are as for `writeMRC()`.
1175
1176 Returns
1177 -------
1178 future
1179 A ``concurrent.futures.Future`` object. If needed, you can call
1180 ``future.result()`` to wait for the write to finish, or check with
1181 ``future.done()``. Most of the time you can ignore the return and let
1182 the system write unmonitored. An exception would be if you need to pass
1183 in the output to a subprocess.
1184
1185 Example
1186 -------
1187
1188 worker = asyncWriteMRC( npImageData, 'my_mrcfile.mrc' )
1189 # Do some work
1190 if not worker.done():
1191 time.sleep(0.001)
1192 # File is written to disk
1193 '''
•1194 return _asyncExecutor.submit(writeMRC, *args, **kwargs)