mrc 0.5.1

MRC-2014 file format reader/writer for cryo-EM — SIMD-accelerated, mmap-enabled
Documentation
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! MRC file validation infrastructure.
//!
//! Provides [`validate_full`] for comprehensive file validation,
//! [`validate_reader`] for validating an already-open reader, and
//! [`ValidationReport`] for structured results with categorized issues.
//!
//! # Quick check
//!
//! ```no_run
//! use mrc::validate::{validate_full, Severity};
//!
//! let report = validate_full("protein.mrc", false).unwrap();
//! if report.is_valid() {
//!     println!("File is valid");
//! } else {
//!     for issue in &report.issues {
//!         if issue.severity == Severity::Error {
//!             eprintln!("ERROR [{}]: {}", issue.category, issue.message);
//!         }
//!     }
//! }
//! ```

use crate::engine::endian::FileEndian;
use crate::engine::stats::compute_stats;
use crate::{Error, HeaderValidationError, Mode, Reader};
use std::path::Path;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// ============================================================================
// Issue types
// ============================================================================

/// Severity of a validation issue.
///
/// # Example
///
/// ```rust
/// use mrc::validate::Severity;
///
/// let s = Severity::Error;
/// assert!(matches!(s, Severity::Error));
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// The file cannot be used as-is (corrupt header, data mismatch, etc.).
    Error,
    /// The file is usable but has non-standard or suspicious properties.
    Warning,
    /// Informational message about the file contents.
    Info,
}

/// A single validation issue found during file inspection.
///
/// # Example
///
/// ```rust
/// use mrc::validate::{Severity, ValidationIssue};
///
/// let issue = ValidationIssue {
///     severity: Severity::Warning,
///     category: "Header",
///     message: "Non-standard MACHST stamp".into(),
/// };
/// assert_eq!(issue.severity, Severity::Warning);
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    /// How serious the issue is.
    pub severity: Severity,
    /// Short category label, e.g. `"Header"`, `"Statistics"`, `"Endianness"`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub category: &'static str,
    /// Human-readable description of the issue.
    pub message: String,
}

impl ValidationIssue {
    fn error(category: &'static str, message: String) -> Self {
        Self {
            severity: Severity::Error,
            category,
            message,
        }
    }
    fn warning(category: &'static str, message: String) -> Self {
        Self {
            severity: Severity::Warning,
            category,
            message,
        }
    }
    fn info(category: &'static str, message: String) -> Self {
        Self {
            severity: Severity::Info,
            category,
            message,
        }
    }
}

// ============================================================================
// ValidationReport
// ============================================================================

/// Structured result of a full MRC file validation.
///
/// Returned by [`validate_full`].  The file passes validation when
/// no [`Severity::Error`] issues are present.
///
/// # Example
///
/// ```rust
/// use mrc::validate::{ValidationReport, Severity, ValidationIssue};
///
/// let report = ValidationReport {
///     path: "test.mrc".into(),
///     compression: "plain".into(),
///     nx: 10, ny: 10, nz: 10,
///     mode: 2,
///     issues: vec![],
/// };
/// assert!(report.is_valid());
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct ValidationReport {
    /// Path to the validated file.
    pub path: String,
    /// Detected compression format.
    pub compression: String,
    /// Number of columns.
    pub nx: i32,
    /// Number of rows.
    pub ny: i32,
    /// Number of sections.
    pub nz: i32,
    /// MRC data mode value.
    pub mode: i32,
    /// All issues discovered during validation.
    pub issues: Vec<ValidationIssue>,
}

impl ValidationReport {
    /// `true` when no error-severity issues were found.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mrc::validate::{ValidationReport, Severity, ValidationIssue};
    ///
    /// let report = ValidationReport {
    ///     path: "test.mrc".into(),
    ///     compression: "plain".into(),
    ///     nx: 10, ny: 10, nz: 10, mode: 2,
    ///     issues: vec![ValidationIssue {
    ///         severity: Severity::Error,
    ///         category: "Header",
    ///         message: "bad header".into(),
    ///     }],
    /// };
    /// assert!(!report.is_valid());
    /// ```
    pub fn is_valid(&self) -> bool {
        !self.issues.iter().any(|i| i.severity == Severity::Error)
    }

