1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Read and write MRC-2014 files — the standard in cryo-EM and structural
//! biology.
//!
//! This crate handles file I/O, byte-order detection, and type-safe data
//! access so you can focus on your science. It's fast (SIMD, parallel
//! encoding) and works with plain, gzip, and bzip2 files out of the box.
//!
//! # Quick example
//!
//! ```no_run
//! use mrc::{open, create, VoxelBlock};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let reader = open("protein.mrc")?; // auto-detects compression
//! for slice in reader.slices_f32() { // converts to f32 for you
//! let block = slice?;
//! }
//!
//! let mut writer = create("output.mrc")
//! .shape([512, 512, 256])
//! .mode::<f32>()
//! .finish()?;
//! writer.write_block(&VoxelBlock::new(
//! [0, 0, 0], [512, 512, 1],
//! vec![0.0f32; 512 * 512],
//! )?)?;
//! writer.finalize()?;
//! Ok(())
//! }
//! ```
//!
//! # Reading files
//!
//! Open any MRC file with [`open()`] or [`Reader::open`]. Compression is
//! detected from the file's magic bytes — no need to tell it gzip or bzip2.
//!
//! ```no_run
//! # fn main() -> Result<(), mrc::Error> {
//! use mrc::Reader;
//! let reader = Reader::open("tilt_series.mrc")?;
//! println!("{}×{}×{} voxels, mode {:?}",
//! reader.shape().nx, reader.shape().ny, reader.shape().nz,
//! reader.mode());
//! # Ok(()) }
//! ```
//!
//! Then pick an iteration method:
//!
//! * [`slices`](Reader::slices) — one Z-plane at a time
//! * [`slabs`](Reader::slabs) — batches of `k` Z-planes
//! * [`tiles`](Reader::tiles) — arbitrary 3D blocks
//! * [`subregion`](Reader::subregion) — a single block by coordinate
//!
//! Or grab the full volume in one call:
//!
//! * [`read_volume::<T>()`](Reader::read_volume) — full volume as any [`Voxel`] type
//! * [`read_volume_f32()`](Reader::read_volume_f32) — full volume, any mode converted to `f32`
//!
//! Each yields [`VoxelBlock<T>`] — a data chunk with its `offset` and
//! `shape`, so you always know where it belongs.
//!
//! For density maps stored as integers, use [`slices_f32`](Reader::slices_f32)
//! or [`read_volume_f32()`](Reader::read_volume_f32) to get `f32` with
//! automatic mode conversion (no need to match the file's storage type):
//! It converts every MRC mode to `f32` (integer widening, complex→magnitude,
//! the works):
//!
//! ```no_run
//! # fn main() -> Result<(), mrc::Error> {
//! # let reader = mrc::Reader::open("density.mrc")?;
//! for slice in reader.slices_f32() {
//! let block = slice?;
//! println!("slice {} mean density: {:.2}",
//! block.offset[2],
//! block.data.iter().sum::<f32>() / block.data.len() as f32);
//! }
//! # Ok(()) }
//! ```
//!
//! Or read the full volume at once with [`read_volume_f32()`](Reader::read_volume_f32)
//! and wrap with `ndarray` for numpy-like slicing:
//!
//! ```text
//! let block = reader.read_volume_f32()?;
//! let array = ndarray::Array3::from_shape_vec(
//! [reader.shape().nz, reader.shape().ny, reader.shape().nx],
//! block.data,
//! ).unwrap();
//! ```
//!
//! ### Large files
//!
//! When the file does not fit in RAM, use [`MmapReader`] (requires the
//! `mmap` feature). Same iterator API, zero-copy [`slab_as`](MmapReader::slab_as),
//! OS-managed paging.
//!
//! ### Quirky files
//!
//! [`Reader::open_permissive`] opens files with minor header issues as
//! warnings instead of hard errors — handy for data from older instruments.
//!
//! ```no_run
//! # fn main() -> Result<(), mrc::Error> {
//! # use mrc::Reader;
//! let (reader, warnings) = Reader::open_permissive("legacy.mrc")?;
//! for w in &warnings { eprintln!("note: {w}"); }
//! # Ok(()) }
//! ```
//!
//! # Writing files
//!
//! Use [`create()`] to get a [`WriterBuilder`], set the shape and voxel type,
//! then call [`finish`](WriterBuilder::finish).
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use mrc::create;
//! let mut writer = create("output.mrc")
//! .shape([256, 256, 128])
//! .mode::<f32>()
//! .finish()?;
//! # Ok(()) }
//! ```
//!
//! The lifecycle:
//!
//! 1. **Write** blocks with [`write_block`](Writer::write_block). The type
//! `T` matches the file's mode — a compile-time check that prevents
//! accidentally treating bytes as the wrong kind of number.
//! 2. **Finalize** with [`finalize`](Writer::finalize) to rewrite the header.
//! 3. Optionally call [`update_header_stats`](Writer::update_header_stats)
//! before finalize to fill in `dmin`/`dmax`/`dmean`/`rms`.
//!
//! Four backends through the same builder:
//!
//! | Backend | Builder method | Best for |
//! |---|---|---|
//! | [`Writer`] | [`finish()`](WriterBuilder::finish) | General use, writes straight to disk |
//! | [`MmapWriter`] | [`finish_mmap()`](WriterBuilder::finish_mmap) | Very large files (`mmap` feature) |
//! | [`GzipWriter`] | [`finish_gzip()`](WriterBuilder::finish_gzip) | Compressed output (`gzip` feature) |
//! | [`Bzip2Writer`] | [`finish_bzip2()`](WriterBuilder::finish_bzip2) | Compressed output (`bzip2` feature) |
//!
//! # Data modes
//!
//! MRC files encode voxels in one of several numeric modes. [`Mode`]
//! represents them at runtime; [`Voxel`] ties each Rust type to its mode
//! at compile time, catching mismatches before any data is read or written.
//!
//! | Mode | Rust type | Typical use |
//! |---|---|---|
//! | [`Int8`](Mode::Int8) (0) | `i8` | Binary masks |
//! | [`Int16`](Mode::Int16) (1) | `i16` | Raw cryo-EM density |
//! | [`Float32`](Mode::Float32) (2) | `f32` | Processed / reconstructed density |
//! | [`Uint16`](Mode::Uint16) (6) | `u16` | Segmentation labels |
//! | [`Float16`](Mode::Float16) (12) | `f16` | Half-precision storage (feature `f16`) |
//!
//! Complex ([`Int16Complex`], [`Float32Complex`]) and packed 4-bit
//! ([`Packed4Bit`]) modes are also available — see their individual docs.
//!
//! When you don't know the mode ahead of time, use [`slices_f32`](Reader::slices_f32)
//! which converts any mode to `f32`.
//!
//! # Headers
//!
//! The [`Header`] struct mirrors the 1024-byte MRC-2014 fixed header.
//! Every field is a typed public field — dimensions, cell parameters,
//! axis mapping, density statistics, text labels, and more.
//!
//! ```
//! use mrc::Header;
//! let h = Header::new();
//! assert_eq!(h.map, *b"MAP ");
//! ```
//!
//! For fluent construction with validation, use [`HeaderBuilder`]:
//!
//! ```
//! use mrc::HeaderBuilder;
//! let header = HeaderBuilder::new()
//! .shape([512, 512, 256])
//! .mode::<f32>()
//! .build()?;
//! # Ok::<_, mrc::HeaderValidationError>(())
//! ```
//!
//! Three validation levels:
//!
//! * [`validate`](Header::validate) — quick yes / no
//! * [`validate_detailed`](Header::validate_detailed) — tells you exactly
//! what is wrong via [`HeaderValidationError`]
//! * [`validate_permissive`](Header::validate_permissive) — warnings for
//! non-critical issues
//!
//! # Philosophy
//!
//! This crate does **one thing** — read and write MRC files. It does not
//! do array arithmetic, image processing, or type conversion beyond a few
//! MRC-specific shortcuts (`slices_f32`, `slices_mode0`, `slices_u8`).
//! Leave those to crates like `ndarray`, or your own code.
//!
//! # Feature flags
//!
//! | Feature | Description | Default |
//! |---------|-------------|---------|
//! | `mmap` | Memory-mapped readers and writers | ✅ |
//! | `f16` | Half-precision float via the `half` crate | ✅ |
//! | `simd` | AVX2 / NEON acceleration for integer→f32 | ✅ |
//! | `parallel` | Parallel encoding via `rayon` | ✅ |
//! | `gzip` | Gzip-compressed I/O | ✅ |
//! | `bzip2` | Bzip2-compressed I/O | ❌ |
//!
//! # Advanced topics
//!
//! ## Error handling
//!
//! Fallible functions return `Result<T, Error>`. The errors you will
//! actually hit in practice:
//!
//! * [`Io`](Error::Io) — the file could not be read or written
//! * [`InvalidHeader`](Error::InvalidHeader) — not a valid MRC file
//! * [`ModeMismatch`](Error::ModeMismatch) — calling `slices::<f32>()` on
//! an Int16 file; use `slices_f32()` instead
//! * [`BoundsError`](Error::BoundsError) — read or write outside the volume
//! * [`FileSizeMismatch`](Error::FileSizeMismatch) — file truncated or
//! has trailing garbage
//!
//! [`HeaderValidationError`] gives fine-grained diagnostics for header
//! problems (bad dimensions, wrong MAP field, invalid NVERSION ...).
//!
//! ## Endianness
//!
//! MRC files encode byte order via a 4-byte MACHST stamp. [`FileEndian`]
//! handles detection and conversion automatically. New files are always
//! little-endian, matching modern hardware and the Python `mrcfile` library.
//!
//! ## FEI extended headers
//!
//! Data from Thermo Fisher / FEI microscopes often carries FEI1 or FEI2
//! extended headers — one metadata record per image section.
//! [`Fei1Metadata`] and [`Fei2Metadata`] parse these into named fields
//! (dose, defocus, stage position, pixel size, magnification ...).
//!
//! ```no_run
//! # fn main() -> Result<(), mrc::Error> {
//! use mrc::parse_fei1_records;
//! # let reader = mrc::Reader::open("tilt_series.mrc")?;
//! let bytes = reader.ext_header_bytes();
//! if let Some(records) = parse_fei1_records(bytes) {
//! for r in &records {
//! println!("tilt {:.1}°, defocus {:.1} µm", r.alpha_tilt, r.defocus);
//! }
//! }
//! # Ok(()) }
//! ```
//!
//! ## File validation
//!
//! [`validate_full`](crate::validate::validate_full) runs comprehensive
//! checks on a file — header, size, endianness, data statistics (1 %
//! tolerance), and NaN / Inf scanning. Returns a
//! [`ValidationReport`](crate::validate::ValidationReport) with
//! categorised issues.
//!
//! If you already have an open [`Reader`], use
//! [`validate_reader`](crate::validate::validate_reader) to avoid
//! re-opening the file.
// Re-export core types
pub use ;
/// Endianness of MRC file data.
pub use FileEndian;
// Re-export MRC-specific format utilities
pub use ;
pub use ;
pub use ;
pub use ;
/// Half-precision floating point type (requires `f16` feature).
pub use f16;
/// Buffered MRC reader with lazy slice/slab iterators.
pub use Reader;
/// MRC file writer and its builder.
pub use ;
/// Lazy iterator over MRC voxel blocks.
pub use RegionIter;
/// Stepping strategies for [`RegionIter`].
pub use ;
/// Memory-mapped MRC writer (requires `mmap` feature).
pub use MmapWriter;
/// Memory-mapped MRC reader (requires `mmap` feature).
pub use MmapReader;
/// Gzip-compressed MRC writer (requires `gzip` feature).
pub use GzipWriter;
/// Bzip2-compressed MRC writer (requires `bzip2` feature).
pub use Bzip2Writer;
/// FEI extended header metadata types and parsers.
pub use ;
pub use ;
/// Open an MRC file for reading, auto-detecting gzip or bzip2 compression.
///
/// This is a convenience wrapper around [`Reader::open`].
/// For permissive mode or compressed-file-specific openers,
/// use [`Reader::open_permissive`], [`Reader::open_gzip`], etc. directly.
/// Create a new MRC file for writing.
///
/// Returns a [`WriterBuilder`] that must be configured with at least
/// [`shape`](WriterBuilder::shape) and [`mode`](WriterBuilder::mode)
/// before calling [`finish`](WriterBuilder::finish) to open the file.
///
/// # Example
/// ```no_run
/// use mrc::create;
///
/// let mut writer = create("output.mrc")
/// .shape([256, 256, 128])
/// .mode::<f32>()
/// .finish()?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```