MRC File I/O Library
mrcfile is a pure Python library designed for reading and writing MRC2014 file format data, commonly used in structural biology for image and volume data. It provides a simple API to expose file headers and data as NumPy arrays. The library is actively maintained, with frequent updates to support new Python and NumPy versions, and to enhance features like large file handling and validation.
Warnings
- breaking In v1.5.0, the `indexed_extended_header` attribute was introduced. Code that previously accessed items in FEI1- and FEI2-type extended headers directly via `extended_header` will now need to use `indexed_extended_header` instead.
- breaking Starting with v1.3.0, `float16` (NumPy `float16`) arrays are now saved in MRC mode 12. Previously, they were widened to `float32` and saved in mode 2. This change can lead to incompatibility with other software that does not yet support MRC mode 12.
- gotcha Header statistics calculation was changed in v1.4.3 to use `float32` instead of `float64` for performance. While faster and less memory-intensive, this can lead to slightly less accurate statistics and potential overflow (to 'inf') if data arrays contain very large values (e.g., larger than 1e19).
- gotcha If you modify the data array directly after opening an `MrcFile` object, the header statistics (min, max, mean, etc.) will become out of date. These are not automatically recalculated.
- gotcha Failure to use a `with` statement or explicitly call `.close()` on `MrcFile` objects can lead to changes not being written to disk and file handles remaining open, potentially causing data loss or resource leaks.
- gotcha MRC files with invalid header fields (e.g., incorrect `map` ID or machine stamp) may raise exceptions by default. This can be problematic when trying to repair corrupt files.
Install
-
pip install mrcfile -
conda install --channel conda-forge mrcfile
Imports
- mrcfile
import mrcfile
- numpy
import numpy as np
Quickstart
import mrcfile
import numpy as np
import os
# Define a filename for the MRC file
filename = 'example.mrc'
# Create a new MRC file with some dummy data
data = np.random.rand(10, 20, 30).astype(np.float32)
with mrcfile.new(filename, data=data) as mrc:
mrc.voxel_size = 1.5 # Set a custom voxel size
print(f"Created {filename} with shape {mrc.data.shape} and voxel size {mrc.voxel_size}")
# Open an existing MRC file in read mode
with mrcfile.open(filename) as mrc:
print(f"Opened {filename}. Data shape: {mrc.data.shape}, dtype: {mrc.data.dtype}")
print(f"Header map ID: {mrc.header.map.decode('ascii')}")
# Accessing a slice of data
first_slice = mrc.data[0, :, :]
print(f"First slice min/max: {first_slice.min()}/{first_slice.max()}")
# Clean up the created file
os.remove(filename)