    /// All issues at a given severity level.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mrc::validate::{ValidationReport, Severity, ValidationIssue};
    ///
    /// let report = ValidationReport {
    ///     path: "test.mrc".into(),
    ///     compression: "plain".into(),
    ///     nx: 10, ny: 10, nz: 10, mode: 2,
    ///     issues: vec![ValidationIssue {
    ///         severity: Severity::Warning,
    ///         category: "Endianness",
    ///         message: "Non-native byte order".into(),
    ///     }],
    /// };
    /// let warnings: Vec<_> = report.by_severity(Severity::Warning).collect();
    /// assert_eq!(warnings.len(), 1);
    /// ```
    pub fn by_severity(&self, severity: Severity) -> impl Iterator<Item = &ValidationIssue> {
        self.issues.iter().filter(move |i| i.severity == severity)
    }
}

// ============================================================================
// Validation implementations
// ============================================================================

/// Run comprehensive validation on an already-opened [`Reader`].
///
/// Checks header structure, file size, endianness, data statistics cross-check
/// (1% tolerance), and NaN/Inf scanning. Avoids the redundant open that
/// [`validate_full`] performs.
///
/// The `warnings` parameter accepts the permissive-mode warnings from
/// [`Reader::open_permissive`]; pass an empty slice for strict-mode opens.
///
/// # Errors
/// Returns `Err` only when reading or computing statistics fails.
///
/// # Example
///
/// ```no_run
/// use mrc::Reader;
/// use mrc::validate::validate_reader;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let reader = Reader::open("protein.mrc")?;
/// let report = validate_reader(&reader, "protein.mrc", "plain", &[])?;
/// println!("Is valid: {}", report.is_valid());
/// # Ok(())
/// # }
/// ```
pub fn validate_reader(
    reader: &Reader,
    path: &str,
    compression: &str,
    warnings: &[String],
) -> Result<ValidationReport, Error> {
    let mut issues: Vec<ValidationIssue> = Vec::with_capacity(16);
    let header = reader.header();
    let mode_val = header.mode;
    let endian = reader.endian();

    // ── Open warnings (permissive mode) ──
    for w in warnings {
        issues.push(ValidationIssue::warning("Open", w.clone()));
    }

    // ── 1. Header structure ──
    match header.validate_detailed() {
        Ok(()) => {
            issues.push(ValidationIssue::info("Header", "Structure is valid".into()));
        }
        Err(e) => {
            let desc = match &e {
                HeaderValidationError::InvalidDimensions { nx, ny, nz } => {
                    format!("Dimensions ({nx}×{ny}×{nz}) must all be positive")
                }
                HeaderValidationError::UnsupportedMode(m) => format!("Unsupported mode value: {m}"),
                HeaderValidationError::InvalidMap(m) => format!(
                    "MAP field is {:?}, expected b\"MAP \"",
                    std::str::from_utf8(m).unwrap_or("?")
                ),
                HeaderValidationError::InvalidIspg(s) => {
                    format!("ISPG {s} is outside valid ranges (0, 1–230, 400–630)")
                }
                HeaderValidationError::InvalidAxisMapping { mapc, mapr, maps } => {
                    format!("Axis mapping ({mapc}, {mapr}, {maps}) is not a permutation of 1,2,3")
                }
                HeaderValidationError::InvalidNsymbt(s) => format!("NSYMBT is negative ({s})"),
                HeaderValidationError::InvalidNlabl(n) => format!("NLABL is {n}, must be 0–10"),
                HeaderValidationError::InvalidNversion(n) => {
                    format!("NVERSION is {n}, expected 0, 20140, or 20141")
                }
                HeaderValidationError::InvalidSampling { mx, my, mz } => {
                    format!("Sampling ({mx}×{my}×{mz}) must all be positive")
                }
                HeaderValidationError::InvalidVolumeStack { nz, mz, ispg } => {
                    format!("Volume stack: nz={nz} not divisible by mz={mz} for ispg={ispg}")
                }
                HeaderValidationError::LabelCountMismatch { nlabl, actual } => {
                    format!("nlabl={nlabl} but {actual} non-empty labels found")
                }
                HeaderValidationError::EmptyLabelBeforeFilled { index } => {
                    format!("Empty label at index {index} before all filled labels")
                }
            };
            issues.push(ValidationIssue::error("Header", desc));
        }
    }

    // ── 2. File size ──
    if let Some(data_size) = header.data_size() {
        let expected_total = 1024 + header.nsymbt.max(0) as usize + data_size;
        issues.push(ValidationIssue::info(
            "File size",
            format!("Expected {} bytes (header + ext + data)", expected_total),
        ));
    }

    // ── 3. Endianness ──
    let machst_info = FileEndian::from_machst_with_info(&header.machst);
    if !machst_info.is_standard {
        issues.push(ValidationIssue::warning(
            "Endianness",
            format!("Non-standard MACHST stamp: {}", machst_info.description),
        ));
    }
    let host = FileEndian::native();
    if endian != host {
        issues.push(ValidationIssue::info(
            "Endianness",
            format!("Non-native byte order ({:?}), host is {:?}", endian, host),
        ));
    } else {
        issues.push(ValidationIssue::info(
            "Endianness",
            "Native byte order, fast-path available".into(),
        ));
    }

    // ── 4. Data statistics ──
    let data_bytes = reader.data_bytes();
    match compute_stats(
        data_bytes,
        reader.mode(),
        endian,
        reader.shape().nx,
        reader.shape().ny * reader.shape().nz,
    ) {
        Ok((actual_dmin, actual_dmax, actual_dmean, actual_rms)) => {
            let complex = matches!(reader.mode(), Mode::Float32Complex | Mode::Int16Complex);

            let stats_unset = header.dmin > header.dmax;
            let rms_unset = header.rms < 0.0;

            let rtol = 0.01f32;

            let min_ok = complex
                || stats_unset
                || crate::engine::stats::is_close(header.dmin, actual_dmin, rtol);
            let max_ok = complex
                || stats_unset
                || crate::engine::stats::is_close(header.dmax, actual_dmax, rtol);
            let mean_ok = complex
                || stats_unset
                || crate::engine::stats::is_close(header.dmean, actual_dmean, rtol);
            let rms_ok = rms_unset || crate::engine::stats::is_close(header.rms, actual_rms, rtol);

            if !stats_unset || !rms_unset {
                let mut mismatch_parts = Vec::with_capacity(4);
                if !min_ok {
                    mismatch_parts.push("dmin".to_string());
                }
                if !max_ok {
                    mismatch_parts.push("dmax".to_string());
                }
                if !mean_ok {
                    mismatch_parts.push("dmean".to_string());
                }
                if !rms_ok {
                    mismatch_parts.push("rms".to_string());
                }

                if mismatch_parts.is_empty() {
                    if stats_unset {
                        issues.push(ValidationIssue::info(
                            "Statistics",
                            "Statistics not written in header (sentinel values)".into(),
                        ));
                    } else {
                        issues.push(ValidationIssue::info(
                            "Statistics",
                            "All statistics match actual data (within 1% tolerance)".into(),
                        ));
                    }
                } else {
                    let mut detail = String::new();
                    if !min_ok {
                        detail.push_str(&format!(
                            " dmin claimed={} actual={}",
                            header.dmin, actual_dmin
                        ));
                    }
                    if !max_ok {
                        detail.push_str(&format!(
                            " dmax claimed={} actual={}",
                            header.dmax, actual_dmax
                        ));
                    }
                    if !mean_ok {
                        detail.push_str(&format!(
                            " dmean claimed={} actual={}",
                            header.dmean, actual_dmean
                        ));
                    }
                    if !rms_ok {
                        detail.push_str(&format!(
                            " rms claimed={} actual={}",
                            header.rms, actual_rms
                        ));
                    }
                    issues.push(ValidationIssue::error(
                        "Statistics",
                        format!("Mismatch:{}", detail),
                    ));
                }
            }
        }
        Err(e) => {
            issues.push(ValidationIssue::error(
                "Statistics",
                format!("Cannot compute statistics: {e}"),
            ));
        }
    }

    // ── 5. Data integrity (scan for NaN / Inf in float modes) ──
    if reader.mode().is_float() && !reader.mode().is_complex() {
        match float_mode_issues(data_bytes, reader.mode(), endian) {
            Ok(has_issues) => {
                if has_issues.is_empty() {
                    issues.push(ValidationIssue::info(
                        "Data integrity",
                        "All voxel values are finite numbers".into(),
                    ));
                } else {
                    for issue in has_issues {
                        issues.push(ValidationIssue::warning("Data integrity", issue));
                    }
                }
            }
            Err(e) => {
                issues.push(ValidationIssue::warning(
                    "Data integrity",
                    format!("Could not scan data: {e}"),
                ));
            }
        }
    } else if reader.mode() == Mode::Float32Complex {
        match complex_float_mode_issues(data_bytes, endian) {
            Ok(has_issues) => {
                if has_issues.is_empty() {
                    issues.push(ValidationIssue::info(
                        "Data integrity",
                        "All complex values are finite numbers".into(),
                    ));
                } else {
                    for issue in has_issues {
                        issues.push(ValidationIssue::warning("Data integrity", issue));
                    }
                }
            }
            Err(e) => {
                issues.push(ValidationIssue::warning(
                    "Data integrity",
                    format!("Could not scan complex data: {e}"),
                ));
            }
        }
    }

    // ── 6. Volume info ──
    let vol_type = if header.is_single_image() {
        "single 2D image"
    } else if header.is_image_stack() {
        "image stack"
    } else if header.is_volume_stack() {
        let nvol = if header.mz > 0 {
            header.nz / header.mz
        } else {
            0
        };
        issues.push(ValidationIssue::info(
            "Volume",
            format!("Volume stack: {nvol} sub-volumes × {} slices", header.mz),
        ));
        "volume stack"
    } else {
        "3D volume"
    };
    issues.push(ValidationIssue::info(
        "Volume",
        format!(
            "{} × {} × {} voxels, {}",
            header.nx, header.ny, header.nz, vol_type
        ),
    ));

    Ok(ValidationReport {
        path: path.to_owned(),
        compression: compression.to_owned(),
        nx: header.nx,
        ny: header.ny,
        nz: header.nz,
        mode: mode_val,
        issues,
    })
}

