Debian Codegraph @

mrcz/ioMRC.py

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
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 '''
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))
546
547 # Read in pixelsize
548 f.seek(40)
549 cellsize = np.fromfile(f, dtype=dtype_f4, count=3)
550 header['pixelsize'] = np.flipud( cellsize ) / header['dimensions']
551 # MRC is Angstroms by convention
552 header['pixelunits'] = pixelunits
553
554 # '\AA' will eventually be deprecated, please cease using it.
555 if header['pixelunits'] == u'\\AA' or header['pixelunits'] == u'\AA':
556 pass
557 elif header['pixelunits'] == u'\mum':
558 header['pixelsize'] *= 1E-5
559 elif header['pixelunits'] == u'pm':
560 header['pixelsize'] *= 100.0
561 else: # Default to nm
562 header['pixelsize'] *= 0.1
563
564 # Read in [X,Y,Z] array ordering
565 # Currently I don't use this
566 # f.seek(64)
567 # axesTranpose = np.fromfile( f, dtype=endchar + 'i4', count=3 ) - 1
568
569 # Read in statistics
570 f.seek(76)
571 header['minImage'], header['maxImage'], header['meanImage'] = np.fromfile(f, dtype=dtype_f4, count=3)
572
573 # Size of meta-data
574 f.seek(92)
575 header['extendedBytes'] = int(np.fromfile(f, dtype=dtype_i4, count=1))
576 if header['extendedBytes'] > 0:
577 f.seek(104)
578 header['metaId'] = f.read(4)
579
580 # Read in kV, C3, and gain
581 f.seek(132)
582 microscope_state = np.fromfile(f, dtype=dtype_f4, count=3)
583 header['voltage'] = float(microscope_state[0])
584 header['C3'] = float(microscope_state[1])
585 header['gain'] = float(microscope_state[2])
586
587 # Read in size of packed data
588 f.seek(144)
589 # Have to convert to Python int to avoid index warning.
590 header['packedBytes'] = struct.unpack('q', f.read(8))
591
592 # Now read in JSON meta-data if present
593 if 'metaId' in header and header['metaId'] == b'json':
594 f.seek(DEFAULT_HEADER_LEN)
595 meta = json.loads(f.read(header['extendedBytes'] ).decode('utf-8'))
596 for key, value in meta.items():
597 if key not in header:
598 header[key] = value
599 return header, slices
600
601 def writeMRC(input_image, MRCfilename, meta=None, endian='le', dtype=None,
602 pixelsize=[0.1,0.1,0.1], pixelunits=u'\\AA', shape=None,
603 voltage=0.0, C3=0.0, gain=1.0, compressor=None, clevel=1,
604 n_threads=None, quickStats=True, idx=None):
605 '''
606 Write a conventional MRC file, or a compressed MRCZ file to disk. If
607 compressor is ``None``, then backwards compatibility with other MRC libraries
608 should be preserved. Other libraries will not, however, recognize
609 the JSON extended meta-data.
610
611 Parameters
612 ----------
613 input_image: Union[numpy.ndarray, list[numpy.ndarray]]
614 The image data to write, should be a 1-3 dimension ``numpy.ndarray``
615 or a list of 2-dimensional ``numpy.ndarray``s.
616 meta: dict
617 will be serialized by JSON and written into the extended header. Note
618 that ``rapidjson`` (the default) or ``json`` (the fallback) cannot
619 serialize all Python objects, so sanitizing ``meta`` to remove non-standard
620 library data structures is advisable, including ``numpy.ndarray`` values.
621 dtype: Union[numpy.dtype, str]
622 will cast the data before writing it.
623 pixelsize: Tuple[x,y,z]
624 is [z,y,x] pixel size (singleton values are ok for square/cubic pixels)
625 pixelunits: str = u'\\AA'
626 one of
627 - ``'\\AA'`` for Angstroms
628 - ``'pm'`` for picometers
629 - ``'\mum'`` for micrometers
630 - ``'nm'`` for nanometers.
631 MRC standard is always Angstroms, so pixelsize is converted internally
632 from nm to Angstroms as needed.
633 shape: Optional[Tuple[int]]
634 is only used if you want to later append to the file, such as
635 merging together Relion particles for Frealign. Not recommended and
636 only present for legacy reasons.
637 voltage: float = 300.0
638 accelerating potential in keV
639 C3: float = 2.7
640 spherical aberration in mm
641 gain: float = 1.0
642 detector gain in units (counts/primary electron)
643 compressor: str = None
644 is a choice of ``None, 'lz4', 'zlib', 'zstd'``, plus ``'blosclz'``, ``'lz4hc'``
645 - ``'lz4'`` is generally the fastest.
646 - ``'zstd'`` generally gives the best compression performance, and is still almost
647 as fast as 'lz4' with ``clevel == 1``.
648 clevel: int = 1
649 the compression level, 1 is fastest, 9 is slowest. The compression ratio
650 will rise slowly with clevel (but not as fast as the write time slows
651 down).
652 n_threads: int = None
653 number of threads to use for blosc compression. Defaults to number of
654 virtual cores if ``== None``.
655 quickStats: bool = True
656 estimates the image mean, min, max from the first frame only, which
657 saves computational time for image stacks. Generally strongly advised to
658 be ``True``.
659 idx
660 can be used to write an image or set of images starting at a specific
661 position in the MRC file (which may already exist). Index of first image
662 is 0. A negative index can be used to count backwards. If omitted, will
663 write whole stack to file. If writing to an existing file, compression
664 or extended MRC2014 headers are currently not supported with this option.
665
666 Returns
667 -------
668 ``None``
669
670 Warning
671 -------
672 MRC definitions are not consistent. Generally we support the CCPEM2014 schema
673 as much as possible.
674 '''
675
676 if not BLOSC_PRESENT and compressor is not None:
677 raise ImportError('`blosc` is not installed, cannot use file compression.')
678
679 # For dask, we don't want to import dask, but we can still work-around how to
680 # check its type without isinstance()
681 image_type = type(input_image)
682 if image_type.__module__ == 'dask.array.core' and image_type.__name__ == 'Array':
683 # Ideally it would be faster to iterate over the chunks and pass each one
684 # to blosc but that likely requires c-blosc2
685 input_image = input_image.__array__()
686 dims = input_image.shape
687
688 slices = 0
689 global WARNED_ABOUT_CASTING_F64, WARNED_ABOUT_CASTING_C128
690
691 if isinstance(input_image, (tuple,list)):
692 shape = input_image[0].shape
693 ndim = input_image[0].ndim
694 if ndim == 3:
695 slices = shape[0]
696 shape = shape[1:]
697 elif ndim == 2:
698 slices = 1
699 else:
700 raise ValueError('For a sequence of arrays, only 2D or 3D arrays are handled.')
701
702 dims = np.array([len(input_image)*slices, shape[0], shape[1]])
703
704 # Verify that each image in the list is the same 2D shape and dtype
705 first_shape = input_image[0].shape
706 first_dtype = input_image[0].dtype
707
708 # Cast float64 -> float32, and complex128 -> complex64
709 for J, z_slice in enumerate(input_image):
710 assert(np.all(z_slice.shape == first_shape))
711
712 if z_slice.dtype == np.float64 or z_slice.dtype == float:
713 if not WARNED_ABOUT_CASTING_F64:
714 logger.warn('Casting {} to `numpy.float32`, further warnings will be suppressed.'.format(MRCfilename))
715 WARNED_ABOUT_CASTING_F64 = True
716 input_image[J] = z_slice.astype(np.float32)
717 elif z_slice.dtype == np.complex128:
718 if not WARNED_ABOUT_CASTING_C128:
719 logger.warn('Casting {} to `numpy.complex64`, further warnings will be suppressed.'.format(MRCfilename))
720 WARNED_ABOUT_CASTING_C128 = True
721 input_image[J] = z_slice.astype(np.complex64)
722 else:
723 assert(z_slice.dtype == input_image[0].dtype)
724
725
726 else: # Array-'like' object
727 dims = input_image.shape
728 if input_image.ndim == 2:
729 # If it's a 2D image we force it to 3D - this makes life easier later:
730 input_image = input_image.reshape((1, input_image.shape[0], input_image.shape[1]))
731
732 # Cast float64 -> float32, and complex128 -> complex64
733 if input_image.dtype == np.float64 or input_image.dtype == float:
734 if not WARNED_ABOUT_CASTING_F64:
735 logger.warn('Casting {} to `numpy.float64`'.format(MRCfilename))
736 WARNED_ABOUT_CASTING_F64 = True
737 input_image = input_image.astype(np.float32)
738 elif input_image.dtype == np.complex128:
739 if not WARNED_ABOUT_CASTING_C128:
740 logger.warn('Casting {} to `numpy.complex64`'.format(MRCfilename))
741 WARNED_ABOUT_CASTING_C128 = True
742 input_image = input_image.astype(np.complex64)
743
744 # We will need this regardless if writing to an existing file or not:
745 if endian == 'le':
746 endchar = '<'
747 else:
748 endchar = '>'
749
750 # We now check if we have to create a new header (i.e. new file) or not. If
751 # the file exists, but idx is 'None', it will be replaced by a new file
752 # with new header anyway:
753 if os.path.isfile(MRCfilename):
754 if idx == None:
755 idxnewfile = True
756 else:
757 idxnewfile = False
758 else:
759 idxnewfile = True
760
761
762 if idxnewfile:
763 if dtype == 'uint4' and compressor != None:
764 raise TypeError('uint4 packing is not compatible with compression, use int8 datatype.')
765
766 header = {'meta': meta}
767 if dtype == None:
768 if slices > 0:
769 header['dtype'] = endchar + input_image[0].dtype.descr[0][1].strip('<>|')
770 else:
771 header['dtype'] = endchar + input_image.dtype.descr[0][1].strip('<>|')
772 else:
773 header['dtype'] = dtype
774
775 # Now we need to filter dtype to make sure it's actually acceptable to MRC
776 if not header['dtype'].strip('<>|') in REVERSE_CCPEM_ENUM:
777 raise TypeError('ioMRC.MRCExport: Unsupported dtype cast for MRC %s' % header['dtype'])
778
779 header['dimensions'] = dims
780
781 header['pixelsize'] = pixelsize
782 header['pixelunits'] = pixelunits
783 header['shape'] = shape
784
785 # This overhead calculation is annoying but many 3rd party tools that use
786 # MRC require these statistical parameters.
787 if bool(quickStats):
788 if slices > 0:
789 first_image = input_image[0]
790 else:
791 first_image = input_image[0,:,:]
792
793 imMin = first_image.real.min(); imMax = first_image.real.max()
794 header['maxImage'] = imMax
795 header['minImage'] = imMin
796 header['meanImage'] = 0.5*(imMax + imMin)
797 else:
798 if slices > 0:
799 header['maxImage'] = np.max( [z_slice.real.max() for z_slice in input_image] )
800 header['minImage'] = np.min( [z_slice.real.min() for z_slice in input_image] )
801 header['meanImage'] = np.mean( [z_slice.real.mean() for z_slice in input_image] )
802 else:
803 header['maxImage'] = input_image.real.max()
804 header['minImage'] = input_image.real.min()
805 header['meanImage'] = input_image.real.mean()
806
807 header['voltage'] = voltage
808 if not bool( header['voltage'] ):
809 header['voltage'] = 0.0
810 header['C3'] = C3
811 if not bool( header['C3'] ):
812 header['C3'] = 0.0
813 header['gain'] = gain
814 if not bool( header['gain'] ):
815 header['gain'] = 1.0
816
817 header['compressor'] = compressor
818 header['clevel'] = clevel
819 if n_threads == None and BLOSC_PRESENT:
820 n_threads = DEFAULT_N_THREADS
821 header['n_threads'] = n_threads
822
823 if dtype == 'uint4':
824 if slices > 0:
825 raise NotImplementedError('Saving of lists of arrays not supported for `dtype=uint4`')
826 # Decimate to packed 4-bit
827 input_image = input_image.astype('uint8')
828 input_image = input_image[:,:,::2] + np.left_shift(input_image[:,:,1::2],4)
829
830 else: # We are going to append to an already existing file:
831 # So we try to figure out its header with 'CCPEM' or 'eman2' file conventions:
832 try:
833 header, slices = readMRCHeader(MRCfilename, slices=None, endian=endian, fileConvention='CCPEM', pixelunits=pixelunits)
834
835 except ValueError:
836 try:
837 header, slices = readMRCHeader(MRCfilename, slices=None, endian=endian, fileConvention='eman2', pixelunits=pixelunits)
838 except ValueError:
839 # If neither 'CCPEM' nor 'eman2' formats satisfy:
840 raise ValueError('Error: unrecognized MRC type for file: %s ' % MRCfilename)
841
842 # If the file already exists, its X,Y dimensions must be consistent with the current image to be written:
843 if np.any( header['dimensions'][1:] != input_image.shape[1:]):
844 raise ValueError('Error: x,y dimensions of image do not match that of MRC file: %s ' % MRCfilename)
845 # TO DO: check also consistency of dtype?
846
847 if 'meta' not in header.keys():
848 header['meta'] = meta
849
850 # Now that we have a proper header, we go into the details of writing to a specific position:
851 if idx != None:
852 if header['compressor'] != None:
853 raise RuntimeError('Writing at arbitrary positions not supported for compressed files. Compressor = %s' % header['compressor'])
854
855 idx = int(idx)
856 # Force 2D to 3D dimensions:
857 if len( header['dimensions'] ) == 2:
858 header['dimensions'] = np.array([1, header['dimensions'][0], header['dimensions'][1]])
859
860 # Convert negative index to equivalent positive index:
861 if idx < 0:
862 idx = header['dimensions'][0] + idx
863
864 # Just check if the desired image is within the stack range:
865 # 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:
866 if idx < 0 or idx > header['dimensions'][0]:
867 raise ValueError( 'Error: image or slice index out of range. idx = %d, z_dimension = %d' % (idx, header['dimensions'][0]) )
868
869 # 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:
870 newZ = idx + input_image.shape[0]
871 if newZ > header['dimensions'][0]:
872 header['dimensions'] = np.array([idx + input_image.shape[0], header['dimensions'][1], header['dimensions'][2]])
873
874 # This offset will be applied to f.seek():
875 offset = idx * np.prod(header['dimensions'][1:]) * np.dtype(header['dtype']).itemsize
876
877 else:
878 offset = 0
879
880
881 __MRCExport(input_image, header, MRCfilename, slices,
882 endchar=endchar, offset=offset, idxnewfile=idxnewfile)
883
884
885 def __MRCExport(input_image, header, MRCfilename, slices,
886 endchar='<', offset=0, idxnewfile=True):
887 '''
888 MRCExport private interface with a dictionary rather than a mess of function
889 arguments.
890 '''
891
892 if idxnewfile: # If forcing a new file we truncate it even if it already exists:
893 fmode = 'wb'
894 else: # Otherwise we'll just update its header and append images as required:
895 fmode = 'rb+'
896
897 with open(MRCfilename, fmode, buffering=BUFFERSIZE) as f:
898 extendedBytes = writeMRCHeader(f, header, slices, endchar=endchar)
899 f.seek(DEFAULT_HEADER_LEN + extendedBytes + offset)
900
901 dtype = header['dtype']
902 if ('compressor' in header) \
903 and (header['compressor'] in REVERSE_COMPRESSOR_ENUM) \
904 and (REVERSE_COMPRESSOR_ENUM[header['compressor']]) > 0:
905 # compressed MRCZ
906 logger.debug('Compressing %s with compressor %s%d' %
907 (MRCfilename, header['compressor'], header['clevel']))
908
909 applyCast = False
910 if slices > 0:
911 chunkSize = input_image[0].size
912 typeSize = input_image[0].dtype.itemsize
913 if dtype != 'uint4' and input_image[0].dtype != dtype:
914 applyCast = True
915 else:
916 chunkSize = input_image[0,:,:].size
917 typeSize = input_image.dtype.itemsize
918 if dtype != 'uint4' and input_image.dtype != dtype:
919 applyCast = True
920
921 blosc.set_nthreads(header['n_threads'])
922 # for small image dimensions we need to scale blocksize appropriately
923 # so we use the available cores
924 block_size = np.minimum(BLOSC_BLOCK, chunkSize//header['n_threads'])
925 blosc.set_blocksize(block_size)
926
927 header['packedBytes'] = 0
928
929 clevel = header['clevel']
930 cname = header['compressor']
931
932 # For 3D frames in lists, we need to further sub-divide each frame
933 # into slices so that each channel is compressed seperately by
934 # blosc.
935 if slices > 1:
936 deep_image = input_image # grab a reference
937 input_image = []
938 for frame in deep_image:
939 for I in range(slices):
940 input_image.append(frame[I,:,:])
941
942 for J, frame in enumerate(input_image):
943 if applyCast:
944 frame = frame.astype(dtype)
945
946 if frame.flags['C_CONTIGUOUS'] and frame.flags['ALIGNED']:
947 # Use pointer
948 compressedData = blosc.compress_ptr(frame.__array_interface__['data'][0],
949 frame.size,
950 typeSize,
951 clevel=header['clevel'],
952 shuffle=blosc.BITSHUFFLE,
953 cname=header['compressor'])
954 else:
955 # Use tobytes, which is slower in benchmarking
956 compressedData = blosc.compress(frame.tobytes(),
957 typeSize,
958 clevel=clevel,
959 shuffle=blosc.BITSHUFFLE,
960 cname=cname)
961
962
963 f.write(compressedData)
964 header['packedBytes'] += len(compressedData)
965
966 # Rewind and write out the total compressed size
967 f.seek(144)
968 np.int64(header['packedBytes']).astype(endchar + 'i8').tofile(f)
969
970 else: # vanilla MRC
971 if slices > 0:
972 if dtype != 'uint4' and dtype != input_image[0].dtype:
973 for z_slice in input_image:
974 z_slice.astype(dtype).tofile(f)
975 else:
976 for z_slice in input_image:
977 z_slice.tofile(f)
978 else:
979 if dtype != 'uint4' and dtype != input_image.dtype:
980 input_image = input_image.astype(dtype)
981 input_image.tofile(f)
982
983
984 return
985
986 def writeMRCHeader(f, header, slices, endchar='<'):
987 '''
988 Parameters
989 ----------
990 Writes a header to the file-like object ``f``, requires a dict
991 called ``header`` to parse the appropriate fields.
992
993 Returns
994 -------
995 ``None``
996
997 Note
998 ----
999 Use `defaultHeader()` to retrieve an example with all potential fields.
1000 '''
1001 dtype_f4 = endchar + 'f4'
1002 dtype_i4 = endchar + 'i4'
1003
1004 f.seek(0)
1005 # Write dimensions
1006 if len(header['dimensions']) == 2: # force to 3-D
1007 dimensions = np.array([1, header['dimensions'][0], header['dimensions'][1]])
1008 else:
1009 dimensions = np.array(header['dimensions'])
1010
1011 # Flip to Fortran order
1012 dimensions = np.flipud(dimensions)
1013 dimensions.astype(dtype_i4).tofile(f)
1014
1015 # 64-bit floats are automatically down-cast
1016 dtype = header['dtype'].lower().strip( '<>|' )
1017 try:
1018 MRCmode = np.int32(REVERSE_CCPEM_ENUM[dtype]).astype(endchar + 'i4')
1019 except:
1020 raise ValueError('Warning: Unknown dtype for MRC encountered = ' + str(dtype))
1021
1022 # Add 1000 * COMPRESSOR_ENUM to the dtype for compressed data
1023 if ('compressor' in header
1024 and header['compressor'] in REVERSE_COMPRESSOR_ENUM
1025 and REVERSE_COMPRESSOR_ENUM[header['compressor']] > 0):
1026 header['compressor'] = header['compressor'].lower()
1027 MRCmode += MRC_COMP_RATIO * REVERSE_COMPRESSOR_ENUM[header['compressor']]
1028
1029 # How many bytes in an MRCZ file, so that the file can be appended-to.
1030 try:
1031 f.seek(144)
1032 np.int32( header['packedBytes'] ).astype(endchar + 'i8').tofile(f)
1033 except:
1034 # This is written afterward so we don't try to keep the entire compressed file in RAM
1035 pass
1036
1037 f.seek(12)
1038 MRCmode.tofile(f)
1039
1040 # Print NXSTART, NYSTART, NZSTART
1041 np.array([0, 0, 0], dtype=dtype_i4).tofile(f)
1042
1043 # Print MX, MY, MZ, the sampling. We only allow for slicing along the z-axis,
1044 # e.g. for multi-channel STEM.
1045 f.seek(36)
1046 np.int32(slices).astype(dtype_i4).tofile(f)
1047
1048 # Print cellsize = pixelsize * dimensions
1049 # '\AA' will eventually be deprecated (probably in Python 3.7/8), please cease using it.
1050 if header['pixelunits'] == '\\AA' or header['pixelunits'] == '\AA':
1051 AApixelsize = np.array(header['pixelsize'])
1052 elif header['pixelunits'] == '\mum':
1053 AApixelsize = np.array(header['pixelsize'])*10000.0
1054 elif header['pixelunits'] == 'pm':
1055 AApixelsize = np.array(header['pixelsize'])/100.0
1056 else: # Default is nm
1057 AApixelsize = np.array(header['pixelsize'])*10.0
1058
1059 # The above AApixelsize insures we cannot have an array of len=1 here
1060 if isinstance( AApixelsize, np.ndarray ) and AApixelsize.size == 1:
1061 cellsize = np.array([AApixelsize,AApixelsize,AApixelsize]) * dimensions
1062 elif not isinstance( AApixelsize, (list,tuple,np.ndarray) ):
1063 cellsize = np.array([AApixelsize,AApixelsize,AApixelsize]) * dimensions
1064 elif len(AApixelsize) == 2:
1065 # Default to z-axis pixelsize of 10.0 Angstroms
1066 cellsize = np.flipud(np.array( [10.0, AApixelsize[0], AApixelsize[1]])) * dimensions
1067 else:
1068 cellsize = np.flipud(np.array( AApixelsize )) * dimensions
1069
1070 f.seek(40)
1071 np.array(cellsize, dtype=dtype_f4).tofile(f)
1072 # Print default cell angles
1073 np.array([90.0,90.0,90.0], dtype=dtype_f4).tofile(f)
1074
1075 # Print axis associations (we use C ordering internally in all Python code)
1076 np.array([1,2,3], dtype=dtype_i4).tofile(f)
1077
1078 # Print statistics (if available)
1079 f.seek(76)
1080 if 'minImage' in header:
1081 np.float32(header['minImage']).astype(dtype_f4).tofile(f)
1082 else:
1083 np.float32(0.0).astype(dtype_f4).tofile(f)
1084 if 'maxImage' in header:
1085 np.float32(header['maxImage']).astype(dtype_f4).tofile(f)
1086 else:
1087 np.float32(1.0).astype(dtype_f4).tofile(f)
1088 if 'meanImage' in header:
1089 np.float32(header['meanImage']).astype(dtype_f4).tofile(f)
1090 else:
1091 np.float32(0.0).astype(dtype_f4).tofile(f)
1092
1093 # We'll put the compressor info and number of compressed bytes in 132-204
1094 # and new metadata
1095 # RESERVED: 132: 136: 140 : 144 for voltage, C3, and gain
1096 f.seek(132)
1097 if 'voltage' in header:
1098 np.float32(header['voltage']).astype(dtype_f4).tofile(f)
1099 if 'C3' in header:
1100 np.float32(header['C3']).astype(dtype_f4).tofile(f)
1101 if 'gain' in header:
1102 np.float32(header['gain']).astype(dtype_f4).tofile(f)
1103
1104
1105 # Magic MAP_ indicator that tells us this is in-fact an MRC file
1106 f.seek(208)
1107 f.write(b'MAP ')
1108 # Write a machine stamp, '17,17' for big-endian or '68,65' for little
1109 # Note that the MRC format doesn't indicate the endianness of the endian
1110 # identifier...
1111 f.seek(212)
1112 if endchar == '<':
1113 f.write(struct.pack(b'BB', 68, 65))
1114 else:
1115 f.write(struct.pack(b'BB', 17, 17))
1116
1117 # Write b'MRCZ<version>' into labels
1118 f.seek(220)
1119 f.write(struct.pack(b'i', 1)) # We have one label
1120 f.write(b'MRCZ' + __version__.encode('ascii'))
1121
1122 # Extended header, if meta is not None
1123 if isinstance(header['meta'], dict):
1124 jsonMeta = json.dumps(header['meta'], default=_defaultMetaSerialize).encode('utf-8')
1125
1126 jsonLen = len(jsonMeta)
1127 # Length of extended header
1128 f.seek(92)
1129 f.write(struct.pack(endchar+'i', jsonLen))
1130
1131 # 4-byte char ID string of extended metadata type
1132 f.seek(104)
1133 f.write(b'json')
1134
1135 # Go to the extended header
1136 f.seek(DEFAULT_HEADER_LEN)
1137 f.write( jsonMeta )
1138 return jsonLen
1139
1140 # No extended header
1141 return 0
1142
1143 def asyncReadMRC(*args, **kwargs):
1144 '''
1145 Calls `readMRC` in a separate thread and executes it in the background.
1146
1147 Parameters
1148 ----------
1149 Valid arguments are as for `readMRC()`.
1150
1151 Returns
1152 -------
1153 future
1154 A ``concurrent.futures.Future()`` object. Calling ``future.result()``
1155 will halt until the read is finished and returns the image and meta-data
1156 as per a normal call to `readMRC`.
1157
1158 Example
1159 -------
1160
1161 worker = asyncReadMRC( 'someones_file.mrc' )
1162 # Do some work
1163 mrcImage, mrcMeta = worker.result()
1164 '''
1165 return _asyncExecutor.submit(readMRC, *args, **kwargs)
1166
1167 def asyncWriteMRC(*args, **kwargs):
1168 '''
1169 Calls `writeMRC` in a seperate thread and executes it in the background.
1170
1171 Parameters
1172 ----------
1173 Valid arguments are as for `writeMRC()`.
1174
1175 Returns
1176 -------
1177 future
1178 A ``concurrent.futures.Future`` object. If needed, you can call
1179 ``future.result()`` to wait for the write to finish, or check with
1180 ``future.done()``. Most of the time you can ignore the return and let
1181 the system write unmonitored. An exception would be if you need to pass
1182 in the output to a subprocess.
1183
1184 Example
1185 -------
1186
1187 worker = asyncWriteMRC( npImageData, 'my_mrcfile.mrc' )
1188 # Do some work
1189 if not worker.done():
1190 time.sleep(0.001)
1191 # File is written to disk
1192 '''
1193 return _asyncExecutor.submit(writeMRC, *args, **kwargs)