Registry / data / mrcfile

mrcfile

JSON →
library1.5.4pypypi✓ verified 85d ago

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.

pip install mrcfile
INSTALL
IMPORT
SIG · MRCFILE
M
mrcfile
datapythonv1.5.4
Install
3.7s avg
Import
273ms
Disk
89MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.5.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.271s · 89.6MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.7s · import 0.275s · 86MB
89MB installed
● package 89MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

mrcfile
import mrcfile
numpy
import numpy as np
NumPy is essential for interacting with the data arrays exposed by mrcfile.

This quickstart demonstrates how to create a new MRC file with random data and then open it to inspect its header and data. It uses `mrcfile.new()` for creation and `mrcfile.open()` for reading, both utilizing Python's `with` statement for proper file handling. NumPy is used for data generation and manipulation.

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)
Debug
Known issues
breakingIn 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.
fix
Update direct access to `extended_header` for indexed types to use `mrc.indexed_extended_header` for `mrcfile` objects opened from v1.5.0 onwards. Consider feature-checking with `hasattr(mrc, 'indexed_extended_header')` for backward compatibility.
affects: >=1.5.0
breakingStarting 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.
fix
Be aware that `float16` data may not be readable by older software. If compatibility is critical, explicitly convert `float16` arrays to `float32` before passing them to `mrcfile` functions for saving.
affects: >=1.3.0
gotchaHeader 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).
fix
Be aware of potential precision loss or overflow for extreme data values when relying on header statistics. If maximum precision is required for statistics, calculate them manually using `float64` on the data array.
affects: >=1.4.3
gotchaIf 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.
fix
Call `mrc.update_header_stats()` or `mrc.reset_header_stats()` after modifying `mrc.data` to ensure the header reflects the current data statistics. Alternatively, use `mrc.set_data()` which updates statistics automatically.
affects: All versions
gotchaFailure 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.
fix
Always use `with mrcfile.open(...) as mrc:` or `with mrcfile.new(...) as mrc:` when interacting with MRC files. If using `mrc = mrcfile.open(...)` outside a `with` block (e.g., in an interactive session), remember to call `mrc.close()` explicitly when finished.
affects: All versions
gotchaMRC 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.
fix
When opening potentially corrupt or non-standard files, use `mrcfile.open(filename, permissive=True)`. This will issue warnings instead of exceptions and attempt to interpret the file as far as possible.
affects: All versions
Errors
Common errors & fixes
ValueError: Map ID string not found - not an MRC file, or file is corrupt
The MRC file being opened is either malformed, corrupt, or does not strictly conform to the MRC2014 standard, specifically failing a check on its header fields like the 'MAP ' ID string, machine stamp, or mode number.
fix
Try opening the file using `mrcfile.open('filename.mrc', permissive=True)` to ignore non-critical header errors and attempt to read the file. You can also use `mrcfile.validate('filename.mrc')` to get details on header issues without raising an exception. If the file is opened permissively with write access (`mode='r+'`), you might be able to correct specific header fields, e.g., `mrc.header.map = mrcfile.constants.MAP_ID`.
AttributeError: can't set attribute
The `mrc.data` and `mrc.header` attributes of an `MrcFile` object are designed as views to NumPy arrays and do not support direct assignment of an entirely new array or object to the attribute itself. This is to ensure internal consistency and proper handling of file I/O.
fix
To replace the entire data array, use the `mrc.set_data(new_array)` method. To modify individual fields within the header, access and assign to them directly, for example, `mrc.header.nx = new_value` or `mrc.header.cella = (100.0, 90.0, 80.0)`.
ValueError: operands could not be broadcast together with shapes (X,Y) (A,B)
This error occurs when attempting to perform a NumPy operation (such as addition, multiplication, or other element-wise operations) between the `mrcfile`'s data array (`mrc.data`) and another NumPy array where their dimensions or shapes are incompatible according to NumPy's broadcasting rules.
fix
Ensure that the NumPy arrays involved in the operation have compatible shapes. This often requires explicitly reshaping one or both arrays using methods like `.reshape()`, `np.newaxis` (or `array[:, None]` for adding a new axis), `.transpose()`, or careful slicing to align their dimensions for the intended operation.
Permission denied (e.g., OSError: [Errno 13] Permission denied: 'output.mrc')
The Python script attempting to create or write an MRC file does not have the necessary operating system permissions for the specified output directory, or the target file is currently open and locked by another application.
fix
Ensure that the user account running the Python script has write permissions for the directory where the MRC file is being created or saved. This may involve changing directory permissions, running the script with elevated privileges (e.g., 'Run as administrator' on Windows, or `sudo python script.py` on Linux/macOS), or choosing a different output directory (e.g., your user's home or documents folder). Also, confirm that no other program is currently accessing the file.
Upgrade
Version history
1.5.4latest on PyPI · released Jan 22, 2025
Audit
Dependencies
numpyrequiredmrcfile exposes file headers and data as NumPy arrays and has no other compiled library dependencies.
Agent activity
8 hits · last 30 days
node
6
Resources
mrcfile — pip install mrcfile · libregistry