/// Run comprehensive validation on an MRC file.
///
/// Opens the file, checks header structure, data statistics, and data
/// integrity. In permissive mode, non-critical header issues are reported
/// as warnings rather than hard errors.
///
/// Prefer [`validate_reader`] when you already have an open [`Reader`] — it
/// avoids the redundant file I/O.
///
/// # Errors
/// Returns `Err` only when the file cannot be opened or read at all.
///
/// # Example
///
/// ```no_run
/// use mrc::validate::validate_full;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let report = validate_full("protein.mrc", false)?;
/// if report.is_valid() {
///     println!("File is valid");
/// }
/// # Ok(())
/// # }
/// ```
pub fn validate_full<P: AsRef<Path>>(path: P, permissive: bool) -> Result<ValidationReport, Error> {
    let path_str = path.as_ref().to_string_lossy().into_owned();

    let compression = match crate::io::reader::detect_compression(&path)? {
        crate::io::reader::CompressionType::Plain => "plain".to_string(),
        #[cfg(feature = "gzip")]
        crate::io::reader::CompressionType::Gzip => "gzip".to_string(),
        #[cfg(feature = "bzip2")]
        crate::io::reader::CompressionType::Bzip2 => "bzip2".to_string(),
    };

    let (reader, warnings) = if permissive {
        Reader::open_permissive(&path)?
    } else {
        (Reader::open(&path)?, Vec::new())
    };

    validate_reader(&reader, &path_str, &compression, &warnings)
}

// ── Float-mode data integrity helper ──

fn float_mode_issues(
    data_bytes: &[u8],
    mode: Mode,
    endian: FileEndian,
) -> Result<Vec<String>, Error> {
    use crate::engine::codec::decode_slice;
    let data: Vec<f32> = match mode {
        Mode::Float32 => decode_slice::<f32>(data_bytes, endian)?,
        Mode::Float16 => {
            #[cfg(feature = "f16")]
            {
                let f16_data = decode_slice::<crate::f16>(data_bytes, endian)?;
                f16_data.iter().map(|&v| f32::from(v)).collect()
            }
            #[cfg(not(feature = "f16"))]
            return Ok(vec![
                "Float16 scanning unavailable (requires `f16` feature)".into(),
            ]);
        }
        _ => return Ok(Vec::new()),
    };

    let mut issues = Vec::with_capacity(3);
    let mut nan_count = 0usize;
    let mut inf_count = 0usize;
    let mut neg_inf_count = 0usize;

    for &v in &data {
        if v.is_nan() {
            nan_count += 1;
        } else if v.is_infinite() {
            if v.is_sign_negative() {
                neg_inf_count += 1;
            } else {
                inf_count += 1;
            }
        }
    }

    if nan_count > 0 {
        issues.push(format!(
            "{nan_count} NaN values found ({:.2}%)",
            nan_count as f64 / data.len() as f64 * 100.0
        ));
    }
    if inf_count > 0 {
        issues.push(format!(
            "{inf_count} +Inf values found ({:.2}%)",
            inf_count as f64 / data.len() as f64 * 100.0
        ));
    }
    if neg_inf_count > 0 {
        issues.push(format!(
            "{neg_inf_count} -Inf values found ({:.2}%)",
            neg_inf_count as f64 / data.len() as f64 * 100.0
        ));
    }
    Ok(issues)
}

/// Scan Float32Complex data for NaN/Inf values in both real and imaginary parts.
fn complex_float_mode_issues(data_bytes: &[u8], endian: FileEndian) -> Result<Vec<String>, Error> {
    use crate::engine::codec::decode_slice;
    let data: Vec<crate::mode::Float32Complex> =
        decode_slice::<crate::mode::Float32Complex>(data_bytes, endian)?;

    let mut issues = Vec::with_capacity(3);
    let mut nan_count = 0usize;
    let mut inf_count = 0usize;
    let mut neg_inf_count = 0usize;

    for c in &data {
        for &v in &[c.real, c.imag] {
            if v.is_nan() {
                nan_count += 1;
            } else if v.is_infinite() {
                if v.is_sign_negative() {
                    neg_inf_count += 1;
                } else {
                    inf_count += 1;
                }
            }
        }
    }

    let total_components = data.len() * 2;
    if nan_count > 0 {
        issues.push(format!(
            "{nan_count} NaN values found in complex components ({:.2}%)",
            nan_count as f64 / total_components as f64 * 100.0
        ));
    }
    if inf_count > 0 {
        issues.push(format!(
            "{inf_count} +Inf values found in complex components ({:.2}%)",
            inf_count as f64 / total_components as f64 * 100.0
        ));
    }
    if neg_inf_count > 0 {
        issues.push(format!(
            "{neg_inf_count} -Inf values found in complex components ({:.2}%)",
            neg_inf_count as f64 / total_components as f64 * 100.0
        ));
    }
    Ok(issues)
}